简体   繁体   中英

Setup ANTLR 4 grammar to handle Java and C# environments

I'm using an ANTLR 4 split grammar both in both C# and Java environments and I am unable to compile the grammar in both languages unless I change the function NotifyErrorListeners to use camel case notifyErrorListeners.

C# example:

statement       
:   expression SEMICOLON
|   { NotifyErrorListeners("; expected."); } expression // They forgot the semicolon.

Java example:

statement       
:   expression SEMICOLON
|   { notifyErrorListeners("; expected."); } expression // They forgot the semicolon.

My C# ANTLR environment was pulled through Nuget: Antlr4 4.2.2-alpha001

My Java ANTLR environment was downloaded from antlr.org: antlr-4.5-complete.jar

Is there a way I could modify my grammar so I do not have to modify it when switching between languages? Is there a better function to use that would facilitate both environments?

I have solved my problem. Create a partial class in the C# project for the Parser and make sure it is in the same assembly and namespace. Then it is easy to add a method that uses the camel casing Java is expecting. Now I can use both environments without modifying my grammar.

public partial class ScriptParser
{
    public void notifyErrorListeners(string message)
    {
        this.NotifyErrorListeners(message);
    }
}

Thank you laune for the questions and suggestions. You pushed me towards to the correct answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM