在ANTLR4中使用什么来解决歧义(而不是句法谓词)? [英] What to use in ANTLR4 to resolve ambiguities (instead of syntactic predicates)?
问题描述
在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
;
使用此语法,从输入如果1则2则3否则3否则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))) ).
如果由于某种原因我想要另一棵树,我该怎么办:(编(e如果(e 1)然后(e如果(e 2)然后(e 3))否则(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)) ) ?
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
关联.但是,性能将受到很大影响.另一种选择是将匹配的if
/else
对与未匹配的if
分开. You should be able to use the
??
operator instead of?
to prefer associating theelse
with the outermostif
. However, performance will suffer substantially. Another option is distinguishing matchedif
/else
pairs separately from an unmatchedif
.ifStatement : 'if' expression 'then' (statement | block) 'else' (statement | block) | 'if' expression 'then' (statementNoIf | block) ;
这篇关于在ANTLR4中使用什么来解决歧义(而不是句法谓词)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!