... | ... | @@ -46,6 +46,8 @@ Both `if_single_line` and `if_multi_line` and both grammars (i.e., 4 combination |
|
|
|
|
|
The parse tree is the most detailed tree which corresponds 1:1 with how exactly the code is written (usually it ignores white space, but that's about it). AST on the other hand is the most abstract tree that ignores as much about the code as it can, the only condition is that the code generated from AST, while inevitably different from the original code, must produce exactly the same results as the original when compiled by some compiler that correctly implements the language. An AST however is still able to represent different algorithms that produce the same results, such as array vs element-wise operations. In other words, AST abstracts equivalent syntax, but not equivalent algorithms.
|
|
|
|
|
|
Note: some sources will say an "AST", but they actually mean a parse tree. One can tell easily if a given tree is an AST or a parse tree by looking at, say, an "if" statement, if it is in the form `If(expr test, stmt* body, stmt* orelse)` then it is an AST. If the "if" statement has multiple nodes, or if there are any mention of parsing or how things are parsed (e.g., language keywords like 'if', 'then', 'else', ...), then it's a parse tree, since AST does not have any information about how it was parsed.
|
|
|
|
|
|
Some examples of parse trees and ASTs:
|
|
|
|
|
|
* Python: [parse tree](https://docs.python.org/3/reference/grammar.html) and [AST](https://docs.python.org/3/library/ast.html#abstract-grammar).
|
... | ... | |