Table of Contents

Antlr - Parse Tree (AST)

About

The tree parser is an AST that is created by the parser from a text input.

Management

Print

Grun

with grun, see the -tree of -gui option of

Example:

grun grammar startRule -tree
grun grammar startRule -gui

Type your text and end with a End of File character (Ctrl+Z or Ctrl+D)

Idea

With the idea plugin:

Antlr Idea Plugin

Java

Build

Example from the getting started with an Hello.g4 grammar file that was generated in:

The grammar below will parse every hello [a-z]+ text.

grammar Hello;
r  : 'hello' ID ;   // Top parser rule of the tree
ID : [a-z]+ ;      
WS : [ \t\r\n]+ -> skip ;

To build a tree, you need to:

ANTLRInputStream input = new ANTLRInputStream("hello nico");
HelloLexer lexer = new HelloLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokens);
ParseTree tree = parser.r();    
System.out.println(tree.toStringTree(parser)); // print LISP-style tree