// Usage example of processors and traversers static string printTree(Node tree, System.Type traverserType, int method) { AstPrinter proc = null; switch (method) { // Possible methods to create a processor: // use traverser object case 1: Traverser <bool> vtrav = (Traverser <bool>)Activator.CreateInstance(traverserType); proc = new AstPrinter(vtrav); vtrav.Processor = proc; break; // use 2 steps case 2: proc = new AstPrinter(); Activator.CreateInstance(traverserType, proc); break; // explicitly set traverser case 3: proc = new AstPrinter(); Traverser <bool> trav = (Traverser <bool>)Activator.CreateInstance(traverserType, proc); trav.Processor = proc; proc.traverse = trav.traverse; break; default: return(""); } proc.Visit(tree); return(proc.ToString()); }
/// <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); }); }
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); } }); }
/// <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); });
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); }
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)); }
private static void Run(string Source) { if (!String.IsNullOrEmpty(Source)) { var scanner = new Scanner(Source); List <Token> Tokens = scanner.ScanTokens(); Tokens.ForEach(token => Console.WriteLine(token)); // Tokens into meaningful expressions. Parser parser = new Parser(Tokens); var expr = parser.Parse(); interpreter.Interpret(expr); if (hadError) { Console.WriteLine("Csharp -Lox has died badly."); return; } if (hadRuntimeError) { Console.WriteLine("Csharp - Runtime smash.."); return; } Console.WriteLine(AstPrinter.PrintExpression(expr)); } }
private static void PrintAst(AbstractSyntaxTree ast) { foreach (GameObjectNode gameObject in ast.Root.GameObjects.Values) { AstPrinter astPrinter = new AstPrinter(); astPrinter.Visit(gameObject); } }
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); } }
public void Parse() { if (_result.GetType() == typeof(Parser.ParserException)) { Assert.Throws(_result.GetType(), () => new Parser(new Scanner(_expr).ScanTokens()).Parse()); } else { var e = new Parser(new Scanner(_expr).ScanTokens()).Parse(); var s = new AstPrinter().Print(e, _context); Console.WriteLine(s); Assert.AreEqual(_result, s); } }
public void AstPrinterTest() { Expr expression = new Binary( new Unary( new Token(TokenType.Minus, "-", null), new Literal(123)), new Token(TokenType.Star, "*", null), new Grouping( new Literal(45.67))); var result = new AstPrinter().Print(expression); Assert.AreEqual(result, "(* (- 123) (group 45,67))"); Console.WriteLine(result); }
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)); }
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); }
public void AstPrinter_Print_Binary() { // Arrange Expr expression = new Binary( new Unary( new Token(TokenType.MINUS, "-", null, 1), new Literal(123)), new Token(TokenType.STAR, "*", null, 1), new Grouping( new Literal(45.67))); // Act var actual = new AstPrinter().Print(expression); var expected = "(* (- 123) (group 45.67))"; // Assert Assert.Equal(expected, actual); }
private static int Run(string source) { Scanner scanner = new Scanner(source); Token[] tokens = scanner.ScanTokens().ToArray(); Parser parser = new Parser(tokens); Stmt[] statements = parser.Parse().ToArray(); var astPrinter = new AstPrinter(); foreach (Stmt stmt in statements) { foreach (string print in astPrinter.PrintStmt(stmt)) { Console.WriteLine(print); } } if (HadError) { Console.Read(); return(65); } Resolver resolver = new Resolver(Interpreter); resolver.Resolve(statements); if (HadError) { Console.Read(); return(65); } Interpreter.Interpret(statements); if (HadRuntimeError) { Console.Read(); return(70); } Console.Read(); return(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); }
public void TestAstPrinter() { string result; using (StringWriter writer = new StringWriter()) using (AstPrinter printer = new AstPrinter(writer)) { Expr expression = new Expr.Binary( new Expr.Unary( new Token(TokenType.MINUS, "-", null, 1), new Expr.Literal(123)), new Token(TokenType.STAR, "*", null, 1), new Expr.Grouping( new Expr.Literal(45.67))); printer.Write(expression); result = writer.ToString(); } string expected = "(* (- 123) (group 45.67))"; Assert.AreEqual(expected, result); }
static void Old(string[] args) { // CsLoxInterpreter.Details.CSLox.Main(args); var expr = new Expr.Binary( new Expr.Unary( new Token(TokenType.MINUS, "-", null, 1), new Expr.Literal(123)), new Token(TokenType.STAR, "*", null, 1), new Expr.Grouping( new Expr.Literal(45.67))); var expr2 = new Expr.Binary( new Expr.Binary(new Expr.Literal(100), new Token(TokenType.PLUS, "*", null, 1), new Expr.Literal(45)), new Token(TokenType.STAR, "*", null, 1), new Expr.Binary(new Expr.Literal(80), new Token(TokenType.SLASH, "/", null, 1), new Expr.Literal(42))); Console.WriteLine(AstPrinter.PrintExpression(expr)); Console.WriteLine(RpnAstPrinter.PrintExpression(expr)); Console.WriteLine(AstPrinter.PrintExpression(expr2)); Console.WriteLine(RpnAstPrinter.PrintExpression(expr2)); }
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); }
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); } }
private bool SameValue(Argument arg1, Argument arg2) { return(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)); }
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) => AstPrinter.Print(CoreToVanillaConverter.Directive(directive));
public bool Compile(string[] filenames) { bool success = true; Console.WriteLine("MultiPascal Delphi compiler"); // Load, preprocess and order them planner.LoadFiles(filenames); if (planner.GetNumFiles() == 0) { return(false); } Console.WriteLine(planner.ListFiles()); AstPrinter astPrinter = new AstPrinter(); NameResolver resolver = new NameResolver(); int skip = 0; foreach (SourceFile sf in planner.GetSourceFiles()) { if (++skip < 0) { continue; } Console.Write("####### Compile file " + Path.GetFileName(sf.name) + ": "); if (sf.preprocText == null) // preprocessing failed { success = false; Console.Error.WriteLine("preprocessing failed"); break; } StringReader sr = new StringReader(sf.preprocText); TranslationUnit ast = null; try { ast = parser.Parse(sr, sf); } catch (ParserException e) { Console.Error.WriteLine(e); Console.Error.WriteLine("Parsing failed"); success = false; break; } if (ast == null) { Console.ReadLine(); continue; } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Parsed OK: " + ast.name + " " + ast.ToString()); Console.ResetColor(); resolver.Reset(sf); resolver.Process(ast); Console.WriteLine("Name Resolving OK: " + ast.name + " " + ast.ToString()); DeclarationsEnvironment env = resolver.declEnv; env.InitEnvironment(); // Console.WriteLine(env.symEnv.ListTreeFromRoot(Int32.Max, false)); PostProcessing.SetParents(ast); // new ParentProcessor().StartProcessing(ast); Console.WriteLine("SET parents OK: " + ast.name + " " + ast.ToString()); // astPrinter.Process(ast); // Console.WriteLine(astPrinter.Output()); ConstantFolder constfolder = new ConstantFolder(); constfolder.Process(ast); CppCodegen cppGen = new CppCodegen(); Console.WriteLine("Now compiling..."); cppGen.Process(ast); Console.WriteLine(cppGen.Output()); LlvmILGen llvmGen = new LlvmILGen(); // llvmGen.Process(ast); } return(success); }
public void AsSelctionSetRespectsJsonProperties() { this.Assent(AstPrinter.Print(typeof(CamelCaseClass).AsSelctionSet(3)), SelectionSetAssentConfiguration); }
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[] {}); }
public string Print(INode node) { return(AstPrinter.Print(node)); }
public void Compile() { lexer.GetText(); try { lexer.StartLexer(); } catch (Exception e) { Console.WriteLine(e.Message); //throw; return; } parser = new Parser(lexer.GetTokens(), lexer.GetScriptName()); Root root; try { root = parser.ParseProgram(); } catch (Exception e) { Console.WriteLine(e.Message); //throw; return; } foreach (var decl in root.Decls.Where(decl => decl.ReturnName().Value.ToString().ToLower() == "main" && decl.getParams().Count == 0)) { mainFound = true; } if (!mainFound) { Console.WriteLine($"{lexer.GetScriptName()}:{lexer.GetTokens().Last().LineN}: error: function main must exist and have zero parameters"); return; } var printer = new AstPrinter(); //printer.Print("root", root); var rootScope = new Scope(null, lexer.GetScriptName()); try { root.ResolveNames(rootScope); } catch (Exception e) { Console.WriteLine(e.Message); GlobalVars.running = false; //throw; } try { root.CheckTypes(); } catch (Exception e) { Console.WriteLine(e.Message); //throw; } if (!GlobalVars.running) { return; } PushInstructions(); var writer = new CodeWriter(); try { root.GenCode(writer); writer.DumpCode(); } catch (Exception e) { Console.WriteLine(e.Message); //throw; return; } var interpreter = new Interpreter.Interpreter(writer.Code, CodeWriter.StringStorage); try { interpreter.Exec(); } catch (Exception e) { /*if (e is System.FormatException) * { * //Console.WriteLine($"{GlobalVars.FileName}:{}:Error :Input was not an integer"); * //throw; * return; * }*/ Console.WriteLine(e.Message); //throw; } }