@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (!reportSyntaxErrors) { return; } // String sourceName = recognizer.getInputStream().getSourceName(); // if (!sourceName.isEmpty()) { // sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine); // } System.err.println("CUSTOM: " + "line " + line + ":" + charPositionInLine + " " + msg); syntaxErrors = msg; }
private void setupPicky(PainlessParser parser) { // Diagnostic listener invokes syntaxError on other listeners for ambiguity issues, parser.addErrorListener(new DiagnosticErrorListener(true)); // a second listener to fail the test when the above happens. parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(final Recognizer<?,?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) { throw new AssertionError("line: " + line + ", offset: " + charPositionInLine + ", symbol:" + offendingSymbol + " " + msg); } }); // Enable exact ambiguity detection (costly). we enable exact since its the default for // DiagnosticErrorListener, life is too short to think about what 'inexact ambiguity' might mean. parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (!REPORT_SYNTAX_ERRORS) { return; } String sourceName = recognizer.getInputStream().getSourceName(); if (!sourceName.isEmpty()) { sourceName = String.format("%d:%d: ", line, charPositionInLine); } error_msg.add(sourceName+"line "+line+":"+charPositionInLine+" "+msg); }
private void parseInputStream(CharStream inputStream, OboParseResultListener listener) { final OboLexer l = new OboLexer(inputStream); final Antlr4OboParser p = new Antlr4OboParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException("Failed to parse at line " + line + " due to " + msg, e); } }); if (debug) { p.addErrorListener(new DiagnosticErrorListener()); } p.addParseListener(new OboParserListener(listener)); p.oboFile(); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { List<String> stack = ((Parser)recognizer).getRuleInvocationStack(); Collections.reverse(stack); System.err.println("rule stack: "+stack); System.err.println("linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg); String rule = "rule stack: "+stack; String mensaje = "linea "+line+":"+charPositionInLine+" at "+ offendingSymbol+": "+msg + "\n\r"; agregarLog("Un error inesperado ha ocurrido " +"\n" + mensaje, line, charPositionInLine,true); }
public static void registerErrorListener(final CoqFTParser parser) { parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new CoqSyntaxException(parser, (Token)offendingSymbol, line, charPositionInLine, msg, e); } }); }
/** * Logs parser errors in Checkstyle manner. Parser can generate error * messages. There is special error that parser can generate. It is * missed close HTML tag. This case is special because parser prints * error like {@code "no viable alternative at input 'b \n *\n'"} and it * is not clear that error is about missed close HTML tag. Other error * messages are not special and logged simply as "Parse Error...". * * <p>{@inheritDoc} */ @Override public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException ex) { final int lineNumber = offset + line; if (MSG_JAVADOC_WRONG_SINGLETON_TAG.equals(msg)) { errorMessage = new ParseErrorMessage(lineNumber, MSG_JAVADOC_WRONG_SINGLETON_TAG, charPositionInLine, ((Token) offendingSymbol).getText()); throw new IllegalArgumentException(msg); } else { final int ruleIndex = ex.getCtx().getRuleIndex(); final String ruleName = recognizer.getRuleNames()[ruleIndex]; final String upperCaseRuleName = CaseFormat.UPPER_CAMEL.to( CaseFormat.UPPER_UNDERSCORE, ruleName); errorMessage = new ParseErrorMessage(lineNumber, MSG_JAVADOC_PARSE_RULE_ERROR, charPositionInLine, msg, upperCaseRuleName); } }
@Test public void testExampleFieldCondition() throws Exception { ScoreLexer l = new ScoreLexer(CharStreams.fromString(expression)); ScoreParser p = new ScoreParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException(String.format( "Failed to parse at line %d position %d due to %s", line, charPositionInLine, msg), e); } }); ScoreTranslator visitor = new ScoreTranslator(); AnyExpressionContext ctx = p.anyExpression(); String text = visitor.visitAnyExpression(ctx); System.out.println(text); }
@Test public void testExampleFieldCondition() throws Exception { ScoreLexer l = new ScoreLexer(CharStreams.fromString(fieldCondition)); ScoreParser p = new ScoreParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException(String.format( "Failed to parse at line %d position %d due to %s", line, charPositionInLine, msg), e); } }); ScoreBaseVisitor<Object> visitor = new ScoreBaseVisitor<>(); AnyExpressionContext ctx = p.anyExpression(); Object expression = visitor.visitAnyExpression(ctx); //System.out.println(expression.getClass().getSimpleName()); }
public Statement compileExpression(String expr, MethodDecl method, ModuleInstance module) throws CompileException { VbaLexer lexer = new VbaLexer(new org.antlr.v4.runtime.ANTLRInputStream(expr)); CommonTokenStream tokenStream = new CommonTokenStream(lexer); VbaParser parser = new VbaParser(tokenStream); parser.setBuildParseTree(true); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { // errors.add(new CompileException(new SourceLocation(file, line, charPositionInLine, 0), // CompileException.SYNTAX_ERROR, msg, ((CommonToken) offendingSymbol).getText())); System.err.println(msg); } }); EvalStmtContext eval = parser.evalStmt(); ParserRuleContext c = (ParserRuleContext) eval.getChild(0); if (c instanceof ValueStmtContext) { return this.compileValueStatement((ValueStmtContext) c, method).getStatement(); } else { return new BlockCompiler(method, this).compileBlockStatement(c); } }
/** * {@inheritDoc} */ @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if (parserException != null) { return; } String errorSymbol = getOffendingSymbol(recognizer, offendingSymbol, charPositionInLine); parserException = new ParseException( ErrorCode.SEMANTICANALYZE_PARSE_ERROR, "You have an error in your CQL syntax; check the manual that corresponds to your Streaming version for the right syntax to use near '" + errorSymbol + "' at line " + line + ":" + charPositionInLine); LOG.error(parserException.getMessage(), parserException); }
/** * Syntax error occurred. Add the error to the list of parse issues. */ @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { parseIssues.add(new ParseIssue(line, charPositionInLine, msg, currentFileName, ParseIssueType.SYNTAX_ERROR)); try { setAtLeastOneError(true); // Print error messages with file name if (currentFileName == null) log.error("line " + line + ":" + charPositionInLine + " " + msg); else { String fileName = currentFileName; log.error(fileName + " line " + line + ":" + charPositionInLine + " " + msg); } } catch (Exception e1) { log.error("ERROR: while customizing error message:" + e1); } }
/** * Method, which overrides method from antlr package. This method, as an input, gets the offending * mismatched symbol, location of the mismatch and the message returned by the antlr error listener. * In our case the line is always 1. * With this method we change the incoming error message to something more user friendly * * @param recognizer antlr parser * @param offendingSymbol mismatched symbol * @param line line of the mismatch * @param charPositionInLine position of the character for the mismatch * @param msg error message returned by antlr * @param e antlr recognition exception */ @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { errors = true; charPositionInLine++; if (msg.contains("extraneous input")) { //example: \declare{syntax={infix,7,"+",l}, meaning=artih1.sum, misc=&abc"} String input = getInput(msg); String expectedElements = getExpectedElements(msg); msg = "Extraneous input: " + input + ", were expecting one of the following: " + expectedElements; } else if (msg.contains("no viable alternative at input")) { //example: \declare{syntax={infix,7,"+",l}, meaning=artih1.sum, misc={&abc"} (???) msg = "Something missing from the declaration, possibly a brace or a key-value pair."; } else if (msg.contains("missing")) { msg = msg.replaceAll("missing", "Missing character:"); } msg = msg.replaceAll("WS", "whitespace"); msg = msg.replaceAll("<EOF>", "the end of the file"); Logger.log("Syntax error at character " + charPositionInLine + ": " + msg); }
/** * Compile request to AST. * * @param path request * @return AST parse tree */ public static ParseTree parse(String path) { String normalizedPath = Paths.get(path).normalize().toString().replace(File.separatorChar, '/'); if (normalizedPath.startsWith("/")) { normalizedPath = normalizedPath.substring(1); } ANTLRInputStream is = new ANTLRInputStream(normalizedPath); CoreLexer lexer = new CoreLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(msg, e); } }); CoreParser parser = new CoreParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); return parser.start(); }
/** * Compile request to AST. * @param path request * @return AST */ public static ParseTree parse(String path) { ANTLRInputStream is = new ANTLRInputStream(path); CoreLexer lexer = new CoreLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(e); } }); CoreParser parser = new CoreParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); return parser.start(); }
public static ParseTree parseExpression(String expression) { ANTLRInputStream is = new ANTLRInputStream(expression); ExpressionLexer lexer = new ExpressionLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(msg, e); } }); ExpressionParser parser = new ExpressionParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); lexer.reset(); return parser.start(); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { if ( offendingSymbol==null ) { final Lexer lexer = (Lexer) recognizer; int i = lexer.getCharIndex(); final int n = lexer.getInputStream().size(); if (i >= n) { i = n - 1; } final String text = lexer.getInputStream().getText(new Interval(i, i)); CommonToken t = (CommonToken) lexer.getTokenFactory().create(Token.INVALID_TYPE, text); t.setStartIndex(i); t.setStopIndex(i); t.setLine(line); t.setCharPositionInLine(charPositionInLine); offendingSymbol = t; } // System.out.println("lex error: " + offendingSymbol); issues.add(new Issue(msg, (Token)offendingSymbol)); }
/** * @see BaseErrorListener#reportAmbiguity */ @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { List<String> stack = ((Parser) recognizer).getRuleInvocationStack(); Collections.reverse(stack); String logMsg = "Parser ERROR: line " + line + ":" + charPositionInLine + " at " + offendingSymbol + ": " + msg; CommonToken tok = (CommonToken) offendingSymbol; String s = tok.getText(); logMsg += ": offending token " + s; if (s.equals("<EOF>")) { logMsg += ". Look for tag=(null or empty)."; } else { try { Integer.parseInt(s); } catch (NumberFormatException ex) { logMsg += " not a number. "; } } FixRulesParserErrorListener.logger.error(logMsg + " Tree = {}", stack); throw new RuntimeException(logMsg); }
public static void main(final String[] args) throws Exception { final FileInputStream fileInputStream = new FileInputStream(args[0]); final GMLLexer gmlLexer = new GMLLexer(new ANTLRInputStream(fileInputStream)); final GMLParser gmlParser = new GMLParser(new CommonTokenStream(gmlLexer)); gmlParser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String message, final RecognitionException exception) { throw new RuntimeException(message); } }); final GMLExtractor gmlExtractor = new GMLExtractor(gmlParser); final GMLInterpreter gmlInterpreter = new GMLInterpreter(gmlExtractor); gmlInterpreter.interpret(); }
@Test public void twelveFactorial() throws IOException { final GMLLexer gmlLexer = new GMLLexer(new ANTLRInputStream(getClass().getResourceAsStream("fact.gml"))); final GMLParser gmlParser = new GMLParser(new CommonTokenStream(gmlLexer)); gmlParser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(final Recognizer<?, ?> theRecognizer, final Object theOffendingSymbol, final int theLine, final int theCharPositionInLine, final String theMsg, final RecognitionException theE) { Assert.fail(theMsg); } }); final GMLExtractor gmlExtractor = new GMLExtractor(gmlParser); final GMLInterpreter gmlInterpreter = new GMLInterpreter(gmlExtractor); final Stack<Token> tokenStack = gmlInterpreter.interpret(); Assert.assertEquals(tokenStack.size(), 1); final NumberToken result = (NumberToken) tokenStack.pop(); Assert.assertEquals(result.getValue(), 479001600d); }
@Test(dataProvider = "dataProvider") public void gmlExtractorTest(final String fileName, final int expectedTokenCount) throws IOException { final GMLLexer gmlLexer = new GMLLexer(new ANTLRInputStream(getClass().getResourceAsStream(fileName))); final GMLParser gmlParser = new GMLParser(new CommonTokenStream(gmlLexer)); gmlParser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(final Recognizer<?, ?> theRecognizer, final Object theOffendingSymbol, final int theLine, final int theCharPositionInLine, final String theMsg, final RecognitionException theE) { Assert.fail(theMsg); } }); final GMLExtractor gmlExtractor = new GMLExtractor(gmlParser); final List<Token> tokens = gmlExtractor.extract(); LOGGER.info(tokens.toString()); Assert.assertEquals(tokens.size(), expectedTokenCount); }
private void assertEqualDescriptorProtoFields(final int messageIndex, final boolean isProtocCompatible) throws URISyntaxException, IOException { // given final List<FieldDescriptorProto> expected = protocProto.getMessageType(messageIndex).getFieldList(); // when final Builder protoBuilder = filesBuilder.setProtocCompatible(isProtocCompatible) .addFiles(baseDir, DEFAULT_VALUES_PROTO); final List<FieldDescriptorProto> actual = protoBuilder.buildProtos().get(0).getMessageType(messageIndex).getFieldList(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); assertThat(actual).as("check nullness, duplicates, size").isNotNull().doesNotContainNull() .doesNotHaveDuplicates().hasSameSizeAs(expected); assertThat(actual).as("check fields equality").containsOnlyElementsOf(expected); }
@Test public void testInvalidExtensionRange1() throws Exception { // given baseDir = new File(baseDir, "NonUniqueExtensionName1"); final File errorsFile = new File(baseDir, "errors.txt"); assertThat("cannot read file", errorsFile.canRead()); final String expectedErrorText = Files.asCharSource(errorsFile, Charsets.UTF_8).read(); // when final Map<String, FileDescriptor> result = filesBuilder.addFilesByRegex(baseDir, filePattern).build(); // then final ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); // TODO: add position capturing and asserts! verify(mockErrorListener, atLeastOnce()).validationError(anyInt(), anyInt(), argument.capture(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); // verify(mockErrorListener, atLeast(protocFdProtos.size())).setProtoName(anyString()); final List<String> actualErrors = argument.getAllValues(); assertThat(result, is(nullValue())); assertThat(expectedErrorText, stringContainsInOrder(actualErrors)); }
/** * protoc custom options' UnknownFieldSet serialization is different from Java; the resulted * extensions are the same, but UnknownFieldSets are different, thus the invariant has been * violated. When the serializations become identical, the test will start failing, indicating * everything is alright, so the expected exception will have to be safely removed! */ @Test public void unknownToExtensionsToUnknownShouldBeEqualProtoc() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(false).setProtocCompatible(false) .addProtos(protocFdProtos).build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); expected.expect(Throwable.class); for (final FileDescriptor file : files) { assertReserializationInvariant(file); } }
@Test public void unknownToExtensionsToUnknownShouldBeEqual() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(false).setProtocCompatible(false) .addFilesByGlob(baseDir, "**/*.proto").build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); for (final FileDescriptor file : files) { assertReserializationInvariant(file); } }
@Test public void extensionsToUnknownToExtensionsShouldBeEqualProtoc() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(true).setProtocCompatible(false) .addProtos(protocFdProtos).build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); for (final FileDescriptor file : files) { assertReserializationInvariant2(file); } }
@Test public void extensionsToUnknownToExtensionsShouldBeEqual() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(true).setProtocCompatible(false) .addFilesByGlob(baseDir, "**/*.proto").build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); for (final FileDescriptor file : files) { assertReserializationInvariant2(file); } }
@Override public final void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) { String input; if (recognizer instanceof Lexer) { final CharStream cs = ((Lexer) recognizer).getInputStream(); input = cs.getText(new Interval(0, cs.size())); } else if (recognizer instanceof Parser) { final TokenStream tokens = ((Parser) recognizer).getInputStream(); if (tokens != null) { input = tokens.getText(); } else { input = "<unknown input>"; } } else { input = "<unknown input>"; } throw new AntlrParseException(input, line, charPositionInLine, msg); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { super.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e); hasErrors = true; }
/** Parse data or input file and initialize the parse tree. */ private void parseInput() { if (data == null) loadInputFile(); if (data == null) throw new IllegalArgumentException("Unable to load input file or data is missing."); ANTLRInputStream input = new ANTLRInputStream(data); SaltLexer lexer = new SaltLexer(input); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> arg0, Object arg1, int arg2, int arg3, String arg4, RecognitionException arg5) { throw new RuntimeException(arg5); } }); CommonTokenStream tokens = new CommonTokenStream(lexer); SaltParser parser = new SaltParser(tokens); tree = parser.document(); if (parser.getNumberOfSyntaxErrors() > 0) { System.out.println("Syntax error in file " + inputFile); return; } }
/** * Parse the string passed as parameter returning the string representing the structure of the UI * described by the parameter. * @param document * @return * @throws Exception */ private String parse(String document) throws Exception { ANTLRInputStream input = new ANTLRInputStream(document); SaltLexer lexer = new SaltLexer(input); // The lexer should not recover errors. lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> arg0, Object arg1, int arg2, int arg3, String arg4, RecognitionException arg5) { throw new RuntimeException(arg5); } }); CommonTokenStream tokens = new CommonTokenStream(lexer); SaltParser parser = new SaltParser(tokens); ParseTree tree = parser.document(); if (parser.getNumberOfSyntaxErrors() > 0) { throw new SyntaxException("Syntax error into the document: " + document); } // SaltTextVisitor visitor = new SaltTextVisitor(parser); return visitor.visit(tree); }
@Override public void syntaxError( final Recognizer<?, ?> recognizer, final Object offending, final int line, final int position, final String msg, final RecognitionException exception ) { super.syntaxError( recognizer, offending, line, position, msg, exception ); throw new ParseCancellationException(exception); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { // if (!REPORT_SYNTAX_ERRORS) { // return; // } String sourceName = recognizer.getInputStream().getSourceName(); if (sourceName!=null) { sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine); } StringBuilder sb = new StringBuilder(); if(sourceName!=null) sb.append(sourceName); sb.append("line "+line+":"+charPositionInLine+" "+msg); String errMsg = sb.toString(); //System.err.println(errMsg); throw new RuntimeException(errMsg); }
public void syntaxError(Recognizer<?, ?> aRecognizer, Object aOffendingSymbol, int aLine, int aCharIndex, String aMessage, RecognitionException aException) { ANTLRErrorStrategy errorHandler = myParser.getErrorHandler(); if (LOGGER.isWarnEnabled()) { LOGGER.warn(aMessage + " [" + aLine + ":" + aCharIndex + "]"); } /* * Setting the lexer exception in the parser since I don't see a * getNumberOfSyntaxErrors() method in the lexer (like in antlr3) and * the lexer's errors aren't being reported by parser's method * * I may just be missing the correct way this should be handled(?) */ if (aException instanceof LexerNoViableAltException) { NoViableAltException exception = new NoViableAltException(myParser); errorHandler.reportError(myParser, exception); } else { errorHandler.reportError(myParser, aException); } }
public static WorkspaceContext getWorkspaceContext(InputStream source) throws IOException { WorkspaceLexer l = new WorkspaceLexer(CharStreams.fromStream(source)); WorkspaceParser p = new WorkspaceParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e); } }); WorkspaceContext ctx = p.workspace(); return ctx; }
@Test public void testParse() throws Exception { WorkspaceLexer l = new WorkspaceLexer(CharStreams.fromStream(getClass().getResourceAsStream("/thing.wsp"))); WorkspaceParser p = new WorkspaceParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e); } }); p.workspace(); }
public static Spa manifest(String resource) throws IOException { SpaLexer l = new SpaLexer(CharStreams.fromStream(Utils.resolveResource(Spa.class, resource))); SpaParser p = new SpaParser(new CommonTokenStream(l)); p.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e); } }); SpaContext spa = p.spa(); SpaImporter importer = new SpaImporter(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(importer, spa); return importer.getSpa(); }
@Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { output.write(msg); output.write("\n"); if ( offendingSymbol instanceof org.antlr.v4.runtime.CommonToken ) symbol = ((CommonToken) offendingSymbol).getText(); }