Example usage for org.antlr.v4.runtime RecognitionException getOffendingToken

List of usage examples for org.antlr.v4.runtime RecognitionException getOffendingToken

Introduction

In this page you can find the example usage for org.antlr.v4.runtime RecognitionException getOffendingToken.

Prototype

public Token getOffendingToken() 

Source Link

Usage

From source file:org.beetl.core.parser.BeetlAntlrErrorStrategy.java

License:BSD License

@Override
public void reportError(Parser recognizer, RecognitionException e) {
    // if we've already reported an error and have not matched a token
    // yet successfully, don't report any errors.
    if (inErrorRecoveryMode(recognizer)) {
        //         System.err.print("[SPURIOUS] ");
        return; // don't report spurious errors
    }// ww  w  .  j a v  a2 s  .  c o  m
    beginErrorCondition(recognizer);
    if (e instanceof NoViableAltException) {
        reportNoViableAlternative(recognizer, (NoViableAltException) e);
    } else if (e instanceof InputMismatchException) {
        reportInputMismatch(recognizer, (InputMismatchException) e);
    } else if (e instanceof FailedPredicateException) {
        reportFailedPredicate(recognizer, (FailedPredicateException) e);
    } else {
        //         System.err.println("unknown recognition error type: " + e.getClass().getName());
        BeetlException exception = new BeetlException(BeetlException.PARSER_UNKNOW_ERROR,
                e.getClass().getName(), e);
        exception.token = this.getGrammarToken(e.getOffendingToken());
        throw exception;
    }
}

From source file:org.elasticsearch.painless.ParserErrorStrategy.java

License:Apache License

@Override
public void recover(Parser recognizer, RecognitionException re) {
    Token token = re.getOffendingToken();
    String message;//from  w ww  . ja  va2s. c  o  m

    if (token == null) {
        message = "Error: no parse token found.";
    } else if (re instanceof InputMismatchException) {
        message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                + " unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of ["
                + re.getExpectedTokens().toString(recognizer.getVocabulary()) + "].";
    } else if (re instanceof NoViableAltException) {
        if (token.getType() == PainlessParser.EOF) {
            message = "Error: unexpected end of script.";
        } else {
            message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                    + "invalid sequence of tokens near [" + getTokenErrorDisplay(token) + "].";
        }
    } else {
        message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                + " unexpected token near [" + getTokenErrorDisplay(token) + "].";
    }

    ParseException parseException = new ParseException(message, token == null ? -1 : token.getStartIndex());
    parseException.initCause(re);

    throw new RuntimeException(parseException);
}

From source file:org.elasticsearch.plan.a.ParserErrorStrategy.java

License:Apache License

@Override
public void recover(Parser recognizer, RecognitionException re) {
    Token token = re.getOffendingToken();
    String message;/*from w  ww .  j  ava  2s . c om*/

    if (token == null) {
        message = "Error: no parse token found.";
    } else if (re instanceof InputMismatchException) {
        message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                + " unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of ["
                + re.getExpectedTokens().toString(recognizer.getVocabulary()) + "].";
    } else if (re instanceof NoViableAltException) {
        if (token.getType() == PlanAParser.EOF) {
            message = "Error: unexpected end of script.";
        } else {
            message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                    + "invalid sequence of tokens near [" + getTokenErrorDisplay(token) + "].";
        }
    } else {
        message = "Error[" + token.getLine() + ":" + token.getCharPositionInLine() + "]:"
                + " unexpected token near [" + getTokenErrorDisplay(token) + "].";
    }

    ParseException parseException = new ParseException(message, token == null ? -1 : token.getStartIndex());
    parseException.initCause(re);

    throw new RuntimeException(parseException);
}

From source file:org.hawkular.inventory.rest.Traverser.java

License:Apache License

public Query navigate(String traversal) {
    HawkularInventoryGetUriLexer lexer = new HawkularInventoryGetUriLexer(new ANTLRInputStream(traversal));
    CommonTokenStream tokens = new CommonTokenStream(lexer);

    HawkularInventoryGetUriParser parser = new HawkularInventoryGetUriParser(tokens);
    parser.setErrorHandler(new BailErrorStrategy());

    ParseListener listener = new ParseListener(queryPrefix);

    try {//from w ww  .  j  a v a 2s.  c o  m
        UriContext ctx = parser.uri();

        ParseTreeWalker.DEFAULT.walk(listener, ctx);

        return listener.getParsedQuery();
    } catch (ParseCancellationException e) {
        Throwable error = e.getCause();
        if (error instanceof RecognitionException) {
            RecognitionException re = (RecognitionException) error;
            int errorIndex = indexPrefixSize + re.getOffendingToken().getTokenIndex();
            String errorToken = re.getOffendingToken().getText();
            String expectedAlternatives = re.getExpectedTokens() == null ? "none"
                    : re.getExpectedTokens().toString(HawkularInventoryGetUriLexer.VOCABULARY);

            throw new IllegalArgumentException("Illegal inventory traversal URL. Token '" + errorToken
                    + "' on index " + errorIndex + " is not legal. Expected " + expectedAlternatives);
        } else {
            throw new IllegalArgumentException(
                    "Illegal inventory traversal URL. Error message: " + e.getCause().getMessage(),
                    e.getCause());
        }
    }
}

From source file:org.kaazing.k3po.lang.internal.parser.ScriptParserImpl.java

License:Open Source License

private ScriptParseException createScriptParseException(RobotParser parser, RecognitionException re) {

    if (re instanceof NoViableAltException) {
        return createScriptParseException(parser, (NoViableAltException) re);
    } else {/*from   ww  w . j ava  2 s  .c  o m*/
        Token token = re.getOffendingToken();
        String desc = format("line %d:%d: ", token.getLine(), token.getCharPositionInLine());

        String tokenText = token.getText();
        String msg = null;

        if (tokenText == null) {
            msg = "error: end of input";

        } else {
            desc = format("%s'%s'", desc, tokenText);

            @SuppressWarnings("unused")
            String unexpectedTokenName = token.getType() != -1 ? parser.getTokenNames()[token.getType()]
                    : parser.getTokenNames()[0];

            msg = format("error: unexpected keyword '%s'", tokenText);
        }

        return new ScriptParseException(msg, re);
    }
}

From source file:org.kaazing.robot.lang.parser.ScriptParserImpl.java

License:Open Source License

private ScriptParseException createScriptParseException(RobotParser parser, RecognitionException re) {

    if (re instanceof InputMismatchException) {
        return createScriptParseException(parser, (InputMismatchException) re);

    } else if (re instanceof NoViableAltException) {
        return createScriptParseException(parser, (NoViableAltException) re);

    } else {/*from   w w w. ja v a  2s  .c om*/
        Token token = re.getOffendingToken();
        String desc = String.format("line %d:%d: ", token.getLine(), token.getCharPositionInLine());

        String tokenText = token.getText();
        String msg = null;

        if (tokenText == null) {
            msg = "error: end of input";

        } else {
            desc = String.format("%s'%s'", desc, tokenText);

            @SuppressWarnings("unused")
            String unexpectedTokenName = token.getType() != -1 ? parser.getTokenNames()[token.getType()]
                    : parser.getTokenNames()[0];

            msg = String.format("error: unexpected keyword '%s'", tokenText);
        }

        return new ScriptParseException(msg, re);
    }
}

From source file:org.osate.ba.AadlBaParserAction.java

License:Open Source License

public AnnexSubclause parseAnnexSubclause(String annexName, String source, String filename, int line,
        int column, ParseErrorReporter errReporter) throws antlr.RecognitionException {
    if (false == ANNEX_NAME.equalsIgnoreCase(annexName)) {
        return null;
    }//  w w w . j  a v a2 s .co  m

    CharStream cs = new CaseInsensitiveCharStream(source);

    // AnnexOffset is the offset of the first token found in String source
    // considering the whole source file.
    int annexOffset = column;

    AadlBaHighlighter highlighter;
    // Set a Xtext highlighter if AADLBA Front End is running under OSATE2.
    if (Platform.isRunning()) {
        highlighter = new XtextAadlBaHighlighter();
    } else {
        // Default highlighter does nothing.
        highlighter = new DefaultAadlBaHighlighter();
    }

    AadlAntlrErrorReporter parserErrorReporter = new AadlAntlrErrorReporter(errReporter, filename);

    AadlBaLexer lexer = new AadlBaLexer(cs);
    lexer.setLine(line);
    lexer.setCharPositionInLine(column);
    lexer.removeErrorListeners();
    lexer.addErrorListener(parserErrorReporter);
    lexer.setHighlighter(highlighter);
    lexer.setAnnexOffset(annexOffset);

    CommonTokenStream tokens = new CommonTokenStream(lexer);

    AadlBaParser parser = new AadlBaParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(parserErrorReporter);

    try {
        // Build the primary AST: AST without AADLBA or declarative meta objects 
        // Instanced.
        Behavior_annexContext bac = parser.behavior_annex();
        BehaviorAnnex ba = null;
        // Perform primary checking. Escape on error.

        if (parser.getNumberOfSyntaxErrors() == 0) {
            AadlBaParserVisitor<Boolean> visitor = new AadlBaParserVisitor<Boolean>(filename, annexOffset);

            visitor.visit(bac);

            ba = bac.result;
        } else {
            // Create an empty behavior annex object in order to
            // highlight keywords even if there is some syntax errors.
            ba = AadlBaFactory.eINSTANCE.createBehaviorAnnex();
        }

        if (ba != null) {
            AadlBaLocationReference location = new AadlBaLocationReference(annexOffset, filename, line);

            location.setOffset(0);
            ba.setLocationReference(location);
            ba.getHighlighters().put(ba, highlighter);
        }

        return ba;
    }
    // Translates ANTLR runtime exception to ANTLR Exception. 
    catch (org.antlr.v4.runtime.RecognitionException e) {
        int errLine = e.getOffendingToken().getLine();
        int errColumn = e.getOffendingToken().getCharPositionInLine();

        throw new antlr.RecognitionException(e.getMessage(), filename, errLine, errColumn);
    } catch (IllegalArgumentException e) {
        // Nothing to do as the parser is supposed to report any error.
        // DEBUG
        e.printStackTrace();
        return null;
    }
}

From source file:org.reaktivity.nukleus.maven.plugin.internal.AbstractMojo.java

License:Apache License

private AstSpecificationNode parseSpecification(String resourceName, URL resource) throws IOException {
    try (InputStream input = resource.openStream()) {
        ANTLRInputStream ais = new ANTLRInputStream(input);
        NukleusLexer lexer = new NukleusLexer(ais);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        NukleusParser parser = new NukleusParser(tokens);
        parser.setErrorHandler(new BailErrorStrategy());

        SpecificationContext ctx = parser.specification();
        return new AstParser().visitSpecification(ctx);
    } catch (ParseCancellationException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof RecognitionException) {
            RecognitionException re = (RecognitionException) cause;
            Token token = re.getOffendingToken();
            if (token != null) {
                String message = String.format("Parse failed in %s at %d:%d on \"%s\"", resourceName,
                        token.getLine(), token.getCharPositionInLine(), token.getText());
                getLog().error(message);
            }/* ww  w. ja  va 2s. co  m*/
        }

        throw ex;
    }
}

From source file:org.structr.core.graphql.GraphQLRequest.java

License:Open Source License

public static Document parse(final Parser parser, final String query) throws FrameworkException {

    try {/*from   w ww  . jav a 2s.co  m*/

        return parser.parseDocument(query);

    } catch (Throwable t) {

        String message = t.getMessage();
        if (message == null) {

            message = t.getClass().getName();

            if (t instanceof ParseCancellationException) {

                final Throwable cause = t.getCause();
                if (cause instanceof RecognitionException) {

                    final RecognitionException err = (RecognitionException) cause;
                    final Token offendingToken = err.getOffendingToken();

                    if (offendingToken != null) {

                        final int line = offendingToken.getLine();
                        final int column = offendingToken.getCharPositionInLine();
                        final String text = offendingToken.getText();

                        message = "Parse error at " + text + " in line " + line + ", column " + column;
                    }
                }

            }
        }

        final FrameworkException fex = new FrameworkException(422, message);
        final Map<String, String> data = new LinkedHashMap<>();

        // do not output an empty array of errors
        fex.setErrorBuffer(null);
        fex.setData(data);

        data.put("query", query);

        throw fex;
    }
}