Search code examples
c#antlrantlr4antlr4cs

What's the best way to translate ANTLR errors sentences from english to another language?


The application I'm building targets portuguese speaking users. The users can input a sentence which will be interpreted by ANTLR. To provide the users the best feedback from their input I will need to have errors displayed in portuguese.

I didn't found an configuration or file where i could change the error tokens like in some other libraries.


Solution

  • As i searched deeper the best alternative is to override the methods on DefaultErrorStrategy and build the message the way you want.

    You can set an error Handler to your parser, it should be your new custom error strategy.

    typescript DefaultErrorStrategy

    Here is my override for reportInputMismatch method with custom translation:

    reportInputMismatch(recognizer: Parser, e: InputMismatchException): void {
        const expected = e.expectedTokens;
        const expectedString = expected ? this.getFriendlyExpectedTokens(expected, recognizer.vocabulary) : '';
        const input = this.getTokenErrorDisplay(e.getOffendingToken(recognizer));
        const msg = `entrada ${input} não compatível, espera-se ${expectedString}`;
        this.notifyErrorListeners(recognizer, msg, e);
    }