repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
jkind
jkind-master/jkind/src/jkind/analysis/ArraysNonempty.java
package jkind.analysis; import jkind.StdErr; import jkind.lustre.ArrayType; import jkind.lustre.Program; import jkind.lustre.visitors.TypeIterVisitor; public class ArraysNonempty extends TypeIterVisitor { public static boolean check(Program program) { ArraysNonempty visitor = new ArraysNonempty(); visitor.visitProgram(program); return visitor.nonempty; } private boolean nonempty = true; @Override public Void visit(ArrayType e) { if (e.size == 0) { StdErr.error(e.location, "array is empty"); nonempty = false; } return null; } }
561
20.615385
53
java
jkind
jkind-master/jkind/src/jkind/analysis/TypesDefined.java
package jkind.analysis; import java.util.HashSet; import java.util.List; import java.util.Set; import jkind.StdErr; import jkind.lustre.Constant; import jkind.lustre.NamedType; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstIterVisitor; import jkind.lustre.visitors.TypeIterVisitor; public class TypesDefined extends AstIterVisitor { public static boolean check(Program program) { TypesDefined visitor = new TypesDefined(); visitor.visit(program); return visitor.passed; } private final Set<String> defined = new HashSet<>(); private boolean passed = true; @Override protected void visitTypeDefs(List<TypeDef> es) { for (TypeDef e : es) { defined.add(e.id); } super.visitTypeDefs(es); } @Override public Void visit(TypeDef e) { check(e.type); return null; } @Override public Void visit(Constant e) { if (e.type != null) { check(e.type); } return null; } @Override public Void visit(VarDecl e) { check(e.type); return null; } private void check(Type type) { type.accept(new TypeIterVisitor() { @Override public Void visit(NamedType e) { if (!e.isBuiltin() && !defined.contains(e.name)) { StdErr.error(e.location, "unknown type " + e.name); passed = false; } return null; } }); } }
1,372
19.191176
56
java
jkind
jkind-master/jkind/src/jkind/analysis/Level.java
package jkind.analysis; public enum Level { ERROR, WARNING, IGNORE; @Override public String toString() { switch (this) { case ERROR: return "Error"; case WARNING: return "Warning"; default: throw new IllegalArgumentException(); } } }
259
13.444444
40
java
jkind
jkind-master/jkind/src/jkind/analysis/StaticAnalyzer.java
package jkind.analysis; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jkind.ExitCodes; import jkind.JKindSettings; import jkind.Settings; import jkind.SolverOption; import jkind.StdErr; import jkind.analysis.evaluation.DivisionChecker; import jkind.lustre.Constant; import jkind.lustre.EnumType; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.VarDecl; import jkind.util.Util; public class StaticAnalyzer { public static void check(Program program, SolverOption solver) { check(program, solver, new Settings()); } public static void check(Program program, SolverOption solver, Settings settings) { checkErrors(program, solver, settings); checkSolverLimitations(program, solver); checkWarnings(program, solver); } private static void checkErrors(Program program, SolverOption solver, Settings settings) { boolean valid = true; valid = valid && hasMainNode(program); valid = valid && typesUnique(program); valid = valid && TypesDefined.check(program); valid = valid && TypeDependencyChecker.check(program); valid = valid && enumsAndConstantsUnique(program); valid = valid && ConstantDependencyChecker.check(program); valid = valid && nodesAndFunctionsUnique(program); valid = valid && functionsHaveUnconstrainedOutputTypes(program); valid = valid && variablesUnique(program); valid = valid && TypeChecker.check(program); valid = valid && SubrangesNonempty.check(program); valid = valid && ArraysNonempty.check(program); valid = valid && constantsConstant(program); valid = valid && DivisionChecker.check(program); valid = valid && NodeDependencyChecker.check(program); valid = valid && assignmentsSound(program); valid = valid && ConstantArrayAccessBounded.check(program); valid = valid && propertiesUnique(program); valid = valid && propertiesExist(program); valid = valid && propertiesBoolean(program); valid = valid && ivcUnique(program); valid = valid && ivcLocalOrOutput(program); switch (solver) { case Z3: break; case YICES2: if (settings instanceof JKindSettings) { JKindSettings jKindSettings = (JKindSettings) settings; if (jKindSettings.reduceIvc && !LinearChecker.check(program, Level.IGNORE)) { StdErr.warning(jKindSettings.solver + " does not support unsat-cores for nonlinear logic so IVC reduction will be slow"); } } break; default: valid = valid && LinearChecker.check(program, Level.ERROR); break; } if (!valid) { System.exit(ExitCodes.STATIC_ANALYSIS_ERROR); } } private static void checkSolverLimitations(Program program, SolverOption solver) { if (solver == SolverOption.MATHSAT) { if (!MathSatFeatureChecker.check(program)) { System.exit(ExitCodes.UNSUPPORTED_FEATURE); } } } private static void checkWarnings(Program program, SolverOption solver) { warnUnusedAsserts(program); warnAlgebraicLoops(program); WarnUnguardedPreVisitor.check(program); if (solver == SolverOption.Z3) { LinearChecker.check(program, Level.WARNING); } } private static boolean hasMainNode(Program program) { if (program.getMainNode() == null) { StdErr.error("no main node"); return false; } return true; } private static boolean typesUnique(Program program) { boolean unique = true; Set<String> seen = new HashSet<>(); for (TypeDef def : program.types) { if (!seen.add(def.id)) { StdErr.error(def.location, "type " + def.id + " already defined"); unique = false; } } return unique; } private static boolean enumsAndConstantsUnique(Program program) { boolean unique = true; Set<String> seen = new HashSet<>(); for (EnumType et : Util.getEnumTypes(program.types)) { for (String value : et.values) { if (!seen.add(value)) { StdErr.error(et.location, value + " defined multiple times"); unique = false; } } } for (Constant c : program.constants) { if (!seen.add(c.id)) { StdErr.error(c.location, c.id + " defined multiple times"); unique = false; } } for (Node node : program.nodes) { for (VarDecl vd : Util.getVarDecls(node)) { if (seen.contains(vd.id)) { StdErr.error(vd.location, vd.id + " already defined globally"); unique = false; } } } return unique; } private static boolean nodesAndFunctionsUnique(Program program) { boolean unique = true; Set<String> seen = new HashSet<>(); for (Function function : program.functions) { if (!seen.add(function.id)) { StdErr.error(function.location, "function or node " + function.id + " already defined"); unique = false; } } for (Node node : program.nodes) { if (!seen.add(node.id)) { StdErr.error(node.location, "function or node " + node.id + " already defined"); unique = false; } } return unique; } private static boolean functionsHaveUnconstrainedOutputTypes(Program program) { boolean valid = true; Map<String, Type> typeTable = Util.createResolvedTypeTable(program.types); for (Function function : program.functions) { for (VarDecl output : function.outputs) { if (ContainsConstrainedType.check(output.type, typeTable)) { StdErr.error(output.type.location, "function " + function.id + " may not use constrained output type (subrange or enumeration)"); valid = false; } } } return valid; } private static boolean variablesUnique(Program program) { boolean unique = true; for (Function function : program.functions) { unique = variablesUnique(Util.getVarDecls(function)) && unique; } for (Node node : program.nodes) { unique = variablesUnique(Util.getVarDecls(node)) && unique; } return unique; } private static boolean variablesUnique(List<VarDecl> varDecls) { boolean unique = true; Set<String> seen = new HashSet<>(); for (VarDecl decl : varDecls) { if (!seen.add(decl.id)) { StdErr.error(decl.location, "variable " + decl.id + " already declared"); unique = false; } } return unique; } private static boolean constantsConstant(Program program) { boolean constant = true; ConstantAnalyzer constantAnalyzer = new ConstantAnalyzer(program); for (Constant c : program.constants) { if (!c.expr.accept(constantAnalyzer)) { StdErr.error(c.location, "constant " + c.id + " does not have a constant value"); constant = false; } } return constant; } private static boolean assignmentsSound(Program program) { boolean sound = true; for (Node node : program.nodes) { sound = assignmentsSound(node) && sound; } return sound; } private static boolean assignmentsSound(Node node) { Set<String> toAssign = new HashSet<>(); toAssign.addAll(Util.getIds(node.outputs)); toAssign.addAll(Util.getIds(node.locals)); Set<String> assigned = new HashSet<>(); boolean sound = true; for (Equation eq : node.equations) { for (IdExpr idExpr : eq.lhs) { if (toAssign.contains(idExpr.id)) { toAssign.remove(idExpr.id); assigned.add(idExpr.id); } else if (assigned.contains(idExpr.id)) { StdErr.error(idExpr.location, "variable '" + idExpr.id + "' cannot be reassigned"); sound = false; } else { StdErr.error(idExpr.location, "variable '" + idExpr.id + "' cannot be assigned"); sound = false; } } } if (!toAssign.isEmpty()) { StdErr.error("in node '" + node.id + "' variables must be assigned: " + toAssign); sound = false; } return sound; } private static boolean propertiesUnique(Program program) { boolean unique = true; for (Node node : program.nodes) { Set<String> seen = new HashSet<>(); for (String prop : node.properties) { if (!seen.add(prop)) { StdErr.error("in node '" + node.id + "' property '" + prop + "' declared multiple times"); unique = false; } } } return unique; } private static boolean propertiesExist(Program program) { boolean exist = true; for (Node node : program.nodes) { Set<String> variables = new HashSet<>(Util.getIds(Util.getVarDecls(node))); for (String prop : node.properties) { if (!variables.contains(prop)) { StdErr.error("in node '" + node.id + "' property '" + prop + "' does not exist"); exist = false; } } } return exist; } private static boolean propertiesBoolean(Program program) { boolean allBoolean = true; for (Node node : program.nodes) { Set<String> booleans = getBooleans(node); for (String prop : node.properties) { if (!booleans.contains(prop)) { StdErr.error("in node '" + node.id + "' property '" + prop + "' does not have type bool"); allBoolean = false; } } } return allBoolean; } private static Set<String> getBooleans(Node node) { Set<String> booleans = new HashSet<>(); for (VarDecl varDecl : Util.getVarDecls(node)) { if (varDecl.type == NamedType.BOOL) { booleans.add(varDecl.id); } } return booleans; } private static void warnUnusedAsserts(Program program) { for (Node node : program.nodes) { if (node.id.equals(program.main)) { continue; } for (Expr expr : node.assertions) { StdErr.warning(expr.location, "assertion in subnode ignored"); } } } private static void warnAlgebraicLoops(Program program) { for (Node node : program.nodes) { Map<String, Set<String>> directDepends = Util.getDirectDependencies(node); Set<String> covered = new HashSet<>(); for (Equation eq : node.equations) { List<String> stack = new ArrayList<>(); for (IdExpr idExpr : eq.lhs) { checkAlgebraicLoops(node.id, idExpr.id, stack, covered, directDepends); } } } } private static boolean checkAlgebraicLoops(String node, String id, List<String> stack, Set<String> covered, Map<String, Set<String>> directDepends) { if (stack.contains(id)) { StringBuilder text = new StringBuilder(); text.append("in node '" + node + "' possible algebraic loop: "); for (String s : stack.subList(stack.indexOf(id), stack.size())) { text.append(s + " -> "); } text.append(id); StdErr.warning(text.toString()); return true; } if (!covered.add(id)) { return false; } if (directDepends.containsKey(id)) { stack.add(id); for (String next : directDepends.get(id)) { if (checkAlgebraicLoops(node, next, stack, covered, directDepends)) { return true; } } stack.remove(stack.size() - 1); } return false; } private static boolean ivcUnique(Program program) { boolean unique = true; for (Node node : program.nodes) { Set<String> seen = new HashSet<>(); for (String e : node.ivc) { if (!seen.add(e)) { StdErr.error("in node '" + node.id + "' IVC element '" + e + "' declared multiple times"); unique = false; } } } return unique; } private static boolean ivcLocalOrOutput(Program program) { boolean passed = true; for (Node node : program.nodes) { Set<String> assigned = new HashSet<>(); assigned.addAll(Util.getIds(node.outputs)); assigned.addAll(Util.getIds(node.locals)); for (String e : node.ivc) { if (!assigned.contains(e)) { StdErr.error("in node '" + node.id + "' IVC element '" + e + "' must be a local or output"); passed = false; } } } return passed; } }
11,521
26.630695
108
java
jkind
jkind-master/jkind/src/jkind/analysis/ConstantDependencyChecker.java
package jkind.analysis; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jkind.StdErr; import jkind.lustre.Constant; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Program; import jkind.lustre.visitors.ExprIterVisitor; import jkind.util.CycleFinder; public class ConstantDependencyChecker { public static boolean check(Program program) { return new ConstantDependencyChecker().check(program.constants); } protected boolean check(List<Constant> constants) { Map<String, Set<String>> dependencies = new HashMap<>(); for (Constant c : constants) { dependencies.put(c.id, getConstantDependencies(c.expr)); } List<String> cycle = CycleFinder.findCycle(dependencies); if (cycle != null) { StdErr.error("cyclic constants: " + cycle); return false; } return true; } private static Set<String> getConstantDependencies(Expr e) { final Set<String> dependencies = new HashSet<>(); e.accept(new ExprIterVisitor() { @Override public Void visit(IdExpr e) { dependencies.add(e.id); return null; } }); return dependencies; } }
1,176
23.520833
66
java
jkind
jkind-master/jkind/src/jkind/analysis/TypeDependencyChecker.java
package jkind.analysis; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jkind.StdErr; import jkind.lustre.NamedType; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.visitors.TypeIterVisitor; import jkind.util.CycleFinder; public class TypeDependencyChecker { public static boolean check(Program program) { return new TypeDependencyChecker().check(program.types); } protected boolean check(List<TypeDef> types) { Map<String, Set<String>> dependencies = new HashMap<>(); for (TypeDef def : types) { dependencies.put(def.id, getTypeDependencies(def.type)); } List<String> cycle = CycleFinder.findCycle(dependencies); if (cycle != null) { StdErr.error("cyclic types: " + cycle); return false; } return true; } private static Set<String> getTypeDependencies(Type type) { final Set<String> dependencies = new HashSet<>(); type.accept(new TypeIterVisitor() { @Override public Void visit(NamedType e) { if (!e.isBuiltin()) { dependencies.add(e.name); } return null; } }); return dependencies; } }
1,194
22.9
60
java
jkind
jkind-master/jkind/src/jkind/analysis/RemoveSubranges.java
package jkind.analysis; import jkind.lustre.NamedType; import jkind.lustre.SubrangeIntType; import jkind.lustre.Type; import jkind.lustre.visitors.TypeMapVisitor; public class RemoveSubranges extends TypeMapVisitor { public static Type remove(Type type) { return type.accept(new RemoveSubranges()); } @Override public Type visit(SubrangeIntType e) { return NamedType.INT; } }
388
20.611111
53
java
jkind
jkind-master/jkind/src/jkind/analysis/MathSatFeatureChecker.java
package jkind.analysis; import jkind.StdErr; import jkind.lustre.BinaryExpr; import jkind.lustre.Program; import jkind.lustre.visitors.AstIterVisitor; public class MathSatFeatureChecker extends AstIterVisitor { private boolean passed = true; public static boolean check(Program program) { MathSatFeatureChecker checker = new MathSatFeatureChecker(); checker.visit(program); return checker.passed; } @Override public Void visit(BinaryExpr e) { super.visit(e); switch (e.op) { case INT_DIVIDE: StdErr.error(e.location, "integer division not supported in MathSAT"); passed = false; break; case MODULUS: StdErr.error(e.location, "modulus not supported in MathSAT"); passed = false; break; default: break; } return null; } }
775
18.897436
73
java
jkind
jkind-master/jkind/src/jkind/analysis/TypeChecker.java
package jkind.analysis; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.StdErr; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.Ast; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Constant; import jkind.lustre.EnumType; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.Location; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.SubrangeIntType; import jkind.lustre.TupleExpr; import jkind.lustre.TupleType; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.UnaryExpr; import jkind.lustre.VarDecl; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class TypeChecker implements ExprVisitor<Type> { private final Map<String, Type> typeTable = new HashMap<>(); private final Map<String, Type> constantTable = new HashMap<>(); private final Map<String, Constant> constantDefinitionTable = new HashMap<>(); private final Map<String, EnumType> enumValueTable = new HashMap<>(); private final Map<String, Type> variableTable = new HashMap<>(); private final Map<String, Node> nodeTable; private final Map<String, Function> functionTable; private boolean passed; private TypeChecker(Program program) { this.nodeTable = Util.getNodeTable(program.nodes); this.functionTable = Util.getFunctionTable(program.functions); this.passed = true; populateTypeTable(program.types); populateEnumValueTable(program.types); populateConstantTable(program.constants); } public static boolean check(Program program) { return new TypeChecker(program).visitProgram(program); } private boolean visitProgram(Program program) { for (Node node : program.nodes) { visitNode(node); } return passed; } private void populateTypeTable(List<TypeDef> typeDefs) { typeTable.putAll(Util.createResolvedTypeTable(typeDefs)); } private void populateEnumValueTable(List<TypeDef> typeDefs) { for (EnumType et : Util.getEnumTypes(typeDefs)) { for (String id : et.values) { enumValueTable.put(id, et); } } } private void populateConstantTable(List<Constant> constants) { // The constantDefinitionTable is used for constants whose type has not // yet been computed for (Constant c : constants) { constantDefinitionTable.put(c.id, c); } for (Constant c : constants) { addConstant(c); } } private Type addConstant(Constant c) { if (constantTable.containsKey(c.id)) { return constantTable.get(c.id); } Type actual = c.expr.accept(this); if (c.type == null) { constantTable.put(c.id, actual); return actual; } else { Type expected = resolveType(c.type); compareTypeAssignment(c.expr, expected, actual); constantTable.put(c.id, expected); return expected; } } private boolean visitNode(Node node) { repopulateVariableTable(node); for (Equation eq : node.equations) { checkEquation(eq); } for (Expr assertion : node.assertions) { compareTypeAssignment(assertion, NamedType.BOOL, assertion.accept(this)); } return passed; } private void repopulateVariableTable(Node node) { variableTable.clear(); for (VarDecl v : Util.getVarDecls(node)) { variableTable.put(v.id, resolveType(v.type)); } } private Type resolveType(Type type) { return Util.resolveType(type, typeTable); } private boolean isIntBased(Type type) { return type == NamedType.INT || type instanceof SubrangeIntType; } private void checkEquation(Equation eq) { List<Type> expected = getExpectedTypes(eq.lhs); List<Type> actual = removeTuple(eq.expr.accept(this)); if (expected == null || actual == null || expected.contains(null) || actual.contains(null)) { return; } if (expected.size() != actual.size()) { error(eq, "trying to assign " + actual.size() + " values to " + expected.size() + " variables"); return; } for (int i = 0; i < expected.size(); i++) { Type ex = expected.get(i); Type ac = actual.get(i); if (!typeAssignable(ex, ac)) { error(eq.lhs.get(i), "trying to assign value of type " + ac + " to variable of type " + ex); } } } private List<Type> getExpectedTypes(List<IdExpr> lhs) { List<Type> result = new ArrayList<>(); for (IdExpr idExpr : lhs) { result.add(idExpr.accept(this)); } return result; } private List<Type> removeTuple(Type type) { if (type == null) { return null; } else if (type instanceof TupleType) { return ((TupleType) type).types; } else { return Collections.singletonList(type); } } @Override public Type visit(ArrayAccessExpr e) { Type type = e.array.accept(this); Type indexType = e.index.accept(this); if (type == null || indexType == null) { return null; } if (!isIntBased(indexType)) { error(e.index, "expected type int, but found " + simple(indexType)); } if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; return arrayType.base; } error(e.array, "expected array type, but found " + simple(type)); return null; } @Override public Type visit(ArrayExpr e) { Iterator<Expr> iterator = e.elements.iterator(); Type common = iterator.next().accept(this); if (common == null) { return null; } while (iterator.hasNext()) { Expr nextExpr = iterator.next(); Type next = nextExpr.accept(this); if (next == null) { return null; } Type join = joinTypes(common, next); if (join == null) { error(nextExpr, "expected type " + simple(common) + ", but found " + simple(next)); return null; } common = join; } return new ArrayType(common, e.elements.size()); } @Override public Type visit(ArrayUpdateExpr e) { Type type = e.array.accept(this); Type indexType = e.index.accept(this); Type valueType = e.value.accept(this); if (type == null || indexType == null || valueType == null) { return null; } if (!isIntBased(indexType)) { error(e.index, "expected type int, but found " + simple(indexType)); } if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; compareTypeAssignment(e.value, arrayType.base, valueType); return arrayType; } error(e.array, "expected array type, but found " + simple(type)); return null; } @Override public Type visit(BinaryExpr e) { Type left = e.left.accept(this); Type right = e.right.accept(this); if (left == null || right == null) { return null; } switch (e.op) { case PLUS: case MINUS: case MULTIPLY: if (left == NamedType.REAL && right == NamedType.REAL) { return NamedType.REAL; } if (isIntBased(left) && isIntBased(right)) { return NamedType.INT; } break; case DIVIDE: if (left == NamedType.REAL && right == NamedType.REAL) { return NamedType.REAL; } break; case INT_DIVIDE: case MODULUS: if (isIntBased(left) && isIntBased(right)) { return NamedType.INT; } break; case EQUAL: case NOTEQUAL: if (joinTypes(left, right) != null) { return NamedType.BOOL; } break; case GREATER: case LESS: case GREATEREQUAL: case LESSEQUAL: if (left == NamedType.REAL && right == NamedType.REAL) { return NamedType.BOOL; } if (isIntBased(left) && isIntBased(right)) { return NamedType.BOOL; } break; case OR: case AND: case XOR: case IMPLIES: if (left == NamedType.BOOL && right == NamedType.BOOL) { return NamedType.BOOL; } break; case ARROW: Type join = joinTypes(left, right); if (join != null) { return join; } break; } error(e, "operator '" + e.op + "' not defined on types " + simple(left) + ", " + simple(right)); return null; } @Override public Type visit(BoolExpr e) { return NamedType.BOOL; } @Override public Type visit(CastExpr e) { Type type = e.expr.accept(this); if (type == null) { return null; } if (e.type == NamedType.REAL && !isIntBased(type)) { error(e, "expected type int, but found " + simple(type)); } else if (e.type == NamedType.INT && type != NamedType.REAL) { error(e, "expected type real, but found " + simple(type)); } return e.type; } @Override public Type visit(CondactExpr e) { return compressTypes(visitCondactExpr(e)); } private Type compressTypes(List<Type> types) { if (types == null || types.contains(null)) { return null; } else { return TupleType.compress(types); } } private List<Type> visitCondactExpr(CondactExpr e) { compareTypeAssignment(e.clock, NamedType.BOOL, e.clock.accept(this)); List<Type> expected = visitNodeCallExpr(e.call); if (expected == null) { return null; } List<Type> actual = new ArrayList<>(); for (Expr arg : e.args) { actual.add(arg.accept(this)); } if (actual.size() != expected.size()) { error(e, "expected " + expected.size() + " default values, but found " + actual.size()); return null; } for (int i = 0; i < expected.size(); i++) { compareTypeAssignment(e.args.get(i), expected.get(i), actual.get(i)); } return expected; } @Override public Type visit(FunctionCallExpr e) { Function function = functionTable.get(e.function); if (function != null) { return compressTypes(visitCallExpr(e, e.args, function.inputs, function.outputs)); } error(e, "unknown function " + e.function); return null; } private List<Type> visitCallExpr(Expr e, List<Expr> args, List<VarDecl> inputs, List<VarDecl> outputs) { List<Type> actual = new ArrayList<>(); for (Expr arg : args) { actual.add(arg.accept(this)); } List<Type> expected = new ArrayList<>(); for (VarDecl input : inputs) { expected.add(resolveType(input.type)); } if (actual.size() != expected.size()) { error(e, "expected " + expected.size() + " arguments, but found " + actual.size()); return null; } for (int i = 0; i < expected.size(); i++) { compareTypeAssignment(args.get(i), expected.get(i), actual.get(i)); } List<Type> result = new ArrayList<>(); for (VarDecl decl : outputs) { result.add(resolveType(decl.type)); } return result; } @Override public Type visit(IdExpr e) { if (variableTable.containsKey(e.id)) { return variableTable.get(e.id); } else if (constantTable.containsKey(e.id)) { return constantTable.get(e.id); } else if (constantDefinitionTable.containsKey(e.id)) { return addConstant(constantDefinitionTable.get(e.id)); } else if (enumValueTable.containsKey(e.id)) { return enumValueTable.get(e.id); } else { error(e, "unknown variable " + e.id); return null; } } @Override public Type visit(IfThenElseExpr e) { Type condType = e.cond.accept(this); Type thenType = e.thenExpr.accept(this); Type elseType = e.elseExpr.accept(this); compareTypeAssignment(e.cond, NamedType.BOOL, condType); return compareTypeJoin(e.elseExpr, thenType, elseType); } @Override public Type visit(IntExpr e) { return new SubrangeIntType(e.value, e.value); } @Override public Type visit(NodeCallExpr e) { return compressTypes(visitNodeCallExpr(e)); } private List<Type> visitNodeCallExpr(NodeCallExpr e) { Node node = nodeTable.get(e.node); if (node != null) { return visitCallExpr(e, e.args, node.inputs, node.outputs); } error(e, "unknown node " + e.node); return null; } @Override public Type visit(RealExpr e) { return NamedType.REAL; } @Override public Type visit(RecordAccessExpr e) { Type type = e.record.accept(this); if (type == null) { return null; } if (type instanceof RecordType) { RecordType recordType = (RecordType) type; if (recordType.fields.containsKey(e.field)) { return recordType.fields.get(e.field); } } error(e, "expected record type with field " + e.field + ", but found " + simple(type)); return null; } @Override public Type visit(RecordExpr e) { Map<String, Type> fields = new HashMap<>(); for (Entry<String, Expr> entry : e.fields.entrySet()) { fields.put(entry.getKey(), entry.getValue().accept(this)); } Type expectedType = typeTable.get(e.id); if (!(expectedType instanceof RecordType)) { error(e, "unknown record type " + e.id); return null; } RecordType expectedRecordType = (RecordType) expectedType; for (Entry<String, Type> entry : expectedRecordType.fields.entrySet()) { String expectedField = entry.getKey(); Type expectedFieldType = entry.getValue(); if (!fields.containsKey(expectedField)) { error(e, "record of type " + e.id + " is missing field " + expectedField); } else { Type actualFieldType = fields.get(expectedField); compareTypeAssignment(e.fields.get(expectedField), expectedFieldType, actualFieldType); } } for (String actualField : fields.keySet()) { if (!expectedRecordType.fields.keySet().contains(actualField)) { error(e.fields.get(actualField), "record of type " + e.id + " has extra field " + actualField); } } return new RecordType(e.location, e.id, fields); } @Override public Type visit(RecordUpdateExpr e) { Type type = e.record.accept(this); Type valueType = e.value.accept(this); if (type == null || valueType == null) { return null; } if (type instanceof RecordType) { RecordType rt = (RecordType) type; if (rt.fields.containsKey(e.field)) { Type fieldType = rt.fields.get(e.field); compareTypeAssignment(e.value, fieldType, valueType); return rt; } else { error(e, "expected record type with field " + e.field + ", but found " + simple(type)); } } else { error(e.record, "expected a record type, but found " + simple(type)); } return null; } @Override public Type visit(TupleExpr e) { List<Type> types = new ArrayList<>(); for (Expr expr : e.elements) { types.add(expr.accept(this)); } return compressTypes(types); } @Override public Type visit(UnaryExpr e) { Type type = e.expr.accept(this); if (type == null) { return null; } switch (e.op) { case NEGATIVE: if (type instanceof SubrangeIntType) { SubrangeIntType subrange = (SubrangeIntType) type; return new SubrangeIntType(subrange.high.negate(), subrange.low.negate()); } if (type == NamedType.INT || type == NamedType.REAL) { return type; } break; case NOT: if (type == NamedType.BOOL) { return type; } break; case PRE: return type; } error(e, "operator '" + e.op + "' not defined on type " + simple(type)); return null; } private void compareTypeAssignment(Ast ast, Type expected, Type actual) { if (expected == null || actual == null) { return; } if (!typeAssignable(expected, actual)) { Type found = ContainsSubrange.check(expected) ? actual : simple(actual); error(ast, "expected type " + expected + ", but found type " + found); } } private boolean typeAssignable(Type expected, Type actual) { if (expected.equals(actual)) { return true; } if (expected == NamedType.INT && actual instanceof SubrangeIntType) { return true; } if (expected instanceof SubrangeIntType && actual instanceof SubrangeIntType) { SubrangeIntType exRange = (SubrangeIntType) expected; SubrangeIntType acRange = (SubrangeIntType) actual; return exRange.low.compareTo(acRange.low) <= 0 && exRange.high.compareTo(acRange.high) >= 0; } if (expected instanceof ArrayType && actual instanceof ArrayType) { ArrayType expectedArrayType = (ArrayType) expected; ArrayType actualArrayType = (ArrayType) actual; return expectedArrayType.size == actualArrayType.size && typeAssignable(expectedArrayType.base, actualArrayType.base); } if (expected instanceof TupleType && actual instanceof TupleType) { TupleType expectedTupleType = (TupleType) expected; TupleType actualTupleType = (TupleType) actual; if (expectedTupleType.types.size() != actualTupleType.types.size()) { return false; } for (int i = 0; i < expectedTupleType.types.size(); i++) { if (!typeAssignable(expectedTupleType.types.get(i), actualTupleType.types.get(i))) { return false; } } return true; } return false; } private Type compareTypeJoin(Ast ast, Type t1, Type t2) { if (t1 == null || t2 == null) { return null; } Type join = joinTypes(t1, t2); if (join == null) { error(ast, "cannot join types " + simple(t1) + " and " + simple(t2)); return null; } return join; } private Type simple(Type type) { return RemoveSubranges.remove(type); } private Type joinTypes(Type t1, Type t2) { if (t1 instanceof SubrangeIntType && t2 instanceof SubrangeIntType) { SubrangeIntType s1 = (SubrangeIntType) t1; SubrangeIntType s2 = (SubrangeIntType) t2; return new SubrangeIntType(s1.low.min(s2.low), s1.high.max(s2.high)); } else if (isIntBased(t1) && isIntBased(t2)) { return NamedType.INT; } else if (t1 instanceof ArrayType && t2 instanceof ArrayType) { ArrayType a1 = (ArrayType) t1; ArrayType a2 = (ArrayType) t2; Type join = joinTypes(a1.base, a2.base); if (a1.size != a2.size || join == null) { return null; } return new ArrayType(join, a1.size); } else if (t1 instanceof TupleType && t2 instanceof TupleType) { TupleType tt1 = (TupleType) t1; TupleType tt2 = (TupleType) t2; if (tt1.types.size() != tt2.types.size()) { return null; } List<Type> joinList = new ArrayList<>(); for (int i = 0; i < tt1.types.size(); i++) { Type join = joinTypes(tt1.types.get(i), tt2.types.get(i)); if (join == null) { return null; } else { joinList.add(join); } } return new TupleType(joinList); } else if (t1.equals(t2)) { return t1; } else { return null; } } private void error(Location location, String message) { passed = false; StdErr.error(location, message); } private void error(Ast ast, String message) { error(ast.location, message); } }
18,484
24.998594
105
java
jkind
jkind-master/jkind/src/jkind/analysis/SubrangesNonempty.java
package jkind.analysis; import jkind.StdErr; import jkind.lustre.Program; import jkind.lustre.SubrangeIntType; import jkind.lustre.visitors.TypeIterVisitor; public class SubrangesNonempty extends TypeIterVisitor { public static boolean check(Program program) { SubrangesNonempty visitor = new SubrangesNonempty(); visitor.visitProgram(program); return visitor.nonempty; } private boolean nonempty = true; @Override public Void visit(SubrangeIntType e) { if (e.high.compareTo(e.low) < 0) { StdErr.error(e.location, "subrange is empty"); nonempty = false; } return null; } }
601
22.153846
56
java
jkind
jkind-master/jkind/src/jkind/analysis/NodeDependencyChecker.java
package jkind.analysis; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import jkind.StdErr; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.util.CycleFinder; import jkind.util.Util; public class NodeDependencyChecker { public static boolean check(Program program) { return new NodeDependencyChecker().check(program.nodes); } protected boolean check(List<Node> nodes) { Map<String, Set<String>> dependencies = new HashMap<>(); for (Node node : nodes) { dependencies.put(node.id, Util.getNodeDependenciesByName(node)); } List<String> cycle = CycleFinder.findCycle(dependencies); if (cycle != null) { StdErr.error("cyclic node calls: " + cycle); return false; } return true; } }
776
22.545455
67
java
jkind
jkind-master/jkind/src/jkind/analysis/ConstantAnalyzer.java
package jkind.analysis; import java.util.HashSet; import java.util.Set; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.CondactExpr; import jkind.lustre.Constant; import jkind.lustre.EnumType; import jkind.lustre.IdExpr; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.visitors.ExprConjunctiveVisitor; import jkind.util.Util; public class ConstantAnalyzer extends ExprConjunctiveVisitor { private final Set<String> constants = new HashSet<>(); public ConstantAnalyzer() { } public ConstantAnalyzer(Program program) { for (Constant c : program.constants) { constants.add(c.id); } for (EnumType et : Util.getEnumTypes(program.types)) { for (String id : et.values) { constants.add(id); } } } @Override public Boolean visit(BinaryExpr e) { return e.op != BinaryOp.ARROW && super.visit(e); } @Override public Boolean visit(CondactExpr e) { return false; } @Override public Boolean visit(IdExpr e) { return constants.contains(e.id); } @Override public Boolean visit(NodeCallExpr e) { return false; } }
1,120
19.759259
62
java
jkind
jkind-master/jkind/src/jkind/analysis/LinearChecker.java
package jkind.analysis; import java.util.Set; import jkind.StdErr; import jkind.lustre.BinaryExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.visitors.ExprIterVisitor; import jkind.util.Util; public class LinearChecker extends ExprIterVisitor { private final Level level; private boolean passed; private ConstantAnalyzer constantAnalyzer; public LinearChecker(Level level) { this.level = level; this.passed = true; } public static boolean check(Program program, Level level) { return new LinearChecker(level).visitProgram(program); } public static boolean isLinear(Program program) { return new LinearChecker(Level.IGNORE).visitProgram(program); } public static boolean isLinear(Node node) { return isLinear(new Program(node)); } public boolean visitProgram(Program program) { constantAnalyzer = new ConstantAnalyzer(program); // Do not iterate over allDependencies directly, so that errors are in // program order Set<Node> allDependencies = Util.getAllNodeDependencies(program); for (Node node : program.nodes) { if (allDependencies.contains(node)) { visitNode(node); } } return passed; } public void visitNode(Node node) { for (Equation eq : node.equations) { eq.expr.accept(this); } for (Expr e : node.assertions) { e.accept(this); } } @Override public Void visit(BinaryExpr e) { e.left.accept(this); e.right.accept(this); switch (e.op) { case MULTIPLY: if (!isConstant(e.left) && !isConstant(e.right)) { StdErr.output(level, e.location, "non-constant multiplication"); passed = false; } break; case DIVIDE: case INT_DIVIDE: if (!isConstant(e.right)) { StdErr.output(level, e.location, "non-constant division"); passed = false; } break; case MODULUS: if (!isConstant(e.right)) { StdErr.output(level, e.location, "non-constant modulus"); passed = false; } break; default: break; } return null; } private boolean isConstant(Expr e) { return e.accept(constantAnalyzer); } }
2,125
20.474747
72
java
jkind
jkind-master/jkind/src/jkind/analysis/ContainsConstrainedType.java
package jkind.analysis; import java.util.Map; import jkind.lustre.EnumType; import jkind.lustre.NamedType; import jkind.lustre.SubrangeIntType; import jkind.lustre.Type; import jkind.lustre.visitors.TypeIterVisitor; public class ContainsConstrainedType extends TypeIterVisitor { public static boolean check(Type type, Map<String, Type> typeTable) { ContainsConstrainedType visitor = new ContainsConstrainedType(typeTable); type.accept(visitor); return visitor.containsConstrainedType; } private final Map<String, Type> typeTable; private boolean containsConstrainedType = false; public ContainsConstrainedType(Map<String, Type> typeTable) { this.typeTable = typeTable; } @Override public Void visit(EnumType e) { containsConstrainedType = true; return null; } @Override public Void visit(NamedType e) { if (!e.isBuiltin()) { typeTable.get(e.name).accept(this); } return null; } @Override public Void visit(SubrangeIntType e) { containsConstrainedType = true; return null; } }
1,023
22.272727
75
java
jkind
jkind-master/jkind/src/jkind/analysis/ContainsSubrange.java
package jkind.analysis; import jkind.lustre.ArrayType; import jkind.lustre.EnumType; import jkind.lustre.NamedType; import jkind.lustre.RecordType; import jkind.lustre.SubrangeIntType; import jkind.lustre.TupleType; import jkind.lustre.Type; import jkind.lustre.visitors.TypeVisitor; public class ContainsSubrange implements TypeVisitor<Boolean> { public static boolean check(Type type) { return type.accept(new ContainsSubrange()); } @Override public Boolean visit(ArrayType e) { return e.base.accept(this); } @Override public Boolean visit(EnumType e) { return false; } @Override public Boolean visit(NamedType e) { return false; } @Override public Boolean visit(RecordType e) { // We only care if the toString() has subranges, thus records never do return false; } @Override public Boolean visit(TupleType e) { for (Type type : e.types) { if (type.accept(this)) { return true; } } return false; } @Override public Boolean visit(SubrangeIntType e) { return true; } }
1,027
18.396226
72
java
jkind
jkind-master/jkind/src/jkind/analysis/WarnUnguardedPreVisitor.java
package jkind.analysis; import jkind.StdErr; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.visitors.ExprIterVisitor; public class WarnUnguardedPreVisitor extends ExprIterVisitor { public static void check(Program program) { for (Node node : program.nodes) { for (Equation eq : node.equations) { eq.expr.accept(UNGUARDED); } for (Expr e : node.assertions) { e.accept(UNGUARDED); } } } public static final WarnUnguardedPreVisitor GUARDED = new WarnUnguardedPreVisitor(); public static final WarnUnguardedPreVisitor UNGUARDED = new WarnUnguardedPreVisitor(); @Override public Void visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { if (this == GUARDED) { e.expr.accept(UNGUARDED); } else { StdErr.warning(e.location, "unguarded pre expression"); } } else { super.visit(e); } return null; } @Override public Void visit(BinaryExpr e) { if (e.op == BinaryOp.ARROW) { e.left.accept(this); e.right.accept(GUARDED); } else { super.visit(e); } return null; } @Override public Void visit(NodeCallExpr e) { UNGUARDED.visitExprs(e.args); return null; } }
1,374
20.825397
87
java
jkind
jkind-master/jkind/src/jkind/analysis/ConstantArrayAccessBounded.java
package jkind.analysis; import java.math.BigInteger; import jkind.StdErr; import jkind.analysis.evaluation.ConstantEvaluator; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayType; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Location; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.visitors.ExprIterVisitor; import jkind.lustre.visitors.TypeReconstructor; public class ConstantArrayAccessBounded extends ExprIterVisitor { private boolean passed = true; private ConstantAnalyzer constantAnalyzer; private ConstantEvaluator constantEvaluator; private TypeReconstructor typeReconstructor; public static boolean check(Program program) { return new ConstantArrayAccessBounded().visitProgram(program); } public boolean visitProgram(Program program) { constantAnalyzer = new ConstantAnalyzer(program); constantEvaluator = new ConstantEvaluator(program); typeReconstructor = new TypeReconstructor(program); for (Node node : program.nodes) { visitNode(node); } return passed; } public void visitNode(Node node) { typeReconstructor.setNodeContext(node); for (Equation eq : node.equations) { eq.expr.accept(this); } for (Expr e : node.assertions) { e.accept(this); } } @Override public Void visit(ArrayAccessExpr e) { checkAccess(e.index.location, e.array, e.index); super.visit(e); return null; } @Override public Void visit(ArrayUpdateExpr e) { checkAccess(e.index.location, e.array, e.index); super.visit(e); return null; } private void checkAccess(Location location, Expr arrayExpr, Expr indexExpr) { if (isConstant(indexExpr)) { BigInteger index = evalIndex(indexExpr); ArrayType arrayType = getArrayType(arrayExpr); if (index.compareTo(BigInteger.ZERO) < 0 || index.compareTo(BigInteger.valueOf(arrayType.size)) >= 0) { StdErr.error(location, "index " + index + " out of range"); passed = false; } } } private ArrayType getArrayType(Expr e) { return (ArrayType) e.accept(typeReconstructor); } private boolean isConstant(Expr e) { return e.accept(constantAnalyzer); } private BigInteger evalIndex(Expr e) { return constantEvaluator.evalInt(e).value; } }
2,272
24.829545
106
java
jkind
jkind-master/jkind/src/jkind/analysis/evaluation/DivisionException.java
package jkind.analysis.evaluation; public class DivisionException extends RuntimeException { private static final long serialVersionUID = 1L; }
146
23.5
57
java
jkind
jkind-master/jkind/src/jkind/analysis/evaluation/InitialStepEvaluator.java
package jkind.analysis.evaluation; import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Node; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; import jkind.lustre.values.Value; import jkind.lustre.visitors.Evaluator; /** * This class is used by invariant generation to suggest upper and lower bounds * on states variables. It assumes that all transformations have been performed * and the Lustre is in a simple format. */ public class InitialStepEvaluator extends Evaluator { private Map<String, Value> values = new HashMap<>(); private ArrayDeque<String> evalStack = new ArrayDeque<>(); private Map<String, Expr> equations = new HashMap<>(); public InitialStepEvaluator(Node node) { for (VarDecl input : node.inputs) { values.put(input.id, null); } for (Equation eq : node.equations) { equations.put(eq.lhs.get(0).id, eq.expr); } } public Value eval(String id) { if (values.containsKey(id)) { return values.get(id); } else if (evalStack.contains(id)) { return null; } evalStack.push(id); Value value = equations.get(id).accept(this); values.put(id, value); evalStack.pop(); return value; } @Override public Value visit(BinaryExpr e) { if (e.op == BinaryOp.ARROW) { return e.left.accept(this); } else { return super.visit(e); } } @Override public Value visit(IdExpr e) { return eval(e.id); } @Override public Value visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { return null; } else { return super.visit(e); } } }
1,737
21.571429
79
java
jkind
jkind-master/jkind/src/jkind/analysis/evaluation/DivisionChecker.java
package jkind.analysis.evaluation; import java.math.BigInteger; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jkind.StdErr; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Constant; import jkind.lustre.EnumType; import jkind.lustre.IdExpr; import jkind.lustre.Program; import jkind.lustre.TypeDef; import jkind.lustre.values.EnumValue; import jkind.lustre.values.IntegerValue; import jkind.lustre.values.RealValue; import jkind.lustre.values.Value; import jkind.lustre.visitors.AstIterVisitor; import jkind.util.BigFraction; import jkind.util.Util; public class DivisionChecker extends AstIterVisitor { private final Map<String, Constant> constantDefinitions = new HashMap<>(); private final Set<String> enumeratedValues = new HashSet<>(); // In order to use a ConstantEvaluator, we first have to ensure that the // constants themselves don't have division by zero. This is a bit // tricky due to constants being defined in any order. private ConstantEvaluator constantEvaluator = new ConstantEvaluator() { @Override public Value visit(IdExpr e) { if (enumeratedValues.contains(e.id)) { return new EnumValue(e.id); } Value value = super.visit(e); if (value == null && constantDefinitions.containsKey(e.id)) { // Check constants on the fly checkConstant(constantDefinitions.get(e.id)); } return value; } }; public static boolean check(Program program) { try { new DivisionChecker().visit(program); return true; } catch (DivisionException e) { return false; } } @Override protected void visitTypeDefs(List<TypeDef> es) { for (EnumType et : Util.getEnumTypes(es)) { enumeratedValues.addAll(et.values); } } @Override protected void visitConstants(List<Constant> constants) { for (Constant c : constants) { constantDefinitions.put(c.id, c); } for (Constant c : constants) { if (!constantEvaluator.containsConstant(c.id)) { checkConstant(c); } } } private void checkConstant(Constant c) { c.accept(this); constantEvaluator.addConstant(c); } @Override public Void visit(BinaryExpr e) { e.left.accept(this); e.right.accept(this); if (e.op == BinaryOp.DIVIDE || e.op == BinaryOp.INT_DIVIDE || e.op == BinaryOp.MODULUS) { int rightSignum = signum(constantEvaluator.eval(e.right)); if (rightSignum == 0) { StdErr.error(e.location, "division by zero"); throw new DivisionException(); } else if (rightSignum < 0 && e.op == BinaryOp.INT_DIVIDE) { StdErr.error(e.location, "integer division by negative numbers is disabled"); throw new DivisionException(); } else if (rightSignum < 0 && e.op == BinaryOp.MODULUS) { StdErr.error(e.location, "modulus by negative numbers is disabled"); throw new DivisionException(); } } return null; } private int signum(Value value) { if (value instanceof IntegerValue) { IntegerValue iv = (IntegerValue) value; return iv.value.compareTo(BigInteger.ZERO); } else if (value instanceof RealValue) { RealValue rv = (RealValue) value; return rv.value.compareTo(BigFraction.ZERO); } else { /* * This should only arise for non-constant division which is * currently only enabled for Z3. We return 1 to allow everything to * go through. This allows, for example, users to divide by a * negative integer which gives different results for different * solvers, or even to divide by 0. We allow this, but may change * the semantics of those operations later. */ return 1; } } }
3,622
27.753968
91
java
jkind
jkind-master/jkind/src/jkind/analysis/evaluation/ConstantEvaluator.java
package jkind.analysis.evaluation; import java.util.HashMap; import java.util.Map; import jkind.lustre.Constant; import jkind.lustre.EnumType; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Program; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.EnumValue; import jkind.lustre.values.Value; import jkind.lustre.visitors.Evaluator; import jkind.util.Util; public class ConstantEvaluator extends Evaluator { private final Map<String, Value> constants = new HashMap<>(); private final Map<String, Expr> constantDefinitions = new HashMap<>(); public ConstantEvaluator() { } public ConstantEvaluator(Program program) { for (EnumType et : Util.getEnumTypes(program.types)) { for (String id : et.values) { constants.put(id, new EnumValue(id)); } } for (Constant c : program.constants) { constantDefinitions.put(c.id, c.expr); } for (Constant c : program.constants) { addConstant(c); } } public Value addConstant(Constant c) { return constants.put(c.id, c.expr.accept(this)); } public boolean containsConstant(String id) { return constants.containsKey(id); } @Override public Value visit(IdExpr e) { if (constants.containsKey(e.id)) { return constants.get(e.id); } else if (constantDefinitions.containsKey(e.id)) { return constantDefinitions.get(e.id).accept(this); } else { return null; } } @Override public Value visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { return e.expr.accept(this); } else { return super.visit(e); } } }
1,576
21.855072
71
java
jkind
jkind-master/jkind/src/jkind/engines/AdviceEngine.java
package jkind.engines; import java.util.List; import jkind.JKindSettings; import jkind.advice.Advice; import jkind.engines.invariant.AbstractInvariantGenerationEngine; import jkind.engines.invariant.ListInvariant; import jkind.engines.invariant.StructuredInvariant; import jkind.lustre.Expr; import jkind.translation.Specification; public class AdviceEngine extends AbstractInvariantGenerationEngine { public static final String NAME = "advice"; private final List<Expr> potentialInvariants; public AdviceEngine(Specification spec, JKindSettings settings, Director director, Advice advice) { super(NAME, spec, settings, director); advice.prune(spec.node); this.potentialInvariants = advice.getInvariants(); } @Override protected StructuredInvariant createInitialInvariant() { return new ListInvariant(potentialInvariants); } }
848
28.275862
100
java
jkind
jkind-master/jkind/src/jkind/engines/Engine.java
package jkind.engines; import java.util.ArrayList; import java.util.List; import jkind.JKindSettings; import jkind.engines.messages.MessageHandler; import jkind.engines.messages.StopMessage; import jkind.translation.Specification; public abstract class Engine extends MessageHandler implements Runnable { protected final String name; protected final Specification spec; protected final JKindSettings settings; protected final Director director; protected final List<String> properties; // The director process will read this from another thread, // so we make it volatile protected volatile Throwable throwable; public Engine(String name, Specification spec, JKindSettings settings, Director director) { this.name = name; this.spec = spec; this.settings = settings; this.director = director; this.properties = new ArrayList<>(spec.node.properties); } protected abstract void main(); @Override public void run() { try { main(); } catch (StopException se) { } catch (Throwable t) { throwable = t; } finally { stopReceivingMessages(); } } public String getName() { return name; } public Throwable getThrowable() { return throwable; } public void stopEngine() { receiveMessage(new StopMessage()); } protected String getScratchBase() { if (settings.scratch) { return settings.filename + "." + name; } else { return null; } } }
1,403
20.6
92
java
jkind
jkind-master/jkind/src/jkind/engines/KInductionEngine.java
package jkind.engines; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.JKindSettings; import jkind.engines.invariant.InvariantSet; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.Message; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.UnknownResult; import jkind.solvers.UnsatResult; import jkind.translation.Specification; import jkind.util.SexpUtil; import jkind.util.StreamIndex; public class KInductionEngine extends SolverBasedEngine { public static final String NAME = "k-induction"; private int kCurrent = 0; private int kLimit = 0; private InvariantSet invariants = new InvariantSet(); private Map<Integer, List<String>> baseStepValid = new HashMap<>(); public KInductionEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); } @Override public void main() { createVariables(-1); for (kCurrent = 0; kCurrent <= settings.n; kCurrent++) { comment("K = " + kCurrent); processMessagesAndWait(); pruneUnknownProperties(kCurrent); createVariables(kCurrent); assertTransitionAndInvariants(kCurrent); checkProperties(kCurrent); if (properties.isEmpty()) { return; } } sendUnknown(properties); } private void processMessagesAndWait() { processMessagesAndWaitUntil(() -> kCurrent <= kLimit); } private void pruneUnknownProperties(int kCurrent) { List<String> bmcValid = baseStepValid.remove(kCurrent); if (bmcValid == null) { return; } List<String> unknown = difference(properties, bmcValid); properties.removeAll(unknown); if (!unknown.isEmpty()) { sendUnknown(unknown); } } private List<String> difference(List<String> list1, List<String> list2) { List<String> result = new ArrayList<>(list1); result.removeAll(list2); return result; } private void checkProperties(int k) { List<String> possiblyValid = new ArrayList<>(properties); while (!possiblyValid.isEmpty()) { Result result = solver.query(getInductiveQuery(k, possiblyValid)); if (result instanceof SatResult || result instanceof UnknownResult) { Model model = getModel(result); if (model == null) { sendUnknown(properties); properties.clear(); break; } List<String> bad = getFalseProperties(possiblyValid, k, model); possiblyValid.removeAll(bad); if (result instanceof UnknownResult) { sendUnknown(bad); } sendInductiveCounterexamples(bad, k + 1, model); } else if (result instanceof UnsatResult) { properties.removeAll(possiblyValid); addPropertiesAsInvariants(k, possiblyValid); sendValid(possiblyValid, k); return; } } } private void addPropertiesAsInvariants(int k, List<String> valid) { List<Expr> newInvariants = valid.stream().map(IdExpr::new).collect(toList()); invariants.addAll(newInvariants); assertNewInvariants(newInvariants, k); } private void assertNewInvariants(List<Expr> invariants, int limit) { for (int i = 0; i <= limit; i++) { assertInvariants(invariants, i); } } private void assertInvariants(List<Expr> invariants, int i) { solver.assertSexp(SexpUtil.conjoinInvariants(invariants, i)); } private void assertTransitionAndInvariants(int k) { assertInductiveTransition(k); assertInvariants(invariants.getInvariants(), k); } private Sexp getInductiveQuery(int k, List<String> possiblyValid) { List<Sexp> hyps = new ArrayList<>(); for (int i = 0; i < k; i++) { hyps.add(StreamIndex.conjoinEncodings(possiblyValid, i)); } Sexp conc = StreamIndex.conjoinEncodings(possiblyValid, k); return new Cons("=>", SexpUtil.conjoin(hyps), conc); } private void sendValid(List<String> valid, int k) { Itinerary itinerary = director.getValidMessageItinerary(); Message vm = new ValidMessage(getName(), valid, k, getRuntime(), invariants.getInvariants(), null, itinerary, null, false); director.broadcast(vm); } private void sendInductiveCounterexamples(List<String> properties, int length, Model model) { if (settings.inductiveCounterexamples && properties.size() > 0) { director.broadcast(new InductiveCounterexampleMessage(properties, length, model)); } } private void sendUnknown(List<String> unknown) { director.receiveMessage(new UnknownMessage(getName(), unknown)); } @Override protected void handleMessage(BaseStepMessage bsm) { kLimit = bsm.step; baseStepValid.put(bsm.step, bsm.properties); } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { properties.removeAll(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { List<Expr> supported = im.invariants.stream().filter(solver::supports).collect(toList()); invariants.addAll(supported); assertNewInvariants(supported, kCurrent - 1); } @Override protected void handleMessage(UnknownMessage um) { properties.removeAll(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { properties.removeAll(vm.valid); addPropertiesAsInvariants(kCurrent - 1, vm.valid); } private double getRuntime() { return (System.currentTimeMillis() - director.startTime) / 1000.0; } }
5,768
28.136364
111
java
jkind
jkind-master/jkind/src/jkind/engines/SolverUtil.java
package jkind.engines; import static java.util.stream.Collectors.toList; import java.util.Arrays; import java.util.List; import jkind.JKindException; import jkind.SolverOption; import jkind.analysis.LinearChecker; import jkind.analysis.YicesArithOnlyCheck; import jkind.lustre.Node; import jkind.lustre.builders.NodeBuilder; import jkind.solvers.Solver; import jkind.solvers.cvc4.Cvc4Solver; import jkind.solvers.mathsat.MathSatSolver; import jkind.solvers.smtinterpol.SmtInterpolSolver; import jkind.solvers.yices.YicesSolver; import jkind.solvers.yices2.Yices2Solver; import jkind.solvers.z3.Z3Solver; public class SolverUtil { public static Solver getSolver(SolverOption solverOption, String scratchBase, Node node) { switch (solverOption) { case YICES: return new YicesSolver(scratchBase, YicesArithOnlyCheck.check(node)); case CVC4: return new Cvc4Solver(scratchBase); case Z3: return new Z3Solver(scratchBase, LinearChecker.isLinear(node)); case YICES2: return new Yices2Solver(scratchBase, LinearChecker.isLinear(node)); case MATHSAT: return new MathSatSolver(scratchBase); case SMTINTERPOL: return new SmtInterpolSolver(scratchBase); } throw new IllegalArgumentException("Unknown solver: " + solverOption); } public static Solver getBasicSolver(SolverOption solverOption) { Node emptyNode = new NodeBuilder("empty").build(); return getSolver(solverOption, null, emptyNode); } public static boolean solverIsAvailable(SolverOption solverOption) { try { getBasicSolver(solverOption); } catch (JKindException e) { return false; } return true; } public static List<SolverOption> availableSolvers() { return Arrays.stream(SolverOption.values()).filter(x -> solverIsAvailable(x)).collect(toList()); } }
1,775
29.101695
98
java
jkind
jkind-master/jkind/src/jkind/engines/StopException.java
package jkind.engines; public class StopException extends RuntimeException { private static final long serialVersionUID = 1L; }
130
20.833333
53
java
jkind
jkind-master/jkind/src/jkind/engines/BmcEngine.java
package jkind.engines; import java.util.ArrayList; import java.util.List; import jkind.JKindSettings; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.UnknownResult; import jkind.translation.Specification; import jkind.util.StreamIndex; public class BmcEngine extends SolverBasedEngine { public static final String NAME = "bmc"; private List<String> validProperties = new ArrayList<>(); public BmcEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); } @Override public void main() { createVariables(-1); for (int k = 0; k < settings.n; k++) { comment("K = " + (k + 1)); processMessages(); if (properties.isEmpty()) { return; } createVariables(k); assertBaseTransition(k); checkProperties(k); assertProperties(k); } sendUnknown(properties); } private void checkProperties(int k) { Result result; do { result = solver.query(StreamIndex.conjoinEncodings(properties, k)); if (result instanceof SatResult || result instanceof UnknownResult) { Model model = getModel(result); if (model == null) { sendUnknown(properties); properties.clear(); break; } List<String> bad = getFalseProperties(properties, k, model); properties.removeAll(bad); if (result instanceof SatResult) { sendInvalid(bad, k, model); } else { sendUnknown(bad); } } } while (!properties.isEmpty() && result instanceof SatResult); sendBaseStep(k); } private void sendInvalid(List<String> invalid, int k, Model model) { Itinerary itinerary = director.getInvalidMessageItinerary(); director.broadcast(new InvalidMessage(getName(), invalid, k + 1, model, itinerary)); } private void sendBaseStep(int k) { director.broadcast(new BaseStepMessage(k + 1, properties)); } private void sendUnknown(List<String> unknown) { director.receiveMessage(new UnknownMessage(getName(), unknown)); } private void assertProperties(int k) { assertProperties(properties, k); assertProperties(validProperties, k); } private void assertProperties(List<String> properties, int k) { for (String prop : properties) { solver.assertSexp(new StreamIndex(prop, k).getEncoded()); } } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { properties.removeAll(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { } @Override protected void handleMessage(ValidMessage vm) { properties.removeAll(vm.valid); validProperties.addAll(vm.valid); } }
3,151
24.626016
86
java
jkind
jkind-master/jkind/src/jkind/engines/MiniJKind.java
package jkind.engines; import static java.util.stream.Collectors.toList; import java.util.List; import java.util.Set; import jkind.AllIvcsAlgorithm; import jkind.ExitCodes; import jkind.JKindSettings; import jkind.engines.ivcs.IvcUtil; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.Program; import jkind.results.Counterexample; import jkind.translation.Specification; public class MiniJKind extends Engine { public static final String NAME = "mini-jkind"; private Director director; public static final String UNKNOWN = "UNKNOWN"; public static final String UNKNOWN_WITH_EXCEPTION = "UNKNOW_WITH_EXCEPTION"; public static final String INVALID = "INVALID"; public static final String VALID = "VALID"; public static final String NOT_YET_CHECKED = "NOT_YET_CHECKED"; private ValidMessage validMessage; private Counterexample invalidModel; private double runtime; private String status = NOT_YET_CHECKED; public MiniJKind(Program program, Specification spec, JKindSettings settings) { super(NAME, spec, settings, null); if (spec.node.properties.size() != 1) { throw new IllegalArgumentException("MiniJKind Expects exactly one property"); } // make sure the caller set these variables correctly settings.xml = false; settings.xmlToStdout = false; settings.allIvcs = false; settings.allIvcsAlgorithm = AllIvcsAlgorithm.OFFLINE_MIVC_ENUM_ALG; settings.allIvcsMaxGrows = 1000; settings.allIvcsJkindTimeout = -1; settings.excel = false; settings.miniJkind = true; if (settings.allAssigned && settings.reduceIvc) { program = IvcUtil.setIvcArgs(spec.node, IvcUtil.getAllAssigned(spec.node)); this.director = new Director(settings, new Specification(program, settings.slicing), new Specification(program, settings.slicing), this); } else if (!settings.allAssigned && settings.reduceIvc) { this.director = new Director(settings, new Specification(program, settings.slicing), new Specification(program, settings.slicing), this); } else { this.director = new Director(settings, spec, spec, this); } settings.miniJkind = true; } public void verify() { try { int ret = director.run(); if (ret == ExitCodes.IVC_EXCEPTION) { status = UNKNOWN_WITH_EXCEPTION; } } catch (Throwable t) { System.exit(ExitCodes.UNCAUGHT_EXCEPTION); } } public void setValidMessage(ValidMessage vm) { status = VALID; validMessage = new ValidMessage(vm.source, vm.valid, vm.k, vm.proofTime, vm.invariants, vm.ivc, null, null, false); } public ValidMessage getValidMessage() { return validMessage; } public void setInvalid(Counterexample cex) { status = INVALID; this.invalidModel = cex; } public Counterexample getInvalidModel() { return invalidModel; } public double getRuntime() { return runtime; } public void setRuntime(double rt) { runtime = rt; } public void setUnknown() { status = UNKNOWN; } public String getPropertyStatus() { return status; } public Set<String> getPropertyIvc() { return validMessage.ivc; } public List<String> getPropertyInvariants() { return validMessage.invariants.stream().map(Object::toString).collect(toList()); } public int getK() { return validMessage.k; } @Override protected void main() { } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { } @Override protected void handleMessage(ValidMessage vm) { } }
3,945
24.458065
109
java
jkind
jkind-master/jkind/src/jkind/engines/Director.java
package jkind.engines; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import jkind.ExitCodes; import jkind.JKindException; import jkind.JKindSettings; import jkind.Main; import jkind.StdErr; import jkind.advice.Advice; import jkind.advice.AdviceReader; import jkind.advice.AdviceWriter; import jkind.engines.invariant.GraphInvariantGenerationEngine; import jkind.engines.ivcs.AllIVCs; import jkind.engines.ivcs.AllIvcsExtractorEngine; import jkind.engines.ivcs.IvcReductionEngine; import jkind.engines.ivcs.IvcUtil; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.EngineType; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.Message; import jkind.engines.messages.MessageHandler; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.engines.pdr.PdrEngine; import jkind.lustre.Expr; import jkind.results.Counterexample; import jkind.results.layout.NodeLayout; import jkind.solvers.Model; import jkind.translation.Specification; import jkind.util.CounterexampleExtractor; import jkind.util.ModelReconstructionEvaluator; import jkind.util.Util; import jkind.writers.ConsoleWriter; import jkind.writers.ExcelWriter; import jkind.writers.Writer; import jkind.writers.XmlWriter; public class Director extends MessageHandler { public static final String NAME = "director"; private final JKindSettings settings; private final Specification userSpec; private final Specification analysisSpec; private final Writer writer; public final long startTime; private final List<String> remainingProperties = new ArrayList<>(); private final List<String> validProperties = new ArrayList<>(); private final List<String> invalidProperties = new ArrayList<>(); private int baseStep = 0; private final Map<String, InductiveCounterexampleMessage> inductiveCounterexamples = new HashMap<>(); private final List<Engine> engines = new ArrayList<>(); private final List<Thread> threads = new ArrayList<>(); private Advice inputAdvice; private AdviceWriter adviceWriter; private MiniJKind miniJkind; public Director(JKindSettings settings, Specification userSpec, Specification analysisSpec) { this(settings, userSpec, analysisSpec, null); } public Director(JKindSettings settings, Specification userSpec, Specification analysisSpec, MiniJKind miniJkind) { this.settings = settings; this.userSpec = userSpec; this.analysisSpec = analysisSpec; this.miniJkind = miniJkind; this.writer = getWriter(); this.startTime = System.currentTimeMillis(); this.remainingProperties.addAll(analysisSpec.node.properties); if (settings.readAdvice != null) { this.inputAdvice = AdviceReader.read(settings.readAdvice); } if (settings.writeAdvice != null) { this.adviceWriter = new AdviceWriter(settings.writeAdvice); this.adviceWriter.addVarDecls(Util.getVarDecls(analysisSpec.node)); } initializeUnknowns(settings, analysisSpec.node.properties); } private final Writer getWriter() { try { if (settings.excel) { return new ExcelWriter(settings.filename + ".xls", userSpec.node); } else if (settings.xml) { return new XmlWriter(settings.filename + ".xml", userSpec.typeMap, settings.xmlToStdout); } else if (settings.miniJkind) { return new ConsoleWriter(new NodeLayout(userSpec.node), miniJkind); } else { return new ConsoleWriter(new NodeLayout(userSpec.node)); } } catch (IOException e) { throw new JKindException("Unable to open output file", e); } } public int run() { if (!settings.miniJkind) { printHeader(); } writer.begin(); addShutdownHook(); createAndStartEngines(); while (!timeout() && propertiesRemaining() && someThreadAlive() && !someEngineFailed() && !exitRequested()) { processMessages(); sleep(100); } processMessages(); int exitCode = 0; if (removeShutdownHook()) { postProcessing(); exitCode = reportFailures(); } // Needed for minijkind; other cases the top-level jkind shuts down if (settings.miniJkind) { stopEngines(); } return exitCode; } private boolean exitRequested() { try { while (System.in.available() > 0) { if (System.in.read() == Util.END_OF_TEXT) { return true; } } } catch (IOException e) { } return false; } private void postProcessing() { writeUnknowns(); writer.end(); writeAdvice(); printSummary(); } private final Thread shutdownHook = new Thread("shutdown-hook") { @Override public void run() { Director.sleep(100); postProcessing(); } }; private void addShutdownHook() { Runtime.getRuntime().addShutdownHook(shutdownHook); } private boolean removeShutdownHook() { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); return true; } catch (IllegalStateException e) { // JVM already shutting down return false; } } private void createAndStartEngines() { createEngines(); threads.forEach(Thread::start); } private void createEngines() { if (settings.boundedModelChecking) { addEngine(new BmcEngine(analysisSpec, settings, this)); } if (settings.kInduction) { addEngine(new KInductionEngine(analysisSpec, settings, this)); } if (settings.invariantGeneration) { addEngine(new GraphInvariantGenerationEngine(analysisSpec, settings, this)); } if (settings.smoothCounterexamples) { addEngine(new SmoothingEngine(analysisSpec, settings, this)); } if (settings.pdrMax > 0) { addEngine(new PdrEngine(analysisSpec, settings, this)); } if (settings.readAdvice != null) { addEngine(new AdviceEngine(analysisSpec, settings, this, inputAdvice)); } if (settings.reduceIvc) { addEngine(new IvcReductionEngine(analysisSpec, settings, this)); } if (settings.allIvcs) { addEngine(new AllIvcsExtractorEngine(analysisSpec, settings, this)); } } private void addEngine(Engine engine) { engines.add(engine); threads.add(new Thread(engine, engine.getName())); } private void stopEngines() { try { for (Engine engine : engines) { // Add code to kill thread. engine.stopEngine(); } } catch (Throwable t) { } } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } private boolean timeout() { long timeout = startTime + ((long) settings.timeout) * 1000; return System.currentTimeMillis() > timeout; } private boolean propertiesRemaining() { return !remainingProperties.isEmpty(); } private boolean someThreadAlive() { return threads.stream().anyMatch(Thread::isAlive); } private boolean someEngineFailed() { return engines.stream().anyMatch(e -> e.getThrowable() != null); } private void writeUnknowns() { if (!remainingProperties.isEmpty()) { writer.writeUnknown(remainingProperties, baseStep, convertInductiveCounterexamples(), getRuntime()); } } private int reportFailures() { int exitCode = 0; for (Engine engine : engines) { // MWW: specialized for miniJKind - we kill solvers abruptly // for "internal" runs. boolean engine_throwable = (engine.getThrowable() != null); boolean no_minijkind = (!settings.miniJkind); boolean timeout = timeout(); if (engine_throwable) { StdErr.println(engine.getName() + " process failed"); StdErr.printStackTrace(engine.getThrowable()); exitCode = ExitCodes.UNCAUGHT_EXCEPTION; if (engine.getThrowable().toString().contains("IvcException")) { exitCode = ExitCodes.IVC_EXCEPTION; } if (!no_minijkind) { StdErr.println("failed during miniJKind run"); } if (timeout) { StdErr.println("timeout occurred"); } } } return exitCode; } private void printHeader() { if (!settings.xmlToStdout) { System.out.println("=========================================="); System.out.println(" JKind " + Main.getVersion()); System.out.println("=========================================="); System.out.println(); System.out.println("There are " + remainingProperties.size() + " properties to be checked."); System.out.println("PROPERTIES TO BE CHECKED: " + remainingProperties); System.out.println(); } } private void writeAdvice() { if (adviceWriter != null) { adviceWriter.write(); } } public void broadcast(Message message) { receiveMessage(message); for (Engine engine : engines) { engine.receiveMessage(message); } } @Override protected void handleMessage(ValidMessage vm) { if (vm.getNextDestination() != null) { if (vm.getNextDestination().equals(EngineType.IVC_REDUCTION) && adviceWriter != null) { adviceWriter.addInvariants(vm.invariants); } return; } List<String> newValid = intersect(vm.valid, remainingProperties); if (newValid.isEmpty()) { return; } remainingProperties.removeAll(newValid); validProperties.addAll(newValid); inductiveCounterexamples.keySet().removeAll(newValid); if (adviceWriter != null) { adviceWriter.addInvariants(vm.invariants); } List<Expr> invariants = settings.reduceIvc ? vm.invariants : Collections.emptyList(); if ((!settings.miniJkind) && (settings.reduceIvc)) { Set<String> ivc = IvcUtil.findRightSide(vm.ivc, settings.allAssigned, analysisSpec.node.equations); List<AllIVCs> allIvcs = new ArrayList<>(); if (settings.allIvcs) { for (AllIVCs item : vm.allIvcs) { allIvcs.add(new AllIVCs(IvcUtil.findRightSide(item.getAllIVCSet(), settings.allAssigned, analysisSpec.node.equations), item.getAllIVCList())); } } writer.writeValid(newValid, vm.source, vm.k, vm.proofTime, getRuntime(), invariants, ivc, allIvcs, vm.mivcTimedOut); } else { writer.writeValid(newValid, vm.source, vm.k, vm.proofTime, getRuntime(), invariants, vm.ivc, vm.allIvcs, vm.mivcTimedOut); } } private List<String> intersect(List<String> list1, List<String> list2) { List<String> result = new ArrayList<>(); result.addAll(list1); result.retainAll(list2); return result; } @Override protected void handleMessage(InvalidMessage im) { if (im.getNextDestination() != null) { return; } List<String> newInvalid = intersect(im.invalid, remainingProperties); if (newInvalid.isEmpty()) { return; } remainingProperties.removeAll(newInvalid); invalidProperties.addAll(newInvalid); inductiveCounterexamples.keySet().removeAll(newInvalid); double runtime = getRuntime(); for (String invalidProp : newInvalid) { Counterexample cex = extractCounterexample(invalidProp, im.length, im.model, true); writer.writeInvalid(invalidProp, im.source, cex, Collections.emptyList(), runtime); } } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { for (String property : icm.properties) { inductiveCounterexamples.put(property, icm); } } private final Map<String, Integer> bmcUnknowns = new HashMap<>(); private final Set<String> kInductionUnknowns = new HashSet<>(); private final Set<String> pdrUnknowns = new HashSet<>(); private void initializeUnknowns(JKindSettings settings, List<String> properties) { if (!settings.boundedModelChecking) { for (String prop : properties) { bmcUnknowns.put(prop, 0); } } if (!settings.kInduction) { kInductionUnknowns.addAll(properties); } if (settings.pdrMax <= 0) { pdrUnknowns.addAll(properties); } } @Override protected void handleMessage(UnknownMessage um) { if (um.source.equals(NAME)) { return; } markUnknowns(um); Map<Integer, List<String>> completed = getCompletelyUnknownByBaseStep(um); for (Entry<Integer, List<String>> entry : completed.entrySet()) { int baseStep = entry.getKey(); List<String> unknowns = entry.getValue(); remainingProperties.removeAll(unknowns); writer.writeUnknown(um.unknown, baseStep, convertInductiveCounterexamples(), getRuntime()); broadcast(new UnknownMessage(NAME, unknowns)); } } private Map<Integer, List<String>> getCompletelyUnknownByBaseStep(UnknownMessage um) { return um.unknown.stream().filter(this::isCompletelyUnknown).collect(Collectors.groupingBy(bmcUnknowns::get)); } private void markUnknowns(UnknownMessage um) { switch (um.source) { case BmcEngine.NAME: for (String prop : um.unknown) { bmcUnknowns.put(prop, baseStep); } break; case KInductionEngine.NAME: kInductionUnknowns.addAll(um.unknown); break; case PdrEngine.NAME: pdrUnknowns.addAll(um.unknown); break; } } public boolean isCompletelyUnknown(String prop) { return bmcUnknowns.containsKey(prop) && kInductionUnknowns.contains(prop) && pdrUnknowns.contains(prop); } @Override protected void handleMessage(BaseStepMessage bsm) { baseStep = bsm.step; if (!bsm.properties.isEmpty()) { writer.writeBaseStep(bsm.properties, baseStep); } } @Override protected void handleMessage(InvariantMessage im) { } public Itinerary getValidMessageItinerary() { List<EngineType> destinations = new ArrayList<>(); if (settings.reduceIvc) { destinations.add(EngineType.IVC_REDUCTION); } if (settings.allIvcs) { destinations.add(EngineType.IVC_REDUCTION_ALL); } return new Itinerary(destinations); } public Itinerary getInvalidMessageItinerary() { List<EngineType> destinations = new ArrayList<>(); if (settings.smoothCounterexamples) { destinations.add(EngineType.SMOOTHING); } return new Itinerary(destinations); } private double getRuntime() { return (System.currentTimeMillis() - startTime) / 1000.0; } private void printSummary() { if (!settings.xmlToStdout && !settings.miniJkind) { System.out.println(" -------------------------------------"); System.out.println(" --^^-- SUMMARY --^^--"); System.out.println(" -------------------------------------"); System.out.println(); if (!validProperties.isEmpty()) { System.out.println("VALID PROPERTIES: " + validProperties); System.out.println(); } if (!invalidProperties.isEmpty()) { System.out.println("INVALID PROPERTIES: " + invalidProperties); System.out.println(); } List<String> unknownProperties = new ArrayList<>(analysisSpec.node.properties); unknownProperties.removeAll(validProperties); unknownProperties.removeAll(invalidProperties); if (!unknownProperties.isEmpty()) { System.out.println("UNKNOWN PROPERTIES: " + unknownProperties); System.out.println(); } } } private Map<String, Counterexample> convertInductiveCounterexamples() { Map<String, Counterexample> result = new HashMap<>(); for (String prop : inductiveCounterexamples.keySet()) { InductiveCounterexampleMessage icm = inductiveCounterexamples.get(prop); result.put(prop, extractCounterexample(prop, icm.length, icm.model, false)); } return result; } private Counterexample extractCounterexample(String property, int k, Model model, boolean concrete) { model = ModelReconstructionEvaluator.reconstruct(userSpec, analysisSpec, model, property, k, concrete); return CounterexampleExtractor.extract(userSpec, k, model); } }
15,410
27.644981
115
java
jkind
jkind-master/jkind/src/jkind/engines/SolverBasedEngine.java
package jkind.engines; import java.util.ArrayList; import java.util.List; import jkind.JKindSettings; import jkind.engines.messages.StopMessage; import jkind.lustre.Expr; import jkind.lustre.LustreUtil; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; import jkind.lustre.values.BooleanValue; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.Solver; import jkind.solvers.UnknownResult; import jkind.translation.Lustre2Sexp; import jkind.translation.Specification; import jkind.util.StreamIndex; import jkind.util.Util; public abstract class SolverBasedEngine extends Engine { protected Solver solver; public SolverBasedEngine(String name, Specification spec, JKindSettings settings, Director director) { super(name, spec, settings, director); } @Override public final void run() { try { initializeSolver(); super.run(); } catch (StopException se) { } catch (NullPointerException n) { } catch (Throwable t) { throwable = t; } finally { killEngine(); } } protected void initializeSolver() { solver = getSolver(); solver.initialize(); solver.declare(spec.functions); solver.define(spec.getTransitionRelation()); solver.define(new VarDecl(INIT.str, NamedType.BOOL)); } public synchronized void killEngine() { if (solver != null) { solver.stop(); solver = null; } } @Override public void stopEngine() { killEngine(); receiveMessage(new StopMessage()); } protected Solver getSolver() { return SolverUtil.getSolver(settings.solver, getScratchBase(), spec.node); } /** Utility */ protected void comment(String str) { solver.comment(str); } protected void createVariables(int k) { for (VarDecl vd : getOffsetVarDecls(k)) { solver.define(vd); } for (VarDecl vd : Util.getVarDecls(spec.node)) { Expr constraint = LustreUtil.typeConstraint(vd.id, vd.type); if (constraint != null) { solver.assertSexp(constraint.accept(new Lustre2Sexp(k))); } } } protected List<VarDecl> getOffsetVarDecls(int k) { List<VarDecl> result = new ArrayList<>(); for (VarDecl vd : Util.getVarDecls(spec.node)) { StreamIndex si = new StreamIndex(vd.id, k); result.add(new VarDecl(si.getEncoded().str, vd.type)); } return result; } protected static final Symbol INIT = Lustre2Sexp.INIT; protected void assertBaseTransition(int k) { solver.assertSexp(getBaseTransition(k)); } protected void assertInductiveTransition(int k) { solver.assertSexp(getInductiveTransition(k)); } protected Sexp getBaseTransition(int k) { return getTransition(k, k == 0); } protected Sexp getInductiveTransition(int k) { if (k == 0) { return getTransition(0, INIT); } else { return getTransition(k, false); } } protected Sexp getTransition(int k, boolean init) { return getTransition(k, Sexp.fromBoolean(init)); } protected Sexp getTransition(int k, Sexp init) { List<Sexp> args = new ArrayList<>(); args.add(init); args.addAll(getSymbols(getOffsetVarDecls(k - 1))); args.addAll(getSymbols(getOffsetVarDecls(k))); return new Cons(spec.getTransitionRelation().getName(), args); } protected List<Sexp> getSymbols(List<VarDecl> varDecls) { List<Sexp> result = new ArrayList<>(); for (VarDecl vd : varDecls) { result.add(new Symbol(vd.id)); } return result; } protected Model getModel(Result result) { if (result instanceof SatResult) { return ((SatResult) result).getModel(); } else if (result instanceof UnknownResult) { return ((UnknownResult) result).getModel(); } else { throw new IllegalArgumentException(); } } protected List<String> getFalseProperties(List<String> properties, int k, Model model) { List<String> falses = new ArrayList<>(); for (String p : properties) { StreamIndex si = new StreamIndex(p, k); BooleanValue v = (BooleanValue) model.getValue(si); if (!v.value) { falses.add(p); } } return falses; } }
4,044
23.664634
103
java
jkind
jkind-master/jkind/src/jkind/engines/SmoothingEngine.java
package jkind.engines; import jkind.JKindException; import jkind.JKindSettings; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.EngineType; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.VarDecl; import jkind.sexp.Cons; import jkind.sexp.Symbol; import jkind.slicing.Dependency; import jkind.slicing.DependencySet; import jkind.solvers.MaxSatSolver; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.UnsatResult; import jkind.translation.Specification; import jkind.util.StreamIndex; public class SmoothingEngine extends SolverBasedEngine { public static final String NAME = "smoothing"; private MaxSatSolver maxSatSolver; public SmoothingEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); } @Override protected void initializeSolver() { super.initializeSolver(); maxSatSolver = (MaxSatSolver) solver; } @Override public void main() { processMessagesAndWaitUntil(() -> properties.isEmpty()); } private void smooth(InvalidMessage im) { for (String property : im.invalid) { if (properties.remove(property)) { smooth(property, im); } } } private void smooth(String property, InvalidMessage im) { comment("Smoothing: " + property); DependencySet relevant = spec.dependencyMap.get(property); solver.push(); createVariables(-1); for (int i = 0; i < im.length; i++) { createVariables(i); assertBaseTransition(i); if (i > 0) { assertDeltaCost(i, relevant); } } Result result = maxSatSolver.maxsatQuery(new StreamIndex(property, im.length - 1).getEncoded()); if (result instanceof UnsatResult) { throw new JKindException("Failed to recreate counterexample in smoother"); } Model smoothModel = getModel(result); if (smoothModel == null) { // 'unknown' result without model, skip smoothing smoothModel = im.model; } solver.pop(); sendCounterexample(property, smoothModel, im); } private void assertDeltaCost(int k, DependencySet relevant) { for (VarDecl input : spec.node.inputs) { if (relevant.contains(Dependency.variable(input.id))) { Symbol prev = new StreamIndex(input.id, k - 1).getEncoded(); Symbol curr = new StreamIndex(input.id, k).getEncoded(); maxSatSolver.assertSoft(new Cons("=", prev, curr)); } } } private void sendCounterexample(String property, Model model, InvalidMessage im) { comment("Sending " + property); Itinerary itinerary = im.getNextItinerary(); director.broadcast(new InvalidMessage(im.source, property, im.length, model, itinerary)); } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { if (im.getNextDestination() == EngineType.SMOOTHING) { smooth(im); properties.removeAll(im.invalid); } } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { properties.removeAll(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { properties.removeAll(vm.valid); } }
3,466
26.299213
98
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/CounterexampleException.java
package jkind.engines.pdr; import jkind.solvers.Model; public class CounterexampleException extends RuntimeException { private static final long serialVersionUID = 1L; private final int length; private final Model model; public CounterexampleException(int length, Model model) { this.model = model; this.length = length; } public Model getModel() { return model; } public int getLength() { return length; } }
431
17.782609
63
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/Frame.java
package jkind.engines.pdr; import java.util.HashSet; import java.util.Set; import de.uni_freiburg.informatik.ultimate.logic.Script; import de.uni_freiburg.informatik.ultimate.logic.Term; import de.uni_freiburg.informatik.ultimate.logic.Util; public class Frame { private final Term term; private final Set<Cube> cubes = new HashSet<>(); public Frame(Term term) { this.term = term; } public Frame() { this.term = null; } public Term toTerm(Script script) { if (term != null) { return term; } Term[] terms = new Term[cubes.size()]; int i = 0; for (Cube c : cubes) { terms[i] = Util.not(script, c.toTerm(script)); i++; } return Util.and(script, terms); } public void add(Cube c) { assert term == null; cubes.add(c); } public Set<Cube> getCubes() { return cubes; } public boolean isEmpty() { return term == null && cubes.isEmpty(); } @Override public String toString() { if (term != null) { return term.toString(); } else { return cubes.toString(); } } }
1,026
16.706897
56
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/NameGenerator.java
package jkind.engines.pdr; import java.util.ArrayList; import java.util.List; public class NameGenerator { private final String prefix; private int counter = 0; public NameGenerator(String prefix) { this.prefix = prefix; } public String getNextName() { return prefix + counter++; } public List<String> getAllNames() { List<String> result = new ArrayList<>(); for (int i = 0; i < counter; i++) { result.add(prefix + i); } return result; } }
468
17.038462
42
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/TCube.java
package jkind.engines.pdr; public class TCube implements Comparable<TCube> { public static final int FRAME_NULL = -1; public static final int FRAME_INF = Integer.MAX_VALUE; private final Cube cube; private int frame; public TCube(Cube cube, int frame) { this.cube = cube; this.frame = frame; } public Cube getCube() { return cube; } public int getFrame() { return frame; } public void setFrame(int frame) { assert (this.frame == FRAME_NULL); this.frame = frame; } public TCube next() { return new TCube(cube, frame + 1); } @Override public int compareTo(TCube other) { assert (frame != FRAME_NULL); assert (frame != FRAME_INF); assert (other.frame != FRAME_NULL); assert (other.frame != FRAME_INF); return frame - other.frame; } @Override public String toString() { return frame + ": " + cube; } }
854
17.191489
55
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/PdrSubengine.java
package jkind.engines.pdr; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import de.uni_freiburg.informatik.ultimate.logic.Term; import jkind.analysis.LinearChecker; import jkind.engines.Director; import jkind.engines.StopException; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.ValidMessage; import jkind.engines.pdr.PdrSmt.Option; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.Node; import jkind.lustre.builders.NodeBuilder; import jkind.slicing.LustreSlicer; import jkind.solvers.Model; import jkind.translation.Specification; /** * PDR algorithm based on "Efficient implementation of property directed * reachability" by Niklas Een, Alan Mishchenko, and Robert Brayton * * SMT extension based on "IC3 Modulo Theories via Implicit Predicate * Abstraction" by Alessandro Cimatti, Alberto Griggio, Sergio Mover, and * Stefano Tonetta */ public class PdrSubengine extends Thread { private final Node node; private final List<Function> functions; private final String prop; private final PdrEngine parent; private final Director director; private final List<Frame> F = new ArrayList<>(); private final String scratchBase; private PdrSmt Z; private volatile boolean cancel = false; public PdrSubengine(String prop, Specification spec, String scratchBase, PdrEngine parent, Director director) { super("pdr-" + prop); this.prop = prop; Node single = new NodeBuilder(spec.node).clearProperties().addProperty(prop).build(); this.node = LustreSlicer.slice(single, spec.dependencyMap); this.functions = spec.functions; this.scratchBase = scratchBase; this.parent = parent; this.director = director; } public void cancel() { cancel = true; } @Override public void run() { if (!LinearChecker.isLinear(this.node)) { parent.reportUnknown(prop); return; } Z = new PdrSmt(node, functions, F, prop, scratchBase); Z.comment("Checking property: " + prop); // Create F_INF and F[0] F.add(new Frame()); addFrame(Z.createInitialFrame()); try { while (true) { Cube c = Z.getBadCube(); if (c != null) { blockCube(new TCube(c, depth())); } else { addFrame(new Frame()); Z.comment("Number of frames: " + F.size()); List<Expr> invariants = propogateBlockedCubes(); if (invariants != null) { sendValidAndInvariants(invariants); return; } } } } catch (CounterexampleException cex) { Z.comment("Found counterexample of length " + cex.getLength()); sendInvalid(cex.getLength(), cex.getModel()); return; } catch (StopException | OutOfMemoryError e) { parent.reportUnknown(prop); return; } catch (Throwable t) { parent.reportThrowable(t); return; } } private void blockCube(TCube s0) { PriorityQueue<TCube> Q = new PriorityQueue<>(); Q.add(s0); while (!Q.isEmpty()) { checkCancel(); TCube s = Q.poll(); if (s.getFrame() == 0) { Z.refine(getCubes(s.getCube())); Z.comment("Refined abstraction"); return; } if (!isBlocked(s)) { assert (!Z.isInitial(s.getCube())); TCube z = Z.solveRelative(s, Option.EXTRACT_MODEL); if (z.getFrame() != TCube.FRAME_NULL) { // Cube 's' was blocked by image of predecessor generalize(z); // Push z as far forward as possible while (z.getFrame() < depth() - 1) { TCube nz = Z.solveRelative(z.next()); if (nz.getFrame() != TCube.FRAME_NULL) { z = nz; } else { break; } } addBlockedCube(z); if (s.getFrame() < depth() && z.getFrame() != TCube.FRAME_INF) { Q.add(s.next()); } } else { // Cube 's' was not blocked by image of predecessor z.setFrame(s.getFrame() - 1); z.getCube().setNext(s.getCube()); Q.add(z); Q.add(s); } } } } private boolean isBlocked(TCube s) { // Check syntactic subsumption (faster than SAT): for (int d = s.getFrame(); d < F.size(); d++) { for (Cube c : F.get(d).getCubes()) { if (c.subsumes(s.getCube())) { return true; } } } // Semantic subsumption thru SAT: return Z.isBlocked(s); } private void generalize(TCube s) { List<Term> pLiterals = new ArrayList<>(s.getCube().getPLiterals()); for (Term p : pLiterals) { s.getCube().removePLiteral(p); if (Z.isInitial(s.getCube()) || Z.solveRelative(s).getFrame() == TCube.FRAME_NULL) { s.getCube().addPLiteral(p); } } } private int depth() { return F.size() - 2; } private void addFrame(Frame frame) { F.add(F.size() - 1, frame); } private List<Expr> propogateBlockedCubes() { for (int k = 1; k < depth(); k++) { for (Cube c : new ArrayList<>(F.get(k).getCubes())) { checkCancel(); TCube s = Z.solveRelative(new TCube(c, k + 1), Option.NO_IND); if (s.getFrame() != TCube.FRAME_NULL) { addBlockedCube(s); } } if (F.get(k).isEmpty()) { return getInvariants(k + 1); } } return null; } private List<Expr> getInvariants(int k) { List<Expr> invariants = new ArrayList<>(); for (int i = k; i < F.size(); i++) { for (Cube c : F.get(i).getCubes()) { invariants.add(Z.getInvariant(c)); } } return invariants; } private void checkCancel() { if (cancel) { throw new StopException(); } } private void addBlockedCube(TCube s) { int k = Math.min(s.getFrame(), depth() + 1); // Remove subsumed clauses: for (int d = 1; d <= k; d++) { Set<Cube> cubes = F.get(d).getCubes(); for (Cube c : new ArrayList<>(cubes)) { if (s.getCube().subsumes(c)) { cubes.remove(c); } } } // Store clause F.get(k).add(s.getCube()); Z.comment("Blocked [" + k + "] : " + s.getCube()); // Report if invariant if (s.getFrame() == TCube.FRAME_INF) { Expr invariant = Z.getInvariant(s.getCube()); sendInvariant(invariant); } } private List<Cube> getCubes(Cube init) { List<Cube> result = new ArrayList<>(); Cube curr = init; while (curr != null) { result.add(curr); curr = curr.getNext(); } return result; } private void sendValidAndInvariants(List<Expr> invariants) { Itinerary itinerary = director.getValidMessageItinerary(); director.broadcast( new ValidMessage(parent.getName(), prop, 1, getRuntime(), invariants, null, itinerary, null, false)); director.broadcast(new InvariantMessage(invariants)); } private void sendInvalid(int length, Model model) { Itinerary itinerary = director.getInvalidMessageItinerary(); director.broadcast(new InvalidMessage(parent.getName(), prop, length, model, itinerary)); } private void sendInvariant(Expr invariant) { director.broadcast(new InvariantMessage(invariant)); } private double getRuntime() { return (System.currentTimeMillis() - director.startTime) / 1000.0; } }
6,930
24.575646
112
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/Lustre2Term.java
package jkind.engines.pdr; import java.util.ArrayList; import java.util.List; import de.uni_freiburg.informatik.ultimate.logic.Script; import de.uni_freiburg.informatik.ultimate.logic.Term; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.EnumType; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.SubrangeIntType; import jkind.lustre.TupleExpr; import jkind.lustre.Type; import jkind.lustre.UnaryExpr; import jkind.lustre.VarDecl; import jkind.lustre.visitors.ExprVisitor; import jkind.solvers.smtinterpol.ScriptUser; import jkind.util.SexpUtil; import jkind.util.Util; public class Lustre2Term extends ScriptUser implements ExprVisitor<Term> { public static final String INIT = "%init"; public static final String ASSERTIONS = "%assertions"; private final Node node; private boolean pre = false; public Lustre2Term(Script script, Node node) { super(script); this.node = node; } public Term getInit() { return term(INIT); } public Term getAssertions() { return term(ASSERTIONS); } public List<VarDecl> getVariables() { List<VarDecl> variables = new ArrayList<>(); for (VarDecl vd : Util.getVarDecls(node)) { variables.add(encode(vd)); } variables.add(new VarDecl(INIT, NamedType.BOOL)); variables.add(new VarDecl(ASSERTIONS, NamedType.BOOL)); return variables; } public static String encode(String name) { return "$" + name; } private VarDecl encode(VarDecl vd) { return new VarDecl(encode(vd.id), vd.type); } public static String decode(String encoded) { if (encoded.startsWith("$")) { return encoded.substring(1); } else { throw new IllegalArgumentException("Not an encoded name: " + encoded); } } public Term getTransition() { List<Term> conjuncts = new ArrayList<>(); for (Equation eq : node.equations) { Term body = eq.expr.accept(this); Term head = eq.lhs.get(0).accept(this); conjuncts.add(term("=", head, body)); } List<Term> assertions = new ArrayList<>(); for (Expr assertion : node.assertions) { assertions.add(assertion.accept(this)); } assertions.add(or(term(INIT), term(ASSERTIONS))); conjuncts.add(term("=", term(prime(ASSERTIONS)), and(assertions))); // Type constraints need to be included during interpolation, so we // include them in the transition relation for (VarDecl vd : Util.getVarDecls(node)) { Term baseConstraint = typeConstraint(encode(vd.id), vd.type); if (baseConstraint != null) { conjuncts.add(baseConstraint); } Term primeConstraint = typeConstraint(encode(prime(vd.id)), vd.type); if (primeConstraint != null) { conjuncts.add(primeConstraint); } } conjuncts.add(not(term(prime(INIT)))); return and(conjuncts); } public Term encodeProperty(String property) { return or(term(encode(property)), not(term(ASSERTIONS)), term(INIT)); } private String prime(String str) { return str + "'"; } @Override public Term visit(ArrayAccessExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to Term"); } @Override public Term visit(ArrayExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to Term"); } @Override public Term visit(ArrayUpdateExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to Term"); } @Override public Term visit(BinaryExpr e) { Term left = e.left.accept(this); Term right = e.right.accept(this); switch (e.op) { case NOTEQUAL: case XOR: return not(term("=", left, right)); case ARROW: if (pre) { throw new IllegalArgumentException("Arrows cannot be nested under pre during translation to Term"); } return ite(term(INIT), left, right); default: return term(e.op.toString(), left, right); } } @Override public Term visit(BoolExpr e) { return term(Boolean.toString(e.value)); } @Override public Term visit(CastExpr e) { if (e.type == NamedType.REAL) { return term("to_real", e.expr.accept(this)); } else if (e.type == NamedType.INT) { return term("to_int", e.expr.accept(this)); } else { throw new IllegalArgumentException(); } } @Override public Term visit(CondactExpr e) { throw new IllegalArgumentException("Condacts must be removed before translation to Term"); } @Override public Term visit(FunctionCallExpr e) { Term[] params = new Term[e.args.size()]; for (int i = 0; i < e.args.size(); i++) { params[i] = e.args.get(i).accept(this); } return term(SexpUtil.encodeFunction(e.function), params); } @Override public Term visit(IdExpr e) { String id = encode(e.id); return pre ? term(id) : term(prime(id)); } @Override public Term visit(IfThenElseExpr e) { return ite(e.cond.accept(this), e.thenExpr.accept(this), e.elseExpr.accept(this)); } @Override public Term visit(IntExpr e) { return numeral(e.value); } @Override public Term visit(NodeCallExpr e) { throw new IllegalArgumentException("Node calls must be inlined before translation to Term"); } @Override public Term visit(RealExpr e) { return decimal(e.value); } @Override public Term visit(RecordAccessExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to Term"); } @Override public Term visit(RecordExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to Term"); } @Override public Term visit(RecordUpdateExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to Term"); } @Override public Term visit(TupleExpr e) { throw new IllegalArgumentException("Tuples must be flattened before translation to Term"); } @Override public Term visit(UnaryExpr e) { switch (e.op) { case PRE: if (pre) { throw new IllegalArgumentException("Nested pres must be removed before translation to Term"); } pre = true; Term expr = e.expr.accept(this); pre = false; return expr; case NEGATIVE: return term("-", e.expr.accept(this)); case NOT: return not(e.expr.accept(this)); default: throw new IllegalArgumentException("Unhandled unary operator: " + e.op); } } private Term typeConstraint(String id, Type type) { if (type instanceof SubrangeIntType) { return subrangeConstraint(id, (SubrangeIntType) type); } else if (type instanceof EnumType) { return enumConstraint(id, (EnumType) type); } else { return null; } } private Term subrangeConstraint(String id, SubrangeIntType subrange) { return boundConstraint(id, numeral(subrange.low), numeral(subrange.high)); } private Term enumConstraint(String id, EnumType et) { return boundConstraint(id, numeral(0), numeral(et.values.size() - 1)); } private Term boundConstraint(String id, Term low, Term high) { return and(lessEqual(low, term(id)), lessEqual(term(id), high)); } private Term lessEqual(Term left, Term right) { return term("<=", left, right); } }
7,509
24.986159
103
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/PdrSmt.java
package jkind.engines.pdr; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import de.uni_freiburg.informatik.ultimate.logic.Annotation; import de.uni_freiburg.informatik.ultimate.logic.ApplicationTerm; import de.uni_freiburg.informatik.ultimate.logic.Logics; import de.uni_freiburg.informatik.ultimate.logic.Model; import de.uni_freiburg.informatik.ultimate.logic.QuotedObject; import de.uni_freiburg.informatik.ultimate.logic.Sort; import de.uni_freiburg.informatik.ultimate.logic.Term; import de.uni_freiburg.informatik.ultimate.logic.TermVariable; import jkind.engines.StopException; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.Node; import jkind.lustre.Type; import jkind.lustre.VarDecl; import jkind.solvers.smtinterpol.ScriptUser; import jkind.solvers.smtinterpol.SmtInterpolUtil; import jkind.solvers.smtinterpol.Subst; import jkind.solvers.smtinterpol.Term2Expr; import jkind.solvers.smtlib2.SmtLib2Model; import jkind.solvers.smtlib2.SmtLib2Solver; import jkind.translation.Relation; import jkind.util.StreamIndex; public class PdrSmt extends ScriptUser { private final List<Frame> F; private final List<VarDecl> varDecls; private final Map<String, Term[]> variableLists = new HashMap<>(); private final Term[] base; private final Term[] baseAbstract; private final Term[] primeAbstract; private final Term[] prime; private final Term I; private final Term A; private final Term P; private final Set<Term> predicates = new HashSet<>(); private final NameGenerator abstractAssertions = new NameGenerator("abstract"); private final List<Function> functions; public PdrSmt(Node node, List<Function> functions, List<Frame> F, String property, String scratchBase) { super(SmtInterpolUtil.getScript(scratchBase)); this.F = F; script.setOption(":produce-interpolants", true); script.setOption(":produce-unsat-cores", true); script.setOption(":simplify-interpolants", true); script.setLogic(Logics.QF_UFLIRA); script.setOption(":verbosity", 2); this.functions = functions; declareFunctions(functions); Lustre2Term lustre2Term = new Lustre2Term(script, node); this.varDecls = lustre2Term.getVariables(); this.base = getVariables(""); this.baseAbstract = getVariables("-"); this.primeAbstract = getVariables("-'"); this.prime = getVariables("'"); this.I = lustre2Term.getInit(); this.A = lustre2Term.getAssertions(); defineTransitionRelation(lustre2Term.getTransition()); this.P = lustre2Term.encodeProperty(property); assertAbstract(T(baseAbstract, primeAbstract)); addPredicates(PredicateCollector.collect(I)); addPredicates(PredicateCollector.collect(P)); } private void declareFunctions(List<Function> functions) { for (Function function : functions) { SmtInterpolUtil.declareFunction(script, function); } } private void assertAbstract(Term t) { script.assertTerm(name(t, abstractAssertions.getNextName())); } private void defineTransitionRelation(Term transition) { TermVariable[] params = new TermVariable[base.length + prime.length]; for (int i = 0; i < base.length; i++) { params[i] = variable(base[i]); } for (int i = 0; i < prime.length; i++) { params[i + base.length] = variable(prime[i]); } Term body = subst(transition, concat(base, prime), params); script.defineFun(Relation.T, params, script.sort("Bool"), body); } private TermVariable variable(Term v) { String name = variableName(v); return script.variable(name, v.getSort()); } private String variableName(Term v) { if (v instanceof ApplicationTerm) { ApplicationTerm at = (ApplicationTerm) v; return at.getFunction().getName(); } else { throw new IllegalArgumentException("Unexpected variable type: " + v.getClass().getSimpleName()); } } private void addPredicates(Set<Term> otherPredicates) { otherPredicates.removeAll(predicates); predicates.addAll(otherPredicates); for (Term p : otherPredicates) { comment("New predicate: " + p); assertAbstract(term("=", apply(p, base), apply(p, baseAbstract))); assertAbstract(term("=", apply(p, primeAbstract), apply(p, prime))); } return; } public Cube getBadCube() { return extractCube(checkSat(and(R(depth()), not(P)))); } private int depth() { return F.size() - 2; } private Term R(int k) { List<Term> conjuncts = new ArrayList<>(); for (int i = k; i < F.size(); i++) { conjuncts.add(F.get(i).toTerm(script)); } return and(conjuncts); } private Model checkSat(Term assertion) { script.push(1); script.assertTerm(assertion); switch (script.checkSat()) { case UNSAT: script.pop(1); return null; case SAT: Model model = script.getModel(); script.pop(1); return model; default: commentUnknownReason(); throw new StopException(); } } private Cube extractCube(Model model) { if (model == null) { return null; } Cube result = new Cube(); for (Term p : predicates) { result.addPLiteral(isTrue(model.evaluate(p)) ? p : not(p)); } return result; } private boolean isTrue(Term term) { if (term instanceof ApplicationTerm) { ApplicationTerm at = (ApplicationTerm) term; return at.getFunction().getName().equals("true"); } return false; } public boolean isInitial(Cube cube) { // Given our Lustre translation, a frame is initial if it does not // contain ~init return !cube.getPLiterals().contains(not(I)); } public enum Option { DEFAULT, EXTRACT_MODEL, NO_IND }; public TCube solveRelative(TCube s, Option option) { int frame = s.getFrame(); Cube cube = s.getCube(); script.push(1); if (option != Option.NO_IND) { script.assertTerm(not(cube)); } for (int i = frame - 1; i < F.size() - 1; i++) { script.assertTerm(name(F.get(i).toTerm(script), "F" + i)); } script.assertTerm(F.get(F.size() - 1).toTerm(script)); List<Term> pLiterals = s.getCube().getPLiterals(); for (int i = 0; i < pLiterals.size(); i++) { script.assertTerm(name(prime(pLiterals.get(i)), "P" + i)); } switch (script.checkSat()) { case UNSAT: Term[] unsatCore = script.getUnsatCore(); script.pop(1); int minFrame = getMinimumF(unsatCore); Cube minCube = getMinimalNonInitialCube(pLiterals, unsatCore); if (minFrame == F.size() - 2 || minFrame == TCube.FRAME_INF) { return new TCube(minCube, minFrame); } else { return new TCube(minCube, minFrame + 1); } case SAT: Cube c = null; if (option == Option.EXTRACT_MODEL) { c = extractCube(script.getModel()); } script.pop(1); return new TCube(c, TCube.FRAME_NULL); default: commentUnknownReason(); throw new StopException(); } } private void commentUnknownReason() { comment("SMT solver returned 'unknown' due to " + script.getInfo(":reason-unknown")); } private int getMinimumF(Term[] unsatCore) { int min = TCube.FRAME_INF; for (Term t : unsatCore) { String name = t.toString(); if (name.startsWith("F")) { int frame = Integer.parseInt(name.substring(1)); if (frame < min) { min = frame; } } } return min; } private Cube getMinimalNonInitialCube(List<Term> pLiterals, Term[] unsatCore) { Cube result = new Cube(); for (Term t : unsatCore) { String name = t.toString(); if (name.startsWith("P")) { int pIndex = Integer.parseInt(name.substring(1)); result.addPLiteral(pLiterals.get(pIndex)); } } if (isInitial(result)) { result.addPLiteral(not(I)); } return result; } public TCube solveRelative(TCube s) { return solveRelative(s, Option.DEFAULT); } public boolean isBlocked(TCube s) { int frame = s.getFrame(); Cube cube = s.getCube(); Term query = and(cube, R(frame)); return checkSat(query) == null; } public Frame createInitialFrame() { return new Frame(I); } public void refine(List<Cube> cubes) { List<Term> pieces = new ArrayList<>(); Term[] vars = getVariables(StreamIndex.getSuffix(-1)); for (int i = 0; i < cubes.size() - 1; i++) { Term[] nextVars = getVariables(StreamIndex.getSuffix(i)); pieces.add(and(apply(cubes.get(i), vars), T(vars, nextVars))); vars = nextVars; } pieces.add(and(apply(cubes.get(cubes.size() - 1), vars), not(P(vars)))); Term[] interpolants = getInterpolants(pieces); for (int i = 0; i < cubes.size() - 1; i++) { vars = getVariables(StreamIndex.getSuffix(i)); addPredicates(PredicateCollector.collect(subst(interpolants[i], vars, base))); } } private Term[] getInterpolants(List<Term> terms) { script.push(1); Term[] names = new Term[terms.size() + 1]; for (int i = 0; i < terms.size(); i++) { String name = "I" + i; script.assertTerm(name(terms.get(i), name)); names[i] = term(name); } // Ignore all variables related to abstract transition relation names[terms.size()] = and(term(abstractAssertions.getAllNames())); switch (script.checkSat()) { case UNSAT: Term[] interps = script.getInterpolants(names); script.pop(1); return interps; case SAT: int length = terms.size() - 1; SmtLib2Model extractedModel = extractModel(script.getModel(), length); throw new CounterexampleException(length, extractedModel); default: commentUnknownReason(); throw new StopException(); } } private SmtLib2Model extractModel(Model model, int length) { Map<String, Type> varTypes = new HashMap<>(); for (int i = -1; i < length; i++) { for (VarDecl vd : varDecls) { String name = vd.id + StreamIndex.getSuffix(i); varTypes.put(name, vd.type); } } return SmtLib2Solver.parseSmtLib2Model(model.toString(), varTypes, functions); } public void comment(String comment) { script.echo(new QuotedObject(comment)); } public Expr getInvariant(Cube cube) { List<Term> disjuncts = new ArrayList<>(); for (Term literal : cube.getPLiterals()) { if (literal != not(I) && literal != A) { disjuncts.add(not(literal)); } } return Term2Expr.disjunction(disjuncts); } private Term T(Term[] variables1, Term[] variables2) { return script.term(Relation.T, concat(variables1, variables2)); } private Term[] concat(Term[] terms1, Term[] terms2) { Term[] result = new Term[terms1.length + terms2.length]; System.arraycopy(terms1, 0, result, 0, terms1.length); System.arraycopy(terms2, 0, result, terms1.length, terms2.length); return result; } private Term P(Term[] vars) { return subst(P, base, vars); } public Term[] getVariables(String suffix) { if (variableLists.containsKey(suffix)) { return variableLists.get(suffix); } Term[] result = new Term[varDecls.size()]; for (int i = 0; i < varDecls.size(); i++) { VarDecl vd = varDecls.get(i); String name = vd.id + suffix; result[i] = declareVar(name, vd.type); } variableLists.put(suffix, result); return result; } private Term declareVar(String name, Type type) { Sort sort = getSort(type); script.declareFun(name, new Sort[0], sort); return script.term(name); } private Sort getSort(Type type) { return SmtInterpolUtil.getSort(script, type); } private Term not(Cube cube) { return not(cube.toTerm(script)); } private Term prime(Term term) { return subst(term, base, prime); } private Term apply(Term term, Term[] arguments) { return subst(term, base, arguments); } private Term apply(Cube cube, Term[] arguments) { return apply(cube.toTerm(script), arguments); } private Term subst(Term term, Term[] variables, Term[] arguments) { return Subst.apply(script, term, variables, arguments); } private Term and(Cube cube, Term... terms) { return and(cube.toTerm(script), and(terms)); } private Term name(Term term, String name) { return script.annotate(term, new Annotation(":named", name)); } private List<Term> term(List<String> variables) { return variables.stream().map(this::term).collect(toList()); } }
11,977
25.916854
105
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/PdrEngine.java
package jkind.engines.pdr; import java.util.HashSet; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import jkind.JKindSettings; import jkind.engines.Director; import jkind.engines.Engine; import jkind.engines.StopException; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.translation.Specification; public class PdrEngine extends Engine { public static final String NAME = "pdr"; private final ConcurrentMap<String, PdrSubengine> subengines = new ConcurrentHashMap<>(); private int scratchCounter = 1; public PdrEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); } @Override protected void main() { try { while (!done()) { processMessagesAndWaitUntil(() -> done() || canSpawnSubengine()); if (canSpawnSubengine()) { spawnSubengine(); } } } catch (StopException se) { subengines.forEach((name, subengine) -> subengine.cancel()); } } private boolean done() { return throwable != null || (properties.isEmpty() && subengines.isEmpty()); } private boolean canSpawnSubengine() { return subengines.size() < settings.pdrMax && !properties.isEmpty(); } private void spawnSubengine() { String prop = properties.remove(0); String scratch = settings.scratch ? getScratchBase() + scratchCounter++ : null; PdrSubengine subengine = new PdrSubengine(prop, spec, scratch, this, director); subengines.put(prop, subengine); subengine.start(); } public void reportUnknown(String prop) { subengines.remove(prop); director.receiveMessage(new UnknownMessage(getName(), prop)); } public void reportThrowable(Throwable throwable) { this.throwable = throwable; } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { cancel(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { cancel(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { cancel(vm.valid); } private void cancel(List<String> cancel) { for (String prop : new HashSet<>(subengines.keySet())) { if (cancel.contains(prop)) { PdrSubengine subengine = subengines.remove(prop); if (subengine != null) { subengine.cancel(); } } } properties.removeAll(cancel); } @Override public void stopEngine() { for (PdrSubengine subengine : subengines.values()) { subengine.cancel(); } properties.clear(); } }
2,924
24.657895
90
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/Cube.java
package jkind.engines.pdr; import java.util.ArrayList; import java.util.List; import de.uni_freiburg.informatik.ultimate.logic.Script; import de.uni_freiburg.informatik.ultimate.logic.Term; import de.uni_freiburg.informatik.ultimate.logic.Util; public class Cube { private final List<Term> pLiterals = new ArrayList<>(); private Cube next; public void addPLiteral(Term term) { pLiterals.add(term); } public void removePLiteral(Term term) { pLiterals.remove(term); } public List<Term> getPLiterals() { return pLiterals; } public boolean subsumes(Cube other) { return other.pLiterals.containsAll(pLiterals); } public void setNext(Cube next) { this.next = next; } public Cube getNext() { return next; } public Term toTerm(Script script) { return Util.and(script, pLiterals.toArray(new Term[pLiterals.size()])); } @Override public String toString() { return pLiterals.toString(); } }
926
18.723404
73
java
jkind
jkind-master/jkind/src/jkind/engines/pdr/PredicateCollector.java
package jkind.engines.pdr; import java.util.HashSet; import java.util.Set; import de.uni_freiburg.informatik.ultimate.logic.ApplicationTerm; import de.uni_freiburg.informatik.ultimate.logic.Sort; import de.uni_freiburg.informatik.ultimate.logic.Term; public class PredicateCollector { private final Set<Term> predicates = new HashSet<>(); public static Set<Term> collect(Term term) { PredicateCollector collector = new PredicateCollector(); collector.walk(term); return collector.predicates; } private void walk(Term term) { if (term instanceof ApplicationTerm) { ApplicationTerm at = (ApplicationTerm) term; walk(at); } else { throw new IllegalArgumentException("Unhandled: " + term.getClass().getSimpleName()); } } private void walk(ApplicationTerm at) { if (at.getParameters().length == 0) { String name = at.getFunction().getName(); if (name.equals("true") || name.equals("false")) { return; } } else if (booleanParamaters(at)) { for (Term sub : at.getParameters()) { walk(sub); } return; } predicates.add(at); } private boolean booleanParamaters(ApplicationTerm at) { for (Sort sort : at.getFunction().getParameterSorts()) { if (!sort.getName().equals("Bool")) { return false; } } return true; } }
1,291
23.377358
87
java
jkind
jkind-master/jkind/src/jkind/engines/messages/StopMessage.java
package jkind.engines.messages; public class StopMessage extends Message { @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
169
17.888889
45
java
jkind
jkind-master/jkind/src/jkind/engines/messages/UnknownMessage.java
package jkind.engines.messages; import java.util.Collections; import java.util.List; import jkind.util.Util; public class UnknownMessage extends Message { public final String source; public final List<String> unknown; public UnknownMessage(String source, List<String> unknown) { this.source = source; this.unknown = Util.safeList(unknown); } public UnknownMessage(String source, String unknown) { this.source = source; this.unknown = Collections.singletonList(unknown); } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
585
20.703704
61
java
jkind
jkind-master/jkind/src/jkind/engines/messages/BaseStepMessage.java
package jkind.engines.messages; import java.util.List; import jkind.util.Util; public class BaseStepMessage extends Message { public final int step; public final List<String> properties; public BaseStepMessage(int step, List<String> properties) { this.step = step; this.properties = Util.safeList(properties); } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
418
18.952381
60
java
jkind
jkind-master/jkind/src/jkind/engines/messages/Message.java
package jkind.engines.messages; public abstract class Message { public abstract void accept(MessageHandler handler); }
121
19.333333
53
java
jkind
jkind-master/jkind/src/jkind/engines/messages/InductiveCounterexampleMessage.java
package jkind.engines.messages; import java.util.List; import jkind.solvers.Model; import jkind.util.Util; public class InductiveCounterexampleMessage extends Message { public final List<String> properties; public final int length; public final Model model; public InductiveCounterexampleMessage(List<String> properties, int length, Model model) { this.properties = Util.safeList(properties); this.length = length; this.model = model; } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
546
21.791667
90
java
jkind
jkind-master/jkind/src/jkind/engines/messages/MessageHandler.java
package jkind.engines.messages; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import jkind.JKindException; import jkind.engines.StopException; public abstract class MessageHandler { private BlockingQueue<Message> incoming = new LinkedBlockingQueue<>(); // MWW, 8/27/2022 // receiveMessage and stopReceivingMessages run on different threads, // leading to occasional NPE exceptions due to race conditions when solver // is completing analyses. // // NPEs happen when incoming is checked for null, but then receiveMessage // thread is interrupted and incoming is set to null by stopReceivingMessages // prior to incoming.add(message). // // Note that other protected functions do not need to be // synchronized because they are called on the same thread // as stopReceivingMessages. public synchronized void receiveMessage(Message message) { if (incoming != null) { incoming.add(message); } } protected synchronized void stopReceivingMessages() { incoming = null; } protected void processMessages() { while (!incoming.isEmpty()) { handleMessage(incoming.poll()); } } protected void handleMessage(Message message) { message.accept(this); } protected void processMessagesAndWaitUntil(Supplier<Boolean> stoppingCondition) { try { while (!incoming.isEmpty() || !stoppingCondition.get()) { Message message = incoming.poll(100, TimeUnit.MILLISECONDS); if (message != null) { handleMessage(message); } } } catch (InterruptedException e) { throw new JKindException("Interrupted while waiting for message", e); } } protected abstract void handleMessage(BaseStepMessage bsm); protected abstract void handleMessage(InductiveCounterexampleMessage icm); protected abstract void handleMessage(InvalidMessage im); protected abstract void handleMessage(InvariantMessage im); protected abstract void handleMessage(UnknownMessage um); protected abstract void handleMessage(ValidMessage vm); @SuppressWarnings("unused") protected void handleMessage(StopMessage sm) { throw new StopException(); } }
2,203
28.386667
82
java
jkind
jkind-master/jkind/src/jkind/engines/messages/ValidMessage.java
package jkind.engines.messages; import java.util.Collections; import java.util.List; import java.util.Set; import jkind.engines.ivcs.AllIVCs; import jkind.lustre.Expr; import jkind.util.Util; public class ValidMessage extends Message { public final String source; public final List<String> valid; public final Set<String> ivc; public final List<AllIVCs> allIvcs; public final int k; public final double proofTime; public final List<Expr> invariants; private final Itinerary itinerary; public final boolean mivcTimedOut; public ValidMessage(String source, List<String> valid, int k, double proofTime, List<Expr> invariants, Set<String> ivc, Itinerary itinerary, Set<AllIVCs> allIvcs, boolean mivcTimedOut) { this.source = source; this.valid = Util.safeList(valid); this.k = k; this.invariants = Util.safeList(invariants); this.itinerary = itinerary; this.ivc = Util.safeSet(ivc); this.allIvcs = Util.safeList(allIvcs); this.proofTime = proofTime; this.mivcTimedOut = mivcTimedOut; } public ValidMessage(String source, String valid, int k, double proofTime, List<Expr> invariants, Set<String> ivc, Itinerary itinerary, Set<AllIVCs> allIvcs, boolean mivcTimedOut) { this(source, Collections.singletonList(valid), k, proofTime, invariants, ivc, itinerary, allIvcs, mivcTimedOut); } public EngineType getNextDestination() { return itinerary.getNextDestination(); } public Itinerary getNextItinerary() { return itinerary.getNextItinerary(); } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
1,585
28.924528
114
java
jkind
jkind-master/jkind/src/jkind/engines/messages/InvariantMessage.java
package jkind.engines.messages; import java.util.Collections; import java.util.List; import jkind.lustre.Expr; import jkind.util.Util; public class InvariantMessage extends Message { public final List<Expr> invariants; public InvariantMessage(List<Expr> invs) { this.invariants = Util.safeList(invs); } public InvariantMessage(Expr invariant) { this(Collections.singletonList(invariant)); } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
499
19
47
java
jkind
jkind-master/jkind/src/jkind/engines/messages/InvalidMessage.java
package jkind.engines.messages; import java.util.Collections; import java.util.List; import jkind.solvers.Model; import jkind.util.Util; public class InvalidMessage extends Message { public final String source; public final List<String> invalid; public final int length; public final Model model; private final Itinerary itinerary; public InvalidMessage(String source, List<String> invalid, int length, Model model, Itinerary itinerary) { this.source = source; this.invalid = Util.safeList(invalid); this.length = length; this.model = model; this.itinerary = itinerary; } public InvalidMessage(String source, String invalid, int length, Model model, Itinerary itinerary) { this(source, Collections.singletonList(invalid), length, model, itinerary); } public EngineType getNextDestination() { return itinerary.getNextDestination(); } public Itinerary getNextItinerary() { return itinerary.getNextItinerary(); } @Override public void accept(MessageHandler handler) { handler.handleMessage(this); } }
1,040
24.390244
107
java
jkind
jkind-master/jkind/src/jkind/engines/messages/EngineType.java
package jkind.engines.messages; /** Only the engines used for itineraries */ public enum EngineType { SMOOTHING, INTERVAL_GENERALIZATION, IVC_REDUCTION, IVC_REDUCTION_ALL, BMC_BASED_CONSISTENCY_CHECKER, CONSISTENCY_CHECKER; }
228
31.714286
122
java
jkind
jkind-master/jkind/src/jkind/engines/messages/Itinerary.java
package jkind.engines.messages; import java.util.List; import jkind.util.Util; public class Itinerary { private final List<EngineType> destinations; public Itinerary(List<EngineType> destinations) { this.destinations = Util.safeList(destinations); } public EngineType getNextDestination() { if (destinations.isEmpty()) { return null; } else { return destinations.get(0); } } public Itinerary getNextItinerary() { return new Itinerary(destinations.subList(1, destinations.size())); } }
514
18.807692
69
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/IvcReductionEngine.java
package jkind.engines.ivcs; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import jkind.JKindException; import jkind.JKindSettings; import jkind.engines.Director; import jkind.engines.SolverBasedEngine; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.EngineType; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.Expr; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.UnknownResult; import jkind.solvers.UnsatResult; import jkind.translation.Lustre2Sexp; import jkind.translation.Specification; import jkind.util.LinkedBiMap; import jkind.util.SexpUtil; public class IvcReductionEngine extends SolverBasedEngine { public static final String NAME = "ivc-reduction"; private final LinkedBiMap<String, Symbol> ivcMap; private double runtime; public IvcReductionEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); ivcMap = Lustre2Sexp.createIvcMap(spec.node.ivc); } @Override protected void initializeSolver() { solver = getSolver(); solver.initialize(); for (Symbol e : ivcMap.values()) { solver.define(new VarDecl(e.str, NamedType.BOOL)); } solver.declare(spec.functions); solver.define(spec.getIvcTransitionRelation()); solver.define(new VarDecl(INIT.str, NamedType.BOOL)); } @Override public void main() { processMessagesAndWaitUntil(() -> properties.isEmpty()); } private void reduce(ValidMessage vm) { for (String property : vm.valid) { if (properties.remove(property)) { runtime = System.currentTimeMillis(); reduceInvariants(IvcUtil.getInvariantByName(property, vm.invariants), vm); } } } private void reduceInvariants(Expr property, ValidMessage vm) { comment("Reducing invariants for: " + property); solver.push(); solver.assertSexp(SexpUtil.conjoin(ivcMap.valueList())); LinkedBiMap<Symbol, Expr> candidates = createActivationLiterals(vm.invariants, "inv"); Set<Expr> irreducible = new HashSet<>(); irreducible.add(property); candidates.inverse().remove(property); int k = 0; createVariables(-1); createVariables(0); assertInductiveTransition(0); while (k <= vm.k) { Sexp query = SexpUtil.conjoinInvariants(irreducible, k); Result result = solver.unsatQuery(candidates.keyList(), query); if (result instanceof SatResult || result instanceof UnknownResult) { /* * We haven't yet found the minimal value of k, so assert the * irreducible and conditional invariants and increase k */ for (Expr inv : irreducible) { solver.assertSexp(inv.accept(new Lustre2Sexp(k))); } for (Entry<Symbol, Expr> entry : candidates.entrySet()) { solver.assertSexp(createConditional(entry, k)); } k++; createVariables(k); assertInductiveTransition(k); } else if (result instanceof UnsatResult) { /* * We found the minimal value of k, now we determine which * candidate invariants are necessary to prove the irreducible * invariants. If no more are necessary, then we are done. * Otherwise we mark new irreducible invariants and start over * to see if any additional invariants are needed to prove * those. */ List<Symbol> unsatCore = ((UnsatResult) result).getUnsatCore(); if (unsatCore.isEmpty()) { break; } for (Symbol core : unsatCore) { irreducible.add(candidates.remove(core)); solver.assertSexp(core); } } } if (k == vm.k + 1) { /* * Failed to find the right value of k, due to UnknownResult from * solver. Give up and use what we started with. */ irreducible.addAll(vm.invariants); k = vm.k; } solver.pop(); reduceIvc(property, k, new ArrayList<>(irreducible), vm); } private void reduceIvc(Expr property, int k, List<Expr> invariants, ValidMessage vm) { if (spec.node.ivc.isEmpty()) { sendValid(property.toString(), k, invariants, Collections.emptySet(), vm); return; } comment("Reducing ivc for: " + property); solver.push(); createVariables(-1); for (int i = 0; i <= k; i++) { createVariables(i); } assertInductiveTransition(0); Result result = solver.unsatQuery(ivcMap.valueList(), getIvcQuery(invariants, k)); if (!(result instanceof UnsatResult)) { throw new JKindException("Trying to reduce IVC on falsifiable property"); } List<Symbol> unsatCore = ((UnsatResult) result).getUnsatCore(); solver.pop(); sendValid(property.toString(), k, invariants, getIvcNames(unsatCore), vm); } private Sexp getIvcQuery(List<Expr> properties, int k) { if (k == 0) { return SexpUtil.conjoinInvariants(properties, k); } Sexp base = getBaseIvcQuery(properties, k); Sexp inductiveStep = getStepIvcQuery(properties, k); return new Cons("and", base, inductiveStep); } /** * Base step query for IVC reduction. Examples for k = 1, 2, 3: * * %init => P(0) * * %init => (P(0) and (T(0, 1) => P(1))) * * %init => (P(0) and (T(0, 1) => (P(1) and (T(1, 2) => P(2))))) */ private Sexp getBaseIvcQuery(List<Expr> properties, int k) { Sexp query = SexpUtil.conjoinInvariants(properties, k - 1); for (int i = k - 1; i > 0; i--) { query = new Cons("=>", getBaseTransition(i), query); query = new Cons("and", SexpUtil.conjoinInvariants(properties, i - 1), query); } return new Cons("=>", INIT, query); } /** * Inductive step query for IVC reduction. Examples for k = 1, 2, 3: * * (P(0) and T(0, 1)) => P(1) * * (P(0) and T(0, 1) and P(1) and T(1, 2)) => P(2) * * (P(0) and T(0, 1) and P(1) and T(1, 2) and P(2) and T(2, 3)) => P(3) */ private Sexp getStepIvcQuery(List<Expr> properties, int k) { List<Sexp> hyps = new ArrayList<>(); for (int i = 0; i < k; i++) { hyps.add(SexpUtil.conjoinInvariants(properties, i)); hyps.add(getInductiveTransition(i + 1)); } return new Cons("=>", SexpUtil.conjoin(hyps), SexpUtil.conjoinInvariants(properties, k)); } private Sexp createConditional(Entry<Symbol, Expr> entry, int k) { Symbol actLit = entry.getKey(); Sexp inv = entry.getValue().accept(new Lustre2Sexp(k)); return new Cons("=>", actLit, inv); } private <T> LinkedBiMap<Symbol, T> createActivationLiterals(List<T> elements, String prefix) { LinkedBiMap<Symbol, T> map = new LinkedBiMap<>(); int i = 0; for (T element : elements) { map.put(solver.createActivationLiteral(prefix, i++), element); } return map; } private Set<String> getIvcNames(List<Symbol> symbols) { Set<String> result = new HashSet<>(); for (Symbol s : symbols) { result.add(ivcMap.inverse().get(s)); } return result; } private void sendValid(String valid, int k, List<Expr> invariants, Set<String> ivc, ValidMessage vm) { runtime = (System.currentTimeMillis() - runtime) / 1000.0; comment("Sending " + valid + " at k = " + k + " with invariants: "); for (Expr invariant : invariants) { comment(invariant.toString()); } comment("IVC: " + ivc.toString()); Itinerary itinerary = vm.getNextItinerary(); ValidMessage nvm = new ValidMessage(vm.source, valid, k, vm.proofTime + runtime, invariants, ivc, itinerary, null, false); director.broadcast(nvm); } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { properties.removeAll(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { properties.removeAll(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { if (vm.getNextDestination() == EngineType.IVC_REDUCTION) { reduce(vm); } } }
8,239
28.640288
110
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/IvcUtil.java
package jkind.engines.ivcs; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.sexp.Symbol; import jkind.util.LinkedBiMap; import jkind.util.Util; public class IvcUtil { public static final String EQUATION_NAME = "__addedEQforAsr_by_JKind__"; public static Node normalizeAssertions(Node node) { List<VarDecl> locals = new ArrayList<>(node.locals); List<Equation> equations = new ArrayList<>(node.equations); List<Expr> assertions = new ArrayList<>(node.assertions); Iterator<Expr> iter = assertions.iterator(); int id = 0; List<IdExpr> newAssertions = new ArrayList<>(); while (iter.hasNext()) { Expr asr = iter.next(); if (!(asr instanceof IdExpr)) { newAssertions.add(defineNewEquation(asr, locals, equations, EQUATION_NAME + id)); id++; iter.remove(); } } assertions.addAll(newAssertions); NodeBuilder builder = new NodeBuilder(node); builder.clearLocals().addLocals(locals); builder.clearEquations().addEquations(equations); builder.clearAssertions().addAssertions(assertions); return builder.build(); } public static List<String> getAllAssigned(Node node) { List<String> result = new ArrayList<>(); result.addAll(Util.getIds(node.locals)); result.addAll(Util.getIds(node.outputs)); return result; } public static Program setIvcArgs(Node node, List<String> newIvc) { return new Program(new NodeBuilder(node).clearIvc().addIvcs(newIvc).build()); } public static List<VarDecl> removeVariables(List<VarDecl> varDecls, List<String> vars) { List<VarDecl> result = new ArrayList<>(varDecls); Iterator<VarDecl> iter = result.iterator(); while (iter.hasNext()) { if (vars.contains(iter.next().id)) { iter.remove(); } } return result; } public static List<VarDecl> removeVariable(List<VarDecl> varDecls, String v) { List<VarDecl> result = new ArrayList<>(varDecls); Iterator<VarDecl> iter = result.iterator(); while (iter.hasNext()) { if (iter.next().id.equals(v)) { iter.remove(); } } return result; } public static IdExpr defineNewEquation(Expr rightSide, List<VarDecl> locals, List<Equation> equations, String newVar) { locals.add(new VarDecl(newVar, NamedType.BOOL)); IdExpr ret = new IdExpr(newVar); equations.add(new Equation(ret, rightSide)); return ret; } public static Set<String> findRightSide(Set<String> initialIvc, boolean allAssigned, List<Equation> equations) { Set<String> ivc = new HashSet<>(initialIvc); if (allAssigned) { Set<String> itr = new HashSet<>(ivc); for (String core : itr) { if (core.contains(EQUATION_NAME)) { for (Equation eq : equations) { if (core.equals(eq.lhs.get(0).id)) { ivc.remove(core); ivc.add("assert " + eq.expr.toString()); } } } } } return ivc; } protected static Expr getInvariantByName(String name, List<Expr> invariants) { for (Expr invariant : invariants) { if (invariant.toString().equals(name)) { return invariant; } } // In rare cases, PDR will not return the original property as one of // the invariants. By returning a new Expr we will effectively add it as // a new invariants. See https://github.com/agacek/jkind/issues/44 return new IdExpr(name); } protected static Set<String> getIvcNames(LinkedBiMap<String, Symbol> ivcMap, List<Symbol> symbols) { Set<String> result = new HashSet<>(); for (Symbol s : symbols) { result.add(ivcMap.inverse().get(s)); } return result; } protected static List<Symbol> getIvcLiterals(LinkedBiMap<String, Symbol> ivcMap, Collection<String> set) { List<Symbol> result = new ArrayList<>(); for (String ivc : set) { result.add(ivcMap.get(ivc)); } return result; } public static Node unassign(Node node, String v, String property) { List<String> in = new ArrayList<>(); in.add(v); return unassign(node, in, property); } public static Node unassign(Node node, List<String> deactivate, String property) { List<VarDecl> inputs = new ArrayList<>(node.inputs); for (String v : deactivate) { inputs.add(new VarDecl(v, Util.getTypeMap(node).get(v))); } List<VarDecl> locals = removeVariables(node.locals, deactivate); List<VarDecl> outputs = removeVariables(node.outputs, deactivate); List<Equation> equations = new ArrayList<>(node.equations); Iterator<Equation> iter = equations.iterator(); while (iter.hasNext()) { Equation eq = iter.next(); if (deactivate.contains(eq.lhs.get(0).id)) { iter.remove(); } } List<String> ivcs = new ArrayList<>(node.ivc); ivcs.removeAll(deactivate); NodeBuilder builder = new NodeBuilder(node); builder.clearInputs().addInputs(inputs); builder.clearIvc().addIvcs(ivcs); builder.clearLocals().addLocals(locals); builder.clearOutputs().addOutputs(outputs); builder.clearEquations().addEquations(equations); builder.clearProperties().addProperty(property); return builder.build(); } public static Node overApproximateWithIvc(Node node, Set<String> ivc, String property) { List<String> deactivate = new ArrayList<>(); for (Equation eq : node.equations) { if (!ivc.contains(eq.lhs.get(0).id)) { deactivate.add(eq.lhs.get(0).id); } } return unassign(node, deactivate, property); } }
5,586
29.2
113
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/AllIvcsExtractorEngine.java
package jkind.engines.ivcs; import static java.util.stream.Collectors.toList; import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import jkind.ExitCodes; import jkind.JKindException; import jkind.JKindSettings; import jkind.SolverOption; import jkind.StdErr; import jkind.engines.Director; import jkind.engines.MiniJKind; import jkind.engines.SolverBasedEngine; import jkind.engines.SolverUtil; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.EngineType; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.Expr; import jkind.lustre.NamedType; import jkind.lustre.Program; import jkind.lustre.VarDecl; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.Solver; import jkind.solvers.UnknownResult; import jkind.solvers.UnsatResult; import jkind.solvers.z3.Z3Solver; import jkind.translation.Lustre2Sexp; import jkind.translation.Specification; import jkind.util.LinkedBiMap; import jkind.util.SexpUtil; public class AllIvcsExtractorEngine extends SolverBasedEngine { public static final String NAME = "all-ivc-computer"; private final LinkedBiMap<String, Symbol> ivcMap; private Sexp map; private List<SeedPair> shrinkingPool = new ArrayList<SeedPair>(); private List<List<Symbol>> growingPool = new ArrayList<List<Symbol>>(); private Z3Solver z3Solver; private Set<String> mustElements = new HashSet<>(); private Set<String> mayElements = new HashSet<>(); Set<AllIVCs> allIvcs = new HashSet<>(); private int TIMEOUT; private boolean timedoutLoop = false; private double runtime; private class SeedPair { public List<Symbol> properties; public List<String> invariants; public SeedPair(List<Symbol> p, List<String> i) { properties = new ArrayList<Symbol>(p); invariants = new ArrayList<String>(i); } public SeedPair(List<Symbol> p) { properties = new ArrayList<Symbol>(p); invariants = new ArrayList<String>(); } } public AllIvcsExtractorEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); ivcMap = Lustre2Sexp.createIvcMap(spec.node.ivc); } @Override protected Solver getSolver() { return SolverUtil.getSolver(SolverOption.Z3, getScratchBase(), spec.node); } @Override protected void initializeSolver() { solver = getSolver(); solver.initialize(); z3Solver = (Z3Solver) solver; for (Symbol e : ivcMap.values()) { solver.define(new VarDecl(e.str, NamedType.BOOL)); } } @Override public void main() { processMessagesAndWaitUntil(() -> properties.isEmpty()); } private void reduce(ValidMessage vm) { runtime = System.currentTimeMillis(); for (String property : vm.valid) { mayElements.clear(); mustElements.clear(); if (spec.node.ivc.isEmpty()) { StdErr.warning(NAME + ": --%IVC option has no argument for property " + property.toString()); sendValid(property.toString(), vm); return; } if (vm.ivc.isEmpty()) { System.out.println("The high level property " + property + " can be proved without using any of the --%IVC annotated low level properties."); sendValid(property.toString(), vm); return; } System.out.println("Proving the high level property " + property + " might require to use some of the --%IVC annotated low level properties."); if (properties.remove(property)) { switch (settings.allIvcsAlgorithm) { case OFFLINE_MIVC_ENUM_ALG: // offline MIVC enumeration System.out.println("Starting MIVC enumeration using the offline enumeration algorithm."); computeAllIvcs(IvcUtil.getInvariantByName(property, vm.invariants), vm); break; case ONLINE_MIVC_ENUM_ALG: // online MIVC enumeration System.out.println("Starting MIVC enumeration using the online enumeration algorithm."); computeAllIvcsOnline(IvcUtil.getInvariantByName(property, vm.invariants), vm); break; } allIvcs.clear(); } } } /** * offline MIVC enumeration algorithm as described in the FMCAD 2017 paper **/ private void computeAllIvcs(Expr property, ValidMessage vm) { TIMEOUT = (settings.allIvcsJkindTimeout < 0) ? (30 + (int) (vm.proofTime * 5)) : settings.allIvcsJkindTimeout; List<Symbol> seed = new ArrayList<Symbol>(); Set<String> mustChckList = new HashSet<>(); Set<String> resultOfIvcFinder = new HashSet<>(); List<String> inv = vm.invariants.stream().map(Object::toString).collect(toList()); allIvcs.add(new AllIVCs(vm.ivc, inv)); seed.addAll(IvcUtil.getIvcLiterals(ivcMap, new ArrayList<>(vm.ivc))); map = blockUp(seed); mustElements.add(property.toString()); if (ivcMap.containsKey(property.toString())) { map = new Cons("and", map, ivcMap.get(property.toString())); } z3Solver.push(); while (checkMapSatisfiability(seed, mustChckList, true)) { resultOfIvcFinder.clear(); if (ivcFinder(seed, resultOfIvcFinder, mustChckList, property.toString())) { map = new Cons("and", map, blockUp(IvcUtil.getIvcLiterals(ivcMap, resultOfIvcFinder))); } else { map = new Cons("and", map, blockDown(IvcUtil.getIvcLiterals(ivcMap, resultOfIvcFinder))); } } // it is possible that the resultant MIVC is empty (not a bug! this is expected behavior) if (allIvcs.size() == 1 && allIvcs.iterator().next().getAllIVCSet().size() == 0) { System.out.println("The high level property " + property + " can be proved without using any of the --%IVC annotated low level properties."); allIvcs.clear(); } System.out.println("MIVC enumeration completed."); z3Solver.pop(); sendValid(property.toString(), vm); } /** * JB, online MIVC enumeration algorithm as described in the SEFM 2018 paper **/ private void computeAllIvcsOnline(Expr property, ValidMessage vm) { TIMEOUT = (settings.allIvcsJkindTimeout < 0) ? (30 + (int) (vm.proofTime * 5)) : settings.allIvcsJkindTimeout; List<Symbol> seed = new ArrayList<Symbol>(); seed.addAll(IvcUtil.getIvcLiterals(ivcMap, new ArrayList<>(vm.ivc))); map = blockUp(seed); List<String> inv = vm.invariants.stream().map(Object::toString).collect(toList()); shrinkingPool.add(new SeedPair(new ArrayList<Symbol>(seed), inv)); mustElements.add(property.toString()); if (ivcMap.containsKey(property.toString())) { map = new Cons("and", map, ivcMap.get(property.toString())); } z3Solver.push(); seed = getMaximalUnexplored(new ArrayList<Symbol>()); while (!seed.isEmpty()) { SeedPair seedPair = new SeedPair(seed); if (ivcFinderSimple(seedPair, property.toString(), true)) { mapShrink(seedPair, property.toString()); } else { map = new Cons("and", map, blockDownComplement(seed)); } while (!shrinkingPool.isEmpty()) { SeedPair ivc = shrinkingPool.get(0); shrinkingPool.remove(0); mapShrink(ivc, property.toString()); } seed = getMaximalUnexplored(new ArrayList<Symbol>()); } // it is possible that the resultant MIVC is empty (not a bug! this is expected behavior) if (allIvcs.size() == 1 && allIvcs.iterator().next().getAllIVCSet().size() == 0) { System.out.println("The high level property " + property + " can be proved without using any of the --%IVC annotated low level properties."); allIvcs.clear(); } System.out.println("MIVC enumeration completed."); z3Solver.pop(); sendValid(property.toString(), vm); } private boolean ivcFinder(List<Symbol> seed, Set<String> resultOfIvcFinder, Set<String> mustChckList, String property) { JKindSettings js = new JKindSettings(); js.reduceIvc = true; js.timeout = TIMEOUT; js.solver = settings.solver; js.slicing = true; js.pdrMax = settings.pdrMax; js.boundedModelChecking = settings.boundedModelChecking; js.miniJkind = true; js.readAdvice = settings.readAdvice; js.writeAdvice = settings.writeAdvice; Set<String> wantedElem = IvcUtil.getIvcNames(ivcMap, new ArrayList<>(seed)); List<String> deactivate = new ArrayList<>(); deactivate.addAll(ivcMap.keyList()); deactivate.removeAll(wantedElem); Program nodeSpec = new Program(IvcUtil.unassign(spec.node, deactivate, property)); Specification newSpec = new Specification(nodeSpec, js.slicing); if (settings.scratch) { comment("Sending a request for a new IVC while deactivating " + IvcUtil.getIvcLiterals(ivcMap, deactivate)); } MiniJKind miniJkind = new MiniJKind(nodeSpec, newSpec, js); miniJkind.verify(); if (miniJkind.getPropertyStatus().equals(MiniJKind.UNKNOWN)) { timedoutLoop = true; } if (miniJkind.getPropertyStatus().equals(MiniJKind.UNKNOWN_WITH_EXCEPTION)) { js.pdrMax = 0; return retryVerification(nodeSpec, newSpec, property, js, resultOfIvcFinder, mustChckList, deactivate); } else if (miniJkind.getPropertyStatus().equals(MiniJKind.VALID)) { mayElements.addAll(deactivate); mustChckList.removeAll(deactivate); resultOfIvcFinder.addAll(miniJkind.getPropertyIvc()); Set<String> newIvc = resultOfIvcFinder; if (settings.scratch) { comment("New IVC set found: " + IvcUtil.getIvcLiterals(ivcMap, resultOfIvcFinder)); } Set<AllIVCs> temp = new HashSet<>(); for (AllIVCs curr : allIvcs) { Set<String> trimmed = curr.getAllIVCSet(); if (trimmed.containsAll(newIvc)) { temp.add(curr); } // the else part can only happen // while processing mustChckList after finding all IVC sets // if we have different instances of a node in the Lustre file else if (newIvc.containsAll(trimmed)) { return true; } } if (temp.isEmpty()) { allIvcs.add(new AllIVCs(miniJkind.getPropertyIvc(), miniJkind.getPropertyInvariants())); } else { allIvcs.removeAll(temp); allIvcs.add(new AllIVCs(miniJkind.getPropertyIvc(), miniJkind.getPropertyInvariants())); } return true; } else { resultOfIvcFinder.addAll(deactivate); if (settings.scratch) { comment("Property got violated. Adding back the elements"); } if (deactivate.size() == 1) { mustElements.addAll(deactivate); mustChckList.removeAll(deactivate); if (settings.scratch) { comment("One MUST element was found: " + IvcUtil.getIvcLiterals(ivcMap, deactivate)); } } else { deactivate.removeAll(mustElements); deactivate.removeAll(mayElements); if (settings.scratch) { comment(IvcUtil.getIvcLiterals(ivcMap, deactivate) + " could be MUST elements; added to the check list..."); } mustChckList.addAll(deactivate); } return false; } } private boolean ivcFinderSimple(SeedPair seed, String property, boolean reduceSeed) { JKindSettings js = new JKindSettings(); js.reduceIvc = true; js.timeout = TIMEOUT; js.solver = settings.solver; js.slicing = true; js.pdrMax = settings.pdrMax; js.boundedModelChecking = settings.boundedModelChecking; js.miniJkind = true; js.readAdvice = settings.readAdvice; js.writeAdvice = settings.writeAdvice; Set<String> wantedElem = IvcUtil.getIvcNames(ivcMap, new ArrayList<>(seed.properties)); List<String> deactivate = new ArrayList<>(); deactivate.addAll(ivcMap.keyList()); deactivate.removeAll(wantedElem); Program nodeSpec = new Program(IvcUtil.unassign(spec.node, deactivate, property)); Specification newSpec = new Specification(nodeSpec, js.slicing); MiniJKind miniJkind = new MiniJKind(nodeSpec, newSpec, js); miniJkind.verify(); if (miniJkind.getPropertyStatus().equals(MiniJKind.UNKNOWN)) { timedoutLoop = true; } if (miniJkind.getPropertyStatus().equals(MiniJKind.UNKNOWN_WITH_EXCEPTION)) { js.pdrMax = 0; } if (miniJkind.getPropertyStatus().equals(MiniJKind.VALID)) { seed.invariants = miniJkind.getPropertyInvariants(); if (reduceSeed) { seed.properties = IvcUtil.getIvcLiterals(ivcMap, miniJkind.getPropertyIvc()); } return true; } else { if (deactivate.size() == 1) { mustElements.addAll(deactivate); } return false; } } private boolean Grow(List<Symbol> seed, String property) { List<Symbol> top = getMaximalUnexplored(seed); SeedPair approx = new SeedPair(top); List<Symbol> added = new ArrayList<Symbol>(top); added.removeAll(seed); while (ivcFinderSimple(approx, property.toString(), true)) { List<SeedPair> toRemove = new ArrayList<SeedPair>(); for (SeedPair s : shrinkingPool) { if (s.properties.containsAll(approx.properties)) { toRemove.add(s); } } shrinkingPool.removeAll(toRemove); map = new Cons("and", map, blockUp(approx.properties)); shrinkingPool.add(approx); boolean reduced = false; for (Symbol s : approx.properties) { if (added.contains(s)) { added.remove(s); top.remove(s); reduced = true; break; } } if (!reduced) { break; } approx = new SeedPair(top); } map = new Cons("and", map, blockDownComplement(top)); return true; } private boolean isUnexplored(List<Symbol> seed) { z3Solver.push(); List<Symbol> positiveLits = new ArrayList<Symbol>(seed); List<Symbol> negatedLits = new ArrayList<>(ivcMap.valueList()); negatedLits.removeAll(seed); for (Symbol s : negatedLits) { if (mustElements.contains(s.toString())) { return false; } } solver.assertSexp(map); Result result = z3Solver.checkValuation(positiveLits, negatedLits, false); z3Solver.pop(); if (result instanceof UnsatResult) { return false; } else if (result instanceof UnknownResult) { throw new JKindException("Unknown result in solving map"); } return true; } private boolean mapShrink(SeedPair seed, String property) { List<Symbol> candidates = new ArrayList<Symbol>(seed.properties); for (Symbol c : candidates) { seed.properties.remove(c); if (mustElements.contains(c.toString()) || !isUnexplored(seed.properties)) { seed.properties.add(c); continue; } if (!ivcFinderSimple(seed, property, false)) { ArrayList<Symbol> copy = new ArrayList<Symbol>(seed.properties); growingPool.add(copy); seed.properties.add(c); } } map = new Cons("and", map, blockUp(seed.properties)); markMIVC(seed); List<SeedPair> toRemove = new ArrayList<SeedPair>(); for (SeedPair s : shrinkingPool) { if (s.properties.containsAll(seed.properties)) { toRemove.add(s); } } shrinkingPool.removeAll(toRemove); int remainingGrows = settings.allIvcsMaxGrows; while (!growingPool.isEmpty()) { List<Symbol> is = growingPool.get(0); growingPool.remove(0); if (remainingGrows > 0) { remainingGrows--; Grow(is, property.toString()); } else { map = new Cons("and", map, blockDownComplement(is)); } } return true; } private void markMIVC(SeedPair mivc) { Set<String> mivc_set = IvcUtil.getIvcNames(ivcMap, mivc.properties); allIvcs.add(new AllIVCs(mivc_set, mivc.invariants)); double time = (System.currentTimeMillis() - runtime) / 1000.0; writeToXmlAllIvcs(new HashSet<String>(), mivc_set, time, true); } private boolean retryVerification(Program program, Specification newSpec, String prop, JKindSettings js, Set<String> resultOfIvcFinder, Set<String> mustChckList, List<String> deactivate) { if (settings.scratch) { comment("Result was UNKNOWN; Resend the request with pdrMax = 0 ..."); } MiniJKind miniJkind = new MiniJKind(program, newSpec, js); miniJkind.verify(); if (miniJkind.getPropertyStatus().equals(MiniJKind.UNKNOWN)) { timedoutLoop = true; } if (miniJkind.getPropertyStatus().equals(MiniJKind.VALID)) { mayElements.addAll(deactivate); mustChckList.removeAll(deactivate); resultOfIvcFinder.addAll(miniJkind.getPropertyIvc()); Set<String> newIvc = resultOfIvcFinder; if (settings.scratch) { comment("New IVC set found: " + IvcUtil.getIvcLiterals(ivcMap, resultOfIvcFinder)); } Set<AllIVCs> temp = new HashSet<>(); for (AllIVCs curr : allIvcs) { Set<String> trimmed = curr.getAllIVCSet(); if (trimmed.containsAll(newIvc)) { temp.add(curr); } else if (newIvc.containsAll(trimmed)) { return true; } } if (temp.isEmpty()) { allIvcs.add(new AllIVCs(miniJkind.getPropertyIvc(), miniJkind.getPropertyInvariants())); } else { allIvcs.removeAll(temp); allIvcs.add(new AllIVCs(miniJkind.getPropertyIvc(), miniJkind.getPropertyInvariants())); } return true; } else { resultOfIvcFinder.addAll(deactivate); if (settings.scratch) { comment("Property got violated. Adding back the elements"); } if (deactivate.size() == 1) { mustElements.addAll(deactivate); mustChckList.removeAll(deactivate); if (settings.scratch) { comment("One MUST element was found: " + IvcUtil.getIvcLiterals(ivcMap, deactivate)); } } else { deactivate.removeAll(mustElements); deactivate.removeAll(mayElements); if (settings.scratch) { comment(IvcUtil.getIvcLiterals(ivcMap, deactivate) + " could be MUST elements; added to the check list..."); } mustChckList.addAll(deactivate); } return false; } } private Sexp blockUp(Collection<Symbol> list) { List<Sexp> ret = new ArrayList<>(); for (Symbol literal : list) { ret.add(new Cons("not", literal)); } return SexpUtil.disjoin(ret); } private Sexp blockDown(Collection<Symbol> list) { List<Sexp> ret = new ArrayList<>(); for (Symbol literal : list) { ret.add(literal); } return SexpUtil.disjoin(ret); } private Sexp blockDownComplement(Collection<Symbol> list) { List<Sexp> temp = new ArrayList<>(ivcMap.valueList()); temp.removeAll(list); return SexpUtil.disjoin(temp); } private boolean checkMapSatisfiability(List<Symbol> seed, Set<String> mustChckList, boolean maximal) { z3Solver.push(); solver.assertSexp(map); Result result = z3Solver.checkSat(new ArrayList<>(), true, false); if (result instanceof UnsatResult) { return false; } else if (result instanceof UnknownResult) { throw new JKindException("Unknown result in solving map"); } seed.clear(); if (maximal) { seed.addAll(maximizeSat(((SatResult) result), mustChckList)); } else { SatResult sat = (SatResult) result; seed.addAll(getActiveLiteralsFromModel(sat.getModel(), "true")); } z3Solver.pop(); return true; } private List<Symbol> getMaximalUnexplored(List<Symbol> seed) { z3Solver.push(); solver.assertSexp(map); if (!seed.isEmpty()) { solver.assertSexp(new Cons("and", map, SexpUtil.conjoin(seed))); } Result result = z3Solver.checkMaximal(); z3Solver.pop(); if (result instanceof SatResult) { SatResult sat = (SatResult) result; List<Symbol> top = getCompletePositiveModel(sat.getModel()); return new ArrayList<Symbol>(top); } return new ArrayList<Symbol>(); } private List<Symbol> getCompletePositiveModel(Model model) { Set<Symbol> negative_literals = getActiveLiteralsFromModel(model, "false"); List<Symbol> top = new ArrayList<>(ivcMap.valueList()); top.removeAll(negative_literals); return top; } /** * in case of sat result we would like to get a maximum sat subset of activation literals **/ private List<Symbol> maximizeSat(SatResult result, Set<String> mustChckList) { Set<Symbol> seed = getActiveLiteralsFromModel(result.getModel(), "true"); Set<Symbol> falseLiterals = getActiveLiteralsFromModel(result.getModel(), "false"); Set<Symbol> temp = new HashSet<>(); temp.addAll(ivcMap.valueList()); List<Symbol> literalList = IvcUtil.getIvcLiterals(ivcMap, new ArrayList<>(mustChckList)); temp.removeAll(literalList); temp.removeAll(falseLiterals); temp.removeAll(seed); for (Symbol literal : literalList) { if (!seed.contains(literal)) { seed.add(literal); if (z3Solver.quickCheckSat(new ArrayList<>(seed)) instanceof UnsatResult) { seed.remove(literal); } } } for (Symbol literal : falseLiterals) { if (!seed.contains(literal)) { seed.add(literal); if (z3Solver.quickCheckSat(new ArrayList<>(seed)) instanceof UnsatResult) { seed.remove(literal); } } } for (Symbol literal : temp) { seed.add(literal); if (z3Solver.quickCheckSat(new ArrayList<>(seed)) instanceof UnsatResult) { seed.remove(literal); } } return new ArrayList<>(seed); } private Set<Symbol> getActiveLiteralsFromModel(Model model, String val) { Set<Symbol> seed = new HashSet<>(); for (String var : model.getVariableNames()) { if (model.getValue(var).toString() == val) { seed.add(new Symbol(var)); } } return seed; } private void sendValid(String valid, ValidMessage vm) { boolean mivcTimedOut = false; Itinerary itinerary = vm.getNextItinerary(); if (timedoutLoop) { mustElements.add("::AIVCtimedoutLoop::"); mivcTimedOut = true; } // In the all ivc elements, if any of the inner loops times out, the timeout information is encoded in the must elements // and passed to the ivc field of the ValidMessage object, sending it out to the writers director.broadcast(new ValidMessage(vm.source, valid, vm.k, vm.proofTime, null, mustElements, itinerary, allIvcs, mivcTimedOut)); } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { properties.removeAll(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { properties.removeAll(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { if (vm.getNextDestination() == EngineType.IVC_REDUCTION_ALL) { reduce(vm); } } /* * recording (minimal) IVCs found during the computation **/ private void writeToXmlAllIvcs(Set<String> trimmed, Set<String> untrimmed, double d, boolean isNew) { String xmlFilename = settings.filename + "_alg" + settings.allIvcsAlgorithm + "_all_uc_minijkind.xml"; try (PrintWriter out = new PrintWriter(new FileOutputStream(new File(xmlFilename), true))) { out.println("<Results>"); out.println(" <NewSet>" + isNew + "</NewSet>"); out.println(" <Time unit=\"sec\">" + d + "</Time>"); for (String s : untrimmed) { out.println(" <IVC>" + s + "</IVC>"); } for (String s : trimmed) { out.println(" <TRIVC>" + s + "</TRIVC>"); } out.println("</Results>"); out.flush(); out.close(); } catch (Throwable t) { t.printStackTrace(); System.exit(ExitCodes.UNCAUGHT_EXCEPTION); } } }
22,883
30.916318
122
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/MinimalIvcFinder.java
package jkind.engines.ivcs; import java.util.HashSet; import java.util.Set; import jkind.JKindSettings; import jkind.engines.MiniJKind; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.translation.Specification; public class MinimalIvcFinder { private Node node; private String property; public MinimalIvcFinder(Program program, String property) { this.node = program.getMainNode(); this.property = property; } public Set<String> minimizeIvc(Set<String> candidates, Set<String> mustElements, int timeout, JKindSettings settings) { Set<String> minimal = new HashSet<>(candidates); JKindSettings js = new JKindSettings(); js.allAssigned = false; js.miniJkind = true; js.timeout = timeout; js.readAdvice = settings.readAdvice; js.writeAdvice = settings.writeAdvice; for (String s : candidates) { Program candidate = new Program(IvcUtil.unassign(node, s, property)); MiniJKind miniJkind = new MiniJKind(candidate, new Specification(candidate, js.slicing), js); miniJkind.verify(); if (miniJkind.getPropertyStatus() == MiniJKind.VALID) { minimal.remove(s); node = candidate.getMainNode(); } miniJkind = null; } minimal.addAll(mustElements); return minimal; } }
1,241
27.227273
96
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/AllIVCs.java
package jkind.engines.ivcs; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class AllIVCs { Set<String> allIVCSet = new HashSet<>(); List<String> allIVCList = new ArrayList<String>(); public AllIVCs(Set<String> allIVCSet, List<String> allIVCList) { this.allIVCSet = allIVCSet; this.allIVCList = allIVCList; } public Set<String> getAllIVCSet() { return allIVCSet; } public List<String> getAllIVCList() { return allIVCList; } }
505
19.24
65
java
jkind
jkind-master/jkind/src/jkind/engines/ivcs/IvcException.java
package jkind.engines.ivcs; import jkind.JKindException; class IvcException extends JKindException { protected IvcException(String message) { super(message); } }
168
15.9
43
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/InvariantSet.java
package jkind.engines.invariant; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Predicate; import jkind.lustre.Expr; public class InvariantSet { private final List<Expr> invariants = new ArrayList<>(); private final Set<String> uniqueRepresentations = new HashSet<>(); public void add(Expr invariant) { if (uniqueRepresentations.add(invariant.toString())) { invariants.add(invariant); } } public void addAll(Collection<Expr> invariants) { invariants.forEach(this::add); } public List<Expr> getInvariants() { return invariants; } public void removeIf(Predicate<Expr> predicate) { Iterator<Expr> iterator = invariants.iterator(); while (iterator.hasNext()) { Expr invariant = iterator.next(); if (predicate.test(invariant)) { iterator.remove(); uniqueRepresentations.remove(invariant.toString()); } } } }
988
22.547619
67
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/Edge.java
package jkind.engines.invariant; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; public class Edge { public final Node source; public final Node destination; public Edge(Node source, Node destination) { this.source = source; this.destination = destination; } public Expr toInvariant() { Expr sRep = source.getRepresentative(); Expr dRep = destination.getRepresentative(); return new BinaryExpr(sRep, BinaryOp.IMPLIES, dRep); } @Override public String toString() { return source + " -> " + destination; } }
572
20.222222
54
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/Node.java
package jkind.engines.invariant; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.Expr; import jkind.lustre.LustreUtil; import jkind.lustre.values.BooleanValue; import jkind.lustre.visitors.Evaluator; public class Node { private List<Expr> candidates; public Node(List<Expr> candidates) { this.candidates = candidates; } public boolean isEmpty() { return candidates.isEmpty(); } public Expr getRepresentative() { return candidates.get(0); } public boolean isSingleton() { return candidates.size() <= 1; } public List<Expr> toInvariants() { Iterator<Expr> iterator = candidates.iterator(); Expr first = iterator.next(); if (first instanceof BoolExpr) { BoolExpr bool = (BoolExpr) first; return optimizeInvariants(bool.value, iterator); } List<Expr> invariants = new ArrayList<>(); while (iterator.hasNext()) { Expr other = iterator.next(); invariants.add(new BinaryExpr(first, BinaryOp.EQUAL, other)); } return invariants; } /** * By optimizing simple invariants we can prove some properties directly * from invariant generation */ private List<Expr> optimizeInvariants(boolean value, Iterator<Expr> iterator) { List<Expr> invariants = new ArrayList<>(); while (iterator.hasNext()) { Expr expr = iterator.next(); invariants.add(value ? expr : LustreUtil.optimizeNot(expr)); } return invariants; } public List<Node> split(Evaluator eval) { List<Expr> falses = new ArrayList<>(); List<Expr> trues = new ArrayList<>(); for (Expr candidate : candidates) { if (eval.eval(candidate) == BooleanValue.TRUE) { trues.add(candidate); } else { falses.add(candidate); } } List<Node> chain = new ArrayList<>(2); chain.add(new Node(falses)); chain.add(new Node(trues)); return chain; } @Override public String toString() { return candidates.toString(); } }
2,008
21.829545
80
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/CandidateGenerator.java
package jkind.engines.invariant; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import jkind.analysis.evaluation.InitialStepEvaluator; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.EnumType; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.SubrangeIntType; import jkind.lustre.Type; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.IntegerValue; import jkind.lustre.values.Value; import jkind.translation.Specification; public class CandidateGenerator { private Specification spec; private List<Expr> candidates; private InitialStepEvaluator evaluator; public CandidateGenerator(Specification spec) { this.spec = spec; this.evaluator = new InitialStepEvaluator(spec.node); } public List<Expr> generate() { candidates = new ArrayList<>(); candidates.add(new BoolExpr(true)); candidates.add(new BoolExpr(false)); CombinatorialInfo info = new CombinatorialInfo(spec.node); for (String id : spec.typeMap.keySet()) { if (info.isCombinatorial(id) && !spec.node.properties.contains(id)) { continue; } Type type = spec.typeMap.get(id); if (type == NamedType.INT) { addIntCandidates(id); } else if (type == NamedType.BOOL) { addBoolCandidates(id); } else if (type instanceof SubrangeIntType) { addSubrangeCandidates(id, (SubrangeIntType) type); } else if (type instanceof EnumType) { addEnumCandidates(id, (EnumType) type); } } return candidates; } private void addIntCandidates(String id) { BigInteger init = getConstantInitialValue(id); IdExpr idExpr = new IdExpr(id); if (init != null) { IntExpr initExpr = new IntExpr(init); candidates.add(new BinaryExpr(idExpr, BinaryOp.GREATEREQUAL, initExpr)); candidates.add(new BinaryExpr(idExpr, BinaryOp.LESSEQUAL, initExpr)); } else { candidates.add(new BinaryExpr(idExpr, BinaryOp.GREATEREQUAL, new IntExpr(0))); } } private BigInteger getConstantInitialValue(String id) { Value value = evaluator.eval(id); if (value instanceof IntegerValue) { IntegerValue iv = (IntegerValue) value; return iv.value; } return null; } private void addBoolCandidates(String id) { candidates.add(new IdExpr(id)); candidates.add(new UnaryExpr(UnaryOp.NOT, new IdExpr(id))); } private void addSubrangeCandidates(String id, SubrangeIntType subrange) { IdExpr idExpr = new IdExpr(id); for (BigInteger r = subrange.low; r.compareTo(subrange.high) <= 0; r = r.add(BigInteger.ONE)) { candidates.add(new BinaryExpr(idExpr, BinaryOp.EQUAL, new IntExpr(r))); } } private void addEnumCandidates(String id, EnumType et) { BigInteger low = BigInteger.ZERO; BigInteger high = BigInteger.valueOf(et.values.size() - 1); addSubrangeCandidates(id, new SubrangeIntType(low, high)); } }
2,958
28.009804
97
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/ListInvariant.java
package jkind.engines.invariant; import java.util.ArrayList; import java.util.List; import jkind.lustre.Expr; import jkind.lustre.values.BooleanValue; import jkind.lustre.visitors.Evaluator; public class ListInvariant implements StructuredInvariant { private final List<Expr> exprs = new ArrayList<>(); public ListInvariant(List<Expr> exprs) { this.exprs.addAll(exprs); } @Override public boolean isTrivial() { return exprs.isEmpty(); } @Override public List<Expr> toExprs() { return exprs; } @Override public void refine(Evaluator eval) { exprs.removeIf(e -> eval.eval(e) == BooleanValue.FALSE); } @Override public ListInvariant copy() { return new ListInvariant(exprs); } @Override public void reduceProven(StructuredInvariant proven) { if (proven instanceof ListInvariant) { ListInvariant listProven = (ListInvariant) proven; exprs.removeAll(listProven.exprs); } } @Override public List<Expr> toFinalInvariants() { return exprs; } }
989
18.8
59
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/GraphInvariantGenerationEngine.java
package jkind.engines.invariant; import java.util.List; import jkind.JKindSettings; import jkind.engines.Director; import jkind.lustre.Expr; import jkind.translation.Specification; public class GraphInvariantGenerationEngine extends AbstractInvariantGenerationEngine { public static final String NAME = "invariant-generation"; public GraphInvariantGenerationEngine(Specification spec, JKindSettings settings, Director director) { super(NAME, spec, settings, director); } @Override protected GraphInvariant createInitialInvariant() { List<Expr> candidates = new CandidateGenerator(spec).generate(); comment("Proposed " + candidates.size() + " candidates"); return new GraphInvariant(candidates); } }
718
28.958333
103
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/GraphInvariant.java
package jkind.engines.invariant; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import jkind.lustre.BoolExpr; import jkind.lustre.Expr; import jkind.lustre.visitors.Evaluator; public class GraphInvariant implements StructuredInvariant { private List<Node> nodes = new ArrayList<>(); private final Map<Node, Set<Node>> incoming = new HashMap<>(); private final Map<Node, Set<Node>> outgoing = new HashMap<>(); public GraphInvariant(List<Expr> candidates) { nodes.add(new Node(candidates)); } @Override public boolean isTrivial() { return nodes.isEmpty() || (nodes.size() == 1 && nodes.get(0).isSingleton()); } private void addEdge(Node source, Node destination) { outgoing(source).add(destination); incoming(destination).add(source); } private Set<Node> incoming(Node destination) { return safeGet(incoming, destination); } private Set<Node> outgoing(Node source) { return safeGet(outgoing, source); } private Set<Node> safeGet(Map<Node, Set<Node>> map, Node node) { Set<Node> result = map.get(node); if (result == null) { result = new HashSet<>(); map.put(node, result); } return result; } private Set<Edge> getEdges() { Set<Edge> edges = new HashSet<>(); for (Entry<Node, Set<Node>> entry : outgoing.entrySet()) { Node source = entry.getKey(); for (Node destination : entry.getValue()) { edges.add(new Edge(source, destination)); } } return edges; } private void setEdges(List<Edge> edges) { incoming.clear(); outgoing.clear(); for (Edge edge : edges) { addEdge(edge.source, edge.destination); } } @Override public List<Expr> toExprs() { List<Expr> exprs = new ArrayList<>(); for (Node node : nodes) { exprs.addAll(node.toInvariants()); } for (Edge edge : getEdges()) { exprs.add(edge.toInvariant()); } return exprs; } @Override public List<Expr> toFinalInvariants() { removeTrivialInvariants(); return toExprs(); } private void removeTrivialInvariants() { for (Node node : nodes) { if (isTrue(node.getRepresentative())) { Set<Node> in = incoming(node); for (Node other : in) { outgoing(other).remove(node); } in.clear(); } else if (isFalse(node.getRepresentative())) { Set<Node> out = outgoing(node); for (Node other : out) { incoming(other).remove(node); } out.clear(); } } removeUselessNodes(); } private boolean isTrue(Expr expr) { return isBoolean(expr, true); } private boolean isFalse(Expr expr) { return isBoolean(expr, false); } private boolean isBoolean(Expr expr, boolean value) { if (expr instanceof BoolExpr) { BoolExpr be = (BoolExpr) expr; return be.value == value; } return false; } @Override public void refine(Evaluator eval) { splitNodes(eval); removeEmptyNodes(); removeUselessNodes(); } private void splitNodes(Evaluator eval) { List<Node> newNodes = new ArrayList<>(); List<Edge> newEdges = new ArrayList<>(); Map<Node, List<Node>> chains = new HashMap<>(); // Split nodes into chains for (Node curr : nodes) { List<Node> chain = curr.split(eval); chains.put(curr, chain); newNodes.addAll(chain); if (!chain.get(0).isEmpty() && !chain.get(1).isEmpty()) { newEdges.add(new Edge(chain.get(0), chain.get(1))); } } // Join chains based on previous edges for (Edge edge : getEdges()) { List<Node> sourceChain = chains.get(edge.source); List<Node> destinationChain = chains.get(edge.destination); newEdges.add(new Edge(sourceChain.get(0), destinationChain.get(0))); newEdges.add(new Edge(sourceChain.get(1), destinationChain.get(1))); if (sourceChain.get(1).isEmpty() && destinationChain.get(0).isEmpty()) { newEdges.add(new Edge(sourceChain.get(0), destinationChain.get(1))); } } nodes = newNodes; setEdges(newEdges); } private void removeEmptyNodes() { Iterator<Node> iterator = nodes.iterator(); while (iterator.hasNext()) { Node node = iterator.next(); if (node.isEmpty()) { iterator.remove(); rerouteEdgesAroundNode(node); } } } private void rerouteEdgesAroundNode(Node node) { Set<Node> in = incoming(node); Set<Node> out = outgoing(node); incoming.remove(node); outgoing.remove(node); for (Node source : in) { outgoing(source).remove(node); } for (Node destination : out) { incoming(destination).remove(node); } for (Node source : in) { for (Node destination : out) { addEdge(source, destination); } } } private void removeUselessNodes() { Iterator<Node> iterator = nodes.iterator(); while (iterator.hasNext()) { Node node = iterator.next(); if (node.isSingleton() && incoming(node).isEmpty() && outgoing(node).isEmpty()) { iterator.remove(); incoming.remove(node); outgoing.remove(node); } } } @Override public StructuredInvariant copy() { return new GraphInvariant(this); } private GraphInvariant(GraphInvariant other) { nodes.addAll(other.nodes); copy(other.incoming, incoming); copy(other.outgoing, outgoing); } private static void copy(Map<Node, Set<Node>> src, Map<Node, Set<Node>> dst) { for (Entry<Node, Set<Node>> entry : src.entrySet()) { dst.put(entry.getKey(), new HashSet<>(entry.getValue())); } } @Override public void reduceProven(StructuredInvariant proven) { } }
5,470
23.101322
84
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/CombinatorialInfo.java
package jkind.engines.invariant; import java.util.HashSet; import java.util.Set; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.Node; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.visitors.ExprDisjunctiveVisitor; public class CombinatorialInfo { private Set<String> combinatorialIds = new HashSet<>(); public CombinatorialInfo(Node node) { for (Equation eq : node.equations) { if (!containsPre(eq.expr)) { combinatorialIds.add(eq.lhs.get(0).id); } } } private boolean containsPre(Expr expr) { return expr.accept(new ExprDisjunctiveVisitor() { @Override public Boolean visit(UnaryExpr e) { return e.op == UnaryOp.PRE || super.visit(e); } }); } public boolean isCombinatorial(String id) { return combinatorialIds.contains(id); } }
838
21.675676
56
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/AbstractInvariantGenerationEngine.java
package jkind.engines.invariant; import java.util.ArrayList; import java.util.List; import jkind.JKindSettings; import jkind.engines.Director; import jkind.engines.SolverBasedEngine; import jkind.engines.StopException; import jkind.engines.messages.BaseStepMessage; import jkind.engines.messages.InductiveCounterexampleMessage; import jkind.engines.messages.InvalidMessage; import jkind.engines.messages.InvariantMessage; import jkind.engines.messages.Itinerary; import jkind.engines.messages.UnknownMessage; import jkind.engines.messages.ValidMessage; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.solvers.Model; import jkind.solvers.ModelEvaluator; import jkind.solvers.Result; import jkind.solvers.UnsatResult; import jkind.translation.Specification; import jkind.util.SexpUtil; public abstract class AbstractInvariantGenerationEngine extends SolverBasedEngine { private final InvariantSet provenInvariants = new InvariantSet(); public AbstractInvariantGenerationEngine(String name, Specification spec, JKindSettings settings, Director director) { super(name, spec, settings, director); } @Override public void main() { StructuredInvariant invariant = createInitialInvariant(); if (invariant.isTrivial()) { comment("No invariants proposed"); return; } createVariables(-1); createVariables(0); for (int k = 1; k <= settings.n; k++) { comment("K = " + k); refineBaseStep(k - 1, invariant); if (invariant.isTrivial()) { comment("No invariants remaining after base step"); return; } createVariables(k); refineInductiveStep(k, invariant); } } protected abstract StructuredInvariant createInitialInvariant(); private void refineBaseStep(int k, StructuredInvariant invariant) { solver.push(); Result result; for (int i = 0; i <= k; i++) { assertBaseTransition(i); } do { checkForStop(); Sexp query = SexpUtil.conjoinInvariants(invariant.toExprs(), k); result = solver.query(query); if (!(result instanceof UnsatResult)) { Model model = getModel(result); if (model == null) { comment("No model - unable to continue"); throw new StopException(); } invariant.refine(new ModelEvaluator(model, k)); comment("Finished single base step refinement"); } } while (!invariant.isTrivial() && !(result instanceof UnsatResult)); solver.pop(); } private void refineInductiveStep(int k, StructuredInvariant original) { solver.push(); StructuredInvariant invariant = original.copy(); Result result; for (int i = 0; i <= k; i++) { assertInvariants(provenInvariants, i); assertInductiveTransition(i); } do { checkForStop(); result = solver.query(getInductiveQuery(k, invariant)); if (!(result instanceof UnsatResult)) { Model model = getModel(result); if (model == null) { comment("No model - unable to continue"); throw new StopException(); } invariant.refine(new ModelEvaluator(model, k)); comment("Finished single inductive step refinement"); } } while (!invariant.isTrivial() && !(result instanceof UnsatResult)); solver.pop(); List<Expr> newInvariants = invariant.toFinalInvariants(); provenInvariants.addAll(newInvariants); sendValidProperties(newInvariants, k); sendInvariants(newInvariants); original.reduceProven(invariant); return; } private void assertInvariants(InvariantSet set, int i) { solver.assertSexp(SexpUtil.conjoinInvariants(set.getInvariants(), i)); } private void checkForStop() { processMessages(); if (properties.isEmpty()) { throw new StopException(); } } private Sexp getInductiveQuery(int k, StructuredInvariant invariant) { List<Expr> exprs = invariant.toExprs(); List<Sexp> hyps = new ArrayList<>(); for (int i = 0; i < k; i++) { hyps.add(SexpUtil.conjoinInvariants(exprs, i)); } Sexp conc = SexpUtil.conjoinInvariants(exprs, k); return new Cons("=>", SexpUtil.conjoin(hyps), conc); } private void sendValidProperties(List<Expr> newInvariants, int k) { List<String> valid = new ArrayList<>(); for (Expr inv : newInvariants) { if (inv instanceof IdExpr) { IdExpr idExpr = (IdExpr) inv; if (properties.contains(idExpr.id)) { properties.remove(idExpr.id); valid.add(idExpr.id); } } } if (!valid.isEmpty()) { Itinerary itinerary = director.getValidMessageItinerary(); List<Expr> invariants = provenInvariants.getInvariants(); director.broadcast( new ValidMessage(getName(), valid, k, getRuntime(), invariants, null, itinerary, null, false)); } } private void sendInvariants(List<Expr> newInvariants) { comment("Sending invariants:"); for (Expr inv : newInvariants) { comment(" " + inv); } director.broadcast(new InvariantMessage(newInvariants)); } @Override protected void handleMessage(BaseStepMessage bsm) { } @Override protected void handleMessage(InductiveCounterexampleMessage icm) { } @Override protected void handleMessage(InvalidMessage im) { properties.removeAll(im.invalid); } @Override protected void handleMessage(InvariantMessage im) { } @Override protected void handleMessage(UnknownMessage um) { properties.removeAll(um.unknown); } @Override protected void handleMessage(ValidMessage vm) { properties.removeAll(vm.valid); } private double getRuntime() { return (System.currentTimeMillis() - director.startTime) / 1000.0; } }
5,478
25.215311
100
java
jkind
jkind-master/jkind/src/jkind/engines/invariant/StructuredInvariant.java
package jkind.engines.invariant; import java.util.List; import jkind.lustre.Expr; import jkind.lustre.visitors.Evaluator; public interface StructuredInvariant { public boolean isTrivial(); public List<Expr> toExprs(); public void refine(Evaluator eval); public StructuredInvariant copy(); public void reduceProven(StructuredInvariant proven); public List<Expr> toFinalInvariants(); }
398
18
54
java
jkind
jkind-master/jkind/src/jkind/realizability/writers/Writer.java
package jkind.realizability.writers; import java.util.List; import jkind.results.Counterexample; public abstract class Writer { public abstract void begin(); public abstract void end(); public abstract void writeBaseStep(int k); public abstract void writeRealizable(int k, double runtime); public abstract void writeUnrealizable(Counterexample cex, List<String> conflicts, double runtime); public abstract void writeUnknown(int trueFor, Counterexample cex, double runtime); public abstract void writeInconsistent(int k, double runtime); }
555
24.272727
100
java
jkind
jkind-master/jkind/src/jkind/realizability/writers/ExcelWriter.java
package jkind.realizability.writers; import java.util.Collections; import java.util.List; import java.util.Map; import jkind.lustre.Node; import jkind.results.Counterexample; import jkind.results.layout.RealizabilityNodeLayout; import jkind.util.Util; public class ExcelWriter extends Writer { private final jkind.writers.ExcelWriter internal; private final ConsoleWriter summaryWriter = new ConsoleWriter(null); private static final List<String> REALIZABLE_LIST = Collections.singletonList(Util.REALIZABLE); public ExcelWriter(String filename, Node node) { this.internal = new jkind.writers.ExcelWriter(filename, new RealizabilityNodeLayout(node)); } @Override public void begin() { internal.begin(); } @Override public void end() { internal.end(); } @Override public void writeBaseStep(int k) { internal.writeBaseStep(REALIZABLE_LIST, k); } @Override public void writeRealizable(int k, double runtime) { internal.writeValid(REALIZABLE_LIST, "extend", k, runtime, runtime, Collections.emptyList(), Collections.emptySet(), Collections.emptyList(), false); summaryWriter.writeRealizable(k, runtime); } @Override public void writeUnrealizable(Counterexample cex, List<String> conflicts, double runtime) { internal.writeInvalid(Util.REALIZABLE, "base", cex, conflicts, runtime); summaryWriter.writeUnrealizable(cex, conflicts, runtime); } @Override public void writeUnknown(int trueFor, Counterexample cex, double runtime) { Map<String, Counterexample> map = Collections.singletonMap(Util.REALIZABLE, cex); internal.writeUnknown(REALIZABLE_LIST, trueFor, map, runtime); summaryWriter.writeUnknown(trueFor, cex, runtime); } @Override public void writeInconsistent(int k, double runtime) { internal.writeInconsistent(Util.REALIZABLE, "base", k, runtime); summaryWriter.writeInconsistent(k, runtime); } }
1,865
29.590164
96
java
jkind
jkind-master/jkind/src/jkind/realizability/writers/ConsoleWriter.java
package jkind.realizability.writers; import java.util.List; import jkind.results.Counterexample; import jkind.results.layout.Layout; import jkind.util.Util; public class ConsoleWriter extends Writer { private final Layout layout; public ConsoleWriter(Layout layout) { super(); this.layout = layout; } @Override public void begin() { } @Override public void end() { } @Override public void writeBaseStep(int k) { } @Override public void writeRealizable(int k, double runtime) { writeLine(); System.out.println("REALIZABLE || K = " + k + " || Time = " + Util.secondsToTime(runtime)); writeLine(); System.out.println(); } @Override public void writeUnrealizable(Counterexample cex, List<String> conflicts, double runtime) { writeLine(); String details = conflicts.isEmpty() ? "" : ": " + conflicts; System.out.println( "UNREALIZABLE" + details + " || K = " + cex.getLength() + " || Time = " + Util.secondsToTime(runtime)); if (layout != null) { System.out.println(cex.toString(layout)); } writeLine(); System.out.println(); } @Override public void writeUnknown(int trueFor, Counterexample cex, double runtime) { writeLine(); System.out.println("UNKNOWN || True for " + trueFor + " steps" + " || Time = " + Util.secondsToTime(runtime)); writeLine(); System.out.println(); if (cex != null && layout != null) { writeLine(); System.out.println("EXTEND COUNTEREXAMPLE || K = " + cex.getLength()); System.out.println(cex.toString(layout)); writeLine(); System.out.println(); } } @Override public void writeInconsistent(int k, double runtime) { writeLine(); System.out.println( "INCONSISTENT || System inconsistent at " + k + " steps" + " || Time = " + Util.secondsToTime(runtime)); writeLine(); System.out.println(); } private void writeLine() { System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); } }
1,949
24
112
java
jkind
jkind-master/jkind/src/jkind/realizability/writers/XmlWriter.java
package jkind.realizability.writers; import java.io.FileNotFoundException; import java.util.Collections; import java.util.List; import java.util.Map; import jkind.lustre.Type; import jkind.results.Counterexample; import jkind.util.Util; public class XmlWriter extends Writer { private final jkind.writers.XmlWriter internal; private final ConsoleWriter summaryWriter = new ConsoleWriter(null); private static final List<String> REALIZABLE_LIST = Collections.singletonList(Util.REALIZABLE); public XmlWriter(String filename, Map<String, Type> types) throws FileNotFoundException { this.internal = new jkind.writers.XmlWriter(filename, types, false); } @Override public void begin() { internal.begin(); } @Override public void end() { internal.end(); } @Override public void writeBaseStep(int k) { internal.writeBaseStep(REALIZABLE_LIST, k); } @Override public void writeRealizable(int k, double runtime) { internal.writeValid(REALIZABLE_LIST, "extend", k, runtime, runtime, Collections.emptyList(), Collections.emptySet(), Collections.emptyList(), false); summaryWriter.writeRealizable(k, runtime); } @Override public void writeUnrealizable(Counterexample cex, List<String> conflicts, double runtime) { internal.writeInvalid(Util.REALIZABLE, "base", cex, conflicts, runtime); summaryWriter.writeUnrealizable(cex, conflicts, runtime); } @Override public void writeUnknown(int trueFor, Counterexample cex, double runtime) { Map<String, Counterexample> map = Collections.singletonMap(Util.REALIZABLE, cex); internal.writeUnknown(REALIZABLE_LIST, trueFor, map, runtime); summaryWriter.writeUnknown(trueFor, cex, runtime); } @Override public void writeInconsistent(int k, double runtime) { internal.writeInconsistent(Util.REALIZABLE, "base", k, runtime); summaryWriter.writeInconsistent(k, runtime); } }
1,864
29.57377
96
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/RealizabilityExtendEngine.java
package jkind.realizability.engines; import jkind.JKindException; import jkind.JRealizabilitySettings; import jkind.engines.StopException; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; import jkind.realizability.engines.messages.BaseStepMessage; import jkind.realizability.engines.messages.ExtendCounterexampleMessage; import jkind.realizability.engines.messages.InconsistentMessage; import jkind.realizability.engines.messages.Message; import jkind.realizability.engines.messages.RealizableMessage; import jkind.realizability.engines.messages.UnknownMessage; import jkind.realizability.engines.messages.UnrealizableMessage; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.UnknownResult; import jkind.solvers.UnsatResult; import jkind.translation.Specification; import jkind.util.StreamIndex; public class RealizabilityExtendEngine extends RealizabilityEngine { private int kLimit = 0; private RealizabilityBaseEngine baseEngine; public RealizabilityExtendEngine(Specification spec, JRealizabilitySettings settings, RealizabilityDirector director) { super("extend", spec, settings, director); } public void setBaseEngine(RealizabilityBaseEngine baseEngine) { this.baseEngine = baseEngine; } @Override protected void initializeSolver() { super.initializeSolver(); solver.define(new VarDecl(INIT.str, NamedType.BOOL)); } @Override public void main() { createVariables(-1); for (int k = 0; k <= settings.n; k++) { comment("K = " + k); processMessagesAndWait(k); createVariables(k); assertTransition(k); checkRealizabilities(k); assertProperties(k); } } private void processMessagesAndWait(int k) { try { while (!incoming.isEmpty() || k > kLimit) { Message message = incoming.take(); if (message instanceof UnrealizableMessage) { throw new StopException(); } else if (message instanceof InconsistentMessage) { throw new StopException(); } else if (message instanceof BaseStepMessage) { BaseStepMessage baseStepMessage = (BaseStepMessage) message; kLimit = baseStepMessage.step; } else if (message instanceof UnknownMessage) { throw new StopException(); } else { throw new JKindException( "Unknown message type in inductive process: " + message.getClass().getCanonicalName()); } } } catch (InterruptedException e) { throw new JKindException("Interrupted while waiting for message", e); } } private void assertTransition(int k) { solver.assertSexp(getInductiveTransition(k)); } private void assertProperties(int k) { solver.assertSexp(StreamIndex.conjoinEncodings(spec.node.properties, k)); } private void checkRealizabilities(int k) { Result result = solver.realizabilityQuery(getRealizabilityOutputs(k), getInductiveTransition(k), StreamIndex.conjoinEncodings(spec.node.properties, k)); if (result instanceof UnsatResult) { sendRealizable(k); throw new StopException(); } else if (result instanceof SatResult) { Model model = ((SatResult) result).getModel(); sendExtendCounterexample(k + 1, model); } else if (result instanceof UnknownResult) { throw new StopException(); } } private void sendRealizable(int k) { RealizableMessage rm = new RealizableMessage(k); baseEngine.incoming.add(rm); director.incoming.add(rm); } private void sendExtendCounterexample(int k, Model model) { if (settings.extendCounterexample) { director.incoming.add(new ExtendCounterexampleMessage(k, model)); } } }
3,558
30.776786
98
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/RealizabilityBaseEngine.java
package jkind.realizability.engines; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jkind.JKindException; import jkind.JRealizabilitySettings; import jkind.engines.StopException; import jkind.realizability.engines.messages.BaseStepMessage; import jkind.realizability.engines.messages.InconsistentMessage; import jkind.realizability.engines.messages.Message; import jkind.realizability.engines.messages.RealizableMessage; import jkind.realizability.engines.messages.UnknownMessage; import jkind.realizability.engines.messages.UnrealizableMessage; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.solvers.Model; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.UnknownResult; import jkind.solvers.UnsatResult; import jkind.translation.Specification; import jkind.util.StreamIndex; public class RealizabilityBaseEngine extends RealizabilityEngine { private RealizabilityExtendEngine extendEngine; private static final int REDUCE_TIMEOUT_MS = 200; public RealizabilityBaseEngine(Specification spec, JRealizabilitySettings settings, RealizabilityDirector director) { super("base", spec, settings, director); } public void setExtendEngine(RealizabilityExtendEngine extendEngine) { this.extendEngine = extendEngine; } @Override public void main() { createVariables(-1); for (int k = 0; k < settings.n; k++) { comment("K = " + (k + 1)); processMessages(); createVariables(k); assertTransition(k); checkConsistency(k); checkRealizable(k); assertProperties(k); } } private void processMessages() { while (!incoming.isEmpty()) { Message message = incoming.poll(); if (message instanceof RealizableMessage) { throw new StopException(); } throw new JKindException("Unknown message type in base process: " + message.getClass().getCanonicalName()); } } private void assertTransition(int k) { solver.assertSexp(getTransition(k, k == 0)); } private void assertProperties(int k) { solver.assertSexp(StreamIndex.conjoinEncodings(spec.node.properties, k)); } private void checkConsistency(int k) { Result result = solver.query(new Symbol("false")); if (result instanceof UnsatResult) { sendInconsistent(k); throw new StopException(); } } private void checkRealizable(int k) { Result result = solver.realizabilityQuery(getRealizabilityOutputs(k), getTransition(k, k == 0), StreamIndex.conjoinEncodings(spec.node.properties, k)); if (result instanceof UnsatResult) { sendBaseStep(k); return; } if (result instanceof SatResult) { Model model = ((SatResult) result).getModel(); if (settings.reduce) { reduceAndSendUnrealizable(k, model); } else { sendUnrealizable(k, model); } } else if (result instanceof UnknownResult) { sendUnknown(); } throw new StopException(); } private void reduceAndSendUnrealizable(int k, Model model) { Sexp realizabilityOutputs = getRealizabilityOutputs(k); Sexp transition = getTransition(k, k == 0); List<String> conflicts = new ArrayList<>(spec.node.properties); for (String curr : spec.node.properties) { conflicts.remove(curr); Result result = solver.realizabilityQuery(realizabilityOutputs, transition, StreamIndex.conjoinEncodings(conflicts, k), REDUCE_TIMEOUT_MS); if (result instanceof SatResult) { model = ((SatResult) result).getModel(); } else { conflicts.add(curr); } } sendUnrealizable(k, model, conflicts); } private void sendBaseStep(int k) { BaseStepMessage bsm = new BaseStepMessage(k + 1); director.incoming.add(bsm); extendEngine.incoming.add(bsm); } private void sendInconsistent(int k) { InconsistentMessage im = new InconsistentMessage(k + 1); director.incoming.add(im); extendEngine.incoming.add(im); } private void sendUnrealizable(int k, Model model) { sendUnrealizable(k, model, Collections.emptyList()); } private void sendUnrealizable(int k, Model model, List<String> conflicts) { UnrealizableMessage im = new UnrealizableMessage(k + 1, model, conflicts); director.incoming.add(im); extendEngine.incoming.add(im); } private void sendUnknown() { UnknownMessage um = new UnknownMessage(); director.incoming.add(um); extendEngine.incoming.add(um); } }
4,305
28.094595
110
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/RealizabilityEngine.java
package jkind.realizability.engines; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import jkind.JRealizabilitySettings; import jkind.analysis.LinearChecker; import jkind.engines.StopException; import jkind.lustre.Expr; import jkind.lustre.LustreUtil; import jkind.lustre.VarDecl; import jkind.realizability.engines.messages.Message; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.solvers.z3.Z3Solver; import jkind.translation.Lustre2Sexp; import jkind.translation.Specification; import jkind.util.StreamIndex; import jkind.util.Util; public abstract class RealizabilityEngine implements Runnable { protected final String name; protected final Specification spec; protected final JRealizabilitySettings settings; protected final RealizabilityDirector director; protected Z3Solver solver; protected final BlockingQueue<Message> incoming = new LinkedBlockingQueue<>(); // The director process will read this from another thread, so we // make it volatile protected volatile Throwable throwable; public RealizabilityEngine(String name, Specification spec, JRealizabilitySettings settings, RealizabilityDirector director) { this.name = name; this.spec = spec; this.settings = settings; this.director = director; } protected abstract void main(); @Override public final void run() { try { initializeSolver(); main(); } catch (StopException se) { } catch (Throwable t) { throwable = t; } finally { if (solver != null) { solver.stop(); solver = null; } } } protected void initializeSolver() { solver = new Z3Solver(getScratchBase(), LinearChecker.isLinear(spec.node)); solver.initialize(); solver.declare(spec.functions); solver.define(spec.getTransitionRelation()); } protected String getScratchBase() { if (settings.scratch) { return settings.filename + "." + name; } else { return null; } } public Throwable getThrowable() { return throwable; } /** Utility */ protected void comment(String str) { solver.comment(str); } public String getName() { return name; } protected void createVariables(int k) { for (VarDecl vd : getOffsetVarDecls(k)) { solver.define(vd); } for (VarDecl vd : Util.getVarDecls(spec.node)) { Expr constraint = LustreUtil.typeConstraint(vd.id, vd.type); if (constraint != null) { solver.assertSexp(constraint.accept(new Lustre2Sexp(k))); } } } protected List<VarDecl> getOffsetVarDecls(int k) { return getOffsetVarDecls(k, Util.getVarDecls(spec.node)); } protected List<VarDecl> getOffsetVarDecls(int k, List<VarDecl> varDecls) { List<VarDecl> result = new ArrayList<>(); for (VarDecl vd : varDecls) { StreamIndex si = new StreamIndex(vd.id, k); result.add(new VarDecl(si.getEncoded().str, vd.type)); } return result; } protected Sexp getTransition(int k, Sexp init) { List<Sexp> args = new ArrayList<>(); args.add(init); args.addAll(getSymbols(getOffsetVarDecls(k - 1))); args.addAll(getSymbols(getOffsetVarDecls(k))); return new Cons(spec.getTransitionRelation().getName(), args); } protected Sexp getTransition(int k, boolean init) { return getTransition(k, Sexp.fromBoolean(init)); } protected Sexp getRealizabilityOutputs(int k) { List<VarDecl> realizabilityOutputVarDecls = getRealizabilityOutputVarDecls(); if (realizabilityOutputVarDecls.isEmpty()) { return null; } else { return varDeclsToQuantifierArguments(realizabilityOutputVarDecls, k); } } protected Sexp getInductiveTransition(int k) { if (k == 0) { return getTransition(0, INIT); } else { return getTransition(k, false); } } protected static final Symbol INIT = Lustre2Sexp.INIT; private List<VarDecl> getRealizabilityOutputVarDecls() { List<String> realizabilityInputs = spec.node.realizabilityInputs; List<VarDecl> all = Util.getVarDecls(spec.node); all.removeIf(vd -> realizabilityInputs.contains(vd.id)); return all; } protected Sexp varDeclsToQuantifierArguments(List<VarDecl> varDecls, int k) { List<Sexp> args = new ArrayList<>(); for (VarDecl vd : varDecls) { Symbol name = new StreamIndex(vd.id, k).getEncoded(); Symbol type = solver.type(vd.type); args.add(new Cons(name, type)); } return new Cons(args); } protected List<Sexp> getSymbols(List<VarDecl> varDecls) { List<Sexp> result = new ArrayList<>(); for (VarDecl vd : varDecls) { result.add(new Symbol(vd.id)); } return result; } }
4,571
25.427746
93
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/RealizabilityDirector.java
package jkind.realizability.engines; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import jkind.ExitCodes; import jkind.JKindException; import jkind.JRealizabilitySettings; import jkind.Main; import jkind.StdErr; import jkind.realizability.engines.messages.BaseStepMessage; import jkind.realizability.engines.messages.ExtendCounterexampleMessage; import jkind.realizability.engines.messages.InconsistentMessage; import jkind.realizability.engines.messages.Message; import jkind.realizability.engines.messages.RealizableMessage; import jkind.realizability.engines.messages.UnknownMessage; import jkind.realizability.engines.messages.UnrealizableMessage; import jkind.realizability.writers.ConsoleWriter; import jkind.realizability.writers.ExcelWriter; import jkind.realizability.writers.Writer; import jkind.realizability.writers.XmlWriter; import jkind.results.Counterexample; import jkind.results.layout.RealizabilityNodeLayout; import jkind.solvers.Model; import jkind.translation.Specification; import jkind.util.CounterexampleExtractor; public class RealizabilityDirector { private JRealizabilitySettings settings; private Specification spec; private Writer writer; private int baseStep = 0; private ExtendCounterexampleMessage extendCounterexample; private boolean done = false; private List<RealizabilityEngine> engines = new ArrayList<>(); private List<Thread> threads = new ArrayList<>(); protected BlockingQueue<Message> incoming = new LinkedBlockingQueue<>(); public RealizabilityDirector(JRealizabilitySettings settings, Specification spec) { this.settings = settings; this.spec = spec; this.writer = getWriter(spec); } private Writer getWriter(Specification spec) { try { if (settings.excel) { return new ExcelWriter(settings.filename + ".xls", spec.node); } else if (settings.xml) { return new XmlWriter(settings.filename + ".xml", spec.typeMap); } else { return new ConsoleWriter(new RealizabilityNodeLayout(spec.node)); } } catch (IOException e) { throw new JKindException("Unable to open output file", e); } } public int run() { printHeader(); writer.begin(); startThreads(); long startTime = System.currentTimeMillis(); long timeout = startTime + ((long) settings.timeout) * 1000; while (System.currentTimeMillis() < timeout && !done && someThreadAlive() && !someEngineFailed()) { processMessages(startTime); try { Thread.sleep(100); } catch (InterruptedException e) { } } processMessages(startTime); if (!done) { writer.writeUnknown(baseStep, convertExtendCounterexample(), getRuntime(startTime)); } writer.end(); return reportFailures(); } private boolean someThreadAlive() { for (Thread thread : threads) { if (thread.isAlive()) { return true; } } return false; } private boolean someEngineFailed() { for (RealizabilityEngine process : engines) { if (process.getThrowable() != null) { return true; } } return false; } private int reportFailures() { int exitCode = 0; for (RealizabilityEngine process : engines) { if (process.getThrowable() != null) { Throwable t = process.getThrowable(); StdErr.println(process.getName() + " process failed"); StdErr.printStackTrace(t); exitCode = ExitCodes.UNCAUGHT_EXCEPTION; } } return exitCode; } private void printHeader() { System.out.println("=========================================="); System.out.println(" JRealizability " + Main.getVersion()); System.out.println("=========================================="); System.out.println(); } private void startThreads() { RealizabilityBaseEngine baseEngine = new RealizabilityBaseEngine(spec, settings, this); registerProcess(baseEngine); RealizabilityExtendEngine extendEngine = new RealizabilityExtendEngine(spec, settings, this); baseEngine.setExtendEngine(extendEngine); extendEngine.setBaseEngine(baseEngine); registerProcess(extendEngine); for (Thread thread : threads) { thread.start(); } } private void registerProcess(RealizabilityEngine process) { engines.add(process); threads.add(new Thread(process, process.getName())); } private void processMessages(long startTime) { while (!done && !incoming.isEmpty()) { Message message = incoming.poll(); double runtime = getRuntime(startTime); if (message instanceof RealizableMessage) { RealizableMessage rm = (RealizableMessage) message; done = true; writer.writeRealizable(rm.k, runtime); } else if (message instanceof UnrealizableMessage) { UnrealizableMessage um = (UnrealizableMessage) message; done = true; Counterexample cex = extractCounterexample(um.k, um.model); writer.writeUnrealizable(cex, um.properties, runtime); } else if (message instanceof ExtendCounterexampleMessage) { extendCounterexample = (ExtendCounterexampleMessage) message; } else if (message instanceof UnknownMessage) { done = true; writer.writeUnknown(baseStep, null, runtime); } else if (message instanceof BaseStepMessage) { BaseStepMessage bsm = (BaseStepMessage) message; writer.writeBaseStep(bsm.step); baseStep = bsm.step; } else if (message instanceof InconsistentMessage) { InconsistentMessage im = (InconsistentMessage) message; done = true; writer.writeInconsistent(im.k, runtime); } else { throw new JKindException("Unknown message type in director: " + message.getClass().getCanonicalName()); } } } private double getRuntime(long startTime) { return (System.currentTimeMillis() - startTime) / 1000.0; } private Counterexample convertExtendCounterexample() { if (extendCounterexample == null) { return null; } return extractCounterexample(extendCounterexample.k, extendCounterexample.model); } private Counterexample extractCounterexample(int k, Model model) { return CounterexampleExtractor.extract(spec, k, model); } }
6,051
29.877551
107
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/ExtendCounterexampleMessage.java
package jkind.realizability.engines.messages; import jkind.solvers.Model; public class ExtendCounterexampleMessage extends Message { public final int k; public final Model model; public ExtendCounterexampleMessage(int k, Model model) { this.k = k; this.model = model; } }
283
19.285714
58
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/UnknownMessage.java
package jkind.realizability.engines.messages; public class UnknownMessage extends Message { }
95
18.2
45
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/BaseStepMessage.java
package jkind.realizability.engines.messages; public class BaseStepMessage extends Message { public int step; public BaseStepMessage(int step) { this.step = step; } }
174
16.5
46
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/Message.java
package jkind.realizability.engines.messages; public abstract class Message { }
81
15.4
45
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/RealizableMessage.java
package jkind.realizability.engines.messages; public class RealizableMessage extends Message { public final int k; public RealizableMessage(int k) { this.k = k; } }
172
16.3
48
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/UnrealizableMessage.java
package jkind.realizability.engines.messages; import java.util.List; import jkind.solvers.Model; import jkind.util.Util; public class UnrealizableMessage extends Message { public final int k; public final Model model; public final List<String> properties; public UnrealizableMessage(int k, Model model, List<String> conflicts) { this.k = k; this.model = model; this.properties = Util.safeList(conflicts); } }
424
21.368421
73
java
jkind
jkind-master/jkind/src/jkind/realizability/engines/messages/InconsistentMessage.java
package jkind.realizability.engines.messages; public class InconsistentMessage extends Message { public final int k; public InconsistentMessage(int k) { this.k = k; } }
176
16.7
50
java
jkind
jkind-master/jkind/src/jkind/sexp/Symbol.java
package jkind.sexp; public class Symbol extends Sexp { public final String str; public Symbol(String sym) { this.str = sym; } @Override public String toString() { return str; } @Override protected void toBuilder(StringBuilder sb) { sb.append(str); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((str == null) ? 0 : str.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Symbol)) { return false; } Symbol other = (Symbol) obj; if (str == null) { if (other.str != null) { return false; } } else if (!str.equals(other.str)) { return false; } return true; } }
804
15.1
65
java
jkind
jkind-master/jkind/src/jkind/sexp/Cons.java
package jkind.sexp; import java.util.Arrays; import java.util.List; public class Cons extends Sexp { public final Sexp head; public final List<? extends Sexp> args; public Cons(Sexp head, List<? extends Sexp> args) { this.head = head; this.args = args; } public Cons(Sexp head, Sexp... args) { this(head, Arrays.asList(args)); } public Cons(String head, List<? extends Sexp> args) { this.head = new Symbol(head); this.args = args; } public Cons(String head, Sexp... args) { this(head, Arrays.asList(args)); } public Cons(List<Sexp> sexps) { this(sexps.get(0), sexps.subList(1, sexps.size())); } @Override public String toString() { StringBuilder sb = new StringBuilder(); toBuilder(sb); return sb.toString(); } @Override protected void toBuilder(StringBuilder sb) { sb.append("("); head.toBuilder(sb); for (Sexp arg : args) { sb.append(" "); arg.toBuilder(sb); } sb.append(")"); } }
946
17.94
54
java
jkind
jkind-master/jkind/src/jkind/sexp/Sexp.java
package jkind.sexp; import java.math.BigInteger; public abstract class Sexp { protected abstract void toBuilder(StringBuilder sb); public static Sexp fromInt(int i) { if (i >= 0) { return new Symbol(Integer.toString(i)); } else { return new Cons("-", new Symbol("0"), new Symbol(Integer.toString(-i))); } } public static Sexp fromBigInt(BigInteger i) { if (i.signum() >= 0) { return new Symbol(i.toString()); } else { return new Cons("-", new Symbol("0"), new Symbol(i.negate().toString())); } } public static Sexp fromBoolean(boolean b) { return new Symbol(b ? "true" : "false"); } }
623
21.285714
76
java
jkind
jkind-master/jkind/src/jkind/translation/Specification.java
package jkind.translation; import java.util.List; import java.util.Map; import jkind.lustre.Function; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.slicing.DependencyMap; import jkind.slicing.LustreSlicer; import jkind.util.Util; public class Specification { public final Node node; public final List<Function> functions; public final DependencyMap dependencyMap; public final Map<String, Type> typeMap; private Relation transitionRelation; private Relation ivcTransitionRelation; public Specification(Program program, boolean slicing) { Node main = program.getMainNode(); if (slicing) { this.dependencyMap = new DependencyMap(main, main.properties, program.functions); } else { this.dependencyMap = DependencyMap.full(main, program.functions); } this.node = LustreSlicer.slice(main, dependencyMap); this.functions = Util.safeList(program.functions); this.typeMap = Util.getTypeMap(node); } public Specification(Program program) { this(program, false); } public Relation getTransitionRelation() { if (transitionRelation == null) { transitionRelation = Lustre2Sexp.constructTransitionRelation(node); } return transitionRelation; } public Relation getIvcTransitionRelation() { if (ivcTransitionRelation == null) { ivcTransitionRelation = Lustre2Sexp.constructIvcTransitionRelation(node); } return ivcTransitionRelation; } }
1,430
27.058824
84
java
jkind
jkind-master/jkind/src/jkind/translation/Node2Excel.java
package jkind.translation; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.EnumType; import jkind.lustre.Equation; import jkind.lustre.Node; import jkind.lustre.VarDecl; import jkind.util.Util; import jxl.CellView; import jxl.JXLException; import jxl.Workbook; import jxl.format.CellFormat; import jxl.write.Formula; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class Node2Excel { public static final int LENGTH = 30; private final Map<String, Integer> rowAssignments = new HashMap<>(); private final Map<String, String> intToEnum = new HashMap<>(); private final Map<String, String> enumToInt = new HashMap<>(); private int row = 0; private int enumerationsStartRow; public void convert(Node main, String filename) throws JXLException, IOException { WritableWorkbook workbook = Workbook.createWorkbook(new File(filename)); WritableSheet sheet = workbook.createSheet("Lustre", 0); // Print steps header CellFormat boldFormat = getBoldFormat(); sheet.addCell(new Label(0, row, "Step", boldFormat)); for (int col = 1; col <= LENGTH; col++) { sheet.addCell(new Number(col, row, col - 1)); } // Calculate locations and fill in enumerations row += 2; createRowAssignments(main); row += 1; createEnumerations(sheet, main); // Print headers List<String> rows = Util.getIds(Util.getVarDecls(main)); for (String row : rows) { sheet.addCell(new Label(0, rowAssignments.get(row), row, boldFormat)); } // Print equations for locals and outputs for (Equation eq : main.equations) { String id = eq.lhs.get(0).id; int row = rowAssignments.get(id); for (int col = 1; col <= LENGTH; col++) { Expr2FormulaVisitor visitor = new Expr2FormulaVisitor(id, col, rowAssignments, intToEnum, enumToInt); eq.expr.accept(visitor); String formula = visitor.toString(); if (!formula.isEmpty()) { sheet.addCell(new Formula(col, row, formula)); } } } // Hide generated locals for (VarDecl local : main.locals) { if (local.id.contains("~")) { hideRow(sheet, rowAssignments.get(local.id)); } } // Hide enumerations for (int i = enumerationsStartRow; i < row; i++) { hideRow(sheet, i); } workbook.write(); workbook.close(); } private void hideRow(WritableSheet sheet, int i) throws RowsExceededException { CellView rowView = sheet.getRowView(i); rowView.setHidden(true); sheet.setRowView(i, rowView); } /** * The enumerated type { A, B, C, D } will be represented by * * <pre> * 0 1 2 3 * A B C D * 0 1 2 3 * </pre> * * This allows us to do a hlookup on rows 1 & 2 to convert integers to * enumerated values, and a hlookup on rows 2 & 3 to convert enumerated * values to integers. * * Note: The index and match functions do not work in JExcelApi. Nor do * array literals. Otherwise, this conversion would be much easier. */ private void createEnumerations(WritableSheet sheet, Node main) throws JXLException { Map<EnumType, String> intToEnumCache = new HashMap<>(); Map<EnumType, String> enumToIntCache = new HashMap<>(); enumerationsStartRow = row; for (VarDecl def : Util.getVarDecls(main)) { if (def.type instanceof EnumType) { EnumType et = (EnumType) def.type; if (intToEnumCache.containsKey(et)) { intToEnum.put(def.id, intToEnumCache.get(et)); enumToInt.put(def.id, enumToIntCache.get(et)); } else { for (int i = 0; i < et.values.size(); i++) { sheet.addCell(new Number(i, row, i)); sheet.addCell(new Label(i, row + 1, et.values.get(i))); sheet.addCell(new Number(i, row + 2, i)); } String i2e = "$A$" + (row + 1) + ":$ZZ$" + (row + 2); String e2i = "$A$" + (row + 2) + ":$ZZ$" + (row + 3); intToEnum.put(def.id, i2e); enumToInt.put(def.id, e2i); intToEnumCache.put(et, i2e); enumToIntCache.put(et, e2i); row += 4; } } } } private static CellFormat getBoldFormat() throws WriteException { WritableCellFormat boldFormat = new WritableCellFormat(); WritableFont font = new WritableFont(boldFormat.getFont()); font.setBoldStyle(WritableFont.BOLD); boldFormat.setFont(font); return boldFormat; } private void createRowAssignments(Node main) { for (VarDecl input : main.inputs) { rowAssignments.put(input.id, row++); } row++; for (VarDecl local : main.locals) { rowAssignments.put(local.id, row++); } row++; for (VarDecl output : main.outputs) { rowAssignments.put(output.id, row++); } } }
4,815
27.666667
105
java
jkind
jkind-master/jkind/src/jkind/translation/Lustre2Sexp.java
package jkind.translation; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.VarDecl; import jkind.lustre.visitors.ExprVisitor; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.sexp.Symbol; import jkind.util.LinkedBiMap; import jkind.util.SexpUtil; import jkind.util.StreamIndex; import jkind.util.Util; public class Lustre2Sexp implements ExprVisitor<Sexp> { public static final Symbol INIT = new Symbol("%init"); private final int index; private boolean pre = false; public Lustre2Sexp(int index) { this.index = index; } public static Relation constructTransitionRelation(Node node) { return constructGeneralTransitionRelation(node, Collections.emptyList()); } public static Relation constructIvcTransitionRelation(Node node) { return constructGeneralTransitionRelation(node, node.ivc); } private static Relation constructGeneralTransitionRelation(Node node, List<String> ivc) { Lustre2Sexp visitor = new Lustre2Sexp(1); List<Sexp> conjuncts = new ArrayList<>(); LinkedBiMap<String, Symbol> ivcMap = createIvcMap(ivc); for (Equation eq : node.equations) { Sexp body = eq.expr.accept(visitor); Sexp head = eq.lhs.get(0).accept(visitor); Sexp sexp = new Cons("=", head, body); String id = eq.lhs.get(0).id; if (ivcMap.containsKey(id)) { sexp = new Cons("=>", ivcMap.get(id), sexp); } conjuncts.add(sexp); } for (Expr assertion : node.assertions) { conjuncts.add(assertion.accept(visitor)); } List<VarDecl> inputs = new ArrayList<>(); inputs.add(new VarDecl(INIT.str, NamedType.BOOL)); inputs.addAll(visitor.pre(Util.getVarDecls(node))); inputs.addAll(visitor.curr(Util.getVarDecls(node))); return new Relation(Relation.T, inputs, SexpUtil.conjoin(conjuncts)); } public static LinkedBiMap<String, Symbol> createIvcMap(List<String> ivc) { LinkedBiMap<String, Symbol> ivcMap = new LinkedBiMap<>(); int id = 0; for (String s : ivc) { ivcMap.put(s, new Symbol("ivc" + id++)); } return ivcMap; } private Symbol curr(String id) { return new StreamIndex(id, index).getEncoded(); } private Symbol pre(String id) { return new StreamIndex(id, index - 1).getEncoded(); } private VarDecl curr(VarDecl vd) { return new VarDecl(curr(vd.id).str, vd.type); } private VarDecl pre(VarDecl vd) { return new VarDecl(pre(vd.id).str, vd.type); } private List<VarDecl> curr(List<VarDecl> varDecls) { List<VarDecl> result = new ArrayList<>(); for (VarDecl vd : varDecls) { result.add(curr(vd)); } return result; } private List<VarDecl> pre(List<VarDecl> varDecls) { List<VarDecl> result = new ArrayList<>(); for (VarDecl vd : varDecls) { result.add(pre(vd)); } return result; } @Override public Sexp visit(ArrayAccessExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to sexp"); } @Override public Sexp visit(ArrayExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to sexp"); } @Override public Sexp visit(ArrayUpdateExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to sexp"); } @Override public Sexp visit(FunctionCallExpr e) { if (e.args.isEmpty()) { return new Symbol(SexpUtil.encodeFunction(e.function)); } List<Sexp> args = new ArrayList<>(); for (Expr expr : e.args) { args.add(expr.accept(this)); } return new Cons(SexpUtil.encodeFunction(e.function), args); } @Override public Sexp visit(BinaryExpr e) { Sexp left = e.left.accept(this); Sexp right = e.right.accept(this); switch (e.op) { case NOTEQUAL: case XOR: return new Cons("not", new Cons("=", left, right)); case ARROW: if (pre) { throw new IllegalArgumentException("Arrows cannot be nested under pre during translation to sexp"); } return new Cons("ite", INIT, left, right); default: return new Cons(e.op.toString(), left, right); } } @Override public Sexp visit(BoolExpr e) { return Sexp.fromBoolean(e.value); } @Override public Sexp visit(CastExpr e) { if (e.type == NamedType.REAL) { return new Cons("to_real", e.expr.accept(this)); } else if (e.type == NamedType.INT) { return new Cons("to_int", e.expr.accept(this)); } else { throw new IllegalArgumentException(); } } @Override public Sexp visit(CondactExpr e) { throw new IllegalArgumentException("Condacts must be removed before translation to sexp"); } @Override public Sexp visit(IdExpr e) { return pre ? pre(e.id) : curr(e.id); } @Override public Sexp visit(IfThenElseExpr e) { return new Cons("ite", e.cond.accept(this), e.thenExpr.accept(this), e.elseExpr.accept(this)); } @Override public Sexp visit(IntExpr e) { return Sexp.fromBigInt(e.value); } @Override public Sexp visit(NodeCallExpr e) { throw new IllegalArgumentException("Node calls must be inlined before translation to sexp"); } @Override public Sexp visit(RealExpr e) { Sexp numerator = Sexp.fromBigInt(e.value.unscaledValue()); Sexp denominator = Sexp.fromBigInt(BigDecimal.TEN.pow(e.value.scale()).toBigInteger()); return new Cons("/", numerator, denominator); } @Override public Sexp visit(RecordAccessExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to sexp"); } @Override public Sexp visit(RecordExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to sexp"); } @Override public Sexp visit(RecordUpdateExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to sexp"); } @Override public Sexp visit(TupleExpr e) { throw new IllegalArgumentException("Tuples must be flattened before translation to sexp"); } @Override public Sexp visit(UnaryExpr e) { switch (e.op) { case PRE: if (pre) { throw new IllegalArgumentException("Nested pres must be removed before translation to sexp"); } pre = true; Sexp expr = e.expr.accept(this); pre = false; return expr; case NEGATIVE: return new Cons("-", new Symbol("0"), e.expr.accept(this)); default: return new Cons(e.op.toString(), e.expr.accept(this)); } } }
6,966
25.390152
103
java
jkind
jkind-master/jkind/src/jkind/translation/Translate.java
package jkind.translation; import jkind.lustre.Program; import jkind.translation.compound.FlattenCompoundTypes; public class Translate { public static Program translate(Program program) { program = InlineEnumValues.program(program); program = InlineUserTypes.program(program); program = InlineConstants.program(program); program = RemoveCondacts.program(program); program = InlineNodeCalls.program(program); program = FlattenCompoundTypes.program(program); program = FlattenPres.program(program); return program; } }
537
28.888889
55
java
jkind
jkind-master/jkind/src/jkind/translation/Relation.java
package jkind.translation; import java.util.List; import jkind.lustre.VarDecl; import jkind.sexp.Sexp; public class Relation { public static final String T = "T"; // transition private final String name; private final List<VarDecl> inputs; private final Sexp body; public Relation(String name, List<VarDecl> inputs, Sexp body) { this.name = name; this.inputs = inputs; this.body = body; } public String getName() { return name; } public List<VarDecl> getInputs() { return inputs; } public Sexp getBody() { return body; } }
555
15.848485
64
java
jkind
jkind-master/jkind/src/jkind/translation/ResolvingSubstitutionMap.java
package jkind.translation; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.Set; import jkind.lustre.Expr; import jkind.lustre.IdExpr; public class ResolvingSubstitutionMap implements Map<String, Expr> { private final Map<String, Expr> map = new HashMap<>(); private final Deque<String> stack = new ArrayDeque<>(); private Expr resolve(Expr e) { if (e instanceof IdExpr) { IdExpr eid = (IdExpr) e; return resolve(eid.id); } return e; } private Expr resolve(String id) { if (stack.contains(id)) { return null; } stack.push(id); Expr e = map.get(id); Expr eResolved = resolve(e); if (eResolved == null) { eResolved = e; } else if (e != eResolved) { map.put(id, eResolved); } stack.pop(); return eResolved; } @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public Expr get(Object key) { if (key instanceof String) { String id = (String) key; return resolve(id); } return null; } @Override public Expr put(String key, Expr value) { return map.put(key, value); } @Override public Expr remove(Object key) { return map.remove(key); } @Override public void putAll(Map<? extends String, ? extends Expr> m) { map.putAll(m); } @Override public void clear() { map.clear(); } @Override public Set<String> keySet() { return map.keySet(); } @Override public Collection<Expr> values() { return map.values(); } @Override public Set<Map.Entry<String, Expr>> entrySet() { return map.entrySet(); } }
1,860
16.392523
68
java
jkind
jkind-master/jkind/src/jkind/translation/DefaultValueVisitor.java
package jkind.translation; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.BoolExpr; import jkind.lustre.EnumType; import jkind.lustre.Expr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.RealExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.SubrangeIntType; import jkind.lustre.TupleExpr; import jkind.lustre.TupleType; import jkind.lustre.Type; import jkind.lustre.visitors.TypeVisitor; public class DefaultValueVisitor implements TypeVisitor<Expr> { @Override public Expr visit(ArrayType e) { List<Expr> elements = new ArrayList<>(); Expr baseValue = e.base.accept(this); for (int i = 0; i < e.size; i++) { elements.add(baseValue); } return new ArrayExpr(elements); } @Override public Expr visit(EnumType e) { // Enums are already inlined return new IntExpr(0); } @Override public Expr visit(NamedType e) { if (e == NamedType.BOOL) { return new BoolExpr(false); } else if (e == NamedType.INT) { return new IntExpr(BigInteger.ZERO); } else if (e == NamedType.REAL) { return new RealExpr(BigDecimal.ZERO); } else { throw new IllegalArgumentException(); } } @Override public Expr visit(RecordType e) { Map<String, Expr> fields = new HashMap<>(); for (String key : e.fields.keySet()) { fields.put(key, e.fields.get(key).accept(this)); } return new RecordExpr(e.id, fields); } @Override public Expr visit(TupleType e) { List<Expr> elements = new ArrayList<>(); for (Type t : e.types) { elements.add(t.accept(this)); } return new TupleExpr(elements); } @Override public Expr visit(SubrangeIntType e) { return new IntExpr(e.low); } }
1,883
22.848101
63
java
jkind
jkind-master/jkind/src/jkind/translation/InlineUserTypes.java
package jkind.translation; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstMapVisitor; import jkind.util.Util; public class InlineUserTypes extends AstMapVisitor { public static Program program(Program program) { return new InlineUserTypes().visit(program); } private final Map<String, Type> types = new HashMap<>(); @Override protected List<TypeDef> visitTypeDefs(List<TypeDef> es) { types.putAll(Util.createResolvedTypeTable(es)); return Collections.emptyList(); } @Override public VarDecl visit(VarDecl e) { return new VarDecl(e.id, Util.resolveType(e.type, types)); } }
795
23.121212
60
java
jkind
jkind-master/jkind/src/jkind/translation/RemoveEnumTypes.java
package jkind.translation; import java.math.BigInteger; import jkind.lustre.EnumType; import jkind.lustre.Program; import jkind.lustre.SubrangeIntType; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstMapVisitor; public class RemoveEnumTypes extends AstMapVisitor { public static Program program(Program program) { return new RemoveEnumTypes().visit(program); } @Override public VarDecl visit(VarDecl e) { if (e.type instanceof EnumType) { EnumType et = (EnumType) e.type; BigInteger high = BigInteger.valueOf(et.values.size() - 1); return new VarDecl(e.id, new SubrangeIntType(BigInteger.ZERO, high)); } else { return e; } } }
669
23.814815
72
java
jkind
jkind-master/jkind/src/jkind/translation/InlineEnumValues.java
package jkind.translation; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.EnumType; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.Program; import jkind.lustre.TypeDef; import jkind.lustre.visitors.AstMapVisitor; import jkind.util.Util; public class InlineEnumValues extends AstMapVisitor { public static Program program(Program program) { return new InlineEnumValues().visit(program); } private final Map<String, IntExpr> enumValues = new HashMap<>(); @Override protected List<TypeDef> visitTypeDefs(List<TypeDef> es) { for (EnumType et : Util.getEnumTypes(es)) { for (int i = 0; i < et.values.size(); i++) { enumValues.put(et.values.get(i), new IntExpr(i)); } } return es; } @Override public Expr visit(IdExpr e) { if (enumValues.containsKey(e.id)) { return enumValues.get(e.id); } else { return e; } } }
953
21.186047
65
java
jkind
jkind-master/jkind/src/jkind/translation/RemoveCondacts.java
package jkind.translation; import static jkind.lustre.LustreUtil.FALSE; import static jkind.lustre.LustreUtil.TRUE; import static jkind.lustre.LustreUtil.and; import static jkind.lustre.LustreUtil.arrow; import static jkind.lustre.LustreUtil.eq; import static jkind.lustre.LustreUtil.id; import static jkind.lustre.LustreUtil.implies; import static jkind.lustre.LustreUtil.ite; import static jkind.lustre.LustreUtil.pre; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.builders.ProgramBuilder; import jkind.lustre.visitors.AstMapVisitor; import jkind.lustre.visitors.TypeReconstructor; import jkind.util.Util; /** * Remove all condacts and replace with modified nodes and node calls. * * We handle condacts by creating a modified node that takes the clock and * default values as arguments. The new node guards stateful computations (pre * expressions) so they are only persisted when the clock is active. The new * node also guards outputs so that they only change when the clock is active * and they default to the specified values. */ public class RemoveCondacts { public static Program program(Program program) { RemoveCondacts remover = new RemoveCondacts(program); remover.remove(); return remover.getResult(); } private final Program program; private final Map<String, Node> nodeTable; private final List<Node> resultNodes = new ArrayList<>(); private final TypeReconstructor typeReconstructor; private final IdExpr INIT = id("~init"); private final IdExpr CLOCK = id("~clock"); private RemoveCondacts(Program program) { this.program = program; this.nodeTable = Util.getNodeTable(program.nodes); this.typeReconstructor = new TypeReconstructor(program); } private void remove() { Program simplified = removeTrivialCondacts(); for (Node node : simplified.nodes) { resultNodes.add(removeCondacts(node)); } } private Program removeTrivialCondacts() { return (Program) program.accept(new AstMapVisitor() { @Override public Expr visit(CondactExpr e) { if (isLiteralTrue(e.clock)) { return e.call.accept(this); } else { return super.visit(e); } } }); } private boolean isLiteralTrue(Expr e) { return e instanceof BoolExpr && ((BoolExpr) e).value; } private Node removeCondacts(Node node) { return (Node) node.accept(new AstMapVisitor() { @Override public Expr visit(CondactExpr e) { NodeCallExpr call = (NodeCallExpr) e.call.accept(this); List<Expr> args = new ArrayList<>(); args.add(e.clock.accept(this)); args.addAll(e.call.args); args.addAll(visitExprs(e.args)); Node condact = createCondactNode(call.node); return new NodeCallExpr(condact.id, args); } }); } /* * This used to be implemented with the computeIfAbsent method but this creates * concurrent modification exceptions. * * The code below implements the computeIfAbsent check but omits the concurrent * modification check. We're not modifying the mapping between keys and variables * during traversal so we're comfortable with this arrangement for now. */ private Node createCondactNode(String id) { String condactId = id + "~condact"; if (nodeTable.containsKey(condactId)) { return nodeTable.get(condactId); } else { return createTimedNode(id, condactId, true); } } private Node createTimedNode(String id, String condactId, boolean clockOutputs) { Node node = nodeTable.get(id); typeReconstructor.setNodeContext(node); typeReconstructor.addVariable(new VarDecl(INIT.id, NamedType.BOOL)); typeReconstructor.addVariable(new VarDecl(CLOCK.id, NamedType.BOOL)); node = clockArrows(node); node = clockPres(node); node = defineInit(node); node = addClockInput(node); if (clockOutputs) { node = clockOutputs(node); } node = clockNodeCalls(node); node = clockProperties(node); node = renameNode(node, condactId); nodeTable.put(node.id, node); resultNodes.add(node); return node; } private Node clockArrows(Node node) { return (Node) node.accept(new AstMapVisitor() { @Override public Expr visit(BinaryExpr e) { if (e.op == BinaryOp.ARROW) { return ite(INIT, e.left.accept(this), e.right.accept(this)); } else { return super.visit(e); } } }); } private Node clockPres(Node node) { List<Equation> stateEquations = new ArrayList<>(); List<VarDecl> stateLocals = new ArrayList<>(); Map<String, Expr> cache = new HashMap<>(); node = DistributePres.node(node); node = (Node) node.accept(new AstMapVisitor() { private int counter = 0; @Override public Expr visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { return cache.computeIfAbsent(e.expr.toString(), ignore -> { String state = "~state" + counter++; Type type = e.expr.accept(typeReconstructor); stateLocals.add(new VarDecl(state, type)); // state = if clock then expr else pre state stateEquations.add(eq(id(state), ite(CLOCK, e.expr.accept(this), pre(id(state))))); return pre(id(state)); }); } else { return super.visit(e); } } }); NodeBuilder builder = new NodeBuilder(node); builder.addLocals(stateLocals); builder.addEquations(stateEquations); return builder.build(); } private Node defineInit(Node node) { NodeBuilder builder = new NodeBuilder(node); // init = true -> if pre clock then false else pre init builder.addLocal(new VarDecl(INIT.id, NamedType.BOOL)); builder.addEquation(eq(INIT, arrow(TRUE, ite(pre(CLOCK), FALSE, pre(INIT))))); return builder.build(); } private Node addClockInput(Node node) { NodeBuilder builder = new NodeBuilder(node); builder.clearInputs(); builder.addInput(new VarDecl(CLOCK.id, NamedType.BOOL)); builder.addInputs(node.inputs); return builder.build(); } private Node clockOutputs(Node node) { NodeBuilder builder = new NodeBuilder(node); builder.clearOutputs(); builder.addLocals(node.outputs); for (VarDecl output : node.outputs) { VarDecl dflt = new VarDecl(output.id + "~default", output.type); builder.addInput(dflt); VarDecl clocked = new VarDecl(output.id + "~clocked", output.type); builder.addOutput(clocked); // clocked = if clock then output else (default -> pre clocked) Equation eq = eq(id(clocked), ite(CLOCK, id(output), arrow(id(dflt), pre(id(clocked))))); builder.addEquation(eq); } return builder.build(); } private Node clockNodeCalls(Node node) { return (Node) node.accept(new AstMapVisitor() { @Override public Expr visit(NodeCallExpr e) { List<Expr> args = new ArrayList<>(); args.add(CLOCK); args.addAll(visitExprs(e.args)); Node clocked = createClockedNode(e.node); return new NodeCallExpr(clocked.id, args); } @Override public Expr visit(CondactExpr e) { NodeCallExpr call = (NodeCallExpr) super.visit(e.call); List<Expr> args = new ArrayList<>(); args.add(and(e.clock.accept(this), CLOCK)); args.addAll(e.call.args); args.addAll(visitExprs(e.args)); Node condact = createCondactNode(call.node); return new NodeCallExpr(condact.id, args); } }); } /* * This used to be implemented with the computeIfAbsent method but this creates * concurrent modification exceptions. * * The code below implements the computeIfAbsent check but omits the concurrent * modification check. We're not modifying the mapping between keys and variables * during traversal so we're comfortable with this arrangement for now. */ private Node createClockedNode(String id) { String clockedId = id + "~clocked"; if (nodeTable.containsKey(clockedId)) { return nodeTable.get(clockedId); } else { return createTimedNode(id, clockedId, false); } } private Node clockProperties(Node node) { NodeBuilder builder = new NodeBuilder(node); builder.clearProperties(); for (String property : node.properties) { VarDecl clocked = new VarDecl(property + "~clocked_property", NamedType.BOOL); builder.addLocal(clocked); // clocked_property = clock => property builder.addEquation(eq(id(clocked), implies(CLOCK, id(property)))); builder.addProperty(clocked.id); } return builder.build(); } private Node renameNode(Node node, String id) { return new NodeBuilder(node).setId(id).build(); } private Program getResult() { return new ProgramBuilder(program).clearNodes().addNodes(resultNodes).build(); } }
8,992
29.177852
92
java
jkind
jkind-master/jkind/src/jkind/translation/Expr2FormulaVisitor.java
package jkind.translation; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.NodeCallExpr; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.visitors.ExprVisitor; import jxl.CellReferenceHelper; public class Expr2FormulaVisitor implements ExprVisitor<Void> { private int column; private final String id; private final Map<String, Integer> rowAssignments; private final Map<String, String> intToEnum; private final Map<String, String> enumToInt; private final Set<String> refs; private final StringBuilder buf; final private static int INITIAL_COLUMN = 1; public Expr2FormulaVisitor(String id, int column, Map<String, Integer> rowAssignments, Map<String, String> intToEnum, Map<String, String> enumToInt) { this.id = id; this.column = column; this.rowAssignments = rowAssignments; this.intToEnum = intToEnum; this.enumToInt = enumToInt; this.refs = new LinkedHashSet<>(); this.buf = new StringBuilder(); } @Override public String toString() { if (refs.isEmpty()) { return wrap(buf.toString()); } StringBuilder result = new StringBuilder(); result.append("IF(OR("); boolean first = true; for (String ref : refs) { if (!first) { result.append(","); } result.append("IF(ISERROR(" + ref + "),FALSE," + ref + "=\"\")"); first = false; } result.append("), \"\", "); result.append(wrap(buf.toString())); result.append(")"); return result.toString(); } private String wrap(String formula) { if (intToEnum.containsKey(id)) { return "HLOOKUP(" + buf + "," + intToEnum.get(id) + ",2,FALSE)"; } else { return formula; } } @Override public Void visit(ArrayAccessExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to formula"); } @Override public Void visit(ArrayExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to formula"); } @Override public Void visit(ArrayUpdateExpr e) { throw new IllegalArgumentException("Arrays must be flattened before translation to formula"); } @Override public Void visit(FunctionCallExpr e) { throw new IllegalArgumentException("Functions are not supported"); } @Override public Void visit(BinaryExpr e) { switch (e.op) { case ARROW: if (column > INITIAL_COLUMN) { e.right.accept(this); } else { e.left.accept(this); } return null; case OR: case AND: buf.append(e.op.toString().toUpperCase()); buf.append("("); e.left.accept(this); buf.append(","); e.right.accept(this); buf.append(")"); return null; case XOR: buf.append("("); e.left.accept(this); buf.append("<>"); e.right.accept(this); buf.append(")"); return null; case INT_DIVIDE: buf.append("INT("); e.left.accept(this); buf.append("/"); e.right.accept(this); buf.append(")"); return null; case MODULUS: buf.append("MOD("); e.left.accept(this); buf.append(","); e.right.accept(this); buf.append(")"); return null; case IMPLIES: buf.append("OR(NOT("); e.left.accept(this); buf.append("),"); e.right.accept(this); buf.append(")"); return null; default: buf.append("("); e.left.accept(this); buf.append(e.op); e.right.accept(this); buf.append(")"); return null; } } @Override public Void visit(BoolExpr e) { buf.append(e.value ? "TRUE" : "FALSE"); return null; } @Override public Void visit(CastExpr e) { if (e.type == NamedType.REAL) { e.expr.accept(this); } else if (e.type == NamedType.INT) { buf.append("FLOOR("); e.expr.accept(this); buf.append(",1)"); } else { throw new IllegalArgumentException(); } return null; } @Override public Void visit(CondactExpr e) { throw new IllegalArgumentException("Condacts must be removed before translation to formula"); } @Override public Void visit(IdExpr e) { int row = rowAssignments.get(e.id); String cell = CellReferenceHelper.getCellReference(column, row); if (enumToInt.containsKey(e.id)) { buf.append("HLOOKUP(" + cell + "," + enumToInt.get(e.id) + ",2,FALSE)"); } else { buf.append(cell); } refs.add(cell); return null; } @Override public Void visit(IfThenElseExpr e) { buf.append("IF("); e.cond.accept(this); buf.append(","); e.thenExpr.accept(this); buf.append(","); e.elseExpr.accept(this); buf.append(")"); return null; } @Override public Void visit(IntExpr e) { buf.append(e.value); return null; } @Override public Void visit(NodeCallExpr e) { throw new IllegalArgumentException("Node calls must be inlined before translation to formula"); } @Override public Void visit(RealExpr e) { buf.append(e.value.toPlainString()); return null; } @Override public Void visit(RecordAccessExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to formula"); } @Override public Void visit(RecordExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to formula"); } @Override public Void visit(RecordUpdateExpr e) { throw new IllegalArgumentException("Records must be flattened before translation to formula"); } @Override public Void visit(TupleExpr e) { throw new IllegalArgumentException("Tuples must be flattened before translation to formula"); } @Override public Void visit(UnaryExpr e) { switch (e.op) { case PRE: if (column == INITIAL_COLUMN) { // Create an error value for pre in initial step buf.append("(0+\"\")"); return null; } buf.append("("); column--; e.expr.accept(this); column++; buf.append(")"); return null; case NEGATIVE: buf.append("(-"); e.expr.accept(this); buf.append(")"); return null; case NOT: buf.append("NOT("); e.expr.accept(this); buf.append(")"); return null; default: throw new IllegalArgumentException("Unknown unary operator"); } } }
6,539
21.551724
97
java
jkind
jkind-master/jkind/src/jkind/translation/InlineConstants.java
package jkind.translation; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Constant; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Program; import jkind.lustre.visitors.AstMapVisitor; public class InlineConstants extends AstMapVisitor { public static Program program(Program program) { return new InlineConstants().visit(program); } private final Map<String, Expr> constants = new HashMap<>(); @Override protected List<Constant> visitConstants(List<Constant> es) { for (Constant e : es) { constants.put(e.id, e.expr); } return Collections.emptyList(); } @Override public Expr visit(IdExpr e) { if (constants.containsKey(e.id)) { return constants.get(e.id).accept(this); } else { return e; } } }
835
20.435897
61
java
jkind
jkind-master/jkind/src/jkind/translation/InlineSimpleEquations.java
package jkind.translation; import java.util.Map; import jkind.lustre.BoolExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.Node; import jkind.lustre.RealExpr; public class InlineSimpleEquations { public static Node node(Node node) { return new SubstitutionVisitor(getInliningMap(node)).visit(node); } private static Map<String, Expr> getInliningMap(Node node) { ResolvingSubstitutionMap map = new ResolvingSubstitutionMap(); for (Equation eq : node.equations) { String id = eq.lhs.get(0).id; if (isSimple(eq.expr) && !node.ivc.contains(id)) { map.put(id, eq.expr); } } return map; } private static boolean isSimple(Expr e) { return isConstant(e) || e instanceof IdExpr; } private static boolean isConstant(Expr e) { return e instanceof BoolExpr || e instanceof IntExpr || e instanceof RealExpr; } }
929
24.135135
80
java