What to use in ANTLR4 to resolve ambiguities (instead of syntactic predicates)?

放肆的年华 提交于 2019-12-01 08:10:55

问题


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?

For example, the dangling else problem:

prog
    :   e EOF
    ;

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

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))) ).

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)) ) ?

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


回答1:


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

    ('else' e | {_input.LA(1) != ELSE}?)
    
  • 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)
      ;
    


来源:https://stackoverflow.com/questions/21415917/what-to-use-in-antlr4-to-resolve-ambiguities-instead-of-syntactic-predicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!