Search in sources :

Example 11 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project Alpha by alpha-asp.

the class Main method main.

public static void main(String[] args) {
    final Options options = new Options();
    Option numAnswerSetsOption = new Option("n", OPT_NUM_AS, true, "the number of Answer Sets to compute");
    numAnswerSetsOption.setArgName("number");
    numAnswerSetsOption.setRequired(false);
    numAnswerSetsOption.setArgs(1);
    numAnswerSetsOption.setType(Number.class);
    options.addOption(numAnswerSetsOption);
    Option inputOption = new Option("i", OPT_INPUT, true, "read the ASP program from this file");
    inputOption.setArgName("file");
    inputOption.setRequired(true);
    inputOption.setArgs(1);
    inputOption.setType(FileInputStream.class);
    options.addOption(inputOption);
    Option helpOption = new Option("h", OPT_HELP, false, "show this help");
    options.addOption(helpOption);
    Option grounderOption = new Option("g", OPT_GROUNDER, false, "name of the grounder implementation to use");
    grounderOption.setArgs(1);
    grounderOption.setArgName("grounder");
    options.addOption(grounderOption);
    Option solverOption = new Option("s", OPT_SOLVER, false, "name of the solver implementation to use");
    solverOption.setArgs(1);
    solverOption.setArgName("solver");
    options.addOption(solverOption);
    Option filterOption = new Option("f", OPT_FILTER, true, "predicates to show when printing answer sets");
    filterOption.setArgs(1);
    filterOption.setArgName("filter");
    filterOption.setValueSeparator(',');
    options.addOption(filterOption);
    Option sortOption = new Option("sort", OPT_SORT, false, "sort answer sets");
    options.addOption(sortOption);
    Option deterministicOption = new Option("d", OPT_DETERMINISTIC, false, "disable randomness");
    options.addOption(deterministicOption);
    Option seedOption = new Option("e", OPT_SEED, true, "set seed");
    seedOption.setArgName("number");
    seedOption.setRequired(false);
    seedOption.setArgs(1);
    seedOption.setType(Number.class);
    options.addOption(seedOption);
    Option debugFlags = new Option(OPT_DEBUG_INTERNAL_CHECKS, "run additional (time-consuming) safety checks.");
    options.addOption(debugFlags);
    Option branchingHeuristicOption = new Option("b", OPT_BRANCHING_HEURISTIC, false, "name of the branching heuristic to use");
    branchingHeuristicOption.setArgs(1);
    branchingHeuristicOption.setArgName("heuristic");
    options.addOption(branchingHeuristicOption);
    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar alpha.jar\njava -jar alpha_bundled.jar", options);
        System.exit(1);
        return;
    }
    if (commandLine.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        // TODO(flowlo): This is quite optimistic. How do we know that the program
        // really was invoked as "java -jar ..."?
        formatter.printHelp("java -jar alpha.jar OR java -jar alpha-bundled.jar", options);
        System.exit(0);
        return;
    }
    java.util.function.Predicate<Predicate> filter = p -> true;
    if (commandLine.hasOption(OPT_FILTER)) {
        Set<String> desiredPredicates = new HashSet<>(Arrays.asList(commandLine.getOptionValues(OPT_FILTER)));
        filter = p -> {
            return desiredPredicates.contains(p.getPredicateName());
        };
    }
    int limit = 0;
    try {
        Number n = (Number) commandLine.getParsedOptionValue(OPT_NUM_AS);
        if (n != null) {
            limit = n.intValue();
        }
    } catch (ParseException e) {
        bailOut("Failed to parse number of answer sets requested.", e);
    }
    boolean debugInternalChecks = commandLine.hasOption(OPT_DEBUG_INTERNAL_CHECKS);
    ParsedProgram program = null;
    try {
        // Parse all input files and accumulate their results in one ParsedProgram.
        String[] inputFileNames = commandLine.getOptionValues(OPT_INPUT);
        program = parseVisit(new ANTLRFileStream(inputFileNames[0]));
        for (int i = 1; i < inputFileNames.length; i++) {
            program.accumulate(parseVisit(new ANTLRFileStream(inputFileNames[i])));
        }
    } catch (RecognitionException e) {
        // In case a recognitionexception occured, parseVisit will
        // already have printed an error message, so we just exit
        // at this point without further logging.
        System.exit(1);
    } catch (FileNotFoundException e) {
        bailOut(e.getMessage());
    } catch (IOException e) {
        bailOut("Failed to parse program.", e);
    }
    // Apply program transformations/rewritings (currently none).
    IdentityProgramTransformation programTransformation = new IdentityProgramTransformation();
    ParsedProgram transformedProgram = programTransformation.transform(program);
    Grounder grounder = GrounderFactory.getInstance(commandLine.getOptionValue(OPT_GROUNDER, DEFAULT_GROUNDER), transformedProgram, filter);
    // NOTE: Using time as seed is fine as the internal heuristics
    // do not need to by cryptographically securely randomized.
    long seed = commandLine.hasOption(OPT_DETERMINISTIC) ? 0 : System.nanoTime();
    try {
        Number s = (Number) commandLine.getParsedOptionValue(OPT_SEED);
        if (s != null) {
            seed = s.longValue();
        }
    } catch (ParseException e) {
        bailOut("Failed to parse seed.", e);
    }
    LOGGER.info("Seed for pseudorandomization is {}.", seed);
    String chosenSolver = commandLine.getOptionValue(OPT_SOLVER, DEFAULT_SOLVER);
    String chosenBranchingHeuristic = commandLine.getOptionValue(OPT_BRANCHING_HEURISTIC, DEFAULT_BRANCHING_HEURISTIC);
    Heuristic parsedChosenBranchingHeuristic = null;
    try {
        parsedChosenBranchingHeuristic = Heuristic.get(chosenBranchingHeuristic);
    } catch (IllegalArgumentException e) {
        bailOut("Unknown branching heuristic: {}. Please try one of the following: {}.", chosenBranchingHeuristic, Heuristic.listAllowedValues());
    }
    Solver solver = SolverFactory.getInstance(chosenSolver, grounder, new Random(seed), parsedChosenBranchingHeuristic, debugInternalChecks);
    Stream<AnswerSet> stream = solver.stream();
    if (limit > 0) {
        stream = stream.limit(limit);
    }
    if (commandLine.hasOption(OPT_SORT)) {
        stream = stream.sorted();
    }
    stream.forEach(System.out::println);
}
Also used : org.antlr.v4.runtime(org.antlr.v4.runtime) java.util(java.util) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) Logger(org.slf4j.Logger) Solver(at.ac.tuwien.kr.alpha.solver.Solver) org.apache.commons.cli(org.apache.commons.cli) SolverFactory(at.ac.tuwien.kr.alpha.solver.SolverFactory) LoggerFactory(org.slf4j.LoggerFactory) PredictionMode(org.antlr.v4.runtime.atn.PredictionMode) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) IdentityProgramTransformation(at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation) GrounderFactory(at.ac.tuwien.kr.alpha.grounder.GrounderFactory) ASPCore2Lexer(at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer) ASPCore2Parser(at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser) Stream(java.util.stream.Stream) java.io(java.io) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic) Predicate(at.ac.tuwien.kr.alpha.common.Predicate) ParsedTreeVisitor(at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) Solver(at.ac.tuwien.kr.alpha.solver.Solver) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet) Predicate(at.ac.tuwien.kr.alpha.common.Predicate) IdentityProgramTransformation(at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic)

Example 12 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project aic-praise by aic-sri-international.

the class HOGMQueryRunner method query.

public List<HOGMQueryResult> query() {
    List<HOGMQueryResult> result = new ArrayList<>();
    Expression queryExpr = null;
    //
    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;
}
Also used : HOGModelException(com.sri.ai.praise.model.v1.HOGModelException) Expressions(com.sri.ai.expresso.helper.Expressions) Parser(com.sri.ai.expresso.api.Parser) ParsedHOGModel(com.sri.ai.praise.model.v1.hogm.antlr.ParsedHOGModel) Expression(com.sri.ai.expresso.api.Expression) FactorsAndTypes(com.sri.ai.praise.sgsolver.solver.FactorsAndTypes) Context(com.sri.ai.grinder.sgdpllt.api.Context) HOGModelException(com.sri.ai.praise.model.v1.HOGModelException) Theory(com.sri.ai.grinder.sgdpllt.api.Theory) HOGMParserWrapper(com.sri.ai.praise.model.v1.hogm.antlr.HOGMParserWrapper) ArrayList(java.util.ArrayList) Beta(com.google.common.annotations.Beta) GrinderUtil(com.sri.ai.grinder.helper.GrinderUtil) List(java.util.List) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) RecognitionException(org.antlr.v4.runtime.RecognitionException) InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) UnableToParseAllTheInputError(com.sri.ai.praise.model.v1.hogm.antlr.UnableToParseAllTheInputError) HOGMSortDeclaration(com.sri.ai.praise.model.v1.HOGMSortDeclaration) Collections(java.util.Collections) ParsedHOGModel(com.sri.ai.praise.model.v1.hogm.antlr.ParsedHOGModel) FactorsAndTypes(com.sri.ai.praise.sgsolver.solver.FactorsAndTypes) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) ArrayList(java.util.ArrayList) ExpressionFactorsAndTypes(com.sri.ai.praise.sgsolver.solver.ExpressionFactorsAndTypes) HOGMParserWrapper(com.sri.ai.praise.model.v1.hogm.antlr.HOGMParserWrapper) InferenceForFactorGraphAndEvidence(com.sri.ai.praise.sgsolver.solver.InferenceForFactorGraphAndEvidence) Expression(com.sri.ai.expresso.api.Expression) UnableToParseAllTheInputError(com.sri.ai.praise.model.v1.hogm.antlr.UnableToParseAllTheInputError) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 13 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project lucene-solr by apache.

the class JavascriptParserErrorStrategy method recoverInline.

/**
   * Ensures the ANTLR parser will throw an exception after the first error
   *
   * @param recognizer the parser being used
   * @return no actual return value
   * @throws RecognitionException not used as a ParseException wrapped in a RuntimeException is thrown instead
   */
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    Token token = recognizer.getCurrentToken();
    String message = "unexpected token " + getTokenErrorDisplay(token) + " on line (" + token.getLine() + ") position (" + token.getCharPositionInLine() + ")" + " was expecting one of " + recognizer.getExpectedTokens().toString(recognizer.getVocabulary());
    ParseException parseException = new ParseException(message, token.getStartIndex());
    throw new RuntimeException(parseException);
}
Also used : Token(org.antlr.v4.runtime.Token) ParseException(java.text.ParseException)

Example 14 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project sling by apache.

the class ExpressionParser method parseInterpolation.

/**
     * Parses the expression string.
     *
     * @param expressionString as defined by the HTL spec (https://github.com/Adobe-Marketing-Cloud/htl-spec/blob/master/SPECIFICATION.md)
     * @return Parsed Expression object
     * @throws NullPointerException     is the given exprString is null
     * @throws SightlyCompilerException if an error occurs while parsing the expression
     */
public Interpolation parseInterpolation(String expressionString) throws SightlyCompilerException {
    SightlyParser parser = createParser(expressionString);
    try {
        Interpolation interpolation = parser.interpolation().interp;
        interpolation.setContent(expressionString);
        return interpolation;
    } catch (RecognitionException e) {
        throw new SightlyCompilerException(e);
    }
}
Also used : SightlyCompilerException(org.apache.sling.scripting.sightly.compiler.SightlyCompilerException) SightlyParser(org.apache.sling.scripting.sightly.impl.parser.expr.generated.SightlyParser) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 15 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project oxTrust by GluuFederation.

the class ScimFilterParser method criteria.

public final CriteriaContext criteria() throws RecognitionException {
    CriteriaContext _localctx = new CriteriaContext(_ctx, getState());
    enterRule(_localctx, 4, RULE_criteria);
    try {
        int _alt;
        enterOuterAlt(_localctx, 1);
        {
            setState(139);
            match(T__0);
            setState(141);
            _errHandler.sync(this);
            _alt = 1 + 1;
            do {
                switch(_alt) {
                    case 1 + 1:
                        {
                            {
                                setState(140);
                                matchWildcard();
                            }
                        }
                        break;
                    default:
                        throw new NoViableAltException(this);
                }
                setState(143);
                _errHandler.sync(this);
                _alt = getInterpreter().adaptivePredict(_input, 20, _ctx);
            } while (_alt != 1 && _alt != org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER);
            setState(145);
            match(T__0);
        }
    } catch (RecognitionException re) {
        _localctx.exception = re;
        _errHandler.reportError(this, re);
        _errHandler.recover(this, re);
    } finally {
        exitRule();
    }
    return _localctx;
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Aggregations

RecognitionException (org.antlr.v4.runtime.RecognitionException)13 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)10 ArrayList (java.util.ArrayList)8 BaseErrorListener (org.antlr.v4.runtime.BaseErrorListener)6 Token (org.antlr.v4.runtime.Token)6 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)6 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)5 RecognitionException (org.antlr.runtime.RecognitionException)4 ParseTree (org.antlr.v4.runtime.tree.ParseTree)4 BoaLexer (boa.parser.BoaLexer)3 BoaParser (boa.parser.BoaParser)3 Expression (com.sri.ai.expresso.api.Expression)3 IOException (java.io.IOException)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3 NoViableAltException (org.antlr.v4.runtime.NoViableAltException)3 ASPCore2Lexer (at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer)2 ASPCore2Parser (at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)2 ParsedProgram (at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram)2 ParsedTreeVisitor (at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor)2 Start (boa.compiler.ast.Start)2