In the previous post, we saw how the grammar framework supports callbacks nearly everywhere in the EBNF terms. You are able to inject custom code before and after any term is matched. One of the most important injection points is the Error callback since that allows you to tell the parser how to handle errors.
In today’s post, we’ll examine the importance of adding error handling. We’ll enhance our Simple language grammar to properly recover from nearly any invalid syntax in a document so that it can continue parsing the rest of the document.
Why add error handling?
An error occurs when one or more terminals is expected by the parser (per the grammar) but a different token is found at the current location in the document.
By default when this scenario occurs, the parser will report a parse error if a single terminal is expected. If there is more than one terminal that could be next, and if the containing non-terminal has an error alias set, it will report a parse error instead. This behavior is described in the previous post.
Following any possible error reporting, the parser will immediately exit the current non-terminal and will continue up the non-terminal stack, exiting each one as it goes until the root non-terminal is reached and exited itself.
Thus the result is that if any invalid syntax is found in a document, parsing stops at that point and no AST will be built. That’s definitely not good since we expect code being parsed from our SyntaxEditor control editing to be invalid most of the time. End users are continuously typing in it.
As shown in the previous post, the grammar framework has a lot ways to recover from errors, and they are easy to add. More...