syntax-errorgrammarstrict

How to make ANTLR parser strict?


Below is a simple ANTLR grammar:

grammar EXAMPLE;

document
            :  Name+ EOF ;

Name
            : 'k'+ ;

The generated antlr parser accepts any string that contains substring 'k'.

However, I want the parser to accept only strings that conform to the grammar. that is, strings that contain characters other than 'k' should trigger an error.

Is there a way to ensure that?

I tried modifying the grammar. And testing with different inputs. But no fix worked.


Solution

  • After reading the comment by Ken and revisiting my code, it turns out that I had the following line in my main function:

    lexer.removeErrorListeners()
    

    After deleting that line, now lexer errors are reported.

    Thank you all.