Antlr Error Strategy to skip tokens until rule matches again

不羁岁月 提交于 2019-12-05 16:12:31

You should be able to accomplish this with this error strategy class:

internal class MyGrammarErrorStrategy : DefaultErrorStrategy
{
    public override void Recover(Parser recognizer, RecognitionException e)
    {
        // This should should move the current position to the next 'END' token
        base.Recover(recognizer, e);

        ITokenStream tokenStream = (ITokenStream)recognizer.InputStream;

        // Verify we are where we expect to be
        if (tokenStream.La(1) == MyGrammarParser.END)
        {
            // Get the next possible tokens
            IntervalSet intervalSet = GetErrorRecoverySet(recognizer);

            // Move to the next token
            tokenStream.Consume();

            // Move to the next possible token
            // If the errant element is the last in the set, this will move to the 'END' token in 'END MODULE'.
            // If there are subsequent elements in the set, this will move to the 'BEGIN' token in 'BEGIN module_element'.
            ConsumeUntil(recognizer, intervalSet);
        }
    }
}

And then set the error handler, accordingly:

parser.ErrorHandler = new MyGrammarErrorStrategy();

The idea is that we first allow the default Recover implementation to move the current position to the "resynchronization set," which in this case is the next END token. Subsequently, we consume additional tokens using the provided error recovery set to move the position to where we need it to be. This resulting position will differ based on whether or not the errant module_element is the last in the module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!