Example usage for org.antlr.v4.runtime Parser getContext

List of usage examples for org.antlr.v4.runtime Parser getContext

Introduction

In this page you can find the example usage for org.antlr.v4.runtime Parser getContext.

Prototype

public ParserRuleContext getContext() 

Source Link

Usage

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  ww  w  .  j ava 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.sample.JavaErrorStrategy.java

License:BSD License

/**
 * This is called by {@link #reportError} when the exception is a
 * {@link FailedPredicateException}./*from w w  w.  j  a va  2s. com*/
 *
 * @see #reportError
 *
 * @param recognizer
 *            the parser instance
 * @param e
 *            the recognition exception
 */
protected void reportFailedPredicate(@NotNull Parser recognizer, @NotNull FailedPredicateException e) {
    String ruleName = recognizer.getRuleNames()[recognizer.getContext().getRuleIndex()];
    String msg = "rule " + ruleName + " " + e.getMessage();
    recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);
}

From source file:com.sample.JavaErrorStrategy.java

License:BSD License

/**
 * This method implements the single-token insertion inline error recovery
 * strategy. It is called by {@link #recoverInline} if the single-token
 * deletion strategy fails to recover from the mismatched input. If this
 * method returns {@code true}, {@code recognizer} will be in error recovery
 * mode.// ww  w  . j av a 2 s . c o  m
 *
 * <p>
 * This method determines whether or not single-token insertion is viable by
 * checking if the {@code LA(1)} input symbol could be successfully matched
 * if it were instead the {@code LA(2)} symbol. If this method returns
 * {@code true}, the caller is responsible for creating and inserting a
 * token with the correct type to produce this behavior.
 * </p>
 *
 * @param recognizer
 *            the parser instance
 * @return {@code true} if single-token insertion is a viable recovery
 *         strategy for the current mismatched input, otherwise
 *         {@code false}
 */
protected boolean singleTokenInsertion(@NotNull Parser recognizer) {
    int currentSymbolType = recognizer.getInputStream().LA(1);
    // if current token is consistent with what could come after current
    // ATN state, then we know we're missing a token; error recovery
    // is free to conjure up and insert the missing token
    ATNState currentState = recognizer.getInterpreter().atn.states.get(recognizer.getState());
    ATNState next = currentState.transition(0).target;
    ATN atn = recognizer.getInterpreter().atn;
    IntervalSet expectingAtLL2 = atn.nextTokens(next, recognizer.getContext());
    // System.out.println("LT(2) set="+expectingAtLL2.toString(recognizer.getTokenNames()));
    if (expectingAtLL2.contains(currentSymbolType)) {
        reportMissingToken(recognizer);
        return true;
    }
    return false;
}

From source file:com.sample.JavaErrorStrategy.java

License:BSD License

@NotNull
protected IntervalSet getErrorRecoverySet(@NotNull Parser recognizer) {
    ATN atn = recognizer.getInterpreter().atn;
    RuleContext ctx = recognizer.getContext();
    IntervalSet recoverSet = new IntervalSet();
    while (ctx != null && ctx.invokingState >= 0) {
        // compute what follows who invoked us
        ATNState invokingState = atn.states.get(ctx.invokingState);
        RuleTransition rt = (RuleTransition) invokingState.transition(0);
        IntervalSet follow = atn.nextTokens(rt.followState);
        recoverSet.addAll(follow);//from   w  w  w  .ja va2s .  c o m
        ctx = ctx.parent;
    }
    recoverSet.remove(Token.EPSILON);
    // System.out.println("recover set "+recoverSet.toString(recognizer.getTokenNames()));
    return recoverSet;
}

From source file:compile.compilersource.ExceptionErrorStrategy.java

@Override
public void sync(Parser recognizer) {
    if (recognizer.getContext() instanceof ParserRuleContext) {
        super.sync(recognizer);
    }//from  w  ww  .  jav a  2  s  .  c  om
}

From source file:de.up.ling.irtg.codec.ExceptionErrorStrategy.java

@Override
public void reportInputMismatch(Parser recognizer, InputMismatchException e) throws RecognitionException {
    String msg = getTokenPosition(e.getOffendingToken()) + ": mismatched input "
            + getTokenErrorDisplay(e.getOffendingToken());
    msg += " expecting one of " + e.getExpectedTokens().toString(recognizer.getTokenNames());
    RecognitionException ex = new RecognitionException(msg, recognizer, recognizer.getInputStream(),
            recognizer.getContext());
    ex.initCause(e);/* w  ww .  j a v  a2  s . co m*/
    throw ex;
}

From source file:de.up.ling.irtg.codec.ExceptionErrorStrategy.java

@Override
public void reportMissingToken(Parser recognizer) {
    beginErrorCondition(recognizer);/*from   www . ja v a2 s.  co m*/
    Token t = recognizer.getCurrentToken();
    IntervalSet expecting = getExpectedTokens(recognizer);
    String msg = getTokenPosition(t) + ": missing " + expecting.toString(recognizer.getTokenNames()) + " at "
            + getTokenErrorDisplay(t);
    throw new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
}

From source file:de.up.ling.irtg.codec.ExceptionErrorStrategy.java

@Override
protected void reportNoViableAlternative(Parser parser, NoViableAltException nvae) {
    Token t = parser.getCurrentToken();/*from w w w . j a v  a 2s  . c  o m*/
    IntervalSet expecting = getExpectedTokens(parser);
    String msg = getTokenPosition(t) + ": no viable alternative: " + expecting.toString(parser.getTokenNames())
            + " at " + getTokenErrorDisplay(t);
    throw new RecognitionException(msg, parser, parser.getInputStream(), parser.getContext());
}

From source file:de.up.ling.irtg.codec.ExceptionErrorStrategy.java

@Override
protected void reportFailedPredicate(Parser parser, FailedPredicateException fpe) {
    Token t = parser.getCurrentToken();//from   w  ww . j a va  2 s.  com
    IntervalSet expecting = getExpectedTokens(parser);
    String msg = getTokenPosition(t) + ": failed predicate '" + fpe.getMessage() + "': "
            + expecting.toString(parser.getTokenNames()) + " at " + getTokenErrorDisplay(t);
    throw new RecognitionException(msg, parser, parser.getInputStream(), parser.getContext());
}

From source file:de.up.ling.irtg.codec.ExceptionErrorStrategy.java

@Override
protected void reportUnwantedToken(Parser parser) {
    Token t = parser.getCurrentToken();//from w w  w  . j a  v a  2s. c  o  m
    IntervalSet expecting = getExpectedTokens(parser);
    String msg = getTokenPosition(t) + ": expected token " + expecting.toString(parser.getTokenNames())
            + ", but got " + getTokenErrorDisplay(t) + ".";
    throw new RecognitionException(msg, parser, parser.getInputStream(), parser.getContext());
}