ANTLR4 语法不识别布尔文字

ANTLR4 Grammar doesn't recognize Boolean literals

为什么下面的语法不能识别布尔值?

我已经将其与 Java 和 GraphQL 的语法进行了比较,但不明白为什么它不起作用。

给定以下语法,解析如下:

foo = null // foo = value:nullValue
foo = 123 // foo = value:numberValue
foo = "Hello" // foo = value:stringValue
foo = true // line 1:6 mismatched input 'true' expecting {'null', STRING, BOOLEAN, NUMBER}

怎么了?

grammar issue;

elementValuePair
    :   Identifier '=' value
    ;

Identifier : [_A-Za-z] [_0-9A-Za-z]* ;

value
   : STRING # stringValue | NUMBER # numberValue | BOOLEAN # booleanValue | 'null' #nullValue
   ;

STRING
   : '"' ( ESC | ~ ["\] )* '"'
   ;

BOOLEAN
   : 'true' | 'false'
   ;

NUMBER
   : '-'? INT '.' [0-9]+| '-'? INT | '-'? INT
   ;

fragment INT
   : '0' | [1-9] [0-9]*
   ;

fragment ESC
   : '\' ( ["\/bfnrt]  )
   ;

fragment HEX
   : [0-9a-fA-F]
   ;

WS
   : [ \t\n\r]+ -> skip
   ;

它不起作用,因为令牌 'true' 匹配词法分析器规则标识符:

[@0,0:2='foo',<Identifier>,1:0]
[@1,4:4='=',<'='>,1:4]
[@2,6:9='true',<Identifier>,1:6] <== lexed as an Identifier!
[@3,14:13='<EOF>',<EOF>,3:0]
line 1:6 mismatched input 'true' expecting {'null', STRING, BOOLEAN, NUMBER}

将您对标识符的定义向下移动到词法分析器规则中,它起作用了:

NUMBER
   : '-'? INT '.' [0-9]+| '-'? INT | '-'? INT
   ;

Identifier : [_A-Za-z] [_0-9A-Za-z]* ;

记住顶部的东西胜过底部的东西。在像您这样的组合语法中,不要将词法分析器规则(以大写字母开头)与解析器规则(以小写字母开头)穿插。