List of usage examples for org.antlr.v4.runtime CommonTokenStream CommonTokenStream
public CommonTokenStream(TokenSource tokenSource)
From source file:it.cnr.istc.iloc.ddl.TypeRefinement.java
License:Open Source License
@Override public void exitClass_declaration(DDLParser.Class_declarationContext ctx) { if (((IType) scope).getConstructors().isEmpty()) { DDLParser c_parser = new DDLParser( new CommonTokenStream(new DDLLexer(new ANTLRInputStream(ctx.name.getText() + "(){}")))); DDLParser.Constructor_declarationContext constructor_declaration = c_parser.constructor_declaration(); ((IType) scope).defineConstructor(new DDLConstructor(solver, scope, new IField[0], parser, scopes, constructor_declaration.explicit_constructor_invocation(), constructor_declaration.block())); }// w ww.j a v a 2 s . c o m scope = scope.getEnclosingScope(); }
From source file:it.cnr.istc.iloc.pddl.PDDLTranslator.java
License:Open Source License
public static String translatePDDLInstance(File pddl_domain, File pddl_problem, boolean ground) 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(new CaseInsensitiveFileStream(pddl_domain.getPath())); 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 BaseErrorListener()); // we create the problem parser.. PDDLLexer problem_lexer = new PDDLLexer(new CaseInsensitiveFileStream(pddl_problem.getPath())); 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 BaseErrorListener()); // 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())); Problem problem = new Problem(domain, Utils.capitalize(problem_context.name(1).NAME().getSymbol().getText())); TermVisitor term_visitor = new TermVisitor(domain_parser, domain, problem); if (domain_context.types_def() != null) { /**//from w w w.j ava 2s .co m * We define all the types of the domain. */ WALKER.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. */ WALKER.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())); domain.addType(type); } assert type != null : "Cannot find type " + ctx.type().primitive_type(0).name().getText(); Type c_type = type; ctx.name().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. */ WALKER.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); WALKER.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. */ WALKER.walk(new PDDLBaseListener() { Type type = null; @Override public void enterFunction_typed_list_atomic_function_skeleton( PDDLParser.Function_typed_list_atomic_function_skeletonContext ctx) { if (ctx.function_type() == null) { type = Type.OBJECT; } else if (ctx.function_type().type() == null) { type = Type.NUMBER; } else if (ctx.function_type().type().primitive_type().size() == 1) { 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 { 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(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); WALKER.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()), type, variables)); } }, domain_context.functions_def()); } /** * We define the structures. */ domain_context.structure_def().forEach(structure_def -> { if (structure_def.action_def() != null) { WALKER.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); WALKER.walk(typedListVariable, ctx.typed_list_variable()); variables = typedListVariable.variables .toArray(new Variable[typedListVariable.variables.size()]); } domain.addAction( new Action(Utils.capitalize(ctx.action_symbol().name().getText()), variables, ctx.action_def_body().emptyOr_pre_GD() != null ? term_visitor.visit(ctx.action_def_body().emptyOr_pre_GD()) : null, ctx.action_def_body().emptyOr_effect() != null ? term_visitor.visit(ctx.action_def_body().emptyOr_effect()) : null)); } }, structure_def.action_def()); } else if (structure_def.durative_action_def() != null) { WALKER.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); WALKER.walk(typedListVariable, ctx.typed_list_variable()); variables = typedListVariable.variables .toArray(new Variable[typedListVariable.variables.size()]); } domain.addDurativeAction( new DurativeAction(Utils.capitalize(ctx.da_symbol().name().getText()), variables, term_visitor.visit(ctx.da_def_body().duration_constraint()), term_visitor.visit(ctx.da_def_body().emptyOr_da_GD()), term_visitor.visit(ctx.da_def_body().emptyOr_da_effect()))); } }, structure_def.durative_action_def()); } }); /** * We define the objects. */ if (problem_context.object_declaration() != null) { WALKER.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().forEach(object -> { problem.addObject(c_type.newInstance(Utils.lowercase(object.getText()))); }); } }, problem_context.object_declaration()); } /** * We define the initial state */ problem_context.init().init_el().forEach(init_el -> { problem.addInitEl(term_visitor.visit(init_el)); }); /** * We define the goal */ problem.setGoal(term_visitor.visit(problem_context.goal().pre_GD())); if (ground) { ProblemInstance ground_instance = makeGround(new ProblemInstance(domain, problem)); STGroupFile file = new STGroupFile(PDDLTranslator.class.getResource("PDDLTemplate.stg").getPath()); file.registerRenderer(Domain.class, new DomainRenderer(file)); file.registerRenderer(Problem.class, new ProblemRenderer(file)); file.registerRenderer(Action.class, new ActionRenderer(file)); file.registerRenderer(DurativeAction.class, new DurativeActionRenderer(file)); file.registerRenderer(Predicate.class, new PredicateRenderer(file, ground_instance.domain)); file.registerRenderer(Function.class, new FunctionRenderer(file, ground_instance.domain)); ST translation = file.getInstanceOf("PDDL"); translation.add("domain", ground_instance.domain); translation.add("problem", ground_instance.problem); return translation.render(); } else { STGroupFile file = new STGroupFile(PDDLTranslator.class.getResource("PDDLTemplate.stg").getPath()); file.registerRenderer(Domain.class, new DomainRenderer(file)); file.registerRenderer(Problem.class, new ProblemRenderer(file)); file.registerRenderer(Action.class, new ActionRenderer(file)); file.registerRenderer(DurativeAction.class, new DurativeActionRenderer(file)); file.registerRenderer(Predicate.class, new PredicateRenderer(file, domain)); file.registerRenderer(Function.class, new FunctionRenderer(file, domain)); ST translation = file.getInstanceOf("PDDL"); translation.add("domain", domain); translation.add("problem", problem); return translation.render(); } }
From source file:it.cnr.istc.iloc.translators.mrcpsp.MRCPSPMaxTranslator.java
License:Open Source License
public static String translate(File file) throws IOException { final List<Resource> renewable_resources = new ArrayList<>(); final List<Resource> nonrenewable_resources = new ArrayList<>(); final List<Resource> doubly_constrained_resources = new ArrayList<>(); final Map<Integer, Activity> activities = new LinkedHashMap<>(); final List<Constraint> constraints = new ArrayList<>(); MRCPSPParser parser = new MRCPSPParser( new CommonTokenStream(new MRCPSPLexer(new ANTLRFileStream(file.getPath())))); MRCPSPParser.Compilation_unitContext context = parser.compilation_unit(); // Creating resources for (int i = 0; i < parser.n_renewable_resources; i++) { renewable_resources.add(new Resource("rr" + i, context.capacities().renewable_resources_capacities().positive_number(i).v)); }/* w w w . j a v a 2 s . c o m*/ for (int i = 0; i < parser.n_nonrenewable_resources; i++) { nonrenewable_resources.add(new Resource("cr" + i, context.capacities().nonrenewable_resources_capacities().positive_number(i).v)); } if (parser.n_doubly_constrained_resources > 0) { throw new UnsupportedOperationException("Doubly-constrained resources are not supported yet.."); } // Creating all activities (also initial and final one!) for (int i = 0; i <= parser.n_real_activities + 1; i++) { Activity activity = new Activity(i, renewable_resources, nonrenewable_resources, doubly_constrained_resources); for (int j = 0; j < context.activities().activity(i).n_modes.v; j++) { List<String> renewable_resource_usages = new ArrayList<>(parser.n_renewable_resources); List<String> nonrenewable_resource_usages = new ArrayList<>(parser.n_nonrenewable_resources); for (int k = 0; k < parser.n_renewable_resources; k++) { renewable_resource_usages.add(Integer.toString(context.resource_usages().resource_usage(i) .modes().activity_mode(j).renewable_resources_uses().positive_number(k).v)); } for (int k = 0; k < parser.n_nonrenewable_resources; k++) { nonrenewable_resource_usages.add(Integer.toString(context.resource_usages().resource_usage(i) .modes().activity_mode(j).nonrenewable_resources_uses().positive_number(k).v)); } Mode mode = new Mode(j + 1, context.resource_usages().resource_usage(i).modes().activity_mode(j).activity_duration.v, renewable_resource_usages, nonrenewable_resource_usages); activity.modes.add(mode); } activities.put(activity.id, activity); } // Creating constraints for (int i = 0; i <= parser.n_real_activities + 1; i++) { Activity activity = activities.get(i); for (int j = 0; j < context.activities().activity(i).n_direct_successors.v; j++) { List<String> weights = new ArrayList<>(context.activities().activity(i).weights(j).number().size()); for (MRCPSPParser.NumberContext numberContext : context.activities().activity(i).weights(j) .number()) { weights.add(Integer.toString(numberContext.v)); } activity.addSuccessor(new Successor( activities.get(context.activities().activity(i).direct_successors().positive_number(j).v), weights)); } for (Successor successor : activity.successors) { int j = 0; for (Mode mode0 : activity.modes) { for (Mode mode1 : successor.activity.modes) { constraints.add(new Constraint(activity, mode0, successor.activity, mode1, Integer.parseInt(successor.weights.get(j++)), activities)); } } } } ST translation = new STGroupFile(MRCPSPMaxTranslator.class.getResource("MRCPSPMaxTemplate.stg").getPath()) .getInstanceOf("MRCPSPMax"); translation.add("class_name", "RCPSP_max"); translation.add("instance_name", "rcpsp_max"); if (renewable_resources.isEmpty()) { translation.add("renewable_resources", new ST.AttributeList()); } else { renewable_resources.stream().forEach((resource) -> { translation.add("renewable_resources", resource); }); } if (nonrenewable_resources.isEmpty()) { translation.add("nonrenewable_resources", new ST.AttributeList()); } else { nonrenewable_resources.stream().forEach((resource) -> { translation.add("nonrenewable_resources", resource); }); } if (doubly_constrained_resources.isEmpty()) { translation.add("doubly_constrained_resources", new ST.AttributeList()); } else { doubly_constrained_resources.stream().forEach((resource) -> { translation.add("doubly_constrained_resources", resource); }); } activities.values().stream().forEach((activity) -> { translation.add("activities", activity); }); constraints.stream().forEach((constraint) -> { translation.add("constraints", constraint); }); return translation.render(); }
From source file:it.cnr.istc.iloc.translators.pddl.parser.Parser.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(new CaseInsensitiveFileStream(pddl_domain.getPath())); 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 BaseErrorListener()); // we create the problem parser.. PDDLLexer problem_lexer = new PDDLLexer(new CaseInsensitiveFileStream(pddl_problem.getPath())); 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 BaseErrorListener()); // 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())); Problem problem = new Problem(domain, Utils.capitalize(problem_context.name(1).NAME().getSymbol().getText())); if (domain_context.types_def() != null) { /**/*from w w w . j av a 2 s .c o m*/ * We define all the types of the domain.. */ WALKER.walk(new PDDLBaseListener() { @Override public void enterTyped_list_name(PDDLParser.Typed_list_nameContext ctx) { ctx.name().stream().forEach(type_name -> { Type type = new Type(Utils.capitalize(type_name.getText())); domain.addType(type); }); } }, domain_context.types_def()); /** * We set the superclasses (i.e., we manage type inheritance).. */ WALKER.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())); } else { throw new AssertionError("multiple inheritance.."); } final Type superclass = c_superclass; ctx.name().stream().forEach(type_name -> { Type type = domain.getType(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. */ WALKER.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. */ WALKER.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); WALKER.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. */ WALKER.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); WALKER.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) { WALKER.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); WALKER.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) { WALKER.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); WALKER.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) { WALKER.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); }
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/*w ww.ja v a2s. 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); }
From source file:it.polimi.tower4clouds.rules.RulesValidator.java
License:Apache License
private Set<Problem> validateCondition(MonitoringRule rule) { Set<Problem> problems = new HashSet<Problem>(); if (rule.getCondition() == null) return problems; String condition = rule.getCondition().getValue(); if (condition != null) { ANTLRInputStream input = new ANTLRInputStream(condition); ConditionLexer lexer = new ConditionLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); ConditionParser parser = new ConditionParser(tokens); parser.setErrorHandler(new ErrorStrategy()); parser.removeErrorListeners();/*ww w .j av a 2s. com*/ lexer.removeErrorListeners(); try { parser.expression(); } catch (Exception e) { Problem problem = new Problem(); problem.setElementId(rule.getId()); problem.setTagName("condition"); problem.setError(EnumErrorType.CONDITION_LEXICAL_ERROR); if (e.getCause().toString().contains("NoViableAltException")) { Token token = ((NoViableAltException) (e.getCause())).getOffendingToken(); problem.setDescription( "Lexical error: '" + condition.substring(0, token.getCharPositionInLine()) + " " + condition.substring(token.getCharPositionInLine()) + "'"); } else if (e instanceof InputMismatchException) { problem.setDescription("Input Mismatch Exception"); } else if (e instanceof FailedPredicateException) { problem.setDescription("Failed Predicate Exception"); } else { problem.setDescription("Unknown recognition error! Exception: " + e.getClass().getName()); } problems.add(problem); } } return problems; }
From source file:it.sijmen.hanasdapp.lang.config.Config.java
License:Open Source License
protected void load(ANTLRInputStream input) { ConfigurationLexer lexer = new ConfigurationLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); ConfigurationParser parser = new ConfigurationParser(tokens); walkParser(parser);//from ww w . ja v a 2s. c o m }
From source file:it.unibo.alchemist.model.implementations.reactions.BiochemicalReactionBuilder.java
License:Open Source License
/** * Builds the chemical reaction.//from www .j a v a2 s. c om * @return a chemical reaction based on the given program */ public Reaction<Double> build() { checkReaction(); final BiochemistrydslLexer lexer = new BiochemistrydslLexer(new ANTLRInputStream(reactionString)); final BiochemistrydslParser parser = new BiochemistrydslParser(new CommonTokenStream(lexer)); parser.removeErrorListeners(); parser.addErrorListener(new BiochemistryParseErrorListener(reactionString)); final ParseTree tree = parser.reaction(); final BiochemistryDSLVisitor<P> eval = new BiochemistryDSLVisitor<>(rand, incarnation, time, node, env); return eval.visit(tree); }
From source file:jasy.lang.ASMCompiler.java
public JasyParser createParser(InputStream sourceCode) throws IOException { CharStream charStream = new ANTLRInputStream(sourceCode); JasyLexer lexer = new JasyLexer(charStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); return new JasyParser(tokenStream); }
From source file:jasy.lang.ASMCompiler.java
public ClassTransformer compile(InputStream sourceCode, ArrayList<Message> errorMessages) throws IOException { CharStream charStream = new ANTLRInputStream(sourceCode); JasyLexer lexer = new JasyLexer(charStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); JasyParser parser = new JasyParser(tokenStream); JasyParser.ProgramContext program = parser.program(); ClassTransformerSequence classTransformers = new ClassTransformerSequence(); validateProgram(program, errorMessages); program.accept(new JasyBaseVisitor<Object>() { @Override//from w ww . j a va 2 s . co m public Object visitClassTransformer(JasyParser.ClassTransformerContext ctx) { CommonClassTransformer transformer = new CommonClassTransformer(); List<AnnotationContext> aCtxs = ctx.annotations().annotation().stream() .filter(pa -> pa.PLUS() == null).collect(Collectors.toList()); transformer.addPredicate(classNode -> { return aCtxs.stream().allMatch(pa -> { String annotationName = pa.typeQualifier().getText().replace(".", "/"); if (classNode.visibleAnnotations != null && classNode.visibleAnnotations.size() > 0) return classNode.visibleAnnotations.stream() .anyMatch(a -> ((AnnotationNode) a).desc.equals(annotationName)); return false; }); }); if (ctx.typeQualifier() != null) { String className = ctx.typeQualifier().getText().replace(".", "/"); transformer.addPredicate(classNode -> { return classNode.name.equals(className); }); } if (ctx.members != null) { // for(DejainParser.ClassTransformerMemberContext memberCtx: ctx.members.classTransformerMember()) { // memberCtx.accept(new DejainBaseVisitor<Object>() { // @Override // public Object visitClassTransformerMemberFieldAdd(DejainParser.ClassTransformerMemberFieldAddContext ctx) { // try { // int fieldAccess = getAccessModifier(ctx.accessModifier(), ctx.modStatic()); // String fieldName = ctx.identifier().getText(); // String fieldTypeName = ctx.typeQualifier().getText(); // String fieldDescriptor = Type.getDescriptor(classResolver.resolveType(fieldTypeName)); // // transformer.addAction(classNode -> // { // classNode.fields.add(new FieldNode(fieldAccess, fieldName, fieldDescriptor, null, null)); // }); // // return null; // } catch (ClassNotFoundException ex) { // Logger.getLogger(ASMCompiler.class.getName()).log(Level.SEVERE, null, ex); // return null; // } // } // // @Override // public Object visitClassTransformerMemberMethod(DejainParser.ClassTransformerMemberMethodContext ctx) { // try { // int methodAccess = getAccessModifier(ctx.accessModifier(), ctx.modStatic()); // String methodName = ctx.identifier().getText(); // Class<?> returnType = classResolver.resolveType(ctx.typeQualifier().getText()); // String methodDescriptor = getMethodDescriptor(ctx.typeQualifier(), ctx.parameters()); // // transformer.addPredicate(classNode -> { // System.out.println(methodName + " " + methodDescriptor); // return classNode.methods.stream().anyMatch(m -> // ((MethodNode)m).name.equals(methodName) && // ((MethodNode)m).desc.equals(methodDescriptor)); // }); // // transformer.addAction(classNode -> // { // MethodNode methodNode = new MethodNode(methodAccess, methodName, methodDescriptor, null, null); // // OptionalInt existingMethodIndex = // IntStream.range(0, classNode.methods.size()) // .filter(i -> // ((MethodNode)classNode.methods.get(i)).name.equals(methodName) && // ((MethodNode)classNode.methods.get(i)).desc.equals(methodDescriptor)) // .findFirst(); // // MethodNode methodNodeOriginal = (MethodNode)classNode.methods.get(existingMethodIndex.getAsInt()); // // InsnList originalIl = new InsnList(); // originalIl.add(methodNodeOriginal.instructions); // // MethodCodeGenerator generator = new MethodCodeGenerator(methodNode, returnType); // // generator.start(); // treeToCode(ctx, generator, originalIl, false); // generator.end(); // // methodNode.visitEnd(); // // classNode.methods.remove(existingMethodIndex.getAsInt()); // classNode.methods.add(methodNode); // }); // // return null; // } catch (ClassNotFoundException ex) { // Logger.getLogger(ASMCompiler.class.getName()).log(Level.SEVERE, null, ex); // return null; // } // } // // @Override // public Object visitClassTransformerMemberMethodAdd(DejainParser.ClassTransformerMemberMethodAddContext ctx) { // try { // int methodAccess = getAccessModifier(ctx.methodDefinition().accessModifier(), ctx.methodDefinition().modStatic()); // String methodName = ctx.methodDefinition().identifier().getText(); // Class<?> returnType = classResolver.resolveType(ctx.methodDefinition().typeQualifier().getText()); // String methodDescriptor = getMethodDescriptor(ctx.methodDefinition().typeQualifier(), ctx.methodDefinition().parameters()); // // transformer.addAction(classNode -> // { // MethodNode methodNode = new MethodNode(methodAccess, methodName, methodDescriptor, null, null); // MethodCodeGenerator generator = new MethodCodeGenerator(methodNode, returnType); // // generator.start(); // treeToCode(ctx, generator, new InsnList() /*Something that generates a default values for non-void returns?*/, false); // generator.end(); // // methodNode.visitEnd(); // // OptionalInt existingMethodIndex = // IntStream.range(0, classNode.methods.size()) // .filter(i -> // ((MethodNode)classNode.methods.get(i)).name.equals(methodName) && // ((MethodNode)classNode.methods.get(i)).desc.equals(methodDescriptor)) // .findFirst(); // if(existingMethodIndex.isPresent()) // classNode.methods.remove(existingMethodIndex.getAsInt()); // // classNode.methods.add(methodNode); // }); // // return null; // } catch (ClassNotFoundException ex) { // Logger.getLogger(ASMCompiler.class.getName()).log(Level.SEVERE, null, ex); // return null; // } // } // }); // } } transformer.addAction(classNode -> { ctx.annotations().annotation().stream().filter(pa -> pa.PLUS() != null).forEach(pa -> { String annotationName = pa.typeQualifier().getText().replace(".", "/"); try { classNode.visitAnnotation(annotationName, true); } catch (Exception e) { e.printStackTrace(); } }); }); classTransformers.addTransformer(transformer); return null; } }); return classTransformers; }