我有一个Hello.g4
带有语法定义的语法文件:
definition : wordsWithPunctuation ;
words : (WORD)+ ;
wordsWithPunctuation : word ( word | punctuation word | word punctuation | '(' wordsWithPunctuation ')' | '"' wordsWithPunctuation '"' )* ;
NUMBER : [0-9]+ ;
word : WORD ;
WORD : [A-Za-z-]+ ;
punctuation : PUNCTUATION ;
PUNCTUATION : (','|'!'|'?'|'\''|':'|'.') ;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
现在,如果我尝试从以下输入构建解析树:
a b c d of at of abc bcd of
a b c d at abc, bcd
a b c d of at of abc, bcd of
它返回错误:
Hello::definition:1:31: extraneous input 'of' expecting {<EOF>, '(', '"', WORD, PUNCTUATION}
虽然:
a b c d at: abc bcd!
工作正常。
语法、输入或解释器有什么问题?
如果我修改wordsWithPunctuation
规则,通过添加(... | 'of' | ',' word | ...)
然后它完全匹配输入,但它对我来说看起来很可疑 - 这个词如何of
和这个词不一样a
or abc
?或者为什么,
与其他不同punctuation
字符(即为什么它匹配:
or !
, 但不是,
?)?
Update1:
我正在使用 Eclipse 的 ANTLR4 插件,因此项目构建会产生以下输出:
ANTLR Tool v4.2.2 (/var/folders/.../antlr-4.2.2-complete.jar)
Hello.g4 -o /Users/.../eclipse_workspace/antlr_test_project/target/generated-sources/antlr4 -listener -no-visitor -encoding UTF-8
Update2:
上面给出的语法只是以下语法的一部分:
grammar Hello;
text : (entry)+ ;
entry : blub 'abrr' '-' ('1')? '.' ('(' NUMBER ')')? sims '-' '(' definitionAndExamples ')' 'Hello' 'all' 'the' 'people' 'of' 'the' 'world';
blub : WORD ;
sims : sim (',' sim)* ;
sim : words ;
definitionAndExamples : definitions (';' examples)? ;
definitions : definition (';' definition )* ;
definition : wordsWithPunctuation ;
examples : example (';' example )* ;
example : '"' wordsWithPunctuation '"' ;
words : (WORD)+ ;
wordsWithPunctuation : word ( word | punctuation word | word punctuation | '(' wordsWithPunctuation ')' | '"' wordsWithPunctuation '"' )* ;
NUMBER : [0-9]+ ;
word : WORD ;
WORD : [A-Za-z-]+ ;
punctuation : PUNCTUATION ;
PUNCTUATION : (','|'!'|'?'|'\''|':'|'.') ;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
现在我看来,来自entry
规则以某种方式打破了其他规则entry
规则。但为什么?它是语法中的一种反模式吗?