How to force an auto-generated parser class to implement an interface in ANTLR4?

I use ANTLR 4 to create a parser, and I finished my grammar. I need to enter some Java code in the resulting parser file, which ANTLR automatically generates for me.

If I want to include a method in the resulting parser, I can add this to the ANTLR grammar:

@parser::members
{
  @Override
  public CGrammarParser.CSnippetContext call()
  {
    return cSnippet();
  }
}

If I want to include some import statements, I can add this to the grammar:

@header
{
  import java.lang.Thread;
  import java.lang.InterruptedException;
  import java.util.concurrent.Callable;
}

If I want to change the class declaration so that it implements the interface , how can I do this? In other words, this is what ANTLR automatically generates:

public class CGrammarParser extends Parser 
{
  ...
}

But this is what I want it to generate:

public class CGrammarParser extends Parser implements Callable<CGrammarParser.CSnippetContext> 
{
  ...
}
+4
source share
2 answers

.

ANTLR- , (.g4) Java. :

1) , ANTLR , :

public class CallableParser extends CGrammarParser implements Callable<CGrammarParser.CSnippetContext>
{
    public CallableParser(TokenStream input)
    {
        super(input);
    }

    @Override
    public CGrammarParser.CSnippetContext call()
    {
        return cSnippet();
    }
}

2) ANTLR CallableParser, :

CharStream in = new ANTLRInputStream(input);
CGrammarLexer lexer = new CGrammarLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Instead of doing this...
// CGrammarParser parser = new CGrammarParser(tokens);
// Do this...
CallableParser parser = new CallableParser(tokens);
0

, , ( ()). , , . , , ANTLR Parser. () , .

:

CallableParser

import java.util.concurrent.Callable;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.TokenStream;

public abstract class CallableParser extends Parser implements Callable<CGrammarParser.CSnippetContext>
{
    public CallableParser(TokenStream input)
    {
        super(input);
    }
}

CGrammar.g4

grammar CGrammar;

options
{
  superClass = CallableParser;
}

@header
{
  import java.lang.Thread;
  import java.lang.InterruptedException;
  import java.util.concurrent.Callable;
}

@parser::members
{
  @Override
  public CGrammarParser.CSnippetContext call()
  {
    return cSnippet();
  }
}

cSnippet
 : ANY*? EOF
 ;

ANY
 : .
 ;
+2

Source: https://habr.com/ru/post/1623441/


All Articles