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

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

Introduction

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

Prototype

ANTLRErrorListener

Source Link

Usage

From source file:com.github.mariusdw.sqlsim.validator.sqlite.SqLiteValidator.java

License:Open Source License

@Override
public void validate(String query) throws ValidationException {
    SQLiteLexer lexer = new SQLiteLexer(new ANTLRInputStream(query));
    SQLiteParser parser = new SQLiteParser(new CommonTokenStream(lexer));
    List<String> errorStrs = new ArrayList<>(1);
    ANTLRErrorListener listener = new ANTLRErrorListener() {
        @Override/* ww  w. ja v a 2s . c  om*/
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                int charPositionInLine, String msg, RecognitionException e) {

            String newMsg = "Error [line:" + line + "|char:" + charPositionInLine + "] " + msg;
            if (errorStrs.size() > 0) {
                newMsg += "\n" + errorStrs.get(0);
                errorStrs.set(0, newMsg);
            } else {
                errorStrs.add(newMsg);
            }

        }

        @Override
        public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean bln, BitSet bitset,
                ATNConfigSet atncs) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitset,
                ATNConfigSet atncs) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2,
                ATNConfigSet atncs) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    parser.addErrorListener(listener);

    try {
        parser.parse();
        if (errorStrs.size() > 0) {
            throw new ValidationException("Validation error: " + errorStrs.get(0));
        }
    } catch (RecognitionException e) {
        throw new ValidationException("Validation error:", e);
    }
}

From source file:it.cnr.istc.iloc.Solver.java

License:Open Source License

public Solver(Properties properties) {
    this.properties = properties;
    this.parser = new LanguageParser(this, properties, new ANTLRErrorListener() {
        @Override//from w w  w .j  av  a2 s .  com
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                int charPositionInLine, String msg, RecognitionException e) {
            LOG.log(Level.SEVERE, "[{0}, {1}] {2}", new Object[] { line, charPositionInLine, msg });
        }

        @Override
        public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
                BitSet ambigAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                BitSet conflictingAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                int prediction, ATNConfigSet configs) {
        }
    });

    this.currentNode = new Node(this);
    this.fringe.add(currentNode);

    // We create primitive types ..
    IType boolType = new Type(this, this, Constants.BOOL) {
        @Override
        public boolean isPrimitive() {
            return true;
        }

        @Override
        public IObject newInstance(IEnvironment enclosing_environment) {
            return constraintNetwork.newBool();
        }
    };
    IType numberType = new Type(this, this, Constants.NUMBER) {
        @Override
        public boolean isPrimitive() {
            return true;
        }

        @Override
        public IObject newInstance(IEnvironment enclosing_environment) {
            return constraintNetwork.newReal();
        }
    };
    IType intType = new Type(this, this, Constants.INT) {
        @Override
        public boolean isPrimitive() {
            return true;
        }

        @Override
        public IObject newInstance(IEnvironment enclosing_environment) {
            return constraintNetwork.newInt();
        }
    };
    intType.setSuperclass(numberType);
    IType realType = new Type(this, this, Constants.REAL) {
        @Override
        public boolean isPrimitive() {
            return true;
        }

        @Override
        public IObject newInstance(IEnvironment enclosing_environment) {
            return constraintNetwork.newReal();
        }
    };
    realType.setSuperclass(numberType);
    IType stringType = new Type(this, this, Constants.STRING) {
        @Override
        public boolean isPrimitive() {
            return true;
        }

        @Override
        public IObject newInstance(IEnvironment enclosing_environment) {
            return constraintNetwork.newString();
        }
    };

    // .. and define them
    defineType(boolType);
    defineType(numberType);
    defineType(intType);
    defineType(realType);
    defineType(stringType);

    String[] types = properties.getProperty("Types", "it.cnr.istc.iloc.types.agent.AgentType:"
            + "it.cnr.istc.iloc.types.impulsiveagent.ImpulsiveAgentType:"
            + "it.cnr.istc.iloc.types.statevariable.StateVariableType:"
            + "it.cnr.istc.iloc.types.reusableresource.ReusableResourceType:"
            + "it.cnr.istc.iloc.types.consumableresource.ConsumableResourceType:"
            + "it.cnr.istc.iloc.types.battery.BatteryType:" + "it.cnr.istc.iloc.types.sensor.SensorType:"
            + "it.cnr.istc.iloc.types.propositionalstate.PropositionalStateType:"
            + "it.cnr.istc.iloc.types.propositionalstate.PropositionalImpulsiveAgentType:"
            + "it.cnr.istc.iloc.types.propositionalstate.PropositionalAgentType").split(":");
    for (String type : types) {
        try {
            defineType((IType) Class.forName(type.trim())
                    .getDeclaredConstructor(ISolver.class, Properties.class).newInstance(this, properties));
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }

    this.constraintNetwork = new ConstraintNetwork(this, properties);
    this.exploit_landmarks = Boolean.valueOf(properties.getProperty("Landmarks", "False"));
    if (exploit_landmarks) {
        this.lm_graph = new LandmarkGraph(this);
    } else {
        this.lm_graph = null;
    }

    INumber origin = constraintNetwork.newReal();
    INumber horizon = constraintNetwork.newReal();
    defineField(new Field(Constants.ORIGIN, origin.getType()));
    defineField(new Field(Constants.HORIZON, horizon.getType()));

    set(Constants.ORIGIN, origin);
    set(Constants.HORIZON, horizon);

    constraintNetwork.assertFacts(constraintNetwork.geq(origin, constraintNetwork.newReal("0")),
            constraintNetwork.geq(horizon, origin));
}

From source file:it.cnr.istc.translators.pddl2ratio.parser.Translator.java

License:Open Source License

public static PDDLInstance parse(File pddl_domain, File pddl_problem) throws IOException {
    // We get the requirements
    Set<String> domain_requirements = PDDLRequirements.getRequirements(pddl_domain);
    Set<String> problem_requirements = PDDLRequirements.getRequirements(pddl_problem);
    problem_requirements.addAll(domain_requirements);

    // we create the domain parser..
    PDDLLexer domain_lexer = new PDDLLexer(
            CharStreams.fromString(new String(Files.readAllBytes(pddl_domain.toPath())).toLowerCase()));
    domain_lexer.requirements.addAll(domain_requirements);
    PDDLParser domain_parser = new PDDLParser(new CommonTokenStream(domain_lexer));
    domain_parser.requirements.addAll(domain_requirements);
    domain_parser.addErrorListener(new ANTLRErrorListener() {
        @Override//from   w  w  w .  j a  va 2s.  c  o m
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                int charPositionInLine, String msg, RecognitionException e) {
            LOG.severe(msg);
        }

        @Override
        public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
                BitSet ambigAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                BitSet conflictingAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                int prediction, ATNConfigSet configs) {
        }
    });

    // we create the problem parser..
    PDDLLexer problem_lexer = new PDDLLexer(
            CharStreams.fromString(new String(Files.readAllBytes(pddl_problem.toPath())).toLowerCase()));
    problem_lexer.requirements.addAll(problem_requirements);
    PDDLParser problem_parser = new PDDLParser(new CommonTokenStream(problem_lexer));
    problem_parser.requirements.addAll(problem_requirements);
    problem_parser.addErrorListener(new ANTLRErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                int charPositionInLine, String msg, RecognitionException e) {
            LOG.severe(msg);
        }

        @Override
        public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
                BitSet ambigAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                BitSet conflictingAlts, ATNConfigSet configs) {
        }

        @Override
        public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
                int prediction, ATNConfigSet configs) {
        }
    });

    // We parse the domain..
    PDDLParser.DomainContext domain_context = domain_parser.domain();

    // We parse the problem..
    PDDLParser.ProblemContext problem_context = problem_parser.problem();

    Domain domain = new Domain(Utils.capitalize(domain_context.name().NAME().getSymbol().getText()),
            domain_requirements);
    Problem problem = new Problem(domain,
            Utils.capitalize(problem_context.name(1).NAME().getSymbol().getText()), problem_requirements);

    if (domain_context.types_def() != null) {
        /**
         * We define all the types of the domain..
         */
        ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
            @Override
            public void enterTyped_list_name(PDDLParser.Typed_list_nameContext ctx) {
                Type c_superclass = null;
                if (ctx.type() == null) {
                    c_superclass = Type.OBJECT;
                } else if (ctx.type().primitive_type().size() == 1) {
                    c_superclass = ctx.type().primitive_type(0).name() == null ? Type.OBJECT
                            : domain.getType(Utils.capitalize(ctx.type().primitive_type(0).name().getText()));
                    if (c_superclass == null) {
                        c_superclass = new Type(
                                Utils.capitalize(ctx.type().primitive_type(0).name().getText()));
                        domain.addType(c_superclass);
                    }
                } else {
                    c_superclass = new EitherType(ctx.type().primitive_type().stream()
                            .map(primitive_type -> primitive_type.name() == null ? Type.OBJECT
                                    : domain.getType(Utils.capitalize(primitive_type.name().getText())))
                            .collect(Collectors.toList()));
                    domain.addType(c_superclass);
                }
                final Type superclass = c_superclass;
                ctx.name().forEach(type_name -> {
                    Type type = new Type(Utils.capitalize(type_name.getText()));
                    type.setSuperclass(superclass);
                    domain.addType(type);
                });
            }
        }, domain_context.types_def());
    }

    if (domain_context.constants_def() != null) {
        /**
         * We define the constants.
         */
        ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
            @Override
            public void enterTyped_list_name(PDDLParser.Typed_list_nameContext ctx) {
                Type type = null;
                if (ctx.type() == null) {
                    type = Type.OBJECT;
                } else if (ctx.type().primitive_type().size() == 1) {
                    type = ctx.type().primitive_type(0).name() == null ? Type.OBJECT
                            : domain.getType(Utils.capitalize(ctx.type().primitive_type(0).name().getText()));
                } else {
                    type = new EitherType(ctx.type().primitive_type().stream()
                            .map(primitive_type -> primitive_type.name() == null ? Type.OBJECT
                                    : domain.getType(Utils.capitalize(primitive_type.name().getText())))
                            .collect(Collectors.toList()));
                    if (!domain.getTypes().containsKey(type.getName())) {
                        domain.addType(type);
                    }
                }

                assert type != null : "Cannot find type " + ctx.type().primitive_type(0).name().getText();
                Type c_type = type;
                ctx.name().stream().forEach(name -> {
                    domain.addConstant(c_type.newInstance(Utils.lowercase(name.getText())));
                });
            }
        }, domain_context.constants_def());
    }

    if (domain_context.predicates_def() != null) {
        /**
         * We define the predicates.
         */
        ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
            @Override
            public void enterAtomic_formula_skeleton(PDDLParser.Atomic_formula_skeletonContext ctx) {
                Variable[] variables = new Variable[0];
                if (ctx.typed_list_variable() != null) {
                    // The predicate formula has parameters
                    TypedListVariableListener typedListVariable = new TypedListVariableListener(domain);
                    ParseTreeWalker.DEFAULT.walk(typedListVariable, ctx.typed_list_variable());
                    variables = typedListVariable.variables
                            .toArray(new Variable[typedListVariable.variables.size()]);
                }
                domain.addPredicate(
                        new Predicate(Utils.capitalize(ctx.predicate().name().getText()), variables));
            }
        }, domain_context.predicates_def());
    }

    if (domain_context.functions_def() != null) {
        /**
         * We define the functions.
         */
        ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
            private Type function_type = null;

            @Override
            public void enterFunction_typed_list_atomic_function_skeleton(
                    PDDLParser.Function_typed_list_atomic_function_skeletonContext ctx) {
                if (ctx.function_type() == null) {
                    function_type = Type.OBJECT;
                } else if (ctx.function_type().type() == null) {
                    function_type = Type.NUMBER;
                } else if (ctx.function_type().type().primitive_type().size() == 1) {
                    function_type = ctx.function_type().type().primitive_type(0).name() == null ? Type.OBJECT
                            : domain.getType(Utils
                                    .capitalize(ctx.function_type().type().primitive_type(0).name().getText()));
                } else {
                    function_type = new EitherType(ctx.function_type().type().primitive_type().stream()
                            .map(primitive_type -> primitive_type.name() == null ? Type.OBJECT
                                    : domain.getType(Utils.capitalize(primitive_type.name().getText())))
                            .collect(Collectors.toList()));
                    domain.addType(function_type);
                }
            }

            @Override
            public void enterAtomic_function_skeleton(PDDLParser.Atomic_function_skeletonContext ctx) {
                Variable[] variables = new Variable[0];
                if (ctx.typed_list_variable() != null) {
                    // The predicate formula has parameters
                    TypedListVariableListener typedListVariable = new TypedListVariableListener(domain);
                    ParseTreeWalker.DEFAULT.walk(typedListVariable, ctx.typed_list_variable());
                    variables = typedListVariable.variables
                            .toArray(new Variable[typedListVariable.variables.size()]);
                }
                domain.addFunction(new Function(Utils.capitalize(ctx.function_symbol().name().getText()),
                        function_type, variables));
            }
        }, domain_context.functions_def());
    }

    /**
     * We define the structures.
     */
    domain_context.structure_def().stream().forEach(structure_def -> {
        if (structure_def.action_def() != null) {
            ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
                @Override
                public void enterAction_def(PDDLParser.Action_defContext ctx) {
                    Variable[] variables = new Variable[0];
                    if (ctx.typed_list_variable() != null) {
                        // The action has parameters
                        TypedListVariableListener typedListVariable = new TypedListVariableListener(domain);
                        ParseTreeWalker.DEFAULT.walk(typedListVariable, ctx.typed_list_variable());
                        variables = typedListVariable.variables
                                .toArray(new Variable[typedListVariable.variables.size()]);
                    }
                    Action action = new Action(Utils.capitalize(ctx.action_symbol().name().getText()),
                            variables);

                    TermVisitor term_visitor = new TermVisitor(domain_parser, domain, problem, Stream
                            .of(variables).collect(Collectors.toMap(Variable::getName, variable -> variable)));
                    if (ctx.action_def_body().emptyOr_pre_GD() != null) {
                        action.setPrecondition(term_visitor.visit(ctx.action_def_body().emptyOr_pre_GD()));
                    }
                    if (ctx.action_def_body().emptyOr_effect() != null) {
                        action.setEffect(term_visitor.visit(ctx.action_def_body().emptyOr_effect()));
                    }
                    domain.addAction(action);
                }
            }, structure_def.action_def());
        } else if (structure_def.durative_action_def() != null) {
            ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
                @Override
                public void enterDurative_action_def(PDDLParser.Durative_action_defContext ctx) {
                    Variable[] variables = new Variable[0];
                    if (ctx.typed_list_variable() != null) {
                        // The durative action has parameters
                        TypedListVariableListener typedListVariable = new TypedListVariableListener(domain);
                        ParseTreeWalker.DEFAULT.walk(typedListVariable, ctx.typed_list_variable());
                        variables = typedListVariable.variables
                                .toArray(new Variable[typedListVariable.variables.size()]);
                    }
                    DurativeAction action = new DurativeAction(
                            Utils.capitalize(ctx.da_symbol().name().getText()), variables);
                    TermVisitor term_visitor = new TermVisitor(domain_parser, domain, problem, Stream
                            .of(variables).collect(Collectors.toMap(Variable::getName, variable -> variable)));
                    if (ctx.da_def_body().duration_constraint() != null) {
                        action.setDuration(term_visitor.visit(ctx.da_def_body().duration_constraint()));
                    }
                    if (ctx.da_def_body().emptyOr_da_GD() != null) {
                        action.setEffect(term_visitor.visit(ctx.da_def_body().emptyOr_da_GD()));
                    }
                    if (ctx.da_def_body().emptyOr_da_effect() != null) {
                        action.setEffect(term_visitor.visit(ctx.da_def_body().emptyOr_da_effect()));
                    }
                    domain.addDurativeAction(action);
                }
            }, structure_def.durative_action_def());
        }
    });

    /**
     * We define the objects.
     */
    if (problem_context.object_declaration() != null) {
        ParseTreeWalker.DEFAULT.walk(new PDDLBaseListener() {
            @Override
            public void enterTyped_list_name(PDDLParser.Typed_list_nameContext ctx) {
                Type type = null;
                if (ctx.type() == null) {
                    type = Type.OBJECT;
                } else if (ctx.type().primitive_type().size() == 1) {
                    type = ctx.type().primitive_type(0).name() == null ? Type.OBJECT
                            : domain.getType(Utils.capitalize(ctx.type().primitive_type(0).name().getText()));
                }
                final Type c_type = type;
                ctx.name().stream().forEach(object -> {
                    problem.addObject(c_type.newInstance(Utils.lowercase(object.getText())));
                });
            }
        }, problem_context.object_declaration());
    }

    TermVisitor term_visitor = new TermVisitor(domain_parser, domain, problem, Collections.emptyMap());
    /**
     * We define the initial state
     */
    problem_context.init().init_el().stream().forEach(init_el -> {
        problem.addInitEl(term_visitor.visit(init_el));
    });

    /**
     * We define the goal
     */
    problem.setGoal(term_visitor.visit(problem_context.goal().pre_GD()));

    return new PDDLInstance(domain, problem);
}