Introduction to ANTLR4

Hannes Kinks

Tallinn 2014

Resources

ANTLR4 vs Flex+Bison

  • Ease of use over performance
  • Simplicity over complexity
  • Automatic generation of parse trees
  • Decoupled grammar and application-specific code
    • Listeners
    • Visitors
  • Parsing algorithms
    • LL(*)
    • LALR 

Parsing algorithm comparison

Bison - LALR

Bottom-up parsing

ANTLR - LL(*)

Top-down parsing

Parsing with ANTLR4

  • Grammar divided to
    • Lexer
    • Parser
  • Described in *.g4 file

Example

1. Define grammar in  

Assign.g4

2. ANTLR tool generates code

4. Walking the parse tree

3. Input text: 
"sp = 100;"

Listener

  • Parse tree walked depth-first
  • Events fired at every node

Visitor pattern

  • Option -visitor

Setting up the environment

  • http://ati.ttu.ee/~hkinks/antlr/
  • antlr.sh
    • downloads ANTLR4 library
    • adds lib to classpath
    • sets aliases for antlr4 and grun
  • ​plugin.zip
    • Plugin for Intellij IDEA

 

  • Plugins existing also for eclipse and netbeans

antlr4

By Hannes Kinks

antlr4

  • 740