/antlr4-calculator

ANTLR4 calculator example and explanation

Primary LanguageJavaMIT LicenseMIT

ANTLR4 Calculator Example

ANTLR4 calculator example and explanation

line coverage branch coverage

How do I set this up?

  • The project uses Java 11, but you can change this in pom.xml if need be
  • Install packages using Maven (see pom.xml)
  • This automatically generates the required classes through ANTLR4
  • For manually updating/regenerating the required classes based on the grammar, you can let Maven execute the antlr4:antlr4 command
  • The generated classes are found under target/generated-sources.
  • Make sure your IDE includes the generated-sources in its imports.
    • In IntelliJ IDEA, you can right-click the project folder at the top of the project tab (in our case antlr4-calculator) and then click Maven > Generate Sources and Update Folders
  • If you're working on your own DSL, you probably want to use a plug-in for your IDE or another tool

How to start?

Run the nl.arothuis.antlr4calculator.ListenerMain.main() or nl.arothuis.antlr4calculator.VisitorMain.main()
and start typing your calculations. Leave the calculation blank or type exit to exit the program.

What is going on?

ANTLR4 generates Parser, Visitor and Listener classes based on the Calculator.g4 grammar found in src/main/antlr4/nl.arothuis.antlr4calculator.core.parser. These classes contain context and methods needed for visiting the nodes in the parse tree or for listening to events when entering or exiting the nodes in a parse tree.

The CalculationVisitor and CalculationListener are custom classes that extend their respective base classes generated by ANTLR4. In this custom class, we can overwrite the steps taken when visiting each node in a certain expression.

💡 Want to learn more about the architecture and underlying techniques?

Have a look at this document!

Where are all the classes?

ANTLR4 generates these class files in the target directory. You can use the maven commands defined in the pom.xml.

The generated classes are output to the target/generated-sources/antlr4 directory and reside in the project's nl.arothuis.antlr4calculator.core.parser package. This is due to the standard configuration of ANTLR4, matching the location of the grammar file (src/antlr4/nl.arothuis.antlr4calculator.core.parser). No further configuration required.

Author

Alex Rothuis: @arothuis

arothuis.nl