Search code examples
c#antlr4cs

How to compile .g4 to .cs?


I reread all documentations but still didn't get what exactly do I need to do. Please explain step by step what do I need to do to set up work with Antlr in VS2019 (for C#) and how can I compile .g4 to .cs after. Do I need to install Antlr4 or Antlr4.Runtime or Antlr4.Runtime.Standard? Do I need to download "antlr-4.8-complete.jar" file from official site? If so, what should I do with it after? In general, as you can see, I'm confused in it.


Solution

  • I recommend this way--not because I wrote the software--but because it is easy and uses the most up-to-date release of Antlr:

    • Install the NET SDK (aka "dotnet.exe").
    • dotnet new -i Antlr4BuildTasks.Templates
    • dotnet new antlr
    • dotnet build
    • dotnet run

    You can then open VS2019 or VSCode on the .csproj. See Antlr4BuildTasks.Templates. It uses Antlr4BuildTask for building. You don't need to install Java nor Antlr--it includes a copy of the Java JRE and Antlr. But, you will need connectivity to NuGet.org.

    If for whatever reason you need to generate the .cs files outside of a build, then you can type it in from a shell:

    • java -jar ~/Downloads/antlr-4.8-complete.jar -Dlanguage=CSharp *.g4

    Note, Antlr4.Runtime.Standard is the current Antlr runtime for C# as a netstandard1.3;net35 package. Antlr4.Runtime is Harwell's port of the entire Antlr Java code and runtime v4.6.6 to C#, and, as far as I know, it is not being maintained. There is a tool in that package that is the equivalent to the Java-based Antlr tool, so you can use that in a similar way. But, it is roughly 3 years behind the current release v4.8--soon to be v4.9. The Antlr4BuildTasks package I wrote is a modification of Harwell's package, but instead calls the Java-based Antlr tool.

    Support within an editor for Antlr in VS2019, VSCode, or what have you, for syntactic or semantic highlighting, goto refs, goto def, etc., should be considered separate from the build of your app. Harwell's extension is for VS2017. For VSCode, you have the choice of Mike's vscode-antlr or my LSP-based tool Antlrvsix-vscode. For VS2019, you can use my extension Antlrvsix, or one of the few unsupported and very old extensions. Or, you can skip all that, and just edit it as text.