I try to build a very simple calculator supporting x,y,+,-,*,/(,). The idea is simple:
- Build syntax tree from input string (which may be: “x+3y”)
- For given x,y calculate the result by parsing the syntax tree, and inserting ints for x and y.
With boost 1.46, you can easily do both steps at once, using parse_phrase(). However, I have to execute step 2 a million of times, while the parsing does not change. So I’d like to separate this (like it was usual in the classic spirit versions). How can I do this? (Please note: boost 1.46 has no utree data structure yet)
I got a solution meanwhile. It is pretty simple, look at the boost docs linked here.
The main() function contains this code:
There are actually multiple phrase_parse() functions in boost. There are variations of the phrase_parse without and “variation[s] of the phrase_parse with an additional argument: the parser’s attribute.”, as stated in the boost docs. In the above code,
astis the parser’s attribute;printerthen evaluates the ast.If we wanted to evaluate the printer with different values from outside, we would pass them to printer before each call of
printer(ast).Note for 1.46: There’s no
boost::utreein yet. However, the AST in this example is a replacement with full functionaliy.