Is it possible to make Antlr4 generate lexer from

2019-08-29 12:15发布

问题:

I have lexer grammar called BasicTokens which is set of basic tokens for my language, having tokens like null, true, false etc.

Now when I create parser grammar say BasicGrammar which imports refers BasicTokens and another grammar called InheritedGrammar which imports BasicGrammar.

When Antlr4 generates the parser for InheritedGrammar it included all the rules already defined in BasicGrammar.

Is there a way to make Antlr describe only the rules generated in InheritedGrammar and not in BasicGrammar and also inherit BasicGrammarParser instead of Parser?

回答1:

This is not possible due to the way ANTLR 4 implements imports.

If grammar x imports grammar y, the operation behaves as follows:

  1. Load grammar y (and all its rules).
  2. Add the rules from grammar x to the collection of rules. If any name collision occurs, replace the rule found in y with the one found in x.

By the time you reach the code generator, the rules hierarchy is completely flattened.