How to include a grammar into another in ANTLR?

Hello, I need help on the following problem.
Let’s suppose we have a general purpose language, call it L0, described by a grammar in ANTLR.
I want to build a domain specific language, call it L1, with its specific features, but that exploits some features of L0, for instance its type system.
What is the best way to do it? I was thinking to create an L1Visitor class that derives from L0Visitor class… is it safe? any idea?
Thanks in advance

There are a couple of options to do that, depending on what you need.

If what you need is in the L0 grammar itself, you can import the L0 grammar from the L1 grammar, rather than creating a derived visitor.

Example with baseLines (L0) and derivedLines (L1) languages.

baseLines.g4 (L0)

grammar baseLines;

@members {
    public String superText = "superText"; // example code in Java, but it applies to all targets
}

line: WORD NEWLINE;

WORD: [a-zA-Z]+ ;

NEWLINE: [\r\n]+ ;

derivedLines.g4 (L1)

grammar derivedLines;

import baseLines;

// import grammar rule and method from baseLines
multiline: line+ { System.out.println(superText); } ;

Instead if your type system is pure code (no shared grammers rules), it may be easier to create a shared base class and use it both in the L0 and L1 grammar.

LinesBase.Java

import org.antlr.v4.runtime.*;

// Parser is the ANTLR parser class
public abstract class LinesBase extends Parser
{    
    public LinesBase(TokenStream input) {
        super(input);
    }
    
    protected boolean HasZero(String text)
    {
        return text.contains("0");
    }
}

derivedLines.g4 (L1)

grammar derivedLines;

options {
    superClass=LinesBase;
}

// use method from super class
multiline: line+ { System.out.println(this.HasZero($ctx.getText())); } ;

line: WORD NEWLINE;

WORD: [a-zA-Z]+ ;

NEWLINE: [\r\n]+ ;

Let me know, if this helps.

Thanks! Very helpful

1 Like