Esempio n. 1
0
        public Value Run(string code, SourceId sid, Options opts)
        {
            var lexer  = new Lexer.Lexer(code, sid);
            var tokens = lexer.Lex();

            if (opts.DebugLexer)
            {
                foreach (Lexer.Token token in tokens)
                {
                    Console.WriteLine(
                        $"{token.Span.S.ToString()}-{token.Span.E.ToString()}: {token.Ty.Display()}: `{token.Contents}`");
                }
            }

            _ops.SetStream(tokens);
            _ops.Extract();
            if (opts.DebugParser)
            {
                _ops.PrintEntries();
            }

            var parser = new Parser.Parser(_ops, tokens, new Span(0, 0, sid));
            var expr   = parser.ParseProgram();

            if (opts.DebugParser)
            {
                var prettyPrinter = new AstPrinter();
                Console.WriteLine(prettyPrinter.Print(expr));
            }

            return(InterpreterVisitor.Interpret(_env, expr));
        }
        public __DirectiveArgument()
        {
            Description =
                "Value of an argument provided to directive";

            Field <NonNullGraphType <StringGraphType> >(
                "name",
                "Argument name",
                resolve: context => context.Source.Name);

            Field <StringGraphType>(
                "value",
                "A GraphQL-formatted string representing the value for argument.",
                resolve: context =>
            {
                var argument = context.Source;
                if (argument.Value == null)
                {
                    return(null);
                }

                var ast = argument.Value.AstFromValue(context.Schema, argument.ResolvedType);
                if (ast is StringValue value)     //TODO: ???
                {
                    return(value.Value);
                }
                else
                {
                    string result = AstPrinter.Print(ast);
                    return(string.IsNullOrWhiteSpace(result) ? null : result);
                }
            });
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <c>__InputValue</c> introspection type.
        /// </summary>
        /// <param name="allowAppliedDirectives">Allows 'appliedDirectives' field for this type. It is an experimental feature.</param>
        public __InputValue(bool allowAppliedDirectives = false)
        {
            Name = nameof(__InputValue);

            Description =
                "Arguments provided to Fields or Directives and the input fields of an " +
                "InputObject are represented as Input Values which describe their type " +
                "and optionally a default value.";

            Field <NonNullGraphType <StringGraphType> >("name");

            Field <StringGraphType>("description");

            Field <NonNullGraphType <__Type> >("type", resolve: context => ((IProvideResolvedType)context.Source !).ResolvedType);

            Field <StringGraphType>(
                "defaultValue",
                "A GraphQL-formatted string representing the default value for this input value.",
                resolve: context =>
            {
                var hasDefault = context.Source as IHaveDefaultValue;
                if (hasDefault?.DefaultValue == null)
                {
                    return(null);
                }

                var ast       = hasDefault.ResolvedType !.ToAST(hasDefault.DefaultValue);
                string result = AstPrinter.Print(ast);
                return(string.IsNullOrWhiteSpace(result) ? null : result);
            });
Esempio n. 4
0
        public __InputValue()
        {
            Name        = "__InputValue";
            Description =
                "Arguments provided to Fields or Directives and the input fields of an " +
                "InputObject are represented as Input Values which describe their type " +
                "and optionally a default value.";
            Field <NonNullGraphType <StringGraphType> >("name");
            Field <StringGraphType>("description");
            Field <NonNullGraphType <__Type> >("type", resolve: ctx => ctx.Schema.FindType(ctx.Source.Type));
            Field <StringGraphType>(
                "defaultValue",
                "A GraphQL-formatted string representing the default value for this input value.",
                resolve: context =>
            {
                var hasDefault = context.Source;
                if (context.Source == null)
                {
                    return(null);
                }

                var ast    = hasDefault.DefaultValue.AstFromValue(context.Schema, context.Schema.FindType(hasDefault.Type));
                var result = AstPrinter.Print(ast);
                return(string.IsNullOrWhiteSpace(result) ? null : result);
            });
        }
        public void ToAST_Test(IGraphType type, object value, IValue expected)
        {
            var actual = AstPrinter.Print(type.ToAST(value));
            var result = AstPrinter.Print(expected);

            actual.ShouldBe(result);
        }
        /// <summary>
        /// Initializes a new instance of this graph type.
        /// </summary>
        public __DirectiveArgument()
        {
            Description =
                "Value of an argument provided to directive";

            Field <NonNullGraphType <StringGraphType> >(
                "name",
                "Argument name",
                resolve: context => context.Source.Name);

            Field <NonNullGraphType <StringGraphType> >(
                "value",
                "A GraphQL-formatted string representing the value for argument.",
                resolve: context =>
            {
                var argument = context.Source;
                if (argument.Value == null)
                {
                    return("null");
                }

                var grandParent         = context.Parent.Parent;
                int index               = (int)grandParent.Path.Last();
                var appliedDirective    = ((IList <AppliedDirective>)grandParent.Source)[index];
                var directiveDefinition = context.Schema.Directives.Find(appliedDirective.Name);
                var argumentDefinition  = directiveDefinition.Arguments.Find(argument.Name);

                var ast       = argumentDefinition.ResolvedType.ToAST(argument.Value);
                string result = AstPrinter.Print(ast);
                return(string.IsNullOrWhiteSpace(result) ? null : result);
            });
        }
Esempio n. 7
0
        public void prints_node(INode node, string expected)
        {
            var printed = AstPrinter.Print(node);

            printed.ShouldBe(expected);

            if (node is StringValue str)
            {
                var token = GraphQLParser.Lexer.Lex(printed);
                token.Kind.ShouldBe(GraphQLParser.TokenKind.STRING);
                token.Value.ShouldBe(str.Value);
            }
        }
Esempio n. 8
0
        public void TransformToPrefixForm()
        {
            var expr = new Binary(
                new Unary(
                    new Token(TokenType.MINUS, "-", null, 1),
                    new Literal("123")
                    ),
                new Token(TokenType.STAR, "*", null, 1),
                new Grouping(new Literal(123.45))
                );

            AstPrinter sut = new AstPrinter();

            Assert.Equal("(* (- 123) (group 123.45))", sut.Print(expr));
        }
Esempio n. 9
0
        private static void Run(String source)
        {
            var lexer  = new Lexer(source);
            var tokens = lexer.Tokenize();

            var parser     = new Parser(tokens);
            var printer    = new AstPrinter();
            var statements = parser.Parse();

            printer.Print(statements);

            var interpreter = new Interpreter();

            interpreter.Interpret(statements);
        }
Esempio n. 10
0
        public void string_encodes_control_characters()
        {
            var sample = new string(Enumerable.Range(0, 256).Select(x => (char)x).ToArray());
            var ret    = AstPrinter.Print(new StringValue(sample));

            foreach (char c in ret)
            {
                c.ShouldBeGreaterThanOrEqualTo(' ');
            }

            var deserialized = System.Text.Json.JsonSerializer.Deserialize <string>(ret);

            deserialized.ShouldBe(sample);

            var token = GraphQLParser.Lexer.Lex(ret);

            token.Kind.ShouldBe(GraphQLParser.TokenKind.STRING);
            token.Value.ShouldBe(sample);
        }
 private bool SameValue(Argument arg1, Argument arg2)
 {
     return(arg1.Value == null && arg2.Value == null ||
            AstPrinter.Print(arg1.Value) == AstPrinter.Print(arg2.Value));
 }
Esempio n. 12
0
 public void anynode_throws()
 {
     Should.Throw <InvalidOperationException>(() => AstPrinter.Print(new AnyValue("")));
 }
 private static bool SameValue(Argument arg1, Argument arg2)
 {
     // normalize values prior to comparison by using AstPrinter.Print rather than INode.ToString(document)
     return(arg1.Value == null && arg2.Value == null ||
            arg1.Value != null && arg2.Value != null && AstPrinter.Print(arg1.Value) == AstPrinter.Print(arg2.Value));
 }
        public string PrintAstDirective(GraphQLDirective directive)
        {
            var ast = _converter.Directive(directive);

            return(AstPrinter.Print(ast));
        }
Esempio n. 15
0
 public string PrintAstDirective(GraphQLDirective directive) => AstPrinter.Print(CoreToVanillaConverter.Directive(directive));
Esempio n. 16
0
 internal string ResolveQuery(GraphQLOperationDefinition operation)
 {
     return(astPrinter.Print(operation));
 }
        public GraphQLRequest AstToRequest(
            string operationType,
            string operationName,
            VariableDefinitions variableDefinitions,
            ISelection selection,
            JObject variables
            )
        {
            var formattedVariableDefinitions = variableDefinitions.Any()
                ? "(" + string.Join(", ", variableDefinitions.Select(AstPrinter.Print)) + ")"
                : "";

            return(new GraphQLRequest {
                Query = $"{operationType} {operationName}{formattedVariableDefinitions} {{\n {AstPrinter.Print(selection)} \n}}",
                OperationName = operationName,
                Variables = variables
            });
        }
        public string PrintAstDirective(GraphQLDirective directive)
        {
            Schema?.Initialize();

            return(AstPrinter.Print(CoreToVanillaConverter.Directive(directive)));
        }
        public static IEnumerable <string> IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema)
        {
            if (type is NonNullGraphType)
            {
                var nonNull = (NonNullGraphType)type;
                var ofType  = nonNull.ResolvedType;

                if (valueAst == null || valueAst is NullValue)
                {
                    if (ofType != null)
                    {
                        return(new[] { $"Expected \"{ofType.Name}!\", found null." });
                    }

                    return(new[] { "Expected non-null value, found null" });
                }

                return(IsValidLiteralValue(ofType, valueAst, schema));
            }
            else if (valueAst is NullValue)
            {
                return(new string[] { });
            }

            if (valueAst == null)
            {
                return(new string[] {});
            }

            // This function only tests literals, and assumes variables will provide
            // values of the correct type.
            if (valueAst is VariableReference)
            {
                return(new string[] {});
            }

            if (type is ListGraphType)
            {
                var list   = (ListGraphType)type;
                var ofType = list.ResolvedType;

                if (valueAst is ListValue)
                {
                    var index = 0;
                    return(((ListValue)valueAst).Values.Aggregate(new string[] {}, (acc, value) =>
                    {
                        var errors = IsValidLiteralValue(ofType, value, schema);
                        var result = acc.Concat(errors.Map(err => $"In element #{index}: {err}")).ToArray();
                        index++;
                        return result;
                    }));
                }

                return(IsValidLiteralValue(ofType, valueAst, schema));
            }

            if (type is InputObjectGraphType)
            {
                if (!(valueAst is ObjectValue))
                {
                    return(new[] { $"Expected \"{type.Name}\", found not an object." });
                }

                var inputType = (InputObjectGraphType)type;

                var fields    = inputType.Fields.ToList();
                var fieldAsts = ((ObjectValue)valueAst).ObjectFields.ToList();

                var errors = new List <string>();

                // ensure every provided field is defined
                fieldAsts.Apply(providedFieldAst =>
                {
                    var found = fields.FirstOrDefault(x => x.Name == providedFieldAst.Name);
                    if (found == null)
                    {
                        errors.Add($"In field \"{providedFieldAst.Name}\": Unknown field.");
                    }
                });

                // ensure every defined field is valid
                fields.Apply(field =>
                {
                    var fieldAst = fieldAsts.FirstOrDefault(x => x.Name == field.Name);
                    var result   = IsValidLiteralValue(field.ResolvedType, fieldAst?.Value, schema);

                    errors.AddRange(result.Map(err => $"In field \"{field.Name}\": {err}"));
                });

                return(errors);
            }

            var scalar = (ScalarGraphType)type;

            var parseResult = scalar.ParseLiteral(valueAst);

            if (parseResult == null)
            {
                return(new [] { $"Expected type \"{type.Name}\", found {AstPrinter.Print(valueAst)}." });
            }

            return(new string[] {});
        }
Esempio n. 20
0
 public override void PrintNode(AstPrinter p)
 {
     p.Print("op", op);
     p.Print("left", left);
     p.Print("right", right);
 }
Esempio n. 21
0
        static void Main(string[] args)
        {
            string exampleScript = @"define woodtick-theme       = 0
define bar-theme            = 1
define cartographers-theme  = 2
define laundry-theme        = 3
define inn-theme            = 4
define woodshop-theme       = 5

sounds
{
    'wood'      woodtick-theme
    'woodbar'   bar-theme
    'woodcart'  cartographers-theme
    'woodlaun'  laundry-theme
    'woodinn'   inn-theme
    'woodshop'  woodshop-theme
}

action during woodtick-theme
{
    name is 'Enter Bar'
    shortcut is a
    
    enqueue woodtick-theme marker 0
    {
        if largo is pissed-off
        {
            start-music pissed-off-largo-theme
        }
        else
        {
            for a = 1 to 5 ++
            {
                x = a + b * c / (d - e * b)
                jump-to woodtick-theme track random(1,5) beat 4 tick 400
            }
        }
    }
    enqueue woodtick-theme marker 1
    {
        stop-music bar-theme
        start-music bar-theme
    }
}";

            /*
             * string singlelineScript = @"define woodtick-theme = 0 define bar-theme = 1 define cartographers-theme = 2 define laundry-theme = 3 " +
             *  "define inn-theme = 4 define woodshop-theme = 5 sounds { 'wood' woodtick-theme 'woodbar' bar-theme 'woodcart' cartographers-theme 'woodlaun' laundry-theme " +
             *  "'woodinn' inn-theme 'woodshop' woodshop-theme } action during woodtick-theme { name is 'Enter Bar' shortcut is a enqueue woodtick-theme marker 0 { " +
             *  "if largo is pissed-off { start-music pissed-off-largo-theme } else { x = a + b * c / (d - e * b) jump-to woodtick-theme track random(1,5) beat 4 tick 400 " +
             *  "}} enqueue woodtick-theme marker 1 { stop-music bar-theme start-music bar-theme } }";
             */

            string source = exampleScript;

            var parser = new ScriptParser(source);

            try
            {
                var script    = parser.Parse();
                var flattener = new ActionFlattener();
                flattener.Execute(script);
                var printer = new AstPrinter();
                Console.WriteLine(printer.Print(script));
            }
            catch (ParserException ex)
            {
                ConsoleColor defaultColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = defaultColor;
                Console.WriteLine();
                OutputSourceWithPosition(source, ex.Range);
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Returns a string representation of the specified node.
 /// </summary>
 public string Print(INode node) => AstPrinter.Print(node);
Esempio n. 23
0
 public override void PrintNode(AstPrinter p)
 {
     p.Print("ident", ident);
     p.Print("args", Args);
 }
Esempio n. 24
0
        public static IEnumerable <string> IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema)
        {
            if (type is NonNullGraphType nonNull)
            {
                var ofType = nonNull.ResolvedType;

                if (valueAst == null || valueAst is NullValue)
                {
                    if (ofType != null)
                    {
                        return(new[] { $"Expected \"{ofType.Name}!\", found null." });
                    }

                    return(new[] { "Expected non-null value, found null" });
                }

                return(IsValidLiteralValue(ofType, valueAst, schema));
            }
            else if (valueAst is NullValue)
            {
                return(EmptyStringArray);
            }

            if (valueAst == null)
            {
                return(EmptyStringArray);
            }

            // This function only tests literals, and assumes variables will provide
            // values of the correct type.
            if (valueAst is VariableReference)
            {
                return(EmptyStringArray);
            }

            if (type is ListGraphType list)
            {
                var ofType = list.ResolvedType;

                if (valueAst is ListValue listValue)
                {
                    return(listValue.Values
                           .SelectMany(value =>
                                       IsValidLiteralValue(ofType, value, schema)
                                       .Select((err, index) => $"In element #{index + 1}: {err}")
                                       )
                           .ToList());
                }

                return(IsValidLiteralValue(ofType, valueAst, schema));
            }

            if (type is IInputObjectGraphType inputType)
            {
                if (!(valueAst is ObjectValue objValue))
                {
                    return(new[] { $"Expected \"{inputType.Name}\", found not an object." });
                }

                var fields    = inputType.Fields.ToList();
                var fieldAsts = objValue.ObjectFields.ToList();

                var errors = new List <string>();

                // ensure every provided field is defined
                foreach (var providedFieldAst in fieldAsts)
                {
                    var found = fields.Find(x => x.Name == providedFieldAst.Name);
                    if (found == null)
                    {
                        errors.Add($"In field \"{providedFieldAst.Name}\": Unknown field.");
                    }
                }

                // ensure every defined field is valid
                foreach (var field in fields)
                {
                    var fieldAst = fieldAsts.Find(x => x.Name == field.Name);
                    var result   = IsValidLiteralValue(field.ResolvedType, fieldAst?.Value, schema);

                    errors.AddRange(result.Select(err => $"In field \"{field.Name}\": {err}"));
                }

                return(errors);
            }

            var scalar = (ScalarGraphType)type;

            var parseResult = scalar.ParseLiteral(valueAst);

            if (parseResult == null)
            {
                return(new[] { $"Expected type \"{type.Name}\", found {AstPrinter.Print(valueAst)}." });
            }

            return(EmptyStringArray);
        }
 public void AsSelctionSetBase()
 {
     this.Assent(AstPrinter.Print(typeof(ATestGraphQLClass).AsSelctionSet(1)), SelectionSetAssentConfiguration);
 }
 public void AsSelctionSetDeepNested()
 {
     this.Assent(AstPrinter.Print(typeof(DeepNestedGraphQLClass).AsSelctionSet(3)), SelectionSetAssentConfiguration);
 }
 public void AsSelctionSetRespectsJsonProperties()
 {
     this.Assent(AstPrinter.Print(typeof(CamelCaseClass).AsSelctionSet(3)), SelectionSetAssentConfiguration);
 }
 public string Print(INode node)
 {
     return(AstPrinter.Print(node));
 }
Esempio n. 29
0
 internal string ResolveQuery(OperationDefinitionNode operation)
 {
     return(astPrinter.Print(operation));
 }