0
votes

I'm trying to match something that has the same beginning but different thing in the end as for example:

'+' something+

'+' | '-' | '/' | '*' something something somethingDifferentAtTheEnd

and my code for the following is:

something: // rule for something here
rule1: '+' something+
rule2: OPERATOR something something somethingDifferentAtTheEnd
ruleForSomethingDifferent: // goes here

OPERATOR: '+' | '-' | '/' | '*'

The problem is I can't get this to work, I always seem to get 'extraneous input' error when I pass rule2 that starts with a '+' (its trying to match the first one and fails because there's a 'somethingDifferentAtTheEnd' but it doesnt fall to the 2nd rule..

1

1 Answers

1
votes

The lexer will consume all of the '+' characters before they get to the parser, so rule1 is going to confuse Antlr - likely there is an error or warning when on generation of the parser/lexer and likely why the run-time error messages do not seem to make much sense. Should correct all generation errors and warnings before proceeding.

In matching rules, the rule matching the longest sequence of tokens is always selected first.

This is likely what you were intending:

rule1    : Plus a+ ;
rule2    : operator a a b ;
a        : .... ;
b        : .... ;
operator : Plus | Minus | Div | Star ;

Plus : '+' ;
Minus: '-' ;
Div  : '/' ;
Star : '*' ;