本文介绍了使用javacc解析和评估简单语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的语言,例如:

I have simple language like:

funa X ( X+3*funb(1) ) ;
funb Y ( 2*Y ) ;
main ( 2+func(func(1)) ) ;
func A ( funa(A) ) ;

我使用CFG将上面的内容解析为:

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>

令牌识别:

<main_keyword>   -> "main"
<idl>            -> (["a"-"z"])+
<idu>            -> (["A"-"Z"])+
<lparan>         -> "("
<rparan>         -> ")"
<semicolon>      -> ";"
<number>         -> (["0"-"9"])+
<plus>           -> "+"
<multiplication> -> "*"

我能够使用javaCC解析以上内容,但是我不知道如何使用解析器评估以上此类程序.上面的程序应该评估为15.如何在javaCC中实现这样,可以使用扩展解析器产生吗?函数可以出现在调用之前或调用之后的任何位置.

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.

谢谢

推荐答案

您可以通过以下方法来实现此目的:让JavaCC为您创建AST,然后在遍历树时创建自定义节点.构建完树之后,您将调用根节点的eval(...)方法来评估整个表达式/树.

You can do this by letting JavaCC create an AST for you , 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.

有关如何使用JavaCC + JJTree评估简单表达式的演示: http://www.cs.nmsu.edu/~rth​​/cs/cs471/InterpretersJavaCC.html

A demo of how to evaluate simple expressions with JavaCC + JJTree: http://www.cs.nmsu.edu/~rth/cs/cs471/InterpretersJavaCC.html

一个更广泛的示例,包括功能: https://github.com/bkiers/Curta

A more extensive example, including functions: https://github.com/bkiers/Curta

https://javacc.java.net/doc/JJTree.html

这篇关于使用javacc解析和评估简单语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 12:39