Antlr - Parse Tree (AST)


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




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


grun grammar startRule -tree
grun grammar startRule -gui

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


With the idea plugin:

  • right click on the line of the start rule
  • start to type a text to see the tree




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

  • a lexer file called
  • a parser file called

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");
  • Build the lexer from the input
HelloLexer lexer = new HelloLexer(input);
  • Wrap the lexer into a stream of tokens CommonTokenStream (The parser can then read this stream back and forth)
CommonTokenStream tokens = new CommonTokenStream(lexer);
  • Create a parser that will build the tree
HelloParser parser = new HelloParser(tokens);
  • Finally, you can build the tree (a ParseTree) from the parser rule called r (present in the grammar file and generated in the parser as a function)
ParseTree tree = parser.r();    
System.out.println(tree.toStringTree(parser)); // print LISP-style tree

Powered by ComboStrap