Tiso AP
Tiso AP

Reputation: 61

Running ANTRL TestRig GUI from within a Java application

I know it's possible to generate a graphical representation of a parse tree using ANTLR's TestRig "grun" through the terminal:

$ alias grun='java org.antlr.v4.runtime.misc.TestRig'​​
$ grun Example test -gui
hello world
​​​​E​O​F​​​​

But is it possible to call the TestRig from within a Java application? I want to make use of the TestRig capabilities to make a Java application that takes the user input and shows the generated parse tree graphical representation.

I already tried the following:

import org.antlr.v4.runtime.misc.TestRig;
...
TestRig test = new TestRig(args);
test.process();

But I got this message:

Can't load Example as lexer or parser

It looks it should work, because it correctly identified the arguments Example test -gui I set on Eclipse, but the TestRig does not seem to be able to find the grammar.

How do I set up the arguments properly? And if that's not possible, is there any other way of running ANTLR's TestRig inside a Java application?

Upvotes: 0

Views: 2139

Answers (2)

Gryffe
Gryffe

Reputation: 411

This snippet works for me (antlr-4.5.3-complete.jar):

void showGuiTreeView(final String code)
{
    final org.antlr.v4.runtime.CharStream stream = new ANTLRInputStream(code);
    final MyLexer lexer = new MyLexer(stream);
    final CommonTokenStream tokens = new CommonTokenStream(lexer);
    final MyParser parser = new MyParser(tokens);
    final ParseTree tree = parser.expr();
    final List<String> ruleNames = Arrays.asList(MyParser.ruleNames);
    final TreeViewer view = new TreeViewer(ruleNames, tree);
    view.open();
}

Upvotes: 1

Tiso AP
Tiso AP

Reputation: 61

OK I've solved my issue. By looking at the source code of the TestRig class, I've found that I just needed to use the inspect() method to generate the GUI view. Here's an example code:

// Create an input stream that receives text from the terminal
ANTLRInputStream input = new ANTLRInputStream(System.in);

// Create an Lexer that receives the char stream
ExampleLexer lexer = new ExampleLexer(input);

// Create a token stream from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);

// Create a parser that receives the token stream
ExampleParser parser = new ExampleParser(tokens);

// Create a parser tree starting from the first rule
TestContext tree = parser.test();

//Generates the GUI
tree.inspect(parser);

EDIT: As for version 4.5.1, the code that generates the tree changes to this:

//Generates the GUI
Trees.inspect(tree, parser);

Upvotes: 4

Related Questions