Antlr4 C# Application Tutorial/Example

Neil Pittman picture Neil Pittman · Oct 11, 2013 · Viewed 21k times · Source

I want to use Antlr4 to parse some files in my C# application. I have been able to generate the parser and lexer files so far given my grammer. Now I would like to use read in the files and apply the parser and lexer to them. I have been searching for documentation on how to do that but I am coming up short. I have found some old examples using previous versions of Antlr but they don't appear to work for Antlr4. Any help would be appreciated. Thanks.

Answer

Esten picture Esten · Apr 26, 2014
  • 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#.