Search in sources :

Example 1 with InputMismatchException

use of org.antlr.v4.runtime.InputMismatchException in project claw-compiler by C2SM-RCM.

the class ClawLanguage method analyze.

/**
   * Analyze a raw string input and match it with the CLAW language definition.
   *
   * @param rawPragma A raw pragma statement to be analyzed against the CLAW
   *                  language.
   * @param lineno    Line number of the pragma statement.
   * @param generator Accelerator directive generator.
   * @param target    Target that influences the code transformation.
   * @return A ClawLanguage object with the corresponding extracted information.
   * @throws IllegalDirectiveException If directive does not follow the CLAW
   *                                   language specification.
   */
private static ClawLanguage analyze(String rawPragma, int lineno, AcceleratorGenerator generator, Target target) throws IllegalDirectiveException {
    // Remove additional claw keyword
    rawPragma = nakenize(rawPragma);
    // Discard the ignored code after the claw ignore directive
    if (rawPragma.toLowerCase().contains(IGNORE)) {
        rawPragma = rawPragma.substring(0, rawPragma.toLowerCase().indexOf(IGNORE) + IGNORE.length());
    }
    // Instantiate the lexer with the raw string input
    ClawLexer lexer = new ClawLexer(CharStreams.fromString(rawPragma));
    // Get a list of matched tokens
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    // Pass the tokens to the parser
    ClawParser parser = new ClawParser(tokens);
    parser.setErrorHandler(new BailErrorStrategy());
    parser.removeErrorListeners();
    try {
        // Start the parser analysis from the "analyze" entry point
        ClawParser.AnalyzeContext ctx = parser.analyze();
        // Get the ClawLanguage object return by the parser after analysis.
        ctx.l.setAcceleratorGenerator(generator);
        ctx.l.setTarget(target);
        return ctx.l;
    } catch (ParseCancellationException pcex) {
        if (pcex.getCause() instanceof InputMismatchException) {
            InputMismatchException imex = (InputMismatchException) pcex.getCause();
            throw new IllegalDirectiveException(getTokens(imex.getExpectedTokens(), parser), lineno, imex.getOffendingToken().getCharPositionInLine());
        } else if (pcex.getCause() instanceof NoViableAltException) {
            NoViableAltException nvex = (NoViableAltException) pcex.getCause();
            throw new IllegalDirectiveException(nvex.getOffendingToken(), getTokens(nvex.getExpectedTokens(), parser), lineno, nvex.getOffendingToken().getCharPositionInLine());
        }
        throw new IllegalDirectiveException(rawPragma, "Unsupported construct", lineno, 0);
    }
}
Also used : ClawParser(cx2x.translator.language.parser.ClawParser) IllegalDirectiveException(cx2x.xcodeml.exception.IllegalDirectiveException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) ClawLexer(cx2x.translator.language.parser.ClawLexer)

Example 2 with InputMismatchException

use of org.antlr.v4.runtime.InputMismatchException in project ballerina by ballerina-lang.

the class LSCustomErrorStrategy method setContextException.

@Override
protected void setContextException(Parser parser) {
    // Here the type of the exception is not important.
    InputMismatchException e = new InputMismatchException(parser);
    ParserRuleContext context = parser.getContext();
    // the run time
    if (context instanceof BallerinaParser.CallableUnitBodyContext) {
        context.exception = null;
        return;
    }
    context.exception = e;
    // 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);
    } else if (context instanceof BallerinaParser.ExpressionContext) {
        setContextIfConditionalStatement(context, e);
    }
}
Also used : ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) InputMismatchException(org.antlr.v4.runtime.InputMismatchException) BallerinaParser(org.wso2.ballerinalang.compiler.parser.antlr4.BallerinaParser)

Example 3 with InputMismatchException

use of org.antlr.v4.runtime.InputMismatchException in project ballerina by ballerina-lang.

the class BallerinaParserErrorStrategy method reportInputMismatch.

@Override
public void reportInputMismatch(Parser parser, InputMismatchException e) {
    setContextException(parser);
    Token offendingToken = e.getOffendingToken();
    String mismatchedToken = getTokenErrorDisplay(offendingToken);
    String expectedToken = e.getExpectedTokens().toString(parser.getVocabulary());
    DiagnosticPos pos = getPosition(offendingToken);
    dlog.error(pos, DiagnosticCode.MISMATCHED_INPUT, mismatchedToken, expectedToken);
}
Also used : DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) Token(org.antlr.v4.runtime.Token)

Example 4 with InputMismatchException

use of org.antlr.v4.runtime.InputMismatchException in project beetl2.0 by javamonkey.

the class BeetlAntlrErrorStrategy method reportError.

@Override
public void reportError(Parser recognizer, RecognitionException e) {
    // yet successfully, don't report any errors.
    if (inErrorRecoveryMode(recognizer)) {
        // don't report spurious errors
        return;
    }
    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());
        exception.pushToken(this.getGrammarToken(e.getOffendingToken()));
        throw exception;
    }
}
Also used : BeetlException(org.beetl.core.exception.BeetlException) NoViableAltException(org.antlr.v4.runtime.NoViableAltException) FailedPredicateException(org.antlr.v4.runtime.FailedPredicateException) InputMismatchException(org.antlr.v4.runtime.InputMismatchException)

Example 5 with InputMismatchException

use of org.antlr.v4.runtime.InputMismatchException in project presto by prestodb.

the class SqlParser method invokeParser.

private Node invokeParser(String name, String sql, Function<SqlBaseParser, ParserRuleContext> parseFunction, ParsingOptions parsingOptions) {
    try {
        SqlBaseLexer lexer = new SqlBaseLexer(new CaseInsensitiveStream(CharStreams.fromString(sql)));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        SqlBaseParser parser = new SqlBaseParser(tokenStream);
        initializer.accept(lexer, parser);
        // 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()), parsingOptions.getWarningConsumer()));
        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
            // rewind input stream
            tokenStream.reset();
            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)");
    }
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) Token(org.antlr.v4.runtime.Token) CommonToken(org.antlr.v4.runtime.CommonToken) InputMismatchException(org.antlr.v4.runtime.InputMismatchException) Parser(org.antlr.v4.runtime.Parser) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) DefaultErrorStrategy(org.antlr.v4.runtime.DefaultErrorStrategy) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Aggregations

InputMismatchException (org.antlr.v4.runtime.InputMismatchException)10 NoViableAltException (org.antlr.v4.runtime.NoViableAltException)5 Token (org.antlr.v4.runtime.Token)5 ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)3 ATNState (org.antlr.v4.runtime.atn.ATNState)3 IntervalSet (org.antlr.v4.runtime.misc.IntervalSet)3 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)3 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)2 FailedPredicateException (org.antlr.v4.runtime.FailedPredicateException)2 ParseTreePatternMatcher (org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher)2 BeetlException (org.beetl.core.exception.BeetlException)2 Test (org.junit.Test)2 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)2 IllegalDirectiveException (claw.tatsu.xcodeml.exception.IllegalDirectiveException)1 ClawLexer (claw.wani.language.parser.ClawLexer)1 ClawParser (claw.wani.language.parser.ClawParser)1 ClawLexer (cx2x.translator.language.parser.ClawLexer)1 ClawParser (cx2x.translator.language.parser.ClawParser)1 IllegalDirectiveException (cx2x.xcodeml.exception.IllegalDirectiveException)1 ParseException (java.text.ParseException)1