Reputation: 3390
I have simple language like:
funa X ( X+3*funb(1) ) ;
funb Y ( 2*Y ) ;
main ( 2+func(func(1)) ) ;
func A ( funa(A) ) ;
I used CFG to parse above as:
program => (statement)+
statement => (<main_keyword> | <idl> <idu>) <lparan> expression <rparan> <semicolon>
expression => T(<plus> T)*
T => P(<multipliation>P)*
P => <idu> | <idl> <lparan> expression <rparan> | <number>
And token recognizing:
<main_keyword> -> "main"
<idl> -> (["a"-"z"])+
<idu> -> (["A"-"Z"])+
<lparan> -> "("
<rparan> -> ")"
<semicolon> -> ";"
<number> -> (["0"-"9"])+
<plus> -> "+"
<multiplication> -> "*"
I am able to parse above using javaCC, but I dont have idea, how to evaluate above such programs with parser. Above program should evaluate to 15. How to implement such in javaCC, will it be possible using augmenting parser productions? Functions can appear at any place, before call or after call.
Thanks
Upvotes: 4
Views: 4450
Reputation: 170257
You can do this by letting JavaCC create an AST for you 1, and then creating custom nodes while you walk the tree. Once your tree is constructed, you invoke the root node's eval(...)
method to evaluate the entire expression/tree.
A demo of how to evaluate simple expressions with JavaCC + JJTree: http://www.cs.nmsu.edu/~rth/cs/cs471/InterpretersJavaCC.html
A more extensive example, including functions: https://github.com/bkiers/Curta
1 https://javacc.java.net/doc/JJTree.html
Upvotes: 3