ANTLR:空状态不起作用 [英] ANTLR: empty condition not working

查看:37
本文介绍了ANTLR:空状态不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够解析 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] warning(200): MiniJava.g:5:9: Decision can match input例如 "" 使用多个替代: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')+;

每当您开始组合不同类型的字符以创建(单个)标记时,通常最好为此创建解析器规则.将词法分析器规则(标记)视为语言的最小构建块.从这些构建块中,您组成解析器规则.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆