3

I use ANTLR 2.7 to create a grammar to parse simple expressions like

1
2%
(3%)
(4)
((5))
((6%))

It's simple numbers which can have paranthesis and optional percent characters

My grammar looks like this:

class MyParser extends Parser;
options {
  k=2;
  buildAST = true;
}

parexpr
  : variable
  | LPAREN^ parexpr RPAREN!
  ;

variable
  : (NUMBER PCT) => NUMBER PCT^
  | NUMBER
  ;

class MyLexer extends Lexer;
options {
  k=6;
}
LPAREN:  '(';
RPAREN:  ')';
DOT: '.';
PCT: '%';
protected
DIGIT:  '0'..'9';
NUMBER: (DIGIT)+ (DOT (DIGIT)+)*;

I can successfully parse e.g.

(1)
(2%)

But it fails to parse a single number:

1

If I remove either | LPAREN^ parexpr RPAREN! or : (NUMBER PCT) => NUMBER PCT^ then I can parse a single number (but obviously not the other expressions).

I do not understand why I cannot parse a single number with this grammar..?

Note that I am working on a project that was implemented with this version a long time ago, and I'm just extending the existing things.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
JayTheKay
  • 1,463
  • 12
  • 22
  • Because I am working on a project that was implemented with this version a long time ago, and I'm just extending the existing things. Afaik ANTLR is not backwards compatible :-( – JayTheKay Dec 15 '15 at 14:18
  • 1
    That's a sound reason. I just wanted to double check you're not accidentally starting something new with this older version. – Bart Kiers Dec 15 '15 at 14:23

0 Answers0