ANTLR "Hello" Grammar File and Test

Q

How to create a simple "Hello" grammar file and test it with ANTLR?

✍: FYIcenter

A

There 4 steps you need to follow to create "Hello" grammar file and test it:

1. Create grammar file, Hello.g4:

// Define a grammar called Hello
grammar Hello;
r  : 'hello' ID ;         // match keyword hello followed by an identifier
ID : [a-z]+ ;             // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

2. Generate the lexer and parser in Java:

\fyicenter>java -cp antlr-4.10.1-complete.jar org.antlr.v4.Tool Hello.g4

\fyicenter>dir 
    249 Hello.interp
     27 Hello.tokens
   1305 HelloBaseListener.java
    990 HelloLexer.interp
   4419 HelloLexer.java
     27 HelloLexer.tokens
    537 HelloListener.java
   4004 HelloParser.java

3. Compile the lexer, parser and supporting Java classes

\fyicenter>javac -cp .;antlr-4.10.1-complete.jar Hello*.java

\fyicenter>dir *.class
    794 HelloBaseListener.class
   3794 HelloLexer.class
    304 HelloListener.class
    888 HelloParser$RContext.class
   4391 HelloParser.class

4. Testing the lexer and parser with ANTLR TestRig:

\fyicenter>java -cp .;antlr-4.10.1-complete.jar org.antlr.v4.gui.TestRig Hello r -tree
   
hello you
^Z
(r hello you)

The above output shows that the Hello lexer and parser is working:

  • Argument "Hello" tells the TestRig to use the "Hello" lexer and parser.
  • Argument "r" tells the TestRig to start parsing source code with the grammar rule "r".
  • Option "-tree" tells the TestRig to display parser output in text tree format.
  • No input file specified. So source code was entered from the console.
  • The source code is 1 line: "hello you".
  • "^Z" indicates that Ctrl-Z was pressed to end the source code. On Linux systems, you need to use Ctrl-D.
  • "(r hello you)" is the output of the parser indicating source coded parsed correctly.

ANTLR "Hello" Lexer and Parser Error

ANTLR TestRig Command and Options

ANTLR Commands and Examples

⇑⇑ FAQ for ANTLR Parser Generator

2020-12-02, 7275🔥, 0💬