accessing or reporting a context's exceptions while parsing

12 views
Skip to first unread message

Dillon Blanksma

unread,
Oct 27, 2015, 7:15:51 PM10/27/15
to antlr-discussion
I am attempting to test a language created in Visual Studio using Antlr4 (target language is C#). Everything works wonderful, but I need a way to access exceptions that are thrown while parsing.
I have implemented a listener that extends IAntlrErrorListener<IToken> as follows:

public class SettlementErrorListener : IAntlrErrorListener<IToken>
   {
       public static SettlementErrorListener INSTANCE = new SettlementErrorListener();
 
       public void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
       {
           throw new Exception(msg + " on line " + line + ";character position " + charPositionInLine + e.Message);
       }
   }

Everything works fine and dandy, and I could work with this. It throws the exception because something parsed wrong down the line.
But what I want it to be able to access the exception field associated with each context. In other words I want exception in the context to not be null:

If I just run this line of code:

var ctx = p.solution();

No matter what, the exception field is not populated just running through. Debugging and STEPPING OVER also does not catch the RecognitionException.
However if I go back and STEP INTO the actual rule, the exception is caught and passed back on up through the contexts which makes it available in the ctx variable.

catch (RecognitionException re) {
			_localctx.exception = re;
			_errHandler.ReportError(this, re);
			_errHandler.Recover(this, re);
		}
		finally {
			ExitRule();

Can some please explain this behavior to me?
Reply all
Reply to author
Forward
0 new messages