Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Antlr generated classes access modifier to internal

Tags:

c#

antlr

antlr4

I am building a library which contains certain parsers. These parsers are internally built with ANTLR4. Since the generated classes are all public, users of my library are able to see all the classes they do not need to see. Also the Sandcastle documentation contains all these classes. Is there any way I can tell Antlr to make the generated classes internal instead of public?

like image 683
metacircle Avatar asked Apr 22 '14 11:04

metacircle


2 Answers

Actually, it's relatively easy to do. Internally, ANTLR uses StringTemplate files to generate code for each of the supported languages. For C#, you can find the template here in the ANTLR's JAR file:

org\antlr\v4\tool\templates\codegen\CSharp\CSharp.stg

Just make a copy of this file, and modify it as needed. For example, I usually remove CLSCompliant(false) attributes to get rid of the compiler's warnings, and make all the classes and interfaces internal.

Then, you need to tell the ANTLR to use the modified template during code generation. In order to do this, you need to put it in the CLASSPATH before ANTLR's JAR, and make sure that you keep the original folder structure, so that you point to a folder where the org directory is located, not to the CSharp.stg itself.

Here is an example of the folder structure that you can use:

enter image description here

In this case, Generate.bat should look something as follows (assuming that java.exe is in your PATH):

pushd %~dp0
set CLASSPATH=.;antlr-4.7-complete.jar
java org.antlr.v4.Tool -Dlanguage=CSharp Grammar.g4

Happy coding!

like image 55
Yarik Avatar answered Sep 28 '22 13:09

Yarik


We have not implemented public/private on the generated classes yet I don't think.

like image 40
Terence Parr Avatar answered Sep 28 '22 12:09

Terence Parr