World's most popular travel blog for travel bloggers.

[Solved]: Evaluating Statements Using a Parse Tree

, , No Comments
Problem Detail: 

I'm building a compiler. I already have a parse tree which I built using Bison for a grammar similar to the ANSI C grammar in this link. I see that for multiplicative expression in my parse tree, there can be 3 children e.g.

child 1: multiplicative_expression  child 2: '*' child 3: cast_expression 

I expect to implement a new class for interpreting the parse tree. However, I have no idea how to even traverse the parse tree in order to evaluate the statements. How do I traverse the tree properly in order to interpret all the types of statements? I want to interpret not only multiplicative statements but also if-else statements etc.

Asked By : legen wait for it dary

Answered By : babou

An expression is composed usually of an operator (or function) applied to some arguments, or in the simplest case, just a constant (aka literal) or a variable.

For evaluation:
The value of a constant is that constant, The value for a variable is the current value stored in that variable, as each variable corresponds to a memory location where values can be stored. The value of an operator or function applied to arguments is obtained by evaluating arguments (recursively) and then applying the operator or function to the values thus obtained.

Actually, things can be more complex for a function (and some operator), depending on parameter passing mechanisms or evaluation modes (lazy or not), but that is to complex to explain at this level of discourse.

In your example the operator is child 2, and the two other children are arguments.

In general the algorithm does pretty much what you would do if you had to interpret the program by hand. That should be a good guide.

Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/33256

0 comments:

Post a Comment

Let us know your responses and feedback