Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

parsing - Ambiguous call expression in ANTLR4 grammar

I have a simple grammar (for demonstration)

grammar Test;


program
    :   expression* EOF
    ;


expression
    :   Identifier
    |   expression '(' expression? ')'
    |   '(' expression ')'
    ;


Identifier
    :   [a-zA-Z_] [a-zA-Z_0-9?]*
    ;

WS
    :   [ 
]+ -> channel(HIDDEN)
    ;

Obviously the second and third alternatives in the expression rule are ambiguous. I want to resolve this ambiguity by permitting the second alternative only if an expression is immediately followed by a '('.

So the following

bar(foo)

should match the second alternative while

bar
(foo)

should match the 1st and 3rd alternatives (even if the token between them is in the HIDDEN channel).

How can I do that? I have seen these ambiguities, between call expressions and parenthesized expressions, present in languages that have no (or have optional) expression terminator tokens (or rules) - example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution to this is to temporary "unhide" whitespace in your second alternative. Have a look at this question for how this can be done.

With that solution your code could look somthing like this

expression
    :   Identifier
    |   {enableWS();} expression '(' {disableWS();} expression? ')'
    |   '(' expression ')'
    ;

That way the second alternative matches the input WS-sensitive and will therefore only be matched if the identifier is directly followed by the bracket.

See here for the implementation of the MultiChannelTokenStream that is mentioned in the linked question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...