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/translation/compound/FlattenCompoundExpressions.java
package jkind.translation.compound; import java.util.ArrayDeque; import java.util.Deque; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.Program; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.visitors.AstMapVisitor; /** * Flatten array and record expressions to scalars variables * * Assumption: All node calls have been inlined. * * Assumption: All array indices are integer literals * * Assumption: All array updates are removed */ public class FlattenCompoundExpressions extends AstMapVisitor { public static Program program(Program program) { return new FlattenCompoundExpressions().visit(program); } private final Deque<Access> accesses = new ArrayDeque<>(); @Override public Expr visit(ArrayAccessExpr e) { IntExpr intExpr = (IntExpr) e.index; accesses.push(new ArrayAccess(intExpr.value)); Expr result = e.array.accept(this); accesses.pop(); return result; } @Override public Expr visit(ArrayExpr e) { if (accesses.isEmpty()) { return super.visit(e); } else { ArrayAccess arrayAccess = (ArrayAccess) accesses.pop(); Expr result = e.elements.get(arrayAccess.index.intValue()).accept(this); accesses.push(arrayAccess); return result; } } @Override public Expr visit(RecordAccessExpr e) { accesses.push(new RecordAccess(e.field)); Expr result = e.record.accept(this); accesses.pop(); return result; } @Override public Expr visit(RecordExpr e) { if (accesses.isEmpty()) { return super.visit(e); } else { RecordAccess recordAccess = (RecordAccess) accesses.pop(); Expr result = e.fields.get(recordAccess.field).accept(this); accesses.push(recordAccess); return result; } } @Override public Expr visit(IdExpr e) { if (!accesses.isEmpty()) { throw new IllegalArgumentException(); } return e; } @Override public Expr visit(IfThenElseExpr e) { Expr cond = e.cond.accept(new FlattenCompoundExpressions()); Expr thenExpr = e.thenExpr.accept(this); Expr elseExpr = e.elseExpr.accept(this); return new IfThenElseExpr(cond, thenExpr, elseExpr); } }
2,266
24.188889
75
java
jkind
jkind-master/jkind/src/jkind/translation/compound/FlattenCompoundFunctionInputs.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.FunctionCallExpr; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstMapVisitor; import jkind.util.Util; /** * Flatten array and record outputs of functions */ public class FlattenCompoundFunctionInputs extends AstMapVisitor { public static Program program(Program program) { return new FlattenCompoundFunctionInputs().visit(program); } private final Map<String, Function> originalFunctionTable = new HashMap<>(); @Override public Program visit(Program program) { originalFunctionTable.putAll(Util.getFunctionTable(program.functions)); return super.visit(program); } @Override protected List<Function> visitFunctions(List<Function> functions) { List<Function> result = new ArrayList<>(); for (Function fn : functions) { List<VarDecl> inputs = CompoundUtil.flattenVarDecls(fn.inputs); result.add(new Function(fn.id, inputs, fn.outputs)); } return result; } @Override public Expr visit(FunctionCallExpr e) { Function fn = originalFunctionTable.get(e.function); List<Expr> args = visitExprs(e.args); List<Expr> flatArgs = new ArrayList<>(); for (int i = 0; i < args.size(); i++) { flatArgs.addAll(flattenExpr(args.get(i), fn.inputs.get(i).type)); } return new FunctionCallExpr(e.function, flatArgs); } private List<Expr> flattenExpr(Expr expr, Type type) { List<Expr> result = new ArrayList<>(); for (ExprType et : CompoundUtil.flattenExpr(expr, type)) { result.add(et.expr); } return result; } }
1,739
27.52459
77
java
jkind
jkind-master/jkind/src/jkind/translation/compound/CompoundUtil.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayType; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordType; import jkind.lustre.Type; import jkind.lustre.VarDecl; public class CompoundUtil { public static List<ExprType> flattenExpr(Expr expr, Type type) { if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; return flattenArrayExpr(expr, arrayType.base, arrayType.size); } else if (type instanceof RecordType) { RecordType recordType = (RecordType) type; return flattenRecordExpr(expr, recordType.fields); } else { return Collections.singletonList(new ExprType(expr, type)); } } private static List<ExprType> flattenArrayExpr(Expr expr, Type base, int size) { List<ExprType> result = new ArrayList<>(); for (int i = 0; i < size; i++) { result.addAll(flattenExpr(new ArrayAccessExpr(expr, i), base)); } return result; } private static List<ExprType> flattenRecordExpr(Expr expr, Map<String, Type> fields) { List<ExprType> result = new ArrayList<>(); for (Entry<String, Type> entry : fields.entrySet()) { result.addAll(flattenExpr(new RecordAccessExpr(expr, entry.getKey()), entry.getValue())); } return result; } public static List<VarDecl> flattenVarDecls(List<VarDecl> varDecls) { List<VarDecl> result = new ArrayList<>(); for (VarDecl varDecl : varDecls) { IdExpr id = new IdExpr(varDecl.id); for (ExprType et : flattenExpr(id, varDecl.type)) { result.add(new VarDecl(et.expr.toString(), et.type)); } } return result; } public static List<Expr> mapExprs(List<ExprType> ets) { List<Expr> result = new ArrayList<>(); for (ExprType et : ets) { result.add(et.expr); } return result; } public static List<Expr> mapBinary(BinaryOp op, List<Expr> exprs1, List<Expr> exprs2) { List<Expr> result = new ArrayList<>(); for (int i = 0; i < exprs1.size(); i++) { result.add(new BinaryExpr(exprs1.get(i), op, exprs2.get(i))); } return result; } }
2,277
28.973684
92
java
jkind
jkind-master/jkind/src/jkind/translation/compound/RemoveArrayUpdates.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.List; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.Expr; import jkind.lustre.IntExpr; import jkind.lustre.Program; import jkind.lustre.visitors.TypeAwareAstMapVisitor; /** * Replace all non-constant array indices using if-then-else expressions. Remove * all array updates entirely. * * Assumption: All node calls have been inlined. */ public class RemoveArrayUpdates extends TypeAwareAstMapVisitor { public static Program program(Program program) { return new RemoveArrayUpdates().visit(program); } @Override public Expr visit(ArrayUpdateExpr e) { Expr array = e.array.accept(this); IntExpr indexExpr = (IntExpr) e.index; Expr value = e.value.accept(this); ArrayType at = (ArrayType) getType(array); int index = indexExpr.value.intValue(); List<Expr> elements = new ArrayList<>(); for (int i = 0; i < at.size; i++) { if (i == index) { elements.add(value); } else { elements.add(new ArrayAccessExpr(array, i)); } } return new ArrayExpr(elements); } }
1,195
25.577778
80
java
jkind
jkind-master/jkind/src/jkind/translation/compound/RecordAccess.java
package jkind.translation.compound; public class RecordAccess implements Access { public final String field; public RecordAccess(String field) { this.field = field; } @Override public String toString() { return "." + field; } }
241
15.133333
45
java
jkind
jkind-master/jkind/src/jkind/translation/compound/FlattenCompoundVariables.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayType; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordType; import jkind.lustre.Type; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.AstMapVisitor; import jkind.translation.SubstitutionVisitor; import jkind.util.Util; /** * Flatten array and record variables to scalars variables * * Assumption: All node calls have been inlined. * * Assumption: All array indices are integer literals */ public class FlattenCompoundVariables extends AstMapVisitor { public static Program program(Program program) { return new FlattenCompoundVariables().visit(program); } private final Map<String, Type> originalTypes = new HashMap<>(); @Override public Node visit(Node node) { addOriginalTypes(node.inputs); addOriginalTypes(node.outputs); addOriginalTypes(node.locals); NodeBuilder builder = new NodeBuilder(node); builder.clearInputs().addInputs(CompoundUtil.flattenVarDecls(node.inputs)); builder.clearOutputs().addOutputs(CompoundUtil.flattenVarDecls(node.outputs)); builder.clearLocals().addLocals(CompoundUtil.flattenVarDecls(node.locals)); builder.clearEquations().addEquations(flattenLeftHandSide(node.equations)); if (node.realizabilityInputs != null) { builder.setRealizabilityInputs(flattenNames(node.realizabilityInputs)); } builder.clearIvc().addIvcs(flattenNames(node.ivc)); Map<String, Expr> map = createExpandedVariables(Util.getVarDecls(node)); return new SubstitutionVisitor(map).visit(builder.build()); } private void addOriginalTypes(List<VarDecl> varDecls) { for (VarDecl varDecl : varDecls) { originalTypes.put(varDecl.id, varDecl.type); } } private List<String> flattenNames(List<String> names) { List<String> result = new ArrayList<>(); for (String name : names) { IdExpr id = new IdExpr(name); for (ExprType et : CompoundUtil.flattenExpr(id, originalTypes.get(name))) { result.add(et.expr.toString()); } } return result; } private List<Equation> flattenLeftHandSide(List<Equation> equations) { List<Equation> result = new ArrayList<>(); for (Equation eq : equations) { IdExpr lhs = eq.lhs.get(0); Type type = originalTypes.get(lhs.id); result.addAll(flattenLeftHandSide(lhs, eq.expr, type)); } return result; } private static List<Equation> flattenLeftHandSide(Expr lhs, Expr rhs, Type type) { List<Equation> result = new ArrayList<>(); if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; for (int i = 0; i < arrayType.size; i++) { Expr accessLhs = new ArrayAccessExpr(lhs, i); Expr accessRhs = new ArrayAccessExpr(rhs, i); result.addAll(flattenLeftHandSide(accessLhs, accessRhs, arrayType.base)); } } else if (type instanceof RecordType) { RecordType recordType = (RecordType) type; for (Entry<String, Type> entry : recordType.fields.entrySet()) { Expr accessLhs = new RecordAccessExpr(lhs, entry.getKey()); Expr accessRhs = new RecordAccessExpr(rhs, entry.getKey()); result.addAll(flattenLeftHandSide(accessLhs, accessRhs, entry.getValue())); } } else { result.add(new Equation(new IdExpr(lhs.toString()), rhs)); } return result; } private Map<String, Expr> createExpandedVariables(List<VarDecl> varDecls) { Map<String, Expr> map = new HashMap<>(); for (VarDecl varDecl : varDecls) { IdExpr expr = new IdExpr(varDecl.id); Type type = originalTypes.get(varDecl.id); map.put(varDecl.id, expand(expr, type)); } return map; } private Expr expand(Expr expr, Type type) { return new Expander() { @Override protected Expr baseCase(Expr expr) { return new IdExpr(expr.toString()); } }.expand(expr, type); } }
4,072
31.070866
83
java
jkind
jkind-master/jkind/src/jkind/translation/compound/Expander.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.Expr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.Type; /** * This utility expands an expression with a complex type to corresponding * complex literals with explicit accesses. */ public abstract class Expander { public Expr expand(Expr expr, Type type) { if (type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; List<Expr> elements = new ArrayList<>(); for (int i = 0; i < arrayType.size; i++) { elements.add(expand(new ArrayAccessExpr(expr, i), arrayType.base)); } return new ArrayExpr(elements); } else if (type instanceof RecordType) { RecordType recordType = (RecordType) type; Map<String, Expr> fields = new HashMap<>(); for (Entry<String, Type> entry : recordType.fields.entrySet()) { String field = entry.getKey(); Type fieldType = entry.getValue(); fields.put(field, expand(new RecordAccessExpr(expr, field), fieldType)); } return new RecordExpr(recordType.id, fields); } else { return baseCase(expr); } } abstract protected Expr baseCase(Expr expr); }
1,404
29.543478
76
java
jkind
jkind-master/jkind/src/jkind/translation/compound/FlattenCompoundTypes.java
package jkind.translation.compound; import jkind.lustre.Program; import jkind.translation.tuples.FlattenTuples; /** * Flatten arrays and records to scalars * * Assumption: All node calls have been inlined. */ public class FlattenCompoundTypes { public static Program program(Program program) { program = RemoveNonConstantArrayIndices.program(program); program = RemoveArrayUpdates.program(program); program = RemoveRecordUpdates.program(program); program = FlattenCompoundFunctionOutputs.program(program); program = FlattenCompoundFunctionInputs.program(program); program = FlattenTuples.program(program); program = FlattenCompoundComparisons.program(program); program = FlattenCompoundVariables.program(program); program = FlattenCompoundExpressions.program(program); return program; } }
818
31.76
60
java
jkind
jkind-master/jkind/src/jkind/translation/compound/ArrayAccess.java
package jkind.translation.compound; import java.math.BigInteger; public class ArrayAccess implements Access { public final BigInteger index; public ArrayAccess(BigInteger index) { this.index = index; } @Override public String toString() { return "[" + index + "]"; } }
283
15.705882
44
java
jkind
jkind-master/jkind/src/jkind/translation/compound/ExprType.java
package jkind.translation.compound; import jkind.lustre.Expr; import jkind.lustre.Type; public class ExprType { public final Expr expr; public final Type type; public ExprType(Expr expr, Type type) { this.expr = expr; this.type = type; } }
251
15.8
40
java
jkind
jkind-master/jkind/src/jkind/translation/compound/Access.java
package jkind.translation.compound; public interface Access { }
66
10.166667
35
java
jkind
jkind-master/jkind/src/jkind/translation/compound/RemoveRecordUpdates.java
package jkind.translation.compound; import java.util.HashMap; import java.util.Map; import jkind.lustre.Expr; import jkind.lustre.Program; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordType; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.visitors.TypeAwareAstMapVisitor; /** * Removes all record updates via expansion to full record expressions. * * <code> * type record_type = struct { a : int; b : int; c : bool }; * expr1 {a := expr2} * * ===> * * record_type {a = expr2; b = expr1.b; c = expr1.c}; * </code> * * Assumptions: Nodes are already inlined. * * Guarantees: All record update expressions are removed */ public class RemoveRecordUpdates extends TypeAwareAstMapVisitor { public static Program program(Program program) { return new RemoveRecordUpdates().visit(program); } @Override public Expr visit(RecordUpdateExpr e) { Expr record = e.record.accept(this); Expr value = e.value.accept(this); RecordType rt = (RecordType) getType(record); Map<String, Expr> fields = new HashMap<>(); for (String key : rt.fields.keySet()) { if (key.equals(e.field)) { fields.put(key, value); } else { fields.put(key, new RecordAccessExpr(record, key)); } } return new RecordExpr(rt.id, fields); } }
1,325
24.018868
71
java
jkind
jkind-master/jkind/src/jkind/translation/compound/FlattenCompoundFunctionOutputs.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Expr; import jkind.lustre.Function; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.Program; import jkind.lustre.TupleExpr; import jkind.lustre.Type; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstMapVisitor; import jkind.util.Util; /** * Flatten array and record outputs of functions */ public class FlattenCompoundFunctionOutputs extends AstMapVisitor { public static Program program(Program program) { return new FlattenCompoundFunctionOutputs().visit(program); } private final Map<String, Function> originalFunctionTable = new HashMap<>(); @Override public Program visit(Program program) { originalFunctionTable.putAll(Util.getFunctionTable(program.functions)); return super.visit(program); } @Override protected List<Function> visitFunctions(List<Function> functions) { List<Function> result = new ArrayList<>(); for (Function fn : functions) { result.addAll(visitFunction(fn)); } return result; } private List<Function> visitFunction(Function fn) { List<Function> result = new ArrayList<>(); for (VarDecl output : fn.outputs) { Expr originalFnId = new IdExpr(output.id); for (ExprType et : CompoundUtil.flattenExpr(originalFnId, output.type)) { String newOutputId = et.expr.toString(); String newFnId = fn.id + "." + newOutputId; result.add(new Function(newFnId, fn.inputs, new VarDecl(newOutputId, et.type))); } } return result; } @Override public Expr visit(FunctionCallExpr e) { Function fn = originalFunctionTable.get(e.function); List<Expr> args = visitExprs(e.args); List<Expr> exprs = new ArrayList<>(); for (VarDecl output : fn.outputs) { exprs.add(expand(new IdExpr(fn.id + "." + output.id), output.type, args)); } return TupleExpr.compress(exprs); } private static Expr expand(Expr expr, Type type, List<Expr> args) { return new Expander() { @Override protected Expr baseCase(Expr expr) { return new FunctionCallExpr(expr.toString(), args); } }.expand(expr, type); } }
2,197
27.545455
84
java
jkind
jkind-master/jkind/src/jkind/translation/compound/RemoveNonConstantArrayIndices.java
package jkind.translation.compound; import java.util.ArrayList; import java.util.List; import jkind.analysis.ConstantAnalyzer; import jkind.analysis.evaluation.ConstantEvaluator; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayType; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.Program; import jkind.lustre.values.IntegerValue; import jkind.lustre.visitors.TypeAwareAstMapVisitor; /** * Replace all non-constant array indices using if-then-else expressions. * Constant array indices are evaluated to be integer literal. * * Assumption: All node calls have been inlined. */ public class RemoveNonConstantArrayIndices extends TypeAwareAstMapVisitor { public static Program program(Program program) { return new RemoveNonConstantArrayIndices().visit(program); } private boolean isConstant(Expr e) { return e.accept(new ConstantAnalyzer()); } private IntExpr evalIndex(Expr e) { IntegerValue value = new ConstantEvaluator().evalInt(e); return new IntExpr(value.value); } @Override public Expr visit(ArrayAccessExpr e) { Expr array = e.array.accept(this); Expr index = e.index.accept(this); if (isConstant(index)) { return new ArrayAccessExpr(array, evalIndex(index)); } else { return expandArrayAccess(array, index); } } private Expr expandArrayAccess(Expr array, Expr index) { ArrayType arrayType = (ArrayType) getType(array); Expr result = new ArrayAccessExpr(array, arrayType.size - 1); for (int i = arrayType.size - 1; i >= 0; i--) { Expr cond = new BinaryExpr(index, BinaryOp.EQUAL, new IntExpr(i)); Expr thenExpr = new ArrayAccessExpr(array, i); result = new IfThenElseExpr(cond, thenExpr, result); } return result; } @Override public Expr visit(ArrayUpdateExpr e) { Expr array = e.array.accept(this); Expr index = e.index.accept(this); Expr value = e.value.accept(this); if (isConstant(index)) { return new ArrayUpdateExpr(array, evalIndex(index), value); } else { return expandNonConstantArrayUpdate(array, index, value); } } private Expr expandNonConstantArrayUpdate(Expr array, Expr index, Expr value) { ArrayType arrayType = (ArrayType) getType(array); List<Expr> elements = new ArrayList<>(); for (int i = 0; i < arrayType.size; i++) { Expr cond = new BinaryExpr(index, BinaryOp.EQUAL, new IntExpr(i)); Expr elseExpr = new ArrayAccessExpr(array, i); elements.add(new IfThenElseExpr(cond, value, elseExpr)); } return new ArrayExpr(elements); } }
2,674
30.104651
80
java
jkind
jkind-master/jkind/src/jkind/translation/compound/FlattenCompoundComparisons.java
package jkind.translation.compound; import static jkind.lustre.LustreUtil.not; import java.util.List; import jkind.lustre.ArrayType; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.LustreUtil; import jkind.lustre.Program; import jkind.lustre.RecordType; import jkind.lustre.TupleType; import jkind.lustre.Type; import jkind.lustre.visitors.TypeAwareAstMapVisitor; /** * Expand equalities and inequalities on records and arrays */ public class FlattenCompoundComparisons extends TypeAwareAstMapVisitor { public static Program program(Program program) { return new FlattenCompoundComparisons().visit(program); } @Override public Expr visit(BinaryExpr e) { Expr left = e.left.accept(this); Expr right = e.right.accept(this); if (e.op == BinaryOp.EQUAL || e.op == BinaryOp.NOTEQUAL) { Type type = getType(e.left); if (type instanceof ArrayType || type instanceof RecordType || type instanceof TupleType) { List<ExprType> leftExprTypes = CompoundUtil.flattenExpr(left, type); List<ExprType> rightExprTypes = CompoundUtil.flattenExpr(right, type); List<Expr> leftExprs = CompoundUtil.mapExprs(leftExprTypes); List<Expr> rightExprs = CompoundUtil.mapExprs(rightExprTypes); List<Expr> exprs = CompoundUtil.mapBinary(BinaryOp.EQUAL, leftExprs, rightExprs); Expr equal = LustreUtil.and(exprs); if (e.op == BinaryOp.EQUAL) { return equal; } else { return not(equal); } } } return new BinaryExpr(e.location, left, e.op, right); } }
1,562
29.057692
94
java
jkind
jkind-master/jkind/src/jkind/translation/tuples/FlattenTupleComparisons.java
package jkind.translation.tuples; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.LustreUtil; import jkind.lustre.Program; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.visitors.AstMapVisitor; /** * Expand equalities and inequalities on tuples * * Assumption: All tuple expressions have been lifted as far as possible. */ public class FlattenTupleComparisons extends AstMapVisitor { public static Program program(Program program) { return new FlattenTupleComparisons().visit(program); } @Override public Expr visit(BinaryExpr e) { if (isTupleComparison(e)) { TupleExpr left = (TupleExpr) e.left.accept(this); TupleExpr right = (TupleExpr) e.right.accept(this); TupleExpr tuple = TupleUtil.mapBinary(BinaryOp.EQUAL, left, right); Expr equal = LustreUtil.and(tuple.elements); if (e.op == BinaryOp.EQUAL) { return equal; } else { return new UnaryExpr(UnaryOp.NOT, equal); } } else { return super.visit(e); } } private boolean isTupleComparison(BinaryExpr e) { // We assume tuples are lifted, so just check the top level of e.left return (e.op == BinaryOp.EQUAL || e.op == BinaryOp.NOTEQUAL) && e.left instanceof TupleExpr; } }
1,309
28.111111
94
java
jkind
jkind-master/jkind/src/jkind/translation/tuples/LiftTuples.java
package jkind.translation.tuples; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.Program; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.visitors.AstMapVisitor; /** * Lift all tuples as far as possible */ public class LiftTuples extends AstMapVisitor { public static Program program(Program program) { return new LiftTuples().visit(program); } @Override public Expr visit(BinaryExpr e) { Expr left = e.left.accept(this); Expr right = e.right.accept(this); if (left instanceof TupleExpr && e.op == BinaryOp.ARROW) { return TupleUtil.mapBinary(e.op, (TupleExpr) left, (TupleExpr) right); } else { return new BinaryExpr(left, e.op, right); } } @Override public Expr visit(IfThenElseExpr e) { Expr cond = e.cond.accept(this); Expr thenExpr = e.thenExpr.accept(this); Expr elseExpr = e.elseExpr.accept(this); if (thenExpr instanceof TupleExpr) { return TupleUtil.mapIf(cond, (TupleExpr) thenExpr, (TupleExpr) elseExpr); } else { return new IfThenElseExpr(cond, thenExpr, elseExpr); } } @Override public Expr visit(UnaryExpr e) { Expr expr = e.expr.accept(this); if (expr instanceof TupleExpr) { return TupleUtil.mapUnary(e.op, (TupleExpr) expr); } else { return new UnaryExpr(e.op, expr); } } }
1,390
25.245283
76
java
jkind
jkind-master/jkind/src/jkind/translation/tuples/FlattenTuples.java
package jkind.translation.tuples; import jkind.lustre.Program; /** * Flatten all tuple expressions via expansion. * * Assumption: All node calls have been inlined. */ public class FlattenTuples { public static Program program(Program program) { program = LiftTuples.program(program); program = FlattenTupleComparisons.program(program); program = FlattenTupleAssignments.program(program); return program; } }
425
22.666667
53
java
jkind
jkind-master/jkind/src/jkind/translation/tuples/TupleUtil.java
package jkind.translation.tuples; import java.util.ArrayList; import java.util.List; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.translation.compound.CompoundUtil; public class TupleUtil { public static TupleExpr mapBinary(BinaryOp op, TupleExpr expr1, TupleExpr expr2) { return new TupleExpr(CompoundUtil.mapBinary(op, expr1.elements, expr2.elements)); } public static TupleExpr mapIf(Expr cond, TupleExpr expr1, TupleExpr expr2) { return new TupleExpr(mapIf(cond, expr1.elements, expr2.elements)); } private static List<Expr> mapIf(Expr cond, List<Expr> exprs1, List<Expr> exprs2) { List<Expr> result = new ArrayList<>(); for (int i = 0; i < exprs1.size(); i++) { result.add(new IfThenElseExpr(cond, exprs1.get(i), exprs2.get(i))); } return result; } public static TupleExpr mapUnary(UnaryOp op, TupleExpr expr) { return new TupleExpr(mapUnary(op, expr.elements)); } public static List<Expr> mapUnary(UnaryOp op, List<Expr> exprs) { List<Expr> result = new ArrayList<>(); for (int i = 0; i < exprs.size(); i++) { result.add(new UnaryExpr(op, exprs.get(i))); } return result; } }
1,278
28.744186
83
java
jkind
jkind-master/jkind/src/jkind/translation/tuples/FlattenTupleAssignments.java
package jkind.translation.tuples; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jkind.lustre.Equation; import jkind.lustre.Program; import jkind.lustre.TupleExpr; import jkind.lustre.visitors.AstMapVisitor; /** * Expand tuple assignments into single value assignments * * Assumption: All tuple expressions have been lifted as far as possible. */ public class FlattenTupleAssignments extends AstMapVisitor { public static Program program(Program program) { return new FlattenTupleAssignments().visit(program); } @Override protected List<Equation> visitEquations(List<Equation> es) { List<Equation> results = new ArrayList<>(); for (Equation e : es) { results.addAll(visitEquation(e)); } return results; } private List<Equation> visitEquation(Equation eq) { if (eq.lhs.size() == 1) { return Collections.singletonList(eq); } List<Equation> results = new ArrayList<>(); TupleExpr tuple = (TupleExpr) eq.expr; for (int i = 0; i < eq.lhs.size(); i++) { results.add(new Equation(eq.lhs.get(i), tuple.elements.get(i))); } return results; } }
1,127
24.636364
73
java
gluon
gluon-master/src/main/java/gluon/Main.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import soot.*; import soot.jimple.spark.SparkTransformer; import soot.options.Options; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { private static final String PROGNAME="gluon"; private static String classPath=null; private static String mainClassName=null; private static String moduleClassName=null; private static String contract=null; public static boolean WITH_JAVA_LIB=false; public static boolean TIME=false; public static boolean PROFILING_VARS=false; public static boolean CLASS_SCOPE=false; public static boolean ATOMICITY_SYNCH=false; public static boolean CONSERVATIVE_POINTS_TO=false; public static int TIMEOUT=0; /* timeout in seconds */ private static final String DEFAULT_PATH_CONTRACTS = "default_contract.txt"; public static void fatal(String error) { System.err.println(PROGNAME+": "+error); System.err.flush(); System.exit(-1); } public static void warning(String warning) { System.err.println(PROGNAME+": "+warning); } private static void help() { System.out.println("Usage: "+PROGNAME+" OPTIONS <main_class>"); System.out.println(); System.out.println("Options:"); System.out.println(" -m, --module <module> " +"Module to verify"); System.out.println(" -c, --classpath <class_path> " +"Java classpath"); System.out.println(" -j, --with-java-lib " +"Do not refrain from analyzing java library code"); System.out.println(" -t, --time " +"Output information about several run times"); System.out.println(" -p, --prof-vars " +"Output profiling variables"); System.out.println(" -o, --contract <contract> " +"Module's contract (overrides annotation)"); System.out.println(" -s, --class-scope " +"Restrict analysis to each class"); System.out.println(" -y, --synch " +"Atomicity is based on java synchronized"); System.out.println(" -r, --conservative-points-to " +"Conservative points-to analysis."); System.out.println(" " +"Use when there are classes loaded dynamically,"); System.out.println(" " +"which makes the regular points-to analysis"); System.out.println(" " +"incomplete"); System.out.println(" -i, --timeout " +"Timeout in mins for class scope analysis."); System.out.println(" -d, --default-contract " +"Uses the default contract with common dependencies"); System.out.println(" -h, --help " +"Display this help and exit"); } private static void parseArguments(String[] args) { LongOpt[] options=new LongOpt[12]; Getopt g; int c; options[0]=new LongOpt("help",LongOpt.NO_ARGUMENT,null,'h'); options[1]=new LongOpt("classpath",LongOpt.REQUIRED_ARGUMENT,null,'c'); options[2]=new LongOpt("module",LongOpt.REQUIRED_ARGUMENT,null,'m'); options[3]=new LongOpt("with-java-lib",LongOpt.NO_ARGUMENT, null,'j'); options[4]=new LongOpt("time",LongOpt.NO_ARGUMENT,null,'t'); options[5]=new LongOpt("prof-vars",LongOpt.NO_ARGUMENT,null,'p'); options[6]=new LongOpt("contract",LongOpt.REQUIRED_ARGUMENT, null,'o'); options[7]=new LongOpt("class-scope",LongOpt.NO_ARGUMENT,null,'s'); options[8]=new LongOpt("synch",LongOpt.NO_ARGUMENT,null,'y'); options[9]=new LongOpt("conservative-points-to",LongOpt.NO_ARGUMENT, null,'r'); options[10]=new LongOpt("default-contract",LongOpt.NO_ARGUMENT,null,'d'); options[11]=new LongOpt("timeout",LongOpt.REQUIRED_ARGUMENT,null,'i'); g=new Getopt(PROGNAME,args,"hc:m:o:jtpsyri",options); g.setOpterr(true); while ((c = g.getopt()) != -1) switch (c) { case 'h': { help(); System.exit(0); break; } case 'c': { classPath=g.getOptarg(); break; } case 'm': { moduleClassName=g.getOptarg(); break; } case 'j': { WITH_JAVA_LIB=true; break; } case 't': { TIME=true; break; } case 'p': { PROFILING_VARS=true; break; } case 'o': { contract=g.getOptarg(); break; } case 'd': { File savedContractFile = new File(DEFAULT_PATH_CONTRACTS); if(savedContractFile.isFile()) { try { FileReader reader = new FileReader(DEFAULT_PATH_CONTRACTS); Scanner in = new Scanner(reader); StringBuilder sb = new StringBuilder(); String line; while(in.hasNextLine()) { line = in.nextLine(); sb.append(line); } contract = sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { fatal("The file of the default contract does not exist"); } break; } case 's': { CLASS_SCOPE=true; break; } case 'y': { ATOMICITY_SYNCH=true; break; } case 'r': { CONSERVATIVE_POINTS_TO=true; break; } case 'i': { String timeout=null; try { timeout=g.getOptarg(); TIMEOUT=Integer.parseInt(timeout)*60; } catch (NumberFormatException e) { fatal(timeout+": invalid format"); } break; } case '?': { /* getopt already printed an error */ System.exit(-1); break; } } if (CONSERVATIVE_POINTS_TO && !CLASS_SCOPE) fatal("conservative points-to only makes sense with class scope analysis"); if (TIMEOUT < 0) fatal("negative timeout"); if (g.getOptind() != args.length-1) fatal("there must be one main class specified"); mainClassName=args[g.getOptind()]; } private static Map<String,String> getSparkOptions() { Map<String,String> opt = new HashMap<String,String>(); opt.put("verbose","false"); opt.put("propagator","worklist"); opt.put("simple-edges-bidirectional","false"); opt.put("on-fly-cg","true"); opt.put("set-impl","double"); opt.put("double-set-old","hybrid"); opt.put("double-set-new","hybrid"); return opt; } private static String fullClasspath() { StringBuilder cp = new StringBuilder(); String javaHome = System.getProperty("java.home"); Collection<File> jarFiles = FileUtils.listFiles( new File(javaHome), new RegexFileFilter("^.*\\.jar$"), DirectoryFileFilter.DIRECTORY ); for (File jarFile: jarFiles) { cp.append(jarFile.getAbsolutePath()).append(File.pathSeparator); } cp.append(classPath); return cp.toString(); } private static void run() throws IOException { Transform t; gluon.profiling.Timer.start("soot-init"); Options.v().set_output_dir(Files.createTempDirectory("gluon").toString()); Options.v().set_whole_program(true); Options.v().set_whole_shimple(true); Options.v().set_verbose(false); Options.v().set_interactive_mode(false); Options.v().set_debug(false); Options.v().set_debug_resolver(false); Options.v().set_show_exception_dests(false); Options.v().set_output_format(Options.output_format_none); Options.v().set_allow_phantom_refs(true); Options.v().set_keep_line_number(true); /* For line number information */ PhaseOptions.v().setPhaseOption("tag.ln","on"); /* Soot bug workaround */ // PhaseOptions.v().setPhaseOption("jb","use-original-names:true"); PhaseOptions.v().setPhaseOption("jb.ulp","enabled:false"); /* For points-to analysis */ PhaseOptions.v().setPhaseOption("cg.spark","enabled:true"); Scene.v().setSootClassPath(fullClasspath()); t=new Transform("wstp.gluon",AnalysisMain.instance()); AnalysisMain.instance().setModuleToAnalyze(moduleClassName); if (contract != null) AnalysisMain.instance().setContract(contract); PackManager.v().getPack("wstp").add(t); SootClass mainClass=Scene.v().loadClassAndSupport(mainClassName); Scene.v().addBasicClass(mainClassName,SootClass.SIGNATURES); Scene.v().addBasicClass(moduleClassName,SootClass.SIGNATURES); Scene.v().loadNecessaryClasses(); Scene.v().loadDynamicClasses(); try { Scene.v().setMainClass(mainClass); } catch (Exception e) { fatal("error loading main class: " + e.getMessage()); } if (CLASS_SCOPE) { for (String path: classPath.split(":")) try { Scanner sc=new Scanner(new File(path+"/LOADEXTRA")); while (sc.hasNext()) { String c=sc.next(); try { Scene.v().loadClassAndSupport(c); } catch (Exception e) {}; } } catch (Exception e) {} for (SootClass c: Scene.v().getClasses()) for (soot.SootMethod m: c.getMethods()) try { m.retrieveActiveBody(); } catch (Exception e) {} for (SootClass c: Scene.v().dynamicClasses()) for (soot.SootMethod m: c.getMethods()) try { m.retrieveActiveBody(); } catch (Exception e) {} } /* Points-to analyses */ SparkTransformer.v().transform("",getSparkOptions()); PackManager.v().runPacks(); } private static void dumpRunTimes() { System.out.println(); System.out.println("Run Time:"); for (String id: gluon.profiling.Timer.getIds()) System.out.printf(" %40s %6d.%03ds\n",id, gluon.profiling.Timer.getTime(id)/1000, gluon.profiling.Timer.getTime(id)%1000); } private static void dumpProfilingVars() { System.out.println(); System.out.println("Profiling Vars:"); for (String id: gluon.profiling.Profiling.getIds()) System.out.printf(" %40s %9d\n",id, gluon.profiling.Profiling.get(id)); } public static void main(String[] args) throws Exception { if (args.length == 0) { help(); System.exit(0); } parseArguments(args); if (classPath == null) fatal("No classpath specified!"); if (moduleClassName == null) fatal("No module specified!"); gluon.profiling.Timer.start("total"); run(); gluon.profiling.Timer.stop("total"); if (TIME) dumpRunTimes(); if (PROFILING_VARS) dumpProfilingVars(); } }
13,938
33.080685
87
java
gluon
gluon-master/src/main/java/gluon/AnalysisMain.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon; import gluon.analysis.atomicity.AtomicityAnalysis; import gluon.analysis.monitor.MonitorAnalysis; import gluon.analysis.pointsTo.PointsToInformation; import gluon.analysis.programBehavior.*; import gluon.analysis.thread.ThreadAnalysis; import gluon.analysis.valueEquivalence.ValueEquivAnalysis; import gluon.contract.Contract; import gluon.grammar.Cfg; import gluon.grammar.NonTerminal; import gluon.grammar.Terminal; import gluon.parsing.parser.Parser; import gluon.parsing.parser.ParserAbortedException; import gluon.parsing.parser.ParserCallback; import gluon.parsing.parser.ParserSubwords; import gluon.parsing.parsingTable.ParsingTable; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.jimple.spark.pag.AllocNode; import java.util.*; public class AnalysisMain extends SceneTransformer { private static final boolean DEBUG=false; private static final AnalysisMain instance=new AnalysisMain(); private Scene scene; private String moduleName; /* Name of the module to analyze */ private SootClass module; /* Class of the module to analyze */ private Contract contract; private String contractRaw; /* TODO: we should have a class called AnalysisContext */ class ParserCallbackCheckWord implements ParserCallback { private List<Terminal> word; private Set<WordInstance> verifiedWords; private AtomicityAnalysis atomicityAnalysis; private ValueEquivAnalysis vEquiv; private long startTime; private int reported; public ParserCallbackCheckWord(List<Terminal> word, Set<WordInstance> verifiedWords, AtomicityAnalysis atomicityAnalysis, ValueEquivAnalysis vEquiv, long startTime) { this.word=word; this.verifiedWords=verifiedWords; this.atomicityAnalysis=atomicityAnalysis; this.vEquiv=vEquiv; this.startTime=startTime; this.reported=0; } public int getReported() { return reported; } public boolean onLCA(List<ParsingAction> actions, NonTerminal lca) { WordInstance wordInst; int ret; gluon.profiling.Timer.start(".onLCA"); wordInst=new WordInstance((PBNonTerminal)lca,word,actions); if (verifiedWords.contains(wordInst)) { gluon.profiling.Timer.stop(".onLCA"); return false; } ret=checkWordInstance(wordInst,atomicityAnalysis,vEquiv); verifiedWords.add(wordInst); if (ret <= 0) reported++; if (ret <= 0) System.out.println(); gluon.profiling.Timer.stop(".onLCA"); return false; } public boolean shouldAbort() { long now; if (Main.TIMEOUT == 0) return false; now=System.currentTimeMillis()/1000; return now-startTime > Main.TIMEOUT; } public void accepted(List<ParsingAction> actions, NonTerminal lca) { assert false : "We should be prunning everything on LCA"; } }; private AnalysisMain() { scene=null; moduleName=null; module=null; contract=null; contractRaw=null; } private void dprint(String s) { if (DEBUG) System.out.print(s); } private void dprintln(String s) { dprint(s+"\n"); } public static AnalysisMain instance() { return instance; } public void setModuleToAnalyze(String m) { moduleName=m; } private Collection<SootMethod> getThreads() { ThreadAnalysis ta=new ThreadAnalysis(scene.getCallGraph()); Collection<SootMethod> allThreads; Collection<SootMethod> relevantThreads; ta.analyze(); allThreads=ta.getThreadsEntryMethod(); relevantThreads=new ArrayList<SootMethod>(allThreads.size()); for (SootMethod m: allThreads) if (!m.isJavaLibraryMethod()) relevantThreads.add(m); return relevantThreads; } /* Returns > 0 if the word is ignored; * = 0 if the word is atomic; * < 0 if the word is a contract violation. */ private int checkWordInstance(WordInstance wordInst, AtomicityAnalysis atomicity, ValueEquivAnalysis vEquiv) { SootMethod lcaMethod; boolean atomic; gluon.profiling.Timer.start("check-word-instance"); if (!wordInst.argumentsMatch(vEquiv)) { gluon.profiling.Profiling.inc("discarded-trees-args-not-match"); gluon.profiling.Timer.stop("check-word-instance"); return 1; } gluon.profiling.Profiling.inc("parse-trees"); atomic=atomicity.isAtomic(wordInst); dprintln(" Lowest common ancestor: "+wordInst.getLCA()); lcaMethod=wordInst.getLCAMethod(); System.out.println(" Method: "+lcaMethod.getDeclaringClass().getShortName() +"."+lcaMethod.getName()+"()"); System.out.print(" Calls Location:"); for (PBTerminal t: wordInst.getParsingTerminals()) { int linenum=t.getLineNumber(); String source=t.getSourceFile(); System.out.print(" "+source+":"+(linenum > 0 ? ""+linenum : "?")); } System.out.println(); System.out.println(" Atomic: "+(atomic ? "YES" : "NO")); gluon.profiling.Timer.stop("check-word-instance"); return atomic ? 0 : -1; } private static List<String> wordToStrings(List<Terminal> word) { List<String> strings=new ArrayList<String>(word.size()); for (int i=0; i < word.size(); i++) strings.add(word.get(i).getName()); return strings; } private void checkThreadWord(SootMethod thread, List<Terminal> word, ValueEquivAnalysis vEquiv) throws ParserAbortedException { Set<WordInstance> verifiedWords=new HashSet<WordInstance>(); long startTime=System.currentTimeMillis()/1000; Collection<AllocNode> moduleAllocSites; int reported=0; System.out.println(" Verifying clause "+WordInstance.wordStr(word)+":"); System.out.println(); moduleAllocSites=PointsToInformation.getModuleAllocationSites(module); /* Represents a static module */ moduleAllocSites.add(null); for (soot.jimple.spark.pag.AllocNode as: moduleAllocSites) { Parser parser; Cfg grammar; BehaviorAnalysis ba; AtomicityAnalysis aa; ParserCallbackCheckWord pcb; gluon.profiling.Profiling.inc("alloc-sites"); ba=new WholeProgramBehaviorAnalysis(thread,module,as,wordToStrings(word)); if (Main.ATOMICITY_SYNCH) { MonitorAnalysis monAnalysis=new MonitorAnalysis(scene); monAnalysis.analyze(); ba.setSynchMode(monAnalysis); } ba.analyze(); grammar=ba.getGrammar(); aa=new AtomicityAnalysis(grammar); aa.analyze(); parser=makeParser(grammar); dprintln("Created parser for thread "+thread.getName() +"(), allocation site "+as+"."); pcb=new ParserCallbackCheckWord(word,verifiedWords,aa,vEquiv,startTime); parser.parse(word,pcb); reported+=pcb.getReported(); } if (reported == 0) { System.out.println(" No occurrences"); System.out.println(); } } private Parser makeParser(Cfg grammar) { ParsingTable parsingTable; gluon.profiling.Profiling.inc("grammar-productions",grammar.size()); assert gluon.parsing.parser.ParserSubwords.isParsable(grammar); parsingTable=new ParsingTable(grammar); parsingTable.buildParsingTable(); gluon.profiling.Profiling.inc("parsing-table-states", parsingTable.numberOfStates()); return new ParserSubwords(parsingTable); } private void checkThread(SootMethod thread) { ValueEquivAnalysis vEquiv=new ValueEquivAnalysis(); System.out.println("Checking thread " +thread.getDeclaringClass().getShortName() +"."+thread.getName()+"():"); System.out.println(); for (List<Terminal> word: contract.getWords()) try { checkThreadWord(thread,word,vEquiv); } catch (ParserAbortedException e) { System.out.println(" *** Timeout ***"); System.out.println(); } } private SootClass getModuleClass() { assert moduleName != null; for (SootClass c: scene.getClasses()) if (c.getName().equals(moduleName)) return c; return null; } public void setContract(String contract) { contractRaw=contract; } private void checkClassWordConservativePointsTo(SootClass c, List<Terminal> word, ValueEquivAnalysis vEquiv) throws ParserAbortedException { Set<WordInstance> verifiedWords=new HashSet<WordInstance>(); long startTime=System.currentTimeMillis()/1000; Parser parser; Cfg grammar; BehaviorAnalysis ba; AtomicityAnalysis aa; ParserCallbackCheckWord pcb; System.out.println(" Verifying clause "+WordInstance.wordStr(word)+":"); System.out.println(); ba=new ClassBehaviorAnalysis(c,module,wordToStrings(word)); if (Main.ATOMICITY_SYNCH) { MonitorAnalysis monAnalysis=new MonitorAnalysis(scene); monAnalysis.analyze(); ba.setSynchMode(monAnalysis); } ba.analyze(); grammar=ba.getGrammar(); aa=new AtomicityAnalysis(grammar); aa.analyze(); parser=makeParser(grammar); pcb=new ParserCallbackCheckWord(word,verifiedWords,aa,vEquiv,startTime); parser.parse(word,pcb); if (pcb.getReported() == 0) { System.out.println(" No occurrences"); System.out.println(); } } private void checkClassWordRegularPointsTo(SootClass c, List<Terminal> word, ValueEquivAnalysis vEquiv) throws ParserAbortedException { Set<WordInstance> verifiedWords=new HashSet<WordInstance>(); long startTime=System.currentTimeMillis()/1000; Collection<AllocNode> moduleAllocSites; int reported=0; System.out.println(" Verifying clause "+WordInstance.wordStr(word)+":"); System.out.println(); moduleAllocSites=PointsToInformation.getModuleAllocationSites(module); /* Represents a static module */ moduleAllocSites.add(null); for (soot.jimple.spark.pag.AllocNode as: moduleAllocSites) { Parser parser; Cfg grammar; BehaviorAnalysis ba; AtomicityAnalysis aa; ParserCallbackCheckWord pcb; gluon.profiling.Profiling.inc("alloc-sites"); ba=new ClassBehaviorAnalysis(c,module,as,wordToStrings(word)); if (Main.ATOMICITY_SYNCH) { MonitorAnalysis monAnalysis=new MonitorAnalysis(scene); monAnalysis.analyze(); ba.setSynchMode(monAnalysis); } ba.analyze(); grammar=ba.getGrammar(); aa=new AtomicityAnalysis(grammar); aa.analyze(); parser=makeParser(grammar); dprintln("Created parser for class "+c.getName() +", allocation site "+as+"."); pcb=new ParserCallbackCheckWord(word,verifiedWords,aa,vEquiv,startTime); parser.parse(word,pcb); reported+=pcb.getReported(); } if (reported == 0) { System.out.println(" No occurrences"); System.out.println(); } } private void checkClassWord(SootClass c, List<Terminal> word, ValueEquivAnalysis vEquiv) throws ParserAbortedException { if (Main.CONSERVATIVE_POINTS_TO) checkClassWordConservativePointsTo(c,word,vEquiv); else checkClassWordRegularPointsTo(c,word,vEquiv); } private void checkClass(SootClass c) { ValueEquivAnalysis vEquiv=new ValueEquivAnalysis(); if (c.isJavaLibraryClass() && !gluon.Main.WITH_JAVA_LIB) return; if (c.getMethodCount() == 0) return; System.out.println("Checking class " +c.getShortName()+":"); System.out.println(); for (List<Terminal> word: contract.getWords()) try { checkClassWord(c,word,vEquiv); } catch (ParserAbortedException e) { System.out.println(" *** Timeout ***"); System.out.println(); } } private void runAnalysis() { Collection<SootMethod> threads; scene=Scene.v(); assert scene.getMainMethod() != null; gluon.profiling.Timer.stop("soot-init"); dprintln("Started MainAnalysis."); module=getModuleClass(); if (module == null) Main.fatal(moduleName+": module's class not found"); /* If the contract was not passed by the command line then extract it * from the module's annotation @Contract. */ if (contractRaw != null) contract=new Contract(module,contractRaw); else { contract=new Contract(module); contract.loadAnnotatedContract(); } if (contract.clauseNum() == 0) Main.fatal("empty contract"); dprintln("Loaded Contract."); threads=getThreads(); dprintln("Obtained "+threads.size()+" thread entry points."); gluon.profiling.Profiling.set("threads",threads.size()); if (Main.CLASS_SCOPE) { for (SootClass c: scene.getClasses()) if (!module.equals(c)) checkClass(c); } else { // TODO Since Java 8 the language also contains lambda functions that can be used as entrypoints for thread. // Are they also represented as a `SootMethod`? for (SootMethod m: threads) checkThread(m); } } @Override protected void internalTransform(String paramString, @SuppressWarnings("rawtypes") java.util.Map paramMap) { runAnalysis(); } }
16,290
27.381533
120
java
gluon
gluon-master/src/main/java/gluon/WordInstance.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon; import gluon.analysis.programBehavior.PBNonTerminal; import gluon.analysis.programBehavior.PBTerminal; import gluon.analysis.valueEquivalence.ValueEquivAnalysis; import gluon.analysis.valueEquivalence.ValueM; import gluon.grammar.Terminal; import gluon.parsing.parseTree.ParseTree; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import gluon.parsing.parsingTable.parsingAction.ParsingActionAccept; import gluon.parsing.parsingTable.parsingAction.ParsingActionReduce; import gluon.parsing.parsingTable.parsingAction.ParsingActionShift; import soot.SootMethod; import soot.Unit; import soot.jimple.AssignStmt; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class WordInstance { private static final boolean DEBUG=false; private PBNonTerminal lca; private List<Terminal> word; private List<ParsingAction> actions; public WordInstance(PBNonTerminal lca, List<Terminal> word, List<ParsingAction> actions) { this.lca=lca; this.word=word; this.actions=actions; } private void dprint(String s) { if (DEBUG) System.out.print(s); } private void dprintln(String s) { dprint(s+"\n"); } public SootMethod getLCAMethod() { return lca.getMethod(); } public PBNonTerminal getLCA() { return lca; } /* Memoization */ private ParseTree parseTree=null; public ParseTree getParseTree() { ParseTree tree; if (parseTree != null) return parseTree; tree=new ParseTree(word,actions); tree.buildTree(); assert lca.equals(tree.getLCA().getElem()); return tree; } /* Memoization */ private List<PBTerminal> parsingTerminals=null; public List<PBTerminal> getParsingTerminals() { ParseTree tree; List<PBTerminal> ppterms; List<Terminal> terms; if (parsingTerminals != null) return parsingTerminals; tree=getParseTree(); terms=tree.getTerminals(); ppterms=new ArrayList<PBTerminal>(terms.size()); for (Terminal t: terms) ppterms.add((PBTerminal)t); return parsingTerminals=ppterms; } public String actionsStr() { String r=""; for (ParsingAction a: actions) { if (a instanceof ParsingActionShift) r+="s ; "; else if (a instanceof ParsingActionReduce) r+=((ParsingActionReduce)a).getProduction()+" ; "; else if (a instanceof ParsingActionAccept) r+=a.toString(); } return r; } public static String wordStr(List<Terminal> word) { String r=""; for (int i=0; i < word.size(); i++) { Terminal term=word.get(i); if (term instanceof gluon.grammar.EOITerminal) break; assert term instanceof PBTerminal; r+=(i > 0 ? " " : "")+((PBTerminal)term).getFullName(); } return r; } public String wordStr() { return wordStr(word); } private int tryUnify(Map<String,ValueM> unif, String contractVar, ValueM v, ValueEquivAnalysis vEquiv) { if (contractVar == null) return 0; if (unif.containsKey(contractVar)) return vEquiv.equivTo(unif.get(contractVar),v) ? 0 : -1; unif.put(contractVar,v); return 0; } public boolean argumentsMatch(ValueEquivAnalysis vEquiv) { List<PBTerminal> parsedWord; /* contract variable -> program value */ Map<String,ValueM> unif=new HashMap<String,ValueM>(); parsedWord=getParsingTerminals(); for (int i=0; i < parsedWord.size(); i++) { PBTerminal termC=(PBTerminal)word.get(i); PBTerminal termP=parsedWord.get(i); SootMethod method=termP.getCodeMethod(); List<String> argumentsC; Unit unit; assert termC.equals(termP); /* equals ignores arguments and return */ assert method != null; argumentsC=termC.getArguments(); unit=termP.getCodeUnit(); if (termC.getReturn() != null) { String contractVar=termC.getReturn(); /* unify return value */ if (unit instanceof AssignStmt) { ValueM v=new ValueM(method,((AssignStmt)unit).getLeftOp()); dprintln(" Trying unification "+contractVar+" <-> "+v); if (tryUnify(unif,contractVar,v,vEquiv) != 0) return false; } else { /* If control reaches here then the contract does specify a * return value but the word in the client program does not * assign the return value to a variable. In this case * we don't fail immediately because it is possible that the * variable is not used elsewhere. So we unify the variable * with null. That variable will not be able to be unified * with anything but null values. */ if (tryUnify(unif,contractVar,null,vEquiv) != 0) return false; } } for (int j=0; argumentsC != null && j < argumentsC.size(); j++) { InvokeExpr call=((Stmt)unit).getInvokeExpr(); String contractVar=argumentsC.get(j); ValueM v; v=new ValueM(method,call.getArg(j)); dprintln(" Trying unification "+contractVar+" <-> "+v); if (tryUnify(unif,contractVar,v,vEquiv) != 0) return false; } } return true; } @Override public boolean equals(Object o) { WordInstance other; List<PBTerminal> thisParsingTerminals; List<PBTerminal> otherParsingTerminals; if (!(o instanceof WordInstance)) return false; other=(WordInstance)o; if (!getLCAMethod().equals(other.getLCAMethod())) return false; thisParsingTerminals=getParsingTerminals(); otherParsingTerminals=other.getParsingTerminals(); if (thisParsingTerminals.size() != otherParsingTerminals.size()) return false; for (int i=0; i < thisParsingTerminals.size(); i++) { PBTerminal tterm=thisParsingTerminals.get(i); PBTerminal oterm=otherParsingTerminals.get(i); if (!tterm.getCodeUnit().equals(oterm.getCodeUnit())) return false; } return true; } @Override public int hashCode() { int h=getLCAMethod().getSignature().hashCode(); for (PBTerminal t: getParsingTerminals()) h=h^(t.getLineNumber()*92821)^t.getSourceFile().hashCode(); return h; } }
7,971
26.777003
81
java
gluon
gluon-master/src/main/java/gluon/profiling/Profiling.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.profiling; import java.util.*; public class Profiling { private static Map<String,Long> values; static { values=new HashMap<String,Long>(); } private Profiling() { assert false; } public static void set(String id, long v) { values.put(id,v); } public static long get(String id) { Long v=values.get(id); assert v != null; return v; } public static void inc(String id) { inc(id,1); } public static void inc(String id, int delta) { Long v=values.get(id); if (v == null) v=0L; set(id,v+delta); } public static List<String> getIds() { List<String> ids=new ArrayList<String>(values.size()); ids.addAll(values.keySet()); Collections.sort(ids); return ids; } }
1,559
19.8
71
java
gluon
gluon-master/src/main/java/gluon/profiling/Timer.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.profiling; import java.util.*; public class Timer { private static Map<String,Long> timer; private static Map<String,Long> running; static { timer=new HashMap<String,Long>(); running=new HashMap<String,Long>(); } private Timer() { assert false; } public static void start(String id) { long now=System.currentTimeMillis(); assert !running.containsKey(id) : "Timer is already running "+id; running.put(id,now); } public static void stop(String id) { long now=System.currentTimeMillis(); long delta; long acc=0; assert running.containsKey(id) : "Timer is not running"; delta=now-running.get(id); assert delta >= 0; running.remove(id); if (timer.containsKey(id)) acc=timer.get(id); timer.put(id,acc+delta); } public static List<String> getIds() { List<String> ids=new ArrayList<String>(timer.size()); ids.addAll(timer.keySet()); Collections.sort(ids); return ids; } public static long getTime(String id) { Long t=timer.get(id); return t == null ? -1 : t; } }
1,913
21.785714
73
java
gluon
gluon-master/src/main/java/gluon/parsing/parseTree/ParseTree.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parseTree; import gluon.grammar.EOITerminal; import gluon.grammar.NonTerminal; import gluon.grammar.Symbol; import gluon.grammar.Terminal; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import gluon.parsing.parsingTable.parsingAction.ParsingActionAccept; import gluon.parsing.parsingTable.parsingAction.ParsingActionReduce; import gluon.parsing.parsingTable.parsingAction.ParsingActionShift; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class ParseTree { private static final boolean DEBUG=false; private List<ParseTreeNode> leafs; private final List<Terminal> word; private final List<ParsingAction> actions; public ParseTree(List<Terminal> word, List<ParsingAction> actions) { this.word=word; this.actions=actions; } public void buildTree() { Stack<ParseTreeNode> stack=new Stack<ParseTreeNode>(); int pos=0; gluon.profiling.Timer.start(".buildTree"); leafs=new ArrayList<ParseTreeNode>(word.size()); for (ParsingAction a: actions) if (a instanceof ParsingActionReduce) { ParsingActionReduce red=(ParsingActionReduce)a; int len=red.getProduction().bodyLength(); ParseTreeNode parent =new ParseTreeNode(red.getProduction().getHead()); for (int i=0; i < len; i++) { ParseTreeNode node=stack.pop(); node.setParent(parent); /* Update leaf with true parsed terminal */ if (node.getElem() instanceof Terminal) { Symbol nodeTerm=red.getProduction() .getBody().get(len-1-i); assert nodeTerm instanceof Terminal; node.setElem(nodeTerm); } if (DEBUG) { System.out.println(parent); System.out.println(" |"); System.out.println(node); System.out.println(); } } stack.push(parent); } else if (a instanceof ParsingActionShift) { ParseTreeNode node=new ParseTreeNode(word.get(pos)); stack.push(node); leafs.add(node); pos++; } else if (a instanceof ParsingActionAccept) { int inputTerminals; inputTerminals=word.size() -(word.get(word.size()-1) instanceof EOITerminal ? 1 : 0); assert pos == inputTerminals; } gluon.profiling.Timer.stop(".buildTree"); } public List<Terminal> getTerminals() { List<Terminal> terminals=new ArrayList<Terminal>(leafs.size()); assert leafs != null; for (ParseTreeNode node: leafs) { assert node.getElem() instanceof Terminal; terminals.add((Terminal)node.getElem()); } return terminals; } public ParseTreeNode getLCA() { assert leafs != null; for (ParseTreeNode node: leafs) while (node != null) { node.count++; if (node.count == leafs.size() && node.getElem() instanceof NonTerminal) return node; node=node.getParent(); } return null; } }
4,325
28.834483
78
java
gluon
gluon-master/src/main/java/gluon/parsing/parseTree/ParseTreeNode.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parseTree; import gluon.grammar.Symbol; public class ParseTreeNode { private Symbol elem; private ParseTreeNode parent; protected int count; /* For getLCA() */ public ParseTreeNode(Symbol e) { elem=e; parent=null; count=0; } public void setParent(ParseTreeNode p) { parent=p; } public ParseTreeNode getParent() { return parent; } public void setElem(Symbol e) { elem=e; } public Symbol getElem() { return elem; } @Override public String toString() { return elem.toString()+"_"+hashCode(); } }
1,339
21.333333
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parser/ParserCallback.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parser; import gluon.grammar.NonTerminal; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import java.util.List; public interface ParserCallback { /* Whenever the parser reaches an LCA this is called with the list of * parsing actions so far. * Notice that this only contains a partial parse tree (up to the LCA); * there might be multiple ways to complete this tree up to the start * nonterminal. * * If the return value is false the parsing branch is discarded. */ public boolean onLCA(List<ParsingAction> actions, NonTerminal lca); /* Called periodically while the parser is running. * It can be used to implement a timeout when the parser is running for too * long. */ public boolean shouldAbort(); public void accepted(List<ParsingAction> actions, NonTerminal lca); }
1,548
35.023256
79
java
gluon
gluon-master/src/main/java/gluon/parsing/parser/ParserSubwords.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parser; import gluon.grammar.*; import gluon.parsing.parsingTable.Item; import gluon.parsing.parsingTable.ParsingTable; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import gluon.parsing.parsingTable.parsingAction.ParsingActionAccept; import gluon.parsing.parsingTable.parsingAction.ParsingActionReduce; import gluon.parsing.parsingTable.parsingAction.ParsingActionShift; import java.util.*; /* Extends ParserConfiguration to override the semantics of * getSuccessorActions() to perform the reductions that are missing * due to the way the subword parser works. * * This does not comform with the Liskov substitution principle but it was * the least ugly solution I found. */ class ParserConfigurationCompleteReductions extends ParserConfiguration { public ParserConfigurationCompleteReductions() { super(); } public static ParserConfiguration makeParserConfigCR(ParserConfiguration parserConfig) { ParserConfiguration parserConfigCR; parserConfigCR=new ParserConfigurationCompleteReductions(); parserConfigCR.copy(parserConfig); return parserConfigCR; } @Override public Collection<ParsingAction> getSuccessorActions(ParsingTable table, List<Terminal> input) { final EOITerminal EOI=new EOITerminal(); final ParsingActionAccept ACCEPT=new ParsingActionAccept(); Collection<ParsingAction> actions; int state=super.getState(); Collection<Item> items; assert pos == input.size(); items=table.getStateItems(state); actions=new ArrayList<ParsingAction>(items.size()+1); for (Item item: items) { Production partialProd=item.getPartialProduction(); ParsingActionReduce red=new ParsingActionReduce(partialProd); if (partialProd.bodyLength() > 0) actions.add(red); } if (table.actions(state,EOI).contains(ACCEPT)) { assert items.size() == 0 : "When we find an action there " +"should not be any possible alternative"; actions.add(new ParsingActionAccept()); } return actions; } @Override public ParserConfiguration clone() { ParserConfiguration clone; clone=new ParserConfigurationCompleteReductions(); clone.copy(this); return clone; } } /* Subword parser as described in "Substring parsing for arbitrary context-free * grammars", J Rekers, W Koorn, 1991. */ public class ParserSubwords extends Parser { public ParserSubwords(ParsingTable t) { super(t); } private static boolean addNonTerminalsToQueue(Production prod, Queue<NonTerminal> queue, Set<NonTerminal> enqueued, Set<NonTerminal> terminalGenerators) { for (Symbol s: prod.getBody()) { NonTerminal nonterm; if (s instanceof Terminal) { terminalGenerators.add(prod.getHead()); return true; } assert s instanceof NonTerminal; nonterm=(NonTerminal)s; if (terminalGenerators.contains(s)) return true; if (!enqueued.contains(nonterm)) { queue.add(nonterm); enqueued.add(nonterm); } } return false; } private static boolean productionGenerateTerminal(Cfg grammar, Production prod, Set<NonTerminal> terminalGenerators) { Queue<NonTerminal> queue=new LinkedList<NonTerminal>(); Set<NonTerminal> enqueued=new HashSet<NonTerminal>(); if (addNonTerminalsToQueue(prod,queue,enqueued,terminalGenerators)) return true; while (queue.size() > 0) { NonTerminal nonterm=queue.poll(); for (Production p: grammar.getProductionsOf(nonterm)) if (addNonTerminalsToQueue(p,queue,enqueued,terminalGenerators)) return true; } return false; } /* For the subword parser to be able to parse the grammar every production * must generate at least one non-empty word. */ public static boolean isParsable(Cfg grammar) { Set<NonTerminal> terminalGenerators=new HashSet<NonTerminal>(); boolean emptyGrammar=true; boolean fail=false; Production fprod=null; for (Production p: grammar.getProductions()) if (productionGenerateTerminal(grammar,p,terminalGenerators)) emptyGrammar=false; else { fail=true; fprod=p; } /* It's always ok if the grammar is empty */ if (emptyGrammar) return true; return !fail; } @Override protected Collection<ParserConfiguration> shift(ParserConfiguration parent, ParsingActionShift shift, List<Terminal> input) throws ParserAbortedException { ParserConfiguration parserConf; parserConf=super.shift(parent,shift,input).iterator().next(); if (parserConf.pos >= input.size()) parserConf=ParserConfigurationCompleteReductions .makeParserConfigCR(parserConf); return Collections.singleton(parserConf); } private ParsingActionReduce getSufixRedution(Production p, int takeOnly) { Production sufixProd; assert takeOnly > 0; sufixProd=new Production(p.getHead(), p.getBody().subList(p.bodyLength()-takeOnly, p.bodyLength())); assert sufixProd.bodyLength() == takeOnly; return new ParsingActionReduce(sufixProd); } private Collection<ParserConfiguration> reduceWithReachedByJump(ParserConfiguration parent, ParsingActionReduce reduction) { ParserConfiguration parserConf; Production p=reduction.getProduction(); Collection<ParserConfiguration> configs; ParsingStackNode newStackNode=new ParsingStackNode(); configs=new LinkedList<ParserConfiguration>(); parserConf=parent.clone(); super.stackPop(parserConf,p.bodyLength(),newStackNode,p.getHead()); for (int s: super.table.statesReachedBy(p.getHead())) { ParserConfiguration succParserConfig=parserConf.clone(); ParsingStackNode succNewStackNode=newStackNode.clone(); succNewStackNode.state=s; succParserConfig.getStack().push(succNewStackNode); succParserConfig.addAction(reduction); configs.add(succParserConfig); } return configs; } /* The algorithm implemented here is from "Substring parsing for arbitrary * context-free grammars" by Jan Rekers and Wilco Koorn. */ @Override protected Collection<ParserConfiguration> reduce(ParserConfiguration parent, ParsingActionReduce reduction, List<Terminal> input) throws ParserAbortedException { Collection<ParserConfiguration> configs; Production p=reduction.getProduction(); int stackSize=parent.getStack().size(); if (stackSize > p.bodyLength()) configs=super.reduce(parent,reduction,input); else if (stackSize < p.bodyLength()) { ParsingActionReduce sufixReduction; sufixReduction=getSufixRedution(p,stackSize); configs=reduceWithReachedByJump(parent,sufixReduction); } else { assert stackSize == p.bodyLength(); configs=reduceWithReachedByJump(parent,reduction); } return configs; } @Override protected Collection<ParserConfiguration> getInitialConfigurations(List<Terminal> input) throws ParserAbortedException { Collection<ParserConfiguration> configurations; configurations=new ArrayList<ParserConfiguration>(128); for (int s: super.table.statesReachedBy(input.get(0))) { ParserConfiguration initConfig; ParsingActionShift shift=new ParsingActionShift(s); initConfig=shift(null,shift,input).iterator().next(); configurations.add(initConfig); } return configurations; } @Override public void parse(List<Terminal> input, ParserCallback pcb) throws ParserAbortedException { assert input.size() > 0; assert !(input.get(input.size()-1) instanceof EOITerminal) : "input should not end with $"; super.parse(input,pcb); } }
9,950
29.431193
90
java
gluon
gluon-master/src/main/java/gluon/parsing/parser/ParserNormal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parser; import gluon.grammar.EOITerminal; import gluon.grammar.Terminal; import gluon.parsing.parsingTable.ParsingTable; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ParserNormal extends Parser { public ParserNormal(ParsingTable t) { super(t); } @Override protected Collection<ParserConfiguration> getInitialConfigurations(List<Terminal> input) { ParserConfiguration initConfig=new ParserConfiguration(); Collection<ParserConfiguration> configurations; initConfig.getStack().push(new ParsingStackNode(table.getInitialState(),0)); configurations=new ArrayList<ParserConfiguration>(1); configurations.add(initConfig); return configurations; } @Override public void parse(List<Terminal> input, ParserCallback pcb) throws ParserAbortedException { assert input.size() == 0 || input.get(input.size()-1) instanceof EOITerminal : "input should end with $"; super.parse(input,pcb); } }
1,780
28.196721
84
java
gluon
gluon-master/src/main/java/gluon/parsing/parser/Parser.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parser; import gluon.grammar.EOITerminal; import gluon.grammar.NonTerminal; import gluon.grammar.Production; import gluon.grammar.Terminal; import gluon.parsing.parsingTable.ParsingTable; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import gluon.parsing.parsingTable.parsingAction.ParsingActionAccept; import gluon.parsing.parsingTable.parsingAction.ParsingActionReduce; import gluon.parsing.parsingTable.parsingAction.ParsingActionShift; import java.util.*; class ParsingStackNode { public int state; public int generatedTerminals; /* If generatedTerminalsByNonTerm.get(nonterm) = m then this subtree has a * nonterminal that consumed m terminals and no more. * * This is used to prune unproductive loops. */ private Map<NonTerminal,Integer> terminalsByNonTerm; public ParsingStackNode parent; public ParsingStackNode() { state=-1; generatedTerminals=0; terminalsByNonTerm=new HashMap<NonTerminal,Integer>(); parent=null; } public ParsingStackNode(int state, int generatedTerminals) { this(); this.state=state; this.generatedTerminals=generatedTerminals; } public int getTerminalsByNonTerm(NonTerminal nonterm) { Integer terms=terminalsByNonTerm.get(nonterm); return terms == null ? 0 : terms; } public void updateTerminalsByNonTerm(NonTerminal nonterm, int terms) { int currentTerms=getTerminalsByNonTerm(nonterm); if (terms > currentTerms) terminalsByNonTerm.put(nonterm,terms); } public Set<Map.Entry<NonTerminal,Integer>> getNonTermTerminals() { return terminalsByNonTerm.entrySet(); } public ParsingStackNode clone() { ParsingStackNode clone=new ParsingStackNode(); clone.state=state; clone.generatedTerminals=generatedTerminals; /* We don't need to do a deep clone of this map because it will be * read-only from now on. */ clone.terminalsByNonTerm=terminalsByNonTerm; clone.parent=parent; return clone; } } class ParsingStack { private ParsingStackNode top; private int size; public ParsingStack() { size=0; top=null; } public int size() { return size; } public ParsingStackNode peek() { assert top != null; return top; } public void push(ParsingStackNode node) { assert node.parent == null; node.parent=top; top=node; size++; } public ParsingStackNode pop() { ParsingStackNode node=top; assert top != null; top=top.parent; size--; return top; } public ParsingStack clone() { ParsingStack clone=new ParsingStack(); clone.top=top; clone.size=size; return clone; } } class ParserConfiguration { private class ParserHistory { public final ParsingAction action; public final ParserHistory parent; public ParserHistory(ParsingAction a, ParserHistory p) { action=a; parent=p; } } private ParsingStack stack; private ParserHistory history; public int pos; public NonTerminal lca; public ParserConfiguration() { history=null; stack=new ParsingStack(); lca=null; pos=0; } /* This should always be called *after* the stack is changed as a result of * this action. */ public void addAction(ParsingAction action) { ParserHistory h=new ParserHistory(action,history); history=h; } public ParsingAction getLastAction() { return history.action; } public List<ParsingAction> getActionList() { LinkedList<ParsingAction> actions=new LinkedList<ParsingAction>(); for (ParserHistory h=history; h != null; h=h.parent) { assert h.action != null; actions.addFirst(h.action); } return actions; } public ParsingStack getStack() { return stack; } public boolean isLoop(ParserConfiguration conf) { ParsingAction action=conf.getLastAction(); Production reduction; NonTerminal head; ParsingStackNode subTree; if (!(action instanceof ParsingActionReduce)) return false; reduction=((ParsingActionReduce)action).getProduction(); head=reduction.getHead(); subTree=stack.peek(); /* This iterates all the subtrees of the reduction made. */ for (int i=0; i < reduction.bodyLength(); i++) { /* If this condition is true then there is a subtree that contains * /head/, and in that subtree head consumes the same number of * terminals as the branch /conf/. This means that /conf/ contains * a loop (since there are two /head/ in the tree) and that loop is * inproductive (since from those two points of the tree no extra * terminal were consumed). */ if (subTree.getTerminalsByNonTerm(head) == conf.getTerminalNum()) return true; assert subTree.getTerminalsByNonTerm(head) < conf.getTerminalNum(); subTree=subTree.parent; } return false; } public int getTerminalNum() { return stack.peek().generatedTerminals; } public int getState() { return stack.peek().state; } public Collection<ParsingAction> getSuccessorActions(ParsingTable table, List<Terminal> input) { Terminal term; int state; assert pos < input.size(); state=getState(); term=input.get(pos); return table.actions(state,term); } protected void copy(ParserConfiguration src) { stack=src.stack.clone(); history=src.history; lca=src.lca; pos=src.pos; } public ParserConfiguration clone() { ParserConfiguration clone=new ParserConfiguration(); clone.copy(this); return clone; } } /* This is a partial implementation of the tomita parser. We do not merge * configuration states as described in the full tomita implementation. * * This parser also detects and prune branches with unproductive loops in the * grammar. */ public abstract class Parser { private static final boolean DEBUG=false; protected final ParsingTable table; private Stack<ParserConfiguration> parseLifo; protected ParserCallback parserCB; public Parser(ParsingTable t) { table=t; parseLifo=null; } protected void dprintln(String s) { if (DEBUG) System.out.println(this.getClass().getSimpleName()+": "+s); } protected Collection<ParserConfiguration> shift(ParserConfiguration parent, ParsingActionShift shift, List<Terminal> input) throws ParserAbortedException { ParserConfiguration parserConf; parserConf=parent == null ? new ParserConfiguration() : parent.clone(); parserConf.getStack().push(new ParsingStackNode(shift.getState(),1)); parserConf.pos++; parserConf.addAction(shift); dprintln(parserConf.hashCode()+": shift "+shift.getState()); return Collections.singleton(parserConf); } /* Pops n elements from the stack, returns the number of terminals * generated by the poped elements, and updates the "terminals by nonterm" * of the next stack node. */ protected void stackPop(ParserConfiguration parserConf, int n, ParsingStackNode newStackNode, NonTerminal reductionHead) { for (int i=0; i < n; i++) { ParsingStackNode subtree; subtree=parserConf.getStack().peek(); newStackNode.generatedTerminals+=subtree.generatedTerminals; parserConf.getStack().pop(); for (Map.Entry<NonTerminal,Integer> e: subtree.getNonTermTerminals()) { NonTerminal nonterm=e.getKey(); int terms=e.getValue(); newStackNode.updateTerminalsByNonTerm(nonterm,terms); } } newStackNode.updateTerminalsByNonTerm(reductionHead, newStackNode.generatedTerminals); } protected Collection<ParserConfiguration> reduce(ParserConfiguration parent, ParsingActionReduce reduction, List<Terminal> input) throws ParserAbortedException { ParserConfiguration parserConf=parent.clone(); Production p=reduction.getProduction(); ParsingStackNode newStackNode=new ParsingStackNode(); int s; stackPop(parserConf,p.bodyLength(),newStackNode,p.getHead()); s=parserConf.getState(); newStackNode.state=table.goTo(s,p.getHead()); parserConf.getStack().push(newStackNode); parserConf.addAction(reduction); dprintln(parserConf.hashCode()+": reduce "+p); return Collections.singleton(parserConf); } private void acceptedDeliver(ParserConfiguration parserConf) { NonTerminal lca=parserConf.lca; assert parserConf.lca != null; gluon.profiling.Timer.stop("parsing"); parserCB.accepted(parserConf.getActionList(),lca); gluon.profiling.Timer.start("parsing"); } protected Collection<ParserConfiguration> accept(ParserConfiguration parent, ParsingActionAccept accept, List<Terminal> input) throws ParserAbortedException { ParserConfiguration parserConf=parent.clone(); dprintln(parserConf.hashCode()+": accept"); parserConf.addAction(accept); acceptedDeliver(parserConf); gluon.profiling.Profiling.inc("parse-branches"); return new ArrayList<ParserConfiguration>(0); } private void parseSingleStep(ParserConfiguration parserConf, List<Terminal> input) throws ParserAbortedException { Collection<ParsingAction> actions; actions=parserConf.getSuccessorActions(table,input); if (actions.size() == 0) { dprintln(parserConf.hashCode()+": error: actions=∅"); gluon.profiling.Profiling.inc("parse-branches"); return; } for (ParsingAction action: actions) { Collection<ParserConfiguration> branches=null; if (action instanceof ParsingActionShift) branches=shift(parserConf,(ParsingActionShift)action,input); else if (action instanceof ParsingActionReduce) branches=reduce(parserConf,(ParsingActionReduce)action,input); else if (action instanceof ParsingActionAccept) branches=accept(parserConf,(ParsingActionAccept)action,input); else assert false; for (ParserConfiguration branch: branches) { int inputTerminals; if (parserConf.isLoop(branch)) { gluon.profiling.Profiling.inc("parse-branches"); continue; } inputTerminals=input.size() -(input.get(input.size()-1) instanceof EOITerminal ? 1 : 0); /* Check if we have a lca */ if (branch.getTerminalNum() == inputTerminals && parserConf.lca == null && action instanceof ParsingActionReduce) { ParsingActionReduce red=(ParsingActionReduce)action; boolean cont; branch.lca=red.getProduction().getHead(); gluon.profiling.Timer.stop("parsing"); cont=parserCB.onLCA(branch.getActionList(),branch.lca); gluon.profiling.Timer.start("parsing"); if (!cont) { gluon.profiling.Profiling.inc("parse-branches"); continue; } } parseLifo.add(branch); } } } protected abstract Collection<ParserConfiguration> getInitialConfigurations(List<Terminal> input) throws ParserAbortedException; /* Argument input should be an ArrayList for performance reasons. */ public void parse(List<Terminal> input, ParserCallback pcb) throws ParserAbortedException { int counter=0; /* For calling pcb.shouldStop() */ gluon.profiling.Timer.start("parsing"); parseLifo=new Stack<ParserConfiguration>(); parserCB=pcb; for (ParserConfiguration initialConfig: getInitialConfigurations(input)) parseLifo.add(initialConfig); while (parseLifo.size() > 0) { ParserConfiguration parserConf=parseLifo.pop(); counter=(counter+1)%500000; if (counter == 0 && parserCB.shouldAbort()) { gluon.profiling.Timer.stop("parsing"); throw new ParserAbortedException(); } parseSingleStep(parserConf,input); } /* free memory */ parseLifo=null; parserCB=null; gluon.profiling.Timer.stop("parsing"); } }
14,670
26.118299
83
java
gluon
gluon-master/src/main/java/gluon/parsing/parser/ParserAbortedException.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parser; public class ParserAbortedException extends Exception { public ParserAbortedException() { super(); } }
822
29.481481
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/ParsingTable.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable; /* This is a implementation of a LR(0) parsing table generator as described in * the dragon book (Compilers - Principles, Techniques, & Tools; second edition). * Pages 241..254. */ import gluon.grammar.*; import gluon.parsing.parsingTable.parsingAction.ParsingAction; import gluon.parsing.parsingTable.parsingAction.ParsingActionAccept; import gluon.parsing.parsingTable.parsingAction.ParsingActionReduce; import gluon.parsing.parsingTable.parsingAction.ParsingActionShift; import java.util.*; class GoToTable { /* state -> nonterm -> state */ private List<Map<NonTerminal,Integer>> goToTable; private Map<NonTerminal,Set<Integer>> statesReachedBy; public GoToTable(int states) { statesReachedBy=new HashMap<NonTerminal,Set<Integer>>(); goToTable=new ArrayList<Map<NonTerminal,Integer>>(states); for (int i=0; i < states; i++) goToTable.add(new HashMap<NonTerminal,Integer>()); } public void add(int state, NonTerminal nonterm, int newstate) { goToTable.get(state).put(nonterm,newstate); if (!statesReachedBy.containsKey(nonterm)) statesReachedBy.put(nonterm,new HashSet<Integer>()); statesReachedBy.get(nonterm).add(newstate); } public Integer get(int state, NonTerminal nonterm) { Integer destState; destState=goToTable.get(state).get(nonterm); return destState == null ? -1 : destState; } public Set<Integer> statesReachedBy(NonTerminal nonterm) { if (!statesReachedBy.containsKey(nonterm)) return new HashSet<Integer>(); return statesReachedBy.get(nonterm); } public int size() { return goToTable.size(); } @Override public String toString() { String r="== Goto Table ==\n"; for (int i=0; i < size(); i++) { r+=i+" "; for (Map.Entry<NonTerminal,Integer> entry: goToTable.get(i).entrySet()) r+=entry.getKey()+"↦"+entry.getValue()+" "; r+="\n"; } r+="\n"; return r; } } class ActionTable { /* state -> term -> set of actions */ private List<Map<Terminal,Collection<ParsingAction>>> actionTable; private Map<Terminal,Set<Integer>> statesReachedBy; public ActionTable(int states) { statesReachedBy=new HashMap<Terminal,Set<Integer>>(); actionTable=new ArrayList<Map<Terminal,Collection<ParsingAction>>>(states); for (int i=0; i < states; i++) actionTable.add(new HashMap<Terminal,Collection<ParsingAction>>()); } public void add(int state, Terminal term, ParsingAction action) { Map<Terminal,Collection<ParsingAction>> row; row=actionTable.get(state); if (!row.containsKey(term)) row.put(term,new HashSet<ParsingAction>(8)); row.get(term).add(action); if (action instanceof ParsingActionShift) { ParsingActionShift shift=(ParsingActionShift)action; if (!statesReachedBy.containsKey(term)) statesReachedBy.put(term,new HashSet<Integer>()); statesReachedBy.get(term).add(shift.getState()); } } public Collection<ParsingAction> get(int state, Terminal nonterm) { Collection<ParsingAction> actions; actions=actionTable.get(state).get(nonterm); return actions != null ? actions : new ArrayList<ParsingAction>(0); } public Set<Integer> statesReachedBy(Terminal term) { if (!statesReachedBy.containsKey(term)) return new HashSet<Integer>(); return statesReachedBy.get(term); } public int size() { return actionTable.size(); } @Override public String toString() { String r="== Action Table ==\n"; for (int i=0; i < actionTable.size(); i++) { r+=i+" "; for (Map.Entry<Terminal,Collection<ParsingAction>> entry: actionTable.get(i).entrySet()) { int count=0; r+=entry.getKey()+"->"; for (ParsingAction a: entry.getValue()) r+=(count++ == 0 ? "" : ",")+a.toString(); r+=" "; } r+="\n"; } r+="\n"; return r; } } public class ParsingTable { private static final boolean DEBUG=false; private static final Terminal EOI_TERMINAL=new EOITerminal(); private GoToTable goToTable; private ActionTable actionTable; /* state -> items of the state */ private List<Set<Item>> states; /* items of the state -> state */ private Map<Set<Item>,Integer> stateMap; private int initialState; private Map<Symbol,Set<List<Terminal>>> first; private Map<NonTerminal,Collection<Terminal>> follow; private Cfg grammar; public ParsingTable(Cfg g) { grammar=g; goToTable=null; actionTable=null; states=null; follow=null; initialState=-1; } private void debugPrintStates() { System.out.println("== States =="); System.out.println(); for (Set<Item> state: states) { for (Item i: state) System.out.println(i); System.out.println(); } } private void debugPrintGotoTable() { System.out.println(goToTable.toString()); } private void debugPrintActionTable() { System.out.println(actionTable.toString()); } private void closure(Set<Item> items) { Set<Item> nextNewItems; Set<Item> newItems; boolean fixPoint; nextNewItems=new HashSet<Item>(); newItems=new HashSet<Item>(); newItems.addAll(items); do { nextNewItems.clear(); for (Item i: newItems) { /* If we have item A -> B . C D and C -> E is a production, * then we add C -> . E to nextNewItems */ Symbol c=i.getNextToDot(); if (!(c instanceof NonTerminal)) continue; Collection<Production> toAdd=grammar.getProductionsOf((NonTerminal)c); for (Production p: toAdd) { Item newItem=new Item(p,0); if (!items.contains(newItem)) nextNewItems.add(newItem); } } fixPoint=nextNewItems.size() == 0; items.addAll(nextNewItems); { Set<Item> tmp=newItems; newItems=nextNewItems; nextNewItems=tmp; } } while (!fixPoint); } private Set<Item> goTo(Set<Item> items, Symbol e) { Set<Item> ret=new HashSet<Item>(); for (Item i: items) { /* If i is A -> B . C D and e == C then add A -> B C . D to ret */ Symbol c=i.getNextToDot(); if (e.equals(c)) ret.add(new Item(i.getProduction(),i.getDotPos()+1)); } closure(ret); return ret; } private Production getStartProduction() { NonTerminal start=grammar.getStart(); Collection<Production> prods=grammar.getProductionsOf(start); assert prods.size() == 1; return prods.iterator().next(); } private Set<Item> buildInitialState() { Set<Item> state=new HashSet<Item>(); state.add(new Item(getStartProduction(),0)); closure(state); return state; } private void buildStateMap() { assert states != null; stateMap=new HashMap<Set<Item>,Integer>(); for (int i=0; i < states.size(); i++) stateMap.put(states.get(i),i); } private Collection<Symbol> getStateNextLexicalSymbols(Set<Item> state) { Collection<Symbol> simbols=new HashSet<Symbol>(state.size()*2); for (Item i: state) if (i.getNextToDot() != null) simbols.add(i.getNextToDot()); return simbols; } private void buildStates() { Set<Set<Item>> statesToAdd; Set<Set<Item>> newStates; boolean fixPoint; states=new ArrayList<Set<Item>>(grammar.size()*3); states.add(buildInitialState()); initialState=0; statesToAdd=new HashSet<Set<Item>>(grammar.size()*3); newStates=new HashSet<Set<Item>>(grammar.size()*3); newStates.add(buildInitialState()); do { statesToAdd.clear(); for (Set<Item> state: newStates) for (Symbol e: getStateNextLexicalSymbols(state)) { Set<Item> nextState; nextState=goTo(state,e); if (nextState.size() > 0 && !states.contains(nextState)) statesToAdd.add(nextState); } fixPoint=statesToAdd.size() == 0; states.addAll(statesToAdd); { Set<Set<Item>> tmp=newStates; newStates=statesToAdd; statesToAdd=tmp; } } while (!fixPoint); buildStateMap(); } private Collection<NonTerminal> getStateNextNonTerminals(Set<Item> state) { Collection<NonTerminal> simbols=new HashSet<NonTerminal>(); for (Item i: state) if (i.getNextToDot() instanceof NonTerminal) simbols.add((NonTerminal)i.getNextToDot()); return simbols; } private void buildGotoTable() { goToTable=new GoToTable(states.size()); for (int s=0; s < states.size(); s++) { Set<Item> state=states.get(s); for (NonTerminal n: getStateNextNonTerminals(state)) { Set<Item> destState=goTo(state,n); if (destState.size() > 0) goToTable.add(s,n,stateMap.get(destState)); } } } private void computeFirst() { final List<Terminal> EMPTY_WORD=new ArrayList<Terminal>(0); boolean fixPoint; first=new HashMap<Symbol,Set<List<Terminal>>>(); for (Symbol e: grammar.getSymbols()) first.put(e,new HashSet<List<Terminal>>()); for (Terminal t: grammar.getTerminals()) { List<Terminal> word=new ArrayList<Terminal>(1); word.add(t); first.get(t).add(word); } do { fixPoint=true; for (NonTerminal n: grammar.getNonTerminals()) for (Production p: grammar.getProductionsOf(n)) { boolean deriveEmptyWord=true; int beforeSize=first.get(n).size(); for (Symbol e: p.getBody()) { Set<List<Terminal>> firstsE=first.get(e); for (List<Terminal> f: firstsE) if (!f.equals(EMPTY_WORD)) first.get(n).add(f); if (!firstsE.contains(EMPTY_WORD)) { deriveEmptyWord=false; break; } } if (deriveEmptyWord) first.get(n).add(EMPTY_WORD); if (first.get(n).size() != beforeSize) fixPoint=false; } } while (!fixPoint); } private Set<List<Terminal>> first(List<Symbol> s) { final List<Terminal> EMPTY_WORD=new ArrayList<Terminal>(0); Set<List<Terminal>> ret=new HashSet<List<Terminal>>(); boolean deriveEmptyWord=true; for (Symbol e: s) { Set<List<Terminal>> firstsE=first.get(e); for (List<Terminal> f: firstsE) if (!f.equals(EMPTY_WORD)) ret.add(f); if (!firstsE.contains(EMPTY_WORD)) { deriveEmptyWord=false; break; } } if (deriveEmptyWord) ret.add(EMPTY_WORD); return ret; } private void computeFollow() { final List<Terminal> EMPTY_WORD=new ArrayList<Terminal>(0); boolean fixPoint; Collection<Production> productions=grammar.getProductions(); follow=new HashMap<NonTerminal,Collection<Terminal>>(grammar.size()); for (NonTerminal n: grammar.getNonTerminals()) follow.put(n,new HashSet<Terminal>()); follow.get(grammar.getStart()).add(EOI_TERMINAL); do { fixPoint=true; for (Production p: productions) { List<Symbol> right=new LinkedList<Symbol>(); right.addAll(p.getBody()); while (right.size() > 0) { Symbol e=right.remove(0); NonTerminal n; Set<List<Terminal>> firstRight; Collection<Terminal> followN; int beforeSize; if (!(e instanceof NonTerminal)) continue; n=(NonTerminal)e; followN=follow.get(n); beforeSize=followN.size(); firstRight=first(right); for (List<Terminal> t: firstRight) { Terminal term; assert t.size() == 0 || t.size() == 1; if (t.size() == 0) continue; term=t.get(0); followN.add(term); } if (firstRight.contains(EMPTY_WORD)) followN.addAll(follow.get(p.getHead())); if (followN.size() != beforeSize) fixPoint=false; } } } while (!fixPoint); } private void buildActionTable() { actionTable=new ActionTable(states.size()); for (int s=0; s < states.size(); s++) { Set<Item> state=states.get(s); for (Item i: state) { Symbol next=i.getNextToDot(); if (next instanceof Terminal) { Terminal t=(Terminal)next; Set<Item> destState=goTo(state,t); ParsingAction a; assert stateMap.containsKey(destState); a=new ParsingActionShift(stateMap.get(destState)); actionTable.add(s,t,a); } if (!i.getProduction().getHead().equals(grammar.getStart()) && i.isComplete()) for (Terminal t: follow.get(i.getProduction().getHead())) { // reduce H -> B ParsingAction a; a=new ParsingActionReduce(i.getProduction()); actionTable.add(s,t,a); } // Item S' -> S . if (i.getProduction().getHead().equals(grammar.getStart()) && i.getDotPos() == 1) { assert i.getProduction().bodyLength() == 1; actionTable.add(s,EOI_TERMINAL,new ParsingActionAccept()); } } } } public void buildParsingTable() { gluon.profiling.Timer.start("build-parsing-table"); assert goToTable == null : "Parsing table should only be built only once"; assert grammar.hasUniqueStart() : "Grammar must only have a start production " +"to generate the parsing table"; // 18'540 if (DEBUG) System.out.println("start states "+System.currentTimeMillis()); buildStates(); if (DEBUG) System.out.println("end states "+System.currentTimeMillis()); assert initialState >= 0; // 0'572 if (DEBUG) System.out.println("start goto "+System.currentTimeMillis()); buildGotoTable(); if (DEBUG) System.out.println("end goto "+System.currentTimeMillis()); // 0'023 if (DEBUG) System.out.println("start first "+System.currentTimeMillis()); computeFirst(); if (DEBUG) System.out.println("end first "+System.currentTimeMillis()); // 2'100 if (DEBUG) System.out.println("start follow "+System.currentTimeMillis()); computeFollow(); if (DEBUG) System.out.println("end follow "+System.currentTimeMillis()); // 0'098 if (DEBUG) System.out.println("start action "+System.currentTimeMillis()); buildActionTable(); if (DEBUG) System.out.println("end action "+System.currentTimeMillis()); if (DEBUG) { // debugPrintStates(); debugPrintGotoTable(); debugPrintActionTable(); } // free unused data structures first=null; follow=null; stateMap=null; grammar=null; gluon.profiling.Timer.stop("build-parsing-table"); } public Set<Item> getStateItems(int n) { return states.get(n); } /* Return the states directly reached by transitions of label s. */ public Set<Integer> statesReachedBy(Symbol symb) { if (symb instanceof Terminal) return actionTable.statesReachedBy((Terminal)symb); else if (symb instanceof NonTerminal) return goToTable.statesReachedBy((NonTerminal)symb); assert false; return null; } public int goTo(int state, NonTerminal n) { Integer destState; assert goToTable != null; return goToTable.get(state,n); } public Collection<ParsingAction> actions(int state, Terminal t) { Map<Terminal,Collection<ParsingAction>> row; Collection<ParsingAction> actions; assert actionTable != null; return actionTable.get(state,t); } public int getInitialState() { return initialState; } public int numberOfStates() { return actionTable.size(); } }
19,394
25.244926
86
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/Item.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable; import gluon.grammar.Production; import gluon.grammar.Symbol; public class Item { private final Production prod; private final int pos; public Item(Production prod, int pos) { this.prod=prod; this.pos=pos; assert 0 <= pos && pos <= prod.bodyLength(); } public Production getProduction() { return prod; } /* If this is the item A → α . β then we return A → α. */ public Production getPartialProduction() { Production p; p=new Production(prod.getHead(),prod.getBody().subList(0,pos)); assert p.bodyLength() == pos; return p; } public int getDotPos() { return pos; } public Symbol getNextToDot() { if (isComplete()) return null; return prod.getBody().get(pos); } public boolean isComplete() { return pos == prod.bodyLength(); } @Override public int hashCode() { return prod.hashCode()^pos; } @Override public boolean equals(Object o) { Item other; if (!(o instanceof Item)) return false; other=(Item)o; return other.pos == pos && other.prod.equals(prod); } @Override public String toString() { return prod.toString()+", "+pos; } }
2,052
20.385417
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/parsingAction/ParsingActionAccept.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable.parsingAction; public class ParsingActionAccept extends ParsingAction { public ParsingActionAccept() { } @Override public int hashCode() { return 0x3d057799; } @Override public boolean equals(Object o) { return o instanceof ParsingActionAccept; } @Override public String toString() { return "a"; } }
1,092
23.288889
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/parsingAction/ParsingAction.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable.parsingAction; public abstract class ParsingAction { public abstract int hashCode(); public abstract boolean equals(Object o); public abstract String toString(); }
876
34.08
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/parsingAction/ParsingActionReduce.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable.parsingAction; import gluon.grammar.Production; public class ParsingActionReduce extends ParsingAction { private Production production; public ParsingActionReduce(Production p) { production=p; } public Production getProduction() { return production; } @Override public int hashCode() { return production.hashCode(); } @Override public boolean equals(Object o) { ParsingActionReduce other; if (!(o instanceof ParsingActionReduce)) return false; other=(ParsingActionReduce)o; return other.production.equals(production); } @Override public String toString() { return "r["+production.toString()+"]"; } }
1,465
23.032787
71
java
gluon
gluon-master/src/main/java/gluon/parsing/parsingTable/parsingAction/ParsingActionShift.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.parsing.parsingTable.parsingAction; public class ParsingActionShift extends ParsingAction { private int state; public ParsingActionShift(int s) { state=s; } public int getState() { return state; } @Override public int hashCode() { return state; } @Override public boolean equals(Object o) { ParsingActionShift other; if (!(o instanceof ParsingActionShift)) return false; other=(ParsingActionShift)o; return other.state == state; } @Override public String toString() { return "s"+state; } }
1,333
21.610169
71
java
gluon
gluon-master/src/main/java/gluon/grammar/Symbol.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; public abstract class Symbol { protected String name; public Symbol(String name) { assert name != null; this.name=name; } public String getName() { return name; } @Override public String toString() { return getName(); } public abstract int hashCode(); public abstract boolean equals(Object o); public abstract Symbol clone(); }
1,109
23.666667
71
java
gluon
gluon-master/src/main/java/gluon/grammar/Terminal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; public abstract class Terminal extends Symbol { public Terminal(String name) { super(name); } public abstract boolean isEOI(); @Override public abstract Terminal clone(); }
899
27.125
71
java
gluon
gluon-master/src/main/java/gluon/grammar/EOITerminal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; public final class EOITerminal extends Terminal { public EOITerminal() { super("$"); } public boolean isEOI() { return true; } @Override public int hashCode() { return 0xdecbfe1d; } @Override public boolean equals(Object o) { return o instanceof EOITerminal; } @Override public EOITerminal clone() { return new EOITerminal(); } }
1,138
21.78
71
java
gluon
gluon-master/src/main/java/gluon/grammar/NonTerminal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; public abstract class NonTerminal extends Symbol { public NonTerminal(String name) { super(name); } public void setName(String newName) { name=newName; } @Override public abstract NonTerminal clone(); /* Prevents any simplification that removes this nonterminal */ public abstract boolean noRemove(); }
1,054
26.763158
71
java
gluon
gluon-master/src/main/java/gluon/grammar/Production.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; import java.util.ArrayList; import java.util.List; public class Production { private NonTerminal head; private ArrayList<Symbol> body; // it is important to garantee O(1) get(n) public Production(NonTerminal h, ArrayList<Symbol> b) { this(h); body=b; } public Production(NonTerminal h, List<Symbol> b) { ArrayList<Symbol> alb=new ArrayList<Symbol>(b.size()); alb.addAll(b); head=h; body=alb; } public Production(NonTerminal h) { head=h; body=new ArrayList<Symbol>(2); } public void appendToBody(Symbol e) { body.add(e); } public NonTerminal getHead() { return head; } public ArrayList<Symbol> getBody() { return body; } public int bodyLength() { return body.size(); } /* pre: string does not contain nonterm. */ public void replace(NonTerminal nonterm, ArrayList<Symbol> string) { ArrayList<Symbol> oldBody=body; assert !string.contains(nonterm); /* Most likely there will only be one replace so this size should be * good. */ body=new ArrayList<Symbol>(string.size()+oldBody.size()-1); for (Symbol e: oldBody) if (e.equals(nonterm)) body.addAll(string); else body.add(e); } public boolean isDirectLoop() { return bodyLength() == 1 && getBody().get(0).equals(getHead()); } @Override public int hashCode() { int hash; hash=head.hashCode(); for (Symbol e: body) hash^=e.hashCode(); return hash; } @Override public boolean equals(Object o) { Production other; if (!(o instanceof Production)) return false; other=(Production)o; return other.head.equals(head) && other.body.equals(body); } @Override public String toString() { String s; s=head.toString()+" →"; for (Symbol e: body) s+=' '+e.toString(); if (body.size() == 0) s+=" ε"; return s; } public Production clone() { ArrayList<Symbol> newBody=new ArrayList<Symbol>(body.size()); newBody.addAll(body); return new Production(head,newBody); } }
3,087
20.444444
78
java
gluon
gluon-master/src/main/java/gluon/grammar/Cfg.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar; import java.util.*; public class Cfg { private static final boolean DEBUG=false; private Map<NonTerminal,Set<Production>> productions; private NonTerminal start; private int size; private Map<Symbol,Set<Production>> productionsContaining; private Set<Symbol> lexicalElements; private Set<NonTerminal> nonterminals; private Set<Terminal> terminals; private boolean LESetsUptodate; /* true if the above sets are up to date */ public Cfg() { clear(); } public Cfg(NonTerminal start, Collection<Production> prods) { this(); for (Production p: prods) addProduction(p); setStart(start); } private void clear() { productions=new HashMap<NonTerminal,Set<Production>>(); start=null; size=0; productionsContaining=new HashMap<Symbol,Set<Production>>(); LESetsUptodate=true; lexicalElements=new HashSet<Symbol>(); nonterminals=new HashSet<NonTerminal>(); terminals=new HashSet<Terminal>(); } private void dprintln(String s) { if (DEBUG) System.out.println(this.getClass().getSimpleName()+": "+s); } public boolean addProduction(Production p) { if (!productions.containsKey(p.getHead())) { Set<Production> c=new HashSet<Production>(); productions.put(p.getHead(),c); } else if (productions.get(p.getHead()).contains(p)) { dprintln(" filtering "+p+": already there"); return false; } productions.get(p.getHead()).add(p); updateLESetsProduction(p); /* Maintain productionsContaining */ for (Symbol e: p.getBody()) { if (!productionsContaining.containsKey(e)) { Set<Production> c=new HashSet<Production>(); productionsContaining.put(e,c); } productionsContaining.get(e).add(p); } size++; return true; } public void setStart(NonTerminal s) { start=s; } public NonTerminal getStart() { return start; } public Collection<Production> getProductions() { Collection<Production> prods=new LinkedList<Production>(); for (Collection<Production> c: productions.values()) prods.addAll(c); return prods; } public Collection<Production> getProductionsOf(NonTerminal n) { return productions.containsKey(n) ? new ArrayList<Production>(productions.get(n)) : new ArrayList<Production>(0); } public Collection<Production> getProductionsContaining(Symbol e) { return productionsContaining.containsKey(e) ? new ArrayList<Production>(productionsContaining.get(e)) : new ArrayList<Production>(0); } public boolean removeProduction(Production prod) { Set<Production> prodSet; prodSet=productions.get(prod.getHead()); if (prodSet == null) return false; if (!prodSet.remove(prod)) return false; if (prodSet.size() == 0) productions.remove(prod.getHead()); size--; LESetsUptodate=false; /* Maintain productionsContaining */ for (Symbol e: prod.getBody()) productionsContaining.get(e).remove(prod); return true; } public int size() { return size; } private void updateLESetsProduction(Production prod) { lexicalElements.add(prod.getHead()); nonterminals.add(prod.getHead()); for (Symbol e: prod.getBody()) { if (e instanceof NonTerminal) nonterminals.add((NonTerminal)e); else if (e instanceof Terminal) terminals.add((Terminal)e); lexicalElements.add(e); } } private void updateLESets() { if (LESetsUptodate) return; lexicalElements.clear(); nonterminals.clear(); terminals.clear(); for (Collection<Production> c: productions.values()) for (Production p: c) updateLESetsProduction(p); } public Collection<Symbol> getSymbols() { updateLESets(); return lexicalElements; } public Collection<Terminal> getTerminals() { updateLESets(); return terminals; } public Collection<NonTerminal> getNonTerminals() { updateLESets(); return nonterminals; } public boolean hasUniqueStart() { return getProductionsOf(start).size() == 1; } @Override public String toString() { String s; if (start == null) s="Grammar has no start non-terminal defined!\n"; else s="Start: "+start.toString()+"\n"; for (Production p: getProductions()) s+=p.toString()+"\n"; return s; } public Cfg clone() { return new Cfg(start,getProductions()); } }
5,848
22.396
79
java
gluon
gluon-master/src/main/java/gluon/grammar/transform/CfgOptimizer.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar.transform; import gluon.grammar.*; import java.util.*; public class CfgOptimizer { private static final boolean DEBUG=false; private CfgOptimizer() { assert false; } private static void dprintln(String s) { if (DEBUG) System.out.println("CfgOptimizer: "+s); } private static void replace(Cfg grammar, NonTerminal nonterm, ArrayList<Symbol> string) { for (Production p: grammar.getProductionsContaining(nonterm)) { grammar.removeProduction(p); p.replace(nonterm,string); grammar.addProduction(p); } } /* If there exists * * B → X (where X may be multiple symbols, and X does not contain B) * B ↛ Y (where Y ≠ X) * * remove B → X and replace every B with X. * * Returns true if the grammar was modified. */ private static boolean removeDirectReductions(Cfg grammar) { boolean modified=false; for (NonTerminal nonterm: grammar.getNonTerminals()) { Collection<Production> prodsOf; Production prod; if (nonterm.equals(grammar.getStart())) continue; prodsOf=grammar.getProductionsOf(nonterm); if (prodsOf.size() != 1) continue; prod=prodsOf.iterator().next(); if (prod.getHead().noRemove()) continue; /* Contains a loop (A → αAβ) */ if (prod.getBody().contains(nonterm)) continue; grammar.removeProduction(prod); replace(grammar,nonterm,prod.getBody()); modified=true; } return modified; } /* Remove production of the form * * A → A * * Returns true if the grammar was modified. */ private static boolean removeDirectLoops(Cfg grammar) { boolean modified=false; for (Production p: grammar.getProductions()) if (p.isDirectLoop()) if (grammar.removeProduction(p)) modified=true; return modified; } private static boolean addNonTerminalsToQueue(Production prod, Queue<NonTerminal> queue, Set<NonTerminal> enqueued, Set<NonTerminal> terminalGenerators) { /* Generates the empty word */ if (prod.getBody().size() == 0) { terminalGenerators.add(prod.getHead()); return true; } for (Symbol s: prod.getBody()) { NonTerminal nonterm; if (s instanceof Terminal) { terminalGenerators.add(prod.getHead()); return true; } assert s instanceof NonTerminal; nonterm=(NonTerminal)s; if (terminalGenerators.contains(s)) return true; if (!enqueued.contains(nonterm)) { queue.add(nonterm); enqueued.add(nonterm); } } return false; } private static boolean productionGenerateWord(Cfg grammar, Production prod, Set<NonTerminal> terminalGenerators) { Queue<NonTerminal> queue=new LinkedList<NonTerminal>(); Set<NonTerminal> enqueued=new HashSet<NonTerminal>(); if (addNonTerminalsToQueue(prod,queue,enqueued,terminalGenerators)) return true; while (queue.size() > 0) { NonTerminal nonterm=queue.poll(); for (Production p: grammar.getProductionsOf(nonterm)) if (addNonTerminalsToQueue(p,queue,enqueued,terminalGenerators)) return true; } return false; } private static boolean removeImproductiveProductions(Cfg grammar) { List<Production> toRemove=new LinkedList<Production>(); Set<NonTerminal> terminalGenerators=new HashSet<NonTerminal>(); for (Production p: grammar.getProductions()) if (!productionGenerateWord(grammar,p,terminalGenerators)) toRemove.add(p); for (Production p: toRemove) grammar.removeProduction(p); return toRemove.size() > 0; } public static Cfg optimize(Cfg grammar) { Cfg grammarOpt=grammar.clone(); boolean modified; dprintln("Grammar size start: "+grammarOpt.size()); do { modified=removeImproductiveProductions(grammarOpt); if (removeDirectReductions(grammarOpt)) modified=true; if (removeDirectLoops(grammarOpt)) modified=true; dprintln("Grammar size iterating: "+grammarOpt.size()); } while (modified); dprintln("Grammar size end: "+grammarOpt.size()); return grammarOpt; } }
5,834
26.013889
86
java
gluon
gluon-master/src/main/java/gluon/grammar/transform/CfgSubwords.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar.transform; import gluon.grammar.Cfg; import gluon.grammar.NonTerminal; import gluon.grammar.Production; import gluon.grammar.Symbol; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class CfgSubwords { private static final boolean DEBUG=false; private CfgSubwords() { assert false; } private static void dprintln(String s) { if (DEBUG) System.out.println("CfgSubwords: "+s); } private static Collection<ArrayList<Symbol>> getPrefixes(ArrayList<Symbol> body) { Collection<ArrayList<Symbol>> prefixes =new LinkedList<ArrayList<Symbol>>(); for (int i=1; i <= body.size(); i++) { ArrayList<Symbol> pre=new ArrayList<Symbol>(i); Symbol last; for (int j=0; j < i-1; j++) pre.add(body.get(j)); if (body.get(i-1) instanceof NonTerminal) { last=body.get(i-1).clone(); ((NonTerminal)last).setName(last.getName()+"<"); } else { last=body.get(i-1); prefixes.add(new ArrayList<Symbol>(pre)); } pre.add(last); prefixes.add(pre); } // Add empty production prefixes.add(new ArrayList<Symbol>()); return prefixes; } private static void addPrefixes(Cfg grammar, Collection<Production> prods) { for (Production p: prods) { NonTerminal newProdHead=p.getHead().clone(); newProdHead.setName(newProdHead.getName()+"<"); dprintln("prefixes of "+p+":"); for (ArrayList<Symbol> pre: getPrefixes(p.getBody())) { Production preProd=new Production(newProdHead,pre); dprintln(" "+preProd); grammar.addProduction(preProd); } dprintln(""); } } private static Collection<ArrayList<Symbol>> getSuffixes(ArrayList<Symbol> body) { Collection<ArrayList<Symbol>> suffixes =new LinkedList<ArrayList<Symbol>>(); for (int i=body.size(); i >= 1; i--) { ArrayList<Symbol> suff=new ArrayList<Symbol>(i); Symbol first; if (body.get(i-1) instanceof NonTerminal) { first=body.get(i-1).clone(); ((NonTerminal)first).setName(first.getName()+">"); } else { List<Symbol> l=body.subList(i,body.size()); suffixes.add(new ArrayList<Symbol>(l)); first=body.get(i-1); } suff.add(first); for (int j=i; j < body.size(); j++) suff.add(body.get(j)); suffixes.add(suff); } // Add empty production suffixes.add(new ArrayList<Symbol>()); return suffixes; } private static void addSuffixes(Cfg grammar, Collection<Production> prods) { for (Production p: prods) { NonTerminal newProdHead=p.getHead().clone(); newProdHead.setName(newProdHead.getName()+">"); dprintln("suffixes of "+p+":"); for (ArrayList<Symbol> suff: getSuffixes(p.getBody())) { Production suffProd=new Production(newProdHead,suff); dprintln(" "+suffProd); grammar.addProduction(suffProd); } dprintln(""); } } private static void getSubwords(List<Symbol> body, Collection<ArrayList<Symbol>> subwords) { for (int i=0; i <= body.size(); i++) { ArrayList<Symbol> left; ArrayList<Symbol> right; Collection<ArrayList<Symbol>> leftSuffs; Collection<ArrayList<Symbol>> rightPres; left=new ArrayList<Symbol>(body.subList(0,i)); right=new ArrayList<Symbol>(body.subList(i,body.size())); leftSuffs=getSuffixes(left); rightPres=getPrefixes(right); for (ArrayList<Symbol> leftSuff: leftSuffs) for (ArrayList<Symbol> rightPre: rightPres) { ArrayList<Symbol> sub =new ArrayList<Symbol>(leftSuff.size() +rightPre.size()); sub.addAll(leftSuff); sub.addAll(rightPre); subwords.add(sub); } } for (int i=0; i < body.size(); i++) { ArrayList<Symbol> sub=new ArrayList<Symbol>(1); NonTerminal e; if (!(body.get(i) instanceof NonTerminal)) continue; e=(NonTerminal)body.get(i).clone(); e.setName(e.getName()+"<>"); sub.add(e); subwords.add(sub); } // Add empty production (if the size is non zero there must be already // something that derives the empty word) if (body.size() == 0) subwords.add(new ArrayList<Symbol>(0)); for (int i=0; i < body.size(); i++) for (int j=i+1; j <= body.size(); j++) if (!(i == 0 && j == body.size())) getSubwords(body.subList(i,j),subwords); } private static Collection<ArrayList<Symbol>> getSubwords(List<Symbol> body) { Collection<ArrayList<Symbol>> subwords =new LinkedList<ArrayList<Symbol>>(); getSubwords(body,subwords); return subwords; } private static void addSubwords(Cfg grammar, Collection<Production> prods) { for (Production p: prods) { NonTerminal newProdHead=p.getHead().clone(); newProdHead.setName(newProdHead.getName()+"<>"); dprintln("subwords of "+p+":"); for (ArrayList<Symbol> sub: getSubwords(p.getBody())) { Production subProd=new Production(newProdHead,sub); dprintln(" "+subProd); grammar.addProduction(subProd); } dprintln(""); } } /* * For each nonterminal X, add 3 new ones X< , X> , X<>. * * The idea is that X< will generate all prefixes of strings generated * by X; X> will generate all suffixes, and X<> will generate all * substrings. * * The new start symbol will be S<> . * * If the original grammar has a rule X → Y Z, then the new grammar will * have: * * X< → Y< | Y Z< * X> → Z> | Y> Z * X<> → Y> Z< | Y<> | Z<> * * From http://www.reddit.com/r/compsci/comments/1drkvk/ \ * are_contextfree_languages_closed_under_subwords/ */ public static void subwordClosure(Cfg grammar) { Collection<Production> prods=grammar.getProductions(); NonTerminal newStart; addPrefixes(grammar,prods); addSuffixes(grammar,prods); addSubwords(grammar,prods); newStart=grammar.getStart().clone(); newStart.setName(newStart.getName()+"<>"); grammar.setStart(newStart); } public static Cfg subwordGfg(Cfg grammar) { Cfg subwordGrammar=grammar.clone(); subwordClosure(subwordGrammar); return subwordGrammar; } }
8,224
26.508361
78
java
gluon
gluon-master/src/main/java/gluon/grammar/transform/CfgRemoveEpsilons.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.grammar.transform; import gluon.grammar.Cfg; import gluon.grammar.NonTerminal; import gluon.grammar.Production; import gluon.grammar.Symbol; import java.util.*; public class CfgRemoveEpsilons { private static final boolean DEBUG=false; private CfgRemoveEpsilons() { assert false; } private static void dprintln(String s) { if (DEBUG) System.out.println("CfgOptimizer: "+s); } private static Collection<ArrayList<Symbol>> getCombinations(List<Symbol> original, NonTerminal E) { Collection<ArrayList<Symbol>> combinations =new ArrayList<ArrayList<Symbol>>(8); if (original.size() == 0) combinations.add(new ArrayList<Symbol>(0)); else if (original.get(0).equals(E)) { List<Symbol> tail=original.subList(1,original.size()); for (ArrayList<Symbol> c: getCombinations(tail,E)) { ArrayList<Symbol> Ec; combinations.add(c); Ec=new ArrayList<Symbol>(c.size()+1); Ec.add(E); Ec.addAll(c); combinations.add(Ec); } } else { Symbol head=original.get(0); List<Symbol> tail=original.subList(1,original.size()); for (ArrayList<Symbol> c: getCombinations(tail,E)) { ArrayList<Symbol> Hc=new ArrayList<Symbol>(c.size()+1); Hc.add(head); Hc.addAll(c); combinations.add(Hc); } } return combinations; } /* Remove an epsilon production while preserving the same language. * * If we have * * A → aEbEc * E → ε * E → d * * will be changed to * * A → aEbEc * A → aEbc * A → abEc * A → abc * E → d. * * If there is no alternatives in E only "A → abc" will be added. * * Removed is important because we cannot add an epsilon production which * was already removed, otherwise we can loop forever. */ private static void removeEpsilonProduction(Cfg grammar, Production prod, Set<Production> removed) { NonTerminal E=prod.getHead(); boolean EHasAlternatives; assert prod.bodyLength() == 0; grammar.removeProduction(prod); dprintln("removed "+prod); removed.add(prod); EHasAlternatives=grammar.getProductionsOf(E).size() > 0; for (Production p: grammar.getProductionsContaining(E)) { NonTerminal A=p.getHead(); assert p.getBody().contains(E); /* p is A → aEbEc */ grammar.removeProduction(p); dprintln(" removed "+p); if (EHasAlternatives) { for (ArrayList<Symbol> symbs: getCombinations(p.getBody(),E)) { Production newP=new Production(A,symbs); if (!removed.contains(newP) && !newP.isDirectLoop()) { grammar.addProduction(newP); dprintln(" added "+newP); } } } else { Production pStripped=p.clone(); pStripped.replace(E,new ArrayList<Symbol>(0)); if (!removed.contains(pStripped) && !pStripped.isDirectLoop()) { grammar.addProduction(pStripped); dprintln(" added "+pStripped); } } } } private static Production getEpsilonProduction(Cfg grammar) { for (Production p: grammar.getProductions()) if (p.bodyLength() == 0) return p; return null; } /* Warning: If grammar generates the empty word removeEpsilons(grammar) * will *not* have the empty word. */ public static Cfg removeEpsilons(Cfg grammar) { Cfg grammarClean=grammar.clone(); Production prod; Set<Production> removed=new HashSet<Production>(); while ((prod=getEpsilonProduction(grammarClean)) != null) removeEpsilonProduction(grammarClean,prod,removed); return grammarClean; } }
5,134
26.607527
77
java
gluon
gluon-master/src/main/java/gluon/analysis/pointsTo/PointsToInformation.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.pointsTo; import soot.*; import soot.jimple.spark.pag.AllocNode; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import soot.jimple.spark.sets.DoublePointsToSet; import soot.jimple.spark.sets.P2SetVisitor; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; public class PointsToInformation { private PointsToInformation() { assert false; } public static boolean isModuleInstance(Type module, Type obj) { Type leastCommonType; try { leastCommonType=module.merge(obj,Scene.v()); } catch (Exception e) { return false; } return leastCommonType.equals(module); } public static Collection<AllocNode> getModuleAllocationSites(SootClass module) { Collection<AllocNode> allocSites=new LinkedList<AllocNode>(); PointsToAnalysis pta=Scene.v().getPointsToAnalysis(); PAG pag; Iterator it; assert pta instanceof PAG; pag=(PAG)pta; for (it=pag.getAllocNodeNumberer().iterator(); it.hasNext(); ) { AllocNode an=(AllocNode)it.next(); if (isModuleInstance(module.getType(),an.getType())) allocSites.add(an); } return allocSites; } public static Collection<AllocNode> getReachableAllocSites(Local l) { final Collection<AllocNode> asites=new LinkedList<AllocNode>(); PointsToAnalysis pta; PointsToSet rObjs; DoublePointsToSet reacObjs; pta=Scene.v().getPointsToAnalysis(); rObjs=pta.reachingObjects(l); if (!(rObjs instanceof DoublePointsToSet)) return asites; reacObjs=(DoublePointsToSet)rObjs; reacObjs.forall( new P2SetVisitor() { public final void visit(Node n) { if (n instanceof AllocNode) asites.add((AllocNode)n); } } ); return asites; } }
2,851
27.52
82
java
gluon
gluon-master/src/main/java/gluon/analysis/atomicity/AtomicityAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.atomicity; import gluon.WordInstance; import gluon.analysis.programBehavior.PBNonTerminal; import gluon.grammar.Cfg; import gluon.grammar.NonTerminal; import gluon.grammar.Production; import gluon.grammar.Symbol; import soot.SootMethod; import soot.tagkit.AnnotationTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; import java.util.*; class NonTermAtomicity { public final PBNonTerminal nonterm; public final boolean reachedAtomically; public NonTermAtomicity(PBNonTerminal nont, boolean ra) { nonterm=nont; reachedAtomically=ra; } @Override public int hashCode() { return nonterm.hashCode()^(reachedAtomically ? 0 : 0x6d24f632); } @Override public boolean equals(Object o) { NonTermAtomicity other; if (!(o instanceof NonTermAtomicity)) return false; other=(NonTermAtomicity)o; return reachedAtomically == other.reachedAtomically && nonterm.equals(other.nonterm); } } public class AtomicityAnalysis { private static final String ATOMIC_METHOD_ANNOTATION="Atomic"; private Cfg grammar; private final Map<NonTerminal,Boolean> nontermsAtomicity; public AtomicityAnalysis(Cfg grammar) { int nonterms=2*grammar.getNonTerminals().size(); this.grammar=grammar; this.nontermsAtomicity=new HashMap<NonTerminal,Boolean>(nonterms); } public static boolean isAtomicAnnotated(SootMethod method) { Tag tag=method.getTag("VisibilityAnnotationTag"); if (tag == null) return false; VisibilityAnnotationTag visibilityAnnotationTag=(VisibilityAnnotationTag)tag; List<AnnotationTag> annotations=visibilityAnnotationTag.getAnnotations(); for (AnnotationTag annotationTag: annotations) if (annotationTag.getType().endsWith("/"+ATOMIC_METHOD_ANNOTATION+";")) return true; return false; } public void analyze() { Queue<NonTermAtomicity> queue=new LinkedList<NonTermAtomicity>(); Set<NonTermAtomicity> enqueued=new HashSet<NonTermAtomicity>(); NonTermAtomicity start; assert !((PBNonTerminal)grammar.getStart()).isAtomic() : "The start symbol should be artificial."; start=new NonTermAtomicity((PBNonTerminal)grammar.getStart(),false); queue.add(start); enqueued.add(start); while (queue.size() > 0) { NonTermAtomicity nonterma=queue.poll(); PBNonTerminal nonterm=nonterma.nonterm; boolean reachedAtomically=nonterma.reachedAtomically; if (!nontermsAtomicity.containsKey(nonterm)) nontermsAtomicity.put(nonterm,reachedAtomically); else nontermsAtomicity.put(nonterm, nontermsAtomicity.get(nonterm) && reachedAtomically); for (Production p: grammar.getProductionsOf(nonterm)) for (Symbol s: p.getBody()) { PBNonTerminal n; NonTermAtomicity succ; if (!(s instanceof PBNonTerminal)) continue; n=(PBNonTerminal)s; succ=new NonTermAtomicity(n,reachedAtomically || n.isAtomic()); if (!enqueued.contains(succ)) { queue.add(succ); enqueued.add(succ); } } } } public boolean isAtomic(WordInstance word) { assert word.getLCA() != null; assert nontermsAtomicity.containsKey(word.getLCA()); return isAtomicAnnotated(word.getLCAMethod()) || word.getLCAMethod().isSynchronized() || nontermsAtomicity.get(word.getLCA()); } }
4,655
29.03871
134
java
gluon
gluon-master/src/main/java/gluon/analysis/programBehavior/PBNonTerminal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.programBehavior; import soot.SootMethod; public class PBNonTerminal extends gluon.grammar.NonTerminal { private SootMethod method; private boolean noRemove; private boolean atomic; public PBNonTerminal(String s, SootMethod m) { super(s); method=m; noRemove=false; atomic=false; } public SootMethod getMethod() { return method; } public void setNoRemove() { noRemove=true; } public void setAtomic() { atomic=true; } public boolean isAtomic() { assert !atomic || noRemove; return atomic; } @Override public boolean noRemove() { assert !atomic || noRemove; return noRemove; } @Override public int hashCode() { return super.name.hashCode(); } @Override public boolean equals(Object o) { PBNonTerminal other; if (!(o instanceof PBNonTerminal)) return false; other=(PBNonTerminal)o; return other.name.equals(super.name); } @Override public PBNonTerminal clone() { PBNonTerminal clone=new PBNonTerminal(super.name,method); clone.noRemove=noRemove; clone.atomic=atomic; return clone; } }
1,997
19.8125
71
java
gluon
gluon-master/src/main/java/gluon/analysis/programBehavior/PBTerminal.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.programBehavior; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.tagkit.LineNumberTag; import soot.tagkit.SourceFileTag; import java.util.ArrayList; import java.util.List; /* Represents a call to the module under analysis */ public class PBTerminal extends gluon.grammar.Terminal { private final SootMethod method; /* module's method */ private final Unit codeUnit; private SootMethod codeUnitMethod; /* arguments is null if the arguments are to be ignored. * An null argument represents an argument that should be ignored. */ private List<String> arguments; private String ret; /* null if not used */ public PBTerminal(SootMethod m, Unit u, SootMethod cUnitMethod) { super(m.getName()); method=m; codeUnit=u; arguments=null; ret=null; codeUnitMethod=cUnitMethod; } public PBTerminal(String s) { super(s); method=null; codeUnit=null; arguments=null; ret=null; codeUnitMethod=null; } public Unit getCodeUnit() { return codeUnit; } public SootMethod getCodeMethod() { return codeUnitMethod; } public SootClass getCodeClass() { return getCodeMethod().getDeclaringClass(); } public int getLineNumber() { assert codeUnit != null; LineNumberTag lineTag=(LineNumberTag)codeUnit.getTag("LineNumberTag"); int linenum=-1; if (lineTag != null) linenum=lineTag.getLineNumber(); return linenum; } public String getSourceFile() { assert method != null; String source="?"; SootClass c=getCodeClass(); SourceFileTag sourceTag=(SourceFileTag)c.getTag("SourceFileTag"); if (sourceTag != null) source=sourceTag.getSourceFile(); return source; } public List<String> getArguments() { return arguments; } public void addArgument(String arg) { if (arguments == null) arguments=new ArrayList<String>(16); arguments.add(arg); } public String getReturn() { return ret; } public void setReturn(String r) { ret=r; } public String getFullName() { String str=getName(); if (arguments != null) { int i=0; str+="("; for (String v: arguments) str+=(i++ == 0 ? "" : ",")+(v == null ? "_" : v); str+=")"; } return (ret != null ? ret+"=" : "")+str; } @Override public boolean isEOI() { return false; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object o) { PBTerminal other; if (!(o instanceof PBTerminal)) return false; other=(PBTerminal)o; return other.name.equals(super.name); } @Override public PBTerminal clone() { PBTerminal clone=method != null ? new PBTerminal(method,codeUnit,codeUnitMethod) : new PBTerminal(super.getName()); clone.arguments=new ArrayList<String>(arguments.size()); clone.arguments.addAll(arguments); clone.ret=ret; assert clone.codeUnitMethod == codeUnitMethod; return clone; } }
4,140
21.144385
88
java
gluon
gluon-master/src/main/java/gluon/analysis/programBehavior/ClassBehaviorAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.programBehavior; import gluon.grammar.Cfg; import gluon.grammar.Production; import gluon.grammar.transform.CfgOptimizer; import gluon.grammar.transform.CfgRemoveEpsilons; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.spark.pag.AllocNode; import java.util.Collection; import java.util.HashSet; public class ClassBehaviorAnalysis extends BehaviorAnalysis { private SootClass classA; public ClassBehaviorAnalysis(SootClass c, SootClass modClass, AllocNode aSite, Collection<String> contract) { super(modClass,aSite,contract); classA=c; } /* For conservative points-to analisys */ public ClassBehaviorAnalysis(SootClass c, SootClass modClass, Collection<String> contract) { super(modClass,contract); classA=c; } @Override protected void foundMethodCall(SootMethod method) { } @Override protected boolean ignoreMethodCall(SootMethod method) { /* We are doing class-scope analysis so only calls inside the same class * are taken into account. */ return !method.getDeclaringClass().equals(classA); } public static Cfg emptyGrammar() { Cfg grammar=new Cfg(); Production prod=new Production(new PBNonTerminal("S",null)); grammar.addProduction(prod); grammar.setStart(new PBNonTerminal("S",null)); return grammar; } @Override public void analyze() { gluon.profiling.Timer.start("analysis-behavior"); assert classA.getMethodCount() > 0; assert !classA.equals(super.module); super.visited=new HashSet<Unit>(); for (SootMethod m: classA.getMethods()) if (m.hasActiveBody()) { PBNonTerminal nonterm; Production production; nonterm=super.analyzeMethod(m); production=new Production(new PBNonTerminal("S'",null)); production.appendToBody(nonterm); super.grammar.addProduction(production); } super.visited=null; if (grammar.size() == 0) { super.grammar=emptyGrammar(); gluon.profiling.Timer.stop("analysis-behavior"); return; } super.grammar.setStart(new PBNonTerminal("S'",null)); gluon.profiling.Timer.start("grammar-rm-epsilon"); super.grammar=CfgRemoveEpsilons.removeEpsilons(super.grammar); gluon.profiling.Timer.stop("grammar-rm-epsilon"); gluon.profiling.Timer.start("grammar-opt"); super.grammar=CfgOptimizer.optimize(super.grammar); gluon.profiling.Timer.stop("grammar-opt"); super.addNewStart(); super.dprintln("Grammar: "+super.grammar); assert super.grammar.hasUniqueStart(); gluon.profiling.Timer.stop("analysis-behavior"); } }
3,675
26.848485
82
java
gluon
gluon-master/src/main/java/gluon/analysis/programBehavior/WholeProgramBehaviorAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.programBehavior; import gluon.grammar.transform.CfgOptimizer; import gluon.grammar.transform.CfgRemoveEpsilons; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.spark.pag.AllocNode; import java.util.*; public class WholeProgramBehaviorAnalysis extends BehaviorAnalysis { private SootMethod entryMethod; private Queue<SootMethod> methodQueue; /* queue of methods to analyse */ private Set<SootMethod> enqueuedMethods; public WholeProgramBehaviorAnalysis(SootMethod thread, SootClass modClass, AllocNode aSite, Collection<String> contract) { super(modClass,aSite,contract); entryMethod=thread; methodQueue=null; enqueuedMethods=null; } private void analyzeReachableMethods(SootMethod entryMethod) { super.visited=new HashSet<Unit>(); methodQueue=new LinkedList<SootMethod>(); enqueuedMethods=new HashSet<SootMethod>(); methodQueue.add(entryMethod); enqueuedMethods.add(entryMethod); while (methodQueue.size() > 0) { SootMethod method=methodQueue.poll(); super.analyzeMethod(method); } enqueuedMethods=null; methodQueue=null; super.visited=null; } @Override protected void foundMethodCall(SootMethod method) { if (!enqueuedMethods.contains(method) && method.hasActiveBody()) { methodQueue.add(method); enqueuedMethods.add(method); } } @Override protected boolean ignoreMethodCall(SootMethod method) { /* We are doing whole program analysis so every call is taken * into account. */ return false; } @Override public void analyze() { gluon.profiling.Timer.start("analysis-behavior"); analyzeReachableMethods(entryMethod); super.grammar.setStart(new PBNonTerminal(super.alias(entryMethod),entryMethod)); gluon.profiling.Timer.start("grammar-rm-epsilon"); super.grammar=CfgRemoveEpsilons.removeEpsilons(super.grammar); gluon.profiling.Timer.stop("grammar-rm-epsilon"); gluon.profiling.Timer.start("grammar-opt"); super.grammar=CfgOptimizer.optimize(super.grammar); gluon.profiling.Timer.stop("grammar-opt"); super.addNewStart(); super.dprintln("Grammar: "+super.grammar); assert super.grammar.hasUniqueStart(); gluon.profiling.Timer.stop("analysis-behavior"); } }
3,314
27.333333
88
java
gluon
gluon-master/src/main/java/gluon/analysis/programBehavior/BehaviorAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.programBehavior; /* This analysis creates a grammar that describes the access patterns to * to the module under analysis. * * The grammar is extracted from the flow control graph. Its terminals are * the methods of the module we are analyzing. */ import gluon.analysis.atomicity.AtomicityAnalysis; import gluon.analysis.monitor.MonitorAnalysis; import gluon.analysis.pointsTo.PointsToInformation; import gluon.grammar.Cfg; import gluon.grammar.NonTerminal; import gluon.grammar.Production; import gluon.grammar.Symbol; import soot.*; import soot.jimple.*; import soot.jimple.spark.pag.AllocNode; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.UnitGraph; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; class NonTerminalAliasCreator { private static final char[] RADIX_CHARS ="ABCDEFGHIJKLMNOPQSRTUVWXYZ".toCharArray(); private static final int RADIX=RADIX_CHARS.length; private int counter; private Map<Object,Integer> map; public NonTerminalAliasCreator() { counter=0; map=new HashMap<Object,Integer>(); } private static String intToString(int n) { String r=""; do { r=RADIX_CHARS[n%RADIX]+r; n/=RADIX; } while (n > 0); return r; } public String makeAlias(Object o) { if (map.containsKey(o)) return intToString(map.get(o)); map.put(o,counter); return intToString(counter++); } public String freshAlias() { return intToString(counter++); } } public abstract class BehaviorAnalysis { private static final boolean DEBUG=false; protected SootClass module; /* module under analysis */ /* Allocation site of the "object" under analysis. * null if we are performing the analysis for a static module */ private AllocNode allocSite; protected Cfg grammar; private Collection<String> contract; protected Set<Unit> visited; private NonTerminalAliasCreator aliasCreator; private MonitorAnalysis monitorAnalysis; private boolean conservativePointsTo; public BehaviorAnalysis(SootClass modClass, AllocNode aSite, Collection<String> contract) { this.module=modClass; this.allocSite=aSite; this.grammar=new Cfg(); this.contract=contract; this.monitorAnalysis=null; this.visited=null; this.conservativePointsTo=false; this.aliasCreator=new NonTerminalAliasCreator(); } /* For conservative points-to analisys */ public BehaviorAnalysis(SootClass modClass, Collection<String> contract) { this(modClass,null,contract); conservativePointsTo=true; } protected void dprintln(String s) { if (DEBUG) System.out.println(this.getClass().getSimpleName()+": "+s); } /* Set the grammar generation to handle synchronized blocks. */ public void setSynchMode(MonitorAnalysis monAnalysis) { monitorAnalysis=monAnalysis; } public boolean isSynchMode() { return monitorAnalysis != null; } protected String alias(Object o) { return aliasCreator.makeAlias(o); } private enum ModCall { NEVER, SOMETIMES, ALWAYS } private ModCall invokeCallsModule(InvokeExpr expr) { SootMethod calledMethod=expr.getMethod(); if (calledMethod.isConstructor() || calledMethod.isPrivate()) return ModCall.NEVER; if (conservativePointsTo && expr instanceof InstanceInvokeExpr) { Value obj=((InstanceInvokeExpr)expr).getBase(); boolean isMod; isMod=PointsToInformation.isModuleInstance(module.getType(),obj.getType()); return isMod ? ModCall.SOMETIMES : ModCall.NEVER; } /* We only consider "modules" as instances from objects. * So a call to a static method of a class is not considered * a usage of a module. */ if (expr instanceof InstanceInvokeExpr) { Value obj=((InstanceInvokeExpr)expr).getBase(); boolean hasModule=false; Collection<AllocNode> allocSites=null; /* The object being called may be a local variable or a field */ if (obj instanceof Local) { Local l=(Local)obj; allocSites=PointsToInformation.getReachableAllocSites(l); for (AllocNode ac: allocSites) if (ac.equals(allocSite)) hasModule=true; } else if (obj instanceof SootField) { /* This might not need to be handled since it seems that * in jimple/shimple the fields are accessed through JimpleLocals. */ assert false : "Do we need to handle this?"; } assert allocSites != null; if (!hasModule) return ModCall.NEVER; return allocSites.size() == 1 ? ModCall.ALWAYS : ModCall.SOMETIMES; } else if (expr instanceof StaticInvokeExpr && allocSite == null) { SootClass base=((StaticInvokeExpr)expr).getMethod().getDeclaringClass(); return base.equals(module) ? ModCall.ALWAYS : ModCall.NEVER; } return ModCall.NEVER; } protected abstract void foundMethodCall(SootMethod method); protected abstract boolean ignoreMethodCall(SootMethod method); private void analyzeSuccessors(SootMethod method, UnitGraph cfg, Unit unit) { for (Unit succ: cfg.getSuccsOf(unit)) analyzeUnit(method,cfg,succ); } /* If we have the following CFG: * * A monstart * ↓ * B b * ↓ * ⋮ * ↓ * C monend * ↓ * D d * * We will generate: * * A → A@ D * A@ → B */ private void analyzeUnitEnterMonitor(SootMethod method, UnitGraph cfg, EnterMonitorStmt unit) { PBNonTerminal synchNonTerm=new PBNonTerminal(alias(unit)+"@",method); assert isSynchMode(); synchNonTerm.setNoRemove(); synchNonTerm.setAtomic(); /* Add A → A@ D */ for (ExitMonitorStmt exitmon: monitorAnalysis.getExitMonitor(unit)) { assert cfg.getSuccsOf(exitmon).size() > 0; for (Unit exitmonsucc: cfg.getSuccsOf(exitmon)) { PBNonTerminal head=new PBNonTerminal(alias(unit),method); Production production=new Production(head); production.appendToBody(synchNonTerm); production.appendToBody(new PBNonTerminal(alias(exitmonsucc), method)); grammar.addProduction(production); } } /* Add A@ → B */ for (Unit succ: cfg.getSuccsOf(unit)) { Production production=new Production(synchNonTerm); production.appendToBody(new PBNonTerminal(alias(succ),method)); grammar.addProduction(production); } analyzeSuccessors(method,cfg,unit); } /* An exitmonitor just reduce to ε. See analyzeUnitEnterMonitor() comment. */ private void analyzeUnitExitMonitor(SootMethod method, UnitGraph cfg, ExitMonitorStmt unit) { addUnitToEmptyProduction(unit,method); analyzeSuccessors(method,cfg,unit); } private void analyzeUnit(SootMethod method, UnitGraph cfg, Unit unit) { Symbol prodBodyPrefix=null; boolean addProdSkipPrefix=false; if (visited.contains(unit)) return; /* Unit already taken care of */ gluon.profiling.Profiling.inc("cfg-nodes"); visited.add(unit); if (isSynchMode()) { if (unit instanceof EnterMonitorStmt) { analyzeUnitEnterMonitor(method,cfg,(EnterMonitorStmt)unit); return; } else if (unit instanceof ExitMonitorStmt) { analyzeUnitExitMonitor(method,cfg,(ExitMonitorStmt)unit); return; } } if (((Stmt)unit).containsInvokeExpr()) { InvokeExpr expr=((Stmt)unit).getInvokeExpr(); SootMethod calledMethod=expr.getMethod(); switch (invokeCallsModule(expr)) { case NEVER: if (calledMethod.hasActiveBody() && (!calledMethod.isJavaLibraryMethod() || gluon.Main.WITH_JAVA_LIB)) { foundMethodCall(calledMethod); if (!ignoreMethodCall(calledMethod)) prodBodyPrefix=new PBNonTerminal(alias(calledMethod),method); } break; case SOMETIMES: addProdSkipPrefix=true; /* fall through */ case ALWAYS: if (contract.contains(calledMethod.getName())) prodBodyPrefix=new PBTerminal(calledMethod,unit,method); else { /* This module call does not belong to the contract but we * need to put a dummy terminal here, otherwise we may * introduce words in the grammar's language that cannot * be executed by the program: * * E.g. if the contract is "a b" and the program is * * m.a() m.foo() m.b() * * then we should not get a match, so we use a dummy * terminal "_" in place of "foo". * * The advantage of doing this is that the grammar can be * further optimized. */ prodBodyPrefix=new PBTerminal("_"); } break; } } assert addProdSkipPrefix ? prodBodyPrefix != null : true; PBNonTerminal prodHead=new PBNonTerminal(alias(unit),method); for (Unit succ: cfg.getSuccsOf(unit)) { PBNonTerminal succNonTerm=new PBNonTerminal(alias(succ),method); if (prodBodyPrefix == null || addProdSkipPrefix) addUnitToSymbol(unit,succNonTerm,method); if (prodBodyPrefix != null) addUnitToTwoSymbols(unit,prodBodyPrefix,succNonTerm, method); } if (cfg.getSuccsOf(unit).size() == 0) { assert prodBodyPrefix == null : "If we have no successors we " +"should be a return statement, and therefore have no method " +"calls"; addUnitToEmptyProduction(unit,method); } analyzeSuccessors(method,cfg,unit); } private void addUnitToTwoSymbols(Unit unit, Symbol body1, Symbol body2, SootMethod method) { PBNonTerminal head=new PBNonTerminal(alias(unit),method); Production production=new Production(head); production.appendToBody(body1); production.appendToBody(body2); grammar.addProduction(production); } private void addUnitToSymbol(Unit unit, Symbol body, SootMethod method) { PBNonTerminal head=new PBNonTerminal(alias(unit),method); Production production=new Production(head); production.appendToBody(body); grammar.addProduction(production); } private void addUnitToEmptyProduction(Unit unit, SootMethod method) { PBNonTerminal head=new PBNonTerminal(alias(unit),method); Production production=new Production(head); grammar.addProduction(production); } private void addMethodToHeadProduction(SootMethod method, Unit entryPoint) { PBNonTerminal head=new PBNonTerminal(alias(method),method); Production production=new Production(head); Symbol body=new PBNonTerminal(alias(entryPoint),method); head.setNoRemove(); if (isSynchMode()) { if (method.isSynchronized()) head.setAtomic(); } else { if (AtomicityAnalysis.isAtomicAnnotated(method)) head.setAtomic(); } production.appendToBody(body); grammar.addProduction(production); } /* Adds the patterns of method to grammar */ protected PBNonTerminal analyzeMethod(SootMethod method) { UnitGraph cfg; dprintln("Analyzing method "+method); assert method.hasActiveBody() : "No active body"; cfg=new BriefUnitGraph(method.getActiveBody()); assert cfg.getHeads().size() != 0 : "There are no entry points of the cfg of method "+method; for (Unit head: cfg.getHeads()) { addMethodToHeadProduction(method,head); analyzeUnit(method,cfg,head); } return new PBNonTerminal(alias(method),method); } public Cfg getGrammar() { assert grammar.getStart() != null : "analyze() must first be called"; return grammar; } protected void addNewStart() { NonTerminal oldStart=grammar.getStart(); NonTerminal newStart=new PBNonTerminal(oldStart.toString()+'\'', null); Production prod=new Production(newStart); prod.appendToBody(oldStart); grammar.addProduction(prod); grammar.setStart(newStart); } public abstract void analyze(); }
14,946
28.307843
87
java
gluon
gluon-master/src/main/java/gluon/analysis/thread/ThreadAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.thread; import soot.MethodOrMethodContext; import soot.SootMethod; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import java.util.*; public class ThreadAnalysis { private static final boolean DEBUG=false; private final CallGraph callGraph; private Collection<SootMethod> threadsEntryMethod; public ThreadAnalysis(CallGraph cg) { callGraph=cg; threadsEntryMethod=new LinkedList<SootMethod>(); } private void dprintln(String s) { if (DEBUG) System.out.println(this.getClass().getSimpleName()+": "+s); } private void analyzeEdge(Edge edge) { SootMethod m=edge.tgt(); if (edge.isThreadRunCall()) { threadsEntryMethod.add(m); dprintln("Found thread entry method: "+m.getSignature()); } } private void analyzeReachableMethods(SootMethod entryMethod) { Queue<SootMethod> methodQueue=new LinkedList<SootMethod>(); Set<SootMethod> enqueuedMethods=new HashSet<SootMethod>(2*callGraph.size()); methodQueue.add(entryMethod); enqueuedMethods.add(entryMethod); while (methodQueue.size() > 0) { SootMethod method=methodQueue.poll(); for (Iterator<Edge> it=callGraph.edgesOutOf(method); it.hasNext(); ) { Edge e=it.next(); SootMethod m=e.tgt(); assert m != null; if (enqueuedMethods.contains(m) || (!gluon.Main.WITH_JAVA_LIB && m.isJavaLibraryMethod())) continue; methodQueue.add(m); enqueuedMethods.add(m); analyzeEdge(e); } } } public void analyze() { gluon.profiling.Timer.start("analysis-threads"); for (Iterator<MethodOrMethodContext> it=callGraph.sourceMethods(); it.hasNext(); ) { MethodOrMethodContext mc=it.next(); SootMethod m; if (!(mc instanceof SootMethod)) continue; m=(SootMethod)mc; if (m.isMain()) { dprintln("Found main: "+m.getName()); threadsEntryMethod.add(m); analyzeReachableMethods(m); } } gluon.profiling.Timer.stop("analysis-threads"); } public Collection<SootMethod> getThreadsEntryMethod() { return threadsEntryMethod; } }
3,252
25.884298
84
java
gluon
gluon-master/src/main/java/gluon/analysis/valueEquivalence/ValueM.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.valueEquivalence; import soot.Value; import soot.SootMethod; import soot.Local; public class ValueM { private SootMethod method; private Value value; public ValueM(SootMethod m, Value v) { method=m; value=v; } public SootMethod getMethod() { return method; } public Value getValue() { return value; } public Local getValueAsLocal() { assert isLocal(); return (Local)value; } public boolean isLocal() { return value instanceof Local; } boolean basicEquivTo(Object o) { ValueM other; if (!(o instanceof ValueM)) return false; other=(ValueM)o; /* This case is not handled well by soot */ if (isLocal()) return method.getSignature().equals(other.method.getSignature()) && getValueAsLocal().getName().equals(other.getValueAsLocal().getName()); return value.equivTo(other.value); } @Override public boolean equals(Object o) { ValueM other; if (!(o instanceof ValueM)) return false; other=(ValueM)o; /* This case is not handled well by soot */ if (isLocal()) return method.getSignature().equals(other.method.getSignature()) && getValueAsLocal().getName().equals(other.getValueAsLocal().getName()); return value.equals(other.value); } @Override public int hashCode() { int vh; /* This case is not handled well by soot */ vh=isLocal() ? getValueAsLocal().getName().hashCode() : value.hashCode(); return vh^method.getSignature().hashCode(); } @Override public String toString() { return method.getName()+":"+value.toString(); } }
2,550
22.40367
89
java
gluon
gluon-master/src/main/java/gluon/analysis/valueEquivalence/ValueEquivAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.valueEquivalence; import gluon.analysis.pointsTo.PointsToInformation; import soot.*; import soot.jimple.ArrayRef; import soot.jimple.AssignStmt; import soot.jimple.FieldRef; import soot.jimple.spark.pag.AllocNode; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /* Since the fields assignments to local variables are only done (statically) * before they are used, and are using SSA we don't need a full data-flow * analysis. */ public class ValueEquivAnalysis { private Map<ValueM,Value> localAssigns; private Set<SootMethod> analizedMethods; public ValueEquivAnalysis() { localAssigns=new HashMap<ValueM,Value>(); analizedMethods=new HashSet<SootMethod>(); } private void analyzeMethod(SootMethod method) { if (!method.hasActiveBody()) return; if (analizedMethods.contains(method)) return; gluon.profiling.Timer.start("analysis-vequiv"); analizedMethods.add(method); for (Unit u: method.getActiveBody().getUnits()) if (u instanceof AssignStmt) { AssignStmt assign=(AssignStmt)u; Value l=assign.getLeftOp(); Value r=assign.getRightOp(); if (l instanceof Local) { ValueM local=new ValueM(method,l); assert !localAssigns.containsKey(local) : "localAssigns contains "+localAssigns.keySet() +" and we tried to add "+local+". Are we not using SSA?!"; localAssigns.put(local,r); assert localAssigns.containsKey(local); } } gluon.profiling.Timer.stop("analysis-vequiv"); } private boolean canPointToSameObject(ValueM u, ValueM v) { Local ul=u.getValueAsLocal(); Local vl=v.getValueAsLocal(); for (AllocNode a: PointsToInformation.getReachableAllocSites(ul)) for (AllocNode b: PointsToInformation.getReachableAllocSites(vl)) if (a.equals(b)) return true; return false; } private boolean containsSameField(ValueM u, ValueM v) { Value uValue; Value vValue; SootField uField; SootField vField; analyzeMethod(u.getMethod()); analyzeMethod(v.getMethod()); uValue=localAssigns.get(u); vValue=localAssigns.get(v); if (uValue == null || vValue == null || !(uValue instanceof FieldRef) || !(vValue instanceof FieldRef)) return false; uField=((FieldRef)uValue).getField(); vField=((FieldRef)vValue).getField(); return uField.getSignature().equals(vField.getSignature()); } private boolean containsSameArray(ValueM u, ValueM v) { Value uValue; Value vValue; Value uBase; Value vBase; analyzeMethod(u.getMethod()); analyzeMethod(v.getMethod()); uValue=localAssigns.get(u); vValue=localAssigns.get(v); if (uValue == null || vValue == null || !(uValue instanceof ArrayRef) || !(vValue instanceof ArrayRef)) return false; uBase=((ArrayRef)uValue).getBase(); vBase=((ArrayRef)vValue).getBase(); assert !(uBase instanceof ArrayRef) && !(vBase instanceof ArrayRef); return equivTo(new ValueM(u.getMethod(),uBase), new ValueM(v.getMethod(),vBase)); } public boolean equivTo(ValueM u, ValueM v) { if (u == null || v == null) return u == v; if (u.basicEquivTo(v)) return true; if (u.isLocal() && v.isLocal()) { if (canPointToSameObject(u,v)) return true; if (containsSameField(u,v)) return true; if (containsSameArray(u,v)) return true; } return false; } }
4,736
27.709091
83
java
gluon
gluon-master/src/main/java/gluon/analysis/monitor/MonitorAnalysis.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.analysis.monitor; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.EnterMonitorStmt; import soot.jimple.ExitMonitorStmt; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.UnitGraph; import java.util.*; class StackNode<E> { private StackNode<E> parent; private E element; public StackNode(StackNode<E> p, E elem) { parent=p; element=elem; } public StackNode<E> parent() { return parent; } public E element() { return element; } }; public class MonitorAnalysis { private final Scene scene; private Map<EnterMonitorStmt,Collection<ExitMonitorStmt>> exitMon; private Set<Unit> visited; public MonitorAnalysis(Scene s) { scene=s; visited=null; exitMon=new HashMap<EnterMonitorStmt,Collection<ExitMonitorStmt>>(); } private void analyzeUnit(SootMethod method, Unit unit, UnitGraph cfg, StackNode<EnterMonitorStmt> stack) { if (visited.contains(unit)) return; /* Unit already taken care of */ visited.add(unit); if (unit instanceof EnterMonitorStmt) stack=new StackNode<EnterMonitorStmt>(stack,(EnterMonitorStmt)unit); else if (unit instanceof ExitMonitorStmt && stack != null) { EnterMonitorStmt enter; enter=stack.element(); if (!exitMon.containsKey(enter)) exitMon.put(enter,new ArrayList<ExitMonitorStmt>(8)); exitMon.get(enter).add((ExitMonitorStmt)unit); stack=stack.parent(); } for (Unit succ: cfg.getSuccsOf(unit)) analyzeUnit(method,succ,cfg,stack); } public Collection<ExitMonitorStmt> getExitMonitor(EnterMonitorStmt enterMon) { assert exitMon.containsKey(enterMon); return exitMon.get(enterMon); } public void analyze() { visited=new HashSet<Unit>(); for (SootClass c: scene.getClasses()) if (!c.isJavaLibraryClass() || gluon.Main.WITH_JAVA_LIB) for (SootMethod m: c.getMethods()) { UnitGraph cfg; if (!m.hasActiveBody()) continue; cfg=new BriefUnitGraph(m.getActiveBody()); for (Unit head: cfg.getHeads()) analyzeUnit(m,head,cfg,null); } visited=null; } }
3,257
25.064
80
java
gluon
gluon-master/src/main/java/gluon/contract/Contract.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.contract; import gluon.Main; import gluon.analysis.programBehavior.PBTerminal; import gluon.contract.parsing.ContractVisitorExtractWords; import gluon.contract.parsing.node.Start; import gluon.grammar.Terminal; import soot.SootClass; import soot.SootMethod; import soot.tagkit.*; import java.io.PushbackReader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.HashSet; public class Contract { private static final boolean DEBUG=false; private static final String CONTRACT_ANNOTATION="Contract"; private SootClass module; // class of the module to analyze private Collection<List<Terminal>> contract; private Set<String> nonExistingMethods = new HashSet<>(); public Contract(SootClass mod, String rawContract) { module=mod; contract=null; loadRawContract(rawContract); } public Contract(SootClass mod) { module=mod; contract=null; } private void dprint(String s) { if (DEBUG) System.out.print(s); } private void dprintln(String s) { dprint(s+"\n"); } private Start parseContract(String clause) { PushbackReader reader=new PushbackReader(new StringReader(clause)); gluon.contract.parsing.lexer.Lexer lexer =new gluon.contract.parsing.lexer.Lexer(reader); gluon.contract.parsing.parser.Parser parser =new gluon.contract.parsing.parser.Parser(lexer); Start ast=null; try { ast=parser.parse(); } catch (gluon.contract.parsing.parser.ParserException pe) { Main.fatal("syntax error in contract: "+clause+": "+pe.getMessage()); } catch (gluon.contract.parsing.lexer.LexerException pe) { Main.fatal("syntax error in contract: "+clause+": "+pe.getMessage()); } catch (java.io.IOException e) { assert false : "this should not happen"; } assert ast != null; return ast; } private void loadRawContractClause(String clause) { Start ast; ContractVisitorExtractWords visitorWords =new ContractVisitorExtractWords(); ast=parseContract(clause); ast.apply(visitorWords); for (List<PBTerminal> word: visitorWords.getWords()) { List<Terminal> contractWord; for (PBTerminal t: word) if (module.declaresMethodByName(t.getName())) { try { SootMethod m=module.getMethodByName(t.getName()); if (t.getArguments() != null && t.getArguments().size() != m.getParameterCount()) Main.fatal(t.getName() +": wrong number of parameters!"); } catch (Exception e) { Main.warning(t.getName()+": ambiguous method!"); } } else nonExistingMethods.add(t.getName()); contractWord=new ArrayList<Terminal>(word.size()+1); contractWord.addAll(word); contract.add(contractWord); } } private void loadRawContract(String rawContract) { contract=new LinkedList<List<Terminal>>(); for (String clause: rawContract.split(";")) { clause=clause.trim(); if (clause.length() == 0) continue; loadRawContractClause(clause); } for (String method: nonExistingMethods) { System.out.println(method+" no such method!"); } System.out.println(); dprintln("contract: "+contract); } private String extractContractRaw() { Tag tag=module.getTag("VisibilityAnnotationTag"); if (tag == null) return null; VisibilityAnnotationTag visibilityAnnotationTag=(VisibilityAnnotationTag) tag; List<AnnotationTag> annotations=visibilityAnnotationTag.getAnnotations(); for (AnnotationTag annotationTag: annotations) { Collection<AnnotationElem> elements=annotationTag.getElems(); if (annotationTag.getType().endsWith("/"+CONTRACT_ANNOTATION+";") && elements.size() == 1) { AnnotationElem elem=elements.iterator().next(); if (elem instanceof AnnotationStringElem && elem.getName().equals("clauses")) { AnnotationStringElem e=(AnnotationStringElem)elem; return e.getValue(); } } } return null; } public void loadAnnotatedContract() { loadRawContract(extractContractRaw()); } public Collection<List<Terminal>> getWords() { return contract; } public int clauseNum() { return contract.size(); } }
5,881
27.143541
86
java
gluon
gluon-master/src/main/java/gluon/contract/parsing/ContractVisitorExtractWords.java
/* This file is part of Gluon. * * Gluon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gluon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gluon. If not, see <http://www.gnu.org/licenses/>. */ package gluon.contract.parsing; import gluon.analysis.programBehavior.PBTerminal; import gluon.contract.parsing.analysis.Analysis; import gluon.contract.parsing.node.*; import java.util.*; public class ContractVisitorExtractWords implements Analysis { private Map<Node,Collection<List<PBTerminal>>> words; private Node root; public ContractVisitorExtractWords() { root=null; words=new HashMap<Node,Collection<List<PBTerminal>>>(64); } @Override public void caseStart(Start node) { root=node.getPClause(); root.apply(this); } @Override public void caseAAltClause(AAltClause node) { List<List<PBTerminal>> w=new ArrayList<List<PBTerminal>>(16); node.getL().apply(this); node.getR().apply(this); w.addAll(words.get(node.getL())); w.addAll(words.get(node.getR())); words.put(node,w); } @Override public void caseAConcatClause(AConcatClause node) { List<List<PBTerminal>> w=new ArrayList<List<PBTerminal>>(16); node.getL().apply(this); node.getR().apply(this); for (List<PBTerminal> wl: words.get(node.getL())) for (List<PBTerminal> wr: words.get(node.getR())) { List<PBTerminal> wlr=new ArrayList<PBTerminal>(wl.size()+wr.size()); wlr.addAll(wl); wlr.addAll(wr); w.add(wlr); } words.put(node,w); } @Override public void caseAMethodClause(AMethodClause node) { List<List<PBTerminal>> w=new ArrayList<List<PBTerminal>>(1); List<PBTerminal> word=new ArrayList<PBTerminal>(1); String methodName=node.getMethod().getText(); PBTerminal term=new PBTerminal(methodName); for (TId varId: node.getId()) { String var=varId.getText(); if (var.equals("_")) term.addArgument(null); else term.addArgument(var); } if (node.getRet() != null) term.setReturn(node.getRet().getText()); word.add(term); w.add(word); words.put(node,w); } public Collection<List<PBTerminal>> getWords() { assert root != null && words.containsKey(root); return words.get(root); } @Override public void caseTLpar(TLpar node) { } @Override public void caseTRpar(TRpar node) { } @Override public void caseTAlt(TAlt node) { } @Override public void caseTConcat(TConcat node) { } @Override public void caseTComma(TComma node) { } @Override public void caseTEq(TEq node) { } @Override public void caseTId(TId node) { } @Override public void caseEOF(EOF node) { } @Override public void caseInvalidToken(InvalidToken node) { } @Override public Object getIn(Node node) { return null; } @Override public void setIn(Node node, Object o) { } @Override public Object getOut(Node node) { return null; } @Override public void setOut(Node node, Object o) { } }
3,808
23.733766
84
java
gluon
gluon-master/test/common/Atomic.java
package test.common; public @interface Atomic { }
51
7.666667
24
java
gluon
gluon-master/test/common/Contract.java
package test.common; public @interface Contract { String clauses(); }
75
9.857143
26
java
gluon
gluon-master/test/simple/atomic/Main.java
package test.simple.atomic; @interface Atomic { } class Module { public Module() {} public void a() {} public void b() {} } public class Main { private static Module m; private static void na() { } private static void a1() { na(); } private static void a0() { a1(); } @Atomic private static void f() { if (Math.random() == 23.0) return; m.a(); f(); a0(); m.b(); } public static void main(String[] args) { m=new Module(); f(); na(); } }
618
10.903846
42
java
gluon
gluon-master/test/simple/threads/Main.java
package test.simple.threads; class Module { public void modulemethod() { } } class TestThread extends Thread { private Module m; private void g() { run(); m.modulemethod(); } @Override public void run() { m=new Module(); g(); } } public class Main { public static void f() { f(); new TestThread().start(); } public static void main(String[] args) { f(); } }
492
10.738095
42
java
gluon
gluon-master/test/simple/exampleargssimple/Main.java
package test.simple.exampleargssimple; import test.common.Contract; @Contract(clauses="V=get(_) set(_,V);" +"get(K) set(K,_);") class Module { public Module() { } public int get(int k) { return 0; } public void set(int k, int v) { } } public class Main { private static Module m; public static void main(String[] args) { int a = 1; int b = 2; m = new Module(); // Violates `V=get(_) set(_,V)` int v = m.get(a); m.set(b, v); // Violates `get(K) set(K,_)`: int u = m.get(a); m.set(a, 2 * u); // Does not violate any clause: int t = m.get(a); m.set(b, 2 * t); } }
710
17.710526
42
java
gluon
gluon-master/test/simple/recursion2/Main.java
package test.simple.recursion2; import test.common.Contract; @Contract(clauses="a a b c;" +"b c;" +"b c c") class Module { public Module() { } public void a() { } public void b() { } public void c() { } } public class Main { private static Module m; private static void f(int c) { if (c%2 == 0) f(c-1); else if (c%4 == 0) { while (c%3 == 0) { m.a(); c++; f(c-1); } } else if (c%5 == 0) m.c(); else if (c%6 == 0) { m.b(); f(c+1); } } public static void main(String[] args) { m=new Module(); f(42); } }
796
15.604167
42
java
gluon
gluon-master/test/simple/flowControl/Main.java
package test.simple.flowControl; public class Main { public static Module m; public static boolean cond() { m.c(); return m == new Module(); } public static void main(String[] args) { m=new Module(); if (cond()) m.a(); else m.b(); while (cond()) m.d(); do { m.e(); } while (cond()); } }
441
13.258065
42
java
gluon
gluon-master/test/simple/flowControl/Module.java
package test.simple.flowControl; public class Module { public Module() { } public void a() { } public void b() { } public void c() { } public void d() { } public void e() { } public void f() { } public void g() { } }
321
7.702703
32
java
gluon
gluon-master/test/simple/basicAbcNonAtomic/Main.java
package test.simple.basicAbcNonAtomic; import test.common.Atomic; import test.common.Contract; @Contract(clauses ="a b c;" +"l l l l l l l l;" +"i1 i2;") class Module { public Module() {} public void a() {} public void b() {} public void c() {} public void l() {} public void i1() {} public void i2() {} } public class Main { private static Module m; @Atomic private static void f() { m.a(); m.b(); } @Atomic private static void g() { m.c(); } private static void q() { m.a(); m.b(); g(); } @Atomic private static void k() { q(); } @Atomic private static void foo() { m.i1(); m.i2(); } public static void main(String[] args) { m=new Module(); f(); g(); k(); m.a(); while (Math.random() < 0.5) m.l(); m.a(); if (Math.random() < 0.5) { m.i1(); m.i2(); } else { foo(); } } }
1,177
12.697674
42
java
gluon
gluon-master/test/simple/withoutParams/Main.java
package test.simple.withoutParams; import test.common.Contract; @Contract(clauses="indexOf remove;") class Module { public Module() {} public int indexOf() { return 0; } public void remove(int i) {} } public class Main { private static Module m; public static void main(String[] args) { m = new Module(); int j = 2; int i = m.indexOf(); m.remove(j); } }
415
16.333333
44
java
gluon
gluon-master/test/simple/recursion/Main.java
package test.simple.recursion; public class Main { public static Module m; public static void main(String[] args) { m=new Module(); m.a(); C.foo(m); m.b(); main(new String[0]); m.c(); } }
255
13.222222
42
java
gluon
gluon-master/test/simple/recursion/C.java
package test.simple.recursion; public class C { public static void foo(Module m) { m.d(); foo(m); m.e(); foo(m); m.f(); Main.main(new String[0]); m.g(); } }
226
13.1875
36
java
gluon
gluon-master/test/simple/recursion/Module.java
package test.simple.recursion; public class Module { public Module() { } public void a() { } public void b() { } public void c() { } public void d() { } public void e() { } public void f() { } public void g() { } }
319
7.648649
30
java
gluon
gluon-master/test/simple/auction/Bid.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class Bid implements Comparable<Bid> { public static final char PLACEHOLDER=':'; /* Placeholder for toString() and fromString() */ public static final char CLASS_TYPE='b'; /* For toString() and fromString() */ private int value; private Customer customer; public Bid(int value, Customer customer) { this.value=value; this.customer=customer; } /* Just for comparing purposes */ public Bid(int value) { this(value,null); } /* Useful to load a object fromString() */ public Bid() { this(0); } public int getValue() { return value; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer=customer; } public boolean isHigher(Bid other) { Main.m.h(); return compareTo(other) < 0; } public int compareTo(Bid other) { return value-other.value; } /* This should always keep symmetry with fromString() */ public String toString(String auctionName, String itemName) { Main.m.g(); return CLASS_TYPE+""+PLACEHOLDER+auctionName+PLACEHOLDER +itemName+PLACEHOLDER+customer.getName()+PLACEHOLDER +value; } /* pre: a valid objStr which must be in the same format as toString() * returns */ public void fromString(String objStr) { String[] tokens=objStr.split(PLACEHOLDER+""); value=Integer.parseInt(tokens[4]); } }
1,568
17.903614
72
java
gluon
gluon-master/test/simple/auction/Main.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ import java.util.Scanner; import java.io.PrintWriter; import java.io.FileReader; import java.io.File; public class Main { public static Module m=new Module(); private static final String PROMPT="> "; private static final String CMD_ADD_CUSTOMER="AC"; private static final String CMD_REPORT_CUSTOMERS="RC"; private static final String CMD_CREDIT_CUSTOMER="CC"; private static final String CMD_CREATE_AUCTION="CA"; private static final String CMD_OPEN_AUCTION="OA"; private static final String CMD_TERMINATE_AUCTION="TA"; private static final String CMD_ADD_ITEM="AI"; private static final String CMD_PLACE_BID="PB"; private static final String CMD_REPORT_AUCTION="RA"; private static final String CMD_HELP="H"; private static final String CMD_QUIT="Q"; private static final String MESSAGE_OK="OK" +System.getProperty("line.separator"); /* Comment in a possible script file */ private static final String COMMENT_PREFIX="#"; private static final String SAVE_FILEPATH="auctions.txt"; private static ArraySearchable<Customer> customers; private static ArraySearchable<Auction> auctions; private static void interpreterAddCustomer(Scanner in) { String name; int reputation; name=in.nextLine().trim(); reputation=in.nextInt(); in.nextLine(); if (customers.has(new Customer(name))) System.err.println("Customer "+name+" already created"); else { customers.append(new Customer(name,reputation)); System.out.print(MESSAGE_OK); } } private static void reportCustomers() { if (customers.size() == 0) System.out.println("There is no customer registered"); else System.out.println("Name\tBalance\tReputation\t"+ "Highest bid"); for (Iterator<Customer> it=customers.getIterator(); !it.end(); it.next()) { Customer customer=it.get(); Main.m.c(); System.out.println(customer.getName()+"\t" +customer.getBalance()+"\t" +customer.getReputation()+"\t\t" +customer.getHighestBid()); } } private static void interpreterCreditCustomer(Scanner in) { String name; int credit; Customer customer; name=in.nextLine().trim(); credit=in.nextInt(); in.nextLine(); customer=customers.search(new Customer(name)); if (customer == null) System.err.println("Customer "+name+" not registered"); else { customer.credit(credit); System.out.print(MESSAGE_OK); } } private static void interpreterCreateAuction(Scanner in) { String name; name=in.nextLine().trim(); if (auctions.has(new Auction(name))) System.err.println("Auction "+name+" already created"); else { auctions.append(new Auction(name)); System.out.print(MESSAGE_OK); } } private static void interpreterOpenAuction(Scanner in) { String name; Auction auction; name=in.nextLine().trim(); auction=auctions.search(new Auction(name)); if (auction == null || !auction.canOpen()) System.err.println("Auction "+name+" cannot be opened"); else { auction.open(); System.out.print(MESSAGE_OK); } } private static void interpreterTerminateAuction(Scanner in) { String name; Auction auction; name=in.nextLine().trim(); auction=auctions.search(new Auction(name)); if (auction == null || !auction.canTerminate()) System.err.println("Auction "+name+" not open"); else { auction.terminate(); System.out.print(MESSAGE_OK); } } private static void interpreterAddItem(Scanner in) { Auction auction; String auctionName; String itemName; String seller; int basePrice; auctionName=in.nextLine().trim(); itemName=in.nextLine().trim(); seller=in.nextLine().trim(); basePrice=in.nextInt(); in.nextLine(); auction=auctions.search(new Auction(auctionName)); if (auction == null) System.err.println("Auction "+auctionName +" not created"); else if (!auction.canAddItem()) System.err.println("Cannot insert item in running " +"or terminated auction"); else if (auction.hasItem(new AuctionItem(itemName))) System.err.println("Item already in this auction"); else { auction.addItem(new AuctionItem(itemName,seller, basePrice)); System.out.print(MESSAGE_OK); } Main.m.d(); } private static void interpreterPlaceBid(Scanner in) { Customer customer; Auction auction; AuctionItem item; String auctionName; String itemName; String customerName; int bidValue; auctionName=in.nextLine().trim(); itemName=in.nextLine().trim(); customerName=in.nextLine().trim(); bidValue=in.nextInt(); in.nextLine(); auction=auctions.search(new Auction(auctionName)); customer=customers.search(new Customer(customerName)); item=auction.getItem(new AuctionItem(itemName)); if (auction == null || !auction.canPlaceBid()) System.err.println("Auction "+auctionName +" not created or open"); else if (item == null) System.err.println("Item "+itemName+" " +"not for sale in this auction"); else if (customer == null) System.err.println("Customer "+customerName+" " +"not registered"); else if (!customer.isCredible()) System.err.println("Customer "+customerName+" does " +"not have enough credibility"); else if (customer.getBalance() < bidValue) { customer.reputationPenalty(); System.err.println("Customer "+customerName+" does " +"not have enough credit"); } else if (item.getHighestBid() != null && !item.getHighestBid().isHigher(new Bid(bidValue))) System.err.println("Customer "+customerName+" " +"does not cover the current " +"bidding of " +item.getHighestBid().getValue()+" " +"euros"); else if (bidValue < item.getBase()) System.err.println("Customer "+customerName +" does not cover the base" +" bidding price of " +item.getBase()+" " +"euros"); else { Bid bid=new Bid(bidValue,customer); Main.m.e(); /* Returns the money to the previous highest bidder */ if (item.getHighestBid() != null) item.getHighestBid().getCustomer().credit(item.getHighestBid().getValue()); customer.pay(bidValue); customer.setHighestBidIfHigher(bidValue); item.setHighestBid(bid); System.out.print(MESSAGE_OK); } } /* pre: auction.isTerminated() */ private static void reportAuction(Auction auction) { if (auction.numberOfItems() == 0) System.out.println("There is no items in auction " +auction.getName()); else System.out.println("Name\tSeller\tBuyer\t"+ "Sold price\tBids average"); auction.sortItems(); for (Iterator<AuctionItem> it=auction.getItemIterator(); !it.end(); it.next()) { AuctionItem item=it.get(); System.out.print(item.getName()+"\t" +item.getSeller()); Main.m.f(); if (item.sold()) { System.out.print("\t" +item.getHighestBid().getCustomer().getName()+"\t" +item.getHighestBid().getValue()+"\t\t" +item.getBidsMean()); Main.m.d(); } System.out.println(); } } private static void interpreterReportAuction(Scanner in) { String auctionName; Auction auction; auctionName=in.nextLine().trim(); auction=auctions.search(new Auction(auctionName)); if (auction == null || !auction.isTerminated()) System.err.println("Auction "+auctionName+" " +"not created or not closed"); else reportAuction(auction); } private static void printHelp() { System.out.println("Commands:"); System.out.println(); System.out.println(" "+CMD_ADD_CUSTOMER+", Add customer " +"(name, credit)"); System.out.println(" "+CMD_REPORT_CUSTOMERS +", Report customer"); System.out.println(" "+CMD_CREDIT_CUSTOMER +", Credit customer (name, credit)"); System.out.println(" "+CMD_CREATE_AUCTION +", Create auction (name)"); System.out.println(" "+CMD_OPEN_AUCTION +", Open auction (name)"); System.out.println(" "+CMD_TERMINATE_AUCTION +", Terminate auction (name)"); System.out.println(" "+CMD_ADD_ITEM +", Add item to an auction " +"(auction name, item name, sellers name, " +"base price)"); System.out.println(" "+CMD_PLACE_BID +", Place a bid on an item of an auction " +"(auction name, item name,"); /* To make sure the new line is align */ for (int i=0; i < CMD_PLACE_BID.length()+4; i++) System.out.print(" "); System.out.println("customer name, bid)"); System.out.println(" "+CMD_REPORT_AUCTION+", Report auction "+ "(name)"); System.out.println(" "+CMD_HELP+", Print this message"); System.out.println(" "+CMD_QUIT+", Quit the program"); } private static void interpreter() throws Exception { String cmd; Scanner in=new Scanner(System.in); do { System.out.print(PROMPT); /* This should be checked to prevent a exception if the * input stream is not stdin (in case of a pipe, for * example) or if the user inputs an EOF (C-D in * unix-line systems). */ if (in.hasNextLine()) { cmd=in.nextLine().trim(); cmd=cmd.toUpperCase(); } else cmd=CMD_QUIT; Main.m.h(); if (cmd.equals(CMD_HELP)) printHelp(); else if (cmd.equals(CMD_ADD_CUSTOMER)) interpreterAddCustomer(in); else if (cmd.equals(CMD_REPORT_CUSTOMERS)) reportCustomers(); else if (cmd.equals(CMD_CREDIT_CUSTOMER)) interpreterCreditCustomer(in); else if (cmd.equals(CMD_CREATE_AUCTION)) interpreterCreateAuction(in); else if (cmd.equals(CMD_OPEN_AUCTION)) interpreterOpenAuction(in); else if (cmd.equals(CMD_TERMINATE_AUCTION)) interpreterTerminateAuction(in); else if (cmd.equals(CMD_ADD_ITEM)) interpreterAddItem(in); else if (cmd.equals(CMD_PLACE_BID)) interpreterPlaceBid(in); else if (cmd.equals(CMD_REPORT_AUCTION)) interpreterReportAuction(in); else if (cmd.equals(CMD_QUIT)) save(SAVE_FILEPATH); else if (cmd.length() > 0 && !cmd.startsWith(COMMENT_PREFIX)) System.err.println(cmd+": Unknown command"); } while (!cmd.equals(CMD_QUIT)); in.close(); } private static void init() { customers=new ArraySearchable<Customer>(); auctions=new ArraySearchable<Auction>(); } private static void saveCustomers(PrintWriter o) { for (Iterator<Customer> it=customers.getIterator(); !it.end(); it.next()) o.println(it.get().toString()); } private static void saveAuctionItems(PrintWriter o, Auction auction) { for (Iterator<AuctionItem> it=auction.getItemIterator(); !it.end(); it.next()) { AuctionItem item=it.get(); Bid b=item.getHighestBid(); o.println(item.toString(auction.getName())); Main.m.e(); if (b != null) o.println(b.toString(auction.getName(), item.getName())); } } private static void saveAuctions(PrintWriter o) { for (Iterator<Auction> it=auctions.getIterator(); !it.end(); it.next()) { Auction auction=it.get(); o.println(auction.toString()); saveAuctionItems(o,auction); } } private static void save(String filepath) throws Exception { PrintWriter o=new PrintWriter(filepath); /* Warning: don't change this order, see loadBid() */ saveCustomers(o); saveAuctions(o); o.close(); } private static void loadCustomer(String objStr) { Customer c=new Customer(); c.fromString(objStr); customers.append(c); } private static void loadAuction(String objStr) { Auction a=new Auction(); a.fromString(objStr); auctions.append(a); } private static void loadAuctionItem(String objStr) { AuctionItem i=new AuctionItem(); Auction a; String auctionName=objStr.split(AuctionItem.PLACEHOLDER+"")[1]; i.fromString(objStr); a=auctions.search(new Auction(auctionName)); /* As said in load() we trust the input, and if we do * the previous search will always succeed, because of * the order everything is saved */ a.addItem(i); } private static void loadBid(String objStr) { Bid b=new Bid(); Auction a; AuctionItem i; String auctionName=objStr.split(Bid.PLACEHOLDER+"")[1]; String itemName=objStr.split(Bid.PLACEHOLDER+"")[2]; String costumerName=objStr.split(Bid.PLACEHOLDER+"")[3]; b.fromString(objStr); /* The comment in loadAuctionItem() also holds here */ a=auctions.search(new Auction(auctionName)); i=a.getItem(new AuctionItem(itemName)); /* The customers are also saved before everything else */ b.setCustomer(customers.search(new Customer(costumerName))); i.setHighestBidNoMean(b); } private static void load(String filepath) throws Exception { FileReader fIn=new FileReader(filepath); Scanner in=new Scanner(fIn); while (in.hasNextLine()) { String line=in.nextLine(); /* We trust the file was created by this program * and have not been changed, so we don't check * here if the line is empty (in that case we could * not access index 0, and the program will terminate * with a exception instead of a nice error message) * nor if the data is consistent. * * Of course this is a bug, but we also don't check, * if the file opening goes ok, because we didn't lean * try catch in IP, so I guess this is ok. */ switch (line.charAt(0)) { case Customer.CLASS_TYPE: loadCustomer(line); break; case Auction.CLASS_TYPE: loadAuction(line); break; case AuctionItem.CLASS_TYPE: loadAuctionItem(line); break; case Bid.CLASS_TYPE: loadBid(line); break; } } in.close(); fIn.close(); } public static void main(String[] args) throws Exception { File savedFile=new File(SAVE_FILEPATH); init(); if (savedFile.isFile()) load(SAVE_FILEPATH); Main.m.g(); interpreter(); Main.m.h(); } }
13,980
23.614437
79
java
gluon
gluon-master/test/simple/auction/Array.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ import java.util.Comparator; /* Generic type array implementation. * * Note: You may safely ignore the type safety warning at compile time. */ public class Array<T> { private static final int INIT_SIZE=16; /* Initial array size */ private static final int EXPANSION_COEFFICIENT=2; private T[] elem; private int count; /* Number of valid entries in elem */ public Array() { elem=(T[])new Object[INIT_SIZE]; count=0; } public Array(Array<T> array) { this(array.elem,0,array.count-1); } public Array(T[] array) { this(array,0,array.length-1); } /* pre: count <= array.length */ public Array(T[] array, int count) { this(array,0,count-1); } /* Here begin and end are *indexes* * * pre: begin >= 0 && end < array.length */ public Array(T[] array, int begin, int end) { this(); for (int i=begin; i <= end; i++) append(array[i]); } /* Returns the space left in elem array */ private int spaceLeft() { return elem.length-count; } /* Expand elem array size to newSize */ private void expand(int newSize) { T[] tmp=(T[])new Object[newSize]; for (int i=0; i < count; i++) tmp[i]=elem[i]; Main.m.a(); elem=tmp; } /* Append e to elem array */ public void append(T e) { if (spaceLeft() == 0) expand(EXPANSION_COEFFICIENT*elem.length); Main.m.b(); elem[count++]=e; } /* Returns the number of elements in the array */ public int size() { return count; } /* Returns the element in position index. * * pre: isLegalIndex(index) */ public T get(int index) { return elem[index]; } /* Sets v in position index. * * pre: isLegalIndex(index) */ public void set(int index, T v) { elem[index]=v; } /* Swap two elements of the array * * pre: isLegalIndex(p) && isLegalIndex(q) */ public void swap(int p, int q) { T tmp; tmp=elem[p]; elem[p]=elem[q]; elem[q]=tmp; } /* Sort the array according to cmp */ public void sort(Sorter sorter) { sorter.setArray(this); sorter.sort(); } /* Insert e at the given index * * pre: isLegalIndex(index) */ public void insertAt(int index, T e) { if (spaceLeft() == 0) expand(EXPANSION_COEFFICIENT*elem.length); for (int i=count-1; i > index; i--) { elem[i+1]=elem[i]; Main.m.c(); } elem[index]=e; count++; } /* Remove the element at the given index * * pre: isLegalIndex(index) */ public void remove(int index) { for (int i=index; i < count-1; i++) elem[i]=elem[i+1]; count--; } /* Is legal index? */ public boolean isLegalIndex(int index) { Main.m.d(); return index >= 0 && index < count; } /* Returns a iterator */ public Iterator<T> getIterator() { return new ArrayIterator<T>(this); } }
2,942
15.721591
71
java
gluon
gluon-master/test/simple/auction/SorterQuickSort.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ import java.util.Comparator; import java.util.Random; /* SorterQuickSort implements quicksort, a non-stable, in-place sorting * algorithm. Quicksort takes O(n**2) worst case (the near worst case * is unlikely) and O(n*lg(n)) on average (the average is also the best case). * This implementation uses randomization so no specific input will trigger * the worst case quadratic time. */ public class SorterQuickSort<T> implements Sorter<T> { private Array<T> array; private Comparator<T> cmp; private Random gen; public SorterQuickSort(Comparator<T> cmp) { this.array=null; this.cmp=cmp; gen=new Random(); } public void setArray(Array<T> array) { this.array=array; } /* Swaps pivot (always in index e) with a random element */ private void randomizePivot(int b, int e) { array.swap(e,gen.nextInt(e-b+1)+b); } /* Adapted from Programming Challenges, page 91 */ private int partition(int b, int e) { final int p=e; /* Pivot index (always the last elem) */ int firstHigh=b; /* Index of the first element greater than the pivot */ randomizePivot(b,e); for (int i=b; i < e; i++) /* Iterate though all elements but the pivot */ if (cmp.compare(array.get(i),array.get(p)) < 0) { array.swap(i,firstHigh++); Main.m.b(); } array.swap(firstHigh,p); /* Pivot goes to its position */ return firstHigh; } private void quicksortRecursive(int b, int e) { int pivot; /* Pivot index */ Main.m.a(); if (e > b) { pivot=partition(b,e); quicksortRecursive(b,pivot-1); Main.m.b(); quicksortRecursive(pivot+1,e); } Main.m.c(); } public void sort() { quicksortRecursive(0,array.size()-1); Main.m.a(); } }
1,994
21.166667
78
java
gluon
gluon-master/test/simple/auction/Sorter.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ /* Interface for a array sorter */ public interface Sorter<T> { public void sort(); public void setArray(Array<T> array); }
308
18.3125
51
java
gluon
gluon-master/test/simple/auction/AuctionItemComparator.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ import java.util.Comparator; /* AuctionItem comparator, see compare() comment. */ public class AuctionItemComparator implements Comparator<AuctionItem> { public AuctionItemComparator() { } /* Returns < 0 if a1 < a2, 0 if a1 = a2, or > 0 if a1 > 0 according to * what is needed in Main.InterpreterReportAuction(). */ public int compare(AuctionItem a1, AuctionItem a2) { int r; if (a1.sold() && !a2.sold()) r=-1; else if (!a1.sold() && a2.sold()) r=1; else if (a1.sold()) /* From here on items are both sold or both !sold */ { Main.m.a(); r=a1.getSeller().compareTo(a2.getSeller()); } else r=a1.getName().compareTo(a2.getName()); Main.m.b(); return r; } }
924
19.555556
71
java
gluon
gluon-master/test/simple/auction/Auction.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class Auction implements Comparable<Auction> { enum Status { CREATED, OPENED, CLOSED; /* pre: enumStr must be valid */ public static Status fromString(String enumStr) { if (enumStr.equals(CREATED.toString())) return CREATED; else if (enumStr.equals(OPENED.toString())) return OPENED; else return CLOSED; } } public static final char PLACEHOLDER=':'; /* Placeholder for toString() and fromString() */ public static final char CLASS_TYPE='a'; /* For toString() and fromString() */ private String name; /* Auction's name */ private Status status; /* Auction's status */ private ArraySearchable<AuctionItem> items; /* Auction's items */ public Auction(String name) { this.name=name; items=new ArraySearchable<AuctionItem>(); status=Status.CREATED; } /* Useful to load a object fromString() */ public Auction() { this(null); } public String getName() { return name; } /* Can the auction be opened? */ public boolean canOpen() { return status == Status.CREATED; } public boolean canTerminate() { return status == Status.OPENED; } /* pre: canTerminate() */ public void terminate() { status=Status.CLOSED; } /* pre: canOpen() */ public void open() { status=Status.OPENED; } public boolean isCreated() { return status == Status.CREATED; } public boolean isOpened() { return status == Status.OPENED; } public boolean isTerminated() { return status == Status.CLOSED; } public boolean canAddItem() { return isCreated(); } /* pre: canAddItem() */ public void addItem(AuctionItem item) { items.append(item); } public boolean hasItem(AuctionItem item) { return items.has(item); } public AuctionItem getItem(AuctionItem item) { return items.search(item); } public boolean canPlaceBid() { return isOpened(); } public Iterator<AuctionItem> getItemIterator() { return items.getIterator(); } public int numberOfItems() { return items.size(); } public void sortItems() { Main.m.j(); items.sort(new SorterQuickSort<AuctionItem>(new AuctionItemComparator())); } public int compareTo(Auction other) { return name.compareToIgnoreCase(other.name); } /* This should always keep symmetry with fromString() * * Warning: This does *not* return nothing about items */ public String toString() { Main.m.i(); return CLASS_TYPE+""+PLACEHOLDER+name.replace(PLACEHOLDER,' ') +PLACEHOLDER+status.toString(); } /* pre: a valid objStr which must be in the same format as toString() * returns */ public void fromString(String objStr) { String[] tokens=objStr.split(PLACEHOLDER+""); Main.m.l(); name=tokens[1]; status=Status.fromString(tokens[2]); } }
2,986
17.213415
76
java
gluon
gluon-master/test/simple/auction/Iterator.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ /* Interface for general iteratores */ public interface Iterator<T> { /* Set the current item index pointing to the head of the list */ public void toHead(); /* Set the current item index pointing to the tail of the list */ public void toTail(); /* End of list? */ public boolean end(); /* End of list? (in reverse order) */ public boolean rend(); /* Set the current item index pointing to the next element */ public void next(); /* Set the current item index pointing to the previous element */ public void prev(); /* Is the current item index pointing to a legal position? */ public boolean isLegalPos(); /* Returns the current item */ public T get(); /* Total number of entries in the list */ public int size(); /* Number of entries left */ public int left(); /* Number of entries left (in reverse order) */ public int rleft(); }
1,047
21.782609
66
java
gluon
gluon-master/test/simple/auction/AuctionItem.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ /* Represents an item in the context of an auction */ public class AuctionItem extends Item implements Comparable<AuctionItem> { public static final char PLACEHOLDER=':'; /* Placeholder for toString() and fromString() */ public static final char CLASS_TYPE='i'; /* For toString() and fromString() */ private String seller; /* Seller's name (not used elsewhere) */ private int base; /* Base price */ private int sold; /* Sold price */ private Bid highestBid; /* Highest bid for this item (or null if none) */ /* Used to calculate the bids mean */ private int bidCount; private int bidSum; public AuctionItem(String name, String seller, int base) { super(name); this.seller=seller; this.base=base; sold=-1; highestBid=null; bidCount=0; bidSum=0; } /* Just for comparing purposes */ public AuctionItem(String name) { this(name,null,-1); } /* Useful to load a object fromString() */ public AuctionItem() { this(null); } public int compareTo(AuctionItem other) { return getName().compareTo(other.getName()); } public int getBase() { return base; } public int getSold() { return sold; } public String getSeller() { return seller; } public void setSold(int value) { sold=value; } /* Returns the highest bid or null if no bid has been placed */ public Bid getHighestBid() { return highestBid; } /* Set highestBid *AND* update mean. * * pre: bid.isHigher(highestBid) */ public void setHighestBid(Bid bid) { highestBid=bid; bidCount++; bidSum+=bid.getValue(); } /* Set the highestBid but don't affect the mean. * * pre: bid.isHigher(highestBid) */ public void setHighestBidNoMean(Bid bid) { highestBid=bid; } public double getBidsMean() { return (double)bidSum/(double)bidCount; } public boolean sold() { return highestBid != null; } /* This should always keep symmetry with fromString(). * * Note: The auctionName is passed here so it can be associated * later with that auction. * * Warning: This does *not* return nothing about the highestBid. */ public String toString(String auctionName) { return CLASS_TYPE+""+PLACEHOLDER +auctionName.replace(PLACEHOLDER,' ')+PLACEHOLDER +getName().replace(PLACEHOLDER,' ')+ PLACEHOLDER+seller.replace(PLACEHOLDER,' ') +PLACEHOLDER+base+PLACEHOLDER+sold+PLACEHOLDER +bidCount+PLACEHOLDER+bidSum; } /* pre: a valid objStr which must be in the same format as toString() * returns */ public void fromString(String objStr) { String[] tokens=objStr.split(PLACEHOLDER+""); Main.m.i(); setName(tokens[2]); seller=tokens[3]; base=Integer.parseInt(tokens[4]); sold=Integer.parseInt(tokens[5]); bidCount=Integer.parseInt(tokens[6]); bidSum=Integer.parseInt(tokens[7]); Main.m.e(); } }
3,036
19.52027
72
java
gluon
gluon-master/test/simple/auction/ArrayIterator.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class ArrayIterator<T> implements Iterator<T> { private Array<T> array; private int index; public ArrayIterator(Array<T> array) { this.array=array; toHead(); } /* Set the current item index pointing to the head of the array */ public void toHead() { index=0; } /* Set the current item index pointing to the tail of the array */ public void toTail() { index=array.size()-1; } /* End of array? */ public boolean end() { return index >= array.size(); } /* End of array? (in reverse order) */ public boolean rend() { return index < 0; } /* Set the current item index pointing to the next element */ public void next() { index++; } /* Set the current item index pointing to the previous element */ public void prev() { index--; } /* Is the current item index pointing to a legal position? */ public boolean isLegalPos() { return !end() && !rend(); } /* Returns the current item * * pre: islegalPos() */ public T get() { Main.m.j(); return array.get(index); } /* Total number of entries in the array */ public int size() { return array.size(); } /* Number of entries left */ public int left() { Main.m.d(); return array.size()-(index+1); } /* Number of entries left (in reverse order) */ public int rleft() { return index; } }
1,519
15.521739
67
java
gluon
gluon-master/test/simple/auction/Customer.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class Customer implements Comparable<Customer> { private static final int DEFAULT_REPUTATION_PENALTY=10; private static final int CREDIBILITY_LIMIT=50; public static final char PLACEHOLDER=':'; /* Placeholder for toString() and fromString() */ public static final char CLASS_TYPE='c'; /* For toString() and fromString() */ private String name; /* Customer's name */ private int balance; /* Customer's balance */ private int reputation; /* Customer's reputation */ private int highestBid; /* Customer's Highest Bid */ public Customer(String name, int balance) { this.name=name; this.balance=balance; reputation=100; highestBid=0; } /* Just for comparing purposes */ public Customer(String name) { this(name,0); } /* Useful to load a object fromString() */ public Customer() { this(null); } public String getName() { return name; } public int getBalance() { return balance; } public int getReputation() { return reputation; } public int getHighestBid() { return highestBid; } public void setHighestBidIfHigher(int value) { Main.m.i(); highestBid=Math.max(highestBid,value); } public void credit(int inc) { balance+=inc; } public void pay(int inc) { credit(-inc); } public void reputationPenalty() { reputation-=DEFAULT_REPUTATION_PENALTY; } public boolean isCredible() { Main.m.h(); return reputation >= CREDIBILITY_LIMIT; } public int compareTo(Customer other) { return name.compareToIgnoreCase(other.name); } /* This should always keep symmetry with fromString() */ public String toString() { return CLASS_TYPE+""+PLACEHOLDER+name.replace(PLACEHOLDER,' ') +PLACEHOLDER+balance+PLACEHOLDER+reputation +PLACEHOLDER+highestBid; } /* pre: a valid objStr which must be in the same format as toString() * returns */ public void fromString(String objStr) { String[] tokens=objStr.split(PLACEHOLDER+""); Main.m.l(); name=tokens[1]; balance=Integer.parseInt(tokens[2]); reputation=Integer.parseInt(tokens[3]); highestBid=Integer.parseInt(tokens[4]); } }
2,336
18.475
72
java
gluon
gluon-master/test/simple/auction/ArraySearchable.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class ArraySearchable<T extends Comparable<T>> extends Array<T> { public ArraySearchable() { super(); } /* Is "needle" in the "haystack"? */ public boolean has(T needle) { return search(needle) != null; } /* Returns the object of the list which matches needle or null if * not there is no match. */ public T search(T needle) { T r=null; for (Iterator<T> it=getIterator(); !it.end() && r == null; it.next()) { T c=it.get(); Main.m.l(); if (it.get().compareTo(needle) == 0) { r=c; Main.m.j(); } } Main.m.h(); return r; } }
830
15.62
70
java
gluon
gluon-master/test/simple/auction/Item.java
package test.simple.auction; /** * @author Diogo Sousa, nº 28970, Turno P10 * * Docente (prática): Pedro Leandro da Silva Amaral * Docente (teórico-prática): Miguel Goulão */ public class Item { private String name; /* Article's name */ public Item(String name) { this.name=name; } public String getName() { Main.m.j(); return name; } public void setName(String name) { this.name=name; } }
425
13.2
51
java
gluon
gluon-master/test/simple/auction/Module.java
package test.simple.auction; @interface Contract { String clauses(); } @Contract(clauses ="a b c;") public class Module { public Module() { } public void a() { } public void b() { } public void c() { } public void d() { } public void e() { } public void f() { } public void g() { } public void h() { } public void i() { } public void j() { } public void l() { } }
526
7.783333
28
java
gluon
gluon-master/test/simple/pointsto/Main.java
package test.simple.pointsto; import test.common.Atomic; import test.common.Contract; @Contract(clauses="a b c;" +"c c;") class Module { public Module() { } public void a() { } public void b() { } public void c() { } } public class Main { private Module m; private Module m2=new Module(); private void f() { m.c(); } @Atomic private void g() { m.a(); m.b(); f(); } private void go() { m=new Module(); for (int i=0; i < 10; i++) if (i%2 == 0) m.a(); else { m.b(); if (i%5 == 0) m=m2; } f(); g(); } public static void main(String[] args) { new Main().go(); } }
850
13.672414
42
java
gluon
gluon-master/test/simple/exampleargs/Main.java
package test.simple.exampleargs; import test.common.Atomic; import test.common.Contract; @Contract(clauses="X=d e(X);" +"a b c(X,X);" +"a b c(X,Y);" +"c c;" +"c(X,Y) c(K,_);") class Module { public Module() { } public void a() { } public void b() { } public void c(int x, int y) { } public int d() { return 1; } public void e(int foo) { } } public class Main { private static Module m; private static void f() { m.c(0,1); } @Atomic private static void g() { m.a(); m.b(); f(); } private static void h() { int v=0; v=m.d(); m.e(42); /* otherwise v is removed by the compiler for not being used */ System.out.println(v); } public static void main(String[] args) { int v; m=new Module(); for (int i=0; i < 10; i++) if (i%2 == 0) m.a(); else m.b(); f(); g(); v=m.d(); m.e(v); h(); } }
1,135
15.228571
71
java
gluon
gluon-master/test/simple/fieldargs/Main.java
package test.simple.fieldargs; import test.common.Atomic; import test.common.Contract; @Contract(clauses="a(X) b(X);" +"ai(X) bi(X);" +"X=ai bi(X)") class Module { public Module m; public int foo=3; public Module() { } public void a(String bar) { } public void b(String foo) { } public int ai(int bar) { return 4; } public void bi(int foo) { } } public class Main { private Module m; private String v="42"; private int vi=42; private int[] vvi={1,7}; public void test() { m=new Module(); m.a(v); m.b(v); System.out.println(v); test2(); } public void test2() { m=new Module(); m.ai(vi); m.bi(vi); System.out.println(vi); test3(); } public void test3() { m.ai(vvi[0]); m.bi(vvi[0]); System.out.println(vi); test4(); } public void test4() { m.ai(m.m.foo); m.bi(m.m.foo); System.out.println(vi); test5(); } public void test5() { int[] vec={1,7}; m.ai(vec[0]); m.bi(vec[0]); test6(); } public void test6() { int[][] vec={{1},{7}}; m.ai(vec[0][0]); m.bi(vec[0][0]); test7(10); } public void test7(int a) { vvi[a]=m.ai(8); if (vvi[a] > 0) m.bi(vvi[a]); } public static void main(String[] args) { new Main().test(); } }
1,555
14.106796
42
java
gluon
gluon-master/test/simple/example/Main.java
package test.simple.example; import test.common.Atomic; import test.common.Contract; @Contract(clauses="a b c;" +"c c;") class Module { public Module() { } public void a() { } public void b() { } public void c() { } } public class Main { private static Module m; private static void f() { m.c(); } @Atomic private static void g() { m.a(); m.b(); f(); } public static void main(String[] args) { m=new Module(); for (int i=0; i < 10; i++) if (i%2 == 0) m.a(); else m.b(); f(); g(); } }
689
13.680851
42
java
gluon
gluon-master/test/simple/performance/Main.java
package test.simple.performance; import test.common.Atomic; import test.common.Contract; @Contract(clauses="a b c;" +"c c;") class Module { public Module() { } public void a() { } public void b() { } public void c() { } } public class Main { private static Module m; private static int i=0; private static void f() { if (i == 8) return; m.c(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i == 10) f(); m.c(); if (i == 10) System.out.println(i); else System.out.println(i); if (i == 10) m.c(); m.c(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i == 11) m.c(); if (i == 10) System.out.println(i); else System.out.println(i); while (i < 10) m.c(); if (i == 10) System.out.println(i); else System.out.println(i); if (i == 10) m.c(); m.c(); while (i < 10) { m.c(); f(); } if (i == 13) m.c(); } @Atomic private static void g() { m.a(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); m.b(); while (i < 1000) if (i == 1) m.c(); else f(); if (i == 10) System.out.println(i); else System.out.println(i); while (i < 1000) if (i == 1) m.c(); else f(); if (i == 10) System.out.println(i); else System.out.println(i); while (i < 1000) if (i == 1) m.c(); else { if (i == 10) System.out.println(i); else System.out.println(i); f(); } while (i < 1000) if (i == 1) m.c(); else f(); while (i < 1000) if (i == 1) m.c(); else f(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); while (i < 1000) if (i == 1) m.c(); else f(); if (i == 10) System.out.println(i); else System.out.println(i); while (i < 1000) if (i == 1) m.c(); else f(); if (i == 10) System.out.println(i); else System.out.println(i); while (i < 1000) if (i == 1) m.c(); else f(); } public static void main(String[] args) { m=new Module(); for (int i=0; i < 10; i++) if (i%2 == 0) { if (i == 10) System.out.println(i); else System.out.println(i); m.a(); i++; } else m.b(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i == 10) System.out.println(i); else System.out.println(i); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i >50) i++; else i--; f(); g(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); while (i < 1000) { m.a(); if (i == 10) m.b(); else { m.c(); if (i >50) i++; else i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); if (i == 10) System.out.println(i); else System.out.println(i); i++; } else m.b(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i >50) i++; else i--; if (i%2 == 0) while (i < 1000) { m.a(); if (i == 10) m.b(); else { m.c(); i++; m.c(); } m.c(); } while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); if (i == 10) System.out.println(i); else System.out.println(i); i++; } else m.b(); if (i >50) i++; else i--; while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i%2 == 1) while (i < 1000) { m.a(); if (i == 10) m.b(); else { m.c(); i++; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); if (i == 10) System.out.println(i); else System.out.println(i); i++; } else m.b(); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); if (i >50) i++; else i--; if (i%2 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i == 10) System.out.println(i); else System.out.println(i); if (i >50) i++; else i--; if (i%2 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } if (i == 10) System.out.println(i); else System.out.println(i); while (i%12 == 34) if (i == 10) System.out.println(i++); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i == 10) System.out.println(i); else System.out.println(i); if (i%2 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i == 10) System.out.println(i); else System.out.println(i); if (i >50) i++; else i--; if (i%26 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { if (i == 10) System.out.println(i); else System.out.println(i); m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i%22 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; if (i == 10) System.out.println(i); else System.out.println(i); } else m.b(); if (i >50) i++; else i--; if (i%20 == 2) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } if (i == 10) System.out.println(i); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i == 10) System.out.println(i); else System.out.println(i); if (i%26 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i == 10) System.out.println(i); else System.out.println(i); if (i >50) i++; else i--; if (i%22 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } if (i == 10) System.out.println(i); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i%26 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i == 10) System.out.println(i); else System.out.println(i); if (i >50) i++; else i--; if (i%22 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i == 10) System.out.println(i); else System.out.println(i); for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; if (i == 10) System.out.println(i); else System.out.println(i); } else m.b(); if (i >50) i++; else i--; if (i%26 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; m.c(); } m.c(); } if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i == 10) System.out.println(i); else System.out.println(i); if (i >50) i++; else i--; if (i%22 == 0) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { i--; m.c(); } } else { m.c(); i--; if (i == 10) System.out.println(i); else System.out.println(i); m.c(); } m.c(); } for (int i=0; i < 10; i++) if (i%2 == 0) { m.a(); i++; } else m.b(); if (i >50) i++; else i--; if (i == 10) System.out.println(i); else System.out.println(i); while (i%12 == 34) if (i == 10) System.out.println(i); else System.out.println(i); if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } if (i%20 == 2) while (i < 1000) { m.a(); if (i == 10) { m.b(); if (i >50) i++; else { while (i%12 == 34) if (i == 10) System.out.println(i); else System.out.println(i); i--; m.c(); } while (i%12 == 34) if (i == 10) System.out.println(i); else System.out.println(i); } else { m.c(); i--; m.c(); } m.c(); } if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } while (i%12 == 34) if (i == 10) System.out.println(i); else System.out.println(i); if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; else { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } if (i%26 == 0) while (i < 1000) { System.out.println(i); if (i == 10) { System.out.println(i); if (i >50) i++; while (i%12 == 34) if (i == 10) System.out.println(i); else System.out.println(i); { i--; System.out.println(i); } } else { System.out.println(i); i--; System.out.println(i); } System.out.println(i); } } }
20,700
17.12697
42
java
gluon
gluon-master/test/simple/basic/Main.java
package test.simple.basic; public class Main { public static void main(String[] args) { while (true) main(args); } }
151
11.666667
42
java
gluon
gluon-master/test/simple/withParams/Main.java
package test.simple.withParams; import test.common.Contract; @Contract(clauses="Y=indexOf remove(Y);") class Module { public Module() {} public int indexOf() { return 0; } public void remove(int i) {} } public class Main { private static Module m; public static void main(String[] args) { m = new Module(); int j = 2; int i = m.indexOf(); m.remove(j); } }
417
16.416667
44
java
gluon
gluon-master/test/simple/grammaropt/Main.java
package test.simple.grammaropt; import test.common.Atomic; import test.common.Contract; @Contract(clauses="a b c;" +"c c;") class Module { public Module() { } public void a() { } public void b() { } public void c() { } } public class Main { private static Module m; public static void main(String[] args) { m=new Module(); for (int i=0; i < 10; i++) if (i%2 == 0) { if (i%3 == 0) m.a(); else System.out.println("bar"); } else System.out.println("foo"); } }
663
17.444444
46
java
gluon
gluon-master/test/validation/UnderReportingTest/Main.java
package test.validation.UnderReportingTest; public class Main extends Thread { static Counter c; public static void main(String[] args) { c = new Counter(); new Main().start(); new Main().start(); } public void run() { int i = c.inc(0); c.inc(i); } }
269
14.882353
43
java
gluon
gluon-master/test/validation/UnderReportingTest/Counter.java
package test.validation.UnderReportingTest; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "inc inc;") public class Counter { int i; @Atomic int inc(int a) { i += a; return i; } }
221
12.058824
43
java
gluon
gluon-master/test/validation/Knight/Main.java
package test.validation.Knight; import java.awt.Point; import java.util.Random; public class Main { public static void main(String[] args) { Random rnd=new Random(); Point knight=new Point(Math.abs(rnd.nextInt())%KnightMoves.WIDTH,Math.abs(rnd.nextInt())%KnightMoves.WIDTH); Point prey=new Point(Math.abs(rnd.nextInt())%KnightMoves.WIDTH,Math.abs(rnd.nextInt())%KnightMoves.WIDTH); KnightMoves km=new KnightMoves(knight,prey); int s; int cs; System.out.println("Knight @ "+knight.toString()); System.out.println("Prey @ "+prey.toString()); km.solve(); System.out.println("Moves: "+(s=km.get_moves())); km.solve_correct(); System.out.println("Correct Moves: "+(cs=km.get_moves())); if (cs != s) System.out.println("err"); } }
766
22.242424
110
java
gluon
gluon-master/test/validation/Knight/KnightMoves.java
package test.validation.Knight; import java.awt.Point; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "get_solution(X) set_solution(X,_);") public class KnightMoves { public static final int WIDTH=8; private Point knight; private Point prey; private int solution[][]; public KnightMoves(Point knight, Point prey) { solution=new int[WIDTH][WIDTH]; this.knight=knight; this.prey=prey; } private void reset_solution() { for (int i=0; i < WIDTH; i++) for (int j=0; j < WIDTH; j++) solution[i][j]=Integer.MAX_VALUE; } public void solve() { /* This would be much faster with breadth first search */ reset_solution(); Solver s=new Solver(this,(Point)knight.clone(),0); s.start(); try { s.join(); } catch (Exception e) {} } public Point get_knight() { return knight; } public Point get_prey() { return prey; } @Atomic public int get_solution(Point p) { return solution[p.x][p.y]; } @Atomic public void set_solution(Point p, int m) { solution[p.x][p.y]=m; } public int get_moves() { return get_solution(prey); } public void solve_correct() { reset_solution(); new SolverCorrect(this,(Point)knight.clone(),0).go(); } }
1,223
15.767123
59
java
gluon
gluon-master/test/validation/Knight/Solver.java
package test.validation.Knight; import java.awt.Point; import java.lang.Thread; import java.util.Random; public class Solver extends Thread { private KnightMoves km; private Point me; private int moves; public Solver(KnightMoves km, Point me, int moves) { this.km=km; this.me=me; this.moves=moves; } private int check_and_set_solution() { Random rnd=new Random(); /* Check if other thread has a better solution */ if (km.get_solution(me) <= moves) return -1; if (Math.abs(rnd.nextInt())%2 == 0) try { Thread.sleep(50+(Math.abs(rnd.nextInt())%100)); } catch (Exception e) {} km.set_solution(me,moves); return 0; } public void run() { Point []next=new Point[8]; int c=0; int m[]={1,-1}; Solver []solver=new Solver[8]; int s_c=0; if (check_and_set_solution() < 0) return; if (me.equals(km.get_prey())) return; for (int i=1; i <= 2; i++) for (int j=1; j <= 2; j++) if (i != j) for (int k=0; k < 2; k++) for (int l=0; l < 2; l++) next[c++]=new Point(i*m[k]+me.x,j*m[l]+me.y); for (Point n: next) if (n.x >= 0 && n.y >= 0 && n.x < KnightMoves.WIDTH && n.y < KnightMoves.WIDTH) { //System.out.println(n.toString()); solver[s_c]=new Solver(km,n,moves+1); solver[s_c++].start(); } for (int i=0; i < s_c; i++) try { solver[i].join();} catch (Exception e) {} } }
1,392
18.347222
81
java