<?php

declare(strict_types=1);

namespace GraphQL\Language;

use GraphQL\Error\SyntaxError;
use GraphQL\Language\AST\ArgumentNode;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\DirectiveDefinitionNode;
use GraphQL\Language\AST\DirectiveNode;
use GraphQL\Language\AST\DocumentNode;
use GraphQL\Language\AST\EnumTypeDefinitionNode;
use GraphQL\Language\AST\EnumTypeExtensionNode;
use GraphQL\Language\AST\EnumValueDefinitionNode;
use GraphQL\Language\AST\EnumValueNode;
use GraphQL\Language\AST\ExecutableDefinitionNode;
use GraphQL\Language\AST\FieldDefinitionNode;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\FloatValueNode;
use GraphQL\Language\AST\FragmentDefinitionNode;
use GraphQL\Language\AST\FragmentSpreadNode;
use GraphQL\Language\AST\InlineFragmentNode;
use GraphQL\Language\AST\InputObjectTypeDefinitionNode;
use GraphQL\Language\AST\InputObjectTypeExtensionNode;
use GraphQL\Language\AST\InputValueDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeExtensionNode;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\ListTypeNode;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\Location;
use GraphQL\Language\AST\NamedTypeNode;
use GraphQL\Language\AST\NameNode;
use GraphQL\Language\AST\NodeList;
use GraphQL\Language\AST\NonNullTypeNode;
use GraphQL\Language\AST\NullValueNode;
use GraphQL\Language\AST\ObjectFieldNode;
use GraphQL\Language\AST\ObjectTypeDefinitionNode;
use GraphQL\Language\AST\ObjectTypeExtensionNode;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Language\AST\OperationTypeDefinitionNode;
use GraphQL\Language\AST\ScalarTypeDefinitionNode;
use GraphQL\Language\AST\ScalarTypeExtensionNode;
use GraphQL\Language\AST\SchemaDefinitionNode;
use GraphQL\Language\AST\SchemaTypeExtensionNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Language\AST\TypeExtensionNode;
use GraphQL\Language\AST\TypeSystemDefinitionNode;
use GraphQL\Language\AST\UnionTypeDefinitionNode;
use GraphQL\Language\AST\UnionTypeExtensionNode;
use GraphQL\Language\AST\VariableDefinitionNode;
use GraphQL\Language\AST\VariableNode;
use function count;
use function sprintf;

/**
 * Parses string containing GraphQL query or [type definition](type-system/type-language.md) to Abstract Syntax Tree.
 */
class Parser
{
    /**
     * Given a GraphQL source, parses it into a `GraphQL\Language\AST\DocumentNode`.
     * Throws `GraphQL\Error\SyntaxError` if a syntax error is encountered.
     *
     * Available options:
     *
     * noLocation: boolean,
     *   (By default, the parser creates AST nodes that know the location
     *   in the source that they correspond to. This configuration flag
     *   disables that behavior for performance or testing.)
     *
     * allowLegacySDLEmptyFields: boolean
     *   If enabled, the parser will parse empty fields sets in the Schema
     *   Definition Language. Otherwise, the parser will follow the current
     *   specification.
     *
     *   This option is provided to ease adoption of the final SDL specification
     *   and will be removed in a future major release.
     *
     * allowLegacySDLImplementsInterfaces: boolean
     *   If enabled, the parser will parse implemented interfaces with no `&`
     *   character between each interface. Otherwise, the parser will follow the
     *   current specification.
     *
     *   This option is provided to ease adoption of the final SDL specification
     *   and will be removed in a future major release.
     *
     * experimentalFragmentVariables: boolean,
     *   (If enabled, the parser will understand and parse variable definitions
     *   contained in a fragment definition. They'll be represented in the
     *   `variableDefinitions` field of the FragmentDefinitionNode.
     *
     *   The syntax is identical to normal, query-defined variables. For example:
     *
     *     fragment A($var: Boolean = false) on T  {
     *       ...
     *     }
     *
     *   Note: this feature is experimental and may change or be removed in the
     *   future.)
     *
     * @param Source|string $source
     * @param bool[]        $options
     *
     * @return DocumentNode
     *
     * @throws SyntaxError
     *
     * @api
     */
    public static function parse($source, array $options = [])
    {
        $sourceObj = $source instanceof Source ? $source : new Source($source);
        $parser    = new self($sourceObj, $options);

        return $parser->parseDocument();
    }

    /**
     * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
     * that value.
     * Throws `GraphQL\Error\SyntaxError` if a syntax error is encountered.
     *
     * This is useful within tools that operate upon GraphQL Values directly and
     * in isolation of complete GraphQL documents.
     *
     * Consider providing the results to the utility function: `GraphQL\Utils\AST::valueFromAST()`.
     *
     * @param Source|string $source
     * @param bool[]        $options
     *
     * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode
     *
     * @api
     */
    public static function parseValue($source, array $options = [])
    {
        $sourceObj = $source instanceof Source ? $source : new Source($source);
        $parser    = new Parser($sourceObj, $options);
        $parser->expect(Token::SOF);
        $value = $parser->parseValueLiteral(false);
        $parser->expect(Token::EOF);

        return $value;
    }

    /**
     * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
     * that type.
     * Throws `GraphQL\Error\SyntaxError` if a syntax error is encountered.
     *
     * This is useful within tools that operate upon GraphQL Types directly and
     * in isolation of complete GraphQL documents.
     *
     * Consider providing the results to the utility function: `GraphQL\Utils\AST::typeFromAST()`.
     *
     * @param Source|string $source
     * @param bool[]        $options
     *
     * @return ListTypeNode|NameNode|NonNullTypeNode
     *
     * @api
     */
    public static function parseType($source, array $options = [])
    {
        $sourceObj = $source instanceof Source ? $source : new Source($source);
        $parser    = new Parser($sourceObj, $options);
        $parser->expect(Token::SOF);
        $type = $parser->parseTypeReference();
        $parser->expect(Token::EOF);

        return $type;
    }

    /** @var Lexer */
    private $lexer;

    /**
     * @param bool[] $options
     */
    public function __construct(Source $source, array $options = [])
    {
        $this->lexer = new Lexer($source, $options);
    }

    /**
     * Returns a location object, used to identify the place in
     * the source that created a given parsed object.
     *
     * @return Location|null
     */
    private function loc(Token $startToken)
    {
        if (empty($this->lexer->options['noLocation'])) {
            return new Location($startToken, $this->lexer->lastToken, $this->lexer->source);
        }

        return null;
    }

    /**
     * Determines if the next token is of a given kind
     *
     * @param string $kind
     *
     * @return bool
     */
    private function peek($kind)
    {
        return $this->lexer->token->kind === $kind;
    }

    /**
     * If the next token is of the given kind, return true after advancing
     * the parser. Otherwise, do not change the parser state and return false.
     *
     * @param string $kind
     *
     * @return bool
     */
    private function skip($kind)
    {
        $match = $this->lexer->token->kind === $kind;

        if ($match) {
            $this->lexer->advance();
        }

        return $match;
    }

    /**
     * If the next token is of the given kind, return that token after advancing
     * the parser. Otherwise, do not change the parser state and return false.
     *
     * @param string $kind
     *
     * @return Token
     *
     * @throws SyntaxError
     */
    private function expect($kind)
    {
        $token = $this->lexer->token;

        if ($token->kind === $kind) {
            $this->lexer->advance();

            return $token;
        }

        throw new SyntaxError(
            $this->lexer->source,
            $token->start,
            sprintf('Expected %s, found %s', $kind, $token->getDescription())
        );
    }

    /**
     * If the next token is a keyword with the given value, return that token after
     * advancing the parser. Otherwise, do not change the parser state and return
     * false.
     *
     * @param string $value
     *
     * @return Token
     *
     * @throws SyntaxError
     */
    private function expectKeyword($value)
    {
        $token = $this->lexer->token;

        if ($token->kind === Token::NAME && $token->value === $value) {
            $this->lexer->advance();

            return $token;
        }
        throw new SyntaxError(
            $this->lexer->source,
            $token->start,
            'Expected "' . $value . '", found ' . $token->getDescription()
        );
    }

    /**
     * @return SyntaxError
     */
    private function unexpected(?Token $atToken = null)
    {
        $token = $atToken ?: $this->lexer->token;

        return new SyntaxError($this->lexer->source, $token->start, 'Unexpected ' . $token->getDescription());
    }

    /**
     * Returns a possibly empty list of parse nodes, determined by
     * the parseFn. This list begins with a lex token of openKind
     * and ends with a lex token of closeKind. Advances the parser
     * to the next lex token after the closing token.
     *
     * @param string   $openKind
     * @param callable $parseFn
     * @param string   $closeKind
     *
     * @return NodeList
     *
     * @throws SyntaxError
     */
    private function any($openKind, $parseFn, $closeKind)
    {
        $this->expect($openKind);

        $nodes = [];
        while (! $this->skip($closeKind)) {
            $nodes[] = $parseFn($this);
        }

        return new NodeList($nodes);
    }

    /**
     * Returns a non-empty list of parse nodes, determined by
     * the parseFn. This list begins with a lex token of openKind
     * and ends with a lex token of closeKind. Advances the parser
     * to the next lex token after the closing token.
     *
     * @param string   $openKind
     * @param callable $parseFn
     * @param string   $closeKind
     *
     * @return NodeList
     *
     * @throws SyntaxError
     */
    private function many($openKind, $parseFn, $closeKind)
    {
        $this->expect($openKind);

        $nodes = [$parseFn($this)];
        while (! $this->skip($closeKind)) {
            $nodes[] = $parseFn($this);
        }

        return new NodeList($nodes);
    }

    /**
     * Converts a name lex token into a name parse node.
     *
     * @return NameNode
     *
     * @throws SyntaxError
     */
    private function parseName()
    {
        $token = $this->expect(Token::NAME);

        return new NameNode([
            'value' => $token->value,
            'loc'   => $this->loc($token),
        ]);
    }

    /**
     * Implements the parsing rules in the Document section.
     *
     * @return DocumentNode
     *
     * @throws SyntaxError
     */
    private function parseDocument()
    {
        $start = $this->lexer->token;
        $this->expect(Token::SOF);

        $definitions = [];
        do {
            $definitions[] = $this->parseDefinition();
        } while (! $this->skip(Token::EOF));

        return new DocumentNode([
            'definitions' => new NodeList($definitions),
            'loc'         => $this->loc($start),
        ]);
    }

    /**
     * @return ExecutableDefinitionNode|TypeSystemDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseDefinition()
    {
        if ($this->peek(Token::NAME)) {
            switch ($this->lexer->token->value) {
                case 'query':
                case 'mutation':
                case 'subscription':
                case 'fragment':
                    return $this->parseExecutableDefinition();

                // Note: The schema definition language is an experimental addition.
                case 'schema':
                case 'scalar':
                case 'type':
                case 'interface':
                case 'union':
                case 'enum':
                case 'input':
                case 'extend':
                case 'directive':
                    // Note: The schema definition language is an experimental addition.
                    return $this->parseTypeSystemDefinition();
            }
        } elseif ($this->peek(Token::BRACE_L)) {
            return $this->parseExecutableDefinition();
        } elseif ($this->peekDescription()) {
            // Note: The schema definition language is an experimental addition.
            return $this->parseTypeSystemDefinition();
        }

        throw $this->unexpected();
    }

    /**
     * @return ExecutableDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseExecutableDefinition()
    {
        if ($this->peek(Token::NAME)) {
            switch ($this->lexer->token->value) {
                case 'query':
                case 'mutation':
                case 'subscription':
                    return $this->parseOperationDefinition();
                case 'fragment':
                    return $this->parseFragmentDefinition();
            }
        } elseif ($this->peek(Token::BRACE_L)) {
            return $this->parseOperationDefinition();
        }

        throw $this->unexpected();
    }

    // Implements the parsing rules in the Operations section.

    /**
     * @return OperationDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseOperationDefinition()
    {
        $start = $this->lexer->token;
        if ($this->peek(Token::BRACE_L)) {
            return new OperationDefinitionNode([
                'operation'           => 'query',
                'name'                => null,
                'variableDefinitions' => new NodeList([]),
                'directives'          => new NodeList([]),
                'selectionSet'        => $this->parseSelectionSet(),
                'loc'                 => $this->loc($start),
            ]);
        }

        $operation = $this->parseOperationType();

        $name = null;
        if ($this->peek(Token::NAME)) {
            $name = $this->parseName();
        }

        return new OperationDefinitionNode([
            'operation'           => $operation,
            'name'                => $name,
            'variableDefinitions' => $this->parseVariableDefinitions(),
            'directives'          => $this->parseDirectives(false),
            'selectionSet'        => $this->parseSelectionSet(),
            'loc'                 => $this->loc($start),
        ]);
    }

    /**
     * @return string
     *
     * @throws SyntaxError
     */
    private function parseOperationType()
    {
        $operationToken = $this->expect(Token::NAME);
        switch ($operationToken->value) {
            case 'query':
                return 'query';
            case 'mutation':
                return 'mutation';
            case 'subscription':
                return 'subscription';
        }

        throw $this->unexpected($operationToken);
    }

    /**
     * @return VariableDefinitionNode[]|NodeList
     */
    private function parseVariableDefinitions()
    {
        return $this->peek(Token::PAREN_L) ?
            $this->many(
                Token::PAREN_L,
                function () {
                    return $this->parseVariableDefinition();
                },
                Token::PAREN_R
            ) :
            new NodeList([]);
    }

    /**
     * @return VariableDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseVariableDefinition()
    {
        $start = $this->lexer->token;
        $var   = $this->parseVariable();

        $this->expect(Token::COLON);
        $type = $this->parseTypeReference();

        return new VariableDefinitionNode([
            'variable'     => $var,
            'type'         => $type,
            'defaultValue' =>
                ($this->skip(Token::EQUALS) ? $this->parseValueLiteral(true) : null),
            'loc'          => $this->loc($start),
        ]);
    }

    /**
     * @return VariableNode
     *
     * @throws SyntaxError
     */
    private function parseVariable()
    {
        $start = $this->lexer->token;
        $this->expect(Token::DOLLAR);

        return new VariableNode([
            'name' => $this->parseName(),
            'loc'  => $this->loc($start),
        ]);
    }

    /**
     * @return SelectionSetNode
     */
    private function parseSelectionSet()
    {
        $start = $this->lexer->token;

        return new SelectionSetNode(
            [
                'selections' => $this->many(
                    Token::BRACE_L,
                    function () {
                        return $this->parseSelection();
                    },
                    Token::BRACE_R
                ),
                'loc'        => $this->loc($start),
            ]
        );
    }

    /**
     *  Selection :
     *   - Field
     *   - FragmentSpread
     *   - InlineFragment
     *
     * @return mixed
     */
    private function parseSelection()
    {
        return $this->peek(Token::SPREAD) ?
            $this->parseFragment() :
            $this->parseField();
    }

    /**
     * @return FieldNode
     *
     * @throws SyntaxError
     */
    private function parseField()
    {
        $start       = $this->lexer->token;
        $nameOrAlias = $this->parseName();

        if ($this->skip(Token::COLON)) {
            $alias = $nameOrAlias;
            $name  = $this->parseName();
        } else {
            $alias = null;
            $name  = $nameOrAlias;
        }

        return new FieldNode([
            'alias'        => $alias,
            'name'         => $name,
            'arguments'    => $this->parseArguments(false),
            'directives'   => $this->parseDirectives(false),
            'selectionSet' => $this->peek(Token::BRACE_L) ? $this->parseSelectionSet() : null,
            'loc'          => $this->loc($start),
        ]);
    }

    /**
     * @param bool $isConst
     *
     * @return ArgumentNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseArguments($isConst)
    {
        $parseFn = $isConst ?
            function () {
                return $this->parseConstArgument();
            } :
            function () {
                return $this->parseArgument();
            };

        return $this->peek(Token::PAREN_L) ?
            $this->many(Token::PAREN_L, $parseFn, Token::PAREN_R) :
            new NodeList([]);
    }

    /**
     * @return ArgumentNode
     *
     * @throws SyntaxError
     */
    private function parseArgument()
    {
        $start = $this->lexer->token;
        $name  = $this->parseName();

        $this->expect(Token::COLON);
        $value = $this->parseValueLiteral(false);

        return new ArgumentNode([
            'name'  => $name,
            'value' => $value,
            'loc'   => $this->loc($start),
        ]);
    }

    /**
     * @return ArgumentNode
     *
     * @throws SyntaxError
     */
    private function parseConstArgument()
    {
        $start = $this->lexer->token;
        $name  = $this->parseName();

        $this->expect(Token::COLON);
        $value = $this->parseConstValue();

        return new ArgumentNode([
            'name'  => $name,
            'value' => $value,
            'loc'   => $this->loc($start),
        ]);
    }

    // Implements the parsing rules in the Fragments section.

    /**
     * @return FragmentSpreadNode|InlineFragmentNode
     *
     * @throws SyntaxError
     */
    private function parseFragment()
    {
        $start = $this->lexer->token;
        $this->expect(Token::SPREAD);

        if ($this->peek(Token::NAME) && $this->lexer->token->value !== 'on') {
            return new FragmentSpreadNode([
                'name'       => $this->parseFragmentName(),
                'directives' => $this->parseDirectives(false),
                'loc'        => $this->loc($start),
            ]);
        }

        $typeCondition = null;
        if ($this->lexer->token->value === 'on') {
            $this->lexer->advance();
            $typeCondition = $this->parseNamedType();
        }

        return new InlineFragmentNode([
            'typeCondition' => $typeCondition,
            'directives'    => $this->parseDirectives(false),
            'selectionSet'  => $this->parseSelectionSet(),
            'loc'           => $this->loc($start),
        ]);
    }

    /**
     * @return FragmentDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseFragmentDefinition()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('fragment');

        $name = $this->parseFragmentName();

        // Experimental support for defining variables within fragments changes
        // the grammar of FragmentDefinition:
        //   - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
        $variableDefinitions = null;
        if (isset($this->lexer->options['experimentalFragmentVariables'])) {
            $variableDefinitions = $this->parseVariableDefinitions();
        }
        $this->expectKeyword('on');
        $typeCondition = $this->parseNamedType();

        return new FragmentDefinitionNode([
            'name'                => $name,
            'variableDefinitions' => $variableDefinitions,
            'typeCondition'       => $typeCondition,
            'directives'          => $this->parseDirectives(false),
            'selectionSet'        => $this->parseSelectionSet(),
            'loc'                 => $this->loc($start),
        ]);
    }

    /**
     * @return NameNode
     *
     * @throws SyntaxError
     */
    private function parseFragmentName()
    {
        if ($this->lexer->token->value === 'on') {
            throw $this->unexpected();
        }

        return $this->parseName();
    }

    // Implements the parsing rules in the Values section.

    /**
     * Value[Const] :
     *   - [~Const] Variable
     *   - IntValue
     *   - FloatValue
     *   - StringValue
     *   - BooleanValue
     *   - NullValue
     *   - EnumValue
     *   - ListValue[?Const]
     *   - ObjectValue[?Const]
     *
     * BooleanValue : one of `true` `false`
     *
     * NullValue : `null`
     *
     * EnumValue : Name but not `true`, `false` or `null`
     *
     * @param bool $isConst
     *
     * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode|VariableNode|ListValueNode|ObjectValueNode|NullValueNode
     *
     * @throws SyntaxError
     */
    private function parseValueLiteral($isConst)
    {
        $token = $this->lexer->token;
        switch ($token->kind) {
            case Token::BRACKET_L:
                return $this->parseArray($isConst);
            case Token::BRACE_L:
                return $this->parseObject($isConst);
            case Token::INT:
                $this->lexer->advance();

                return new IntValueNode([
                    'value' => $token->value,
                    'loc'   => $this->loc($token),
                ]);
            case Token::FLOAT:
                $this->lexer->advance();

                return new FloatValueNode([
                    'value' => $token->value,
                    'loc'   => $this->loc($token),
                ]);
            case Token::STRING:
            case Token::BLOCK_STRING:
                return $this->parseStringLiteral();
            case Token::NAME:
                if ($token->value === 'true' || $token->value === 'false') {
                    $this->lexer->advance();

                    return new BooleanValueNode([
                        'value' => $token->value === 'true',
                        'loc'   => $this->loc($token),
                    ]);
                }

                if ($token->value === 'null') {
                    $this->lexer->advance();

                    return new NullValueNode([
                        'loc' => $this->loc($token),
                    ]);
                } else {
                    $this->lexer->advance();

                    return new EnumValueNode([
                        'value' => $token->value,
                        'loc'   => $this->loc($token),
                    ]);
                }
                break;

            case Token::DOLLAR:
                if (! $isConst) {
                    return $this->parseVariable();
                }
                break;
        }
        throw $this->unexpected();
    }

    /**
     * @return StringValueNode
     */
    private function parseStringLiteral()
    {
        $token = $this->lexer->token;
        $this->lexer->advance();

        return new StringValueNode([
            'value' => $token->value,
            'block' => $token->kind === Token::BLOCK_STRING,
            'loc'   => $this->loc($token),
        ]);
    }

    /**
     * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode|VariableNode
     *
     * @throws SyntaxError
     */
    private function parseConstValue()
    {
        return $this->parseValueLiteral(true);
    }

    /**
     * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode
     */
    private function parseVariableValue()
    {
        return $this->parseValueLiteral(false);
    }

    /**
     * @param bool $isConst
     *
     * @return ListValueNode
     */
    private function parseArray($isConst)
    {
        $start   = $this->lexer->token;
        $parseFn = $isConst ? function () {
            return $this->parseConstValue();
        } : function () {
            return $this->parseVariableValue();
        };

        return new ListValueNode(
            [
                'values' => $this->any(Token::BRACKET_L, $parseFn, Token::BRACKET_R),
                'loc'    => $this->loc($start),
            ]
        );
    }

    /**
     * @param bool $isConst
     *
     * @return ObjectValueNode
     */
    private function parseObject($isConst)
    {
        $start = $this->lexer->token;
        $this->expect(Token::BRACE_L);
        $fields = [];
        while (! $this->skip(Token::BRACE_R)) {
            $fields[] = $this->parseObjectField($isConst);
        }

        return new ObjectValueNode([
            'fields' => new NodeList($fields),
            'loc'    => $this->loc($start),
        ]);
    }

    /**
     * @param bool $isConst
     *
     * @return ObjectFieldNode
     */
    private function parseObjectField($isConst)
    {
        $start = $this->lexer->token;
        $name  = $this->parseName();

        $this->expect(Token::COLON);

        return new ObjectFieldNode([
            'name'  => $name,
            'value' => $this->parseValueLiteral($isConst),
            'loc'   => $this->loc($start),
        ]);
    }

    // Implements the parsing rules in the Directives section.

    /**
     * @param bool $isConst
     *
     * @return DirectiveNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseDirectives($isConst)
    {
        $directives = [];
        while ($this->peek(Token::AT)) {
            $directives[] = $this->parseDirective($isConst);
        }

        return new NodeList($directives);
    }

    /**
     * @param bool $isConst
     *
     * @return DirectiveNode
     *
     * @throws SyntaxError
     */
    private function parseDirective($isConst)
    {
        $start = $this->lexer->token;
        $this->expect(Token::AT);

        return new DirectiveNode([
            'name'      => $this->parseName(),
            'arguments' => $this->parseArguments($isConst),
            'loc'       => $this->loc($start),
        ]);
    }

    // Implements the parsing rules in the Types section.

    /**
     * Handles the Type: TypeName, ListType, and NonNullType parsing rules.
     *
     * @return ListTypeNode|NameNode|NonNullTypeNode
     *
     * @throws SyntaxError
     */
    private function parseTypeReference()
    {
        $start = $this->lexer->token;

        if ($this->skip(Token::BRACKET_L)) {
            $type = $this->parseTypeReference();
            $this->expect(Token::BRACKET_R);
            $type = new ListTypeNode([
                'type' => $type,
                'loc'  => $this->loc($start),
            ]);
        } else {
            $type = $this->parseNamedType();
        }
        if ($this->skip(Token::BANG)) {
            return new NonNullTypeNode([
                'type' => $type,
                'loc'  => $this->loc($start),
            ]);
        }

        return $type;
    }

    private function parseNamedType()
    {
        $start = $this->lexer->token;

        return new NamedTypeNode([
            'name' => $this->parseName(),
            'loc'  => $this->loc($start),
        ]);
    }

    // Implements the parsing rules in the Type Definition section.

    /**
     * TypeSystemDefinition :
     *   - SchemaDefinition
     *   - TypeDefinition
     *   - TypeExtension
     *   - DirectiveDefinition
     *
     * TypeDefinition :
     *   - ScalarTypeDefinition
     *   - ObjectTypeDefinition
     *   - InterfaceTypeDefinition
     *   - UnionTypeDefinition
     *   - EnumTypeDefinition
     *   - InputObjectTypeDefinition
     *
     * @return TypeSystemDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseTypeSystemDefinition()
    {
        // Many definitions begin with a description and require a lookahead.
        $keywordToken = $this->peekDescription()
            ? $this->lexer->lookahead()
            : $this->lexer->token;

        if ($keywordToken->kind === Token::NAME) {
            switch ($keywordToken->value) {
                case 'schema':
                    return $this->parseSchemaDefinition();
                case 'scalar':
                    return $this->parseScalarTypeDefinition();
                case 'type':
                    return $this->parseObjectTypeDefinition();
                case 'interface':
                    return $this->parseInterfaceTypeDefinition();
                case 'union':
                    return $this->parseUnionTypeDefinition();
                case 'enum':
                    return $this->parseEnumTypeDefinition();
                case 'input':
                    return $this->parseInputObjectTypeDefinition();
                case 'extend':
                    return $this->parseTypeExtension();
                case 'directive':
                    return $this->parseDirectiveDefinition();
            }
        }

        throw $this->unexpected($keywordToken);
    }

    /**
     * @return bool
     */
    private function peekDescription()
    {
        return $this->peek(Token::STRING) || $this->peek(Token::BLOCK_STRING);
    }

    /**
     * @return StringValueNode|null
     */
    private function parseDescription()
    {
        if ($this->peekDescription()) {
            return $this->parseStringLiteral();
        }
    }

    /**
     * @return SchemaDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseSchemaDefinition()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('schema');
        $directives = $this->parseDirectives(true);

        $operationTypes = $this->many(
            Token::BRACE_L,
            function () {
                return $this->parseOperationTypeDefinition();
            },
            Token::BRACE_R
        );

        return new SchemaDefinitionNode([
            'directives'     => $directives,
            'operationTypes' => $operationTypes,
            'loc'            => $this->loc($start),
        ]);
    }

    /**
     * @return OperationTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseOperationTypeDefinition()
    {
        $start     = $this->lexer->token;
        $operation = $this->parseOperationType();
        $this->expect(Token::COLON);
        $type = $this->parseNamedType();

        return new OperationTypeDefinitionNode([
            'operation' => $operation,
            'type'      => $type,
            'loc'       => $this->loc($start),
        ]);
    }

    /**
     * @return ScalarTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseScalarTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('scalar');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);

        return new ScalarTypeDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return ObjectTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseObjectTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('type');
        $name       = $this->parseName();
        $interfaces = $this->parseImplementsInterfaces();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseFieldsDefinition();

        return new ObjectTypeDefinitionNode([
            'name'        => $name,
            'interfaces'  => $interfaces,
            'directives'  => $directives,
            'fields'      => $fields,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * ImplementsInterfaces :
     *   - implements `&`? NamedType
     *   - ImplementsInterfaces & NamedType
     *
     * @return NamedTypeNode[]
     */
    private function parseImplementsInterfaces()
    {
        $types = [];
        if ($this->lexer->token->value === 'implements') {
            $this->lexer->advance();
            // Optional leading ampersand
            $this->skip(Token::AMP);
            do {
                $types[] = $this->parseNamedType();
            } while ($this->skip(Token::AMP) ||
            // Legacy support for the SDL?
            (! empty($this->lexer->options['allowLegacySDLImplementsInterfaces']) && $this->peek(Token::NAME))
            );
        }

        return $types;
    }

    /**
     * @return FieldDefinitionNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseFieldsDefinition()
    {
        // Legacy support for the SDL?
        if (! empty($this->lexer->options['allowLegacySDLEmptyFields']) &&
            $this->peek(Token::BRACE_L) &&
            $this->lexer->lookahead()->kind === Token::BRACE_R
        ) {
            $this->lexer->advance();
            $this->lexer->advance();

            return [];
        }

        return $this->peek(Token::BRACE_L)
            ? $this->many(
                Token::BRACE_L,
                function () {
                    return $this->parseFieldDefinition();
                },
                Token::BRACE_R
            )
            : new NodeList([]);
    }

    /**
     * @return FieldDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseFieldDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $name        = $this->parseName();
        $args        = $this->parseArgumentDefs();
        $this->expect(Token::COLON);
        $type       = $this->parseTypeReference();
        $directives = $this->parseDirectives(true);

        return new FieldDefinitionNode([
            'name'        => $name,
            'arguments'   => $args,
            'type'        => $type,
            'directives'  => $directives,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return InputValueDefinitionNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseArgumentDefs()
    {
        if (! $this->peek(Token::PAREN_L)) {
            return new NodeList([]);
        }

        return $this->many(
            Token::PAREN_L,
            function () {
                return $this->parseInputValueDef();
            },
            Token::PAREN_R
        );
    }

    /**
     * @return InputValueDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseInputValueDef()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $name        = $this->parseName();
        $this->expect(Token::COLON);
        $type         = $this->parseTypeReference();
        $defaultValue = null;
        if ($this->skip(Token::EQUALS)) {
            $defaultValue = $this->parseConstValue();
        }
        $directives = $this->parseDirectives(true);

        return new InputValueDefinitionNode([
            'name'         => $name,
            'type'         => $type,
            'defaultValue' => $defaultValue,
            'directives'   => $directives,
            'loc'          => $this->loc($start),
            'description'  => $description,
        ]);
    }

    /**
     * @return InterfaceTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseInterfaceTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('interface');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseFieldsDefinition();

        return new InterfaceTypeDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'fields'      => $fields,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * UnionTypeDefinition :
     *   - Description? union Name Directives[Const]? UnionMemberTypes?
     *
     * @return UnionTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseUnionTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('union');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $types      = $this->parseUnionMemberTypes();

        return new UnionTypeDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'types'       => $types,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * UnionMemberTypes :
     *   - = `|`? NamedType
     *   - UnionMemberTypes | NamedType
     *
     * @return NamedTypeNode[]
     */
    private function parseUnionMemberTypes()
    {
        $types = [];
        if ($this->skip(Token::EQUALS)) {
            // Optional leading pipe
            $this->skip(Token::PIPE);
            do {
                $types[] = $this->parseNamedType();
            } while ($this->skip(Token::PIPE));
        }

        return $types;
    }

    /**
     * @return EnumTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseEnumTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('enum');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $values     = $this->parseEnumValuesDefinition();

        return new EnumTypeDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'values'      => $values,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return EnumValueDefinitionNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseEnumValuesDefinition()
    {
        return $this->peek(Token::BRACE_L)
            ? $this->many(
                Token::BRACE_L,
                function () {
                    return $this->parseEnumValueDefinition();
                },
                Token::BRACE_R
            )
            : new NodeList([]);
    }

    /**
     * @return EnumValueDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseEnumValueDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $name        = $this->parseName();
        $directives  = $this->parseDirectives(true);

        return new EnumValueDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return InputObjectTypeDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseInputObjectTypeDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('input');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseInputFieldsDefinition();

        return new InputObjectTypeDefinitionNode([
            'name'        => $name,
            'directives'  => $directives,
            'fields'      => $fields,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return InputValueDefinitionNode[]|NodeList
     *
     * @throws SyntaxError
     */
    private function parseInputFieldsDefinition()
    {
        return $this->peek(Token::BRACE_L)
            ? $this->many(
                Token::BRACE_L,
                function () {
                    return $this->parseInputValueDef();
                },
                Token::BRACE_R
            )
            : new NodeList([]);
    }

    /**
     * TypeExtension :
     *   - ScalarTypeExtension
     *   - ObjectTypeExtension
     *   - InterfaceTypeExtension
     *   - UnionTypeExtension
     *   - EnumTypeExtension
     *   - InputObjectTypeDefinition
     *
     * @return TypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseTypeExtension()
    {
        $keywordToken = $this->lexer->lookahead();

        if ($keywordToken->kind === Token::NAME) {
            switch ($keywordToken->value) {
                case 'schema':
                    return $this->parseSchemaTypeExtension();
                case 'scalar':
                    return $this->parseScalarTypeExtension();
                case 'type':
                    return $this->parseObjectTypeExtension();
                case 'interface':
                    return $this->parseInterfaceTypeExtension();
                case 'union':
                    return $this->parseUnionTypeExtension();
                case 'enum':
                    return $this->parseEnumTypeExtension();
                case 'input':
                    return $this->parseInputObjectTypeExtension();
            }
        }

        throw $this->unexpected($keywordToken);
    }

    /**
     * @return SchemaTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseSchemaTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('schema');
        $directives     = $this->parseDirectives(true);
        $operationTypes = $this->peek(Token::BRACE_L)
            ? $this->many(
                Token::BRACE_L,
                [$this, 'parseOperationTypeDefinition'],
                Token::BRACE_R
            ) : [];
        if (count($directives) === 0 && count($operationTypes) === 0) {
            $this->unexpected();
        }

        return new SchemaTypeExtensionNode([
            'directives' => $directives,
            'operationTypes' => $operationTypes,
            'loc' => $this->loc($start),
        ]);
    }

    /**
     * @return ScalarTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseScalarTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('scalar');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        if (count($directives) === 0) {
            throw $this->unexpected();
        }

        return new ScalarTypeExtensionNode([
            'name'       => $name,
            'directives' => $directives,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * @return ObjectTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseObjectTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('type');
        $name       = $this->parseName();
        $interfaces = $this->parseImplementsInterfaces();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseFieldsDefinition();

        if (count($interfaces) === 0 &&
            count($directives) === 0 &&
            count($fields) === 0
        ) {
            throw $this->unexpected();
        }

        return new ObjectTypeExtensionNode([
            'name'       => $name,
            'interfaces' => $interfaces,
            'directives' => $directives,
            'fields'     => $fields,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * @return InterfaceTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseInterfaceTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('interface');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseFieldsDefinition();
        if (count($directives) === 0 &&
            count($fields) === 0
        ) {
            throw $this->unexpected();
        }

        return new InterfaceTypeExtensionNode([
            'name'       => $name,
            'directives' => $directives,
            'fields'     => $fields,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * UnionTypeExtension :
     *   - extend union Name Directives[Const]? UnionMemberTypes
     *   - extend union Name Directives[Const]
     *
     * @return UnionTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseUnionTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('union');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $types      = $this->parseUnionMemberTypes();
        if (count($directives) === 0 &&
            ! $types
        ) {
            throw $this->unexpected();
        }

        return new UnionTypeExtensionNode([
            'name'       => $name,
            'directives' => $directives,
            'types'      => $types,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * @return EnumTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseEnumTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('enum');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $values     = $this->parseEnumValuesDefinition();
        if (count($directives) === 0 &&
            count($values) === 0
        ) {
            throw $this->unexpected();
        }

        return new EnumTypeExtensionNode([
            'name'       => $name,
            'directives' => $directives,
            'values'     => $values,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * @return InputObjectTypeExtensionNode
     *
     * @throws SyntaxError
     */
    private function parseInputObjectTypeExtension()
    {
        $start = $this->lexer->token;
        $this->expectKeyword('extend');
        $this->expectKeyword('input');
        $name       = $this->parseName();
        $directives = $this->parseDirectives(true);
        $fields     = $this->parseInputFieldsDefinition();
        if (count($directives) === 0 &&
            count($fields) === 0
        ) {
            throw $this->unexpected();
        }

        return new InputObjectTypeExtensionNode([
            'name'       => $name,
            'directives' => $directives,
            'fields'     => $fields,
            'loc'        => $this->loc($start),
        ]);
    }

    /**
     * DirectiveDefinition :
     *   - directive @ Name ArgumentsDefinition? on DirectiveLocations
     *
     * @return DirectiveDefinitionNode
     *
     * @throws SyntaxError
     */
    private function parseDirectiveDefinition()
    {
        $start       = $this->lexer->token;
        $description = $this->parseDescription();
        $this->expectKeyword('directive');
        $this->expect(Token::AT);
        $name = $this->parseName();
        $args = $this->parseArgumentDefs();
        $this->expectKeyword('on');
        $locations = $this->parseDirectiveLocations();

        return new DirectiveDefinitionNode([
            'name'        => $name,
            'arguments'   => $args,
            'locations'   => $locations,
            'loc'         => $this->loc($start),
            'description' => $description,
        ]);
    }

    /**
     * @return NameNode[]
     *
     * @throws SyntaxError
     */
    private function parseDirectiveLocations()
    {
        // Optional leading pipe
        $this->skip(Token::PIPE);
        $locations = [];
        do {
            $locations[] = $this->parseDirectiveLocation();
        } while ($this->skip(Token::PIPE));

        return $locations;
    }

    /**
     * @return NameNode
     *
     * @throws SyntaxError
     */
    private function parseDirectiveLocation()
    {
        $start = $this->lexer->token;
        $name  = $this->parseName();
        if (DirectiveLocation::has($name->value)) {
            return $name;
        }

        throw $this->unexpected($start);
    }
}


<?php

declare(strict_types=1);

namespace GraphQL\Utils;

use GraphQL\Error\InvariantViolation;
use GraphQL\Error\Warning;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\ListTypeNode;
use GraphQL\Language\AST\NamedTypeNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeKind;
use GraphQL\Language\AST\NonNullTypeNode;
use GraphQL\Type\Definition\CompositeType;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\FieldArgument;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InputType;
use GraphQL\Type\Definition\InterfaceType;
use GraphQL\Type\Definition\ListOfType;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\OutputType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Type\Definition\WrappingType;
use GraphQL\Type\Introspection;
use GraphQL\Type\Schema;
use SplStack;
use function array_map;
use function array_merge;
use function array_pop;
use function count;
use function is_array;
use function sprintf;

class TypeInfo
{
    /** @var Schema */
    private $schema;

    /** @var SplStack<OutputType> */
    private $typeStack;

    /** @var SplStack<CompositeType> */
    private $parentTypeStack;

    /** @var SplStack<InputType> */
    private $inputTypeStack;

    /** @var SplStack<FieldDefinition> */
    private $fieldDefStack;

    /** @var Directive */
    private $directive;

    /** @var FieldArgument */
    private $argument;

    /** @var mixed */
    private $enumValue;

    /**
     * @param Type|null $initialType
     */
    public function __construct(Schema $schema, $initialType = null)
    {
        $this->schema          = $schema;
        $this->typeStack       = [];
        $this->parentTypeStack = [];
        $this->inputTypeStack  = [];
        $this->fieldDefStack   = [];
        if (! $initialType) {
            return;
        }

        if (Type::isInputType($initialType)) {
            $this->inputTypeStack[] = $initialType;
        }
        if (Type::isCompositeType($initialType)) {
            $this->parentTypeStack[] = $initialType;
        }
        if (! Type::isOutputType($initialType)) {
            return;
        }

        $this->typeStack[] = $initialType;
    }

    /**
     * @deprecated moved to GraphQL\Utils\TypeComparators
     */
    public static function isEqualType(Type $typeA, Type $typeB)
    {
        return TypeComparators::isEqualType($typeA, $typeB);
    }

    /**
     * @deprecated moved to GraphQL\Utils\TypeComparators
     */
    public static function isTypeSubTypeOf(Schema $schema, Type $maybeSubType, Type $superType)
    {
        return TypeComparators::isTypeSubTypeOf($schema, $maybeSubType, $superType);
    }

    /**
     * @deprecated moved to GraphQL\Utils\TypeComparators
     */
    public static function doTypesOverlap(Schema $schema, CompositeType $typeA, CompositeType $typeB)
    {
        return TypeComparators::doTypesOverlap($schema, $typeA, $typeB);
    }

    /**
     * Given root type scans through all fields to find nested types. Returns array where keys are for type name
     * and value contains corresponding type instance.
     *
     * Example output:
     * [
     *     'String' => $instanceOfStringType,
     *     'MyType' => $instanceOfMyType,
     *     ...
     * ]
     *
     * @param Type|null   $type
     * @param Type[]|null $typeMap
     *
     * @return Type[]|null
     */
    public static function extractTypes($type, ?array $typeMap = null)
    {
        if (! $typeMap) {
            $typeMap = [];
        }
        if (! $type) {
            return $typeMap;
        }

        if ($type instanceof WrappingType) {
            return self::extractTypes($type->getWrappedType(true), $typeMap);
        }
        if (! $type instanceof Type) {
            // Preserve these invalid types in map (at numeric index) to make them
            // detectable during $schema->validate()
            $i            = 0;
            $alreadyInMap = false;
            while (isset($typeMap[$i])) {
                $alreadyInMap = $alreadyInMap || $typeMap[$i] === $type;
                $i++;
            }
            if (! $alreadyInMap) {
                $typeMap[$i] = $type;
            }

            return $typeMap;
        }

        if (! empty($typeMap[$type->name])) {
            Utils::invariant(
                $typeMap[$type->name] === $type,
                sprintf('Schema must contain unique named types but contains multiple types named "%s" ', $type) .
                '(see http://webonyx.github.io/graphql-php/type-system/#type-registry).'
            );

            return $typeMap;
        }
        $typeMap[$type->name] = $type;

        $nestedTypes = [];

        if ($type instanceof UnionType) {
            $nestedTypes = $type->getTypes();
        }
        if ($type instanceof ObjectType) {
            $nestedTypes = array_merge($nestedTypes, $type->getInterfaces());
        }
        if ($type instanceof ObjectType || $type instanceof InterfaceType) {
            foreach ($type->getFields() as $fieldName => $field) {
                if (! empty($field->args)) {
                    $fieldArgTypes = array_map(
                        static function (FieldArgument $arg) {
                            return $arg->getType();
                        },
                        $field->args
                    );

                    $nestedTypes = array_merge($nestedTypes, $fieldArgTypes);
                }
                $nestedTypes[] = $field->getType();
            }
        }
        if ($type instanceof InputObjectType) {
            foreach ($type->getFields() as $fieldName => $field) {
                $nestedTypes[] = $field->getType();
            }
        }
        foreach ($nestedTypes as $nestedType) {
            $typeMap = self::extractTypes($nestedType, $typeMap);
        }

        return $typeMap;
    }

    /**
     * @param Type[] $typeMap
     *
     * @return Type[]
     */
    public static function extractTypesFromDirectives(Directive $directive, array $typeMap = [])
    {
        if (is_array($directive->args)) {
            foreach ($directive->args as $arg) {
                $typeMap = self::extractTypes($arg->getType(), $typeMap);
            }
        }

        return $typeMap;
    }

    /**
     * @return InputType|null
     */
    public function getParentInputType()
    {
        $inputTypeStackLength = count($this->inputTypeStack);
        if ($inputTypeStackLength > 1) {
            return $this->inputTypeStack[$inputTypeStackLength - 2];
        }
    }

    /**
     * @return FieldArgument|null
     */
    public function getArgument()
    {
        return $this->argument;
    }

    /**
     * @return mixed
     */
    public function getEnumValue()
    {
        return $this->enumValue;
    }

    public function enter(Node $node)
    {
        $schema = $this->schema;

        // Note: many of the types below are explicitly typed as "mixed" to drop
        // any assumptions of a valid schema to ensure runtime types are properly
        // checked before continuing since TypeInfo is used as part of validation
        // which occurs before guarantees of schema and document validity.
        switch ($node->kind) {
            case NodeKind::SELECTION_SET:
                $namedType               = Type::getNamedType($this->getType());
                $this->parentTypeStack[] = Type::isCompositeType($namedType) ? $namedType : null;
                break;

            case NodeKind::FIELD:
                $parentType = $this->getParentType();
                $fieldDef   = null;
                if ($parentType) {
                    $fieldDef = self::getFieldDefinition($schema, $parentType, $node);
                }
                $fieldType = null;
                if ($fieldDef) {
                    $fieldType = $fieldDef->getType();
                }
                $this->fieldDefStack[] = $fieldDef;
                $this->typeStack[]     = Type::isOutputType($fieldType) ? $fieldType : null;
                break;

            case NodeKind::DIRECTIVE:
                $this->directive = $schema->getDirective($node->name->value);
                break;

            case NodeKind::OPERATION_DEFINITION:
                $type = null;
                if ($node->operation === 'query') {
                    $type = $schema->getQueryType();
                } elseif ($node->operation === 'mutation') {
                    $type = $schema->getMutationType();
                } elseif ($node->operation === 'subscription') {
                    $type = $schema->getSubscriptionType();
                }
                $this->typeStack[] = Type::isOutputType($type) ? $type : null;
                break;

            case NodeKind::INLINE_FRAGMENT:
            case NodeKind::FRAGMENT_DEFINITION:
                $typeConditionNode = $node->typeCondition;
                $outputType        = $typeConditionNode ? self::typeFromAST(
                    $schema,
                    $typeConditionNode
                ) : Type::getNamedType($this->getType());
                $this->typeStack[] = Type::isOutputType($outputType) ? $outputType : null;
                break;

            case NodeKind::VARIABLE_DEFINITION:
                $inputType              = self::typeFromAST($schema, $node->type);
                $this->inputTypeStack[] = Type::isInputType($inputType) ? $inputType : null; // push
                break;

            case NodeKind::ARGUMENT:
                $fieldOrDirective = $this->getDirective() ?: $this->getFieldDef();
                $argDef           = $argType = null;
                if ($fieldOrDirective) {
                    $argDef = Utils::find(
                        $fieldOrDirective->args,
                        static function ($arg) use ($node) {
                            return $arg->name === $node->name->value;
                        }
                    );
                    if ($argDef !== null) {
                        $argType = $argDef->getType();
                    }
                }
                $this->argument         = $argDef;
                $this->inputTypeStack[] = Type::isInputType($argType) ? $argType : null;
                break;

            case NodeKind::LST:
                $listType               = Type::getNullableType($this->getInputType());
                $itemType               = $listType instanceof ListOfType
                    ? $listType->getWrappedType()
                    : $listType;
                $this->inputTypeStack[] = Type::isInputType($itemType) ? $itemType : null;
                break;

            case NodeKind::OBJECT_FIELD:
                $objectType     = Type::getNamedType($this->getInputType());
                $fieldType      = null;
                $inputFieldType = null;
                if ($objectType instanceof InputObjectType) {
                    $tmp            = $objectType->getFields();
                    $inputField     = $tmp[$node->name->value] ?? null;
                    $inputFieldType = $inputField ? $inputField->getType() : null;
                }
                $this->inputTypeStack[] = Type::isInputType($inputFieldType) ? $inputFieldType : null;
                break;

            case NodeKind::ENUM:
                $enumType  = Type::getNamedType($this->getInputType());
                $enumValue = null;
                if ($enumType instanceof EnumType) {
                    $enumValue = $enumType->getValue($node->value);
                }
                $this->enumValue = $enumValue;
                break;
        }
    }

    /**
     * @return Type
     */
    public function getType()
    {
        if (! empty($this->typeStack)) {
            return $this->typeStack[count($this->typeStack) - 1];
        }

        return null;
    }

    /**
     * @return Type
     */
    public function getParentType()
    {
        if (! empty($this->parentTypeStack)) {
            return $this->parentTypeStack[count($this->parentTypeStack) - 1];
        }

        return null;
    }

    /**
     * Not exactly the same as the executor's definition of getFieldDef, in this
     * statically evaluated environment we do not always have an Object type,
     * and need to handle Interface and Union types.
     *
     * @return FieldDefinition
     */
    private static function getFieldDefinition(Schema $schema, Type $parentType, FieldNode $fieldNode)
    {
        $name       = $fieldNode->name->value;
        $schemaMeta = Introspection::schemaMetaFieldDef();
        if ($name === $schemaMeta->name && $schema->getQueryType() === $parentType) {
            return $schemaMeta;
        }

        $typeMeta = Introspection::typeMetaFieldDef();
        if ($name === $typeMeta->name && $schema->getQueryType() === $parentType) {
            return $typeMeta;
        }
        $typeNameMeta = Introspection::typeNameMetaFieldDef();
        if ($name === $typeNameMeta->name && $parentType instanceof CompositeType) {
            return $typeNameMeta;
        }
        if ($parentType instanceof ObjectType ||
            $parentType instanceof InterfaceType) {
            $fields = $parentType->getFields();

            return $fields[$name] ?? null;
        }

        return null;
    }

    /**
     * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode
     *
     * @return Type|null
     *
     * @throws InvariantViolation
     */
    public static function typeFromAST(Schema $schema, $inputTypeNode)
    {
        return AST::typeFromAST($schema, $inputTypeNode);
    }

    /**
     * @return Directive|null
     */
    public function getDirective()
    {
        return $this->directive;
    }

    /**
     * @return FieldDefinition
     */
    public function getFieldDef()
    {
        if (! empty($this->fieldDefStack)) {
            return $this->fieldDefStack[count($this->fieldDefStack) - 1];
        }

        return null;
    }

    /**
     * @return InputType
     */
    public function getInputType()
    {
        if (! empty($this->inputTypeStack)) {
            return $this->inputTypeStack[count($this->inputTypeStack) - 1];
        }

        return null;
    }

    public function leave(Node $node)
    {
        switch ($node->kind) {
            case NodeKind::SELECTION_SET:
                array_pop($this->parentTypeStack);
                break;

            case NodeKind::FIELD:
                array_pop($this->fieldDefStack);
                array_pop($this->typeStack);
                break;

            case NodeKind::DIRECTIVE:
                $this->directive = null;
                break;

            case NodeKind::OPERATION_DEFINITION:
            case NodeKind::INLINE_FRAGMENT:
            case NodeKind::FRAGMENT_DEFINITION:
                array_pop($this->typeStack);
                break;
            case NodeKind::VARIABLE_DEFINITION:
                array_pop($this->inputTypeStack);
                break;
            case NodeKind::ARGUMENT:
                $this->argument = null;
                array_pop($this->inputTypeStack);
                break;
            case NodeKind::LST:
            case NodeKind::OBJECT_FIELD:
                array_pop($this->inputTypeStack);
                break;
            case NodeKind::ENUM:
                $this->enumValue = null;
                break;
        }
    }
}


<?php

declare(strict_types=1);

namespace GraphQL\Type;

use GraphQL\Error\Error;
use GraphQL\Language\AST\EnumValueDefinitionNode;
use GraphQL\Language\AST\FieldDefinitionNode;
use GraphQL\Language\AST\InputValueDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeExtensionNode;
use GraphQL\Language\AST\NamedTypeNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\ObjectTypeDefinitionNode;
use GraphQL\Language\AST\ObjectTypeExtensionNode;
use GraphQL\Language\AST\SchemaDefinitionNode;
use GraphQL\Language\AST\TypeDefinitionNode;
use GraphQL\Language\AST\TypeNode;
use GraphQL\Type\Definition\Directive;
use GraphQL\Type\Definition\EnumType;
use GraphQL\Type\Definition\EnumValueDefinition;
use GraphQL\Type\Definition\FieldDefinition;
use GraphQL\Type\Definition\InputObjectField;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\InterfaceType;
use GraphQL\Type\Definition\NamedType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
use GraphQL\Utils\TypeComparators;
use GraphQL\Utils\Utils;
use function array_filter;
use function array_key_exists;
use function array_merge;
use function count;
use function is_array;
use function is_object;
use function iterator_to_array;
use function sprintf;

class SchemaValidationContext
{
    /** @var Error[] */
    private $errors = [];

    /** @var Schema */
    private $schema;

    public function __construct(Schema $schema)
    {
        $this->schema = $schema;
    }

    /**
     * @return Error[]
     */
    public function getErrors()
    {
        return $this->errors;
    }

    public function validateRootTypes()
    {
        $queryType = $this->schema->getQueryType();
        if (! $queryType) {
            $this->reportError(
                'Query root type must be provided.',
                $this->schema->getAstNode()
            );
        } elseif (! $queryType instanceof ObjectType) {
            $this->reportError(
                'Query root type must be Object type, it cannot be ' . Utils::printSafe($queryType) . '.',
                $this->getOperationTypeNode($queryType, 'query')
            );
        }

        $mutationType = $this->schema->getMutationType();
        if ($mutationType && ! $mutationType instanceof ObjectType) {
            $this->reportError(
                'Mutation root type must be Object type if provided, it cannot be ' . Utils::printSafe($mutationType) . '.',
                $this->getOperationTypeNode($mutationType, 'mutation')
            );
        }

        $subscriptionType = $this->schema->getSubscriptionType();
        if (! $subscriptionType || $subscriptionType instanceof ObjectType) {
            return;
        }

        $this->reportError(
            'Subscription root type must be Object type if provided, it cannot be ' . Utils::printSafe($subscriptionType) . '.',
            $this->getOperationTypeNode($subscriptionType, 'subscription')
        );
    }

    /**
     * @param string                                       $message
     * @param Node[]|Node|TypeNode|TypeDefinitionNode|null $nodes
     */
    private function reportError($message, $nodes = null)
    {
        $nodes = array_filter($nodes && is_array($nodes) ? $nodes : [$nodes]);
        $this->addError(new Error($message, $nodes));
    }

    /**
     * @param Error $error
     */
    private function addError($error)
    {
        $this->errors[] = $error;
    }

    /**
     * @param Type   $type
     * @param string $operation
     *
     * @return TypeNode|TypeDefinitionNode
     */
    private function getOperationTypeNode($type, $operation)
    {
        $astNode = $this->schema->getAstNode();

        $operationTypeNode = null;
        if ($astNode instanceof SchemaDefinitionNode) {
            $operationTypeNode = null;

            foreach ($astNode->operationTypes as $operationType) {
                if ($operationType->operation === $operation) {
                    $operationTypeNode = $operationType;
                    break;
                }
            }
        }

        return $operationTypeNode ? $operationTypeNode->type : ($type ? $type->astNode : null);
    }

    public function validateDirectives()
    {
        $directives = $this->schema->getDirectives();
        foreach ($directives as $directive) {
            // Ensure all directives are in fact GraphQL directives.
            if (! $directive instanceof Directive) {
                $this->reportError(
                    'Expected directive but got: ' . Utils::printSafe($directive) . '.',
                    is_object($directive) ? $directive->astNode : null
                );
                continue;
            }

            // Ensure they are named correctly.
            $this->validateName($directive);

            // TODO: Ensure proper locations.

            $argNames = [];
            foreach ($directive->args as $arg) {
                $argName = $arg->name;

                // Ensure they are named correctly.
                $this->validateName($directive);

                if (isset($argNames[$argName])) {
                    $this->reportError(
                        sprintf('Argument @%s(%s:) can only be defined once.', $directive->name, $argName),
                        $this->getAllDirectiveArgNodes($directive, $argName)
                    );
                    continue;
                }

                $argNames[$argName] = true;

                // Ensure the type is an input type.
                if (Type::isInputType($arg->getType())) {
                    continue;
                }

                $this->reportError(
                    sprintf(
                        'The type of @%s(%s:) must be Input Type but got: %s.',
                        $directive->name,
                        $argName,
                        Utils::printSafe($arg->getType())
                    ),
                    $this->getDirectiveArgTypeNode($directive, $argName)
                );
            }
        }
    }

    /**
     * @param Type|Directive|FieldDefinition|EnumValueDefinition|InputObjectField $node
     */
    private function validateName($node)
    {
        // Ensure names are valid, however introspection types opt out.
        $error = Utils::isValidNameError($node->name, $node->astNode);
        if (! $error || Introspection::isIntrospectionType($node)) {
            return;
        }

        $this->addError($error);
    }

    /**
     * @param string $argName
     *
     * @return InputValueDefinitionNode[]
     */
    private function getAllDirectiveArgNodes(Directive $directive, $argName)
    {
        $argNodes      = [];
        $directiveNode = $directive->astNode;
        if ($directiveNode && $directiveNode->arguments) {
            foreach ($directiveNode->arguments as $node) {
                if ($node->name->value !== $argName) {
                    continue;
                }

                $argNodes[] = $node;
            }
        }

        return $argNodes;
    }

    /**
     * @param string $argName
     *
     * @return TypeNode|null
     */
    private function getDirectiveArgTypeNode(Directive $directive, $argName)
    {
        $argNode = $this->getAllDirectiveArgNodes($directive, $argName)[0];

        return $argNode ? $argNode->type : null;
    }

    public function validateTypes()
    {
        $typeMap = $this->schema->getTypeMap();
        foreach ($typeMap as $typeName => $type) {
            // Ensure all provided types are in fact GraphQL type.
            if (! $type instanceof NamedType) {
                $this->reportError(
                    'Expected GraphQL named type but got: ' . Utils::printSafe($type) . '.',
                    is_object($type) ? $type->astNode : null
                );
                continue;
            }

            $this->validateName($type);

            if ($type instanceof ObjectType) {
                // Ensure fields are valid
                $this->validateFields($type);

                // Ensure objects implement the interfaces they claim to.
                $this->validateObjectInterfaces($type);
            } elseif ($type instanceof InterfaceType) {
                // Ensure fields are valid.
                $this->validateFields($type);

                // Ensure Interfaces include at least 1 Object type.
                $this->validateInterfaces($type);
            } elseif ($type instanceof UnionType) {
                // Ensure Unions include valid member types.
                $this->validateUnionMembers($type);
            } elseif ($type instanceof EnumType) {
                // Ensure Enums have valid values.
                $this->validateEnumValues($type);
            } elseif ($type instanceof InputObjectType) {
                // Ensure Input Object fields are valid.
                $this->validateInputFields($type);
            }
        }
    }

    /**
     * @param ObjectType|InterfaceType $type
     */
    private function validateFields($type)
    {
        $fieldMap = $type->getFields();

        // Objects and Interfaces both must define one or more fields.
        if (! $fieldMap) {
            $this->reportError(
                sprintf('Type %s must define one or more fields.', $type->name),
                $this->getAllObjectOrInterfaceNodes($type)
            );
        }

        foreach ($fieldMap as $fieldName => $field) {
            // Ensure they are named correctly.
            $this->validateName($field);

            // Ensure they were defined at most once.
            $fieldNodes = $this->getAllFieldNodes($type, $fieldName);
            if ($fieldNodes && count($fieldNodes) > 1) {
                $this->reportError(
                    sprintf('Field %s.%s can only be defined once.', $type->name, $fieldName),
                    $fieldNodes
                );
                continue;
            }

            // Ensure the type is an output type
            if (! Type::isOutputType($field->getType())) {
                $this->reportError(
                    sprintf(
                        'The type of %s.%s must be Output Type but got: %s.',
                        $type->name,
                        $fieldName,
                        Utils::printSafe($field->getType())
                    ),
                    $this->getFieldTypeNode($type, $fieldName)
                );
            }

            // Ensure the arguments are valid
            $argNames = [];
            foreach ($field->args as $arg) {
                $argName = $arg->name;

                // Ensure they are named correctly.
                $this->validateName($arg);

                if (isset($argNames[$argName])) {
                    $this->reportError(
                        sprintf(
                            'Field argument %s.%s(%s:) can only be defined once.',
                            $type->name,
                            $fieldName,
                            $argName
                        ),
                        $this->getAllFieldArgNodes($type, $fieldName, $argName)
                    );
                }
                $argNames[$argName] = true;

                // Ensure the type is an input type
                if (Type::isInputType($arg->getType())) {
                    continue;
                }

                $this->reportError(
                    sprintf(
                        'The type of %s.%s(%s:) must be Input Type but got: %s.',
                        $type->name,
                        $fieldName,
                        $argName,
                        Utils::printSafe($arg->getType())
                    ),
                    $this->getFieldArgTypeNode($type, $fieldName, $argName)
                );
            }
        }
    }

    /**
     * @param ObjectType|InterfaceType $type
     *
     * @return ObjectTypeDefinitionNode[]|ObjectTypeExtensionNode[]|InterfaceTypeDefinitionNode[]|InterfaceTypeExtensionNode[]
     */
    private function getAllObjectOrInterfaceNodes($type)
    {
        return $type->astNode
            ? ($type->extensionASTNodes
                ? array_merge([$type->astNode], $type->extensionASTNodes)
                : [$type->astNode])
            : ($type->extensionASTNodes ?: []);
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     *
     * @return FieldDefinitionNode[]
     */
    private function getAllFieldNodes($type, $fieldName)
    {
        $fieldNodes = [];
        $astNodes   = $this->getAllObjectOrInterfaceNodes($type);
        foreach ($astNodes as $astNode) {
            if (! $astNode || ! $astNode->fields) {
                continue;
            }

            foreach ($astNode->fields as $node) {
                if ($node->name->value !== $fieldName) {
                    continue;
                }

                $fieldNodes[] = $node;
            }
        }

        return $fieldNodes;
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     *
     * @return TypeNode|null
     */
    private function getFieldTypeNode($type, $fieldName)
    {
        $fieldNode = $this->getFieldNode($type, $fieldName);

        return $fieldNode ? $fieldNode->type : null;
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     *
     * @return FieldDefinitionNode|null
     */
    private function getFieldNode($type, $fieldName)
    {
        $nodes = $this->getAllFieldNodes($type, $fieldName);

        return $nodes[0] ?? null;
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     * @param string                   $argName
     *
     * @return InputValueDefinitionNode[]
     */
    private function getAllFieldArgNodes($type, $fieldName, $argName)
    {
        $argNodes  = [];
        $fieldNode = $this->getFieldNode($type, $fieldName);
        if ($fieldNode && $fieldNode->arguments) {
            foreach ($fieldNode->arguments as $node) {
                if ($node->name->value !== $argName) {
                    continue;
                }

                $argNodes[] = $node;
            }
        }

        return $argNodes;
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     * @param string                   $argName
     *
     * @return TypeNode|null
     */
    private function getFieldArgTypeNode($type, $fieldName, $argName)
    {
        $fieldArgNode = $this->getFieldArgNode($type, $fieldName, $argName);

        return $fieldArgNode ? $fieldArgNode->type : null;
    }

    /**
     * @param ObjectType|InterfaceType $type
     * @param string                   $fieldName
     * @param string                   $argName
     *
     * @return InputValueDefinitionNode|null
     */
    private function getFieldArgNode($type, $fieldName, $argName)
    {
        $nodes = $this->getAllFieldArgNodes($type, $fieldName, $argName);

        return $nodes[0] ?? null;
    }

    private function validateObjectInterfaces(ObjectType $object)
    {
        $implementedTypeNames = [];
        foreach ($object->getInterfaces() as $iface) {
            if (! $iface instanceof InterfaceType) {
                $this->reportError(
                    sprintf(
                        'Type %s must only implement Interface types, it cannot implement %s.',
                        $object->name,
                        Utils::printSafe($iface)
                    ),
                    $this->getImplementsInterfaceNode($object, $iface)
                );
                continue;
            }
            if (isset($implementedTypeNames[$iface->name])) {
                $this->reportError(
                    sprintf('Type %s can only implement %s once.', $object->name, $iface->name),
                    $this->getAllImplementsInterfaceNodes($object, $iface)
                );
                continue;
            }
            $implementedTypeNames[$iface->name] = true;
            $this->validateObjectImplementsInterface($object, $iface);
        }
    }

    private function validateInterfaces(InterfaceType $iface)
    {
        $possibleTypes = $this->schema->getPossibleTypes($iface);

        if (count($possibleTypes) !== 0) {
            return;
        }

        $this->reportError(
            sprintf(
                'Interface %s must be implemented by at least one Object type.',
                $iface->name
            ),
            $iface->astNode
        );
    }

    /**
     * @param InterfaceType $iface
     *
     * @return NamedTypeNode|null
     */
    private function getImplementsInterfaceNode(ObjectType $type, $iface)
    {
        $nodes = $this->getAllImplementsInterfaceNodes($type, $iface);

        return $nodes[0] ?? null;
    }

    /**
     * @param InterfaceType $iface
     *
     * @return NamedTypeNode[]
     */
    private function getAllImplementsInterfaceNodes(ObjectType $type, $iface)
    {
        $implementsNodes = [];
        $astNodes        = $this->getAllObjectOrInterfaceNodes($type);

        foreach ($astNodes as $astNode) {
            if (! $astNode || ! $astNode->interfaces) {
                continue;
            }

            foreach ($astNode->interfaces as $node) {
                if ($node->name->value !== $iface->name) {
                    continue;
                }

                $implementsNodes[] = $node;
            }
        }

        return $implementsNodes;
    }

    /**
     * @param InterfaceType $iface
     */
    private function validateObjectImplementsInterface(ObjectType $object, $iface)
    {
        $objectFieldMap = $object->getFields();
        $ifaceFieldMap  = $iface->getFields();

        // Assert each interface field is implemented.
        foreach ($ifaceFieldMap as $fieldName => $ifaceField) {
            $objectField = array_key_exists($fieldName, $objectFieldMap)
                ? $objectFieldMap[$fieldName]
                : null;

            // Assert interface field exists on object.
            if (! $objectField) {
                $this->reportError(
                    sprintf(
                        'Interface field %s.%s expected but %s does not provide it.',
                        $iface->name,
                        $fieldName,
                        $object->name
                    ),
                    [$this->getFieldNode($iface, $fieldName), $object->astNode]
                );
                continue;
            }

            // Assert interface field type is satisfied by object field type, by being
            // a valid subtype. (covariant)
            if (! TypeComparators::isTypeSubTypeOf(
                $this->schema,
                $objectField->getType(),
                $ifaceField->getType()
            )
            ) {
                $this->reportError(
                    sprintf(
                        'Interface field %s.%s expects type %s but %s.%s is type %s.',
                        $iface->name,
                        $fieldName,
                        $ifaceField->getType(),
                        $object->name,
                        $fieldName,
                        Utils::printSafe($objectField->getType())
                    ),
                    [
                        $this->getFieldTypeNode($iface, $fieldName),
                        $this->getFieldTypeNode($object, $fieldName),
                    ]
                );
            }

            // Assert each interface field arg is implemented.
            foreach ($ifaceField->args as $ifaceArg) {
                $argName   = $ifaceArg->name;
                $objectArg = null;

                foreach ($objectField->args as $arg) {
                    if ($arg->name === $argName) {
                        $objectArg = $arg;
                        break;
                    }
                }

                // Assert interface field arg exists on object field.
                if (! $objectArg) {
                    $this->reportError(
                        sprintf(
                            'Interface field argument %s.%s(%s:) expected but %s.%s does not provide it.',
                            $iface->name,
                            $fieldName,
                            $argName,
                            $object->name,
                            $fieldName
                        ),
                        [
                            $this->getFieldArgNode($iface, $fieldName, $argName),
                            $this->getFieldNode($object, $fieldName),
                        ]
                    );
                    continue;
                }

                // Assert interface field arg type matches object field arg type.
                // (invariant)
                // TODO: change to contravariant?
                if (! TypeComparators::isEqualType($ifaceArg->getType(), $objectArg->getType())) {
                    $this->reportError(
                        sprintf(
                            'Interface field argument %s.%s(%s:) expects type %s but %s.%s(%s:) is type %s.',
                            $iface->name,
                            $fieldName,
                            $argName,
                            Utils::printSafe($ifaceArg->getType()),
                            $object->name,
                            $fieldName,
                            $argName,
                            Utils::printSafe($objectArg->getType())
                        ),
                        [
                            $this->getFieldArgTypeNode($iface, $fieldName, $argName),
                            $this->getFieldArgTypeNode($object, $fieldName, $argName),
                        ]
                    );
                }
                // TODO: validate default values?
            }

            // Assert additional arguments must not be required.
            foreach ($objectField->args as $objectArg) {
                $argName  = $objectArg->name;
                $ifaceArg = null;

                foreach ($ifaceField->args as $arg) {
                    if ($arg->name === $argName) {
                        $ifaceArg = $arg;
                        break;
                    }
                }

                if ($ifaceArg || ! ($objectArg->getType() instanceof NonNull)) {
                    continue;
                }

                $this->reportError(
                    sprintf(
                        'Object field argument %s.%s(%s:) is of required type %s but is not also provided by the Interface field %s.%s.',
                        $object->name,
                        $fieldName,
                        $argName,
                        Utils::printSafe($objectArg->getType()),
                        $iface->name,
                        $fieldName
                    ),
                    [
                        $this->getFieldArgTypeNode($object, $fieldName, $argName),
                        $this->getFieldNode($iface, $fieldName),
                    ]
                );
            }
        }
    }

    private function validateUnionMembers(UnionType $union)
    {
        $memberTypes = $union->getTypes();

        if (! $memberTypes) {
            $this->reportError(
                sprintf('Union type %s must define one or more member types.', $union->name),
                $union->astNode
            );
        }

        $includedTypeNames = [];

        foreach ($memberTypes as $memberType) {
            if (isset($includedTypeNames[$memberType->name])) {
                $this->reportError(
                    sprintf('Union type %s can only include type %s once.', $union->name, $memberType->name),
                    $this->getUnionMemberTypeNodes($union, $memberType->name)
                );
                continue;
            }
            $includedTypeNames[$memberType->name] = true;
            if ($memberType instanceof ObjectType) {
                continue;
            }

            $this->reportError(
                sprintf(
                    'Union type %s can only include Object types, it cannot include %s.',
                    $union->name,
                    Utils::printSafe($memberType)
                ),
                $this->getUnionMemberTypeNodes($union, Utils::printSafe($memberType))
            );
        }
    }

    /**
     * @param string $typeName
     *
     * @return NamedTypeNode[]
     */
    private function getUnionMemberTypeNodes(UnionType $union, $typeName)
    {
        if ($union->astNode && $union->astNode->types) {
            return array_filter(
                $union->astNode->types,
                static function (NamedTypeNode $value) use ($typeName) {
                    return $value->name->value === $typeName;
                }
            );
        }

        return $union->astNode ?
            $union->astNode->types : null;
    }

    private function validateEnumValues(EnumType $enumType)
    {
        $enumValues = $enumType->getValues();

        if (! $enumValues) {
            $this->reportError(
                sprintf('Enum type %s must define one or more values.', $enumType->name),
                $enumType->astNode
            );
        }

        foreach ($enumValues as $enumValue) {
            $valueName = $enumValue->name;

            // Ensure no duplicates
            $allNodes = $this->getEnumValueNodes($enumType, $valueName);
            if ($allNodes && count($allNodes) > 1) {
                $this->reportError(
                    sprintf('Enum type %s can include value %s only once.', $enumType->name, $valueName),
                    $allNodes
                );
            }

            // Ensure valid name.
            $this->validateName($enumValue);
            if ($valueName !== 'true' && $valueName !== 'false' && $valueName !== 'null') {
                continue;
            }

            $this->reportError(
                sprintf('Enum type %s cannot include value: %s.', $enumType->name, $valueName),
                $enumValue->astNode
            );
        }
    }

    /**
     * @param string $valueName
     *
     * @return EnumValueDefinitionNode[]
     */
    private function getEnumValueNodes(EnumType $enum, $valueName)
    {
        if ($enum->astNode && $enum->astNode->values) {
            return array_filter(
                iterator_to_array($enum->astNode->values),
                static function (EnumValueDefinitionNode $value) use ($valueName) {
                    return $value->name->value === $valueName;
                }
            );
        }

        return $enum->astNode ?
            $enum->astNode->values : null;
    }

    private function validateInputFields(InputObjectType $inputObj)
    {
        $fieldMap = $inputObj->getFields();

        if (! $fieldMap) {
            $this->reportError(
                sprintf('Input Object type %s must define one or more fields.', $inputObj->name),
                $inputObj->astNode
            );
        }

        // Ensure the arguments are valid
        foreach ($fieldMap as $fieldName => $field) {
            // Ensure they are named correctly.
            $this->validateName($field);

            // TODO: Ensure they are unique per field.

            // Ensure the type is an input type
            if (Type::isInputType($field->getType())) {
                continue;
            }

            $this->reportError(
                sprintf(
                    'The type of %s.%s must be Input Type but got: %s.',
                    $inputObj->name,
                    $fieldName,
                    Utils::printSafe($field->getType())
                ),
                $field->astNode ? $field->astNode->type : null
            );
        }
    }
}


<?php

declare(strict_types=1);

namespace GraphQL\Type\Definition;

use Exception;
use GraphQL\Error\Error;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\Node;
use GraphQL\Utils\Utils;
use function floatval;
use function intval;
use function is_bool;
use function is_numeric;

class IntType extends ScalarType
{
    // As per the GraphQL Spec, Integers are only treated as valid when a valid
    // 32-bit signed integer, providing the broadest support across platforms.
    //
    // n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because
    // they are internally represented as IEEE 754 doubles.
    private const MAX_INT = 2147483647;
    private const MIN_INT = -2147483648;

    /** @var string */
    public $name = Type::INT;

    /** @var string */
    public $description =
        'The `Int` scalar type represents non-fractional signed whole numeric
values. Int can represent values between -(2^31) and 2^31 - 1. ';

    /**
     * @param mixed $value
     *
     * @return int|null
     *
     * @throws Error
     */
    public function serialize($value)
    {
        return $this->coerceInt($value);
    }

    /**
     * @param mixed $value
     *
     * @return int
     */
    private function coerceInt($value)
    {
        if ($value === '') {
            throw new Error(
                'Int cannot represent non 32-bit signed integer value: (empty string)'
            );
        }

        $num = floatval($value);
        if ((! is_numeric($value) && ! is_bool($value)) || $num > self::MAX_INT || $num < self::MIN_INT) {
            throw new Error(
                'Int cannot represent non 32-bit signed integer value: ' .
                Utils::printSafe($value)
            );
        }
        $int = intval($num);
        // int cast with == used for performance reasons
        // phpcs:ignore
        if ($int != $num) {
            throw new Error(
                'Int cannot represent non-integer value: ' .
                Utils::printSafe($value)
            );
        }

        return $int;
    }

    /**
     * @param mixed $value
     *
     * @return int|null
     *
     * @throws Error
     */
    public function parseValue($value)
    {
        return $this->coerceInt($value);
    }

    /**
     * @param Node         $valueNode
     * @param mixed[]|null $variables
     *
     * @return int|null
     *
     * @throws Exception
     */
    public function parseLiteral($valueNode, ?array $variables = null)
    {
        if ($valueNode instanceof IntValueNode) {
            $val = (int) $valueNode->value;
            if ($valueNode->value === (string) $val && self::MIN_INT <= $val && $val <= self::MAX_INT) {
                return $val;
            }
        }

        // Intentionally without message, as all information already in wrapped Exception
        throw new Exception();
    }
}


<?php

declare(strict_types=1);

namespace GraphQL\Language\AST;

use GraphQL\Language\Source;
use GraphQL\Language\Token;

/**
 * Contains a range of UTF-8 character offsets and token references that
 * identify the region of the source from which the AST derived.
 */
class Location
{
    /**
     * The character offset at which this Node begins.
     *
     * @var int
     */
    public $start;

    /**
     * The character offset at which this Node ends.
     *
     * @var int
     */
    public $end;

    /**
     * The Token at which this Node begins.
     *
     * @var Token
     */
    public $startToken;

    /**
     * The Token at which this Node ends.
     *
     * @var Token
     */
    public $endToken;

    /**
     * The Source document the AST represents.
     *
     * @var Source|null
     */
    public $source;

    /**
     * @param int $start
     * @param int $end
     *
     * @return static
     */
    public static function create($start, $end)
    {
        $tmp        = new static();
        $tmp->start = $start;
        $tmp->end   = $end;

        return $tmp;
    }

    public function __construct(?Token $startToken = null, ?Token $endToken = null, ?Source $source = null)
    {
        $this->startToken = $startToken;
        $this->endToken   = $endToken;
        $this->source     = $source;

        if (! $startToken || ! $endToken) {
            return;
        }

        $this->start = $startToken->start;
        $this->end   = $endToken->end;
    }
}