我怎么告诉ANTLR更喜欢一种替代方案?

时间:2017-06-13 21:01:34

标签: java parsing antlr grammar antlr4

我有以下作品:

expression
    :   primary # stubLabel
    |   expression '.' Identifier # stubLabel
    |   expression '.' 'this' # stubLabel
    |   expression '.' 'new' nonWildcardTypeArguments? innerCreator # stubLabel
    |   expression '.' 'super' superSuffix # stubLabel
    |   expression '.' explicitGenericInvocation # stubLabel
    |   expression '[' expression ']' # stubLabel
    |   Identifier arguments # namedMethodInvocation
    |   expression '.' Identifier arguments # namedMethodInvocation
    |   expression arguments # unnamedMethodInvocation
    |   // Lots of other patterns...
    ;

我希望解析器首先尝试namedMethodInvocation模式,然后再尝试unnamedMethodInvocation。这不会自动发生,因为ANTLR尝试选择具有最长匹配的替代方案,而不是使用第一个匹配策略。我怎么强迫它这样做?

编辑抱歉,我忽略了将链接发布到上面的语法文件中。 Here它是。

1 个答案:

答案 0 :(得分:0)

尝试将namedMethodInvocation移至primary制作规则(Identifier之前),如下所示。

primary
    :   '(' expression ')'
    |   'this'
    |   'super'
    |   literal
    |   Identifier arguments // namedMethodInvocation
    |   Identifier
    |   typeType '.' 'class'
    |   'void' '.' 'class'
    |   nonWildcardTypeArguments (explicitGenericInvocationSuffix | 'this' arguments)
    ;

或将primary移至expression中的最后一个。

expression
    : expression '.' Identifier
    .....
    | Identifier arguments  // namedMethodInvocation
    | expression arguments  // unnamedMethodInvocation
    .....
    | primary
    ;

或插入新规则primaryOrNamedMethodInvocation

expression
    : primaryOrNamedMethodInvocation
    | expression '.' Identifier
    .....
    ;

primaryOrNamedMethodInvocation
    : Identifier arguments  // namedMethodInvocation
    | primary
    ;