我需要實現以下功能:我的語法可以接受兩個範圍的值,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';
ANTLR: expr:(Accepted_Values){Do_Something(); } | (for_all_other_values){Print_Error_Message(); } – Preeti 2011-04-06 08:39:18