The Definitive ANTLR 4 Reference

Author: Terence Parr
4.8
This Year Stack Overflow 1
This Month Stack Overflow 1

The Definitive ANTLR 4 Reference

4.8

Review Date:

Comments

by anonymous   2017-08-20
  • In Visual Studio, go to Tools -> Extensions and Updates and search the Online section for "ANTLR Language Support" by Sam Harwell. More information can be found on the GitHub project site
    • This does a few things:
      • Adds Templates for the combined grammars.
      • Adds Syntax Highlighting
      • Adds an MSBuild target for the grammar to generate the parser.
  • In your solution, set up your project structure like this:
    • Solution
      • GrammarProject
        • Calculator.g4
      • ImplementationProject
        • GeneratedFiles (All files in this folder are added as Links to files located in GrammarProject\obj\Debug)
          • CalculatorBaseListener.cs
          • CalculatorBaseVisitor.cs
          • CalculatorLexer.cs
          • CalculatorListener.cs
          • CalculatorParser.cs
          • CalculatorVistor.cs
        • MyCalcualtorImplementation.cs
  • Write and Compile your grammar.
  • In your folder for the Links to Generated Files, Right-Click the folder and click Add -> Existing Item
  • Browse to Grammar Project\obj\Debug and select all the generated parser files.
  • This next step is important. On the Add button there is a little drop-down arrow. Click the drop-down arrow and click "Add As Link".
    • This will add the generated files to the implementation project using a symbolic link instead of a direct copy.
    • This gives the added benefit of not having to remove and re-add the parser files if you have to change your grammar later.
  • Once you have gotten this far, then you can inherit from GrammarProject.CalculatorBaseListener or GrammarProject.CalculatorBaseParser depending on what development pattern you have decided to use.

As a side note, "The Definitive ANTLR 4 Reference" by Terence Parr is an excellent resource to understand how ANTLR4 works and the difference development patterns. All the examples are in java, but the concepts apply to both Java and C#.