如何让 ANTLR 消耗所有可见元素? [英] How to make ANTLR consume all visible elements?
问题描述
这是我的语法:
grammar test;
text: foo EOF;
foo:
'X'
|
foo
'!'
|
foo
'?'
|
foo
tail
;
tail: (' ' foo)+;
我正在解析这段文字:
X? X! X X
这是我得到的树:
语法中应该有什么变化,以便我只得到一个 tail
元素,其中包含所有 foo
元素的集合?
What should change in the grammar so that I get only one tail
element with a collection of all foo
elements inside?
在现实世界中,任务要复杂得多,仅使用扫描仪无法解决问题.
In the real world the task is way more complex, and using only a scanner is no solution to it.
推荐答案
据我所知,你想要的是:
As far as I can tell, what you want is this:
item: 'X' ('!' | '?')*;
// Alternatively to get a tree per operator instead of a list of operators:
// item
// : 'X'
// | item '!'
// | item '?'
// ;
foo: item (' ' item)*;
也许是这样,如果您希望尾部仍然在树中拥有自己的节点:
Maybe this, if you want the tail still to have its own node in the tree:
item: 'X' ('!' | '?')*;
foo: item tail;
tail: (' ' item)*;
你的版本只给你 1-item 列表的原因是 foo
和 tail
之间的相互递归消耗了所有的 item,所以没有什么可重复的了消费.
The reason that your version only gave you 1-item lists is that the mutual recursion between foo
and tail
consumed all the items, so there's nothing left for the repetition to consume.
一般来说,当你有一些可以重复的东西时,你要么想使用 *
/+
来实现它(如果你想要结果树中的列表)或者使用递归(如果你想要一个更像树的树)——不能同时使用.
Generally when you have something that can be repeated, you either want to implement this using *
/+
(if you want lists in the resulting tree) or using recursion (if you want a more tree-like tree) - not both.
这篇关于如何让 ANTLR 消耗所有可见元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!