模棱两可的 ANTLR 解析器规则 [英] Ambiguous ANTLR parser rule

查看:28
本文介绍了模棱两可的 ANTLR 解析器规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的示例文本,我想用 ANTLR 解析它,但由于规则的定义不明确,我得到了错误的结果.

I have a very simple example text which I want to parse with ANTLR, and yet I'm getting wrong results due to ambiguous definition of the rule.

语法如下:

grammar SimpleExampleGrammar;

prog : event EOF;

event : DEFINE EVT_HEADER eventName=eventNameRule;

eventNameRule : DIGIT+;

DEFINE : '#define';

EVT_HEADER : 'EVT_';

DIGIT                   :           [0-9a-zA-Z_];

WS     :   ('' | ' ' | '\r' | '\n' | '\t') -> channel(HIDDEN);

第一个文本示例:

#define EVT_EX1

第二个文本示例:

#define EVT_EX1
#define EVT_EX2

所以,第一个例子被正确解析.

So, the first example is parsed correctly.

然而,第二个例子不起作用,因为 eventNameRule 匹配下一个#define ..."并且解析树不正确

However, the second example doesn't work, as the eventNameRule matches the next "#define ..." and the parse tree is incorrect

感谢任何更改语法以正确解析它的帮助.

Appreciate any help to change the grammar to parse this correctly.

谢谢,商务

推荐答案

除了缺少循环说明符之外,您的 WS 规则还存在问题.第一个 alt 匹配任何内容.去掉那个.而且,顺便说一句,给你的 DIGIT 规则一个不同的名字.它匹配的不仅仅是数字.

Beside the missing loop specifier you also have a problem in your WS rule. The first alt matches anything. Remove that. And, btw, give your DIGIT rule a different name. It matches more than just digits.

这篇关于模棱两可的 ANTLR 解析器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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