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:ch.raffael.contracts.processor.cel.Compiler.java

License:Apache License

private void addANTLRError(RecognitionException e, String msg) {
    errors.add(new CelError(
            new Position(e.getOffendingToken().getLine(), e.getOffendingToken().getCharPositionInLine()), msg));
}

From source file:com.eprosima.idl.parser.strategy.DefaultErrorStrategy.java

License:Apache License

@Override
public void reportError(Parser recognizer, RecognitionException e) {
    if (inErrorRecoveryMode(recognizer)) {
        // System.err.print("[SPURIOUS] ");
        return; // don't report spurious errors
    }//from  w w  w  . j  a  v a  2s . com
    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 if (e instanceof ParseException) {
        if (e.getOffendingToken() != null) {
            String message = ColorMessage.bold(getTokenErrorDisplay(e.getOffendingToken()) + " ")
                    + e.getMessage();
            recognizer.notifyErrorListeners(e.getOffendingToken(), message, e);
        } else
            recognizer.notifyErrorListeners(e.getMessage());
    } else {
        System.err.println("unknown recognition error type: " + e.getClass().getName());
        recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }
}

From source file:com.espertech.esper.epl.parse.Antlr4ErrorStrategy.java

License:Open Source License

public void reportError(Parser recognizer, RecognitionException e) {
    // Antlr has an issue handling LexerNoViableAltException as then offending token can be null
    // Try: "select a.b('aa\") from A"
    if (e instanceof LexerNoViableAltException && e.getOffendingToken() == null) {
        return;/*ww w  .  ja  v a  2  s  .  co  m*/
    }
    super.reportError(recognizer, e);
}

From source file:com.espertech.esper.epl.parse.ExceptionConvertor.java

License:Open Source License

/**
 * Converts from a syntax error to a nice exception.
 * @param e is the syntax error//from  ww  w  . j av a2  s  .  c om
 * @param expression is the expression text
 * @param parser the parser that parsed the expression
 * @param addPleaseCheck indicates to add "please check" paraphrases
 * @return syntax exception
 */
public static UniformPair<String> convert(RecognitionException e, String expression, boolean addPleaseCheck,
        EsperEPL2GrammarParser parser) {
    if (expression.trim().length() == 0) {
        String message = "Unexpected " + END_OF_INPUT_TEXT;
        return new UniformPair<String>(message, expression);
    }

    Token t;
    Token tBeforeBefore = null;
    Token tBefore = null;
    Token tAfter = null;

    int tIndex = e.getOffendingToken() != null ? e.getOffendingToken().getTokenIndex() : Integer.MAX_VALUE;
    if (tIndex < parser.getTokenStream().size()) {
        t = parser.getTokenStream().get(tIndex);
        if ((tIndex + 1) < parser.getTokenStream().size()) {
            tAfter = parser.getTokenStream().get(tIndex + 1);
        }
        if (tIndex - 1 >= 0) {
            tBefore = parser.getTokenStream().get(tIndex - 1);
        }
        if (tIndex - 2 >= 0) {
            tBeforeBefore = parser.getTokenStream().get(tIndex - 2);
        }
    } else {
        if (parser.getTokenStream().size() >= 1) {
            tBeforeBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
        }
        if (parser.getTokenStream().size() >= 2) {
            tBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 2);
        }
        t = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
    }

    Token tEnd = null;
    if (parser.getTokenStream().size() > 0) {
        tEnd = parser.getTokenStream().get(parser.getTokenStream().size() - 1);
    }

    String positionInfo = getPositionInfo(t);
    String token = t.getType() == EsperEPL2GrammarParser.EOF ? "end-of-input" : "'" + t.getText() + "'";

    Stack stack = parser.getParaphrases();
    String check = "";
    boolean isSelect = stack.size() == 1 && stack.get(0).equals("select clause");
    if ((stack.size() > 0) && addPleaseCheck) {
        String delimiter = "";
        StringBuilder checkList = new StringBuilder();
        checkList.append(", please check the ");
        while (stack.size() != 0) {
            checkList.append(delimiter);
            checkList.append(stack.pop());
            delimiter = " within the ";
        }
        check = checkList.toString();
    }

    // check if token is a reserved keyword
    Set<String> keywords = parser.getKeywords();
    boolean reservedKeyword = false;
    if (keywords.contains(token.toLowerCase())) {
        token += " (a reserved keyword)";
        reservedKeyword = true;
    } else if (tAfter != null && keywords.contains("'" + tAfter.getText().toLowerCase() + "'")) {
        token += " ('" + tAfter.getText() + "' is a reserved keyword)";
        reservedKeyword = true;
    } else {
        if ((tBefore != null) && (tAfter != null)
                && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'"))
                && (keywords.contains("'" + tAfter.getText().toLowerCase() + "'"))) {
            token += " ('" + tBefore.getText() + "' and '" + tAfter.getText() + "' are a reserved keyword)";
            reservedKeyword = true;
        } else if ((tBefore != null) && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'"))) {
            token += " ('" + tBefore.getText() + "' is a reserved keyword)";
            reservedKeyword = true;
        } else if (tEnd != null && keywords.contains("'" + tEnd.getText().toLowerCase() + "'")) {
            token += " ('" + tEnd.getText() + "' is a reserved keyword)";
            reservedKeyword = true;
        }
    }

    // special handling for the select-clause "as" keyword, which is required
    if (isSelect && !reservedKeyword) {
        check += getSelectClauseAsText(tBeforeBefore, t);
    }

    String message = "Incorrect syntax near " + token + positionInfo + check;
    if (e instanceof NoViableAltException || e instanceof LexerNoViableAltException
            || checkForInputMismatchWithNoExpected(e)) {
        Token nvaeToken = e.getOffendingToken();
        int nvaeTokenType = nvaeToken != null ? nvaeToken.getType() : EsperEPL2GrammarLexer.EOF;

        if (nvaeTokenType == EsperEPL2GrammarLexer.EOF) {
            if (token.equals(END_OF_INPUT_TEXT)) {
                message = "Unexpected " + END_OF_INPUT_TEXT + positionInfo + check;
            } else {
                if (ParseHelper.hasControlCharacters(expression)) {
                    message = "Unrecognized control characters found in text" + positionInfo;
                } else {
                    message = "Unexpected " + END_OF_INPUT_TEXT + " near " + token + positionInfo + check;
                }
            }
        } else {
            if (parser.getParserTokenParaphrases().get(nvaeTokenType) != null) {
                message = "Incorrect syntax near " + token + positionInfo + check;
            } else {
                // find next keyword in the next 3 tokens
                int currentIndex = tIndex + 1;
                while ((currentIndex > 0) && (currentIndex < parser.getTokenStream().size() - 1)
                        && (currentIndex < tIndex + 3)) {
                    Token next = parser.getTokenStream().get(currentIndex);
                    currentIndex++;

                    String quotedToken = "'" + next.getText() + "'";
                    if (parser.getKeywords().contains(quotedToken)) {
                        check += " near reserved keyword '" + next.getText() + "'";
                        break;
                    }
                }
                message = "Incorrect syntax near " + token + positionInfo + check;
            }
        }
    } else if (e instanceof InputMismatchException) {
        InputMismatchException mismatched = (InputMismatchException) e;

        String expected;
        if (mismatched.getExpectedTokens().size() > 1) {
            StringWriter writer = new StringWriter();
            writer.append("any of the following tokens {");
            String delimiter = "";
            for (int i = 0; i < mismatched.getExpectedTokens().size(); i++) {
                writer.append(delimiter);
                if (i > 5) {
                    writer.append("...");
                    writer.append(Integer.toString(mismatched.getExpectedTokens().size() - 5));
                    writer.append(" more");
                    break;
                }
                delimiter = ", ";
                writer.append(getTokenText(parser, mismatched.getExpectedTokens().get(i)));
            }
            writer.append("}");
            expected = writer.toString();
        } else {
            expected = getTokenText(parser, mismatched.getExpectedTokens().get(0));
        }

        int offendingTokenType = mismatched.getOffendingToken().getType();
        String unexpected = getTokenText(parser, offendingTokenType);

        String expecting = " expecting " + expected.trim() + " but found " + unexpected.trim();
        message = "Incorrect syntax near " + token + expecting + positionInfo + check;
    }

    return new UniformPair<String>(message, expression);
}

From source file:com.facebook.presto.sql.parser.ErrorHandler.java

License:Apache License

@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
        String message, RecognitionException e) {
    try {//from  w  w w.  java  2s . c o m
        Parser parser = (Parser) recognizer;

        ATN atn = parser.getATN();

        ATNState currentState;
        Token currentToken;
        RuleContext context;

        if (e != null) {
            currentState = atn.states.get(e.getOffendingState());
            currentToken = e.getOffendingToken();
            context = e.getCtx();

            if (e instanceof NoViableAltException) {
                currentToken = ((NoViableAltException) e).getStartToken();
            }
        } else {
            currentState = atn.states.get(parser.getState());
            currentToken = parser.getCurrentToken();
            context = parser.getContext();
        }

        Analyzer analyzer = new Analyzer(atn, parser.getVocabulary(), specialRules, specialTokens, ignoredRules,
                parser.getTokenStream());
        Multimap<Integer, String> candidates = analyzer.process(currentState, currentToken.getTokenIndex(),
                context);

        // pick the candidate tokens associated largest token index processed (i.e., the path that consumed the most input)
        String expected = candidates.asMap().entrySet().stream().max(Comparator.comparing(Map.Entry::getKey))
                .get().getValue().stream().sorted().collect(Collectors.joining(", "));

        message = String.format("mismatched input '%s'. Expecting: %s", ((Token) offendingSymbol).getText(),
                expected);
    } catch (Exception exception) {
        LOG.error(exception,
                "Unexpected failure when handling parsing error. This is likely a bug in the implementation");
    }

    throw new ParsingException(message, e, line, charPositionInLine);
}

From source file:com.jmcalc.utils.DescriptiveErrorListener.java

License:Apache License

@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
        String msg, RecognitionException e) {
    CommonToken offendingToken = ((CommonToken) offendingSymbol);
    String sourceName = offendingToken.getInputStream()
            .getText(new Interval(0, offendingToken.getInputStream().size()));
    if (e != null) {
        throw new ExpressionParseException(sourceName + " -> line " + line + ":" + charPositionInLine
                + " mismatched input '" + e.getOffendingToken().getText() + "'");
    } else {/*from   w w w  .ja va2  s  . c  o m*/
        throw new ExpressionParseException(sourceName + " -> line " + line + ":" + charPositionInLine
                + " unexpected token: " + offendingToken.getText());
    }
}

From source file:com.nextbreakpoint.nextfractal.contextfree.compiler.CompilerErrorStrategy.java

License:Open Source License

@Override
public void reportError(Parser recognizer, RecognitionException e) {
    String message = generateErrorMessage("Parse failed", recognizer);
    CompilerError error = new CompilerError(CompilerError.ErrorType.CFDG_COMPILER,
            e.getOffendingToken().getLine(), e.getOffendingToken().getCharPositionInLine(),
            e.getOffendingToken().getStartIndex(),
            recognizer.getCurrentToken().getStopIndex() - recognizer.getCurrentToken().getStartIndex(),
            message);// w w w .ja va 2  s  . com
    logger.log(Level.FINE, error.toString(), e);
    errors.add(error);
}

From source file:com.nextbreakpoint.nextfractal.mandelbrot.compiler.CompilerErrorStrategy.java

License:Open Source License

@Override
public void reportError(Parser recognizer, RecognitionException e) {
    String message = generateErrorMessage("Parse failed", recognizer);
    CompilerError error = new CompilerError(CompilerError.ErrorType.M_COMPILER, e.getOffendingToken().getLine(),
            e.getOffendingToken().getCharPositionInLine(), e.getOffendingToken().getStartIndex(),
            recognizer.getCurrentToken().getStopIndex() - recognizer.getCurrentToken().getStartIndex(),
            message);//ww  w.j  ava2  s  .com
    logger.log(Level.FINE, error.toString(), e);
    errors.add(error);
}

From source file:com.oembedler.moon.graphql.engine.execute.GraphQLQueryExecutor.java

License:Open Source License

public <T extends ExecutionResult> T execute() {

    assertNotNull(arguments, "Arguments can't be null");
    LOGGER.info("Executing request. Operation name: {}. Request: {} ", operationName, requestQuery);

    Parser parser = new Parser();
    Document document;/*  w ww  .j a  v  a 2s .  c  o m*/
    try {
        document = parser.parseDocument(requestQuery);
    } catch (ParseCancellationException e) {
        RecognitionException recognitionException = (RecognitionException) e.getCause();
        SourceLocation sourceLocation = new SourceLocation(recognitionException.getOffendingToken().getLine(),
                recognitionException.getOffendingToken().getCharPositionInLine());
        InvalidSyntaxError invalidSyntaxError = new InvalidSyntaxError(sourceLocation);
        return (T) new GraphQLRxExecutionResult(Observable.just(null),
                Observable.just(Arrays.asList(invalidSyntaxError)));
    }

    Validator validator = new Validator();
    List<ValidationError> validationErrors = validator.validateDocument(graphQLSchemaHolder.getGraphQLSchema(),
            document);
    if (validationErrors.size() > 0) {
        return (T) new GraphQLRxExecutionResult(Observable.just(null), Observable.just(validationErrors));
    }

    if (executionStrategy == null) {
        if (executorService == null) {
            executionStrategy = new GraphQLDefaultRxExecutionStrategy(graphQLSchemaHolder, maxQueryDepth,
                    maxQueryComplexity);
        } else {
            executionStrategy = new GraphQLExecutorServiceRxExecutionStrategy(graphQLSchemaHolder,
                    executorService, maxQueryDepth, maxQueryComplexity);
        }
    }

    RxExecution execution = new RxExecution(graphQLSchemaHolder, maxQueryDepth, maxQueryComplexity,
            executionStrategy);
    ExecutionResult executionResult = execution.execute(graphQLSchemaHolder.getGraphQLSchema(), context,
            document, operationName, arguments);

    return (T) (executionResult instanceof GraphQLRxExecutionResult ? executionResult
            : new GraphQLRxExecutionResult(Observable.just(executionResult.getData()),
                    Observable.just(executionResult.getErrors())));
}

From source file:com.spotify.heroic.grammar.CoreQueryParser.java

License:Apache License

private ParseException toParseException(final RecognitionException e) {
    final Token token = e.getOffendingToken();

    if (token.getType() == HeroicQueryLexer.UnterminatedQutoedString) {
        return new ParseException(String.format("unterminated string: %s", token.getText()), null,
                token.getLine(), token.getCharPositionInLine());
    }//  ww  w.j a v a 2  s  .co m

    return new ParseException("unexpected token: " + token.getText(), null, token.getLine(),
            token.getCharPositionInLine());
}