[antlr-interest] if/else if/else vs. if/elif/else

shmuel siegel antlr at shmuelhome.mine.nu
Thu Sep 2 10:34:40 PDT 2010


  Answering to the list after I accidentally answered off-line
On 9/2/2010 8:01 PM, Serghei A wrote:
> Hi,
>
> I tried your suggestion - created tokens for IF and ELSE:
>
> ifExpr    :    IF LRND ifCond=rightExpr RRND ifBlock=block
>             (ELSE IF LRND elifCond+=rightExpr RRND elifBlock+=block)*
>             (ELSE elseBlock=block)?
>             ->    ^(ASTFuncNode<ASTFuncNode>["ASTFuncNode", "if", 
> createIfCommand($ifCond.tree, $ifBlock.tree, $elifCond, $elifBlock, 
> $elseBlock.tree)])
>         ;
>
> however this throws the following error:
>
> the following token definitions can never be matched because prior 
> tokens match the same input IF, ELSE...
>
> Does it mean I'm practically stuck with using "elif" for "else if" 
> clause?
>
> Thanks for your help.
>
No, it means that you lexer grammar is not what you think it is. Try to 
explicitly define all of the tokens for your lexer. Don't use any quoted 
strings in the parser.
>
> On Thu, Sep 2, 2010 at 12:55 PM, shmuel siegel 
> <antlr at shmuelhome.mine.nu <mailto:antlr at shmuelhome.mine.nu>> wrote:
>
>      On 9/2/2010 7:45 PM, st3 wrote:
>
>         Hi,
>
>         I have defined a simple if/else if/else rule (below):
>
>         ifExpr  :       'if' LRND ifCond=rightExpr RRND ifBlock=block
>                        ('else if' LRND elifCond+=rightExpr RRND
>         elifBlock+=block)*
>                        ('else' elseBlock=block)?
>
>         this throws the following error:
>
>         mismatched character '{' expecting 'i'
>         extraneous input '}' expecting 'return '
>
>         I can solve it by changing 'else if' to 'elif' - as clearly
>         'else if' and
>         'else' are confusing the lexer/parser.
>
>         However, I was hoping to have the easer-to-read 'else if'.
>
>         Can someone suggest how I can accomplish that?
>
>         I tried the syntactic predicate ('else if')=>  - but that did
>         not work.
>
>         Thank you!
>
>     To start with, this reads like you are trying to distinguish
>     "else" from "else if" in the lexer. Probably a mistake. You then
>     try to correct it with a parser rule. This will never work.
>     Mismatched char is a lexer error. When the lexer sees the space
>     character it tries to match the longer token and then fails.
>     Make else and if separate tokens.
>
>




More information about the antlr-interest mailing list