Improved error message for unterminated string literals (fixes #243)

This commit is contained in:
Sam Harwell 2013-05-26 13:43:56 -05:00
parent d3af4a2f3a
commit 2f2fd4585e
3 changed files with 38 additions and 4 deletions

View File

@ -618,10 +618,17 @@ SRC : 'src' WSCHARS+ file=ACTION_STRING_LITERAL WSCHARS+ line=INT
// may contain unicode escape sequences of the form \uxxxx, where x
// is a valid hexadecimal number (as per Java basically).
STRING_LITERAL
@init {
int len = 0;
}
: '\'' ( ( ESC_SEQ | ~('\\'|'\''|'\r'|'\n') ) {len++;} )* '\''
: '\'' ( ( ESC_SEQ | ~('\\'|'\''|'\r'|'\n') ) )*
( '\''
| // Unterminated string literal
{
Token t = new CommonToken(input, state.type, state.channel, state.tokenStartCharIndex, getCharIndex()-1);
t.setLine(state.tokenStartLine);
t.setText(state.text);
t.setCharPositionInLine(state.tokenStartCharPositionInLine);
grammarError(ErrorType.UNTERMINATED_STRING_LITERAL, t);
}
)
;
// A valid hex digit specification

View File

@ -207,6 +207,17 @@ public enum ErrorType {
* </pre>
*/
UNWANTED_LEXER_COMMAND_ARGUMENT(151, "lexer command '<arg>' does not take any arguments", ErrorSeverity.ERROR),
/**
* The parser contains an unterminated string literal.
* <p/>
* The following rule produces this error.
*
* <pre>
* x : 'x'; // ok
* y : 'y; // error 152
* </pre>
*/
UNTERMINATED_STRING_LITERAL(152, "unterminated string literal", ErrorSeverity.ERROR),
// Backward incompatibility errors
V3_TREE_GRAMMAR(200, "tree grammars are not supported in ANTLR 4", ErrorSeverity.ERROR),

View File

@ -172,6 +172,22 @@ public class TestToolSyntaxErrors extends BaseTest {
super.testErrors(pair, true);
}
/**
* This is a regression test for antlr/antlr4#243
* "Generate a good message for unterminated strings"
* https://github.com/antlr/antlr4/issues/243
*/
@Test public void testUnterminatedStringLiteral() {
String[] pair = new String[] {
"grammar A;\n" +
"a : 'x\n" +
" ;\n",
"error(" + ErrorType.UNTERMINATED_STRING_LITERAL.code + "): A.g4:2:4: unterminated string literal\n"
};
super.testErrors(pair, true);
}
/**
* This is a regression test for antlr/antlr4#262
* "Parser Rule Name Starting With an Underscore"