grammar Simpletest;
prog: test_statement* EOF ;
test_statement
:COPY_TABLE ID INTO_WORD ID # copytable;
ID
: (SIMPLE_LETTER) (SIMPLE_LETTER | '$' | '_' | '#' | ('0'..'9'))*;
COPY_TABLE: 'COPY TABLE';
SIMPLE_LETTER
: 'a'..'z'
| 'A'..'Z'
;
INTO_WORD: 'INTO';
SPACES
: [ tnr]+ -> skip
;
NEWLINE : [rn]+ ;
正如您在上面的测试语法中看到的那样,我希望它能很容易地解析"COPY TABLE blah INTO blah2"这样的内容。然而,结果令人惊讶。$ grun Simpletest prog -tokens -trace -diagnostics -tree
COPY TABLE blah INTO blah2
[@0,0:9='COPY TABLE',<2>,1:0]
[@1,11:14='blah',<1>,1:11]
[@2,16:19='INTO',<1>,1:16]
[@3,21:25='blah2',<1>,1:21]
[@4,27:26='<EOF>',<-1>,2:0]
enter prog, LT(1)=COPY TABLE
enter test_statement, LT(1)=COPY TABLE
consume [@0,0:9='COPY TABLE',<2>,1:0] rule test_statement
consume [@1,11:14='blah',<1>,1:11] rule test_statement
line 1:16 missing 'INTO' at 'INTO'
consume [@2,16:19='INTO',<1>,1:16] rule test_statement
exit test_statement, LT(1)=blah2
line 1:21 extraneous input 'blah2' expecting {<EOF>, 'COPY TABLE'}
consume [@4,27:26='<EOF>',<-1>,2:0] rule prog
exit prog, LT(1)=<EOF>
它成功匹配了COPYTABLE和blah,但是没有匹配INTO和INTO!!
有人能解释一下为什么会这样吗?
嗯,在盯着我自己的问题看了一分钟后,我明白了。它与模棱两可的lex规则有关。'INTO'可以同时匹配INTO_WORD和ID。由于ID位于词法分析器规则的顶部,因此它首先匹配。