akawhy
akawhy

Reputation: 1608

How to use lemon to handle a expression with variables

I want to implement such a program: it reads some expressions which includes some variables. These variables will be set later, and the program should calculate the final result(like sql prepared statement).

For example, the expression maybe like $foo + $bar + 2, and I need to calculate the result when $foo and $bar is set later.

I'm trying to implement it with ragel and lemon. I have learned use ragel to parse the expression. But I don't know how to use lemon to handle the variable and do the calculation.

Thanks for any help.

Upvotes: 2

Views: 204

Answers (1)

Anton Gorev
Anton Gorev

Reputation: 433

You have to build AST for your expression. For every variable in this tree you should save some pointer to a variable (just a name for instance). At the evaluation time, you have to provide values for variable entries. For example, it might be a dictionary <variable name> -> <variable value>.

As an example of building AST on C++ using lemon, I can suggest this one: https://github.com/kvirund/calculator

veei@sauron:~/git/calculator/build$ ./test.it
expr> foo=1
Value: 1
expr> bar=2
Value: 2
expr> foo+bar+2
Value: 5
expr>

But there re2c was used instead of Ragel as tokens provider.

Upvotes: 2

Related Questions