Sahil
Sahil

Reputation: 9478

Incorrect Parsing of simple arithmetic grammar in ANTLR

I recently started studying ANTLR. Below is the grammar for the arithmetic expression. The problem is that when I am putting (calling) expression rule in the term rule then it is parsing incorrectly even for (9+8). It is somehow ignoring the right parenthesis.

While when I put add rule instead of calling expression rule from the rule term, it is working fine.

As in:

term:
INTEGER
| '(' add ')'
;

Can anyone tell me why it is happening because more or les they both are the same.

Grammer for which it is giving incorrect results

term
  :
  INTEGER
  | '(' expression ')'
  ;

mult
  :
  term ('*' term)*
  ;

add
  :
  mult ('+' mult)*
  ;

expression
  :
  add
  ;

Upvotes: 1

Views: 375

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170227

When I parse "(8+9)" with a parser generated from your grammar, starting with the expression rule, I get the following parse tree:

enter image description here

In other words: it works just fine.

Perhaps you're using ANTLRWorks' (or ANTLR IDE's) interpreter to test your grammar? In thta case: don't use the interpreter, it's buggy. Use ANTLRWorks' debugger instead (the image is exported from ANTLRWorks' debugger).

Upvotes: 2

Related Questions