1 /** 2 * Provides an AST printer for debugging. 3 * 4 * Copyright: Copyright (C) 1999-2020 by The D Language Foundation, All Rights Reserved 5 * Authors: $(LINK2 http://www.digitalmars.com, Walter Bright) 6 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) 7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/printast.d, _printast.d) 8 * Documentation: https://dlang.org/phobos/dmd_printast.html 9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/printast.d 10 */ 11 12 module dmd.printast; 13 14 import core.stdc.stdio; 15 16 import dmd.expression; 17 import dmd.tokens; 18 import dmd.visitor; 19 20 /******************** 21 * Print AST data structure in a nice format. 22 * Params: 23 * e = expression AST to print 24 * indent = indentation level 25 */ 26 void printAST(Expression e, int indent = 0) 27 { 28 scope PrintASTVisitor pav = new PrintASTVisitor(indent); 29 e.accept(pav); 30 } 31 32 private: 33 34 extern (C++) final class PrintASTVisitor : Visitor 35 { 36 alias visit = Visitor.visit; 37 38 int indent; 39 40 extern (D) this(int indent) 41 { 42 this.indent = indent; 43 } 44 45 override void visit(Expression e) 46 { 47 printIndent(indent); 48 printf("%s %s\n", Token.toChars(e.op), e.type ? e.type.toChars() : ""); 49 } 50 51 override void visit(StructLiteralExp e) 52 { 53 printIndent(indent); 54 printf("%s %s, %s\n", Token.toChars(e.op), e.type ? e.type.toChars() : "", e.toChars()); 55 } 56 57 override void visit(SymbolExp e) 58 { 59 visit(cast(Expression)e); 60 printIndent(indent + 2); 61 printf(".var: %s\n", e.var ? e.var.toChars() : ""); 62 } 63 64 override void visit(DsymbolExp e) 65 { 66 visit(cast(Expression)e); 67 printIndent(indent + 2); 68 printf(".s: %s\n", e.s ? e.s.toChars() : ""); 69 } 70 71 override void visit(DotIdExp e) 72 { 73 visit(cast(Expression)e); 74 printIndent(indent + 2); 75 printf(".ident: %s\n", e.ident.toChars()); 76 printAST(e.e1, indent + 2); 77 } 78 79 override void visit(UnaExp e) 80 { 81 visit(cast(Expression)e); 82 printAST(e.e1, indent + 2); 83 } 84 85 override void visit(BinExp e) 86 { 87 visit(cast(Expression)e); 88 printAST(e.e1, indent + 2); 89 printAST(e.e2, indent + 2); 90 } 91 92 override void visit(DelegateExp e) 93 { 94 visit(cast(Expression)e); 95 printIndent(indent + 2); 96 printf(".func: %s\n", e.func ? e.func.toChars() : ""); 97 } 98 99 static void printIndent(int indent) 100 { 101 foreach (i; 0 .. indent) 102 putc(' ', stdout); 103 } 104 } 105 106