如何使ANTLR消耗所有可见元素? [英] How to make ANTLR consume all visible elements?

查看:69
本文介绍了如何使ANTLR消耗所有可见元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的语法:

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个项目列表的原因是 foo tail 之间的相互递归消耗了所有项目,因此没有重复的余地消费.

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

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