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?
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:
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!
We have not implemented public/private on the generated classes yet I don't think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With