Creating simple calculator with bison & flex in C++ (not C)
- by ak91
Hey,
I would like to create simple C++ calculator using bison and flex. Please note I'm new to the creating parsers. I already found few examples in bison/flex but they were all written in C.
My goal is to create C++ code, where classes would contain nodes of values, operations, funcs - to create AST (evaluation would be done just after creating whole AST - starting from the root and going forward).
For example:
my_var = sqrt(9 ** 2 - 32) + 4 - 20 / 5
my_var * 3
Would be parsed as:
=
/ \
my_var +
/ \
sqrt -
| / \
- 4 /
/ \ / \
** 32 20 5
/ \
9 2
and the second AST would look like:
*
/ \
my_var 3
Then following pseudocode reflects AST:
ast_root = create_node('=', new_variable("my_var"), exp)
where exp is:
exp = create_node(OPERATOR, val1, val2)
but NOT like this:
$$ = $1 OPERATOR $3
because this way I directly get value of operation instead of creation the Node.
I believe the Node should contain type (of operation), val1 (Node), val2 (Node). In some cases val2 would be NULL, like above mentioned sqrt which takes in the end one argument. Right?
It will be nice if you can propose me C++ skeleton (without evaluation) for above described problem (including *.y file creating AST) to help me understand the way of creating/holding Nodes in AST. Code can be snipped, just to let me get the idea.
I'll also be grateful if you point me to an existing (possibly simple) example if you know any.
Thank you all for your time and assistance!