Home » Java » java – Is it possible to include (but not importing) a stand-alone grammar in ANTLR4?-Exceptionshub

java – Is it possible to include (but not importing) a stand-alone grammar in ANTLR4?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a grammar which describes expressions (original, right?). I want to use this Expressions language inside of other languages.

For example, OtherLanguage.g4:

grammar OtherLanguage.g4

import Expressions;

keyPair: IDENTIFIER ':' expression;
IDENTIFIER: [a-zA-Z0-9]+ 

If I use import Expressions;, then it generates a valid parser, but it doesn’t generate or use ExpressionsParser.ExpressionContext, but instead generates and uses OtherLanguageParser.ExpressionContext. This means I can’t create methods that take in “ExpressionContext” and reuse them in other projects.

Is there a feature of ANTLR4 that will make this work?

In other words, I don’t want to “import” the Expressions grammar, but the parser and lexer.

How to&Answers:

Yeah, import really means include—it is not treating the imported grammar as a separate entity for which you can use all of those parts tree objects.