... | ... | @@ -56,4 +56,6 @@ Some examples of parse trees and ASTs: |
|
|
|
|
|
No, one can just use the parse tree as generated by, e.g., ANTLR, and generate LLVM IR directly from that, without ever constructing an AST. The advantage of that approach is that the compiler is faster, and perhaps easier/quicker to write initially. The disadvantage is that since the parse tree is not unique and has different rules for equivalent code (see the "if" example above), one has to deal with this in all the other stages of the compiler, and change those every time the grammar is changed. Also one then depends on a particular parser and how it represents the parse tree.
|
|
|
|
|
|
By using an AST, the parser's job is then well defined: just produce an AST. The AST is well defined and does not change (unless you change the language). One can keep extending the parser to cover more syntax corner cases, or one can change the parser library. At the end of the day, the only result that is needed for the rest of the compiler is an AST, and so the rest of the compiler does not depend on the parser at all. So the compiler is easier to maintain. |
|
|
\ No newline at end of file |
|
|
By using an AST, the parser's job is then well defined: just produce an AST. The AST is well defined and does not change (unless you change the language). One can keep extending the parser to cover more syntax corner cases, or one can change the parser library. At the end of the day, the only result that is needed for the rest of the compiler is an AST, and so the rest of the compiler does not depend on the parser at all. So the compiler is easier to maintain.
|
|
|
|
|
|
The AST is a well defined stage which you have to arrive at, one way or another, but it does not matter how you get there, as long as the generated AST is the correct one. Consequently, the rest of the compiler does not depend on the details of the parser, it simply starts with an AST and does not care how it was obtained. The AST nicely decouples the parser from the rest of the compiler. |
|
|
\ No newline at end of file |