parsing and evaluating simple language using javacc

蓝咒 提交于 2019-12-07 13:27:25

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/16189940/parsing-and-evaluating-simple-language-using-javacc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!