Antlr示例语法错误

时间:2014-07-09 18:40:51

标签: antlr

我是ANTLR的新手,我定义了以下测试语法,它基本上用于解析一系列赋值语句,如下所示

x=1
y=10

=============================================== ========================

grammar test;

program
    :
        assignstatement*
    ;

assignstatement
    :
        ID '=' INT   
    ;

ID : ('_'|'a'..'z'|'A'..'Z'|DIGIT) ('_'|'a'..'z'|'A'..'Z'|DIGIT)*;

INT: DIGIT+;

fragment DIGIT : [0-9] ; // not a token by itself

运行testRig时出现以下错误

[@0,0:0='x',<1>,1:0]
[@1,2:2='=',<3>,1:2]
[@2,4:4='1',<1>,1:4]
[@3,7:7='y',<1>,2:0]
[@4,9:9='=',<3>,2:2]
[@5,11:12='10',<1>,2:4]
[@6,14:13='<EOF>',<-1>,3:0]
line 1:4 missing INT at '1'
line 2:0 extraneous input 'y' expecting '='
line 2:4 missing INT at '10'
line 3:0 mismatched input '<EOF>' expecting '='

(program (assignstatement x = <missing INT>) (assignstatement 1 y = <missing INT>) (assignstatement 10))

有人可以找出造成这些错误的原因吗?

1 个答案:

答案 0 :(得分:3)

词法分析器永远不会创建INT标记,因为您的ID规则也匹配仅由数字组成的标记。

让你的ID规则能够以数字开头,你就可以了:

ID : ('_'|'a'..'z'|'A'..'Z') ('_'|'a'..'z'|'A'..'Z'|DIGIT)*;

或同等的:

ID : [_a-zA-Z] [_a-zA-Z0-9]*;