ANTLR 输入不匹配 [英] ANTLR mismatched input

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

问题描述

我有一个像这样的简单语法:

I have a simple grammar like this:

grammar mygrammar;

the_rule : 'abc' 'xyz' ;

WS  :  [ \t\r\n\u000C]+ -> channel(HIDDEN) ;

当我用 the_rule() 解析文本abc xyz"时,我得到了预期的字符串树表示:

When I parse the text "abc xyz" with the_rule(), I get the expected string tree representation:

(the_rule abc xyz)

但是,然后我添加了以下词法分析器规则,我认为这意味着除了 w 之外的任何东西":

However, then I add the following lexer rule, which I think means "anything except for a w":

TEXT : ~[w]+ ;

现在,当我使用 the_rule() 解析文本abc xyz"时,出现错误:

Now when I parse the text "abc xyz" with the_rule(), I get an error:

line 1:0 mismatched input 'abc xyz' expecting 'abc'

为什么 TEXT 词法分析器规则会影响这个?我想我误解了一些简单的事情.:-(

Why would the TEXT lexer rule affect this? I think I'm misunderstanding something simple. :-(

推荐答案

ANTLR 词法分析器规则是贪婪的:匹配最多的规则获胜.因此,在您的情况下,整个输入 abc xyzTEXT 匹配.如果您的解析器尝试匹配 abc 并不重要,词法分析器独立于解析器运行.

ANTLR lexer rules are greedy: the rule that matches the most wins. So, in your case, the entire input, abc xyz, is matched by TEXT. It doesn't matter if your parser is trying to match abc, the lexer operates independently from the parser.

这篇关于ANTLR 输入不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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