ANTLR TestRig / grun Build Grammar with Visual Parse Tree


Example

Specifying the -gui command line option when running an ANTLR grammar in the test rig will result in a window popping up with a visual representation of the parse tree. For example:

Given the following grammar:

JSON.g4

/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */

// Derived from http://json.org
grammar JSON;

json
   : value
   ;

object
   : '{' pair (',' pair)* '}'
   | '{' '}'
   ;

pair
   : STRING ':' value
   ;

array
   : '[' value (',' value)* ']'
   | '[' ']'
   ;

value
   : STRING
   | NUMBER
   | object
   | array
   | 'true'
   | 'false'
   | 'null'
   ;


STRING
   : '"' (ESC | ~ ["\\])* '"'
   ;
fragment ESC
   : '\\' (["\\/bfnrt] | UNICODE)
   ;
fragment UNICODE
   : 'u' HEX HEX HEX HEX
   ;
fragment HEX
   : [0-9a-fA-F]
   ;
NUMBER
   : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT
   ;
fragment INT
   : '0' | [1-9] [0-9]*
   ;
// no leading zeros
fragment EXP
   : [Ee] [+\-]? INT
   ;
// \- since - means "range" inside [...]
WS
   : [ \t\n\r] + -> skip
   ;

Given the following JSON file:

example.json

{
  "name": "John Doe",
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": null
}

The following syntax command line syntax:

export CLASSPATH=".:/usr/local/lib/antlr-4.0-complete.jar:$CLASSPATH"                                                                                      
alias antlr4='java -jar /usr/local/lib/antlr-4.0-complete.jar'                                                                                             
alias grun='java org.antlr.v4.runtime.misc.TestRig'

antlr4 -o . -lib . -no-listener -no-visitor  JSON.g4; javac *.java; grun JSON json -gui example.json

will result in the generated .java & .tokens files, as well as the compiled .class files:

JSON.g4                        JSONLexer.class                JSONListener.java JSONParser$PairContext.class   JSON.tokens                    JSONLexer.java JSONParser$ArrayContext.class  JSONParser$ValueContext.class  JSONBaseListener.class JSONLexer.tokens               JSONParser$JsonContext.class   JSONParser.class
JSONBaseListener.java          JSONListener.class
JSONParser$ObjectContext.class JSONParser.java

and the following parse tree:

enter image description here