sve
sve

Reputation: 4356

Antlr: Unintended behavior

Why this simple grammar

grammar Test;

expr
    :    Int | expr '+' expr;

Int
:    [0-9]+;

doesn't match the input 1+1 ? It says "No method for rule expr or it has arguments" but in my opition it should be matched.

Upvotes: 3

Views: 1013

Answers (2)

JustBeingHelpful
JustBeingHelpful

Reputation: 18990

If your command looks like this:

grun MYGRAMMAR xxx -tokens

And this exception is thrown:

No method for rule xxx or it has arguments

Then this exception will get thrown with the rule you specified in the command above. It means the rule probably doesn't exist.

System.err.println("No method for rule "+startRuleName+" or it has arguments");

So startRuleName here, should print xxx if it's not the first (start) rule in the grammar. Put xxx as the first rule in your grammar to prevent this.

Upvotes: 1

DaoWen
DaoWen

Reputation: 33029

It looks like I haven't used ANTLR for a while... ANTLRv3 did not support left-recursive rules, but ANTLRv4 does support immediate left recursion. It also supports the regex-like character class syntax you used in your post. I tested this version and it works in ANTLRWorks2 (running on ANTLR4):

grammar Test;

start : expr
      ;
expr  : expr '+' expr
      | INT
      ;
INT   : [0-9]+
      ;

If you add the start rule then ANTLR is able to infer that EOF goes at the end of that rule. It doesn't seem to be able to infer EOF for more complex rules like expr and expr2 since they're recursive...


There are a lot of comments below, so here is (co-author of ANTLR4) Sam Harwell's response (emphasis added):

You still want to include an explicit EOF in the start rule. The problem the OP faced with using expr directly is ANTLR 4 internally rewrote it to be expr[int _p] (it does so for all left recursive rules), and the included TestRig is not able to directly execute rules with parameters. Adding a start rule resolves the problem because TestRig is able to execute that rule. :)

I've posted a follow-up question with regard to EOF: When is EOF needed in ANTLR 4?

Upvotes: 3

Related Questions