Antonello
Antonello

Reputation: 1376

Override Single Rule in ANTLR4 Grammar

I've developed a SQL-2003 ANTLR4 grammar for the project DeveelDB: this defines the main SQL statements for its basic features.

Anyway, we're also developing a set of external libraries to extend the features of the database: for example a XML module that will support the analysis of XML data of a column or a Open-GIS SFS module to support spatial operations.

Given the architecture of the system, it's easy to do all the operations using system functions, that are registered at system build time, and the SQL parser can work with it smoothly.

My question is about the possibility to define a new ANTLR4 grammar that inherits from the existing SQL grammar in the main project and redefine single rules, to include feature-specific commands, rather than defining them in the main grammar, or worse copy and paste the .g4 grammar into the module project and redefine the rules directly there.

Thanks for suggestions!

Upvotes: 1

Views: 924

Answers (1)

cantSleepNow
cantSleepNow

Reputation: 10202

Kind of "inheritance" is possible. Just look up the keyword "import". Example from the antlr4 book : "parent grammar"

grammar ELang;
stat : (expr ';')+ ;
expr : INT ;
WS : [ \r\t\n]+ -> skip ;
ID : [a-z]+ ;

"child" grammar

grammar MyELan
import ELang;
expr : INT | ID ;
INT : [0-9]+

what actually happens is

grammar MyELang;
stat : (expr ';')+ ;
expr : INT | ID ;
INT : [0-9]+
WS : [ \r\t\n]+ -> skip ;
ID : [a-z]+ ;

and a quote from the same book MyELang inherits rules stat, WS, and ID, but it overrides rule expr and adds INT.

The rest you can look in the book under section 15.2 Grammar structure, subtitle Grammar imports.

Upvotes: 2

Related Questions