【发布时间】:2018-02-01 11:39:33
【问题描述】:
我是 ANTLR 的新手,正在开发一个解析器来解析 SAS 代码,该代码主要由 if then else if 语句组成。我创建了以下语法来解析代码,但是当我尝试使用示例应用程序运行时,Intellij 出现错误。
语法创建:
grammar SASDTModel;
parse
: if_block+
| score_block
;
//Model
// : If_block+
// | Score_block
// ;
if_block
: (if_statement|if_in_block)
| else_if_statement+
| else_statement
;
if_statement
: IF '(' if_condition ')' THEN Identifier'='Value ';'
| IF Identifier'='Value THEN Identifier'='Value ';'
;
else_if_statement
: ELSEIF '(' if_condition ')' THEN Identifier'='Value ';'
| ELSEIF Identifier'='Value THEN Identifier'='Value ';'
;
if_condition
: Value ComparisionOperators Identifier ComparisionOperators Value
| Value ComparisionOperators Value;
else_statement
: ELSE Identifier'='Value ';'
;
if_in_block
: IF Identifier IN '(' StringArray ')' THEN Identifier'='Value ';'
;
score_block
: Identifier'='Arithmetic_expression ';'
;
Arithmetic_expression:
| ( ArithmeticOperators '(' Value ')' )+
| ( ArithmeticOperators '(' Value ArithmeticOperators Identifier ')' )+
;
WS : ( ' ' | '\t' | '\r' | '\n' )-> channel(HIDDEN);
//WS : [ \t\n\r]+ -> channel(HIDDEN) ;
//WS : (' ' | '\t')+ -> channel(HIDDEN);
//COMMENT : '/*' .*? '*/' -> skip ;
//LINE_COMMENT : '*' ~[\r\n]* -> skip ;
ArithmeticOperators:
| '+'
| '-'
| '*'
| '/'
| '**'
;
ComparisionOperators
: '=='
| '<'
| '>'
| '<='
| '>='
;
IF: 'IF' | 'if' ;
ELSE: 'ELSE' | 'else' ;
ELSEIF: 'ELSE IF' | 'else if' ;
THEN: 'THEN' | 'then';
IN: 'IN' | 'in';
Value : INT
| DOUBLE
| '-'DOUBLE
| '-'INT
| Identifier
|'null';
INT : [0-9];
DOUBLE : INT+ PT INT+
| PT INT+
| INT+
;
PT : '.';
Identifier : ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')* ;
StringArray : (('\'')(Value)('\''))+;
输入:
if scored = null then scored = -0.05;
else if ( 0 < scored <= 300 ) then scored = -0.5;
else if ( 300 < scored <= 500 ) then scored = -0.4;
else if ( 500 < scored <= 800 ) then scored = -0.8;
else if ( 800 < scored <= 1000 ) then scored = 0.9;
else if ( scored > 1000 ) then scored = 1.735409628;
else scored = 0;
错误我得到了
line 1:4 no viable alternative at input 'IF scored'
line 1:61 mismatched input '<=' expecting ')'
line 1:112 mismatched input '<=' expecting ')'
line 1:163 mismatched input '<=' expecting ')'
line 1:214 mismatched input '<=' expecting ')'
line 1:276 mismatched input 'scored' expecting Identifier
line 1:303 mismatched input 'scored' expecting Identifier
所有错误代码都是 1:因为我正在预处理 SAS 代码并删除任何 cmets 并转换为单行。
所以在预处理后输入被转换为以下内容:`
IF 得分 = null THEN 得分 = -0.05;ELSE IF ( 0 1000) THEN 得分 = 1.735409628;否则得分 = 0;
`
【问题讨论】:
-
可能缺少括号?
if (scored = null) ... -
我对没有括号的场景有第二条规则,所以我认为它仍然应该能够匹配它。 IF Identifier'='Value THEN Identifier'='Value ';' 如果我的理解有误,请纠正我。
-
嗯。你是对的。但也许试试看你是否得到不同的行为。
-
所以在我添加括号后,错误确实更改为 line 1:27 mismatched input 'scored' Expecting Identifier 虽然仍然对新错误感到困惑。
-
这意味着解析器无法识别您的
if_statement中的第二种选择。我对 ANTLR 不够熟悉,无法为您提供帮助。但是您现在可能对如何逐步完成一些想法。
标签: java parsing sas antlr4 parser-generator