ANTLR:空状态不起作用 [英] ANTLR: empty condition not working
问题描述
我希望能够解析 int [] 或 int 标记.
I want to be able to parse int [] or int tokens.
请考虑以下语法:
TYPE : 'int' AFTERINT;
AFTERINT: '[' ']';
当然可以,但是仅适用于 int [] .为了使其也适用于 int ,我将AFTERINT
更改为此(添加了一个空条件':
Of course it works, but only for int []. To make it work for int too, I changed AFTERINT
to this (added an empty condition':
AFTERINT: '[' ']' |
|;
但是现在我得到了这个警告和错误:
But now I get this warning and error:
[13:34:08]警告(200):MiniJava.g:5:9:决策可以匹配输入 例如"使用多种替代方式:2,3
[13:34:08] warning(200): MiniJava.g:5:9: Decision can match input such as "" using multiple alternatives: 2, 3
结果,该输入的替代项3被禁用[13:34:08] 错误(201):MiniJava.g:5:9:永远不可能有以下替代方案 匹配:3
As a result, alternative(s) 3 were disabled for that input [13:34:08] error(201): MiniJava.g:5:9: The following alternatives can never be matched: 3
为什么空条件不起作用?
Why won't empty condition work?
推荐答案
词法分析器无法处理与空字符串匹配的标记.如果您考虑片刻,这并不奇怪:毕竟,您的输入中有无数的空字符串.该词法分析器始终会生成一个空字符串作为有效令牌,从而导致无限循环.
The lexer cannot cope with tokens that match empty string. If you think about it for a moment, this is not surprising: after all, there are an infinite amount of empty strings in your input. The lexer would always produce an empty string as a valid token, resulting in an infinite loop.
类型识别不属于词法分析器,而是属于解析器:
The recognition of types does not belong in the lexer, but in the parser:
type
: (INT | DOUBLE | BOOLEAN | ID) (OBR CBR)?
;
OBR : '[';
CBR : ']';
INT : 'int';
DOUBLE : 'double';
BOOLEAN : 'boolean';
ID : ('a'..'z' | 'A'..'Z')+;
每当您开始组合不同的 type 字符以创建(单个)令牌时,通常最好为此创建一个解析器规则.将词法分析器规则(标记)视为语言的最小组成部分.从这些构建块中,您组成解析器规则.
Whenever you start combining different type of characters to create a (single) token, it's usually better to create a parser rule for this. Think of lexer rules (tokens) as the smallest building block of your language. From these building blocks, you compose parser rules.
这篇关于ANTLR:空状态不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!