Question

ANTLR4 newbie, but it's dang cool. Pardon if this has already been answered, but I couldn't find the answer.

I am wondering if there is a good/standard/common practice for dealing with errors in a custom Visitor.

E.g. I have a VisitEqualityExpression that compares two objects which should fail if the objects are not of the same type.

Obviously I can throw/catch, but I was hoping/looking for something like an ErrorListener which I am using on the parser. The cool thing about the ErrorListener is that it gives really detailed information as to the exact error. Can that be done a Visitor time?

I assume it would be better to catch this at parse time. E.g. catch 'abc' == 123 when parsing?

Was it helpful?

Solution

I'd add a List<MyErrorType> to the visitor and add the error to this list if it occurs. You may add the node or only line/column along with an error message.

It may look something like this:

class MyVisitor : MyGrammarNameVisitor<object>
{
    public readonly List<MyErrorType> errors = new List<MyErrorType>();

    override object visitMyRuleName(MyGrammarName.MyRuleNameContext ctx){
        if (erroneous)
        {
            errors.Add(new MyErrorType(linenumber, column, errorMessage, whateverElseMayBeUseful));
            return null;
        }

        //...
    }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top