Example usage for org.antlr.v4.runtime InputMismatchException InputMismatchException

List of usage examples for org.antlr.v4.runtime InputMismatchException InputMismatchException

Introduction

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

Prototype

public InputMismatchException(Parser recognizer) 

Source Link

Usage

From source file:com.github.jknack.handlebars.internal.HbsErrorStrategy.java

License:Apache License

@Override
public Token recoverInline(final Parser recognizer) {
    // always fail
    throw new InputMismatchException(recognizer);
}

From source file:com.sample.JavaErrorStrategy.java

License:BSD License

/**
 * The default implementation of {@link ANTLRErrorStrategy#sync} makes sure
 * that the current lookahead symbol is consistent with what were expecting
 * at this point in the ATN. You can call this anytime but ANTLR only
 * generates code to check before subrules/loops and each iteration.
 *
 * <p>// w w  w . j av a2 s.  com
 * Implements Jim Idle's magic sync mechanism in closures and optional
 * subrules. E.g.,
 * </p>
 *
 * <pre>
 * a : sync ( stuff sync )* ;
 * sync : {consume to what can follow sync} ;
 * </pre>
 *
 * At the start of a sub rule upon error, {@link #sync} performs single
 * token deletion, if possible. If it can't do that, it bails on the current
 * rule and uses the default error recovery, which consumes until the
 * resynchronization set of the current rule.
 *
 * <p>
 * If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
 * with an empty alternative), then the expected set includes what follows
 * the subrule.
 * </p>
 *
 * <p>
 * During loop iteration, it consumes until it sees a token that can start a
 * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
 * stay in the loop as long as possible.
 * </p>
 *
 * <p>
 * <strong>ORIGINS</strong>
 * </p>
 *
 * <p>
 * Previous versions of ANTLR did a poor job of their recovery within loops.
 * A single mismatch token or missing token would force the parser to bail
 * out of the entire rules surrounding the loop. So, for rule
 * </p>
 *
 * <pre>
 * classDef : 'class' ID '{' member* '}'
 * </pre>
 *
 * input with an extra token between members would force the parser to
 * consume until it found the next class definition rather than the next
 * member definition of the current class.
 *
 * <p>
 * This functionality cost a little bit of effort because the parser has to
 * compare token set at the start of the loop and at each iteration. If for
 * some reason speed is suffering for you, you can turn off this
 * functionality by simply overriding this method as a blank { }.
 * </p>
 */
@Override
public void sync(Parser recognizer) throws RecognitionException {
    ATNState s = recognizer.getInterpreter().atn.states.get(recognizer.getState());
    // System.err.println("sync @ "+s.stateNumber+"="+s.getClass().getSimpleName());
    // If already recovering, don't try to sync
    if (inErrorRecoveryMode(recognizer)) {
        return;
    }

    TokenStream tokens = recognizer.getInputStream();
    int la = tokens.LA(1);

    // try cheaper subset first; might get lucky. seems to shave a wee bit
    // off
    if (recognizer.getATN().nextTokens(s).contains(la) || la == Token.EOF)
        return;

    // Return but don't end recovery. only do that upon valid token match
    if (recognizer.isExpectedToken(la)) {
        return;
    }

    switch (s.getStateType()) {
    case ATNState.BLOCK_START:
    case ATNState.STAR_BLOCK_START:
    case ATNState.PLUS_BLOCK_START:
    case ATNState.STAR_LOOP_ENTRY:
        // report error and recover if possible
        if (singleTokenDeletion(recognizer) != null) {
            return;
        }

        throw new InputMismatchException(recognizer);

    case ATNState.PLUS_LOOP_BACK:
    case ATNState.STAR_LOOP_BACK:
        // System.err.println("at loop back: "+s.getClass().getSimpleName());
        reportUnwantedToken(recognizer);
        IntervalSet expecting = recognizer.getExpectedTokens();
        IntervalSet whatFollowsLoopIterationOrRule = expecting.or(getErrorRecoverySet(recognizer));
        consumeUntil(recognizer, whatFollowsLoopIterationOrRule);
        break;

    default:
        // do nothing if we can't identify the exact kind of ATN state
        break;
    }
}

From source file:com.sample.JavaErrorStrategy.java

License:BSD License

/**
 * {@inheritDoc}//from   w  w w  . j  av  a  2 s . c om
 *
 * <p>
 * The default implementation attempts to recover from the mismatched input
 * by using single token insertion and deletion as described below. If the
 * recovery attempt fails, this method throws an
 * {@link InputMismatchException}.
 * </p>
 *
 * <p>
 * <strong>EXTRA TOKEN</strong> (single token deletion)
 * </p>
 *
 * <p>
 * {@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
 * right token, however, then assume {@code LA(1)} is some extra spurious
 * token and delete it. Then consume and return the next token (which was
 * the {@code LA(2)} token) as the successful result of the match operation.
 * </p>
 *
 * <p>
 * This recovery strategy is implemented by {@link #singleTokenDeletion}.
 * </p>
 *
 * <p>
 * <strong>MISSING TOKEN</strong> (single token insertion)
 * </p>
 *
 * <p>
 * If current token (at {@code LA(1)}) is consistent with what could come
 * after the expected {@code LA(1)} token, then assume the token is missing
 * and use the parser's {@link TokenFactory} to create it on the fly. The
 * "insertion" is performed by returning the created token as the successful
 * result of the match operation.
 * </p>
 *
 * <p>
 * This recovery strategy is implemented by {@link #singleTokenInsertion}.
 * </p>
 *
 * <p>
 * <strong>EXAMPLE</strong>
 * </p>
 *
 * <p>
 * For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
 * the parser returns from the nested call to {@code expr}, it will have
 * call chain:
 * </p>
 *
 * <pre>
 * stat &rarr; expr &rarr; atom
 * </pre>
 *
 * and it will be trying to match the {@code ')'} at this point in the
 * derivation:
 *
 * <pre>
 * =&gt; ID '=' '(' INT ')' ('+' atom)* ';'
 *                    ^
 * </pre>
 *
 * The attempt to match {@code ')'} will fail when it sees {@code ';'} and
 * call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}
 * is in the set of tokens that can follow the {@code ')'} token reference
 * in rule {@code atom}. It can assume that you forgot the {@code ')'}.
 */
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    // SINGLE TOKEN DELETION
    Token matchedSymbol = singleTokenDeletion(recognizer);
    if (matchedSymbol != null) {
        // we have deleted the extra token.
        // now, move past ttype token as if all were ok
        recognizer.consume();
        return matchedSymbol;
    }

    // SINGLE TOKEN INSERTION
    if (singleTokenInsertion(recognizer)) {
        return getMissingSymbol(recognizer);
    }

    // even that didn't work; must throw the exception
    throw new InputMismatchException(recognizer);
}

From source file:eagle.query.parser.EagleANTLRErrorStrategy.java

License:Apache License

/** Make sure we don't attempt to recover inline; if the parser
 *  successfully recovers, it won't throw an exception.
 *///w  ww .  j  av a2  s. com
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    InputMismatchException e = new InputMismatchException(recognizer);
    for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
        context.exception = e;
    }
    return super.recoverInline(recognizer);
}

From source file:io.prestosql.sql.parser.SqlParser.java

License:Apache License

private Node invokeParser(String name, String sql, Function<SqlBaseParser, ParserRuleContext> parseFunction,
        ParsingOptions parsingOptions) {
    try {//from   w  w w . j  av a 2s .com
        SqlBaseLexer lexer = new SqlBaseLexer(new CaseInsensitiveStream(CharStreams.fromString(sql)));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        SqlBaseParser parser = new SqlBaseParser(tokenStream);

        // Override the default error strategy to not attempt inserting or deleting a token.
        // Otherwise, it messes up error reporting
        parser.setErrorHandler(new DefaultErrorStrategy() {
            @Override
            public Token recoverInline(Parser recognizer) throws RecognitionException {
                if (nextTokensContext == null) {
                    throw new InputMismatchException(recognizer);
                } else {
                    throw new InputMismatchException(recognizer, nextTokensState, nextTokensContext);
                }
            }
        });

        parser.addParseListener(new PostProcessor(Arrays.asList(parser.getRuleNames())));

        lexer.removeErrorListeners();
        lexer.addErrorListener(LEXER_ERROR_LISTENER);

        parser.removeErrorListeners();

        if (enhancedErrorHandlerEnabled) {
            parser.addErrorListener(PARSER_ERROR_HANDLER);
        } else {
            parser.addErrorListener(LEXER_ERROR_LISTENER);
        }

        ParserRuleContext tree;
        try {
            // first, try parsing with potentially faster SLL mode
            parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
            tree = parseFunction.apply(parser);
        } catch (ParseCancellationException ex) {
            // if we fail, parse with LL mode
            tokenStream.reset(); // rewind input stream
            parser.reset();

            parser.getInterpreter().setPredictionMode(PredictionMode.LL);
            tree = parseFunction.apply(parser);
        }

        return new AstBuilder(parsingOptions).visit(tree);
    } catch (StackOverflowError e) {
        throw new ParsingException(name + " is too large (stack overflow while parsing)");
    }
}

From source file:it.polimi.tower4clouds.rules.ErrorStrategy.java

License:Apache License

/** Make sure we don't attempt to recover inline; if the parser
  *  successfully recovers, it won't throw an exception.
  *//* ww w. ja v  a  2  s  .  c o  m*/
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    throw new RuntimeException(new InputMismatchException(recognizer));
}

From source file:org.apache.syncope.core.logic.scim.SCIMFilterErrorHandler.java

License:Apache License

@Override
public Token recoverInline(final Parser recognizer) throws RecognitionException {
    throw new InputMismatchException(recognizer);
}

From source file:org.ballerinalang.langserver.completions.BallerinaCustomErrorStrategy.java

License:Open Source License

@Override
protected void setContextException(Parser parser) {
    // Here the type of the exception is not important.
    InputMismatchException e = new InputMismatchException(parser);
    ParserRuleContext context = parser.getContext();
    // Note: Here we forcefully set the exception to null, in order to avoid the callable unit body being null at
    // the run time
    if (context instanceof BallerinaParser.CallableUnitBodyContext) {
        context.exception = null;//from www . j  ava 2 s.c om
        return;
    }
    context.exception = e;
    // Note: Following check added, when the context is variable definition and the type name context is hit,
    // We need to set the error for the variable definition as well.
    if (context.getParent() instanceof BallerinaParser.VariableDefinitionStatementContext) {
        context.getParent().exception = e;
        return;
    }

    if (context instanceof BallerinaParser.NameReferenceContext) {
        setContextIfConnectorInit(context, e);
    }
}

From source file:org.ballerinalang.util.parser.BallerinaParserErrorStrategy.java

License:Open Source License

/**
 * Set an exception in the parser context. This is later used at {@link BLangAntlr4Listener} level
 * to determine whether the parse exception has occured and is in error state.
 * /*from  ww  w  .j  a va2  s  .  co  m*/
 * @param parser    Current parser
 */
private void setContextException(Parser parser) {
    // Here the type of the exception is not important. 
    InputMismatchException e = new InputMismatchException(parser);
    for (ParserRuleContext context = parser.getContext(); context != null; context = context.getParent()) {
        context.exception = e;
    }
}

From source file:org.hawkular.metrics.api.jaxrs.influx.query.parse.QueryErrorHandler.java

License:Apache License

@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    throw new InputMismatchException(recognizer);
}