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:com.sri.ai.praise.sgsolver.solver.HOGMQueryRunner.java

License:Open Source License

public List<HOGMQueryResult> query() {
    List<HOGMQueryResult> result = new ArrayList<>();
    Expression queryExpr = null;/*from ww w.  jav a2 s .  c  om*/
    //
    ParsedHOGModel parsedModel = null;
    for (String query : queries) {
        long startQuery = System.currentTimeMillis();
        List<HOGMQueryError> errors = new ArrayList<>();
        try {
            if (model == null || model.trim().equals("")) {
                errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL, "Model not specified", 0, 0, 0));
            }

            if (query == null || query.trim().equals("")) {
                errors.add(new HOGMQueryError(HOGMQueryError.Context.QUERY, "Query not specified", 0, 0, 0));
            }

            if (errors.size() == 0) {
                HOGMParserWrapper parser = new HOGMParserWrapper();
                if (parsedModel == null) {
                    parsedModel = parser.parseModel(model,
                            new QueryErrorListener(HOGMQueryError.Context.MODEL, errors));
                }
                queryExpr = parser.parseTerm(query,
                        new QueryErrorListener(HOGMQueryError.Context.QUERY, errors));

                if (errors.size() == 0) {
                    FactorsAndTypes factorsAndTypes = new ExpressionFactorsAndTypes(parsedModel);
                    if (!canceled) {
                        inferencer = new InferenceForFactorGraphAndEvidence(factorsAndTypes, false, null, true,
                                getOptionalTheory());

                        startQuery = System.currentTimeMillis();
                        Expression marginal = inferencer.solve(queryExpr);

                        result.add(new HOGMQueryResult(query, queryExpr, parsedModel, marginal,
                                System.currentTimeMillis() - startQuery));
                    }
                }
            }
        } catch (RecognitionException re) {
            errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL, re.getMessage(),
                    re.getOffendingToken().getLine(), re.getOffendingToken().getStartIndex(),
                    re.getOffendingToken().getStopIndex()));
        } catch (UnableToParseAllTheInputError utpai) {
            errors.add(new HOGMQueryError(utpai));
        } catch (HOGModelException me) {
            me.getErrors().forEach(modelError -> {
                String inStatement = modelError.getInStatementInfo().statement.toString();
                String inSource = modelError.getInStatementInfo().sourceText;
                String inSubStatement = modelError.getMessage();
                String inInfo = "";
                if (inSubStatement.equals("") || inSubStatement.equals(inSource)) {
                    inInfo = " in '" + inStatement + "'";
                } else {
                    inInfo = " ('" + inSubStatement + "') in '" + inStatement + "'";
                }
                if (!inSource.replaceAll(" ", "").replaceAll(";", "").equals(inStatement.replaceAll(" ", ""))) {
                    inInfo = inInfo + " derived from '" + inSource + "'";
                }
                errors.add(new HOGMQueryError(HOGMQueryError.Context.MODEL,
                        modelError.getErrorType().formattedMessage() + inInfo,
                        modelError.getInStatementInfo().line, modelError.getInStatementInfo().startIndex,
                        modelError.getInStatementInfo().endIndex));
            });
        } catch (Throwable t) {
            // Unexpected
            errors.add(new HOGMQueryError(t));
        }

        if (errors.size() > 0) {
            result.add(new HOGMQueryResult(query, queryExpr, parsedModel, errors,
                    System.currentTimeMillis() - startQuery));
        }
    }

    return result;
}

From source file:excecoes.SyntaxError.java

public SyntaxError(String message, RecognitionException e, int line, int charPositionInLine) {
    super(message, e.getRecognizer(), e.getInputStream(), (ParserRuleContext) e.getCtx());
    this.setOffendingToken(e.getOffendingToken());
    this.initCause(e);
    this.setLine(line);
    this.setCharPositionInLine(charPositionInLine);

}

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

License:Apache 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
    }//from   w w w. j  a  v a 2  s  .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 {
        System.err.println("unknown recognition error type: " + e.getClass().getName());
        recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }
    //Listener listener = new Listener();
    //listener.syntaxError(e.getRecognizer(), e.getOffendingToken(), e.getOffendingToken().getLine(), e.getOffendingToken().getCharPositionInLine(), e.getMessage(), e);
}

From source file:kr.ac.korea.dbserver.parser.SQLErrorStrategy.java

License:Apache 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)) {
        return; // don't report spurious errors
    }/*from   w  w w  . jav a  2 s .  c o m*/
    beginErrorCondition(recognizer);
    if (e instanceof NoViableAltException) {
        reportNoViableAltException(recognizer, (NoViableAltException) e);
    } else if (e instanceof InputMismatchException) {
        reportInputMismatchException(recognizer, (InputMismatchException) e);
    } else if (e instanceof FailedPredicateException) {
        reportFailedPredicate(recognizer, (FailedPredicateException) e);
    } else {
        recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }
}

From source file:kr.simula.formula.ide.ast.SyntaxErrorAdapter.java

License:Apache License

protected static IProblem makeProblem(String fileName, String msg, RecognitionException e) {
    Token offendingToken = e.getOffendingToken();
    IProblem problem = new DefaultProblem(fileName, msg, IProblem.Internal, new String[0],
            ProblemSeverities.Fatal, offendingToken.getLine(), offendingToken.getCharPositionInLine(),
            offendingToken.getStartIndex(), offendingToken.getStopIndex());
    return problem;
}

From source file:mbtarranger.languages.mcrlOuter.ErrorReporter.java

License:Open Source License

private void toBadbank(Parser arg0, RecognitionException arg1) {
    // if (arg1 instanceof NoViableAltException){
    // NoViableAltException novex = (NoViableAltException) arg1;
    StringBuilder sb = new StringBuilder();
    for (int tk : arg1.getExpectedTokens().toArray()) {
        sb.append(arg0.getTokenNames()[tk]);
        sb.append(" ");
    }//  w w w.  ja v  a 2s  .  c  o  m
    String positionInfo = "";
    try {
        positionInfo = "startline " +
        /* [@8,50:50='.',<94>,3:5] */
                arg1.getOffendingToken().toString().split(">,")[1].split("]")[0];
    } catch (Exception ex) {
    }
    String msg = String.format("%s, mal input: '%s', expected '%s' ", positionInfo,
            getTokenErrorDisplay(arg1.getOffendingToken()), sb.toString());
    BadBank.reportProblem(arg1.getOffendingToken().getLine(), arrFile, msg);
}

From source file:mbtarranger.languages.promelaOuter.ErrorReporter.java

License:Open Source License

private void toBadbank(Parser arg0, RecognitionException arg1) {
    //if (arg1 instanceof NoViableAltException){
    //NoViableAltException novex = (NoViableAltException) arg1;
    StringBuilder sb = new StringBuilder();
    for (int tk : arg1.getExpectedTokens().toArray()) {
        sb.append(arg0.getTokenNames()[tk]);
        sb.append(" ");
    }//from w w w.  j  a va  2  s  . com
    String positionInfo = "";
    try {
        positionInfo = "startline " +
        /* [@8,50:50='.',<94>,3:5] */
                arg1.getOffendingToken().toString().split(">,")[1].split("]")[0];
    } catch (Exception ex) {
    }
    String msg = String.format("%s, mal input: '%s', expected '%s' ", positionInfo,
            getTokenErrorDisplay(arg1.getOffendingToken()), sb.toString());
    BadBank.reportProblem(arg1.getOffendingToken().getLine(), arrFile, msg);
}

From source file:net.openchrom.xxd.processor.supplier.rscripting.ui.editor.RErrorStrategy.java

License:Open Source License

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
    }//from w  w  w .j ava  2s  . 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 error type: " + e.getClass().getName());
        recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }
}

From source file:ninja.leaping.permissionsex.util.glob.Globs.java

License:Apache License

private static GlobNode parse(ANTLRInputStream input) throws GlobParseException {
    GlobLexer lexer = new GlobLexer(input);
    CommonTokenStream tokenStream = new CommonTokenStream(lexer);
    GlobParser parser = new GlobParser(tokenStream);
    parser.setErrorHandler(new BailErrorStrategy());
    ParseTreeWalker walker = new ParseTreeWalker();
    GlobListener listener = new GlobListener();

    try {//  ww w . j a v a  2s .c  o m
        walker.walk(listener, parser.rootGlob());
    } catch (ParseCancellationException e) {
        RecognitionException ex = ((RecognitionException) e.getCause());
        throw new GlobParseException("Unable to parse glob: Error at token " + ex.getOffendingToken().getText()
                + " at position " + ex.getOffendingToken().getLine() + ":"
                + ex.getOffendingToken().getCharPositionInLine(), ex);
    }

    return listener.popNode();
}

From source file:org.apache.lucene.expressions.js.JavascriptParserErrorStrategy.java

License:Apache License

/**
 * Ensures the ANTLR parser will throw an exception after the first error
 *
 * @param recognizer the parser being used
 * @param re the original exception from the parser
 */// ww  w  .j ava  2  s  . c  o  m
@Override
public void recover(Parser recognizer, RecognitionException re) {
    Token token = re.getOffendingToken();
    String message;

    if (token == null) {
        message = "error " + getTokenErrorDisplay(token);
    } else if (re instanceof InputMismatchException) {
        message = "unexpected token " + getTokenErrorDisplay(token) + " on line (" + token.getLine()
                + ") position (" + token.getCharPositionInLine() + ")" + " was expecting one of "
                + re.getExpectedTokens().toString(recognizer.getVocabulary());
    } else if (re instanceof NoViableAltException) {
        if (token.getType() == JavascriptParser.EOF) {
            message = "unexpected end of expression";
        } else {
            message = "invalid sequence of tokens near " + getTokenErrorDisplay(token) + " on line ("
                    + token.getLine() + ") position (" + token.getCharPositionInLine() + ")";
        }
    } else {
        message = " unexpected token near " + getTokenErrorDisplay(token) + " on line (" + token.getLine()
                + ") position (" + token.getCharPositionInLine() + ")";
    }

    ParseException parseException = new ParseException(message, token.getStartIndex());
    parseException.initCause(re);
    throw new RuntimeException(parseException);
}