在 ANTLR4 中使用什么来解决歧义(而不是句法谓词)? [英] What to use in ANTLR4 to resolve ambiguities (instead of syntactic predicates)?

查看:28
本文介绍了在 ANTLR4 中使用什么来解决歧义(而不是句法谓词)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ANTLR v3 中,句法谓词可用于解决例如悬空 else 问题.ANTLR4 似乎接受具有相似歧义的语法,但在解析过程中它会报告这些歧义(例如,第 2:29 行 reportAmbiguity d=0 (e): ambigAlts={1, 2}, input=...").尽管存在这些歧义,它还是生成了一个解析树(根据文档,通过选择第一个选项).但是,如果我想让它选择其他替代方案,我该怎么办?换句话说,我怎样才能明确地解决歧义?

In ANTLR v3, syntactic predicates could be used to solve e.g., the dangling else problem. ANTLR4 seems to accept grammars with similar ambiguities, but during parsing it reports these ambiguities (e.g., "line 2:29 reportAmbiguity d=0 (e): ambigAlts={1, 2}, input=..."). It produces a parse tree, despite these ambiguities (by chosing the first alternative, according to the documentation). But what can I do, if I want it to chose some other alternative? In other words, how can I explicitly resolve ambiguities?

例如,悬空 else 问题:

For example, the dangling else problem:

prog
    :   e EOF
    ;

e
    :   'if' e 'then' e ('else' e)?
    |   INT
    ;

使用这个语法,从输入if 1 then if 2 then 3 else 4",它构建这个解析树: (prog (e if (e 1) then (e if (e 2) then (e 3)否则 (e 4))) ).

With this grammar, from the input "if 1 then if 2 then 3 else 4", it builds this parse tree: (prog (e if (e 1) then (e if (e 2) then (e 3) else (e 4))) ).

如果出于某种原因,我想要另一棵树,我该怎么办: (prog (e if (e 1) then (e if (e 2) then (e 3)) else (e 4)) ) ?

What can I do, if for some reason, I want the other tree: (prog (e if (e 1) then (e if (e 2) then (e 3)) else (e 4)) ) ?

有关更复杂的示例,请参阅 在 ANTLR4 中使用什么来解决更复杂情况下的歧义(而不是句法谓词)?)

for a more complex example, see What to use in ANTLR4 to resolve ambiguities in more complex cases (instead of syntactic predicates)?)

推荐答案

  • 在这种情况下,您可以使用语义谓词明确禁止替代方案.

    • You can explicitly disallow an alternative in this type of situation by using a semantic predicate.

      ('else' e | {_input.LA(1) != ELSE}?)
      

    • 您应该能够使用 ?? 运算符而不是 ? 来更喜欢将 else 与最外面的 相关联>如果.但是,性能会受到很大影响.另一种选择是将匹配的 if/else 对与不匹配的 if 区分开来.

    • You should be able to use the ?? operator instead of ? to prefer associating the else with the outermost if. However, performance will suffer substantially. Another option is distinguishing matched if/else pairs separately from an unmatched if.

      ifStatement
        : 'if' expression 'then' (statement | block) 'else' (statement | block)
        | 'if' expression 'then' (statementNoIf | block)
        ;
      

    • 这篇关于在 ANTLR4 中使用什么来解决歧义(而不是句法谓词)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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