1 语法树(parse tree):
是在parsing阶段,derivation的图像化表示,parser tree focus on grammar的actual implemment,包括像white spaces, braces, keywords, parenthesis 等一些细节。 “parse tree” 也叫 “concrete syntax tree” ,它represents the syntactic structure of a string
(or token stream)according to some context-free grammar.
In the picture above you can see that:
- The parse tree records a sequence of rules the parser applies to recognize the input.
parse tree记录解析器应用于识别输入的一系列规则 - The root of the parse tree is labeled with the grammar start symbol.
parse tree的根是grammar的start non-terminal symbol。 - Each interior node represents a non-terminal, that is it represents a grammar rule application, like expr, term, or factor in our case.
每个内部节点代表一个非终端,即它代表语法规则应用程序,如我们的情况下的expr,term或factor。 - Each leaf node represents a token.
每个叶节点代表一个token。
2 抽象语法树(abstract syntax tree)
AST is a tree representation of the abstract syntactic structure of source code
written in a programming language.它 focus on source code的 各个 components 之间的abstract relationships。 it doesn’t need to contain all the syntactical elements
the AST captures the essence of the input while being smaller. AST在较小的情况下捕获了输入的本质
3 What’s the difference
1.every grammars for the same language will give different parse trees but should result to the same AST
2. AST 不focus on the ways they are generated by a grammar.。 AST focuses on programming constructs。也就是operators:computational operators( ±*/ [a, b]),for operator(for [ expr, expr, expr, stmnt ])
- ASTs uses operators/operations as root and interior nodes and it uses operands as their children.
AST使用运算符/操作作为根节点和内部节点,并使用操作数作为子节点。 - ASTs do not use interior nodes to represent a grammar rule, unlike the parse tree does.
与解析树不同,AST不使用内部节点来表示语法规则 - ASTs don’t represent every detail from the real syntax (that’s why they’re called abstract) - no rule nodes and no parentheses, for example.
AST并不代表真实语法中的每个细节(这就是为什么它们被称为抽象) - 例如,省略了节点和括号等细节。 - ASTs are dense compared to a parse tree for the same language construct
与同一语言构造的解析树相比,AST是密集的。
4 statement的parse tree & AST
java code snippet
for (int i = 0 ; i< 5; i=i+1)
{
sum = sum+i;
}
parse tree
grammar: grammars-v4/java
AST
为了体现和parser tree的对比
一般AST都表示为
5 block的parse tree & AST
6 expression的parse tree & AST
7 class的parse tree & AST
java code snippet
package visualize_AST;
public class Student {
private String name;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
parse tree
AST只关注program construction。
AST
reference 和blog :
Parse tree
What’s the difference between parse tree and AST?
What’s the difference between parse tree and AST?