[英]How to write MIN MAX operation using ANTLR lexer and parser?
For my project I have to define a new grammar rule while will calculate the MIN or MAX of giving argument.Below is the example. 对于我的项目,我必须定义一个新的语法规则,同时将计算给定参数的MIN或MAX。以下是示例。
MIN(3, 4, 5, 6) = 3
MIN(3, 5, 6, 7, 8) = 3
Basically the problem I am facing is defining the TreeWalker function, where it should take variable number of argument. 基本上,我面临的问题是定义TreeWalker函数,该函数应采用可变数量的参数。
The language I am using is Java. 我使用的语言是Java。
OK I will put a snippet of the code which is more or less similar but not the exact one 好吧,我会放一段与或多或少相似但不完全相同的代码
Parser Rule: 解析器规则:
minExpr
: MIN^ LPAREN! minExprStmt RPAREN!
;
minExprStmt
: digitExpr (COMA! digitExpr)+
;
Lexer Rule: Lexer规则:
token{
MIN="MIN"
}
TreeWalker: TreeWalker:
getNode return [double r]
{ExpNode a=null; r = null;}
: #(MIN a=getNode)
{try{r=new MinExpNode();}catch(Exception e){throw new RecognitionException(e.toString();}}
So now what I want is that MinExpNode should take a list or an array of ExpNode in constructor, which in turn will give the computed value of each expNode. 因此,现在我想要的是MinExpNode应该在构造函数中使用ExpNode的列表或数组,而后者又将给出每个expNode的计算值。
I am not using any external libraries for this. 我没有为此使用任何外部库。
Well after some research I think I found a solutions, TreeWalker Code: 经过一番研究,我认为我找到了TreeWalker代码解决方案:
getNode return [double r]
{ExpNode a=null; List<ExpNode> list = new ArrayLis<ExpNode>(); r = null;}
: #(MIN a=getNode {list.add(a);} ({ExpNode b = getNode; list.add(b);})*)
{try{r=new MinExpNode(list);}catch(Exception e){throw new RecognitionException(e.toString();}}
But still if you can suggest me a better one it would be very helpful. 但是,如果您能建议我一个更好的选择,那将非常有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.