Antlr Error Handling
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the antlr4 error handling example workings and policies of this site About Us Learn more about Stack
Antlr3 Error Reporting
Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs antlr exceptions Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them;
Antlr Rulecatch
it only takes a minute: Sign up Handling errors in ANTLR4 up vote 24 down vote favorite 10 The default behavior when the parser doesn't know what to do is to print messages to the terminal like: line 1:23 missing DECIMAL at '}' This is a good message, but in the wrong place. I'd rather receive this as an antlr4 error handling exception. I've tried using the BailErrorStrategy, but this throws a ParseCancellationException without a message (caused by a InputMismatchException, also without a message). Is there a way I can get it to report errors via exceptions while retaining the useful info in the message? Here's what I'm really after--I typically use actions in rules to build up an object: dataspec returns [DataExtractor extractor] @init { DataExtractorBuilder builder = new DataExtractorBuilder(layout); } @after { $extractor = builder.create(); } : first=expr { builder.addAll($first.values); } (COMMA next=expr { builder.addAll($next.values); })* EOF ; expr returns [List
ANTLRErrorStrategy All
Antlr Error Listener Example
Known Implementing Classes: BailErrorStrategy, DefaultErrorStrategy public interface
Antlr4 Throw Exception On Error
ANTLRErrorStrategy The interface for defining strategies to deal with syntax errors antlr baseerrorlistener encountered during a parse by ANTLR-generated parsers. We distinguish between three different kinds of errors: The parser http://stackoverflow.com/questions/18132078/handling-errors-in-antlr4 could not figure out which path to take in the ATN (none of the available alternatives could possibly match) The current input does not match what we were looking for A predicate evaluated to false Implementations http://www.antlr.org/api/Java/org/antlr/v4/runtime/ANTLRErrorStrategy.html of this interface report syntax errors by calling Parser.notifyErrorListeners(java.lang.String). TODO: what to do about lexers Method Summary Methods Modifier and Type Method and Description boolean inErrorRecoveryMode(Parserrecognizer) Tests whether or not recognizer is in the process of recovering from an error. void recover(Parserrecognizer, RecognitionExceptione) This method is called to recover from exception e. Token recoverInline(Parserrecognizer) This method is called when an unexpected symbol is encountered during an inline match operation, such as Parser.match(int). void reportError(Parserrecognizer, Gadgets About Confluence Log in ANTLR 3PagesBlogChild pagesANTLR v3 documentationError reporting and recoveryBrowse pagesConfigureSpace tools Attachments (0) Page History Page Information Resolved comments Link to this Pageā¦ View in Hierarchy https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Error+reporting+and+recovery View Source Export to PDF Export to Word Pages ANTLR 3 Wiki Home ANTLR v3 documentation Skip to end of banner JIRA links Go to start of banner Error reporting and recovery http://www.alittlemadness.com/2006/07/11/antlr-by-example-part-5-extra-credit/ Skip to end of metadata Created by Terence Parr [Administrator], last modified on Jan 20, 2009 Go to start of metadata Default Error Reporting Behavior Errors encountered during lexing and parsing are error handling passed to the displayRecognitionError() method. This method has access to the exception that holds information about the error, and uses it to compose an error string that is then passed to the emitErrorMessage() method. The default behavior of emitErrorMessage() is to print the error string to System.err. Custom Error Reporting To change the default error reporting behavior, override either the displayRecognitionError() or the emitErrorMessage() antlr4 error handling methods in the lexer and parser. If you need to change the format of the error message or obtain extra information, such as the error location, then you must override displayRecognitionError(). If all you need to do is change where errors are reported and are happy to keep the error message itself unchanged, then you can just override emitErrorMessage() instead. Here is an example of overriding displayRecognitionError(): @members { public void displayRecognitionError(String[] tokenNames, RecognitionException e) { String hdr = getErrorHeader(e); String msg = getErrorMessage(e, tokenNames); // Now do something with hdr and msg... } } Rather than simply printing errors to a stream, another common approach is to store them in a data structure for use later in the application. An example of this approach is to append errors to a List within the lexer and parser and to provide a public method to allow access to the list: @members { private List Over the past four parts, I have illustrated how to parse and evaluate boolean expressions using ANTLR. The grammar presented is in those parts is based on real code in pulse. Although it works as presented, there are a couple of items to polish up, one of which I have solved, and the other of which I have not yet been able to solve. Error Reporting As pulse allows users to enter their own boolean expressions (to configure when they receive build notifications), decent error reporting is paramount. The first step is to turn off ANTLR's default error handling, so that the errors can be handled by pulse. This is done by setting the defaultErrorHandler option to false: class NotifyConditionParser extends Parser; options { buildAST=true; defaultErrorHandler=false; } With that done, the ANTLR-generated code will throw exceptions on errors. Let's take a look at the sorts of errors that are generated by the grammar as it stands. Case 1: Unrecognised word: $ java NotifyConditionParserTest "changed or tuer" Caught error: unexpected token: tuer Case 2: Unrecognised character: $ java NotifyConditionParserTest "6 and false" Caught error: unexpected char: '6' Case 3: Illegal expression structure $ java NotifyConditionParserTest "state.change or or success" Caught error: unexpected token: or Case 4: Unbalanced parentheses $ java NotifyConditionParserTest "failure or (changed and success" Caught error: expecting RIGHT_PAREN, found 'null' Most of these messages are not too bad, at least they are on the right track. Case 4 is certainly the worst of the lot, although the information is accurate it is not exactly user friendly. We'll get back to that later. One big thing missing in all cases is location information. I figured that ANTLR must have a way to retrieve the information, and a little digging uncovered it. All of the above messages are generated using the getMessage method of the exceptions thrown by ANTLR. To get the line and column number information (which is indeed stored in the exception), you can use the toString method instead: try { … } catch (Exception e)