[antlr-interest] problem with nested composite grammars

Scott Warren scott at rice.edu
Mon Oct 4 11:30:59 PDT 2010

(Again, sorry if you've seen this -- I think maybe some people have missed this.)


I'm working on a large open-source grammar and I've hit a problem with nested composite grammars. In short, "single inheritance" rule overriding in nested composite grammars does not work like inheritance in Java. I think this is a bug. It does not depend on the grammars being large.

Here's a brief example. Three grammars G1, G2, and G3 are "nested" in the sense that G3 imports G2 and G2 imports G1. A rule is defined in G1 and then overridden in G2. When G3 imports G2 I expect it to get the version of the rule defined in G2. In fact, ANTLR uses the rule from G1. (More precisely, G3Parser.java delegates the rule to G3_G2_G1.java rather than to G3_G2.java.) The example grammars and associated lexer are:

lexer grammar L;
T1: '1';
T2: '2';
T3: '3';
T4: '4';
parser grammar G1;
s: a | b;
a: T1;
b: T2;
parser grammar G2;
import G1;
a: T3;
grammar G3;
import G2;
b: T4;

Using ANTLRWorks 1.4 containing ANTLR 3.2, when I generate these grammars and examine the file "G3Parser.java", I see the following lines of code for delegating methods:

  // Delegated rules
  public void s() throws RecognitionException { gG1.s(); }
  public void a() throws RecognitionException { gG1.a(); }

I think the last of these lines should say "gG2.a()"! The generated Java source will not compile.

Scott Warren

More information about the antlr-interest mailing list