Search code examples
parsingcompiler-constructionprogramming-languages

What is the purpose of creating a parse tree?


What is the use of creating a parse tree for a code? This might sound stupid, but i just cant understand how it works. I understand that it can be useful in arithmatic operations for taking precedence into account. But why convert the code into a tree? And what happens after that? I cant seem to understand what i can do with a parse tree. I am trying to write a very small interpreter which does the arithmatic operations and simple if conditions. I have written a small grammar. I have a parse tree. But dont know what to do with it.


Solution

  • Well, if you have a parse tree and you want to finish your interpreter, what you do is you evaluate the tree, recursively.

    To evaluate a block of code, you evaluate each of its statements, one by one.

    To evaluate an if statement, you evaluate the condition expression and depending on the result, you evaluate the then branch or the else branch (if it exists).

    To evaluate addition, you evaluate each operand and then add them together.

    Having syntax tree means these kinds of operations are natural, they usually involve evaluating (some of) the child nodes of the current node and then possibly combining the results together.