How to control error handling and synchronization in Antlr 4 / c#

前端 未结 2 1973
感动是毒
感动是毒 2020-12-19 11:48

I\'m using Antlr 4 with c# target. Here is a subset of my grammar:

/*
 * Parser Rules
 */
text : term+  EOF;
term : a1 a2 a3;
a1: ....
...
...
2条回答
  •  没有蜡笔的小新
    2020-12-19 12:38

    For the first question (How to synchronize input to the next valid term?) I found some useful information that led me to acceptable solution.

    Antlr generates next subcode for previous grammar:

    public TextContext text() {
        TextContext _localctx = new TextContext(_ctx, State);
        EnterRule(_localctx, 0, RULE_text);
        int _la;
        try {
            EnterOuterAlt(_localctx, 1);
            State = 49;
            _errHandler.Sync(this);
            _la = _input.La(1);
            do {
                State = 48; term();
                State = 51;
                _errHandler.Sync(this);
                _la = _input.La(1);
            } while ( _la==KEYWORD );
            State = 53; Match(EOF);
        }
        catch (RecognitionException re) {
            _localctx.exception = re;
            _errHandler.ReportError(this, re);
            _errHandler.Recover(this, re);
        }
        finally {
            ExitRule();
        }
        return _localctx;
    }
    

    The call '_errHandler.Sync(this);' makes the parser advances through the input stream in an attempt to find next valid turn (as a result of "term+" component). To stop parser from sync in other subrules accept "term" rule", I Extended DefaultErrorStrategy Class as next:

    public class MyErrorStrategy : Antlr4.Runtime.DefaultErrorStrategy
    {
        public EventErrorStrategy() : base()
        { }
    
        public override void Sync(Antlr4.Runtime.Parser recognizer)
        {
            if(recognizer.Context is Dict.TextAnalyzer.DictionaryParser.TextContext)
                base.Sync(recognizer);
        }
    }
    

    then provided it to the parser:

    parser.ErrorHandler = new MyErrorStrategy();
    

提交回复
热议问题