I’m in the process of creating a Java analyzer for an ANTLR grammar that someone else is writing.
Is it possible to combine ANTLR files so that I can add my bracketed Java code to the ANTLR-generated Java files through a file separate from the original grammar (.g) file? I’ve investigated composite grammars, but it doesn’t seem as though I can import the existing grammar as a combined lexer/parser.
For instance, can I do something like this:
Grammar.g
grammar Grammar;
statement : first=WORD ';' ;
WORD : ('A'..'z')* ;
JavaGrammar.g
grammar JavaGrammar;
imports Grammar;
@header {
package pkg;
import Container;
}
@lexer::header {
package pkg;
}
@members{
Container c = null;
public void setContainer(Container c) { this.c = c; }
@Override
protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException {
throw new MismatchedTokenException(ttype, input);
}
@Override
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
throw e;
}
}
@rulecatch {
catch (RecognitionException e) {
throw e;
}
}
jStatement: statement { if(c!=null) c.add($first.text); } ;
You can’t import (it’s
import, btw, notimports) a combined grammar. See the ANTLR Wiki:And you can’t use a label (the
firstin yourstatementrule) outside of the rule it exists in.What you can do is this:
file: L.g
file: P.g
file: JavaGrammar.g
Run the class with the main method:
and you’ll see the following being printed to the console: