如何确定哪个解析器规则调用了方法?
我需要实现以下功能:我的语法可以接受两个值范围:Value1
和 Value2
。如果我输入:'set value1 100'
,它应该打印'Accepted'
。
这么多工作正常。但我需要增强代码,以便:
- 每当我给出由数字以外的任何值组成的值时,我都会打印一条自定义消息。
- 如果整数不在指定范围内,我会显示一条自定义错误消息,告知该值不适合 inbounds 方法内的 value1/value2。问题是,我如何知道谁打来电话?
我的代码如下:
grammar grammar1;
@parser::members {
private boolean inbounds(Token t, int min, int max) {
int n = Integer.parseInt(t.getText());
if(n >= min && n <= max) {
return true;
}
else {
System.out.println("Value does not lie in the specified range");
return false;
}
}
}
expr : SET attribute EOF;
attribute : Value1 integer1 { System.out.println("Accepted"); }
| Value2 integer2 { System.out.println("Accepted"); }
;
integer1 : Int { inbounds($Int,0,1000) }? ;
integer2 : Int { inbounds($Int,0,10000) }? ;
Int : '0'..'9'+;
SET : 'set';
Value1 : 'value';
Value2 : 'value2';
I need to implement the following functionality: my grammar can accept two range of values, Value1
and Value2
. If I give an input: 'set value1 100'
, it should print 'Accepted'
.
This much is working fine. But I need to enhance the code such that:
- I print a customized message whenever I give some value which is made up of anything other than numeric digits.
- If the integer does not lie the specified range, I display a customized error message telling that the value is not fit for value1/value2 inside inbounds method. The problem is, how do I know who called inbounds?
My code is as follows:
grammar grammar1;
@parser::members {
private boolean inbounds(Token t, int min, int max) {
int n = Integer.parseInt(t.getText());
if(n >= min && n <= max) {
return true;
}
else {
System.out.println("Value does not lie in the specified range");
return false;
}
}
}
expr : SET attribute EOF;
attribute : Value1 integer1 { System.out.println("Accepted"); }
| Value2 integer2 { System.out.println("Accepted"); }
;
integer1 : Int { inbounds($Int,0,1000) }? ;
integer2 : Int { inbounds($Int,0,10000) }? ;
Int : '0'..'9'+;
SET : 'set';
Value1 : 'value';
Value2 : 'value2';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个特殊语法的简单答案:每当 max 等于 1000 时,就会通过 value 表达式调用 inbound,否则输入是 < code>value2 表达式。
Trivial answer for this special grammar: whenever max is equal to
1000
,inbound
has been called through thevalue
expression, otherwise the input was avalue2
expression.我得到了第二个问题的解决方案:“我如何知道谁调用了入站方法”
以下语法正在解决这个问题:
I got a solution for my second question: 'How do I know who called the method inbounds'
The following grammar is solving this problem: