proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
soot-oss_soot
|
soot/src/main/java/soot/toDex/instructions/Insn35c.java
|
Insn35c
|
getIncompatibleRegs
|
class Insn35c extends AbstractInsn implements FiveRegInsn {
private int regCount;
private final Reference referencedItem;
public Insn35c(Opcode opc, int regCount, Register regD, Register regE, Register regF, Register regG, Register regA,
Reference referencedItem) {
super(opc);
this.regCount = regCount;
regs.add(regD);
regs.add(regE);
regs.add(regF);
regs.add(regG);
regs.add(regA);
this.referencedItem = referencedItem;
}
public Register getRegD() {
return regs.get(REG_D_IDX);
}
public Register getRegE() {
return regs.get(REG_E_IDX);
}
public Register getRegF() {
return regs.get(REG_F_IDX);
}
public Register getRegG() {
return regs.get(REG_G_IDX);
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
private static boolean isImplicitWide(Register firstReg, Register secondReg) {
return firstReg.isWide() && secondReg.isEmptyReg();
}
private static int getPossiblyWideNumber(Register reg, Register previousReg) {
if (isImplicitWide(previousReg, reg)) {
// we cannot use reg.getNumber(), since the empty reg's number is always 0
return previousReg.getNumber() + 1;
}
return reg.getNumber();
}
private int[] getRealRegNumbers() {
int[] realRegNumbers = new int[5];
Register regD = getRegD();
Register regE = getRegE();
Register regF = getRegF();
Register regG = getRegG();
Register regA = getRegA();
realRegNumbers[REG_D_IDX] = regD.getNumber();
realRegNumbers[REG_E_IDX] = getPossiblyWideNumber(regE, regD);
realRegNumbers[REG_F_IDX] = getPossiblyWideNumber(regF, regE);
realRegNumbers[REG_G_IDX] = getPossiblyWideNumber(regG, regF);
realRegNumbers[REG_A_IDX] = getPossiblyWideNumber(regA, regG);
return realRegNumbers;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
int[] realRegNumbers = getRealRegNumbers();
byte regDNumber = (byte) realRegNumbers[REG_D_IDX];
byte regENumber = (byte) realRegNumbers[REG_E_IDX];
byte regFNumber = (byte) realRegNumbers[REG_F_IDX];
byte regGNumber = (byte) realRegNumbers[REG_G_IDX];
byte regANumber = (byte) realRegNumbers[REG_A_IDX];
return new BuilderInstruction35c(opc, regCount, regDNumber, regENumber, regFNumber, regGNumber, regANumber,
referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return super.toString() + " (" + regCount + " regs), ref: " + referencedItem;
}
}
|
BitSet incompatRegs = new BitSet(5);
int[] realRegNumbers = getRealRegNumbers();
for (int i = 0; i < realRegNumbers.length; i++) {
// real regs aren't wide, because those are represented as two non-wide regs
boolean isCompatible = Register.fitsByte(realRegNumbers[i], false);
if (!isCompatible) {
incompatRegs.set(i);
// if second half of a wide reg is incompatible, so is its first half
Register possibleSecondHalf = regs.get(i);
if (possibleSecondHalf.isEmptyReg() && i > 0) {
Register possibleFirstHalf = regs.get(i - 1);
if (possibleFirstHalf.isWide()) {
incompatRegs.set(i - 1);
}
}
}
}
return incompatRegs;
| 921
| 236
| 1,157
|
<methods>public void <init>(org.jf.dexlib2.Opcode) ,public java.util.BitSet getIncompatibleRegs() ,public int getMinimumRegsNeeded() ,public org.jf.dexlib2.Opcode getOpcode() ,public org.jf.dexlib2.builder.BuilderInstruction getRealInsn(soot.toDex.LabelAssigner) ,public List<soot.toDex.Register> getRegs() ,public int getSize() ,public boolean hasIncompatibleRegs() ,public java.lang.String toString() <variables>protected org.jf.dexlib2.Opcode opc,protected List<soot.toDex.Register> regs
|
soot-oss_soot
|
soot/src/main/java/soot/toDex/instructions/Insn3rc.java
|
Insn3rc
|
getIncompatibleRegs
|
class Insn3rc extends AbstractInsn {
private short regCount;
private Reference referencedItem;
public Insn3rc(Opcode opc, List<Register> regs, short regCount, Reference referencedItem) {
super(opc);
this.regs = regs;
this.regCount = regCount;
this.referencedItem = referencedItem;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
Register startReg = regs.get(0);
return new BuilderInstruction3rc(opc, startReg.getNumber(), regCount, referencedItem);
}
@Override
public BitSet getIncompatibleRegs() {<FILL_FUNCTION_BODY>}
private static BitSet getAllIncompatible(int regCount) {
BitSet incompatRegs = new BitSet(regCount);
incompatRegs.flip(0, regCount);
return incompatRegs;
}
private boolean hasHoleInRange() {
// the only "hole" that is allowed: if regN is wide -> regN+1 must not be there
Register startReg = regs.get(0);
int nextExpectedRegNum = startReg.getNumber() + 1;
if (startReg.isWide()) {
nextExpectedRegNum++;
}
// loop starts at 1, since the first reg alone cannot have a hole
for (int i = 1; i < regs.size(); i++) {
Register r = regs.get(i);
int regNum = r.getNumber();
if (regNum != nextExpectedRegNum) {
return true;
}
nextExpectedRegNum++;
if (r.isWide()) {
nextExpectedRegNum++;
}
}
return false;
}
@Override
public String toString() {
return super.toString() + " ref: " + referencedItem;
}
}
|
// if there is one problem -> all regs are incompatible (this could be optimized in reg allocation, probably)
int regCount = SootToDexUtils.getRealRegCount(regs);
if (hasHoleInRange()) {
return getAllIncompatible(regCount);
}
for (Register r : regs) {
if (!r.fitsUnconstrained()) {
return getAllIncompatible(regCount);
}
if (r.isWide()) {
boolean secondWideHalfFits = Register.fitsUnconstrained(r.getNumber() + 1, false);
if (!secondWideHalfFits) {
return getAllIncompatible(regCount);
}
}
}
return new BitSet(regCount);
| 503
| 195
| 698
|
<methods>public void <init>(org.jf.dexlib2.Opcode) ,public java.util.BitSet getIncompatibleRegs() ,public int getMinimumRegsNeeded() ,public org.jf.dexlib2.Opcode getOpcode() ,public org.jf.dexlib2.builder.BuilderInstruction getRealInsn(soot.toDex.LabelAssigner) ,public List<soot.toDex.Register> getRegs() ,public int getSize() ,public boolean hasIncompatibleRegs() ,public java.lang.String toString() <variables>protected org.jf.dexlib2.Opcode opc,protected List<soot.toDex.Register> regs
|
soot-oss_soot
|
soot/src/main/java/soot/toDex/instructions/Insn51l.java
|
Insn51l
|
getIncompatibleRegs
|
class Insn51l extends AbstractInsn implements OneRegInsn {
private long litB;
public Insn51l(Opcode opc, Register regA, long litB) {
super(opc);
regs.add(regA);
this.litB = litB;
}
public Register getRegA() {
return regs.get(REG_A_IDX);
}
public long getLitB() {
return litB;
}
@Override
protected BuilderInstruction getRealInsn0(LabelAssigner assigner) {
return new BuilderInstruction51l(opc, (short) getRegA().getNumber(), getLitB());
}
@Override
public BitSet getIncompatibleRegs() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return super.toString() + " lit: " + getLitB();
}
}
|
BitSet incompatRegs = new BitSet(1);
if (!getRegA().fitsShort()) {
incompatRegs.set(REG_A_IDX);
}
return incompatRegs;
| 249
| 57
| 306
|
<methods>public void <init>(org.jf.dexlib2.Opcode) ,public java.util.BitSet getIncompatibleRegs() ,public int getMinimumRegsNeeded() ,public org.jf.dexlib2.Opcode getOpcode() ,public org.jf.dexlib2.builder.BuilderInstruction getRealInsn(soot.toDex.LabelAssigner) ,public List<soot.toDex.Register> getRegs() ,public int getSize() ,public boolean hasIncompatibleRegs() ,public java.lang.String toString() <variables>protected org.jf.dexlib2.Opcode opc,protected List<soot.toDex.Register> regs
|
soot-oss_soot
|
soot/src/main/java/soot/toDex/instructions/InsnWithOffset.java
|
InsnWithOffset
|
setTarget
|
class InsnWithOffset extends AbstractInsn {
protected Stmt target;
public InsnWithOffset(Opcode opc) {
super(opc);
}
public void setTarget(Stmt target) {<FILL_FUNCTION_BODY>}
public Stmt getTarget() {
return this.target;
}
/**
* Gets the maximum number of words available for the jump offset
*
* @return The maximum number of words available for the jump offset
*/
public abstract int getMaxJumpOffset();
}
|
if (target == null) {
throw new RuntimeException("Cannot jump to a NULL target");
}
this.target = target;
| 143
| 37
| 180
|
<methods>public void <init>(org.jf.dexlib2.Opcode) ,public java.util.BitSet getIncompatibleRegs() ,public int getMinimumRegsNeeded() ,public org.jf.dexlib2.Opcode getOpcode() ,public org.jf.dexlib2.builder.BuilderInstruction getRealInsn(soot.toDex.LabelAssigner) ,public List<soot.toDex.Register> getRegs() ,public int getSize() ,public boolean hasIncompatibleRegs() ,public java.lang.String toString() <variables>protected org.jf.dexlib2.Opcode opc,protected List<soot.toDex.Register> regs
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/ASTMetric.java
|
ASTMetric
|
leave
|
class ASTMetric extends NodeVisitor implements MetricInterface {
polyglot.ast.Node astNode;
String className = null; // name of Class being currently processed
public ASTMetric(polyglot.ast.Node astNode) {
this.astNode = astNode;
reset();
}
/*
* Taking care of the change in classes within a polyglot ast
*/
public final NodeVisitor enter(Node n) {
if (n instanceof ClassDecl) {
className = ((ClassDecl) n).name();
System.out.println("Starting processing: " + className);
}
return this;
}
/*
* When we leave a classDecl all the metrics for this classDecl must be stored and the metrics reset
*
* This is done by invoking the addMetrics abstract method
*/
public final Node leave(Node parent, Node old, Node n, NodeVisitor v) {<FILL_FUNCTION_BODY>}
public abstract void reset();
public abstract void addMetrics(ClassData data);
/*
* Should be used to execute the traversal which will find the metric being calculated
*/
public final void execute() {
astNode.visit(this);
// Testing testing testing
System.out.println("\n\n\n PRETTY P{RINTING");
if (this instanceof StmtSumWeightedByDepth) {
metricPrettyPrinter p = new metricPrettyPrinter(this);
p.printAst(astNode, new CodeWriter(System.out, 80));
}
}
public void printAstMetric(Node n, CodeWriter w) {
}
/*
* Returns the classData object if one if present in the globals Metrics List otherwise creates new adds to globals metric
* list and returns that
*/
public final ClassData getClassData() {
if (className == null) {
throw new RuntimeException("className is null");
}
Iterator<ClassData> it = G.v().ASTMetricsData.iterator();
while (it.hasNext()) {
ClassData tempData = it.next();
if (tempData.classNameEquals(className)) {
return tempData;
}
}
ClassData data = new ClassData(className);
G.v().ASTMetricsData.add(data);
return data;
}
}
|
if (n instanceof ClassDecl) {
if (className == null) {
throw new RuntimeException("className is null");
}
System.out.println("Done with class " + className);
// get the classData object for this class
ClassData data = getClassData();
addMetrics(data);
reset();
}
return leave(old, n, v);
| 602
| 99
| 701
|
<methods>public void <init>() ,public polyglot.visit.NodeVisitor begin() ,public polyglot.visit.NodeVisitor enter(polyglot.ast.Node) ,public polyglot.visit.NodeVisitor enter(polyglot.ast.Node, polyglot.ast.Node) ,public void finish() ,public void finish(polyglot.ast.Node) ,public polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public polyglot.ast.Node override(polyglot.ast.Node) ,public polyglot.ast.Node override(polyglot.ast.Node, polyglot.ast.Node) ,public java.lang.String toString() ,public polyglot.ast.Node visitEdge(polyglot.ast.Node, polyglot.ast.Node) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/AbruptEdgesMetric.java
|
AbruptEdgesMetric
|
enter
|
class AbruptEdgesMetric extends ASTMetric {
private int iBreaks, eBreaks;
private int iContinues, eContinues;
public AbruptEdgesMetric(polyglot.ast.Node astNode) {
super(astNode);
}
/*
* (non-Javadoc)
*
* @see soot.toolkits.astmetrics.ASTMetric#reset() Implementation of the abstract method which is invoked by parent
* constructor and whenever the classDecl in the polyglot changes
*/
public void reset() {
iBreaks = eBreaks = iContinues = eContinues = 0;
}
/*
* Implementation of the abstract method
*
* Should add the metrics to the data object sent
*/
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("Total-breaks", new Integer(iBreaks + eBreaks)));
data.addMetric(new MetricData("I-breaks", new Integer(iBreaks)));
data.addMetric(new MetricData("E-breaks", new Integer(eBreaks)));
data.addMetric(new MetricData("Total-continues", new Integer(iContinues + eContinues)));
data.addMetric(new MetricData("I-continues", new Integer(iContinues)));
data.addMetric(new MetricData("E-continues", new Integer(eContinues)));
data.addMetric(new MetricData("Total-Abrupt", new Integer(iBreaks + eBreaks + iContinues + eContinues)));
}
/*
* A branch in polyglot is either a break or continue
*/
public NodeVisitor enter(Node parent, Node n) {<FILL_FUNCTION_BODY>}
}
|
if (n instanceof Branch) {
Branch branch = (Branch) n;
if (branch.kind().equals(Branch.BREAK)) {
if (branch.label() != null) {
eBreaks++;
} else {
iBreaks++;
}
} else if (branch.kind().equals(Branch.CONTINUE)) {
if (branch.label() != null) {
eContinues++;
} else {
iContinues++;
}
} else {
System.out.println("\t Error:'" + branch.toString() + "'");
}
}
return enter(n);
| 481
| 173
| 654
|
<methods>public void <init>(polyglot.ast.Node) ,public abstract void addMetrics(soot.toolkits.astmetrics.ClassData) ,public final polyglot.visit.NodeVisitor enter(polyglot.ast.Node) ,public final void execute() ,public final soot.toolkits.astmetrics.ClassData getClassData() ,public final polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public void printAstMetric(polyglot.ast.Node, polyglot.util.CodeWriter) ,public abstract void reset() <variables>polyglot.ast.Node astNode,java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/ClassData.java
|
ClassData
|
addMetric
|
class ClassData {
String className; // the name of the class whose data is being stored
ArrayList<MetricData> metricData; // each element should be a MetricData
public ClassData(String name) {
className = name;
metricData = new ArrayList<MetricData>();
}
public String getClassName() {
return className;
}
/*
* returns true if this className has the same name as the string sent as argument
*/
public boolean classNameEquals(String className) {
return (this.className.equals(className));
}
/*
* Only add new metric if this is not already present Else dont add
*/
public void addMetric(MetricData data) {<FILL_FUNCTION_BODY>}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("<Class>\n");
b.append("<ClassName>" + className + "</ClassName>\n");
Iterator<MetricData> it = metricData.iterator();
while (it.hasNext()) {
b.append(it.next().toString());
}
b.append("</Class>");
return b.toString();
}
}
|
Iterator<MetricData> it = metricData.iterator();
while (it.hasNext()) {
MetricData temp = it.next();
if (temp.metricName.equals(data.metricName)) {
// System.out.println("Not adding same metric again......"+temp.metricName);
return;
}
}
metricData.add(data);
| 311
| 99
| 410
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/ComputeASTMetrics.java
|
ComputeASTMetrics
|
apply
|
class ComputeASTMetrics {
ArrayList<ASTMetric> metrics;
/*
* New metrics should be added into the metrics linked list
*/
public ComputeASTMetrics(Node astNode) {
metrics = new ArrayList<ASTMetric>();
// add new metrics below this line
// REMEMBER ALL METRICS NEED TO implement MetricInterface
// abrupt edges metric calculator
metrics.add(new AbruptEdgesMetric(astNode));
metrics.add(new NumLocalsMetric(astNode));
metrics.add(new ConstructNumbersMetric(astNode));
metrics.add(new StmtSumWeightedByDepth(astNode));
metrics.add(new ConditionComplexityMetric(astNode));
metrics.add(new ExpressionComplexityMetric(astNode));
metrics.add(new IdentifiersMetric(astNode));
}
public void apply() {<FILL_FUNCTION_BODY>}
}
|
if (!Options.v().ast_metrics()) {
return;
}
Iterator<ASTMetric> metricIt = metrics.iterator();
while (metricIt.hasNext()) {
metricIt.next().execute();
}
| 242
| 65
| 307
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/ConditionComplexityMetric.java
|
ConditionComplexityMetric
|
condComplexity
|
class ConditionComplexityMetric extends ASTMetric {
int loopComplexity;
int ifComplexity;
public ConditionComplexityMetric(polyglot.ast.Node node) {
super(node);
}
public void reset() {
loopComplexity = ifComplexity = 0;
}
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("Loop-Cond-Complexity", new Integer(loopComplexity)));
data.addMetric(new MetricData("If-Cond-Complexity", new Integer(ifComplexity)));
data.addMetric(new MetricData("Total-Cond-Complexity", new Integer(loopComplexity + ifComplexity)));
}
public NodeVisitor enter(Node parent, Node n) {
if (n instanceof Loop) {
Expr expr = ((Loop) n).cond();
loopComplexity += condComplexity(expr);
} else if (n instanceof If) {
Expr expr = ((If) n).cond();
ifComplexity += condComplexity(expr);
}
return enter(n);
}
private double condComplexity(Expr expr) {<FILL_FUNCTION_BODY>}
}
|
// boolean literal
// binary check for AND and OR ... else its relational!!
// unary (Check for NOT)
if (expr instanceof Binary) {
Binary b = (Binary) expr;
if (b.operator() == Binary.COND_AND || b.operator() == Binary.COND_OR) {
// System.out.println(">>>>>>>> Binary (AND or OR) "+expr);
return 1.0 + condComplexity(b.left()) + condComplexity(b.right());
} else {
// System.out.println(">>>>>>>> Binary (relatinal) "+expr);
return 0.5 + condComplexity(b.left()) + condComplexity(b.right());
}
} else if (expr instanceof Unary) {
if (((Unary) expr).operator() == Unary.NOT) {
// System.out.println(">>>>>>>>>>>>>>Unary: !"+expr);
return 0.5 + condComplexity(((Unary) expr).expr());
} else {
// System.out.println(">>>>>>>>>>>>>>unary but Not ! "+expr);
return condComplexity(((Unary) expr).expr());
}
} else {
return 1;// should return something as it is a condition after all
}
| 330
| 351
| 681
|
<methods>public void <init>(polyglot.ast.Node) ,public abstract void addMetrics(soot.toolkits.astmetrics.ClassData) ,public final polyglot.visit.NodeVisitor enter(polyglot.ast.Node) ,public final void execute() ,public final soot.toolkits.astmetrics.ClassData getClassData() ,public final polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public void printAstMetric(polyglot.ast.Node, polyglot.util.CodeWriter) ,public abstract void reset() <variables>polyglot.ast.Node astNode,java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/ConstructNumbersMetric.java
|
ConstructNumbersMetric
|
enter
|
class ConstructNumbersMetric extends ASTMetric {
private int numIf, numIfElse;
private int numLabeledBlocks;
private int doLoop, forLoop, whileLoop, whileTrue;
public ConstructNumbersMetric(Node node) {
super(node);
}
public void reset() {
numIf = numIfElse = 0;
numLabeledBlocks = 0;
doLoop = forLoop = whileLoop = whileTrue = 0;
}
public void addMetrics(ClassData data) {
// TODO Auto-generated method stub
// conditionals
data.addMetric(new MetricData("If", new Integer(numIf)));
data.addMetric(new MetricData("IfElse", new Integer(numIfElse)));
data.addMetric(new MetricData("Total-Conditionals", new Integer(numIf + numIfElse)));
// labels
data.addMetric(new MetricData("LabelBlock", new Integer(numLabeledBlocks)));
// loops
data.addMetric(new MetricData("Do", new Integer(doLoop)));
data.addMetric(new MetricData("For", new Integer(forLoop)));
data.addMetric(new MetricData("While", new Integer(whileLoop)));
data.addMetric(new MetricData("UnConditional", new Integer(whileTrue)));
data.addMetric(new MetricData("Total Loops", new Integer(whileTrue + whileLoop + forLoop + doLoop)));
}
public NodeVisitor enter(Node parent, Node n) {<FILL_FUNCTION_BODY>}
}
|
/*
* Num if and ifelse
*/
if (n instanceof If) {
// check if there is the "optional" else branch present
If ifNode = (If) n;
Stmt temp = ifNode.alternative();
if (temp == null) {
// else branch is empty
// System.out.println("This was an if stmt"+n);
numIf++;
} else {
// else branch has something
// System.out.println("This was an ifElse stmt"+n);
numIfElse++;
}
}
/*
* Num Labeled Blocks
*/
if (n instanceof Labeled) {
Stmt s = ((Labeled) n).statement();
// System.out.println("labeled"+((Labeled)n).label());
if (s instanceof Block) {
// System.out.println("labeled block with label"+((Labeled)n).label());
numLabeledBlocks++;
}
}
/*
* Do
*/
if (n instanceof Do) {
// System.out.println((Do)n);
doLoop++;
}
/*
* For
*/
if (n instanceof For) {
// System.out.println((For)n);
forLoop++;
}
/*
* While and While True loop
*/
if (n instanceof While) {
// System.out.println((While)n);
if (((While) n).condIsConstantTrue()) {
whileTrue++;
} else {
whileLoop++;
}
}
return enter(n);
| 415
| 426
| 841
|
<methods>public void <init>(polyglot.ast.Node) ,public abstract void addMetrics(soot.toolkits.astmetrics.ClassData) ,public final polyglot.visit.NodeVisitor enter(polyglot.ast.Node) ,public final void execute() ,public final soot.toolkits.astmetrics.ClassData getClassData() ,public final polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public void printAstMetric(polyglot.ast.Node, polyglot.util.CodeWriter) ,public abstract void reset() <variables>polyglot.ast.Node astNode,java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/MetricData.java
|
MetricData
|
toString
|
class MetricData {
String metricName;
Object value;
public MetricData(String name, Object val) {
metricName = name;
value = val;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuffer b = new StringBuffer();
b.append("<Metric>\n");
b.append(" <MetricName>" + metricName + "</MetricName>\n");
b.append(" <Value>" + value.toString() + "</Value>\n");
b.append("</Metric>\n");
return b.toString();
| 71
| 97
| 168
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/astmetrics/StmtSumWeightedByDepth.java
|
StmtSumWeightedByDepth
|
leave
|
class StmtSumWeightedByDepth extends ASTMetric {
int currentDepth;
int sum;
int maxDepth;
int numNodes;
Stack<ArrayList> labelNodesSoFar = new Stack<ArrayList>();
ArrayList<Node> blocksWithAbruptFlow = new ArrayList<Node>();
HashMap<Node, Integer> stmtToMetric = new HashMap<Node, Integer>();
HashMap<Node, Integer> stmtToMetricDepth = new HashMap<Node, Integer>();
public static boolean tmpAbruptChecker = false;
public StmtSumWeightedByDepth(Node node) {
super(node);
}
public void printAstMetric(Node n, CodeWriter w) {
if (n instanceof Stmt) {
if (stmtToMetric.containsKey(n)) {
w.write(" // sum= " + stmtToMetric.get(n) + " : depth= " + stmtToMetricDepth.get(n) + "\t");
}
}
}
public void reset() {
// if not one, then fields and method sigs don't get counted
currentDepth = 1; // inside a class
maxDepth = 1;
sum = 0;
numNodes = 0;
}
public void addMetrics(ClassData data) {
// data.addMetric(new MetricData("MaxDepth",new Integer(maxDepth)));
data.addMetric(new MetricData("D-W-Complexity", new Double(sum)));
data.addMetric(new MetricData("AST-Node-Count", new Integer(numNodes)));
}
private void increaseDepth() {
System.out.println("Increasing depth");
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
}
private void decreaseDepth() {
System.out.println("Decreasing depth");
currentDepth--;
}
/*
* List of Node types which increase depth of traversal!!! Any construct where one can have a { } increases the depth hence
* even though if(cond) stmt doesnt expicitly use a block its depth is still +1 when executing the stmt
*
* If the "if" stmt has code if(cond) { stmt } OR if(cond) stmt this will only increase the depth by 1 (ignores compound
* stmt blocks)
*
* If, Loop, Try, Synch, ProcDecl, Init, Switch, LocalClassDecl .... add currentDepth to sum and then increase depth by one
* irrespective of how many stmts there are in the body
*
* Block ... if it is a block within a block, add currentDepth plus increment depth ONLY if it has abrupt flow out of it.
*/
public NodeVisitor enter(Node parent, Node n) {
numNodes++;
if (n instanceof CodeDecl) {
// maintain stack of label arrays (can't have label from inside method to outside)
labelNodesSoFar.push(new ArrayList());
} else if (n instanceof Labeled) {
// add any labels we find to the array
labelNodesSoFar.peek().add(((Labeled) n).label());
}
if (n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch || n instanceof LocalClassDecl
|| n instanceof Synchronized || n instanceof ProcedureDecl || n instanceof Initializer) {
sum += currentDepth * 2;
System.out.println(n);
increaseDepth();
} else if (parent instanceof Block && n instanceof Block) {
StmtSumWeightedByDepth.tmpAbruptChecker = false;
n.visit(new NodeVisitor() {
// extended NodeVisitor that checks for branching out of a block
public NodeVisitor enter(Node parent, Node node) {
if (node instanceof Branch) {
Branch b = (Branch) node;
// null branching out of a plain block is NOT ALLOWED!
if (b.label() != null && labelNodesSoFar.peek().contains(b.label())) {
StmtSumWeightedByDepth.tmpAbruptChecker = true;
}
}
return enter(node);
}
// this method simply stops further node visiting if we found our info
public Node override(Node parent, Node node) {
if (StmtSumWeightedByDepth.tmpAbruptChecker) {
return node;
}
return null;
}
});
if (StmtSumWeightedByDepth.tmpAbruptChecker) {
blocksWithAbruptFlow.add(n);
sum += currentDepth * 2;
System.out.println(n);
increaseDepth();
}
}
// switch from Stmt to Expr here, since Expr is the smallest unit
else if (n instanceof Expr || n instanceof Formal) {
System.out.print(sum + " " + n + " ");
sum += currentDepth * 2;
System.out.println(sum);
}
// carry metric cummulative for each statement for metricPrettyPrinter
if (n instanceof Stmt) {
stmtToMetric.put(n, new Integer(sum));
stmtToMetricDepth.put(n, new Integer(currentDepth));
}
return enter(n);
}
public Node leave(Node old, Node n, NodeVisitor v) {<FILL_FUNCTION_BODY>}
}
|
// stack maintenance, if leaving a method
if (n instanceof CodeDecl) {
labelNodesSoFar.pop();
}
if (n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch || n instanceof LocalClassDecl
|| n instanceof Synchronized || n instanceof ProcedureDecl || n instanceof Initializer) {
decreaseDepth();
} else if (n instanceof Block && blocksWithAbruptFlow.contains(n)) {
decreaseDepth();
}
return n;
| 1,387
| 125
| 1,512
|
<methods>public void <init>(polyglot.ast.Node) ,public abstract void addMetrics(soot.toolkits.astmetrics.ClassData) ,public final polyglot.visit.NodeVisitor enter(polyglot.ast.Node) ,public final void execute() ,public final soot.toolkits.astmetrics.ClassData getClassData() ,public final polyglot.ast.Node leave(polyglot.ast.Node, polyglot.ast.Node, polyglot.ast.Node, polyglot.visit.NodeVisitor) ,public void printAstMetric(polyglot.ast.Node, polyglot.util.CodeWriter) ,public abstract void reset() <variables>polyglot.ast.Node astNode,java.lang.String className
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/exceptions/DuplicateCatchAllTrapRemover.java
|
DuplicateCatchAllTrapRemover
|
internalTransform
|
class DuplicateCatchAllTrapRemover extends BodyTransformer {
public DuplicateCatchAllTrapRemover(Singletons.Global g) {
}
public static DuplicateCatchAllTrapRemover v() {
return soot.G.v().soot_toolkits_exceptions_DuplicateCatchAllTrapRemover();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>}
/**
* Checks whether the given trap covers the given unit, i.e., there is an exceptional control flow from the given unit to
* the given trap
*
* @param b
* The body containing the unit and the trap
* @param trap
* The trap
* @param unit
* The unit
* @return True if there can be an exceptional control flow from the given unit to the given trap
*/
private boolean trapCoversUnit(Body b, Trap trap, Unit unit) {
for (Iterator<Unit> unitIt = b.getUnits().iterator(trap.getBeginUnit(), trap.getEndUnit()); unitIt.hasNext();) {
Unit u = unitIt.next();
if (u == unit) {
return true;
}
}
return false;
}
}
|
// Find two traps that use java.lang.Throwable as their type and that
// span the same code region
for (Iterator<Trap> t1It = b.getTraps().snapshotIterator(); t1It.hasNext();) {
Trap t1 = t1It.next();
if (t1.getException().getName().equals(Scene.v().getBaseExceptionType().toString())) {
for (Iterator<Trap> t2It = b.getTraps().snapshotIterator(); t2It.hasNext();) {
Trap t2 = t2It.next();
if (t1 != t2 && t1.getBeginUnit() == t2.getBeginUnit() && t1.getEndUnit() == t2.getEndUnit()
&& t2.getException().getName().equals(Scene.v().getBaseExceptionType().toString())) {
// Both traps (t1, t2) span the same code and catch java.lang.Throwable.
// Check if one trap jumps to a target that then jumps to the target of
// the other trap.
for (Trap t3 : b.getTraps()) {
if (t3 != t1 && t3 != t2 && t3.getException().getName().equals(Scene.v().getBaseExceptionType().toString())) {
if (trapCoversUnit(b, t3, t1.getHandlerUnit()) && t3.getHandlerUnit() == t2.getHandlerUnit()) {
// c -> t1 -> t3 -> t2 && c -> t2
b.getTraps().remove(t2);
break;
} else if (trapCoversUnit(b, t3, t2.getHandlerUnit()) && t3.getHandlerUnit() == t1.getHandlerUnit()) {
// c -> t2 -> t3 -> t1 && c -> t1
b.getTraps().remove(t1);
break;
}
}
}
}
}
}
}
| 341
| 511
| 852
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/exceptions/ThrowAnalysisFactory.java
|
ThrowAnalysisFactory
|
checkInitThrowAnalysis
|
class ThrowAnalysisFactory {
/**
* Resolve the ThrowAnalysis to be used for initialization checking (e.g. soot.Body.checkInit())
*/
public static ThrowAnalysis checkInitThrowAnalysis() {<FILL_FUNCTION_BODY>}
private ThrowAnalysisFactory() {
}
}
|
final Options opts = Options.v();
switch (opts.check_init_throw_analysis()) {
case Options.check_init_throw_analysis_auto:
if (!opts.android_jars().isEmpty() || !opts.force_android_jar().isEmpty()) {
// If Android related options are set, use 'dalvik' throw analysis.
return DalvikThrowAnalysis.v();
} else {
return PedanticThrowAnalysis.v();
}
case Options.check_init_throw_analysis_pedantic:
return PedanticThrowAnalysis.v();
case Options.check_init_throw_analysis_unit:
return UnitThrowAnalysis.v();
case Options.check_init_throw_analysis_dalvik:
return DalvikThrowAnalysis.v();
default:
assert false; // The above cases should cover all posible options
return PedanticThrowAnalysis.v();
}
| 83
| 227
| 310
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/exceptions/TrapTightener.java
|
TrapTightener
|
internalTransform
|
class TrapTightener extends TrapTransformer {
private static final Logger logger = LoggerFactory.getLogger(TrapTightener.class);
protected ThrowAnalysis throwAnalysis = null;
public TrapTightener(Singletons.Global g) {
}
public static TrapTightener v() {
return soot.G.v().soot_toolkits_exceptions_TrapTightener();
}
public TrapTightener(ThrowAnalysis ta) {
this.throwAnalysis = ta;
}
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>}
/**
* A utility routine which determines if a particular {@link Unit} might throw an exception to a particular {@link Trap},
* according to the information supplied by a particular control flow graph.
*
* @param g
* The control flow graph providing information about exceptions.
* @param u
* The unit being inquired about.
* @param t
* The trap being inquired about.
* @return <tt>true</tt> if <tt>u</tt> might throw an exception caught by <tt>t</tt>, according to <tt>g</tt.
*/
protected boolean mightThrowTo(ExceptionalUnitGraph g, Unit u, Trap t) {
for (ExceptionDest dest : g.getExceptionDests(u)) {
if (dest.getTrap() == t) {
return true;
}
}
return false;
}
}
|
if (this.throwAnalysis == null) {
this.throwAnalysis = Scene.v().getDefaultThrowAnalysis();
}
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Tightening trap boundaries...");
}
Chain<Trap> trapChain = body.getTraps();
Chain<Unit> unitChain = body.getUnits();
if (trapChain.size() > 0) {
ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis);
Set<Unit> unitsWithMonitor = getUnitsWithMonitor(graph);
for (Iterator<Trap> trapIt = trapChain.iterator(); trapIt.hasNext();) {
Trap trap = trapIt.next();
boolean isCatchAll = trap.getException().getName().equals(Scene.v().getBaseExceptionType().toString());
Unit firstTrappedUnit = trap.getBeginUnit();
Unit firstTrappedThrower = null;
Unit firstUntrappedUnit = trap.getEndUnit();
Unit lastTrappedUnit = unitChain.getPredOf(firstUntrappedUnit);
Unit lastTrappedThrower = null;
for (Unit u = firstTrappedUnit; u != null && u != firstUntrappedUnit; u = unitChain.getSuccOf(u)) {
if (mightThrowTo(graph, u, trap)) {
firstTrappedThrower = u;
break;
}
// If this is the catch-all block and the current unit has
// an,
// active monitor, we need to keep the block
if (isCatchAll && unitsWithMonitor.contains(u)) {
if (firstTrappedThrower == null) {
firstTrappedThrower = u;
}
break;
}
}
if (firstTrappedThrower != null) {
for (Unit u = lastTrappedUnit; u != null; u = unitChain.getPredOf(u)) {
// If this is the catch-all block and the current unit
// has an, active monitor, we need to keep the block
if (mightThrowTo(graph, u, trap) || (isCatchAll && unitsWithMonitor.contains(u))) {
lastTrappedThrower = u;
break;
}
}
}
// If no statement inside the trap can throw an exception, we
// remove the complete trap.
if (firstTrappedThrower == null) {
trapIt.remove();
} else {
if (firstTrappedThrower != null && firstTrappedUnit != firstTrappedThrower) {
trap.setBeginUnit(firstTrappedThrower);
}
if (lastTrappedThrower == null) {
lastTrappedThrower = firstTrappedUnit;
}
if (lastTrappedUnit != lastTrappedThrower) {
trap.setEndUnit(unitChain.getSuccOf(lastTrappedThrower));
}
}
}
}
| 400
| 765
| 1,165
|
<methods>public non-sealed void <init>() ,public Set<soot.Unit> getUnitsWithMonitor(soot.toolkits.graph.UnitGraph) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/exceptions/TrapTransformer.java
|
TrapTransformer
|
getUnitsWithMonitor
|
class TrapTransformer extends BodyTransformer {
public Set<Unit> getUnitsWithMonitor(UnitGraph ug) {<FILL_FUNCTION_BODY>}
}
|
// Idea: Associate each unit with a set of monitors held at that
// statement
MultiMap<Unit, Value> unitMonitors = new HashMultiMap<>();
// Start at the heads of the unit graph
List<Unit> workList = new ArrayList<>();
Set<Unit> doneSet = new HashSet<>();
for (Unit head : ug.getHeads()) {
workList.add(head);
}
while (!workList.isEmpty()) {
Unit curUnit = workList.remove(0);
boolean hasChanged = false;
Value exitValue = null;
if (curUnit instanceof EnterMonitorStmt) {
// We enter a new monitor
EnterMonitorStmt ems = (EnterMonitorStmt) curUnit;
hasChanged = unitMonitors.put(curUnit, ems.getOp());
} else if (curUnit instanceof ExitMonitorStmt) {
// We leave a monitor
ExitMonitorStmt ems = (ExitMonitorStmt) curUnit;
exitValue = ems.getOp();
}
// Copy over the monitors from the predecessors
for (Unit pred : ug.getPredsOf(curUnit)) {
for (Value v : unitMonitors.get(pred)) {
if (v != exitValue) {
if (unitMonitors.put(curUnit, v)) {
hasChanged = true;
}
}
}
}
// Work on the successors
if (doneSet.add(curUnit) || hasChanged) {
workList.addAll(ug.getSuccsOf(curUnit));
}
}
return unitMonitors.keySet();
| 45
| 419
| 464
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/ArrayRefBlockGraph.java
|
ArrayRefBlockGraph
|
computeLeaders
|
class ArrayRefBlockGraph extends BlockGraph {
/**
* <p>
* Constructs an {@link ArrayRefBlockGraph} from the given {@link Body}.
* </p>
*
* <p>
* Note that this constructor builds a {@link BriefUnitGraph} internally when splitting <tt>body</tt>'s {@link Unit}s into
* {@link Block}s. Callers who need both a {@link BriefUnitGraph} and an {@link ArrayRefBlockGraph} should use the
* constructor taking the <tt>BriefUnitGraph</tt> as a parameter, as a minor optimization.
* </p>
*
* @param body
* the Body instance from which the graph is built.
*/
public ArrayRefBlockGraph(Body body) {
this(new BriefUnitGraph(body));
}
/**
* Constructs an <tt>ArrayRefBlockGraph</tt> corresponding to the <tt>Unit</tt>-level control flow represented by the
* passed {@link BriefUnitGraph}.
*
* @param unitGraph
* The <tt>BriefUnitGraph</tt> for which to build an <tt>ArrayRefBlockGraph</tt>.
*/
public ArrayRefBlockGraph(BriefUnitGraph unitGraph) {
super(unitGraph);
soot.util.PhaseDumper.v().dumpGraph(this, mBody);
}
/**
* <p>
* Utility method for computing the basic block leaders for a {@link Body}, given its {@link UnitGraph} (i.e., the
* instructions which begin new basic blocks).
* </p>
*
* <p>
* This implementation chooses as block leaders all the <tt>Unit</tt>s that {@link BlockGraph.computerLeaders()}, and adds:
*
* <ul>
*
* <li>All <tt>Unit</tt>s which contain an array reference, as defined by {@link Stmt.containsArrayRef()} and
* {@link Inst.containsArrayRef()}.
*
* <li>The first <tt>Unit</tt> not covered by each {@link Trap} (i.e., the <tt>Unit</tt> returned by
* {@link Trap.getLastUnit()}.</li>
*
* </ul>
* </p>
*
* @param unitGraph
* is the <tt>Unit</tt>-level CFG which is to be split into basic blocks.
*
* @return the {@link Set} of {@link Unit}s in <tt>unitGraph</tt> which are block leaders.
*/
@Override
protected Set<Unit> computeLeaders(UnitGraph unitGraph) {<FILL_FUNCTION_BODY>}
}
|
Body body = unitGraph.getBody();
if (body != mBody) {
throw new RuntimeException(
"ArrayRefBlockGraph.computeLeaders() called with a UnitGraph that doesn't match its mBody.");
}
Set<Unit> leaders = super.computeLeaders(unitGraph);
for (Unit unit : body.getUnits()) {
if (((unit instanceof Stmt) && ((Stmt) unit).containsArrayRef())
|| ((unit instanceof Inst) && ((Inst) unit).containsArrayRef())) {
leaders.add(unit);
}
}
return leaders;
| 705
| 152
| 857
|
<methods>public List<soot.toolkits.graph.Block> getBlocks() ,public soot.Body getBody() ,public List<soot.toolkits.graph.Block> getHeads() ,public List<soot.toolkits.graph.Block> getPredsOf(soot.toolkits.graph.Block) ,public List<soot.toolkits.graph.Block> getSuccsOf(soot.toolkits.graph.Block) ,public List<soot.toolkits.graph.Block> getTails() ,public Iterator<soot.toolkits.graph.Block> iterator() ,public int size() ,public java.lang.String toString() <variables>protected List<soot.toolkits.graph.Block> mBlocks,protected soot.Body mBody,protected List<soot.toolkits.graph.Block> mHeads,protected List<soot.toolkits.graph.Block> mTails,protected Chain<soot.Unit> mUnits
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/ClassicCompleteUnitGraph.java
|
ClassicCompleteUnitGraph
|
buildExceptionalEdges
|
class ClassicCompleteUnitGraph extends TrapUnitGraph {
/**
* Constructs the graph from a given Body instance.
*
* @param body
* the Body instance from which the graph is built.
*/
public ClassicCompleteUnitGraph(Body body) {
// The TrapUnitGraph constructor will use our buildExceptionalEdges:
super(body);
}
/**
* Method to compute the edges corresponding to exceptional control flow.
*
* @param unitToSuccs
* A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is * an ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a mapping for every <tt>Unit</tt> within the scope of one or more
* {@link Trap}s to a <tt>List</tt> of the handler units of those <tt>Trap</tt>s.
*
* @param unitToPreds
* A {@link Map} from {@link Unit}s to {@link List}s of {@link Unit}s. This is an ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a mapping for every {@link Trap} handler to all the <tt>Unit</tt>s
* within the scope of that <tt>Trap</tt>.
*/
@Override
protected void buildExceptionalEdges(Map<Unit, List<Unit>> unitToSuccs, Map<Unit, List<Unit>> unitToPreds) {<FILL_FUNCTION_BODY>}
}
|
// First, add the same edges as TrapUnitGraph.
super.buildExceptionalEdges(unitToSuccs, unitToPreds);
// Then add edges from the predecessors of the first
// trapped Unit for each Trap.
for (Trap trap : body.getTraps()) {
Unit catcher = trap.getHandlerUnit();
// Make a copy of firstTrapped's predecessors to iterate over,
// just in case we're about to add new predecessors to this
// very list, though that can only happen if the handler traps
// itself. And to really allow for that
// possibility, we should iterate here until we reach a fixed
// point; but the old UnitGraph that we are attempting to
// duplicate did not do that, so we won't either.
for (Unit pred : new ArrayList<Unit>(getPredsOf(trap.getBeginUnit()))) {
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
| 399
| 254
| 653
|
<methods>public void <init>(soot.Body) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/CytronDominanceFrontier.java
|
CytronDominanceFrontier
|
processNode
|
class CytronDominanceFrontier<N> implements DominanceFrontier<N> {
protected DominatorTree<N> dt;
protected Map<DominatorNode<N>, List<DominatorNode<N>>> nodeToFrontier;
public CytronDominanceFrontier(DominatorTree<N> dt) {
this.dt = dt;
this.nodeToFrontier = new HashMap<DominatorNode<N>, List<DominatorNode<N>>>();
for (DominatorNode<N> head : dt.getHeads()) {
bottomUpDispatch(head);
}
for (N gode : dt.graph) {
DominatorNode<N> dode = dt.fetchDode(gode);
if (dode == null) {
throw new RuntimeException("dode == null");
} else if (!isFrontierKnown(dode)) {
throw new RuntimeException("Frontier not defined for node: " + dode);
}
}
}
@Override
public List<DominatorNode<N>> getDominanceFrontierOf(DominatorNode<N> node) {
List<DominatorNode<N>> frontier = nodeToFrontier.get(node);
if (frontier == null) {
throw new RuntimeException("Frontier not defined for node: " + node);
}
return Collections.unmodifiableList(frontier);
}
protected boolean isFrontierKnown(DominatorNode<N> node) {
return nodeToFrontier.containsKey(node);
}
/**
* Make sure we visit children first. This is reverse topological order.
*/
protected void bottomUpDispatch(DominatorNode<N> node) {
// *** FIXME: It's annoying that this algorithm is so
// *** inefficient in that in traverses the tree from the head
// *** to the tail before it does anything.
if (isFrontierKnown(node)) {
return;
}
for (DominatorNode<N> child : dt.getChildrenOf(node)) {
if (!isFrontierKnown(child)) {
bottomUpDispatch(child);
}
}
processNode(node);
}
/**
* Calculate dominance frontier for a set of basic blocks.
*
* <p>
* Uses the algorithm of Cytron et al., TOPLAS Oct. 91:
*
* <pre>
* <code>
* for each X in a bottom-up traversal of the dominator tree do
*
* DF(X) < - null
* for each Y in Succ(X) do
* if (idom(Y)!=X) then DF(X) <- DF(X) U Y
* end
* for each Z in {idom(z) = X} do
* for each Y in DF(Z) do
* if (idom(Y)!=X) then DF(X) <- DF(X) U Y
* end
* end
* </code>
* </pre>
*/
protected void processNode(DominatorNode<N> node) {<FILL_FUNCTION_BODY>}
}
|
HashSet<DominatorNode<N>> dominanceFrontier = new HashSet<DominatorNode<N>>();
// local
for (DominatorNode<N> succ : dt.getSuccsOf(node)) {
if (!dt.isImmediateDominatorOf(node, succ)) {
dominanceFrontier.add(succ);
}
}
// up
for (DominatorNode<N> child : dt.getChildrenOf(node)) {
for (DominatorNode<N> childFront : getDominanceFrontierOf(child)) {
if (!dt.isImmediateDominatorOf(node, childFront)) {
dominanceFrontier.add(childFront);
}
}
}
nodeToFrontier.put(node, new ArrayList<>(dominanceFrontier));
| 851
| 222
| 1,073
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/DominatorNode.java
|
DominatorNode
|
addChild
|
class DominatorNode<N> {
protected N gode;
protected DominatorNode<N> parent;
protected List<DominatorNode<N>> children;
protected DominatorNode(N gode) {
this.gode = gode;
this.children = new ArrayList<DominatorNode<N>>();
}
/**
* Sets the parent of this node in the DominatorTree. Usually called internally.
**/
public void setParent(DominatorNode<N> parent) {
this.parent = parent;
}
/**
* Adds a child to the internal list of children of this node in tree. Usually called internally.
**/
public boolean addChild(DominatorNode<N> child) {<FILL_FUNCTION_BODY>}
/**
* Returns the node (from the original DirectedGraph) encapsulated by this DominatorNode.
**/
public N getGode() {
return gode;
}
/**
* Returns the parent of the node in the DominatorTree.
**/
public DominatorNode<N> getParent() {
return parent;
}
/**
* Returns a backed list of the children of this node in the DominatorTree.
**/
public List<DominatorNode<N>> getChildren() {
return children;
}
/**
* Returns true if this node is the head of its DominatorTree.
**/
public boolean isHead() {
return parent == null;
}
/**
* Returns true if this node is a tail of its DominatorTree.
**/
public boolean isTail() {
return children.isEmpty();
}
@Override
public String toString() {
// *** FIXME: Print info about parent and children
return gode.toString();
}
}
|
if (children.contains(child)) {
return false;
} else {
children.add(child);
return true;
}
| 473
| 40
| 513
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/DominatorTree.java
|
DominatorTree
|
fetchParent
|
class DominatorTree<N> implements Iterable<DominatorNode<N>> {
private static final Logger logger = LoggerFactory.getLogger(DominatorTree.class);
protected final DominatorsFinder<N> dominators;
protected final DirectedGraph<N> graph;
protected final List<DominatorNode<N>> heads;
protected final List<DominatorNode<N>> tails;
/**
* "gode" is a node in the original graph, "dode" is a node in the dominator tree.
*/
protected final Map<N, DominatorNode<N>> godeToDode;
public DominatorTree(DominatorsFinder<N> dominators) {
// if(Options.v().verbose())
// logger.debug("[" + graph.getBody().getMethod().getName() +
// "] Constructing DominatorTree...");
this.dominators = dominators;
this.graph = dominators.getGraph();
this.heads = new ArrayList<DominatorNode<N>>();
this.tails = new ArrayList<DominatorNode<N>>();
this.godeToDode = new HashMap<N, DominatorNode<N>>();
buildTree();
}
/**
* @return the original graph to which the DominatorTree pertains
*/
public DirectedGraph<N> getGraph() {
return dominators.getGraph();
}
/**
* @return the root of the dominator tree.
*/
public List<DominatorNode<N>> getHeads() {
return Collections.unmodifiableList(heads);
}
/**
* Gets the first head of the dominator tree. This function is implemented for single-headed trees and mainly for backwards
* compatibility.
*
* @return The first head of the dominator tree
*/
public DominatorNode<N> getHead() {
return heads.isEmpty() ? null : heads.get(0);
}
/**
* @return list of the tails of the dominator tree.
*/
public List<DominatorNode<N>> getTails() {
return Collections.unmodifiableList(tails);
}
/**
* @return the parent of {@code node} in the tree, null if the node is at the root.
*/
public DominatorNode<N> getParentOf(DominatorNode<N> node) {
return node.getParent();
}
/**
* @return the children of node in the tree.
*/
public List<DominatorNode<N>> getChildrenOf(DominatorNode<N> node) {
return Collections.unmodifiableList(node.getChildren());
}
/**
* @return list of the DominatorNodes corresponding to the predecessors of {@code node} in the original DirectedGraph
*/
public List<DominatorNode<N>> getPredsOf(DominatorNode<N> node) {
List<DominatorNode<N>> predNodes = new ArrayList<DominatorNode<N>>();
for (N pred : graph.getPredsOf(node.getGode())) {
predNodes.add(getDode(pred));
}
return predNodes;
}
/**
* @return list of the DominatorNodes corresponding to the successors of {@code node} in the original DirectedGraph
*/
public List<DominatorNode<N>> getSuccsOf(DominatorNode<N> node) {
List<DominatorNode<N>> succNodes = new ArrayList<DominatorNode<N>>();
for (N succ : graph.getSuccsOf(node.getGode())) {
succNodes.add(getDode(succ));
}
return succNodes;
}
/**
* @return true if idom immediately dominates node.
*/
public boolean isImmediateDominatorOf(DominatorNode<N> idom, DominatorNode<N> node) {
// node.getParent() could be null
return (node.getParent() == idom);
}
/**
* @return true if dom dominates node.
*/
public boolean isDominatorOf(DominatorNode<N> dom, DominatorNode<N> node) {
return dominators.isDominatedBy(node.getGode(), dom.getGode());
}
/**
* @return DominatorNode for a given node in the original DirectedGraph.
*/
public DominatorNode<N> getDode(N gode) {
DominatorNode<N> dode = godeToDode.get(gode);
if (dode == null) {
throw new RuntimeException(
"Assertion failed: Dominator tree does not have a corresponding dode for gode (" + gode + ")");
}
return dode;
}
/**
* @return iterator over the nodes in the tree. No ordering is implied.
*/
@Override
public Iterator<DominatorNode<N>> iterator() {
return godeToDode.values().iterator();
}
/**
* @return the number of nodes in the tree
*/
public int size() {
return godeToDode.size();
}
/**
* Add all the necessary links between nodes to form a meaningful tree structure.
*/
protected void buildTree() {
// hook up children with parents and vice-versa
for (N gode : graph) {
DominatorNode<N> dode = fetchDode(gode);
DominatorNode<N> parent = fetchParent(gode);
if (parent == null) {
heads.add(dode);
} else {
parent.addChild(dode);
dode.setParent(parent);
}
}
// identify the tail nodes
for (DominatorNode<N> dode : this) {
if (dode.isTail()) {
tails.add(dode);
}
}
if (heads instanceof ArrayList) {
((ArrayList<?>) heads).trimToSize(); // potentially a long-lived object
}
if (tails instanceof ArrayList) {
((ArrayList<?>) tails).trimToSize(); // potentially a long-lived object
}
}
/**
* Convenience method, ensures we don't create more than one DominatorNode for a given block.
*/
protected DominatorNode<N> fetchDode(N gode) {
DominatorNode<N> dode = godeToDode.get(gode);
if (dode == null) {
dode = new DominatorNode<N>(gode);
godeToDode.put(gode, dode);
}
return dode;
}
protected DominatorNode<N> fetchParent(N gode) {<FILL_FUNCTION_BODY>}
}
|
N immediateDominator = dominators.getImmediateDominator(gode);
return (immediateDominator == null) ? null : fetchDode(immediateDominator);
| 1,761
| 49
| 1,810
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/HashReversibleGraph.java
|
HashReversibleGraph
|
addEdge
|
class HashReversibleGraph<N> extends HashMutableDirectedGraph<N> implements ReversibleGraph<N> {
protected boolean reversed;
public HashReversibleGraph(DirectedGraph<N> dg) {
this();
for (N s : dg) {
addNode(s);
}
for (N s : dg) {
for (N t : dg.getSuccsOf(s)) {
addEdge(s, t);
}
}
/* use the same heads and tails as the original graph */
heads.clear();
heads.addAll(dg.getHeads());
tails.clear();
tails.addAll(dg.getTails());
}
public HashReversibleGraph() {
super();
reversed = false;
}
@Override
public boolean isReversed() {
return reversed;
}
@Override
public ReversibleGraph<N> reverse() {
reversed = !reversed;
return this;
}
@Override
public void addEdge(N from, N to) {<FILL_FUNCTION_BODY>}
@Override
public void removeEdge(N from, N to) {
if (reversed) {
super.removeEdge(to, from);
} else {
super.removeEdge(from, to);
}
}
@Override
public boolean containsEdge(N from, N to) {
return reversed ? super.containsEdge(to, from) : super.containsEdge(from, to);
}
@Override
public List<N> getHeads() {
return reversed ? super.getTails() : super.getHeads();
}
@Override
public List<N> getTails() {
return reversed ? super.getHeads() : super.getTails();
}
@Override
public List<N> getPredsOf(N s) {
return reversed ? super.getSuccsOf(s) : super.getPredsOf(s);
}
@Override
public List<N> getSuccsOf(N s) {
return reversed ? super.getPredsOf(s) : super.getSuccsOf(s);
}
}
|
if (reversed) {
super.addEdge(to, from);
} else {
super.addEdge(from, to);
}
| 594
| 42
| 636
|
<methods>public void <init>() ,public void <init>(HashMutableDirectedGraph<N>) ,public void addEdge(N, N) ,public void addNode(N) ,public void clearAll() ,public java.lang.Object clone() ,public boolean containsEdge(N, N) ,public boolean containsNode(N) ,public List<N> getHeads() ,public List<N> getNodes() ,public List<N> getPredsOf(N) ,public Set<N> getPredsOfAsSet(N) ,public List<N> getSuccsOf(N) ,public Set<N> getSuccsOfAsSet(N) ,public List<N> getTails() ,public Iterator<N> iterator() ,public void printGraph() ,public void removeEdge(N, N) ,public void removeNode(N) ,public int size() <variables>protected final non-sealed Set<N> heads,private static final org.slf4j.Logger logger,protected final non-sealed Map<N,Set<N>> nodeToPreds,protected final non-sealed Map<N,Set<N>> nodeToSuccs,protected final non-sealed Set<N> tails
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/MHGDominatorsFinder.java
|
MHGDominatorsFinder
|
isDominatedByAll
|
class MHGDominatorsFinder<N> implements DominatorsFinder<N> {
protected final DirectedGraph<N> graph;
protected final Set<N> heads;
protected final Map<N, BitSet> nodeToFlowSet;
protected final Map<N, Integer> nodeToIndex;
protected final Map<Integer, N> indexToNode;
protected int lastIndex = 0;
public MHGDominatorsFinder(DirectedGraph<N> graph) {
this.graph = graph;
this.heads = new HashSet<>(graph.getHeads());
int size = graph.size() * 2 + 1;
this.nodeToFlowSet = new HashMap<N, BitSet>(size, 0.7f);
this.nodeToIndex = new HashMap<N, Integer>(size, 0.7f);
this.indexToNode = new HashMap<Integer, N>(size, 0.7f);
doAnalysis();
}
protected void doAnalysis() {
final DirectedGraph<N> graph = this.graph;
// build full set
BitSet fullSet = new BitSet(graph.size());
fullSet.flip(0, graph.size());// set all to true
// set up domain for intersection: head nodes are only dominated by themselves,
// other nodes are dominated by everything else
for (N o : graph) {
if (heads.contains(o)) {
BitSet self = new BitSet();
self.set(indexOf(o));
nodeToFlowSet.put(o, self);
} else {
nodeToFlowSet.put(o, fullSet);
}
}
boolean changed;
do {
changed = false;
for (N o : graph) {
if (heads.contains(o)) {
continue;
}
// initialize to the "neutral element" for the intersection
// this clone() is fast on BitSets (opposed to on HashSets)
BitSet predsIntersect = (BitSet) fullSet.clone();
// intersect over all predecessors
for (N next : graph.getPredsOf(o)) {
predsIntersect.and(getDominatorsBitSet(next));
}
BitSet oldSet = getDominatorsBitSet(o);
// each node dominates itself
predsIntersect.set(indexOf(o));
if (!predsIntersect.equals(oldSet)) {
nodeToFlowSet.put(o, predsIntersect);
changed = true;
}
}
} while (changed);
}
protected BitSet getDominatorsBitSet(N node) {
BitSet bitSet = nodeToFlowSet.get(node);
assert (bitSet != null) : "Node " + node + " is not in the graph!";
return bitSet;
}
protected int indexOfAssert(N o) {
Integer index = nodeToIndex.get(o);
assert (index != null) : "Node " + o + " is not in the graph!";
return index;
}
protected int indexOf(N o) {
Integer index = nodeToIndex.get(o);
if (index == null) {
index = lastIndex;
nodeToIndex.put(o, index);
indexToNode.put(index, o);
lastIndex++;
}
return index;
}
@Override
public DirectedGraph<N> getGraph() {
return graph;
}
@Override
public List<N> getDominators(N node) {
// reconstruct list of dominators from bitset
List<N> result = new ArrayList<N>();
BitSet bitSet = getDominatorsBitSet(node);
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
result.add(indexToNode.get(i));
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return result;
}
@Override
public N getImmediateDominator(N node) {
// root node
if (heads.contains(node)) {
return null;
}
BitSet doms = (BitSet) getDominatorsBitSet(node).clone();
doms.clear(indexOfAssert(node));
for (int i = doms.nextSetBit(0); i >= 0; i = doms.nextSetBit(i + 1)) {
N dominator = indexToNode.get(i);
if (isDominatedByAll(dominator, doms)) {
if (dominator != null) {
return dominator;
}
}
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return null;
}
private boolean isDominatedByAll(N node, BitSet doms) {<FILL_FUNCTION_BODY>}
@Override
public boolean isDominatedBy(N node, N dominator) {
return getDominatorsBitSet(node).get(indexOfAssert(dominator));
}
@Override
public boolean isDominatedByAll(N node, Collection<N> dominators) {
BitSet s1 = getDominatorsBitSet(node);
for (N n : dominators) {
if (!s1.get(indexOfAssert(n))) {
return false;
}
}
return true;
}
}
|
BitSet s1 = getDominatorsBitSet(node);
for (int i = doms.nextSetBit(0); i >= 0; i = doms.nextSetBit(i + 1)) {
if (!s1.get(i)) {
return false;
}
if (i == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
return true;
| 1,419
| 110
| 1,529
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/MemoryEfficientGraph.java
|
MemoryEfficientGraph
|
removeEdge
|
class MemoryEfficientGraph<N> extends HashMutableDirectedGraph<N> {
HashMap<N, N> self = new HashMap<N, N>();
@Override
public void addNode(N o) {
super.addNode(o);
self.put(o, o);
}
@Override
public void removeNode(N o) {
super.removeNode(o);
self.remove(o);
}
@Override
public void addEdge(N from, N to) {
if (containsNode(from) && containsNode(to)) {
super.addEdge(self.get(from), self.get(to));
} else if (!containsNode(from)) {
throw new RuntimeException(from.toString() + " not in graph!");
} else {
throw new RuntimeException(to.toString() + " not in graph!");
}
}
@Override
public void removeEdge(N from, N to) {<FILL_FUNCTION_BODY>}
}
|
if (containsNode(from) && containsNode(to)) {
super.removeEdge(self.get(from), self.get(to));
} else if (!containsNode(from)) {
throw new RuntimeException(from.toString() + " not in graph!");
} else {
throw new RuntimeException(to.toString() + " not in graph!");
}
| 261
| 94
| 355
|
<methods>public void <init>() ,public void <init>(HashMutableDirectedGraph<N>) ,public void addEdge(N, N) ,public void addNode(N) ,public void clearAll() ,public java.lang.Object clone() ,public boolean containsEdge(N, N) ,public boolean containsNode(N) ,public List<N> getHeads() ,public List<N> getNodes() ,public List<N> getPredsOf(N) ,public Set<N> getPredsOfAsSet(N) ,public List<N> getSuccsOf(N) ,public Set<N> getSuccsOfAsSet(N) ,public List<N> getTails() ,public Iterator<N> iterator() ,public void printGraph() ,public void removeEdge(N, N) ,public void removeNode(N) ,public int size() <variables>protected final non-sealed Set<N> heads,private static final org.slf4j.Logger logger,protected final non-sealed Map<N,Set<N>> nodeToPreds,protected final non-sealed Map<N,Set<N>> nodeToSuccs,protected final non-sealed Set<N> tails
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/PseudoTopologicalOrderer.java
|
ReverseOrderBuilder
|
computeOrder
|
class ReverseOrderBuilder<N> {
private final DirectedGraph<N> graph;
private final int graphSize;
private final int[] indexStack;
private final N[] stmtStack;
private final Set<N> visited;
private final N[] order;
private int orderLength;
/**
* @param g
* a DirectedGraph instance we want to order the nodes for.
*/
public ReverseOrderBuilder(DirectedGraph<N> g) {
this.graph = g;
final int n = g.size();
this.graphSize = n;
this.visited = Collections.newSetFromMap(new IdentityHashMap<N, Boolean>(n * 2 + 1));
this.indexStack = new int[n];
@SuppressWarnings("unchecked")
N[] tempStmtStack = (N[]) new Object[n];
this.stmtStack = tempStmtStack;
@SuppressWarnings("unchecked")
N[] tempOrder = (N[]) new Object[n];
this.order = tempOrder;
this.orderLength = 0;
}
/**
* Orders in pseudo-topological order.
*
* @param reverse
* specify if we want reverse pseudo-topological ordering, or not.
* @return an ordered list of the graph's nodes.
*/
public List<N> computeOrder(boolean reverse) {<FILL_FUNCTION_BODY>}
// Unfortunately, the nice recursive solution fails
// because of stack overflows
// Fill in the 'order' list with a pseudo topological order
// list of statements starting at s. Simulates recursion with a stack.
private void visitNode(N startStmt) {
int last = 0;
stmtStack[last] = startStmt;
indexStack[last++] = -1;
while (last > 0) {
int toVisitIndex = ++indexStack[last - 1];
N toVisitNode = stmtStack[last - 1];
List<N> succs = graph.getSuccsOf(toVisitNode);
if (toVisitIndex >= succs.size()) {
// Visit this node now that we ran out of children
order[orderLength++] = toVisitNode;
last--;
} else {
N childNode = succs.get(toVisitIndex);
if (visited.add(childNode)) {
stmtStack[last] = childNode;
indexStack[last++] = -1;
}
}
}
}
/**
* Reverses the order of the elements in the specified array.
*
* @param array
*/
private static <T> void reverseArray(T[] array) {
final int max = array.length >> 1;
for (int i = 0, j = array.length - 1; i < max; i++, j--) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
|
// Visit each node
for (N s : graph) {
if (visited.add(s)) {
visitNode(s);
}
if (orderLength == graphSize) {
break;
}
}
if (reverse) {
reverseArray(order);
}
return Arrays.asList(order);
| 783
| 92
| 875
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/SimpleDominatorsFinder.java
|
SimpleDominatorsFinder
|
isDominatedByAll
|
class SimpleDominatorsFinder<N> implements DominatorsFinder<N> {
private static final Logger logger = LoggerFactory.getLogger(SimpleDominatorsFinder.class);
protected final DirectedGraph<N> graph;
protected final Map<N, FlowSet<N>> nodeToDominators;
/**
* Compute dominators for provided singled-headed directed graph.
**/
public SimpleDominatorsFinder(DirectedGraph<N> graph) {
// if(Options.v().verbose())
// logger.debug("[" + graph.getBody().getMethod().getName() +
// "] Finding Dominators...");
this.graph = graph;
this.nodeToDominators = new HashMap<N, FlowSet<N>>(graph.size() * 2 + 1, 0.7f);
// build node to dominators map
SimpleDominatorsAnalysis<N> analysis = new SimpleDominatorsAnalysis<N>(graph);
for (N node : graph) {
this.nodeToDominators.put(node, analysis.getFlowAfter(node));
}
}
@Override
public DirectedGraph<N> getGraph() {
return graph;
}
@Override
public List<N> getDominators(N node) {
// non-backed list since FlowSet is an ArrayPackedFlowSet
return nodeToDominators.get(node).toList();
}
@Override
public N getImmediateDominator(N node) {
// root node
if (getGraph().getHeads().contains(node)) {
return null;
}
// avoid the creation of temp-lists
FlowSet<N> head = nodeToDominators.get(node).clone();
head.remove(node);
for (N dominator : head) {
if (nodeToDominators.get(dominator).isSubSet(head)) {
return dominator;
}
}
return null;
}
@Override
public boolean isDominatedBy(N node, N dominator) {
// avoid the creation of temp-lists
return nodeToDominators.get(node).contains(dominator);
}
@Override
public boolean isDominatedByAll(N node, Collection<N> dominators) {<FILL_FUNCTION_BODY>}
}
|
FlowSet<N> f = nodeToDominators.get(node);
for (N n : dominators) {
if (!f.contains(n)) {
return false;
}
}
return true;
| 606
| 60
| 666
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/StronglyConnectedComponents.java
|
StronglyConnectedComponents
|
visitNode
|
class StronglyConnectedComponents {
private static final Logger logger = LoggerFactory.getLogger(StronglyConnectedComponents.class);
private HashMap<Object, Object> nodeToColor;
private static final Object Visited = new Object();
private static final Object Black = new Object();
private final LinkedList<Object> finishingOrder;
private List<List> componentList = new ArrayList<List>();
private final HashMap<Object, List<Object>> nodeToComponent = new HashMap<Object, List<Object>>();
MutableDirectedGraph sccGraph = new HashMutableDirectedGraph();
private final int[] indexStack;
private final Object[] nodeStack;
private int last;
/**
* @param g
* a graph for which we want to compute the strongly connected components.
* @see DirectedGraph
*/
public StronglyConnectedComponents(DirectedGraph g) {
nodeToColor = new HashMap<Object, Object>((3 * g.size()) / 2, 0.7f);
indexStack = new int[g.size()];
nodeStack = new Object[g.size()];
finishingOrder = new LinkedList<Object>();
// Visit each node
{
Iterator nodeIt = g.iterator();
while (nodeIt.hasNext()) {
Object s = nodeIt.next();
if (nodeToColor.get(s) == null) {
visitNode(g, s);
}
}
}
// Re-color all nodes white
nodeToColor = new HashMap<Object, Object>((3 * g.size()), 0.7f);
// Visit each node via transpose edges
{
Iterator<Object> revNodeIt = finishingOrder.iterator();
while (revNodeIt.hasNext()) {
Object s = revNodeIt.next();
if (nodeToColor.get(s) == null) {
List<Object> currentComponent = null;
currentComponent = new StationaryArrayList();
nodeToComponent.put(s, currentComponent);
sccGraph.addNode(currentComponent);
componentList.add(currentComponent);
visitRevNode(g, s, currentComponent);
}
}
}
componentList = Collections.unmodifiableList(componentList);
if (Options.v().verbose()) {
logger.debug("Done computing scc components");
logger.debug("number of nodes in underlying graph: " + g.size());
logger.debug("number of components: " + sccGraph.size());
}
}
private void visitNode(DirectedGraph graph, Object startNode) {<FILL_FUNCTION_BODY>}
private void visitRevNode(DirectedGraph graph, Object startNode, List<Object> currentComponent) {
last = 0;
nodeToColor.put(startNode, Visited);
nodeStack[last] = startNode;
indexStack[last++] = -1;
while (last > 0) {
int toVisitIndex = ++indexStack[last - 1];
Object toVisitNode = nodeStack[last - 1];
if (toVisitIndex >= graph.getPredsOf(toVisitNode).size()) {
// No more nodes. Add toVisitNode to current component.
currentComponent.add(toVisitNode);
nodeToComponent.put(toVisitNode, currentComponent);
nodeToColor.put(toVisitNode, Black);
// Pop this node off
last--;
} else {
Object childNode = graph.getPredsOf(toVisitNode).get(toVisitIndex);
// Visit this child next if not already visited (or on stack)
if (nodeToColor.get(childNode) == null) {
nodeToColor.put(childNode, Visited);
nodeStack[last] = childNode;
indexStack[last++] = -1;
}
else if (nodeToColor.get(childNode) == Black) {
/* we may be visiting a node in another component. if so, add edge to sccGraph. */
if (nodeToComponent.get(childNode) != currentComponent) {
sccGraph.addEdge(nodeToComponent.get(childNode), currentComponent);
}
}
}
}
}
/**
* Checks if 2 nodes are in the same strongly-connnected component.
*
* @param a
* some graph node.
* @param b
* some graph node
* @return true if both nodes are in the same strongly-connnected component. false otherwise.
*/
public boolean equivalent(Object a, Object b) {
return nodeToComponent.get(a) == nodeToComponent.get(b);
}
/**
* @return a list of the strongly-connnected components that make up the computed strongly-connnect component graph.
*/
public List<List> getComponents() {
return componentList;
}
/**
* @param a
* a node of the original graph.
* @return the strongly-connnected component node to which the parameter node belongs.
*/
public List getComponentOf(Object a) {
return nodeToComponent.get(a);
}
/**
* @return the computed strongly-connnected component graph.
* @see DirectedGraph
*/
public DirectedGraph getSuperGraph() {
/* we should make this unmodifiable at some point. */
return sccGraph;
}
}
|
last = 0;
nodeToColor.put(startNode, Visited);
nodeStack[last] = startNode;
indexStack[last++] = -1;
while (last > 0) {
int toVisitIndex = ++indexStack[last - 1];
Object toVisitNode = nodeStack[last - 1];
if (toVisitIndex >= graph.getSuccsOf(toVisitNode).size()) {
// Visit this node now that we ran out of children
finishingOrder.addFirst(toVisitNode);
// Pop this node off
last--;
} else {
Object childNode = graph.getSuccsOf(toVisitNode).get(toVisitIndex);
// Visit this child next if not already visited (or on stack)
if (nodeToColor.get(childNode) == null) {
nodeToColor.put(childNode, Visited);
nodeStack[last] = childNode;
indexStack[last++] = -1;
}
}
}
| 1,386
| 260
| 1,646
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/interaction/FlowInfo.java
|
FlowInfo
|
toString
|
class FlowInfo<I, U> {
private I info;
private U unit;
private boolean before;
public FlowInfo(I info, U unit, boolean b) {
info(info);
unit(unit);
setBefore(b);
}
public U unit() {
return unit;
}
public void unit(U u) {
unit = u;
}
public I info() {
return info;
}
public void info(I i) {
info = i;
}
public boolean isBefore() {
return before;
}
public void setBefore(boolean b) {
before = b;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuffer sb = new StringBuffer();
sb.append("unit: " + unit);
sb.append(" info: " + info);
sb.append(" before: " + before);
return sb.toString();
| 201
| 56
| 257
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/interaction/InteractionHandler.java
|
InteractionHandler
|
handleCfgEvent
|
class InteractionHandler {
private static final Logger logger = LoggerFactory.getLogger(InteractionHandler.class);
public InteractionHandler(Singletons.Global g) {
}
public static InteractionHandler v() {
return G.v().soot_toolkits_graph_interaction_InteractionHandler();
}
private ArrayList<Object> stopUnitList;
public ArrayList<Object> getStopUnitList() {
return stopUnitList;
}
public void addToStopUnitList(Object elem) {
if (stopUnitList == null) {
stopUnitList = new ArrayList<Object>();
}
stopUnitList.add(elem);
}
public void removeFromStopUnitList(Object elem) {
if (stopUnitList.contains(elem)) {
stopUnitList.remove(elem);
}
}
public void handleNewAnalysis(Transform t, Body b) {
// here save current phase name and only send if actual data flow analysis exists
if (PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions(t.getPhaseName()), "enabled")) {
String name = t.getPhaseName() + " for method: " + b.getMethod().getName();
currentPhaseName(name);
currentPhaseEnabled(true);
doneCurrent(false);
} else {
currentPhaseEnabled(false);
setInteractThisAnalysis(false);
}
}
public void handleCfgEvent(DirectedGraph<?> g) {<FILL_FUNCTION_BODY>}
public void handleStopAtNodeEvent(Object u) {
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.STOP_AT_NODE, u));
}
}
public void handleBeforeAnalysisEvent(Object beforeFlow) {
if (isInteractThisAnalysis()) {
if (autoCon()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO_AUTO, beforeFlow));
} else {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO, beforeFlow));
}
}
}
public void handleAfterAnalysisEvent(Object afterFlow) {
if (isInteractThisAnalysis()) {
if (autoCon()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO_AUTO, afterFlow));
} else {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO, afterFlow));
}
}
}
public void handleTransformDone(Transform t, Body b) {
doneCurrent(true);
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.DONE, null));
}
}
public void handleCallGraphStart(Object info, CallGraphGrapher grapher) {
setGrapher(grapher);
doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_START, info));
if (!isCgReset()) {
handleCallGraphNextMethod();
} else {
setCgReset(false);
handleReset();
}
}
public void handleCallGraphNextMethod() {
if (!cgDone()) {
getGrapher().setNextMethod(getNextMethod());
getGrapher().handleNextMethod();
}
}
private boolean cgReset = false;
public void setCgReset(boolean v) {
cgReset = v;
}
public boolean isCgReset() {
return cgReset;
}
public void handleReset() {
if (!cgDone()) {
getGrapher().reset();
}
}
public void handleCallGraphPart(Object info) {
doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_PART, info));
if (!isCgReset()) {
handleCallGraphNextMethod();
} else {
setCgReset(false);
handleReset();
}
}
private CallGraphGrapher grapher;
private void setGrapher(CallGraphGrapher g) {
grapher = g;
}
private CallGraphGrapher getGrapher() {
return grapher;
}
private SootMethod nextMethod;
public void setNextMethod(SootMethod m) {
nextMethod = m;
}
private SootMethod getNextMethod() {
return nextMethod;
}
private synchronized void doInteraction(InteractionEvent event) {
getInteractionListener().setEvent(event);
getInteractionListener().handleEvent();
}
public synchronized void waitForContinue() {
try {
this.wait();
} catch (InterruptedException e) {
logger.debug("" + e.getMessage());
}
}
private boolean interactThisAnalysis;
public void setInteractThisAnalysis(boolean b) {
interactThisAnalysis = b;
}
public boolean isInteractThisAnalysis() {
return interactThisAnalysis;
}
private boolean interactionCon;
public synchronized void setInteractionCon() {
this.notify();
}
public boolean isInteractionCon() {
return interactionCon;
}
private IInteractionListener interactionListener;
public void setInteractionListener(IInteractionListener listener) {
interactionListener = listener;
}
public IInteractionListener getInteractionListener() {
return interactionListener;
}
private String currentPhaseName;
public void currentPhaseName(String name) {
currentPhaseName = name;
}
public String currentPhaseName() {
return currentPhaseName;
}
private boolean currentPhaseEnabled;
public void currentPhaseEnabled(boolean b) {
currentPhaseEnabled = b;
}
public boolean currentPhaseEnabled() {
return currentPhaseEnabled;
}
private boolean cgDone = false;
public void cgDone(boolean b) {
cgDone = b;
}
public boolean cgDone() {
return cgDone;
}
private boolean doneCurrent;
public void doneCurrent(boolean b) {
doneCurrent = b;
}
public boolean doneCurrent() {
return doneCurrent;
}
private boolean autoCon;
public void autoCon(boolean b) {
autoCon = b;
}
public boolean autoCon() {
return autoCon;
}
public void stopInteraction(boolean b) {
Options.v().set_interactive_mode(false);
}
}
|
if (currentPhaseEnabled()) {
logger.debug("Analyzing: " + currentPhaseName());
doInteraction(new InteractionEvent(IInteractionConstants.NEW_ANALYSIS, currentPhaseName()));
}
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_CFG, g));
}
| 1,759
| 97
| 1,856
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/graph/pdg/Region.java
|
Region
|
toString
|
class Region implements IRegion {
private SootClass m_class = null;
private SootMethod m_method = null;
private List<Block> m_blocks = null;
private List<Unit> m_units = null;
private int m_id = -1;
private UnitGraph m_unitGraph = null;
// The following are needed to create a tree of regions based on the containment (dependency)
// relation between regions.
private IRegion m_parent = null;
private List<IRegion> m_children = new ArrayList<IRegion>();
public Region(int id, SootMethod m, SootClass c, UnitGraph ug) {
this(id, new ArrayList<Block>(), m, c, ug);
}
public Region(int id, List<Block> blocks, SootMethod m, SootClass c, UnitGraph ug) {
this.m_blocks = blocks;
this.m_id = id;
this.m_method = m;
this.m_class = c;
this.m_unitGraph = ug;
this.m_units = null;
}
@SuppressWarnings("unchecked")
public Object clone() {
Region r = new Region(this.m_id, this.m_method, this.m_class, this.m_unitGraph);
r.m_blocks = (List<Block>) ((ArrayList<Block>) this.m_blocks).clone();
return r;
}
public SootMethod getSootMethod() {
return this.m_method;
}
public SootClass getSootClass() {
return this.m_class;
}
public List<Block> getBlocks() {
return this.m_blocks;
}
public UnitGraph getUnitGraph() {
return this.m_unitGraph;
}
public List<Unit> getUnits() {
if (this.m_units == null) {
this.m_units = new LinkedList<Unit>();
for (Iterator<Block> itr = this.m_blocks.iterator(); itr.hasNext();) {
Block b = itr.next();
for (Iterator<Unit> itr1 = b.iterator(); itr1.hasNext();) {
Unit u = itr1.next();
((LinkedList<Unit>) this.m_units).addLast(u);
}
}
}
return this.m_units;
}
public List<Unit> getUnits(Unit from, Unit to) {
return m_units.subList(m_units.indexOf(from), m_units.indexOf(to));
}
public Unit getLast() {
if (this.m_units != null) {
if (this.m_units.size() > 0) {
return ((LinkedList<Unit>) this.m_units).getLast();
}
}
return null;
}
public Unit getFirst() {
if (this.m_units != null) {
if (this.m_units.size() > 0) {
return ((LinkedList<Unit>) this.m_units).getFirst();
}
}
return null;
}
public void add(Block b) {
// Add to the front
this.m_blocks.add(0, b);
}
public void add2Back(Block b) {
// Add to the last
this.m_blocks.add(this.m_blocks.size(), b);
}
public void remove(Block b) {
this.m_blocks.remove(b);
// make the units be recalculated.
this.m_units = null;
}
public int getID() {
return this.m_id;
}
public boolean occursBefore(Unit u1, Unit u2) {
int i = this.m_units.lastIndexOf(u1);
int j = this.m_units.lastIndexOf(u2);
if (i == -1 || j == -1) {
throw new RuntimeException("These units don't exist in the region!");
}
return i < j;
}
public void setParent(IRegion pr) {
this.m_parent = pr;
}
public IRegion getParent() {
return this.m_parent;
}
public void addChildRegion(IRegion chr) {
if (!this.m_children.contains(chr)) {
this.m_children.add(chr);
}
}
public List<IRegion> getChildRegions() {
return this.m_children;
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String str = new String();
str += "Begin-----------Region: " + this.m_id + "-------------\n";
List<Unit> regionUnits = this.getUnits();
for (Iterator<Unit> itr = regionUnits.iterator(); itr.hasNext();) {
Unit u = itr.next();
str += u + "\n";
}
str += "End Region " + this.m_id + " -----------------------------\n";
return str;
| 1,251
| 128
| 1,379
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/AbstractBoundedFlowSet.java
|
AbstractBoundedFlowSet
|
complement
|
class AbstractBoundedFlowSet<T> extends AbstractFlowSet<T> implements BoundedFlowSet<T> {
@Override
public void complement() {
complement(this);
}
@Override
public void complement(FlowSet<T> dest) {<FILL_FUNCTION_BODY>}
@Override
public FlowSet<T> topSet() {
BoundedFlowSet<T> tmp = (BoundedFlowSet<T>) emptySet();
tmp.complement();
return tmp;
}
}
|
if (this == dest) {
complement();
} else {
BoundedFlowSet<T> tmp = (BoundedFlowSet<T>) topSet();
tmp.difference(this, dest);
}
| 135
| 58
| 193
|
<methods>public non-sealed void <init>() ,public abstract void add(T) ,public void add(T, FlowSet<T>) ,public void clear() ,public abstract AbstractFlowSet<T> clone() ,public abstract boolean contains(T) ,public void copy(FlowSet<T>) ,public void difference(FlowSet<T>) ,public void difference(FlowSet<T>, FlowSet<T>) ,public FlowSet<T> emptySet() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public void intersection(FlowSet<T>) ,public void intersection(FlowSet<T>, FlowSet<T>) ,public abstract boolean isEmpty() ,public boolean isSubSet(FlowSet<T>) ,public abstract Iterator<T> iterator() ,public abstract void remove(T) ,public void remove(T, FlowSet<T>) ,public abstract int size() ,public abstract List<T> toList() ,public java.lang.String toString() ,public void union(FlowSet<T>) ,public void union(FlowSet<T>, FlowSet<T>) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/AbstractFlowAnalysis.java
|
AbstractFlowAnalysis
|
mergeInto
|
class AbstractFlowAnalysis<N, A> {
/** The graph being analysed. */
protected final DirectedGraph<N> graph;
/** Maps graph nodes to IN sets. */
protected final Map<N, A> unitToBeforeFlow;
/** Filtered: Maps graph nodes to IN sets. */
protected Map<N, A> filterUnitToBeforeFlow;
/** Constructs a flow analysis on the given <code>DirectedGraph</code>. */
public AbstractFlowAnalysis(DirectedGraph<N> graph) {
this.graph = graph;
this.unitToBeforeFlow = new IdentityHashMap<N, A>(graph.size() * 2 + 1);
this.filterUnitToBeforeFlow = Collections.emptyMap();
if (Options.v().interactive_mode()) {
InteractionHandler.v().handleCfgEvent(graph);
}
}
/**
* Returns the flow object corresponding to the initial values for each graph node.
*/
protected abstract A newInitialFlow();
/**
* Returns the initial flow value for entry/exit graph nodes.
*
* This is equal to {@link #newInitialFlow()}
*/
protected A entryInitialFlow() {
return newInitialFlow();
}
/**
* Determines whether <code>entryInitialFlow()</code> is applied to trap handlers.
*/
protected boolean treatTrapHandlersAsEntries() {
return false;
}
/** Returns true if this analysis is forwards. */
protected abstract boolean isForward();
/**
* Compute the merge of the <code>in1</code> and <code>in2</code> sets, putting the result into <code>out</code>. The
* behavior of this function depends on the implementation ( it may be necessary to check whether <code>in1</code> and
* <code>in2</code> are equal or aliased ). Used by the doAnalysis method.
*/
protected abstract void merge(A in1, A in2, A out);
/**
* Merges in1 and in2 into out, just before node succNode. By default, this method just calls merge(A,A,A), ignoring the
* node.
*/
protected void merge(N succNode, A in1, A in2, A out) {
merge(in1, in2, out);
}
/** Creates a copy of the <code>source</code> flow object in <code>dest</code>. */
protected abstract void copy(A source, A dest);
/**
* Carries out the actual flow analysis. Typically called from a concrete FlowAnalysis's constructor.
*/
protected abstract void doAnalysis();
/** Accessor function returning value of IN set for s. */
public A getFlowBefore(N s) {
return unitToBeforeFlow.get(s);
}
/**
* Merges in into inout, just before node succNode.
*/
protected void mergeInto(N succNode, A inout, A in) {<FILL_FUNCTION_BODY>}
}
|
A tmp = newInitialFlow();
merge(succNode, inout, in, tmp);
copy(tmp, inout);
| 783
| 36
| 819
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/AbstractFlowSet.java
|
AbstractFlowSet
|
difference
|
class AbstractFlowSet<T> implements FlowSet<T> {
@Override
public abstract AbstractFlowSet<T> clone();
/**
* implemented, but inefficient.
*/
@Override
public FlowSet<T> emptySet() {
FlowSet<T> t = clone();
t.clear();
return t;
}
@Override
public void copy(FlowSet<T> dest) {
if (this == dest) {
return;
}
dest.clear();
for (T t : this) {
dest.add(t);
}
}
/**
* implemented, but *very* inefficient.
*/
@Override
public void clear() {
for (T t : this) {
remove(t);
}
}
@Override
public void union(FlowSet<T> other) {
if (this == other) {
return;
}
union(other, this);
}
@Override
public void union(FlowSet<T> other, FlowSet<T> dest) {
if (dest != this && dest != other) {
dest.clear();
}
if (dest != null && dest != this) {
for (T t : this) {
dest.add(t);
}
}
if (other != null && dest != other) {
for (T t : other) {
dest.add(t);
}
}
}
@Override
public void intersection(FlowSet<T> other) {
if (this == other) {
return;
}
intersection(other, this);
}
@Override
public void intersection(FlowSet<T> other, FlowSet<T> dest) {
if (dest == this && dest == other) {
return;
}
FlowSet<T> elements = null;
FlowSet<T> flowSet = null;
if (dest == this) {
/*
* makes automaticly a copy of <code>this</code>, as it will be cleared
*/
elements = this;
flowSet = other;
} else {
/* makes a copy o <code>other</code>, as it might be cleared */
elements = other;
flowSet = this;
}
dest.clear();
for (T t : elements) {
if (flowSet.contains(t)) {
dest.add(t);
}
}
}
@Override
public void difference(FlowSet<T> other) {
difference(other, this);
}
@Override
public void difference(FlowSet<T> other, FlowSet<T> dest) {<FILL_FUNCTION_BODY>}
@Override
public abstract boolean isEmpty();
@Override
public abstract int size();
@Override
public abstract void add(T obj);
@Override
public void add(T obj, FlowSet<T> dest) {
if (dest != this) {
copy(dest);
}
dest.add(obj);
}
@Override
public abstract void remove(T obj);
@Override
public void remove(T obj, FlowSet<T> dest) {
if (dest != this) {
copy(dest);
}
dest.remove(obj);
}
@Override
public boolean isSubSet(FlowSet<T> other) {
if (other == this) {
return true;
}
for (T t : other) {
if (!contains(t)) {
return false;
}
}
return true;
}
@Override
public abstract boolean contains(T obj);
@Override
public abstract Iterator<T> iterator();
@Override
public abstract List<T> toList();
@Override
public boolean equals(Object o) {
if (!(o instanceof FlowSet)) {
return false;
}
FlowSet<T> other = (FlowSet<T>) o;
if (size() != other.size()) {
return false;
}
for (T t : this) {
if (!other.contains(t)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int result = 1;
for (T t : this) {
result += t.hashCode();
}
return result;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer("{");
boolean isFirst = true;
for (T t : this) {
if (!isFirst) {
buffer.append(", ");
}
isFirst = false;
buffer.append(t);
}
buffer.append("}");
return buffer.toString();
}
}
|
if (dest == this && dest == other) {
dest.clear();
return;
}
FlowSet<T> flowSet = (other == dest) ? other.clone() : other;
dest.clear(); // now safe, since we have copies of this & other
for (T t : this) {
if (!flowSet.contains(t)) {
dest.add(t);
}
}
| 1,256
| 108
| 1,364
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/ArrayPackedSet.java
|
ArrayPackedSet
|
iterator
|
class ArrayPackedSet<T> extends AbstractBoundedFlowSet<T> {
protected final ObjectIntMapper<T> map;
protected final BitSet bits;
public ArrayPackedSet(FlowUniverse<T> universe) {
this(new ObjectIntMapper<T>(universe));
}
ArrayPackedSet(ObjectIntMapper<T> map) {
this(map, new BitSet());
}
ArrayPackedSet(ObjectIntMapper<T> map, BitSet bits) {
this.map = map;
this.bits = bits;
}
@Override
public ArrayPackedSet<T> clone() {
return new ArrayPackedSet<T>(map, (BitSet) bits.clone());
}
@Override
public FlowSet<T> emptySet() {
return new ArrayPackedSet<T>(map);
}
@Override
public int size() {
return bits.cardinality();
}
@Override
public boolean isEmpty() {
return bits.isEmpty();
}
@Override
public void clear() {
bits.clear();
}
private BitSet copyBitSet(ArrayPackedSet<?> dest) {
assert (dest.map == this.map);
if (this != dest) {
dest.bits.clear();
dest.bits.or(bits);
}
return dest.bits;
}
/** Returns true if flowSet is the same type of flow set as this. */
private boolean sameType(Object flowSet) {
return (flowSet instanceof ArrayPackedSet) && (((ArrayPackedSet<?>) flowSet).map == this.map);
}
private List<T> toList(BitSet bits, int base) {
final int len = bits.cardinality();
switch (len) {
case 0:
return emptyList();
case 1:
return singletonList(map.getObject((base - 1) + bits.length()));
default:
List<T> elements = new ArrayList<T>(len);
int i = bits.nextSetBit(0);
do {
int endOfRun = bits.nextClearBit(i + 1);
do {
elements.add(map.getObject(base + i++));
} while (i < endOfRun);
i = bits.nextSetBit(i + 1);
} while (i >= 0);
return elements;
}
}
public List<T> toList(int lowInclusive, int highInclusive) {
if (lowInclusive > highInclusive) {
return emptyList();
}
if (lowInclusive < 0) {
throw new IllegalArgumentException();
}
int highExclusive = highInclusive + 1;
return toList(bits.get(lowInclusive, highExclusive), lowInclusive);
}
@Override
public List<T> toList() {
return toList(bits, 0);
}
@Override
public void add(T obj) {
bits.set(map.getInt(obj));
}
@Override
public void complement(FlowSet<T> destFlow) {
if (sameType(destFlow)) {
ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow;
copyBitSet(dest).flip(0, dest.map.size());
} else {
super.complement(destFlow);
}
}
@Override
public void remove(T obj) {
bits.clear(map.getInt(obj));
}
@Override
public boolean isSubSet(FlowSet<T> other) {
if (other == this) {
return true;
}
if (sameType(other)) {
ArrayPackedSet<T> o = (ArrayPackedSet<T>) other;
BitSet tmp = (BitSet) o.bits.clone();
tmp.andNot(bits);
return tmp.isEmpty();
}
return super.isSubSet(other);
}
@Override
public void union(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow;
ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow;
copyBitSet(dest).or(other.bits);
} else {
super.union(otherFlow, destFlow);
}
}
@Override
public void difference(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow;
ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow;
copyBitSet(dest).andNot(other.bits);
} else {
super.difference(otherFlow, destFlow);
}
}
@Override
public void intersection(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
ArrayPackedSet<T> other = (ArrayPackedSet<T>) otherFlow;
ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow;
copyBitSet(dest).and(other.bits);
} else {
super.intersection(otherFlow, destFlow);
}
}
/**
* Returns true, if the object is in the set.
*/
@Override
public boolean contains(T obj) {
/*
* check if the object is in the map, direct call of map.getInt will add the object into the map.
*/
return map.contains(obj) && bits.get(map.getInt(obj));
}
@Override
public boolean equals(Object otherFlow) {
if (sameType(otherFlow)) {
return bits.equals(((ArrayPackedSet<?>) otherFlow).bits);
} else {
return super.equals(otherFlow);
}
}
@Override
public void copy(FlowSet<T> destFlow) {
if (this == destFlow) {
return;
}
if (sameType(destFlow)) {
ArrayPackedSet<T> dest = (ArrayPackedSet<T>) destFlow;
copyBitSet(dest);
} else {
super.copy(destFlow);
}
}
@Override
public Iterator<T> iterator() {<FILL_FUNCTION_BODY>}
}
|
return new Iterator<T>() {
int curr = -1;
int next = bits.nextSetBit(0);
@Override
public boolean hasNext() {
return (next >= 0);
}
@Override
public T next() {
if (next < 0) {
throw new NoSuchElementException();
}
curr = next;
next = bits.nextSetBit(curr + 1);
return map.getObject(curr);
}
@Override
public void remove() {
if (curr < 0) {
throw new IllegalStateException();
}
bits.clear(curr);
curr = -1;
}
};
| 1,726
| 185
| 1,911
|
<methods>public non-sealed void <init>() ,public void complement() ,public void complement(FlowSet<T>) ,public FlowSet<T> topSet() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/BackwardFlowAnalysis.java
|
BackwardFlowAnalysis
|
doAnalysis
|
class BackwardFlowAnalysis<N, A> extends FlowAnalysis<N, A> {
/**
* Construct the analysis from a DirectedGraph representation of a Body.
*/
public BackwardFlowAnalysis(DirectedGraph<N> graph) {
super(graph);
}
/**
* Returns <code>false</code>
*
* @return false
**/
@Override
protected boolean isForward() {
return false;
}
@Override
protected void doAnalysis() {<FILL_FUNCTION_BODY>}
}
|
doAnalysis(GraphView.BACKWARD, InteractionFlowHandler.BACKWARD, unitToAfterFlow, unitToBeforeFlow);
// soot.Timers.v().totalFlowNodes += graph.size();
// soot.Timers.v().totalFlowComputations += numComputations;
| 146
| 74
| 220
|
<methods>public void <init>(DirectedGraph<N>) ,public A getFlowAfter(N) ,public A getFlowBefore(N) <variables>protected Map<N,A> filterUnitToAfterFlow,protected final non-sealed Map<N,A> unitToAfterFlow
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/BinaryIdentitySet.java
|
BinaryIdentitySet
|
equals
|
class BinaryIdentitySet<T> {
protected final T o1;
protected final T o2;
protected final int hashCode;
public BinaryIdentitySet(T o1, T o2) {
this.o1 = o1;
this.o2 = o2;
this.hashCode = computeHashCode();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return hashCode;
}
private int computeHashCode() {
int result = 1;
// must be commutative
result += System.identityHashCode(o1);
result += System.identityHashCode(o2);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
public T getO1() {
return o1;
}
public T getO2() {
return o2;
}
@Override
public String toString() {
return "IdentityPair " + o1 + "," + o2;
}
}
|
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
final BinaryIdentitySet<?> other = (BinaryIdentitySet<?>) obj;
// must be commutative
return (this.o1 == other.o1 || this.o1 == other.o2) && (this.o2 == other.o2 || this.o2 == other.o1);
| 293
| 124
| 417
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/ConstantValueToInitializerTransformer.java
|
ConstantValueToInitializerTransformer
|
getOrCreateInitializer
|
class ConstantValueToInitializerTransformer extends SceneTransformer {
public static ConstantValueToInitializerTransformer v() {
return new ConstantValueToInitializerTransformer();
}
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
for (SootClass sc : Scene.v().getClasses()) {
transformClass(sc);
}
}
public void transformClass(SootClass sc) {
final Jimple jimp = Jimple.v();
SootMethod smInit = null;
Set<SootField> alreadyInitialized = new HashSet<SootField>();
for (SootField sf : sc.getFields()) {
// We can only create an initializer for all fields that have the
// constant value tag. In case of non-static fields, this provides
// a default value
// If there is already an initializer for this field, we do not
// generate a second one (this does not concern overwriting in
// user code)
if (alreadyInitialized.contains(sf)) {
continue;
}
// Look for constant values
for (Tag t : sf.getTags()) {
Constant constant = null;
if (t instanceof DoubleConstantValueTag) {
double value = ((DoubleConstantValueTag) t).getDoubleValue();
constant = DoubleConstant.v(value);
} else if (t instanceof FloatConstantValueTag) {
float value = ((FloatConstantValueTag) t).getFloatValue();
constant = FloatConstant.v(value);
} else if (t instanceof IntegerConstantValueTag) {
int value = ((IntegerConstantValueTag) t).getIntValue();
constant = IntConstant.v(value);
} else if (t instanceof LongConstantValueTag) {
long value = ((LongConstantValueTag) t).getLongValue();
constant = LongConstant.v(value);
} else if (t instanceof StringConstantValueTag) {
String value = ((StringConstantValueTag) t).getStringValue();
constant = StringConstant.v(value);
}
if (constant != null) {
if (sf.isStatic()) {
Stmt initStmt = jimp.newAssignStmt(jimp.newStaticFieldRef(sf.makeRef()), constant);
if (smInit == null) {
smInit = getOrCreateInitializer(sc, alreadyInitialized);
}
if (smInit != null) {
smInit.getActiveBody().getUnits().addFirst(initStmt);
}
} else {
// We have a default value for a non-static field
// So we have to get it into all <init>s, which
// do not call other constructors of the same class.
// It has to be after the constructor call to the super class
// so that it can be potentially overwritten within the method,
// without the default value taking precedence.
// If the constructor body already has the constant assignment,
// e.g. for final instance fields, we do not add another assignment.
for (SootMethod m : sc.getMethods()) {
if (m.isConstructor()) {
final Body body = m.retrieveActiveBody();
final UnitPatchingChain units = body.getUnits();
Local thisLocal = null;
if (isInstanceFieldAssignedConstantInBody(sf, constant, body)) {
continue;
}
for (Unit u : units) {
if (u instanceof Stmt) {
final Stmt s = (Stmt) u;
if (s.containsInvokeExpr()) {
final InvokeExpr expr = s.getInvokeExpr();
if (expr instanceof SpecialInvokeExpr) {
if (expr.getMethod().getDeclaringClass() == sc) {
// Calling another constructor in the same class
break;
}
if (thisLocal == null) {
thisLocal = body.getThisLocal();
}
Stmt initStmt = jimp.newAssignStmt(jimp.newInstanceFieldRef(thisLocal, sf.makeRef()), constant);
units.insertAfter(initStmt, s);
break;
}
}
}
}
}
}
}
}
}
}
if (smInit != null) {
Chain<Unit> units = smInit.getActiveBody().getUnits();
if (units.isEmpty() || !(units.getLast() instanceof ReturnVoidStmt)) {
units.add(jimp.newReturnVoidStmt());
}
}
}
private boolean isInstanceFieldAssignedConstantInBody(SootField sf, Constant constant, Body body) {
for (Unit u : body.getUnits()) {
if (u instanceof AssignStmt) {
final AssignStmt as = ((AssignStmt) u);
if (as.containsFieldRef() && as.getFieldRef() instanceof InstanceFieldRef
&& as.getLeftOpBox().equals(as.getFieldRefBox()) && as.getRightOp().equivTo(constant)) {
final InstanceFieldRef ifr = ((InstanceFieldRef) as.getFieldRef());
if (ifr.getField().equals(sf) && ifr.getBase().equivTo(body.getThisLocal())) {
return true;
}
}
}
}
return false;
}
private SootMethod getOrCreateInitializer(SootClass sc, Set<SootField> alreadyInitialized) {<FILL_FUNCTION_BODY>}
}
|
// Create a static initializer if we don't already have one
SootMethod smInit = sc.getMethodByNameUnsafe(SootMethod.staticInitializerName);
if (smInit == null) {
smInit = Scene.v().makeSootMethod(SootMethod.staticInitializerName, Collections.<Type>emptyList(), VoidType.v());
smInit.setActiveBody(Jimple.v().newBody(smInit));
sc.addMethod(smInit);
smInit.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
} else if (smInit.isPhantom()) {
return null;
} else {
// We need to collect those variables that are already initialized somewhere
for (Unit u : smInit.retrieveActiveBody().getUnits()) {
Stmt s = (Stmt) u;
for (ValueBox vb : s.getDefBoxes()) {
Value value = vb.getValue();
if (value instanceof FieldRef) {
alreadyInitialized.add(((FieldRef) value).getField());
}
}
}
}
return smInit;
| 1,387
| 290
| 1,677
|
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/FastColorer.java
|
UnitInterferenceGraph
|
setInterference
|
class UnitInterferenceGraph {
// Maps a local to its interfering locals.
final Map<Local, Set<Local>> localToLocals;
final List<Local> locals;
public UnitInterferenceGraph(Body body, Map<Local, ? extends Object> localToGroup, LiveLocals liveLocals,
ExceptionalUnitGraph unitGraph) {
this.locals = new ArrayList<Local>(body.getLocals());
this.localToLocals = new HashMap<Local, Set<Local>>(body.getLocalCount() * 2 + 1, 0.7f);
// Go through code, noting interferences
for (Unit unit : body.getUnits()) {
List<ValueBox> defBoxes = unit.getDefBoxes();
// Note interferences if this stmt is a definition
if (!defBoxes.isEmpty()) {
// Only one def box is supported
if (defBoxes.size() != 1) {
throw new RuntimeException("invalid number of def boxes");
}
// Remove those locals that are only live on exceptional flows.
// If we have code like this:
// a = 42
// b = foo()
// catch -> print(a)
// we can transform it to:
// a = 42
// a = foo()
// catch -> print(a)
// If an exception is thrown, at the second assignment, the
// assignment will not actually happen and "a" will be unchanged.
// SA, 2018-02-02: The above is only correct if there is
// nothing else in the trap. Take this example:
// a = 42
// b = foo()
// throw new VeryBadException()
// catch -> print(a)
// In that case, the value of "b" **will** be changed before
// we reach the handler (assuming that foo() does not already
// throw the exception). We may want to have a more complex
// reasoning here some day, but I'll leave it as is for now.
Value defValue = defBoxes.get(0).getValue();
if (defValue instanceof Local) {
Local defLocal = (Local) defValue;
Set<Local> liveLocalsAtUnit = new HashSet<Local>();
for (Unit succ : unitGraph.getSuccsOf(unit)) {
liveLocalsAtUnit.addAll(liveLocals.getLiveLocalsBefore(succ));
}
for (Local otherLocal : liveLocalsAtUnit) {
if (localToGroup.get(otherLocal).equals(localToGroup.get(defLocal))) {
setInterference(defLocal, otherLocal);
}
}
}
}
}
}
public List<Local> getLocals() {
return locals;
}
public void setInterference(Local l1, Local l2) {<FILL_FUNCTION_BODY>}
public int getInterferenceCount(Local l) {
Set<Local> localSet = localToLocals.get(l);
return localSet == null ? 0 : localSet.size();
}
public Local[] getInterferencesOf(Local l) {
Set<Local> localSet = localToLocals.get(l);
if (localSet == null) {
return null;
} else {
return localSet.toArray(new Local[localSet.size()]);
}
}
}
|
// We need the mapping in both directions
// l1 -> l2
Set<Local> locals = localToLocals.get(l1);
if (locals == null) {
locals = new ArraySet<Local>();
localToLocals.put(l1, locals);
}
locals.add(l2);
// l2 -> l1
locals = localToLocals.get(l2);
if (locals == null) {
locals = new ArraySet<Local>();
localToLocals.put(l2, locals);
}
locals.add(l1);
| 871
| 158
| 1,029
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/FlowAnalysis.java
|
Entry
|
newUniverse
|
class Entry<D, F> implements Numberable {
final D data;
int number;
/**
* This Entry is part of a real scc.
*/
boolean isRealStronglyConnected;
Entry<D, F>[] in;
Entry<D, F>[] out;
F inFlow;
F outFlow;
@SuppressWarnings("unchecked")
Entry(D u, Entry<D, F> pred) {
in = new Entry[] { pred };
data = u;
number = Integer.MIN_VALUE;
isRealStronglyConnected = false;
}
@Override
public String toString() {
return data == null ? "" : data.toString();
}
@Override
public void setNumber(int n) {
number = n;
}
@Override
public int getNumber() {
return number;
}
}
static enum Orderer {
INSTANCE;
/**
* Creates a new {@code Entry} graph based on a {@code DirectedGraph}. This includes pseudo topological order, local
* access for predecessors and successors, a graph entry-point, a {@code Numberable} interface and a real strongly
* connected component marker.
*
* @param g
* @param gv
* @param entryFlow
* @return
*/
<D, F> List<Entry<D, F>> newUniverse(DirectedGraph<D> g, GraphView gv, F entryFlow, boolean isForward) {<FILL_FUNCTION_BODY>
|
final int n = g.size();
Deque<Entry<D, F>> s = new ArrayDeque<Entry<D, F>>(n);
List<Entry<D, F>> universe = new ArrayList<Entry<D, F>>(n);
Map<D, Entry<D, F>> visited = new HashMap<D, Entry<D, F>>(((n + 1) * 4) / 3);
// out of universe node
Entry<D, F> superEntry = new Entry<D, F>(null, null);
List<D> entries = null;
List<D> actualEntries = gv.getEntries(g);
if (!actualEntries.isEmpty()) {
// normal cases: there is at least
// one return statement for a backward analysis
// or one entry statement for a forward analysis
entries = actualEntries;
} else {
// cases without any entry statement
if (isForward) {
// case of a forward flow analysis on
// a method without any entry point
throw new RuntimeException("error: no entry point for method in forward analysis");
} else {
// case of backward analysis on
// a method which potentially has
// an infinite loop and no return statement
entries = new ArrayList<D>();
// a single head is expected
assert g.getHeads().size() == 1;
D head = g.getHeads().get(0);
// collect all 'goto' statements to catch the 'goto' from the infinite loop
Set<D> visitedNodes = new HashSet<D>();
List<D> workList = new ArrayList<D>();
workList.add(head);
for (D current; !workList.isEmpty();) {
current = workList.remove(0);
visitedNodes.add(current);
// only add 'goto' statements
if (current instanceof GotoInst || current instanceof GotoStmt) {
entries.add(current);
}
for (D next : g.getSuccsOf(current)) {
if (visitedNodes.contains(next)) {
continue;
}
workList.add(next);
}
}
//
if (entries.isEmpty()) {
throw new RuntimeException("error: backward analysis on an empty entry set.");
}
}
}
visitEntry(visited, superEntry, entries);
superEntry.inFlow = entryFlow;
superEntry.outFlow = entryFlow;
@SuppressWarnings("unchecked")
Entry<D, F>[] sv = new Entry[g.size()];
int[] si = new int[g.size()];
int index = 0;
int i = 0;
Entry<D, F> v = superEntry;
for (;;) {
if (i < v.out.length) {
Entry<D, F> w = v.out[i++];
// an unvisited child node
if (w.number == Integer.MIN_VALUE) {
w.number = s.size();
s.add(w);
visitEntry(visited, w, gv.getOut(g, w.data));
// save old
si[index] = i;
sv[index] = v;
index++;
i = 0;
v = w;
}
} else {
if (index == 0) {
assert universe.size() <= g.size();
Collections.reverse(universe);
return universe;
}
universe.add(v);
sccPop(s, v);
// restore old
index--;
v = sv[index];
i = si[index];
}
}
| 402
| 941
| 1,343
|
<methods>public void <init>(DirectedGraph<N>) ,public A getFlowBefore(N) <variables>protected Map<N,A> filterUnitToBeforeFlow,protected final non-sealed DirectedGraph<N> graph,protected final non-sealed Map<N,A> unitToBeforeFlow
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/ForwardFlowAnalysis.java
|
ForwardFlowAnalysis
|
doAnalysis
|
class ForwardFlowAnalysis<N, A> extends FlowAnalysis<N, A> {
/**
* Construct the analysis from a DirectedGraph representation of a Body.
*/
public ForwardFlowAnalysis(DirectedGraph<N> graph) {
super(graph);
}
@Override
protected boolean isForward() {
return true;
}
@Override
protected void doAnalysis() {<FILL_FUNCTION_BODY>}
}
|
int i = doAnalysis(GraphView.FORWARD, InteractionFlowHandler.FORWARD, unitToBeforeFlow, unitToAfterFlow);
soot.Timers.v().totalFlowNodes += graph.size();
soot.Timers.v().totalFlowComputations += i;
| 118
| 73
| 191
|
<methods>public void <init>(DirectedGraph<N>) ,public A getFlowAfter(N) ,public A getFlowBefore(N) <variables>protected Map<N,A> filterUnitToAfterFlow,protected final non-sealed Map<N,A> unitToAfterFlow
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/HashSparseSet.java
|
HashSparseSet
|
union
|
class HashSparseSet<T> extends AbstractFlowSet<T> {
protected LinkedHashSet<T> elements;
public HashSparseSet() {
@SuppressWarnings("unchecked")
LinkedHashSet<T> newElements = new LinkedHashSet<T>();
elements = newElements;
}
private HashSparseSet(HashSparseSet<T> other) {
elements = new LinkedHashSet<T>(other.elements);
}
/**
* Returns true if flowSet is the same type of flow set as this.
*/
private boolean sameType(Object flowSet) {
return (flowSet instanceof HashSparseSet);
}
@Override
public HashSparseSet<T> clone() {
return new HashSparseSet<T>(this);
}
@Override
public FlowSet<T> emptySet() {
return new HashSparseSet<T>();
}
@Override
public void clear() {
elements.clear();
;
}
@Override
public int size() {
return elements.size();
}
@Override
public boolean isEmpty() {
return elements.isEmpty();
}
/**
* Returns a unbacked list of elements in this set.
*/
@Override
public List<T> toList() {
return new ArrayList<T>(elements);
}
/*
* Expand array only when necessary, pointed out by Florian Loitsch March 08, 2002
*/
@Override
public void add(T e) {
elements.add(e);
}
@Override
public void remove(Object obj) {
elements.remove(obj);
}
public void remove(int idx) {
Iterator<T> itr = elements.iterator();
int currentIndex = 0;
Object elem = null;
while (itr.hasNext()) {
elem = itr.next();
if (currentIndex == idx) {
break;
}
currentIndex++;
}
if (elem != null) {
elements.remove(elem);
}
}
@Override
public void union(FlowSet<T> otherFlow, FlowSet<T> destFlow) {<FILL_FUNCTION_BODY>}
@Override
public void intersection(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
HashSparseSet<T> other = (HashSparseSet<T>) otherFlow;
HashSparseSet<T> dest = (HashSparseSet<T>) destFlow;
HashSparseSet<T> workingSet = new HashSparseSet<>(this);
workingSet.elements.retainAll(other.elements);
dest.elements = workingSet.elements;
} else {
super.intersection(otherFlow, destFlow);
}
}
@Override
public void difference(FlowSet<T> otherFlow, FlowSet<T> destFlow) {
if (sameType(otherFlow) && sameType(destFlow)) {
HashSparseSet<T> other = (HashSparseSet<T>) otherFlow;
HashSparseSet<T> dest = (HashSparseSet<T>) destFlow;
HashSparseSet<T> workingSet;
if (dest == other || dest == this) {
workingSet = new HashSparseSet<T>();
} else {
workingSet = dest;
workingSet.clear();
}
for (Object elem : this.elements) {
if (!other.elements.contains(elem)) {
workingSet.elements.add((T) elem);
}
}
if (workingSet != dest) {
workingSet.copy(dest);
}
} else {
super.difference(otherFlow, destFlow);
}
}
@Override
public boolean contains(Object obj) {
return elements.contains(obj);
}
@Override
public boolean equals(Object otherFlow) {
if (sameType(otherFlow)) {
@SuppressWarnings("unchecked")
HashSparseSet<T> other = (HashSparseSet<T>) otherFlow;
return this.elements.equals(other.elements);
} else {
return super.equals(otherFlow);
}
}
@Override
public void copy(FlowSet<T> destFlow) {
if (sameType(destFlow)) {
HashSparseSet<T> dest = (HashSparseSet<T>) destFlow;
dest.elements.clear();
dest.elements.addAll(this.elements);
} else {
super.copy(destFlow);
}
}
@Override
public Iterator<T> iterator() {
return elements.iterator();
}
}
|
if (sameType(otherFlow) && sameType(destFlow)) {
HashSparseSet<T> other = (HashSparseSet<T>) otherFlow;
HashSparseSet<T> dest = (HashSparseSet<T>) destFlow;
dest.elements.addAll(this.elements);
dest.elements.addAll(other.elements);
} else {
super.union(otherFlow, destFlow);
}
| 1,247
| 113
| 1,360
|
<methods>public non-sealed void <init>() ,public abstract void add(T) ,public void add(T, FlowSet<T>) ,public void clear() ,public abstract AbstractFlowSet<T> clone() ,public abstract boolean contains(T) ,public void copy(FlowSet<T>) ,public void difference(FlowSet<T>) ,public void difference(FlowSet<T>, FlowSet<T>) ,public FlowSet<T> emptySet() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public void intersection(FlowSet<T>) ,public void intersection(FlowSet<T>, FlowSet<T>) ,public abstract boolean isEmpty() ,public boolean isSubSet(FlowSet<T>) ,public abstract Iterator<T> iterator() ,public abstract void remove(T) ,public void remove(T, FlowSet<T>) ,public abstract int size() ,public abstract List<T> toList() ,public java.lang.String toString() ,public void union(FlowSet<T>) ,public void union(FlowSet<T>, FlowSet<T>) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/InitAnalysis.java
|
InitAnalysis
|
flowThrough
|
class InitAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Local>> {
protected final FlowSet<Local> allLocals = new ArraySparseSet<Local>();
public InitAnalysis(DirectedBodyGraph<Unit> g) {
super(g);
FlowSet<Local> allLocalsRef = this.allLocals;
for (Local loc : g.getBody().getLocals()) {
allLocalsRef.add(loc);
}
doAnalysis();
}
@Override
protected FlowSet<Local> entryInitialFlow() {
return new HashSparseSet<Local>();
}
@Override
protected FlowSet<Local> newInitialFlow() {
FlowSet<Local> ret = new HashSparseSet<Local>();
allLocals.copy(ret);
return ret;
}
@Override
protected void flowThrough(FlowSet<Local> in, Unit unit, FlowSet<Local> out) {<FILL_FUNCTION_BODY>}
@Override
protected void merge(FlowSet<Local> in1, FlowSet<Local> in2, FlowSet<Local> out) {
in1.intersection(in2, out);
}
@Override
protected void copy(FlowSet<Local> source, FlowSet<Local> dest) {
source.copy(dest);
}
}
|
in.copy(out);
for (ValueBox defBox : unit.getDefBoxes()) {
Value lhs = defBox.getValue();
if (lhs instanceof Local) {
out.add((Local) lhs);
}
}
| 342
| 67
| 409
|
<methods>public void <init>(DirectedGraph<soot.Unit>) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/LocalPacker.java
|
LocalPacker
|
internalTransform
|
class LocalPacker extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LocalPacker.class);
public LocalPacker(Singletons.Global g) {
}
public static LocalPacker v() {
return G.v().soot_toolkits_scalar_LocalPacker();
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>}
}
|
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Packing locals...");
}
final Chain<Local> bodyLocalsRef = body.getLocals();
final int origLocalCount = bodyLocalsRef.size();
if (origLocalCount < 1) {
return;
}
// A group represents a bunch of locals which may potentially interfere with each other.
// Separate groups can not possibly interfere with each other (coloring say ints and doubles).
Map<Local, Type> localToGroup = new DeterministicHashMap<Local, Type>(origLocalCount * 2 + 1, 0.7f);
Map<Type, Integer> groupToColorCount = new HashMap<Type, Integer>(origLocalCount * 2 + 1, 0.7f);
Map<Local, Integer> localToColor = new HashMap<Local, Integer>(origLocalCount * 2 + 1, 0.7f);
// Assign each local to a group, and set that group's color count to 0.
for (Local l : bodyLocalsRef) {
Type g = l.getType();
localToGroup.put(l, g);
groupToColorCount.putIfAbsent(g, 0);
}
// Assign colors to the parameter locals.
for (Unit s : body.getUnits()) {
if (s instanceof IdentityUnit) {
Value leftOp = ((IdentityUnit) s).getLeftOp();
if (leftOp instanceof Local) {
Local l = (Local) leftOp;
Type group = localToGroup.get(l);
Integer count = groupToColorCount.get(group);
localToColor.put(l, count);
groupToColorCount.put(group, count + 1);
}
}
}
// Call the graph colorer.
if (PhaseOptions.getBoolean(options, "unsplit-original-locals")) {
FastColorer.unsplitAssignColorsToLocals(body, localToGroup, localToColor, groupToColorCount);
} else {
FastColorer.assignColorsToLocals(body, localToGroup, localToColor, groupToColorCount);
}
// Map each local to a new local.
Map<Local, Local> localToNewLocal = new HashMap<Local, Local>(origLocalCount * 2 + 1, 0.7f);
{
Map<GroupIntPair, Local> groupIntToLocal = new HashMap<GroupIntPair, Local>(origLocalCount * 2 + 1, 0.7f);
List<Local> originalLocals = new ArrayList<Local>(bodyLocalsRef);
bodyLocalsRef.clear();
final Set<String> usedLocalNames = new HashSet<>();
for (Local original : originalLocals) {
Type group = localToGroup.get(original);
GroupIntPair pair = new GroupIntPair(group, localToColor.get(original));
Local newLocal = groupIntToLocal.get(pair);
if (newLocal == null) {
newLocal = (Local) original.clone();
newLocal.setType(group);
// Added 'usedLocalNames' for distinct naming.
// Icky fix. But I guess it works. -PL
// It is no substitute for really understanding the
// problem, though. I'll leave that to someone
// who really understands the local naming stuff.
// Does such a person exist?
//
// I'll just leave this comment as folklore for future
// generations. The problem with it is that you can end up
// with different locals that share the same name which can
// lead to all sorts of funny results. (SA, 2017-03-02)
//
// If we have a split local, let's find a better name for it
String name = newLocal.getName();
if (name != null) {
int signIndex = name.indexOf('#');
if (signIndex >= 0) {
String newName = name.substring(0, signIndex);
if (usedLocalNames.add(newName)) {
newLocal.setName(newName);
} else {
// just leave it alone for now
}
} else {
usedLocalNames.add(name);
}
}
groupIntToLocal.put(pair, newLocal);
bodyLocalsRef.add(newLocal);
}
localToNewLocal.put(original, newLocal);
}
}
// Go through all valueBoxes of this method and perform changes
for (Unit s : body.getUnits()) {
for (ValueBox box : s.getUseBoxes()) {
Value val = box.getValue();
if (val instanceof Local) {
box.setValue(localToNewLocal.get((Local) val));
}
}
for (ValueBox box : s.getDefBoxes()) {
Value val = box.getValue();
if (val instanceof Local) {
box.setValue(localToNewLocal.get((Local) val));
}
}
}
| 128
| 1,294
| 1,422
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/LocalSplitter.java
|
LocalSplitter
|
internalTransform
|
class LocalSplitter extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LocalSplitter.class);
protected ThrowAnalysis throwAnalysis;
protected boolean omitExceptingUnitEdges;
public LocalSplitter(Singletons.Global g) {
}
public LocalSplitter(ThrowAnalysis ta) {
this(ta, false);
}
public LocalSplitter(ThrowAnalysis ta, boolean omitExceptingUnitEdges) {
this.throwAnalysis = ta;
this.omitExceptingUnitEdges = omitExceptingUnitEdges;
}
public static LocalSplitter v() {
return G.v().soot_toolkits_scalar_LocalSplitter();
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>}
}
|
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Splitting locals...");
}
if (Options.v().time()) {
Timers.v().splitTimer.start();
Timers.v().splitPhase1Timer.start();
}
if (throwAnalysis == null) {
throwAnalysis = Scene.v().getDefaultThrowAnalysis();
}
if (!omitExceptingUnitEdges) {
omitExceptingUnitEdges = Options.v().omit_excepting_unit_edges();
}
// Pack the locals for efficiency
final LocalBitSetPacker localPacker = new LocalBitSetPacker(body);
localPacker.pack();
// Go through the definitions, building the webs
ExceptionalUnitGraph graph
= ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges);
// run in panic mode on first split (maybe change this depending on the input source)
final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph, true);
final LocalUses uses = LocalUses.Factory.newLocalUses(graph, defs);
if (Options.v().time()) {
Timers.v().splitPhase1Timer.end();
Timers.v().splitPhase2Timer.start();
}
// Collect the set of locals that we need to split
final BitSet localsToSplit;
{
int localCount = localPacker.getLocalCount();
BitSet localsVisited = new BitSet(localCount);
localsToSplit = new BitSet(localCount);
for (Unit s : body.getUnits()) {
Iterator<ValueBox> defsInUnitItr = s.getDefBoxes().iterator();
if (defsInUnitItr.hasNext()) {
Value value = defsInUnitItr.next().getValue();
if (value instanceof Local) {
// If we see a local the second time, we know that we must split it
int localNumber = ((Local) value).getNumber();
if (localsVisited.get(localNumber)) {
localsToSplit.set(localNumber);
} else {
localsVisited.set(localNumber);
}
}
}
}
}
{
int w = 0;
Set<Unit> visited = new HashSet<Unit>();
for (Unit s : body.getUnits()) {
Iterator<ValueBox> defsInUnitItr = s.getDefBoxes().iterator();
if (!defsInUnitItr.hasNext()) {
continue;
}
Value singleDef = defsInUnitItr.next().getValue();
if (defsInUnitItr.hasNext()) {
throw new RuntimeException("stmt with more than 1 defbox!");
}
// we don't want to visit a node twice
if (!(singleDef instanceof Local) || visited.remove(s)) {
continue;
}
// always reassign locals to avoid "use before definition" bugs!
// unfortunately this creates a lot of new locals, so it's important
// to remove them afterwards
Local oldLocal = (Local) singleDef;
if (!localsToSplit.get(oldLocal.getNumber())) {
continue;
}
Local newLocal = (Local) oldLocal.clone();
String name = newLocal.getName();
if (name != null) {
newLocal.setName(name + '#' + (++w)); // renaming should not be done here
}
body.getLocals().add(newLocal);
Deque<Unit> queue = new ArrayDeque<Unit>();
queue.addFirst(s);
do {
final Unit head = queue.removeFirst();
if (visited.add(head)) {
for (UnitValueBoxPair use : uses.getUsesOf(head)) {
ValueBox vb = use.valueBox;
Value v = vb.getValue();
if (v == newLocal) {
continue;
}
// should always be true - but who knows ...
if (v instanceof Local) {
queue.addAll(defs.getDefsOfAt((Local) v, use.unit));
vb.setValue(newLocal);
}
}
for (ValueBox vb : head.getDefBoxes()) {
Value v = vb.getValue();
if (v instanceof Local) {
vb.setValue(newLocal);
}
}
}
} while (!queue.isEmpty());
// keep the set small
visited.remove(s);
}
}
// Restore the original local numbering
localPacker.unpack();
if (Options.v().time()) {
Timers.v().splitPhase2Timer.end();
Timers.v().splitTimer.end();
}
| 229
| 1,261
| 1,490
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/LocalUnitPair.java
|
LocalUnitPair
|
equals
|
class LocalUnitPair {
Local local;
Unit unit;
/**
* Constructs a LocalUnitPair from a Unit object and a Local object.
*
* @param local
* some Local
* @param unit
* some Unit.
*/
public LocalUnitPair(Local local, Unit unit) {
this.local = local;
this.unit = unit;
}
/**
* Two LocalUnitPairs are equal iff they hold the same Unit objects and the same Local objects within them.
*
* @param other
* another LocalUnitPair
* @return true if other contains the same objects as this.
*/
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return local.hashCode() * 101 + unit.hashCode() + 17;
}
public Local getLocal() {
return local;
}
public Unit getUnit() {
return unit;
}
}
|
if (other instanceof LocalUnitPair) {
LocalUnitPair temp = (LocalUnitPair) other;
return temp.local == this.local && temp.unit == this.unit;
} else {
return false;
}
| 269
| 60
| 329
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/SharedInitializationLocalSplitter.java
|
Cluster
|
internalTransform
|
class Cluster {
protected final List<Unit> constantInitializers;
protected final Unit use;
public Cluster(Unit use, List<Unit> constantInitializers) {
this.use = use;
this.constantInitializers = constantInitializers;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Constant intializers:\n");
for (Unit r : constantInitializers) {
sb.append("\n - ").append(toStringUnit(r));
}
return sb.toString();
}
private String toStringUnit(Unit u) {
return u + " (" + System.identityHashCode(u) + ")";
}
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>
|
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Splitting for shared initialization of locals...");
}
if (throwAnalysis == null) {
throwAnalysis = Scene.v().getDefaultThrowAnalysis();
}
if (!omitExceptingUnitEdges) {
omitExceptingUnitEdges = Options.v().omit_excepting_unit_edges();
}
CopyPropagator.v().transform(body);
ConstantPropagatorAndFolder.v().transform(body);
DexNullThrowTransformer.v().transform(body);
DexNullArrayRefTransformer.v().transform(body);
FlowSensitiveConstantPropagator.v().transform(body);
CopyPropagator.v().transform(body);
DexNullThrowTransformer.v().transform(body);
DexNullArrayRefTransformer.v().transform(body);
DeadAssignmentEliminator.v().transform(body);
CopyPropagator.v().transform(body);
final ExceptionalUnitGraph graph
= ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body, throwAnalysis, omitExceptingUnitEdges);
final LocalDefs defs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph, true);
final MultiMap<Local, Cluster> clustersPerLocal = new HashMultiMap<Local, Cluster>();
final Chain<Unit> units = body.getUnits();
for (Unit s : units) {
for (ValueBox useBox : s.getUseBoxes()) {
Value v = useBox.getValue();
if (v instanceof Local) {
Local luse = (Local) v;
List<Unit> allAffectingDefs = defs.getDefsOfAt(luse, s);
// Make sure we are only affected by Constant definitions via AssignStmt
if (allAffectingDefs.isEmpty() || !allAffectingDefs.stream()
.allMatch(u -> (u instanceof AssignStmt) && (((AssignStmt) u).getRightOp() instanceof Constant))) {
continue;
}
clustersPerLocal.put(luse, new Cluster(s, allAffectingDefs));
}
}
}
final Chain<Local> locals = body.getLocals();
int w = 0;
for (Local lcl : clustersPerLocal.keySet()) {
Set<Cluster> clusters = clustersPerLocal.get(lcl);
if (clusters.size() <= 1) {
// Not interesting
continue;
}
for (Cluster cluster : clusters) {
// we have an overlap, we need to split.
Local newLocal = (Local) lcl.clone();
newLocal.setName(newLocal.getName() + '_' + ++w);
locals.add(newLocal);
for (Unit u : cluster.constantInitializers) {
AssignStmt assign = (AssignStmt) u;
AssignStmt newAssign = Jimple.v().newAssignStmt(newLocal, assign.getRightOp());
units.insertAfter(newAssign, assign);
CopyPropagator.copyLineTags(newAssign.getUseBoxes().get(0), assign);
}
replaceLocalsInUnitUses(cluster.use, lcl, newLocal);
}
}
| 222
| 865
| 1,087
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/SmartLocalDefsPool.java
|
SmartLocalDefsPool
|
getSmartLocalDefsFor
|
class SmartLocalDefsPool {
protected Map<Body, Pair<Long, SmartLocalDefs>> pool = Maps.newHashMap();
/**
* This method returns a fresh instance of a {@link SmartLocalDefs} analysis, based on a freshly created
* {@link ExceptionalUnitGraph} for b, with standard parameters. If the body b's modification count has not changed since
* the last time such an analysis was requested for b, then the previously created analysis is returned instead.
*
* @see Body#getModificationCount()
*/
public SmartLocalDefs getSmartLocalDefsFor(Body b) {<FILL_FUNCTION_BODY>}
public void clear() {
pool.clear();
}
public static SmartLocalDefsPool v() {
return G.v().soot_toolkits_scalar_SmartLocalDefsPool();
}
public SmartLocalDefsPool(Singletons.Global g) {
}
public void invalidate(Body b) {
pool.remove(b);
}
}
|
Pair<Long, SmartLocalDefs> modCountAndSLD = pool.get(b);
if (modCountAndSLD != null && modCountAndSLD.o1.longValue() == b.getModificationCount()) {
return modCountAndSLD.o2;
} else {
ExceptionalUnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b);
SmartLocalDefs newSLD = new SmartLocalDefs(g, new SimpleLiveLocals(g));
pool.put(b, new Pair<Long, SmartLocalDefs>(b.getModificationCount(), newSLD));
return newSLD;
}
| 270
| 167
| 437
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/UnitValueBoxPair.java
|
UnitValueBoxPair
|
equals
|
class UnitValueBoxPair {
public Unit unit;
public ValueBox valueBox;
/**
* Constructs a UnitValueBoxPair from a Unit object and a ValueBox object.
*
* @param unit
* some Unit
* @param valueBox
* some ValueBox
*/
public UnitValueBoxPair(Unit unit, ValueBox valueBox) {
this.unit = unit;
this.valueBox = valueBox;
}
/**
* Two UnitValueBoxPairs are equal iff they the Units they hold are 'equal' and the ValueBoxes they hold are 'equal'.
*
* @param other
* another UnitValueBoxPair
* @return true if equal.
*/
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return unit.hashCode() + valueBox.hashCode();
}
@Override
public String toString() {
return valueBox + " in " + unit;
}
public Unit getUnit() {
return unit;
}
public ValueBox getValueBox() {
return valueBox;
}
}
|
if (other instanceof UnitValueBoxPair) {
UnitValueBoxPair otherPair = (UnitValueBoxPair) other;
if (this.unit.equals(otherPair.unit) && this.valueBox.equals(otherPair.valueBox)) {
return true;
}
}
return false;
| 309
| 78
| 387
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/UnusedLocalEliminator.java
|
UnusedLocalEliminator
|
internalTransform
|
class UnusedLocalEliminator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(UnusedLocalEliminator.class);
public UnusedLocalEliminator(Singletons.Global g) {
}
public static UnusedLocalEliminator v() {
return G.v().soot_toolkits_scalar_UnusedLocalEliminator();
}
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>}
}
|
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Eliminating unused locals...");
}
final Chain<Local> locals = body.getLocals();
final int numLocals = locals.size();
final int[] oldNumbers = new int[numLocals];
{
int i = 0;
for (Local local : locals) {
oldNumbers[i] = local.getNumber();
local.setNumber(i);
i++;
}
}
BitSet usedLocals = new BitSet(numLocals);
// Traverse statements noting all the uses and defs
for (Unit s : body.getUnits()) {
for (ValueBox vb : s.getUseBoxes()) {
Value v = vb.getValue();
if (v instanceof Local) {
Local l = (Local) v;
// assert locals.contains(l);
usedLocals.set(l.getNumber());
}
}
for (ValueBox vb : s.getDefBoxes()) {
Value v = vb.getValue();
if (v instanceof Local) {
Local l = (Local) v;
// assert locals.contains(l);
usedLocals.set(l.getNumber());
}
}
}
// Remove all locals that are unused.
for (Iterator<Local> localIt = locals.iterator(); localIt.hasNext();) {
final Local local = localIt.next();
final int lno = local.getNumber();
if (!usedLocals.get(lno)) {
localIt.remove();
} else {
local.setNumber(oldNumbers[lno]);
}
}
| 143
| 443
| 586
|
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
|
soot-oss_soot
|
soot/src/main/java/soot/toolkits/scalar/ValueUnitPair.java
|
ValueUnitPair
|
clone
|
class ValueUnitPair extends AbstractValueBox implements UnitBox, EquivTo {
// oub was initially a private inner class. ended up being a
// *bad* *bad* idea with endless opportunity for *evil* *evil*
// pointer bugs. in the end so much code needed to be copy pasted
// that using an innerclass to reuse code from AbstractUnitBox was
// a losing proposition.
// protected UnitBox oub;
protected Unit unit;
/**
* Constructs a ValueUnitPair from a Unit object and a Value object.
*
* @param value
* some Value
* @param unit
* some Unit.
**/
public ValueUnitPair(Value value, Unit unit) {
setValue(value);
setUnit(unit);
}
@Override
public boolean canContainValue(Value value) {
return true;
}
/**
* @see soot.UnitBox#setUnit(Unit)
**/
@Override
public void setUnit(Unit unit) {
/* Code copied from AbstractUnitBox */
if (!canContainUnit(unit)) {
throw new RuntimeException("Cannot put " + unit + " in this box");
}
// Remove this from set of back pointers.
if (this.unit != null) {
this.unit.removeBoxPointingToThis(this);
}
// Perform link
this.unit = unit;
// Add this to back pointers
if (this.unit != null) {
this.unit.addBoxPointingToThis(this);
}
}
/**
* @see soot.UnitBox#getUnit()
**/
@Override
public Unit getUnit() {
return unit;
}
/**
* @see soot.UnitBox#canContainUnit(Unit)
**/
@Override
public boolean canContainUnit(Unit u) {
return true;
}
/**
* @see soot.UnitBox#isBranchTarget()
**/
@Override
public boolean isBranchTarget() {
return true;
}
@Override
public String toString() {
return "Value = " + getValue() + ", Unit = " + getUnit();
}
@Override
public void toString(UnitPrinter up) {
super.toString(up);
up.literal(isBranchTarget() ? ", " : " #");
up.startUnitBox(this);
up.unitRef(unit, isBranchTarget());
up.endUnitBox(this);
}
@Override
public int hashCode() {
// If you need to change this implementation, please change it in
// a subclass. Otherwise, Shimple is likely to break in evil ways.
return super.hashCode();
}
@Override
public boolean equals(Object other) {
// If you need to change this implementation, please change it in
// a subclass. Otherwise, Shimple is likely to break in evil ways.
return super.equals(other);
}
/**
* Two ValueUnitPairs are equivTo iff they hold the same Unit objects and equivalent Value objects within them.
*
* @param other
* another ValueUnitPair
* @return true if other contains the same objects as this.
**/
@Override
public boolean equivTo(Object other) {
return (other instanceof ValueUnitPair) && ((ValueUnitPair) other).getValue().equivTo(this.getValue())
&& ((ValueUnitPair) other).getUnit().equals(getUnit());
}
/**
* Non-deterministic hashcode consistent with equivTo() implementation.
*
* <p>
*
* <b>Note:</b> If you are concerned about non-determinism, remember that current implementations of equivHashCode() in
* other parts of Soot are non-deterministic as well (see Constant.java for example).
**/
@Override
public int equivHashCode() {
// this is not deterministic because a Unit's hash code is
// non-deterministic.
return (getUnit().hashCode() * 17) + (getValue().equivHashCode() * 101);
}
@Override
public Object clone() {<FILL_FUNCTION_BODY>}
}
|
// Note to self: Do not try to "fix" this. Yes, it should be
// a shallow copy in order to conform with the rest of Soot.
// When a body is cloned, the Values are cloned explicitly and
// replaced, and UnitBoxes are explicitly patched. See
// Body.importBodyContentsFrom for details.
Value cv = Jimple.cloneIfNecessary(getValue());
Unit cu = getUnit();
return new ValueUnitPair(cv, cu);
| 1,113
| 123
| 1,236
|
<methods>public non-sealed void <init>() ,public soot.Value getValue() ,public void setValue(soot.Value) ,public void toString(soot.UnitPrinter) ,public java.lang.String toString() <variables>protected soot.Value value
|
soot-oss_soot
|
soot/src/main/java/soot/tools/BadFields.java
|
BadFields
|
handleMethod
|
class BadFields extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(BadFields.class);
public static void main(String[] args) {
PackManager.v().getPack("cg").add(new Transform("cg.badfields", new BadFields()));
soot.Main.main(args);
}
private SootClass lastClass;
private SootClass currentClass;
protected void internalTransform(String phaseName, Map<String, String> options) {
lastClass = null;
for (Iterator<SootClass> clIt = Scene.v().getApplicationClasses().iterator(); clIt.hasNext();) {
final SootClass cl = clIt.next();
currentClass = cl;
handleClass(cl);
for (Iterator<SootMethod> it = cl.methodIterator(); it.hasNext();) {
handleMethod(it.next());
}
}
Scene.v().setCallGraph(Scene.v().internalMakeCallGraph());
}
private void handleClass(SootClass cl) {
for (Iterator<SootField> fIt = cl.getFields().iterator(); fIt.hasNext();) {
final SootField f = fIt.next();
if (!f.isStatic()) {
continue;
}
String typeName = f.getType().toString();
if (typeName.equals("java.lang.Class")) {
continue;
}
if (f.isFinal()) {
if ((f.getType() instanceof PrimType) || typeName.equals("java.io.PrintStream")
|| typeName.equals("java.lang.String") || typeName.equals(Scene.v().getObjectType().toString())) {
continue;
}
if (typeName.equals("java.lang.Integer") || typeName.equals("java.lang.Boolean")) {
continue;
}
}
warn("Bad field " + f);
}
}
private void warn(String warning) {
if (lastClass != currentClass) {
logger.debug("" + "In class " + currentClass);
}
lastClass = currentClass;
logger.debug("" + " " + warning);
}
private void handleMethod(SootMethod m) {<FILL_FUNCTION_BODY>}
private void calls(SootMethod target) {
if (target.getName().equals("<init>")) {
if (target.getDeclaringClass().getName().equals("java.io.PrintStream")
|| target.getDeclaringClass().getName().equals("java.lang.Boolean")
|| target.getDeclaringClass().getName().equals("java.lang.Integer")
|| target.getDeclaringClass().getName().equals("java.lang.String")) {
return;
}
if (target.getDeclaringClass().getName().equals(Scene.v().getObjectType().toString())) {
return;
}
}
if (target.getName().equals("getProperty")) {
if (target.getDeclaringClass().getName().equals("java.lang.System")) {
return;
}
}
if (target.getName().equals("charAt")) {
if (target.getDeclaringClass().getName().equals("java.lang.String")) {
return;
}
}
warn("<clinit> invokes " + target);
}
}
|
if (!m.isConcrete()) {
return;
}
for (Iterator<ValueBox> bIt = m.retrieveActiveBody().getUseAndDefBoxes().iterator(); bIt.hasNext();) {
final ValueBox b = bIt.next();
Value v = b.getValue();
if (!(v instanceof StaticFieldRef)) {
continue;
}
StaticFieldRef sfr = (StaticFieldRef) v;
SootField f = sfr.getField();
if (!f.getDeclaringClass().getName().equals("java.lang.System")) {
continue;
}
if (f.getName().equals("err")) {
logger.debug("" + "Use of System.err in " + m);
}
if (f.getName().equals("out")) {
logger.debug("" + "Use of System.out in " + m);
}
}
for (Iterator<Unit> sIt = m.getActiveBody().getUnits().iterator(); sIt.hasNext();) {
final Stmt s = (Stmt) sIt.next();
if (!s.containsInvokeExpr()) {
continue;
}
InvokeExpr ie = s.getInvokeExpr();
SootMethod target = ie.getMethod();
if (target.getDeclaringClass().getName().equals("java.lang.System") && target.getName().equals("exit")) {
warn("" + m + " calls System.exit");
}
}
if (m.getName().equals("<clinit>")) {
for (Iterator<Unit> sIt = m.getActiveBody().getUnits().iterator(); sIt.hasNext();) {
final Stmt s = (Stmt) sIt.next();
for (Iterator<ValueBox> bIt = s.getUseBoxes().iterator(); bIt.hasNext();) {
final ValueBox b = bIt.next();
Value v = b.getValue();
if (v instanceof FieldRef) {
warn(m.getName() + " reads field " + v);
}
}
if (!s.containsInvokeExpr()) {
continue;
}
InvokeExpr ie = s.getInvokeExpr();
SootMethod target = ie.getMethod();
calls(target);
}
}
| 854
| 578
| 1,432
|
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/util/AbstractMultiMap.java
|
EntryIterator
|
hasNext
|
class EntryIterator implements Iterator<Pair<K, V>> {
Iterator<K> keyIterator = keySet().iterator();
Iterator<V> valueIterator = null;
K currentKey = null;
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
@Override
public Pair<K, V> next() {
// Obtain the next key
if (valueIterator == null) {
currentKey = keyIterator.next();
valueIterator = get(currentKey).iterator();
}
return new Pair<K, V>(currentKey, valueIterator.next());
}
@Override
public void remove() {
if (valueIterator == null) {
// Removing an element twice or removing no valid element does not make sense
return;
}
valueIterator.remove();
if (get(currentKey).isEmpty()) {
keyIterator.remove();
valueIterator = null;
currentKey = null;
}
}
}
|
if (valueIterator != null && valueIterator.hasNext()) {
return true;
}
// Prepare for the next key
valueIterator = null;
currentKey = null;
return keyIterator.hasNext();
| 256
| 61
| 317
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/ArrayNumberer.java
|
ArrayNumberer
|
get
|
class ArrayNumberer<E extends Numberable> implements IterableNumberer<E> {
protected E[] numberToObj;
protected int lastNumber;
protected BitSet freeNumbers;
@SuppressWarnings("unchecked")
public ArrayNumberer() {
this.numberToObj = (E[]) new Numberable[1024];
this.lastNumber = 0;
}
public ArrayNumberer(E[] elements) {
this.numberToObj = elements;
this.lastNumber = elements.length;
}
private void resize(int n) {
numberToObj = Arrays.copyOf(numberToObj, n);
}
@Override
public synchronized void add(E o) {
if (o.getNumber() != 0) {
return;
}
// In case we removed entries from the numberer, we want to re-use the free space
int chosenNumber = -1;
if (freeNumbers != null) {
int ns = freeNumbers.nextSetBit(0);
if (ns != -1) {
chosenNumber = ns;
freeNumbers.clear(ns);
}
}
if (chosenNumber == -1) {
chosenNumber = ++lastNumber;
}
if (chosenNumber >= numberToObj.length) {
resize(numberToObj.length * 2);
}
numberToObj[chosenNumber] = o;
o.setNumber(chosenNumber);
}
@Override
public long get(E o) {<FILL_FUNCTION_BODY>}
@Override
public E get(long number) {
if (number == 0) {
return null;
}
E ret = numberToObj[(int) number];
if (ret == null) {
return null;
}
return ret;
}
@Override
public int size() {
return lastNumber;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int cur = 1;
@Override
public final boolean hasNext() {
return cur <= lastNumber && cur < numberToObj.length && numberToObj[cur] != null;
}
@Override
public final E next() {
if (hasNext()) {
return numberToObj[cur++];
}
throw new NoSuchElementException();
}
@Override
public final void remove() {
ArrayNumberer.this.remove(numberToObj[cur - 1]);
}
};
}
@Override
public boolean remove(E o) {
if (o == null) {
return false;
}
int num = o.getNumber();
if (num == 0) {
return false;
}
if (freeNumbers == null) {
freeNumbers = new BitSet(2 * num);
}
numberToObj[num] = null;
o.setNumber(0);
freeNumbers.set(num);
return true;
}
}
|
if (o == null) {
return 0;
}
int ret = o.getNumber();
if (ret == 0) {
throw new RuntimeException("unnumbered: " + o);
}
return ret;
| 799
| 63
| 862
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/ArraySet.java
|
ArraySet
|
addAll
|
class ArraySet<E> extends AbstractSet<E> {
private static final int DEFAULT_SIZE = 8;
private int numElements;
private int maxElements;
private E[] elements;
public ArraySet(int size) {
maxElements = size;
@SuppressWarnings("unchecked")
E[] newElements = (E[]) new Object[size];
elements = newElements;
numElements = 0;
}
public ArraySet() {
this(DEFAULT_SIZE);
}
/**
* Create a set which contains the given elements.
*/
public ArraySet(E[] elements) {
this();
for (E element : elements) {
add(element);
}
}
@Override
final public void clear() {
numElements = 0;
}
@Override
final public boolean contains(Object obj) {
for (int i = 0; i < numElements; i++) {
if (elements[i].equals(obj)) {
return true;
}
}
return false;
}
/**
* Add an element without checking whether it is already in the set. It is up to the caller to guarantee that it isn't.
*/
final public boolean addElement(E e) {
if (e == null) {
throw new RuntimeException("oops");
}
// Expand array if necessary
if (numElements == maxElements) {
doubleCapacity();
}
// Add element
elements[numElements++] = e;
return true;
}
@Override
final public boolean add(E e) {
if (e == null) {
throw new RuntimeException("oops");
}
if (contains(e)) {
return false;
} else {
// Expand array if necessary
if (numElements == maxElements) {
doubleCapacity();
}
// Add element
elements[numElements++] = e;
return true;
}
}
@Override
final public boolean addAll(Collection<? extends E> s) {<FILL_FUNCTION_BODY>}
@Override
final public int size() {
return numElements;
}
@Override
final public Iterator<E> iterator() {
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<E> {
int nextIndex;
ArrayIterator() {
nextIndex = 0;
}
@Override
final public boolean hasNext() {
return nextIndex < numElements;
}
@Override
final public E next() throws NoSuchElementException {
if (!(nextIndex < numElements)) {
throw new NoSuchElementException();
} else {
return elements[nextIndex++];
}
}
@Override
final public void remove() throws NoSuchElementException {
if (nextIndex == 0) {
throw new NoSuchElementException();
} else {
removeElementAt(nextIndex - 1);
nextIndex = nextIndex - 1;
}
}
}
private void removeElementAt(int index) {
// Handle simple case
if (index == numElements - 1) {
numElements--;
return;
}
// Else, shift over elements
System.arraycopy(elements, index + 1, elements, index, numElements - (index + 1));
numElements--;
}
private void doubleCapacity() {
// plus one to ensure that we have at least one element
int newSize = maxElements * 2 + 1;
@SuppressWarnings("unchecked")
E[] newElements = (E[]) new Object[newSize];
System.arraycopy(elements, 0, newElements, 0, numElements);
elements = newElements;
maxElements = newSize;
}
@Override
final public E[] toArray() {
@SuppressWarnings("unchecked")
E[] array = (E[]) new Object[numElements];
System.arraycopy(elements, 0, array, 0, numElements);
return array;
}
@Override
final public <T> T[] toArray(T[] array) {
if (array.length < numElements) {
@SuppressWarnings("unchecked")
T[] ret = (T[]) Arrays.copyOf(elements, numElements, array.getClass());
return ret;
} else {
System.arraycopy(elements, 0, array, 0, numElements);
if (array.length > numElements) {
array[numElements] = null;
}
return array;
}
}
final public Object[] getUnderlyingArray() {
return elements;
}
}
|
if (s instanceof ArraySet) {
boolean ret = false;
ArraySet<? extends E> as = (ArraySet<? extends E>) s;
for (E elem : as.elements) {
ret |= add(elem);
}
return ret;
} else {
return super.addAll(s);
}
| 1,223
| 88
| 1,311
|
<methods>public boolean equals(java.lang.Object) ,public int hashCode() ,public boolean removeAll(Collection<?>) <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/util/BitSetIterator.java
|
BitSetIterator
|
next
|
class BitSetIterator {
long[] bits; // Bits inherited from the underlying BitVector
int index; // The 64-bit block currently being examined
long save = 0; // A copy of the 64-bit block (for fast access)
/*
* Computes log_2(x) modulo 67. This uses the fact that 2 is a primitive root modulo 67
*/
final static int[] lookup = { -1, 0, 1, 39, 2, 15, 40, 23, 3, 12, 16, 59, 41, 19, 24, 54, 4, -1, 13, 10, 17, 62, 60, 28,
42, 30, 20, 51, 25, 44, 55, 47, 5, 32, -1, 38, 14, 22, 11, 58, 18, 53, -1, 9, 61, 27, 29, 50, 43, 46, 31, 37, 21, 57,
52, 8, 26, 49, 45, 36, 56, 7, 48, 35, 6, 34, 33 };
/** Creates a new BitSetIterator */
BitSetIterator(long[] bits) {
// this.bits = new long[bits.length];
// System.arraycopy(bits,0,this.bits,0,bits.length);
this.bits = bits;
index = 0;
/* Zip through empty blocks */
while (index < bits.length && bits[index] == 0L) {
index++;
}
if (index < bits.length) {
save = bits[index];
}
}
/** Returns true if there are more set bits in the BitVector; false otherwise. */
public boolean hasNext() {
return index < bits.length;
}
/**
* Returns the index of the next set bit. Note that the return type is int, and not Object.
*/
public int next() {<FILL_FUNCTION_BODY>}
}
|
if (index >= bits.length) {
throw new NoSuchElementException();
}
long k = (save & (save - 1)); // Clears the last non-zero bit. save is guaranteed non-zero.
long diff = save ^ k; // Finds out which bit it is. diff has exactly one bit set.
save = k;
// Computes the position of the set bit.
int result = (diff < 0) ? 64 * index + 63 : 64 * index + lookup[(int) (diff % 67)];
if (save == 0) {
index++;
while (index < bits.length && bits[index] == 0L) {
index++;
}
if (index < bits.length) {
save = bits[index];
}
}
return result;
| 594
| 212
| 806
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/ConcurrentHashMultiMap.java
|
ConcurrentHashMultiMap
|
findSet
|
class ConcurrentHashMultiMap<K, V> extends AbstractMultiMap<K, V> {
private static final long serialVersionUID = -3182515910302586044L;
private final Map<K, ConcurrentMap<V, V>> m = new ConcurrentHashMap<K, ConcurrentMap<V, V>>(0);
public ConcurrentHashMultiMap() {
}
public ConcurrentHashMultiMap(MultiMap<K, V> m) {
putAll(m);
}
@Override
public int numKeys() {
return m.size();
}
@Override
public boolean containsKey(Object key) {
return m.containsKey(key);
}
@Override
public boolean containsValue(V value) {
for (Map<V, V> s : m.values()) {
if (s.containsKey(value)) {
return true;
}
}
return false;
}
protected ConcurrentMap<V, V> newSet() {
return new ConcurrentHashMap<V, V>();
}
private ConcurrentMap<V, V> findSet(K key) {<FILL_FUNCTION_BODY>}
@Override
public boolean put(K key, V value) {
return findSet(key).put(value, value) == null;
}
public V putIfAbsent(K key, V value) {
return findSet(key).putIfAbsent(value, value);
}
@Override
public boolean putAll(K key, Collection<V> values) {
if (values == null || values.isEmpty()) {
return false;
}
ConcurrentMap<V, V> s = m.get(key);
if (s == null) {
synchronized (this) {
// We atomically create a new set, and add the data, before
// making the new set visible to the outside. Therefore,
// concurrent threads will only either see the empty set from
// before or the full set from after the add, but never anything
// in between.
s = m.get(key);
if (s == null) {
ConcurrentMap<V, V> newSet = newSet();
for (V v : values) {
newSet.put(v, v);
}
m.put(key, newSet);
return true;
}
}
}
// No "else", we can fall through if the set was created between first
// check and obtaining the lock.
boolean ok = false;
for (V v : values) {
if (s.put(v, v) == null) {
ok = true;
}
}
return ok;
}
@Override
public boolean remove(K key, V value) {
Map<V, V> s = m.get(key);
if (s == null) {
return false;
}
boolean ret = s.remove(value) != null;
if (s.isEmpty()) {
m.remove(key);
}
return ret;
}
@Override
public boolean remove(K key) {
return null != m.remove(key);
}
@Override
public boolean removeAll(K key, Collection<V> values) {
Map<V, V> s = m.get(key);
if (s == null) {
return false;
}
boolean ret = false;
for (V v : values) {
if (s.remove(v) != null) {
ret = true;
}
}
if (s.isEmpty()) {
m.remove(key);
}
return ret;
}
@Override
public Set<V> get(K o) {
Map<V, V> ret = m.get(o);
if (ret == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(ret.keySet());
}
}
@Override
public Set<K> keySet() {
return m.keySet();
}
@Override
public Set<V> values() {
Set<V> ret = new HashSet<V>(m.size());
for (Map<V, V> s : m.values()) {
ret.addAll(s.keySet());
}
return ret;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MultiMap)) {
return false;
}
@SuppressWarnings("unchecked")
MultiMap<K, V> mm = (MultiMap<K, V>) o;
if (!keySet().equals(mm.keySet())) {
return false;
}
for (Map.Entry<K, ConcurrentMap<V, V>> e : m.entrySet()) {
Map<V, V> s = e.getValue();
if (!s.equals(mm.get(e.getKey()))) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return m.hashCode();
}
@Override
public int size() {
return m.size();
}
@Override
public void clear() {
m.clear();
}
@Override
public String toString() {
return m.toString();
}
}
|
ConcurrentMap<V, V> s = m.get(key);
if (s == null) {
synchronized (this) {
// Better check twice, another thread may have created a set in
// the meantime
s = m.get(key);
if (s == null) {
s = newSet();
m.put(key, s);
}
}
}
return s;
| 1,396
| 108
| 1,504
|
<methods>public non-sealed void <init>() ,public boolean contains(K, V) ,public boolean isEmpty() ,public Iterator<Pair<K,V>> iterator() ,public boolean putAll(MultiMap<K,V>) ,public boolean putAll(Map<K,Collection<V>>) ,public boolean putMap(Map<K,V>) <variables>private static final long serialVersionUID
|
soot-oss_soot
|
soot/src/main/java/soot/util/DeterministicHashMap.java
|
ArrayIterator
|
removeElementAt
|
class ArrayIterator implements Iterator<T> {
private int nextIndex;
ArrayIterator() {
nextIndex = 0;
}
@Override
public boolean hasNext() {
return nextIndex < numElements;
}
@Override
public T next() throws NoSuchElementException {
if (!(nextIndex < numElements)) {
throw new NoSuchElementException();
}
return elements[nextIndex++];
}
@Override
public void remove() throws NoSuchElementException {
if (nextIndex == 0) {
throw new NoSuchElementException();
} else {
removeElementAt(nextIndex - 1);
nextIndex = nextIndex - 1;
}
}
}
private void removeElementAt(int index) {<FILL_FUNCTION_BODY>
|
throw new UnsupportedOperationException();
/*
* // Handle simple case if(index == numElements - 1) { numElements--; return; }
*
* // Else, shift over elements System.arraycopy(elements, index + 1, elements, index, numElements - (index + 1));
* numElements--;
*/
| 212
| 86
| 298
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends K,? extends V>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public V compute(K, BiFunction<? super K,? super V,? extends V>) ,public V computeIfAbsent(K, Function<? super K,? extends V>) ,public V computeIfPresent(K, BiFunction<? super K,? super V,? extends V>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<K,V>> entrySet() ,public void forEach(BiConsumer<? super K,? super V>) ,public V get(java.lang.Object) ,public V getOrDefault(java.lang.Object, V) ,public boolean isEmpty() ,public Set<K> keySet() ,public V merge(K, V, BiFunction<? super V,? super V,? extends V>) ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V putIfAbsent(K, V) ,public V remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public V replace(K, V) ,public boolean replace(K, V, V) ,public void replaceAll(BiFunction<? super K,? super V,? extends V>) ,public int size() ,public Collection<V> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<K,V>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<K,V>[] table,int threshold
|
soot-oss_soot
|
soot/src/main/java/soot/util/EmptyChain.java
|
EmptyChainSingleton
|
insertBefore
|
class EmptyChainSingleton {
static final EmptyChain<Object> INSTANCE = new EmptyChain<Object>();
}
public static <X> EmptyChain<X> v() {
@SuppressWarnings("unchecked")
EmptyChain<X> retVal = (EmptyChain<X>) EmptyChainSingleton.INSTANCE;
return retVal;
}
@Override
public String toString() {
return "[]";
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <X> X[] toArray(X[] a) {
@SuppressWarnings("unchecked")
X[] retVal = (X[]) new Object[0];
return retVal;
}
@Override
public boolean add(T e) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new RuntimeException("Cannot remove elements from an unmodifiable chain");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain or remove ones from such chain");
}
@Override
public void clear() {
throw new RuntimeException("Cannot remove elements from an unmodifiable chain");
}
@Override
public void insertBefore(List<T> toInsert, T point) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public void insertAfter(List<T> toInsert, T point) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public void insertAfter(T toInsert, T point) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public void insertBefore(T toInsert, T point) {
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
}
@Override
public void insertBefore(Chain<T> toInsert, T point) {<FILL_FUNCTION_BODY>
|
throw new RuntimeException("Cannot add elements to an unmodifiable chain");
| 666
| 20
| 686
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/HashChain.java
|
EmptyIteratorSingleton
|
insertBefore
|
class EmptyIteratorSingleton {
static final Iterator<Object> INSTANCE = new Iterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
return null;
}
@Override
public void remove() {
// do nothing
}
};
}
protected static <X> Iterator<X> emptyIterator() {
@SuppressWarnings("unchecked")
Iterator<X> retVal = (Iterator<X>) EmptyIteratorSingleton.INSTANCE;
return retVal;
}
/** Erases the contents of the current HashChain. */
@Override
public synchronized void clear() {
stateCount++;
firstItem = lastItem = null;
map.clear();
}
@Override
public synchronized void swapWith(E out, E in) {
insertBefore(in, out);
remove(out);
}
/** Adds the given object to this HashChain. */
@Override
public synchronized boolean add(E item) {
addLast(item);
return true;
}
/**
* Gets all elements in the chain. There is no guarantee on sorting.
*
* @return All elements in the chain in an unsorted collection
*/
@Override
public synchronized Collection<E> getElementsUnsorted() {
return map.keySet();
}
/**
* Returns an unbacked list containing the contents of the given Chain.
*
* @deprecated you can use <code>new ArrayList<E>(c)</code> instead
*/
@Deprecated
public static <E> List<E> toList(Chain<E> c) {
return new ArrayList<E>(c);
}
@Override
public synchronized boolean follows(E someObject, E someReferenceObject) {
Iterator<E> it;
try {
it = iterator(someReferenceObject);
} catch (NoSuchElementException e) {
// someReferenceObject not in chain.
return false;
}
while (it.hasNext()) {
if (it.next() == someObject) {
return true;
}
}
return false;
}
@Override
public synchronized boolean contains(Object o) {
return map.containsKey(o);
}
@Override
public synchronized boolean containsAll(Collection<?> c) {
for (Object next : c) {
if (!(map.containsKey(next))) {
return false;
}
}
return true;
}
@Override
public synchronized void insertAfter(E toInsert, E point) {
if (toInsert == null) {
throw new RuntimeException("Cannot insert a null object into a Chain!");
}
if (point == null) {
throw new RuntimeException("Insertion point cannot be null!");
}
if (map.containsKey(toInsert)) {
throw new RuntimeException("Chain already contains object.");
}
Link<E> temp = map.get(point);
if (temp == null) {
throw new RuntimeException("Insertion point not found in chain!");
}
stateCount++;
Link<E> newLink = temp.insertAfter(toInsert);
map.put(toInsert, newLink);
}
@Override
public synchronized void insertAfter(Collection<? extends E> toInsert, E point) {
if (toInsert == null) {
throw new RuntimeException("Cannot insert a null Collection into a Chain!");
}
if (point == null) {
throw new RuntimeException("Insertion point cannot be null!");
}
E previousPoint = point;
for (E o : toInsert) {
insertAfter(o, previousPoint);
previousPoint = o;
}
}
@Override
public synchronized void insertAfter(List<E> toInsert, E point) {
insertAfter((Collection<E>) toInsert, point);
}
@Override
public synchronized void insertAfter(Chain<E> toInsert, E point) {
insertAfter((Collection<E>) toInsert, point);
}
@Override
public synchronized void insertBefore(E toInsert, E point) {<FILL_FUNCTION_BODY>
|
if (toInsert == null) {
throw new RuntimeException("Cannot insert a null object into a Chain!");
}
if (point == null) {
throw new RuntimeException("Insertion point cannot be null!");
}
if (map.containsKey(toInsert)) {
throw new RuntimeException("Chain already contains object.");
}
Link<E> temp = map.get(point);
if (temp == null) {
throw new RuntimeException("Insertion point not found in chain!");
}
stateCount++;
Link<E> newLink = temp.insertBefore(toInsert);
map.put(toInsert, newLink);
| 1,114
| 169
| 1,283
|
<methods>public boolean add(E) ,public boolean addAll(Collection<? extends E>) ,public void clear() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean isEmpty() ,public abstract Iterator<E> iterator() ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean retainAll(Collection<?>) ,public abstract int size() ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>
|
soot-oss_soot
|
soot/src/main/java/soot/util/IntegerNumberer.java
|
IntegerNumberer
|
size
|
class IntegerNumberer implements Numberer<Long> {
/** Tells the numberer that a new object needs to be assigned a number. */
@Override
public void add(Long o) {
}
/**
* Should return the number that was assigned to object o that was previously passed as an argument to add().
*/
@Override
public long get(Long o) {
if (o == null) {
return 0;
}
return o.longValue();
}
/** Should return the object that was assigned the number number. */
@Override
public Long get(long number) {
if (number == 0) {
return null;
}
return new Long(number);
}
/** Should return the number of objects that have been assigned numbers. */
@Override
public int size() {<FILL_FUNCTION_BODY>}
@Override
public boolean remove(Long o) {
return false;
}
}
|
throw new RuntimeException("IntegerNumberer does not implement the size() method.");
| 248
| 22
| 270
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/IterableSet.java
|
IterableSet
|
union
|
class IterableSet<T> extends HashChain<T> implements Set<T> {
public IterableSet(Collection<T> c) {
super();
addAll(c);
}
public IterableSet() {
super();
}
@Override
public boolean add(T o) {
if (o == null) {
throw new IllegalArgumentException("Cannot add \"null\" to an IterableSet.");
}
if (contains(o)) {
return false;
}
return super.add(o);
}
@Override
public boolean remove(Object o) {
if (o == null || !contains(o)) {
return false;
}
return super.remove(o);
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (this == o) {
return true;
}
if (!(o instanceof IterableSet)) {
return false;
}
IterableSet<?> other = (IterableSet<?>) o;
if (this.size() != other.size()) {
return false;
}
for (T t : this) {
if (!other.contains(t)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int code = 23 * size();
for (T t : this) {
// use addition here to have hash code independent of order
code += t.hashCode();
}
return code;
}
@Override
public Object clone() {
IterableSet<T> s = new IterableSet<T>();
s.addAll(this);
return s;
}
public boolean isSubsetOf(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\".");
}
if (this.size() > other.size()) {
return false;
}
for (T t : this) {
if (!other.contains(t)) {
return false;
}
}
return true;
}
public boolean isSupersetOf(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\".");
}
if (this.size() < other.size()) {
return false;
}
for (T t : other) {
if (!contains(t)) {
return false;
}
}
return true;
}
public boolean isStrictSubsetOf(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\".");
}
if (this.size() >= other.size()) {
return false;
}
return isSubsetOf(other);
}
public boolean isStrictSupersetOf(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set compare an IterableSet with \"null\".");
}
if (this.size() <= other.size()) {
return false;
}
return isSupersetOf(other);
}
public boolean intersects(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set intersect an IterableSet with \"null\".");
}
if (other.size() < this.size()) {
for (T t : other) {
if (this.contains(t)) {
return true;
}
}
} else {
for (T t : this) {
if (other.contains(t)) {
return true;
}
}
}
return false;
}
public IterableSet<T> intersection(IterableSet<T> other) {
if (other == null) {
throw new IllegalArgumentException("Cannot set intersect an IterableSet with \"null\".");
}
IterableSet<T> c = new IterableSet<T>();
if (other.size() < this.size()) {
for (T t : other) {
if (this.contains(t)) {
c.add(t);
}
}
} else {
for (T t : this) {
if (other.contains(t)) {
c.add(t);
}
}
}
return c;
}
public IterableSet<T> union(IterableSet<T> other) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (T t : this) {
b.append(t.toString()).append('\n');
}
return b.toString();
}
public UnmodifiableIterableSet<T> asUnmodifiable() {
return new UnmodifiableIterableSet<T>(this);
}
}
|
if (other == null) {
throw new IllegalArgumentException("Cannot set union an IterableSet with \"null\".");
}
IterableSet<T> c = new IterableSet<T>();
c.addAll(this);
c.addAll(other);
return c;
| 1,306
| 76
| 1,382
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Chain<T>) ,public synchronized boolean add(T) ,public synchronized void addFirst(T) ,public synchronized void addLast(T) ,public synchronized void clear() ,public synchronized boolean contains(java.lang.Object) ,public synchronized boolean containsAll(Collection<?>) ,public synchronized boolean follows(T, T) ,public synchronized Collection<T> getElementsUnsorted() ,public synchronized T getFirst() ,public synchronized T getLast() ,public long getModificationCount() ,public synchronized T getPredOf(T) throws java.util.NoSuchElementException,public synchronized T getSuccOf(T) throws java.util.NoSuchElementException,public synchronized void insertAfter(T, T) ,public synchronized void insertAfter(Collection<? extends T>, T) ,public synchronized void insertAfter(List<T>, T) ,public synchronized void insertAfter(Chain<T>, T) ,public synchronized void insertBefore(T, T) ,public synchronized void insertBefore(Collection<? extends T>, T) ,public synchronized void insertBefore(List<T>, T) ,public synchronized void insertBefore(Chain<T>, T) ,public synchronized Iterator<T> iterator() ,public synchronized Iterator<T> iterator(T) ,public synchronized Iterator<T> iterator(T, T) ,public static HashChain<T> listToHashChain(List<T>) ,public synchronized boolean remove(java.lang.Object) ,public synchronized void removeFirst() ,public synchronized void removeLast() ,public synchronized int size() ,public Iterator<T> snapshotIterator() ,public Iterator<T> snapshotIterator(T) ,public synchronized void swapWith(T, T) ,public static List<E> toList(Chain<E>) ,public synchronized java.lang.String toString() <variables>protected T firstItem,protected T lastItem,protected final non-sealed Map<T,Link<T>> map,protected int stateCount
|
soot-oss_soot
|
soot/src/main/java/soot/util/LargeNumberedMap.java
|
LargeNumberedMap
|
put
|
class LargeNumberedMap<K extends Numberable, V> implements INumberedMap<K, V> {
private final IterableNumberer<K> universe;
private V[] values;
public LargeNumberedMap(IterableNumberer<K> universe) {
this.universe = universe;
int size = universe.size();
this.values = newArray(size < 8 ? 8 : size);
}
@SuppressWarnings("unchecked")
private static <T> T[] newArray(int size) {
return (T[]) new Object[size];
}
@Override
public boolean put(K key, V value) {<FILL_FUNCTION_BODY>}
@Override
public V get(K key) {
int i = key.getNumber();
if (i >= values.length) {
return null;
}
return values[i];
}
@Override
public void remove(K key) {
int i = key.getNumber();
if (i < values.length) {
values[i] = null;
}
}
@Override
public Iterator<K> keyIterator() {
return new Iterator<K>() {
int cur = 0;
private void advance() {
while (cur < values.length && values[cur] == null) {
cur++;
}
}
@Override
public boolean hasNext() {
advance();
return cur < values.length;
}
@Override
public K next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return universe.get(cur++);
}
@Override
public void remove() {
values[cur - 1] = null;
}
};
}
}
|
int number = key.getNumber();
if (number == 0) {
throw new RuntimeException(String.format("oops, forgot to initialize. Object is of type %s, and looks like this: %s",
key.getClass().getName(), key.toString()));
}
if (number >= values.length) {
Object[] oldValues = values;
values = newArray(Math.max(universe.size() * 2, number) + 5);
System.arraycopy(oldValues, 0, values, 0, oldValues.length);
}
boolean ret = (values[number] != value);
values[number] = value;
return ret;
| 466
| 170
| 636
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/LargePriorityQueue.java
|
LargePriorityQueue
|
nextSetBit
|
class LargePriorityQueue<E> extends PriorityQueue<E> {
private final BitSet queue;
private long modCount = 0;
LargePriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) {
super(universe, ordinalMap);
queue = new BitSet(N);
}
@Override
boolean add(int ordinal) {
if (contains(ordinal)) {
return false;
}
queue.set(ordinal);
min = Math.min(min, ordinal);
modCount++;
return true;
}
@Override
void addAll() {
queue.set(0, N);
min = 0;
modCount++;
}
@Override
int nextSetBit(int fromIndex) {<FILL_FUNCTION_BODY>}
@Override
boolean remove(int ordinal) {
if (!contains(ordinal)) {
return false;
}
queue.clear(ordinal);
if (min == ordinal) {
min = nextSetBit(min + 1);
}
modCount++;
return true;
}
@Override
boolean contains(int ordinal) {
return queue.get(ordinal);
}
@Override
public Iterator<E> iterator() {
return new Itr() {
@Override
long getExpected() {
return modCount;
}
};
}
@Override
public int size() {
return queue.cardinality();
}
}
|
int i = queue.nextSetBit(fromIndex);
return (i < 0) ? Integer.MAX_VALUE : i;
| 407
| 34
| 441
|
<methods>public final boolean add(E) ,public final boolean contains(java.lang.Object) ,public boolean isEmpty() ,public static PriorityQueue<E> noneOf(E[]) ,public static PriorityQueue<E> noneOf(List<? extends E>) ,public static PriorityQueue<E> noneOf(List<? extends E>, boolean) ,public static PriorityQueue<E> of(E[]) ,public static PriorityQueue<E> of(List<? extends E>) ,public static PriorityQueue<E> of(List<? extends E>, boolean) ,public final boolean offer(E) ,public final E peek() ,public final E poll() ,public final boolean remove(java.lang.Object) <variables>final non-sealed int N,private static final org.slf4j.Logger logger,int min,private final non-sealed Map<E,java.lang.Integer> ordinalMap,private final non-sealed List<? extends E> universe
|
soot-oss_soot
|
soot/src/main/java/soot/util/LocalBitSetPacker.java
|
LocalBitSetPacker
|
unpack
|
class LocalBitSetPacker {
private final Body body;
private Local[] locals;
private int[] oldNumbers;
public LocalBitSetPacker(Body body) {
this.body = body;
}
/**
* Reassigns the local numbers such that a dense bit set can be created over them
*/
public void pack() {
int n = body.getLocalCount();
locals = new Local[n];
oldNumbers = new int[n];
n = 0;
for (Local local : body.getLocals()) {
locals[n] = local;
oldNumbers[n] = local.getNumber();
local.setNumber(n++);
}
}
/**
* Restores the original local numbering
*/
public void unpack() {<FILL_FUNCTION_BODY>}
public int getLocalCount() {
return locals == null ? 0 : locals.length;
}
}
|
for (int i = 0; i < locals.length; i++) {
locals[i].setNumber(oldNumbers[i]);
}
locals = null;
oldNumbers = null;
| 248
| 54
| 302
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/MapNumberer.java
|
MapNumberer
|
get
|
class MapNumberer<T> implements Numberer<T> {
final Map<T, Integer> map = new HashMap<T, Integer>();
final ArrayList<T> al = new ArrayList<T>();
int nextIndex = 1;
public MapNumberer() {
al.add(null);
}
@Override
public void add(T o) {
if (!map.containsKey(o)) {
map.put(o, nextIndex);
al.add(o);
nextIndex++;
}
}
@Override
public T get(long number) {
return al.get((int) number);
}
@Override
public long get(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int size() {
/* subtract 1 for null */
return nextIndex - 1;
}
public boolean contains(Object o) {
return map.containsKey(o);
}
@Override
public boolean remove(T o) {
Integer i = map.remove(o);
if (i == null) {
return false;
} else {
al.set(i, null);
return true;
}
}
}
|
if (o == null) {
return 0;
}
Integer i = map.get(o);
if (i == null) {
throw new RuntimeException("couldn't find " + o);
}
return i;
| 322
| 65
| 387
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/MediumPriorityQueue.java
|
MediumPriorityQueue
|
nextSetBit
|
class MediumPriorityQueue<E> extends PriorityQueue<E> {
final static int MAX_CAPACITY = Long.SIZE * Long.SIZE;
private final long[] data;
private int size = 0;
private long modCount = 0;
private long lookup = 0;
MediumPriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) {
super(universe, ordinalMap);
data = new long[(N + Long.SIZE - 1) >>> 6];
assert N > SmallPriorityQueue.MAX_CAPACITY;
assert N <= MAX_CAPACITY;
}
@Override
void addAll() {
size = N;
Arrays.fill(data, -1);
data[data.length - 1] = -1L >>> -size;
lookup = -1L >>> -data.length;
min = 0;
modCount++;
}
@Override
public void clear() {
size = 0;
Arrays.fill(data, 0);
lookup = 0;
min = Integer.MAX_VALUE;
modCount++;
}
@Override
int nextSetBit(int fromIndex) {<FILL_FUNCTION_BODY>}
@Override
boolean add(int ordinal) {
int bucket = ordinal >>> 6;
long prv = data[bucket];
long now = prv | (1L << ordinal);
if (prv == now) {
return false;
}
data[bucket] = now;
lookup |= (1L << bucket);
size++;
modCount++;
min = Math.min(min, ordinal);
return true;
}
@Override
boolean contains(int ordinal) {
assert ordinal >= 0;
assert ordinal < N;
return ((data[ordinal >>> 6] >>> ordinal) & 1L) == 1L;
}
@Override
boolean remove(int index) {
assert index >= 0;
assert index < N;
int bucket = index >>> 6;
long old = data[bucket];
long now = old & ~(1L << index);
if (old == now) {
return false;
}
if (0 == now) {
lookup &= ~(1L << bucket);
}
size--;
modCount++;
data[bucket] = now;
if (min == index) {
min = nextSetBit(min + 1);
}
return true;
}
@Override
public Iterator<E> iterator() {
return new Itr() {
@Override
long getExpected() {
return modCount;
}
};
}
@Override
public int size() {
return size;
}
}
|
assert fromIndex >= 0;
for (int bb = fromIndex >>> 6; fromIndex < N;) {
// remove everything from t1 that is less than "fromIndex",
long m1 = -1L << fromIndex;
// t1 contains now all active bits
long t1 = data[bb] & m1;
// the expected index m1 in t1 is set (optional test if NOTZ is
// expensive)
if ((t1 & -m1) != 0) {
return fromIndex;
}
// some bits are left in t1, so we can finish
if (t1 != 0) {
return (bb << 6) + numberOfTrailingZeros(t1);
}
// we know the previous block is empty, so we start our lookup on
// the next one
long m0 = -1L << ++bb;
long t0 = lookup & m0;
// find next used block
if ((t0 & -m0) == 0) {
bb = numberOfTrailingZeros(t0);
}
// re-assign new search index
fromIndex = bb << 6;
// next and last round
}
return fromIndex;
| 742
| 311
| 1,053
|
<methods>public final boolean add(E) ,public final boolean contains(java.lang.Object) ,public boolean isEmpty() ,public static PriorityQueue<E> noneOf(E[]) ,public static PriorityQueue<E> noneOf(List<? extends E>) ,public static PriorityQueue<E> noneOf(List<? extends E>, boolean) ,public static PriorityQueue<E> of(E[]) ,public static PriorityQueue<E> of(List<? extends E>) ,public static PriorityQueue<E> of(List<? extends E>, boolean) ,public final boolean offer(E) ,public final E peek() ,public final E poll() ,public final boolean remove(java.lang.Object) <variables>final non-sealed int N,private static final org.slf4j.Logger logger,int min,private final non-sealed Map<E,java.lang.Integer> ordinalMap,private final non-sealed List<? extends E> universe
|
soot-oss_soot
|
soot/src/main/java/soot/util/SharedBitSet.java
|
SharedBitSet
|
and
|
class SharedBitSet {
BitVector value;
boolean own = true;
public SharedBitSet(int i) {
this.value = new BitVector(i);
}
public SharedBitSet() {
this(32);
}
private void acquire() {
if (own) {
return;
}
own = true;
value = (BitVector) value.clone();
}
private void canonicalize() {
value = SharedBitSetCache.v().canonicalize(value);
own = false;
}
public boolean set(int bit) {
acquire();
return value.set(bit);
}
public void clear(int bit) {
acquire();
value.clear(bit);
}
public boolean get(int bit) {
return value.get(bit);
}
public void and(SharedBitSet other) {<FILL_FUNCTION_BODY>}
public void or(SharedBitSet other) {
if (own) {
value.or(other.value);
} else {
value = BitVector.or(value, other.value);
own = true;
}
canonicalize();
}
public boolean orAndAndNot(SharedBitSet orset, SharedBitSet andset, SharedBitSet andnotset) {
acquire();
boolean ret = value.orAndAndNot(orset.value, andset.value, andnotset.value);
canonicalize();
return ret;
}
public boolean orAndAndNot(SharedBitSet orset, BitVector andset, SharedBitSet andnotset) {
acquire();
boolean ret = value.orAndAndNot(orset.value, andset, andnotset == null ? null : andnotset.value);
canonicalize();
return ret;
}
public BitSetIterator iterator() {
return value.iterator();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (BitSetIterator it = iterator(); it.hasNext();) {
int next = it.next();
b.append(next);
if (it.hasNext()) {
b.append(',');
}
}
return b.toString();
}
}
|
if (own) {
value.and(other.value);
} else {
value = BitVector.and(value, other.value);
own = true;
}
canonicalize();
| 589
| 54
| 643
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/SharedBitSetCache.java
|
SharedBitSetCache
|
canonicalize
|
class SharedBitSetCache {
public SharedBitSetCache(Singletons.Global g) {
}
public static SharedBitSetCache v() {
return G.v().soot_util_SharedBitSetCache();
}
public static final int size = 32749; // a nice prime about 32k
public BitVector[] cache = new BitVector[size];
public BitVector[] orAndAndNotCache = new BitVector[size];
public BitVector canonicalize(BitVector set) {<FILL_FUNCTION_BODY>}
}
|
int hash = set.hashCode();
if (hash < 0) {
hash = -hash;
}
hash %= size;
BitVector hashed = cache[hash];
if (hashed != null && hashed.equals(set)) {
return hashed;
} else {
cache[hash] = set;
return set;
}
| 146
| 96
| 242
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/SmallNumberedMap.java
|
SmallNumberedMapIterator
|
findPosition
|
class SmallNumberedMapIterator<C> implements Iterator<C> {
private final C[] data;
private int cur;
SmallNumberedMapIterator(C[] data) {
this.data = data;
this.cur = 0;
seekNext();
}
protected final void seekNext() {
V[] temp = SmallNumberedMap.this.values;
try {
while (temp[cur] == null) {
cur++;
}
} catch (ArrayIndexOutOfBoundsException e) {
cur = -1;
}
}
@Override
public final void remove() {
SmallNumberedMap.this.array[cur - 1] = null;
SmallNumberedMap.this.values[cur - 1] = null;
}
@Override
public final boolean hasNext() {
return cur != -1;
}
@Override
public final C next() {
C ret = data[cur];
cur++;
seekNext();
return ret;
}
}
private int findPosition(K o) {<FILL_FUNCTION_BODY>
|
int number = o.getNumber();
if (number == 0) {
throw new RuntimeException("unnumbered");
}
number = number & (array.length - 1);
while (true) {
K key = array[number];
if (key == o || key == null) {
return number;
}
number = (number + 1) & (array.length - 1);
}
| 291
| 108
| 399
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/SmallPriorityQueue.java
|
SmallPriorityQueue
|
removeAll
|
class SmallPriorityQueue<E> extends PriorityQueue<E> {
final static int MAX_CAPACITY = Long.SIZE;
private long queue = 0;
SmallPriorityQueue(List<? extends E> universe, Map<E, Integer> ordinalMap) {
super(universe, ordinalMap);
assert universe.size() <= Long.SIZE;
}
@Override
void addAll() {
if (N == 0) {
return;
}
queue = -1L >>> -N;
min = 0;
}
@Override
public void clear() {
queue = 0L;
min = Integer.MAX_VALUE;
}
@Override
public Iterator<E> iterator() {
return new Itr() {
@Override
long getExpected() {
return queue;
}
};
}
@Override
public int size() {
return Long.bitCount(queue);
}
@Override
int nextSetBit(int fromIndex) {
assert fromIndex >= 0;
if (fromIndex > N) {
return fromIndex;
}
long m0 = -1L << fromIndex;
long t0 = queue & m0;
if ((t0 & -m0) != 0) {
return fromIndex;
}
return numberOfTrailingZeros(t0);
}
@Override
boolean add(int ordinal) {
long old = queue;
queue |= (1L << ordinal);
if (old == queue) {
return false;
}
min = Math.min(min, ordinal);
return true;
}
@Override
boolean contains(int ordinal) {
assert ordinal >= 0;
assert ordinal < N;
return ((queue >>> ordinal) & 1L) == 1L;
}
@Override
boolean remove(int index) {
assert index >= 0;
assert index < N;
long old = queue;
queue &= ~(1L << index);
if (old == queue) {
return false;
}
if (min == index) {
min = nextSetBit(min + 1);
}
return true;
}
@Override
public boolean removeAll(Collection<?> c) {<FILL_FUNCTION_BODY>}
@Override
public boolean retainAll(Collection<?> c) {
long mask = 0;
for (Object o : c) {
mask |= (1L << getOrdinal(o));
}
long old = queue;
queue &= mask;
min = nextSetBit(min);
return old != queue;
}
@Override
public boolean containsAll(Collection<?> c) {
long mask = 0;
for (Object o : c) {
mask |= (1L << getOrdinal(o));
}
return (mask & ~queue) == 0;
}
@Override
public boolean addAll(Collection<? extends E> c) {
long mask = 0;
for (Object o : c) {
mask |= (1L << getOrdinal(o));
}
long old = queue;
queue |= mask;
if (old == queue) {
return false;
}
min = nextSetBit(0);
return true;
}
}
|
long mask = 0;
for (Object o : c) {
mask |= (1L << getOrdinal(o));
}
long old = queue;
queue &= ~mask;
min = nextSetBit(min);
return old != queue;
| 880
| 71
| 951
|
<methods>public final boolean add(E) ,public final boolean contains(java.lang.Object) ,public boolean isEmpty() ,public static PriorityQueue<E> noneOf(E[]) ,public static PriorityQueue<E> noneOf(List<? extends E>) ,public static PriorityQueue<E> noneOf(List<? extends E>, boolean) ,public static PriorityQueue<E> of(E[]) ,public static PriorityQueue<E> of(List<? extends E>) ,public static PriorityQueue<E> of(List<? extends E>, boolean) ,public final boolean offer(E) ,public final E peek() ,public final E poll() ,public final boolean remove(java.lang.Object) <variables>final non-sealed int N,private static final org.slf4j.Logger logger,int min,private final non-sealed Map<E,java.lang.Integer> ordinalMap,private final non-sealed List<? extends E> universe
|
soot-oss_soot
|
soot/src/main/java/soot/util/StringNumberer.java
|
StringNumberer
|
findOrAdd
|
class StringNumberer extends ArrayNumberer<NumberedString> {
private final Map<String, NumberedString> stringToNumbered = new HashMap<String, NumberedString>(1024);
public synchronized NumberedString findOrAdd(String s) {<FILL_FUNCTION_BODY>}
public NumberedString find(String s) {
return stringToNumbered.get(s);
}
}
|
NumberedString ret = stringToNumbered.get(s);
if (ret == null) {
ret = new NumberedString(s);
stringToNumbered.put(s, ret);
add(ret);
}
return ret;
| 110
| 66
| 176
|
<methods>public void <init>() ,public void <init>(soot.util.NumberedString[]) ,public synchronized void add(soot.util.NumberedString) ,public long get(soot.util.NumberedString) ,public soot.util.NumberedString get(long) ,public Iterator<soot.util.NumberedString> iterator() ,public boolean remove(soot.util.NumberedString) ,public int size() <variables>protected java.util.BitSet freeNumbers,protected int lastNumber,protected soot.util.NumberedString[] numberToObj
|
soot-oss_soot
|
soot/src/main/java/soot/util/StringTools.java
|
StringTools
|
getUnEscapedStringOf
|
class StringTools {
/** Convenience field storing the system line separator. */
public final static String lineSeparator = System.getProperty("line.separator");
/**
* Returns fromString, but with non-isalpha() characters printed as <code>'\\unnnn'</code>. Used by SootClass to generate
* output.
*/
public static String getEscapedStringOf(String fromString) {
StringBuilder whole = new StringBuilder();
assert (!lineSeparator.isEmpty());
final int cr = lineSeparator.charAt(0);
final int lf = (lineSeparator.length() == 2) ? lineSeparator.charAt(1) : -1;
for (char ch : fromString.toCharArray()) {
int asInt = ch;
if (asInt != '\\' && ((asInt >= 32 && asInt <= 126) || asInt == cr || asInt == lf)) {
whole.append(ch);
} else {
whole.append(getUnicodeStringFromChar(ch));
}
}
return whole.toString();
}
/**
* Returns fromString, but with certain characters printed as if they were in a Java string literal. Used by
* StringConstant.toString()
*/
public static String getQuotedStringOf(String fromString) {
final int fromStringLen = fromString.length();
// We definitely need fromStringLen + 2, but let's have some additional space
StringBuilder toStringBuffer = new StringBuilder(fromStringLen + 20);
toStringBuffer.append("\"");
for (int i = 0; i < fromStringLen; i++) {
char ch = fromString.charAt(i);
switch (ch) {
case '\\':
toStringBuffer.append("\\\\");
break;
case '\'':
toStringBuffer.append("\\\'");
break;
case '\"':
toStringBuffer.append("\\\"");
break;
case '\n':
toStringBuffer.append("\\n");
break;
case '\t':
toStringBuffer.append("\\t");
break;
case '\r':
/*
* 04.04.2006 mbatch added handling of \r, as compilers throw error if unicode
*/
toStringBuffer.append("\\r");
break;
case '\f':
/*
* 10.04.2006 Nomait A Naeem added handling of \f, as compilers throw error if unicode
*/
toStringBuffer.append("\\f");
break;
default:
if (ch >= 32 && ch <= 126) {
toStringBuffer.append(ch);
} else {
toStringBuffer.append(getUnicodeStringFromChar(ch));
}
break;
}
}
toStringBuffer.append("\"");
return toStringBuffer.toString();
}
/**
* Returns a String containing the escaped <code>\\unnnn</code> representation for <code>ch</code>.
*/
public static String getUnicodeStringFromChar(char ch) {
String s = Integer.toHexString(ch);
switch (s.length()) {
case 1:
return "\\u" + "000" + s;
case 2:
return "\\u" + "00" + s;
case 3:
return "\\u" + "0" + s;
case 4:
return "\\u" + "" + s;
default:
// hex value of a char never exceeds 4 characters since char is 2 bytes
throw new AssertionError("invalid hex string '" + s + "' from char '" + ch + "'");
}
}
/**
* Returns a String de-escaping the <code>\\unnnn</code> representation for any escaped characters in the string.
*/
public static String getUnEscapedStringOf(String str) {<FILL_FUNCTION_BODY>}
/** Returns the canonical C-string representation of c. */
public static char getCFormatChar(char c) {
switch (c) {
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
case '\"':
return '\"';
case '\'':
return '\'';
default:
return '\0';
}
}
}
|
StringBuilder buf = new StringBuilder();
CharacterIterator iter = new StringCharacterIterator(str);
for (char ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) {
if (ch != '\\') {
buf.append(ch);
} else { // enter escaped mode
ch = iter.next();
char format;
if (ch == '\\') {
buf.append(ch);
} else if ((format = getCFormatChar(ch)) != '\0') {
buf.append(format);
} else if (ch == 'u') { // enter unicode mode
StringBuilder mini = new StringBuilder(4);
for (int i = 0; i < 4; i++) {
mini.append(iter.next());
}
buf.append((char) Integer.parseInt(mini.toString(), 16));
} else {
throw new RuntimeException("Unexpected char: " + ch);
}
}
}
return buf.toString();
| 1,161
| 260
| 1,421
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/annotations/AnnotationElemSwitch.java
|
AnnotationElemResult
|
caseAnnotationArrayElem
|
class AnnotationElemResult<V> {
private final String name;
private final V value;
public AnnotationElemResult(String name, V value) {
this.name = name;
this.value = value;
}
public String getKey() {
return name;
}
public V getValue() {
return value;
}
}
@Override
public void caseAnnotationAnnotationElem(AnnotationAnnotationElem v) {
AnnotationInstanceCreator aic = new AnnotationInstanceCreator();
Object result = aic.create(v.getValue());
setResult(new AnnotationElemResult<Object>(v.getName(), result));
}
@Override
public void caseAnnotationArrayElem(AnnotationArrayElem v) {<FILL_FUNCTION_BODY>
|
/*
* for arrays, apply a new AnnotationElemSwitch to every array element and collect the results. Note that the component
* type of the result is unknown here, s.t. object has to be used.
*/
Object[] result = new Object[v.getNumValues()];
int i = 0;
for (AnnotationElem elem : v.getValues()) {
AnnotationElemSwitch sw = new AnnotationElemSwitch();
elem.apply(sw);
result[i] = sw.getResult().getValue();
i++;
}
setResult(new AnnotationElemResult<Object[]>(v.getName(), result));
| 211
| 165
| 376
|
<methods>public non-sealed void <init>() ,public void caseAnnotationAnnotationElem(soot.tagkit.AnnotationAnnotationElem) ,public void caseAnnotationArrayElem(soot.tagkit.AnnotationArrayElem) ,public void caseAnnotationBooleanElem(soot.tagkit.AnnotationBooleanElem) ,public void caseAnnotationClassElem(soot.tagkit.AnnotationClassElem) ,public void caseAnnotationDoubleElem(soot.tagkit.AnnotationDoubleElem) ,public void caseAnnotationEnumElem(soot.tagkit.AnnotationEnumElem) ,public void caseAnnotationFloatElem(soot.tagkit.AnnotationFloatElem) ,public void caseAnnotationIntElem(soot.tagkit.AnnotationIntElem) ,public void caseAnnotationLongElem(soot.tagkit.AnnotationLongElem) ,public void caseAnnotationStringElem(soot.tagkit.AnnotationStringElem) ,public void defaultCase(java.lang.Object) ,public AnnotationElemResult<?> getResult() ,public void setResult(AnnotationElemResult<?>) <variables>AnnotationElemResult<?> result
|
soot-oss_soot
|
soot/src/main/java/soot/util/annotations/ClassLoaderUtils.java
|
ClassLoaderUtils
|
loadClass
|
class ClassLoaderUtils {
/**
* Don't call me. Just don't.
*
* @param className
* @return
* @throws ClassNotFoundException
*/
public static Class<?> loadClass(String className) throws ClassNotFoundException {
return loadClass(className, true);
}
/**
* Don't call me. Just don't.
*
* @param className
* @return
* @throws ClassNotFoundException
*/
public static Class<?> loadClass(String className, boolean allowPrimitives) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
}
|
// Do we have a primitive class
if (allowPrimitives) {
switch (className) {
case "B":
case "byte":
return Byte.TYPE;
case "C":
case "char":
return Character.TYPE;
case "D":
case "double":
return Double.TYPE;
case "F":
case "float":
return Float.TYPE;
case "I":
case "int":
return Integer.TYPE;
case "J":
case "long":
return Long.TYPE;
case "S":
case "short":
return Short.TYPE;
case "Z":
case "boolean":
return Boolean.TYPE;
case "V":
case "void":
return Void.TYPE;
}
}
// JNI format
if (className.startsWith("L") && className.endsWith(";")) {
return loadClass(className.substring(1, className.length() - 1), false);
}
int arrayDimension = 0;
while (className.charAt(arrayDimension) == '[') {
arrayDimension++;
}
// If this isn't an array after all
if (arrayDimension == 0) {
return Class.forName(className);
}
// Load the array
Class<?> baseClass = loadClass(className.substring(arrayDimension));
return Array.newInstance(baseClass, new int[arrayDimension]).getClass();
| 165
| 386
| 551
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/backend/ASMBackendUtils.java
|
ASMBackendUtils
|
toTypeDesc
|
class ASMBackendUtils {
/**
* Convert class identifiers and signatures by replacing dots by slashes.
*
* @param s
* String to convert
* @return Converted identifier
*/
public static String slashify(String s) {
if (s == null) {
return null;
}
return s.replace('.', '/');
}
/**
* Compute type description for methods, comprising parameter types and return type.
*
* @param m
* Method to determine type description
* @return Method type description
*/
public static String toTypeDesc(SootMethodRef m) {
return toTypeDesc(m.parameterTypes(), m.returnType());
}
/**
* Compute type description for methods, comprising parameter types and return type.
*
* @param parameterTypes
* The parameters for some method
* @param returnType
* The return type for some method
* @return Method type description
*/
public static String toTypeDesc(List<Type> parameterTypes, Type returnType) {
StringBuilder sb = new StringBuilder();
sb.append('(');
for (Type t : parameterTypes) {
sb.append(toTypeDesc(t));
}
sb.append(')');
sb.append(toTypeDesc(returnType));
return sb.toString();
}
/**
* Convert type to JVM style type description
*
* @param type
* Type to convert
* @return JVM style type description
*/
public static String toTypeDesc(Type type) {<FILL_FUNCTION_BODY>}
/**
* Get default value of a field for constant pool
*
* @param field
* Field to get default value for
* @return Default value or <code>null</code> if there is no default value.
*/
public static Object getDefaultValue(SootField field) {
for (Tag t : field.getTags()) {
switch (t.getName()) {
case IntegerConstantValueTag.NAME:
return ((IntegerConstantValueTag) t).getIntValue();
case LongConstantValueTag.NAME:
return ((LongConstantValueTag) t).getLongValue();
case FloatConstantValueTag.NAME:
return ((FloatConstantValueTag) t).getFloatValue();
case DoubleConstantValueTag.NAME:
return ((DoubleConstantValueTag) t).getDoubleValue();
case StringConstantValueTag.NAME:
// Default value for string may only be returned if the field is of type String or a sub-type.
if (acceptsStringInitialValue(field)) {
return ((StringConstantValueTag) t).getStringValue();
}
}
}
return null;
}
/**
* Determine if the field accepts a string default value, this is only true for fields of type String or a sub-type of
* String
*
* @param field
* Field
* @return <code>true</code> if the field is of type String or sub-type, <code>false</code> otherwise.
*/
public static boolean acceptsStringInitialValue(SootField field) {
if (field.getType() instanceof RefType) {
SootClass fieldClass = ((RefType) field.getType()).getSootClass();
return fieldClass.getName().equals("java.lang.String");
}
return false;
}
/**
* Get the size in words for a type.
*
* @param t
* Type
* @return Size in words
*/
public static int sizeOfType(Type t) {
if (t instanceof DoubleWordType || t instanceof LongType || t instanceof DoubleType) {
return 2;
} else if (t instanceof VoidType) {
return 0;
} else {
return 1;
}
}
/**
* Create an ASM attribute from an Soot attribute
*
* @param attr
* Soot attribute
* @return ASM attribute
*/
public static org.objectweb.asm.Attribute createASMAttribute(Attribute attr) {
final Attribute a = attr;
return new org.objectweb.asm.Attribute(attr.getName()) {
@Override
protected ByteVector write(final ClassWriter cw, final byte[] code, final int len, final int maxStack,
final int maxLocals) {
ByteVector result = new ByteVector();
result.putByteArray(a.getValue(), 0, a.getValue().length);
return result;
}
};
}
/**
* Translate internal numbering of java versions to real version for debug messages.
*
* @param javaVersion
* Internal java version number
* @return Java version in the format "1.7"
*/
public static String translateJavaVersion(int javaVersion) {
if (javaVersion == Options.java_version_default) {
return "1.0";
} else {
return "1." + (javaVersion - 1);
}
}
}
|
final StringBuilder sb = new StringBuilder(1);
type.apply(new TypeSwitch() {
@Override
public void defaultCase(Type t) {
throw new RuntimeException("Invalid type " + t.toString());
}
@Override
public void caseDoubleType(DoubleType t) {
sb.append('D');
}
@Override
public void caseFloatType(FloatType t) {
sb.append('F');
}
@Override
public void caseIntType(IntType t) {
sb.append('I');
}
@Override
public void caseByteType(ByteType t) {
sb.append('B');
}
@Override
public void caseShortType(ShortType t) {
sb.append('S');
}
@Override
public void caseCharType(CharType t) {
sb.append('C');
}
@Override
public void caseBooleanType(BooleanType t) {
sb.append('Z');
}
@Override
public void caseLongType(LongType t) {
sb.append('J');
}
@Override
public void caseArrayType(ArrayType t) {
sb.append('[');
t.getElementType().apply(this);
}
@Override
public void caseRefType(RefType t) {
sb.append('L');
sb.append(slashify(t.getClassName()));
sb.append(';');
}
@Override
public void caseVoidType(VoidType t) {
sb.append('V');
}
});
return sb.toString();
| 1,283
| 426
| 1,709
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/backend/SootASMClassWriter.java
|
SootASMClassWriter
|
getCommonSuperClass
|
class SootASMClassWriter extends ClassWriter {
/**
* Constructs a new {@link ClassWriter} object.
*
* @param flags
* option flags that can be used to modify the default behavior of this class. See {@link #COMPUTE_MAXS},
* {@link #COMPUTE_FRAMES}.
*/
public SootASMClassWriter(int flags) {
super(flags);
}
/*
* We need to overwrite this method here, as we are generating multiple classes that might reference each other. See
* asm4-guide, top of page 45 for more information.
*/
/*
* (non-Javadoc)
*
* @see org.objectweb.asm.ClassWriter#getCommonSuperClass(java.lang.String, java.lang.String)
*/
@Override
protected String getCommonSuperClass(String type1, String type2) {<FILL_FUNCTION_BODY>}
}
|
String typeName1 = type1.replace('/', '.');
String typeName2 = type2.replace('/', '.');
SootClass s1 = Scene.v().getSootClass(typeName1);
SootClass s2 = Scene.v().getSootClass(typeName2);
// If these two classes haven't been loaded yet or are phantom, we take
// java.lang.Object as the common superclass
final Type mergedType;
if (s1.isPhantom() || s2.isPhantom() || s1.resolvingLevel() == SootClass.DANGLING
|| s2.resolvingLevel() == SootClass.DANGLING) {
mergedType = Scene.v().getObjectType();
} else {
Type t1 = s1.getType();
Type t2 = s2.getType();
mergedType = t1.merge(t2, Scene.v());
}
if (mergedType instanceof RefType) {
return slashify(((RefType) mergedType).getClassName());
} else {
throw new RuntimeException("Could not find common super class");
}
| 246
| 297
| 543
|
<methods>public void <init>(int) ,public void <init>(org.objectweb.asm.ClassReader, int) ,public boolean hasFlags(int) ,public int newClass(java.lang.String) ,public int newConst(java.lang.Object) ,public transient int newConstantDynamic(java.lang.String, java.lang.String, org.objectweb.asm.Handle, java.lang.Object[]) ,public int newField(java.lang.String, java.lang.String, java.lang.String) ,public int newHandle(int, java.lang.String, java.lang.String, java.lang.String) ,public int newHandle(int, java.lang.String, java.lang.String, java.lang.String, boolean) ,public transient int newInvokeDynamic(java.lang.String, java.lang.String, org.objectweb.asm.Handle, java.lang.Object[]) ,public int newMethod(java.lang.String, java.lang.String, java.lang.String, boolean) ,public int newMethodType(java.lang.String) ,public int newModule(java.lang.String) ,public int newNameType(java.lang.String, java.lang.String) ,public int newPackage(java.lang.String) ,public int newUTF8(java.lang.String) ,public byte[] toByteArray() ,public final void visit(int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[]) ,public final org.objectweb.asm.AnnotationVisitor visitAnnotation(java.lang.String, boolean) ,public final void visitAttribute(org.objectweb.asm.Attribute) ,public final void visitEnd() ,public final org.objectweb.asm.FieldVisitor visitField(int, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final void visitInnerClass(java.lang.String, java.lang.String, java.lang.String, int) ,public final org.objectweb.asm.MethodVisitor visitMethod(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[]) ,public final org.objectweb.asm.ModuleVisitor visitModule(java.lang.String, int, java.lang.String) ,public final void visitNestHost(java.lang.String) ,public final void visitNestMember(java.lang.String) ,public final void visitOuterClass(java.lang.String, java.lang.String, java.lang.String) ,public final void visitPermittedSubclass(java.lang.String) ,public final org.objectweb.asm.RecordComponentVisitor visitRecordComponent(java.lang.String, java.lang.String, java.lang.String) ,public final void visitSource(java.lang.String, java.lang.String) ,public final org.objectweb.asm.AnnotationVisitor visitTypeAnnotation(int, org.objectweb.asm.TypePath, java.lang.String, boolean) <variables>public static final int COMPUTE_FRAMES,public static final int COMPUTE_MAXS,private int accessFlags,private int compute,private org.objectweb.asm.ByteVector debugExtension,private int enclosingClassIndex,private int enclosingMethodIndex,private org.objectweb.asm.Attribute firstAttribute,private org.objectweb.asm.FieldWriter firstField,private org.objectweb.asm.MethodWriter firstMethod,private org.objectweb.asm.RecordComponentWriter firstRecordComponent,private final int flags,private org.objectweb.asm.ByteVector innerClasses,private int interfaceCount,private int[] interfaces,private org.objectweb.asm.FieldWriter lastField,private org.objectweb.asm.MethodWriter lastMethod,private org.objectweb.asm.RecordComponentWriter lastRecordComponent,private org.objectweb.asm.AnnotationWriter lastRuntimeInvisibleAnnotation,private org.objectweb.asm.AnnotationWriter lastRuntimeInvisibleTypeAnnotation,private org.objectweb.asm.AnnotationWriter lastRuntimeVisibleAnnotation,private org.objectweb.asm.AnnotationWriter lastRuntimeVisibleTypeAnnotation,private org.objectweb.asm.ModuleWriter moduleWriter,private int nestHostClassIndex,private org.objectweb.asm.ByteVector nestMemberClasses,private int numberOfInnerClasses,private int numberOfNestMemberClasses,private int numberOfPermittedSubclasses,private org.objectweb.asm.ByteVector permittedSubclasses,private int signatureIndex,private int sourceFileIndex,private int superClass,private final org.objectweb.asm.SymbolTable symbolTable,private int thisClass,private int version
|
soot-oss_soot
|
soot/src/main/java/soot/util/cfgcmd/CFGOptionMatcher.java
|
CFGOption
|
help
|
class CFGOption {
private final String name;
protected CFGOption(String name) {
this.name = name;
}
public String name() {
return name;
}
}
private final CFGOption[] options;
/**
* Creates a CFGOptionMatcher.
*
* @param options
* The set of command options to be stored.
*/
public CFGOptionMatcher(CFGOption[] options) {
this.options = options;
}
/**
* Searches the options in this <code>CFGOptionMatcher</code> looking for one whose name begins with the passed string
* (ignoring the case of letters in the string).
*
* @param quarry
* The string to be matched against the stored option names.
*
* @return The matching {@link CFGOption}, if exactly one of the stored option names begins with <code>quarry</code>.
*
* @throws soot.CompilationDeathException
* if <code>quarry</code> matches none of the option names, or if it matches more than one.
*/
public CFGOption match(String quarry) throws soot.CompilationDeathException {
String uncasedQuarry = quarry.toLowerCase();
int match = -1;
for (int i = 0; i < options.length; i++) {
String uncasedName = options[i].name().toLowerCase();
if (uncasedName.startsWith(uncasedQuarry)) {
if (match == -1) {
match = i;
} else {
logger.debug("" + quarry + " is ambiguous; it matches " + options[match].name() + " and " + options[i].name());
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "Option parse error");
}
}
}
if (match == -1) {
logger.debug("\"" + quarry + "\"" + " does not match any value.");
throw new CompilationDeathException(CompilationDeathException.COMPILATION_ABORTED, "Option parse error");
} else {
return options[match];
}
}
/**
* Returns a string containing the names of all the options in this <code>CFGOptionMatcher</code>, separated by '|'
* characters. The string is intended for use in help messages.
*
* @param initialIndent
* The number of blank spaces to insert at the beginning of the returned string. Ignored if negative.
*
* @param rightMargin
* If positive, newlines will be inserted to try to keep the length of each line in the returned string less than
* or equal to <code>rightMargin</code>.
*
* @param hangingIndent
* If positive, this number of spaces will be inserted immediately after each newline inserted to respect the
* <code>rightMargin</code>.
*/
public String help(int initialIndent, int rightMargin, int hangingIndent) {<FILL_FUNCTION_BODY>
|
StringBuilder newLineBuf = new StringBuilder(2 + rightMargin);
newLineBuf.append('\n');
if (hangingIndent < 0) {
hangingIndent = 0;
}
for (int i = 0; i < hangingIndent; i++) {
newLineBuf.append(' ');
}
String newLine = newLineBuf.toString();
StringBuilder result = new StringBuilder();
int lineLength = 0;
for (int i = 0; i < initialIndent; i++) {
lineLength++;
result.append(' ');
}
for (int i = 0; i < options.length; i++) {
if (i > 0) {
result.append('|');
lineLength++;
}
String name = options[i].name();
int nameLength = name.length();
if ((lineLength + nameLength) > rightMargin) {
result.append(newLine);
lineLength = hangingIndent;
}
result.append(name);
lineLength += nameLength;
}
return result.toString();
| 795
| 284
| 1,079
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/cfgcmd/CFGToDotGraph.java
|
ExceptionDestComparator
|
drawCFG
|
class ExceptionDestComparator<T> implements Comparator<ExceptionDest<T>> {
private final DotNamer<T> namer;
ExceptionDestComparator(DotNamer<T> namer) {
this.namer = namer;
}
private int getValue(ExceptionDest<T> o) {
T handler = o.getHandlerNode();
if (handler == null) {
return Integer.MAX_VALUE;
} else {
return namer.getNumber(handler);
}
}
@Override
public int compare(ExceptionDest<T> o1, ExceptionDest<T> o2) {
return (getValue(o1) - getValue(o2));
}
public boolean equal(ExceptionDest<T> o1, ExceptionDest<T> o2) {
return (getValue(o1) == getValue(o2));
}
}
/**
* Create a <code>DotGraph</code> whose nodes and edges depict a control flow graph without distinguished exceptional
* edges.
*
* @param graph
* a <code>DirectedGraph</code> representing a CFG (probably an instance of {@link UnitGraph}, {@link BlockGraph},
* or one of their subclasses).
*
* @param body
* the <code>Body</code> represented by <code>graph</code> (used to format the text within nodes). If no body is
* available, pass <code>null</code>.
*
* @return a visualization of <code>graph</code>.
*/
public <N> DotGraph drawCFG(DirectedGraph<N> graph, Body body) {
DotGraph canvas = initDotGraph(body);
DotNamer<N> namer = new DotNamer<N>((int) (graph.size() / 0.7f), 0.7f);
NodeComparator<N> comparator = new NodeComparator<N>(namer);
// To facilitate comparisons between different graphs of the same
// method, prelabel the nodes in the order they appear
// in the iterator, rather than the order that they appear in the
// graph traversal (so that corresponding nodes are more likely
// to have the same label in different graphs of a given method).
for (N node : graph) {
namer.getName(node);
}
for (N node : graph) {
canvas.drawNode(namer.getName(node));
for (Iterator<N> succsIt = sortedIterator(graph.getSuccsOf(node), comparator); succsIt.hasNext();) {
N succ = succsIt.next();
canvas.drawEdge(namer.getName(node), namer.getName(succ));
}
}
setStyle(graph.getHeads(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, headAttr);
setStyle(graph.getTails(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, tailAttr);
if (!isBrief) {
formatNodeText(body, canvas, namer);
}
return canvas;
}
/**
* Create a <code>DotGraph</code> whose nodes and edges depict the control flow in a <code>ExceptionalGraph</code>, with
* distinguished edges for exceptional control flow.
*
* @param graph
* the control flow graph
*
* @return a visualization of <code>graph</code>.
*/
public <N> DotGraph drawCFG(ExceptionalGraph<N> graph) {<FILL_FUNCTION_BODY>
|
Body body = graph.getBody();
DotGraph canvas = initDotGraph(body);
DotNamer<Object> namer = new DotNamer<Object>((int) (graph.size() / 0.7f), 0.7f);
@SuppressWarnings("unchecked")
NodeComparator<N> nodeComparator = new NodeComparator<N>((DotNamer<N>) namer);
// Prelabel nodes in iterator order, to facilitate
// comparisons between graphs of a given method.
for (N node : graph) {
namer.getName(node);
}
for (N node : graph) {
canvas.drawNode(namer.getName(node));
for (Iterator<N> succsIt = sortedIterator(graph.getUnexceptionalSuccsOf(node), nodeComparator); succsIt.hasNext();) {
N succ = succsIt.next();
DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(succ));
edge.setAttribute(unexceptionalControlFlowAttr);
}
for (Iterator<N> succsIt = sortedIterator(graph.getExceptionalSuccsOf(node), nodeComparator); succsIt.hasNext();) {
N succ = succsIt.next();
DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(succ));
edge.setAttribute(exceptionalControlFlowAttr);
}
if (showExceptions) {
Collection<? extends ExceptionDest<N>> exDests = graph.getExceptionDests(node);
if (exDests != null) {
@SuppressWarnings("unchecked")
ExceptionDestComparator<N> comp = new ExceptionDestComparator<>((DotNamer<N>) namer);
for (Iterator<? extends ExceptionDest<N>> destsIt = sortedIterator(exDests, comp); destsIt.hasNext();) {
ExceptionDest<N> dest = destsIt.next();
Object handlerStart = dest.getHandlerNode();
if (handlerStart == null) {
// Giving each escaping exception its own, invisible
// exceptional exit node produces a less cluttered
// graph.
handlerStart = new Object() {
@Override
public String toString() {
return "Esc";
}
};
DotGraphNode escapeNode = canvas.drawNode(namer.getName(handlerStart));
escapeNode.setStyle(DotGraphConstants.NODE_STYLE_INVISIBLE);
}
DotGraphEdge edge = canvas.drawEdge(namer.getName(node), namer.getName(handlerStart));
edge.setAttribute(exceptionEdgeAttr);
edge.setLabel(formatThrowableSet(dest.getThrowables()));
}
}
}
}
setStyle(graph.getHeads(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, headAttr);
setStyle(graph.getTails(), canvas, namer, DotGraphConstants.NODE_STYLE_FILLED, tailAttr);
if (!isBrief) {
formatNodeText(graph.getBody(), canvas, namer);
}
return canvas;
| 932
| 828
| 1,760
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/util/dot/DotGraphUtility.java
|
DotGraphUtility
|
replaceReturns
|
class DotGraphUtility {
private static final Logger logger = LoggerFactory.getLogger(DotGraphUtility.class);
/**
* Replace any {@code "} with {@code \"}. If the {@code "} character was already escaped (i.e. {@code \"}), then the escape
* character is also escaped (i.e. {@code \\\"}).
*
* @param original
*
* @return
*/
public static String replaceQuotes(String original) {
byte[] ord = original.getBytes();
int quotes = 0;
boolean escapeActive = false;
for (byte element : ord) {
switch (element) {
case '\\':
escapeActive = true;
break;
case '\"':
quotes++;
if (escapeActive) {
quotes++;
}
// fallthrough
default:
escapeActive = false;
break;
}
}
if (quotes == 0) {
return original;
}
byte[] newsrc = new byte[ord.length + quotes];
for (int i = 0, j = 0, n = ord.length; i < n; i++, j++) {
if (ord[i] == '\"') {
if (i > 0 && ord[i - 1] == '\\') {
newsrc[j++] = (byte) '\\';
}
newsrc[j++] = (byte) '\\';
}
newsrc[j] = ord[i];
}
/*
* logger.debug("before "+original); logger.debug("after "+(new String(newsrc)));
*/
return new String(newsrc);
}
/**
* Replace any return ({@code \n}) with {@code \\n}.
*
* @param original
*
* @return
*/
public static String replaceReturns(String original) {<FILL_FUNCTION_BODY>}
public static void renderLine(OutputStream out, String content, int indent) throws IOException {
char[] indentChars = new char[indent];
Arrays.fill(indentChars, ' ');
StringBuilder sb = new StringBuilder();
sb.append(indentChars).append(content).append('\n');
out.write(sb.toString().getBytes());
}
}
|
byte[] ord = original.getBytes();
int quotes = 0;
for (byte element : ord) {
if (element == '\n') {
quotes++;
}
}
if (quotes == 0) {
return original;
}
byte[] newsrc = new byte[ord.length + quotes];
for (int i = 0, j = 0, n = ord.length; i < n; i++, j++) {
if (ord[i] == '\n') {
newsrc[j++] = (byte) '\\';
newsrc[j] = (byte) 'n';
} else {
newsrc[j] = ord[i];
}
}
/*
* logger.debug("before "+original); logger.debug("after "+(new String(newsrc)));
*/
return new String(newsrc);
| 599
| 226
| 825
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/xml/Key.java
|
Key
|
print
|
class Key {
private final int red;
private final int green;
private final int blue;
private final String key;
private String aType;
public Key(int r, int g, int b, String k) {
this.red = r;
this.green = g;
this.blue = b;
this.key = k;
}
public int red() {
return this.red;
}
public int green() {
return this.green;
}
public int blue() {
return this.blue;
}
public String key() {
return this.key;
}
public String aType() {
return this.aType;
}
public void aType(String s) {
this.aType = s;
}
public void print(PrintWriter writerOut) {<FILL_FUNCTION_BODY>}
}
|
writerOut.println("<key red=\"" + red() + "\" green=\"" + green() + "\" blue=\"" + blue() + "\" key=\"" + key()
+ "\" aType=\"" + aType() + "\"/>");
| 237
| 68
| 305
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/xml/TagCollector.java
|
TagCollector
|
collectBodyTags
|
class TagCollector {
private final ArrayList<Attribute> attributes;
private final ArrayList<Key> keys;
public TagCollector() {
this.attributes = new ArrayList<Attribute>();
this.keys = new ArrayList<Key>();
}
public boolean isEmpty() {
return attributes.isEmpty() && keys.isEmpty();
}
/**
* Convenience function for <code>collectTags(sc, true)</code>.
*
* @param sc
*/
public void collectTags(SootClass sc) {
collectTags(sc, true);
}
/**
* Collect tags from all fields and methods of <code>sc</code>. If <code>includeBodies</code> is true, then tags are also
* collected from method bodies.
*
* @param sc
* The class from which to collect the tags.
* @param includeBodies
*/
public void collectTags(SootClass sc, boolean includeBodies) {
// tag the class
collectClassTags(sc);
// tag fields
for (SootField sf : sc.getFields()) {
collectFieldTags(sf);
}
// tag methods
for (SootMethod sm : sc.getMethods()) {
collectMethodTags(sm);
if (includeBodies && sm.hasActiveBody()) {
collectBodyTags(sm.getActiveBody());
}
}
}
public void collectKeyTags(SootClass sc) {
for (Tag next : sc.getTags()) {
if (next instanceof KeyTag) {
KeyTag kt = (KeyTag) next;
Key k = new Key(kt.red(), kt.green(), kt.blue(), kt.key());
k.aType(kt.analysisType());
keys.add(k);
}
}
}
public void printKeys(PrintWriter writerOut) {
for (Key k : keys) {
k.print(writerOut);
}
}
private void addAttribute(Attribute a) {
if (!a.isEmpty()) {
attributes.add(a);
}
}
private void collectHostTags(Host h) {
collectHostTags(h, t -> true);
}
private void collectHostTags(Host h, Predicate<Tag> include) {
List<Tag> tags = h.getTags();
if (!tags.isEmpty()) {
Attribute a = new Attribute();
for (Tag t : tags) {
if (include.test(t)) {
a.addTag(t);
}
}
addAttribute(a);
}
}
public void collectClassTags(SootClass sc) {
// All classes are tagged with their source files which
// is not worth outputing because it can be inferred from
// other information (like the name of the XML file).
collectHostTags(sc, t -> !(t instanceof SourceFileTag));
}
public void collectFieldTags(SootField sf) {
collectHostTags(sf);
}
public void collectMethodTags(SootMethod sm) {
if (sm.hasActiveBody()) {
collectHostTags(sm);
}
}
public synchronized void collectBodyTags(Body b) {<FILL_FUNCTION_BODY>}
public void printTags(PrintWriter writerOut) {
for (Attribute a : attributes) {
// System.out.println("will print attr: "+a);
a.print(writerOut);
}
}
}
|
for (Unit u : b.getUnits()) {
Attribute ua = new Attribute();
JimpleLineNumberTag jlnt = null;
for (Tag t : u.getTags()) {
ua.addTag(t);
if (t instanceof JimpleLineNumberTag) {
jlnt = (JimpleLineNumberTag) t;
}
// System.out.println("adding unit tag: "+t);
}
addAttribute(ua);
for (ValueBox vb : u.getUseAndDefBoxes()) {
// PosColorAttribute attr = new PosColorAttribute();
if (!vb.getTags().isEmpty()) {
Attribute va = new Attribute();
for (Tag t : vb.getTags()) {
// System.out.println("adding vb tag: "+t);
va.addTag(t);
// System.out.println("vb: "+vb.getValue()+" tag: "+t);
if (jlnt != null) {
va.addTag(jlnt);
}
}
// also here add line tags of the unit
addAttribute(va);
// System.out.println("added att: "+va);
}
}
}
| 906
| 318
| 1,224
|
<no_super_class>
|
soot-oss_soot
|
soot/src/main/java/soot/xml/XMLRoot.java
|
XMLRoot
|
addElement
|
class XMLRoot {
public String name = ""; // <NAME attr1="val1" attr2="val2"...>val</NAME>
public String value = ""; // <name attr1="val1" attr2="val2"...>VAL</name>
public String[] attributes = { "" }; // <name ATTR1="val1" ATTR2="val2"...>val</name>
public String[] values = { "" }; // <name attr1="VAL1" attr2="VAL2"...>val</name>
protected XMLNode child = null; // -> to child node
XMLRoot() {
}
@Override
public String toString() {
return XMLPrinter.xmlHeader + XMLPrinter.dtdHeader + this.child.toPostString();
}
// add element to end of tree
public XMLNode addElement(String name) {
return addElement(name, "", "", "");
}
public XMLNode addElement(String name, String value) {
return addElement(name, value, "", "");
}
public XMLNode addElement(String name, String value, String[] attributes) {
return addElement(name, value, attributes, null);
}
public XMLNode addElement(String name, String[] attributes, String[] values) {
return addElement(name, "", attributes, values);
}
public XMLNode addElement(String name, String value, String attribute, String attributeValue) {
return addElement(name, value, new String[] { attribute }, new String[] { attributeValue });
}
public XMLNode addElement(String name, String value, String[] attributes, String[] values) {<FILL_FUNCTION_BODY>}
}
|
XMLNode newnode = new XMLNode(name, value, attributes, values);
newnode.root = this;
if (this.child == null) {
this.child = newnode;
newnode.parent = null; // root's children have NO PARENTS :(
} else {
XMLNode current = this.child;
while (current.next != null) {
current = current.next;
}
current.next = newnode;
newnode.prev = current;
}
return newnode;
| 435
| 139
| 574
|
<no_super_class>
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/abstractmojo/AbstractClearTablesMojo.java
|
AbstractClearTablesMojo
|
execute
|
class AbstractClearTablesMojo extends AbstractSpeedmentMojo {
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject mavenProject;
private @Parameter(defaultValue = "${debug}") Boolean debug;
private @Parameter(defaultValue = "${dbms.host}") String dbmsHost;
private @Parameter(defaultValue = "${dbms.port}") int dbmsPort;
private @Parameter(defaultValue = "${dbms.username}") String dbmsUsername;
private @Parameter(defaultValue = "${dbms.password}") String dbmsPassword;
private @Parameter(defaultValue = "${components}") String[] components;
private @Parameter(defaultValue = "${typeMappers}") Mapping[] typeMappers;
private @Parameter ConfigParam[] parameters;
private @Parameter(defaultValue = "${configFile}") String configFile;
protected AbstractClearTablesMojo() {
}
protected AbstractClearTablesMojo(Consumer<ApplicationBuilder<?, ?>> configurer) {
super(configurer);
}
@Override
protected void execute(Speedment speedment) throws MojoExecutionException, MojoFailureException {<FILL_FUNCTION_BODY>}
@Override
protected MavenProject project() {
return mavenProject;
}
@Override
protected boolean debug() {
return (debug != null) && debug;
}
public String getConfigFile() {
return configFile;
}
@Override
protected String[] components() {
return components;
}
@Override
protected Mapping[] typeMappers() {
return typeMappers;
}
@Override
protected ConfigParam[] parameters() {
return parameters;
}
@Override
protected String dbmsHost() {
return dbmsHost;
}
@Override
protected int dbmsPort() {
return dbmsPort;
}
@Override
protected String dbmsUsername() {
return dbmsUsername;
}
@Override
protected String dbmsPassword() {
return dbmsPassword;
}
}
|
getLog().info("Saving default configuration from database to '" + configLocation().toAbsolutePath() + "'.");
final ConfigFileHelper helper = speedment.getOrThrow(ConfigFileHelper.class);
try {
helper.setCurrentlyOpenFile(configLocation().toFile());
helper.clearTablesAndSaveToFile();
} catch (final Exception ex) {
final String err = "An error occured while reloading.";
getLog().error(err);
throw new MojoExecutionException(err, ex);
}
| 531
| 144
| 675
|
<methods>public final void execute() throws org.apache.maven.plugin.MojoExecutionException, org.apache.maven.plugin.MojoFailureException<variables>private static final java.nio.file.Path DEFAULT_CONFIG,private static final Consumer<ApplicationBuilder<?,?>> NOTHING,static final java.lang.String SPECIFIED_CLASS,private final non-sealed Consumer<ApplicationBuilder<?,?>> configurer,public java.lang.String dbmsConnectionUrl
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/abstractmojo/AbstractGenerateMojo.java
|
AbstractGenerateMojo
|
execute
|
class AbstractGenerateMojo extends AbstractSpeedmentMojo {
private static final Logger LOGGER = LoggerManager.getLogger(AbstractGenerateMojo.class);
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject mavenProject;
private @Parameter(defaultValue = "${debug}") Boolean debug;
private @Parameter(defaultValue = "${dbms.host}") String dbmsHost;
private @Parameter(defaultValue = "${dbms.port}") int dbmsPort;
private @Parameter(defaultValue = "${dbms.username}") String dbmsUsername;
private @Parameter(defaultValue = "${dbms.password}") String dbmsPassword;
private @Parameter(defaultValue = "${components}") String[] components;
private @Parameter(defaultValue = "${typeMappers}") Mapping[] typeMappers;
private @Parameter ConfigParam[] parameters;
private @Parameter(defaultValue = "${configFile}") String configFile;
protected AbstractGenerateMojo() {}
protected AbstractGenerateMojo(Consumer<ApplicationBuilder<?, ?>> configurer) { super(configurer); }
@Override
public void execute(Speedment speedment) throws MojoExecutionException, MojoFailureException {<FILL_FUNCTION_BODY>}
@Override
protected MavenProject project() {
return mavenProject;
}
@Override
protected String[] components() {
return components;
}
@Override
protected Mapping[] typeMappers() {
return typeMappers;
}
@Override
protected ConfigParam[] parameters() {
return parameters;
}
public String getConfigFile() {
return configFile;
}
@Override
protected boolean debug() {
return (debug != null) && debug;
}
@Override
protected String dbmsHost() {
return dbmsHost;
}
@Override
protected int dbmsPort() {
return dbmsPort;
}
@Override
protected String dbmsUsername() {
return dbmsUsername;
}
@Override
protected String dbmsPassword() {
return dbmsPassword;
}
public void setTypeMappers(Mapping[] typeMappers) {
this.typeMappers = typeMappers;
}
}
|
getLog().info("Generating code using JSON configuration file: '" + configLocation().toAbsolutePath() + "'.");
if (hasConfigFile()) {
try {
final Project project = speedment.getOrThrow(ProjectComponent.class).getProject();
speedment.getOrThrow(TranslatorManager.class).accept(project);
// after generating the speedment code, the package location needs to be added as a source folder
if (!mavenProject.getCompileSourceRoots().contains(mavenProject.getBasedir().getAbsolutePath() + "/" + project.getPackageLocation())) {
getLog().info("Adding new source location");
mavenProject.addCompileSourceRoot(mavenProject.getBasedir().getAbsolutePath() + "/" + project.getPackageLocation());
}
} catch (final Exception ex) {
final String err = "Error parsing configFile file.";
LOGGER.error(ex, err);
getLog().error(err);
throw new MojoExecutionException(err, ex);
}
} else {
final String err = "To run speedment:generate a valid configFile needs to be specified.";
getLog().error(err);
throw new MojoExecutionException(err);
}
| 627
| 310
| 937
|
<methods>public final void execute() throws org.apache.maven.plugin.MojoExecutionException, org.apache.maven.plugin.MojoFailureException<variables>private static final java.nio.file.Path DEFAULT_CONFIG,private static final Consumer<ApplicationBuilder<?,?>> NOTHING,static final java.lang.String SPECIFIED_CLASS,private final non-sealed Consumer<ApplicationBuilder<?,?>> configurer,public java.lang.String dbmsConnectionUrl
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/abstractmojo/AbstractToolMojo.java
|
AbstractToolMojo
|
execute
|
class AbstractToolMojo extends AbstractSpeedmentMojo {
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject mavenProject;
private @Parameter(defaultValue = "${debug}") Boolean debug;
private @Parameter(defaultValue = "${dbms.host}") String dbmsHost;
private @Parameter(defaultValue = "${dbms.port}") int dbmsPort;
private @Parameter(defaultValue = "${dbms.username}") String dbmsUsername;
private @Parameter(defaultValue = "${dbms.password}") String dbmsPassword;
private @Parameter(defaultValue = "${components}") String[] components;
private @Parameter(defaultValue = "${typeMappers}") Mapping[] typeMappers;
private @Parameter ConfigParam[] parameters;
private @Parameter(defaultValue = "${configFile}") String configFile;
protected AbstractToolMojo() {}
protected AbstractToolMojo(Consumer<ApplicationBuilder<?, ?>> configurer) { super(configurer);}
@Override
public void execute(Speedment speedment) throws MojoExecutionException, MojoFailureException {<FILL_FUNCTION_BODY>}
@Override
protected void configureBuilder(ApplicationBuilder<?, ?> builder) {
// Add tool specific items, #733
builder.
withBundle(ToolBundle.class);
}
@Override
protected MavenProject project() {
return mavenProject;
}
@Override
protected String[] components() {
return components;
}
@Override
protected Mapping[] typeMappers() {
return typeMappers;
}
@Override
protected ConfigParam[] parameters() {
return parameters;
}
public String getConfigFile() {
return configFile;
}
@Override
protected boolean debug() {
return (debug != null) && debug;
}
@Override
protected String dbmsHost() {
return dbmsHost;
}
@Override
protected int dbmsPort() {
return dbmsPort;
}
@Override
protected String dbmsUsername() {
return dbmsUsername;
}
@Override
protected String dbmsPassword() {
return dbmsPassword;
}
@Override
protected String launchMessage() {
return "Running speedment:tool";
}
}
|
final Injector injector = speedment.getOrThrow(Injector.class);
MainApp.setInjector(injector);
if (hasConfigFile()) {
Application.launch(MainApp.class, configLocation().toAbsolutePath().toString());
} else {
Application.launch(MainApp.class);
}
| 635
| 90
| 725
|
<methods>public final void execute() throws org.apache.maven.plugin.MojoExecutionException, org.apache.maven.plugin.MojoFailureException<variables>private static final java.nio.file.Path DEFAULT_CONFIG,private static final Consumer<ApplicationBuilder<?,?>> NOTHING,static final java.lang.String SPECIFIED_CLASS,private final non-sealed Consumer<ApplicationBuilder<?,?>> configurer,public java.lang.String dbmsConnectionUrl
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/abstractmojo/TypeMapperInstaller.java
|
TypeMapperInstaller
|
installInTypeMapper
|
class TypeMapperInstaller { // This class must be public
private final Mapping[] mappings;
public TypeMapperInstaller(Mapping[] mappings) {
this.mappings = mappings; // Nullable
}
@ExecuteBefore(RESOLVED)
public void installInTypeMapper(
final Injector injector,
final @WithState(INITIALIZED) TypeMapperComponent typeMappers
) throws MojoExecutionException {<FILL_FUNCTION_BODY>}
private TypeMapper<?, ?> tryGetTypeMapper(Constructor<TypeMapper<?, ?>> constructor) {
try {
return constructor.newInstance();
} catch (final IllegalAccessException
| IllegalArgumentException
| InstantiationException
| InvocationTargetException ex) {
throw new TypeMapperInstantiationException(ex);
}
}
private Class<?> databaseTypeFromMapping(Injector injector, Mapping mapping) throws MojoExecutionException {
Class<?> databaseType;
try {
databaseType = injector.classLoader()
.loadClass(mapping.getDatabaseType());
} catch (final ClassNotFoundException ex) {
throw new MojoExecutionException(
"Specified database type '" + mapping.getDatabaseType() + "' "
+ "could not be found on class path. Make sure it is a "
+ "valid JDBC type for the chosen connector.", ex
);
} catch (final ClassCastException ex) {
throw new MojoExecutionException(
"An unexpected ClassCastException occurred.", ex
);
}
return databaseType;
}
private static final class TypeMapperInstantiationException extends RuntimeException {
private static final long serialVersionUID = -8267239306656063289L;
private TypeMapperInstantiationException(Throwable thrw) {
super(thrw);
}
}
}
|
if (mappings != null) {
for (final Mapping mapping : mappings) {
final Class<?> databaseType = databaseTypeFromMapping(injector, mapping);
try {
final Class<?> uncasted = injector.classLoader()
.loadClass(mapping.getImplementation());
@SuppressWarnings("unchecked") final Class<TypeMapper<?, ?>> casted
= (Class<TypeMapper<?, ?>>) uncasted;
final Constructor<TypeMapper<?, ?>> constructor
= casted.getConstructor();
final Supplier<TypeMapper<?, ?>> supplier = () -> tryGetTypeMapper(constructor);
typeMappers.install(databaseType, supplier);
} catch (final ClassNotFoundException ex) {
throw new MojoExecutionException(
AbstractSpeedmentMojo.SPECIFIED_CLASS + "'" + mapping.getImplementation()
+ "' could not be found on class path. Has the "
+ "dependency been configured properly?", ex
);
} catch (final ClassCastException ex) {
throw new MojoExecutionException(
AbstractSpeedmentMojo.SPECIFIED_CLASS + "'" + mapping.getImplementation()
+ "' does not implement the '"
+ TypeMapper.class.getSimpleName() + "'-interface.",
ex
);
} catch (final NoSuchMethodException | TypeMapperInstantiationException ex) {
throw new MojoExecutionException(
AbstractSpeedmentMojo.SPECIFIED_CLASS + "'" + mapping.getImplementation()
+ "' could not be instantiated. Does it have a "
+ "default constructor?", ex
);
}
}
}
| 486
| 428
| 914
|
<no_super_class>
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/component/MavenPathComponent.java
|
MavenPathComponent
|
baseDir
|
class MavenPathComponent implements PathComponent {
public static final String MAVEN_BASE_DIR = "maven.baseDir";
private final String mavenBaseDir;
private final ProjectComponent projectComponent;
public MavenPathComponent(
@Config(name=MAVEN_BASE_DIR, value="") final String mavenBaseDir,
final ProjectComponent projectComponent
) {
this.mavenBaseDir = requireNonNull(mavenBaseDir);
this.projectComponent = requireNonNull(projectComponent);
}
@Override
public Path baseDir() {<FILL_FUNCTION_BODY>}
@Override
public Path packageLocation() {
final Project project = projectComponent.getProject();
return baseDir().resolve(project.getPackageLocation());
}
}
|
if (mavenBaseDir.isEmpty()) {
return Paths.get(System.getProperty("user.home"));
} else {
return Paths.get(mavenBaseDir);
}
| 201
| 51
| 252
|
<no_super_class>
|
speedment_speedment
|
speedment/build-parent/maven-plugin/src/main/java/com/speedment/maven/internal/util/ConfigUtil.java
|
ConfigUtil
|
hasConfigFile
|
class ConfigUtil {
private ConfigUtil() {}
/**
* Returns if the specified file is non-null, exists and is readable. If,
* not, {@code false} is returned and an appropriate message is shown in the
* console.
*
* @param file the config file to check
* @param log the log for outputting messages
* @return {@code true} if available, else {@code false}
*/
public static boolean hasConfigFile(Path file, Log log) {<FILL_FUNCTION_BODY>}
}
|
requireNonNull(log);
if (file == null) {
final String msg = "The expected .json-file is null.";
log.info(msg);
return false;
} else if (!file.toFile().exists()) {
final String msg = "The expected .json-file '"
+ file + "' does not exist.";
log.info(msg);
return false;
} else if (!Files.isReadable(file)) {
final String err = "The expected .json-file '"
+ file + "' is not readable.";
log.error(err);
return false;
} else {
return true;
}
| 138
| 170
| 308
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/constant/SimpleParameterizedType.java
|
SimpleParameterizedType
|
hashCode
|
class SimpleParameterizedType implements ParameterizedType {
/**
* Creates a new {@code SimpleParameterizedType} based on the class name of
* the specified class and the specified parameters.
*
* @param mainType the class to get the name from
* @param parameters list of generic parameters to this type
* @return the created type
*/
public static SimpleParameterizedType create(Type mainType, Type... parameters) {
return create(mainType.getTypeName(), parameters);
}
/**
* Creates a new {@code SimpleParameterizedType} with the specified absolute
* class name.
*
* @param fullName the absolute type name
* @param parameters list of generic parameters to this type
* @return the created simple type
*/
public static SimpleParameterizedType create(String fullName, Type... parameters) {
return new SimpleParameterizedType(fullName, parameters);
}
/**
* Creates a new {@code SimpleParameterizedType} referencing the specified
* class in the specified file. These do not have to exist yet.
*
* @param file the file to reference
* @param clazz the class to reference
* @param parameters list of generic parameters to this type
* @return the new simple type
*/
public static SimpleParameterizedType create(File file, ClassOrInterface<?> clazz, Type... parameters) {
return create(SimpleTypeUtil.nameOf(file, clazz), parameters);
}
@Override
public Type[] getActualTypeArguments() {
return Arrays.copyOf(parameters, parameters.length);
}
@Override
public Type getRawType() {
return SimpleType.create(fullName);
}
@Override
public Type getOwnerType() {
throw new UnsupportedOperationException(
"Owner types are currently not supported by CodeGen."
);
}
@Override
public String getTypeName() {
return fullName;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) { return true; }
else if (obj == null) { return false; }
else if (!(obj instanceof ParameterizedType)) { return false; }
final ParameterizedType other = (ParameterizedType) obj;
return Objects.equals(fullName, other.getTypeName())
&& Arrays.deepEquals(parameters, other.getActualTypeArguments());
}
@Override
public String toString() {
return getTypeName();
}
private SimpleParameterizedType(String fullName, Type[] parameters) {
this.fullName = requireNonNull(fullName);
this.parameters = requireNonNull(parameters);
}
private final String fullName;
private final Type[] parameters;
}
|
int hash = 5;
hash = 29 * hash + Objects.hashCode(this.fullName);
hash = 29 * hash + Arrays.deepHashCode(this.parameters);
return hash;
| 745
| 55
| 800
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/constant/SimpleTypeUtil.java
|
SimpleTypeUtil
|
pathTo
|
class SimpleTypeUtil {
private SimpleTypeUtil() {}
/**
* Creates a full name for the specified class in the specified file,
* suitable to be used as a TypeName.
*
* @param file the file to reference
* @param clazz the class to reference
* @return the full name of the class
*/
public static String nameOf(File file, ClassOrInterface<?> clazz) {
return Formatting.fileToClassName(file.getName())
.flatMap(Formatting::packageName)
.orElseThrow(
() -> new RuntimeException(
"File did not have appropriate name."
)
) + "." + pathTo(file, clazz.getName());
}
private static String pathTo(HasClasses<?> parent, String needle) {
return pathTo(parent, "", needle).orElseThrow(() -> new RuntimeException(
"No class '" + needle + "' found in parent '" + parent + "'."
));
}
private static Optional<String> pathTo(HasClasses<?> parent, String path, String needle) {<FILL_FUNCTION_BODY>}
}
|
for (final ClassOrInterface<?> child : parent.getClasses()) {
final String childName = child.getName();
final String newPath = path.isEmpty() ? "" : path + "." + childName;
if (childName.equals(needle)) {
return Optional.of(newPath);
} else {
final Optional<String> recursion = pathTo(child, newPath, needle);
if (recursion.isPresent()) {
return recursion;
}
}
}
return Optional.empty();
| 299
| 141
| 440
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/controller/AlignTabs.java
|
AlignTabs
|
accept
|
class AlignTabs<T> implements Consumer<T> {
@Override
public void accept(T model) {<FILL_FUNCTION_BODY>}
private static <T> void alignTabs(
final List<T> models,
final Function<T, String> getRow,
final BiConsumer<T, String> setRow
) {
final AtomicInteger maxIndex = new AtomicInteger(-1);
while (true) {
maxIndex.set(-1);
models.forEach(model -> {
final String row = getRow.apply(model);
updateMaxIndex(maxIndex, row);
});
if (maxIndex.get() > -1) {
for (final T model : models) {
final String row = getRow.apply(model);
if (row != null) {
final int index = row.indexOf('\t');
replaceTabWithSpace(setRow, maxIndex, model, row, index);
}
}
} else {
break;
}
}
}
private static <T> void replaceTabWithSpace(BiConsumer<T, String> setRow, AtomicInteger maxIndex, T model, String row, int index) {
if (index > -1) {
setRow.accept(model,
row.replaceFirst("\t", Formatting.repeat(
" ",
maxIndex.get() - index
))
);
}
}
private static void updateMaxIndex(AtomicInteger maxIndex, String row) {
if (row != null) {
final int index = row.indexOf('\t');
if (index > maxIndex.get()) {
maxIndex.set(index);
}
}
}
}
|
if (model instanceof HasCode) {
@SuppressWarnings("unchecked")
final HasCode<?> casted = (HasCode<?>) model;
Formatting.alignTabs(casted.getCode());
}
if (model instanceof HasClasses) {
@SuppressWarnings("unchecked")
final HasClasses<?> casted = (HasClasses<?>) model;
casted.getClasses().forEach(c -> c.call(new AlignTabs<>()));
}
if (model instanceof HasMethods) {
@SuppressWarnings("unchecked")
final HasMethods<?> casted = (HasMethods<?>) model;
casted.getMethods().forEach(c -> c.call(new AlignTabs<>()));
}
if (model instanceof HasConstructors) {
@SuppressWarnings("unchecked")
final HasConstructors<?> casted = (HasConstructors<?>) model;
casted.getConstructors().forEach(c -> c.call(new AlignTabs<>()));
}
if (model instanceof HasInitializers) {
@SuppressWarnings("unchecked")
final HasInitializers<?> casted = (HasInitializers<?>) model;
casted.getInitializers().forEach(c -> c.call(new AlignTabs<>()));
}
if (model instanceof HasFields) {
@SuppressWarnings("unchecked")
final HasFields<?> casted = (HasFields<?>) model;
alignTabs(casted.getFields(), field -> field.getValue()
.filter(ReferenceValue.class::isInstance)
.map(ReferenceValue.class::cast)
.map(ReferenceValue::getValue)
.orElse(null),
(field, value) -> ((ReferenceValue) field.getValue().orElseThrow(NoSuchElementException::new))
.setValue(value)
);
}
if (model instanceof HasJavadoc) {
@SuppressWarnings("unchecked")
final HasJavadoc<?> casted = (HasJavadoc<?>) model;
casted.getJavadoc().ifPresent(javadoc -> {
final List<String> rows = Stream.of(javadoc.getText()
.split(Formatting.nl())
).collect(toList());
Formatting.alignTabs(rows);
javadoc.setText(rows.stream().collect(joining(Formatting.nl())));
});
}
| 448
| 654
| 1,102
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/controller/AutoConstructor.java
|
AutoConstructor
|
accept
|
class AutoConstructor implements Consumer<Class> {
@Override
public void accept(Class aClass) {<FILL_FUNCTION_BODY>}
}
|
aClass.add(Constructor.newPublic()
.call(constr -> aClass.getFields().stream()
.filter(f -> f.getModifiers().contains(FINAL))
.map(Field::copy)
.forEachOrdered(f -> {
f.getModifiers().clear();
f.final_();
constr.add(f).imports(Objects.class, "requireNonNull");
if (isPrimitive(f.getType())) {
constr.add(format("this.%1$s = %1$s;", f.getName()));
} else {
constr.add(format("this.%1$s = requireNonNull(%1$s);", f.getName()));
}
})
)
);
| 41
| 197
| 238
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/controller/AutoEquals.java
|
AutoEquals
|
hasMethod
|
class AutoEquals<T extends HasFields<T> & HasMethods<T> & HasName<T>>
implements Consumer<T> {
protected final HasImports<?> importer;
protected static final String EQUALS = "equals";
protected static final String HASHCODE = "hashCode";
/**
* Instantiates the <code>AutoEquals</code> using something that imports
* can be added to. This can for an example be a {@link File}.
*
* @param importer the importer
*/
public AutoEquals(HasImports<?> importer) {
this.importer = requireNonNull(importer);
}
/**
* Adds an <code>equals()</code> and a <code>hashCode()</code> method to
* the specified model.
* <p>
* If one of the methods already exists, it will not be overwritten.
*
* @param model the model
*/
@Override
public void accept(T model) {
requireNonNull(model);
if (!hasMethod(model, EQUALS, 1)) {
acceptEquals(model);
}
if (!hasMethod(model, HASHCODE, 0)) {
acceptHashcode(model);
}
}
/**
* The <code>equals()</code>-part of the <code>accept</code> method.
*
* @param model the model
*/
protected void acceptEquals(T model) {
requireNonNull(model);
if (importer != null) {
importer.add(Import.of(Objects.class));
importer.add(Import.of(Optional.class));
}
model.add(Method.of(EQUALS, boolean.class)
.set(
Javadoc.of(
"Compares this object with the specified one for equality. " +
"The other object must be of the same type and not null for " +
"the method to return true."
)
.add(PARAM.setValue("other").setText("The object to compare with."))
.add(RETURN.setText("True if the objects are equal."))
).public_()
.add(OVERRIDE)
.add(Field.of("other", Object.class))
.add("return Optional.ofNullable(other)")
.call(m -> {
if (HasSupertype.class.isAssignableFrom(model.getClass())) {
final Optional<Type> supertype = ((HasSupertype<?>) model).getSupertype();
if (supertype.isPresent()) {
m.add(Formatting.tab() + ".filter(o -> super.equals(o))");
}
}
})
.add(Formatting.tab() + ".filter(o -> getClass().equals(o.getClass()))")
.add(Formatting.tab() + ".map(o -> (" + model.getName() + ") o)")
.add(Formatting.tab() + model.getFields().stream().map(this::compare).collect(
Collectors.joining(Formatting.nl() + Formatting.tab())
))
.add(Formatting.tab() + ".isPresent();")
);
}
/**
* The <code>hashCode()</code>-part of the <code>accept</code> method.
*
* @param model the model
*/
protected void acceptHashcode(T model) {
requireNonNull(model);
model.add(Method.of(HASHCODE, int.class)
.set(
Javadoc.of(
"Generates a hashCode for this object. If any field is " +
"changed to another value, the hashCode may be different. " +
"Two objects with the same values are guaranteed to have " +
"the same hashCode. Two objects with the same hashCode are " +
"not guaranteed to have the same hashCode."
)
.add(RETURN.setText("The hash code."))
).public_()
.add(OVERRIDE)
.add("int hash = 7;")
.add(model.getFields().stream()
.map(this::hash)
.collect(Collectors.joining(Formatting.nl()))
)
.add("return hash;")
);
}
/**
* Generates code for comparing the specified field in this and another
* object.
*
* @param f the field
* @return the comparing code
*/
protected String compare(Field f) {
requireNonNull(f);
final StringBuilder str = new StringBuilder(".filter(o -> ");
if (isPrimitive(f.getType())) {
str.append("(this.")
.append(f.getName())
.append(" == o.")
.append(f.getName())
.append(")");
} else {
str.append("Objects.equals(this.")
.append(f.getName())
.append(", o.")
.append(f.getName())
.append(")");
}
return str.append(")").toString();
}
/**
* Generates code for hashing the specified field.
*
* @param f the field
* @return the hashing code
*/
protected String hash(Field f) {
requireNonNull(f);
final String prefix = "hash = 31 * hash + (";
final String suffix = ".hashCode(this." + f.getName() + "));";
switch (f.getType().getTypeName()) {
case "byte":
return prefix + "Byte" + suffix;
case "short":
return prefix + "Short" + suffix;
case "int":
return prefix + "Integer" + suffix;
case "long":
return prefix + "Long" + suffix;
case "float":
return prefix + "Float" + suffix;
case "double":
return prefix + "Double" + suffix;
case "boolean":
return prefix + "Boolean" + suffix;
case "char":
return prefix + "Character" + suffix;
default:
return prefix + "Objects" + suffix;
}
}
/**
* Returns <code>true</code> if the specified type is a primitive type.
*
* @param type the type
* @return <code>true</code> if primitive, else <code>false</code>
*/
protected boolean isPrimitive(Type type) {
requireNonNull(type);
switch (type.getTypeName()) {
case "byte":
case "short":
case "int":
case "long":
case "float":
case "double":
case "boolean":
case "char":
return true;
default:
return false;
}
}
/**
* Returns if a method with the specified signature exists.
*
* @param model the model
* @param method the method name to look for
* @param params the number of parameters in the signature
* @return <code>true</code> if found, else <code>false</code>
*/
protected boolean hasMethod(T model, String method, int params) {<FILL_FUNCTION_BODY>}
}
|
requireNonNull(model);
requireNonNull(method);
requireNonNull(params);
for (Method m : model.getMethods()) {
if (method.equals(m.getName()) && m.getFields().size() == params) {
return true;
}
}
return false;
| 1,905
| 80
| 1,985
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/controller/AutoJavadoc.java
|
AutoJavadoc
|
createJavadoc
|
class AutoJavadoc<T extends HasJavadoc<?>> implements Consumer<T> {
private static final String DEFAULT_TEXT = "Write some documentation here.";
private static final String DEFAULT_NAME = "Your Name";
/**
* Parses the specified model recursively to find all models that implements
* the {@link HasJavadoc} trait but that does not have proper documentation
* and generates javadoc stubs for those models.
*
* @param model the model to parse
*/
@Override
public void accept(T model) {
createJavadoc(requireNonNull(model));
}
/**
* Checks if the specified model already has documentation and if not,
* generates it. This method will recurse through the model tree to make
* sure all children also have documentation.
* <p>
* If documentation exists but is incomplete, it will be completed without
* changing the existing content.
*
* @param <T> the type of the model to operate on
* @param model the model to add documentation to
*/
@SuppressWarnings("unchecked")
private static <T extends HasJavadoc<?>> void createJavadoc(T model) {<FILL_FUNCTION_BODY>}
/**
* Add a javadoc tag to the specified documentation block. If the tag is
* already defined, this will have no effect.
*
* @param doc the documentation block
* @param tag the tag to add
*/
private static void addTag(Javadoc doc, JavadocTag tag) {
if (!hasTagAlready(
requireNonNull(doc),
requireNonNull(tag)
)) {
doc.add(tag);
}
}
/**
* Checks if the specified tag is already defined in the supplied
* documentation block.
*
* @param doc the documentation block
* @param tag the tag to check
* @return {@code true} if it exists, else {@code false}
*/
private static boolean hasTagAlready(Javadoc doc, JavadocTag tag) {
requireNonNull(doc);
requireNonNull(tag);
return doc.getTags().stream().anyMatch(t ->
tag.getName().equals(t.getName())
&& tag.getValue().equals(t.getValue())
);
}
}
|
final Javadoc doc = requireNonNull(model).getJavadoc().orElse(Javadoc.of(DEFAULT_TEXT));
model.set(doc);
if (model instanceof HasGenerics) {
// Add @param for each type variable.
((HasGenerics<?>) model).getGenerics().forEach(g ->
g.getLowerBound().ifPresent(t -> addTag(doc,
PARAM.setValue("<" + t + ">")
))
);
}
if (model instanceof ClassOrInterface) {
// Add @author
doc.add(AUTHOR.setValue(DEFAULT_NAME));
} else {
// Add @param for each parameter.
if (model instanceof HasFields) {
((HasFields<?>) model).getFields().forEach(f ->
addTag(doc, PARAM.setValue(f.getName()))
);
}
}
if ((model instanceof Method) && (((Method) model).getType() != void.class)) {
// Add @return to methods.
addTag(doc, RETURN);
}
if (model instanceof HasConstructors) {
// Generate javadoc for each constructor.
((HasConstructors<?>) model).getConstructors()
.forEach(AutoJavadoc::createJavadoc);
}
if (model instanceof HasMethods) {
// Generate javadoc for each method.
((HasMethods<?>) model).getMethods()
.forEach(AutoJavadoc::createJavadoc);
}
if (model instanceof HasClasses) {
// Generate javadoc for each subclass.
((HasClasses<?>) model).getClasses()
.forEach(AutoJavadoc::createJavadoc);
}
| 610
| 473
| 1,083
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/BridgeTransform.java
|
BridgeTransform
|
transform
|
class BridgeTransform<A, B> implements Transform<A, B> {
private final List<Transform<?, ?>> steps;
private final Class<A> from;
private final Class<B> to;
private final TransformFactory factory;
private Class<?> end;
/**
* Constructs a new transform from one model class to another. The bridge
* requires a factory to create the intermediate steps.
*
* @param from the type to transform from
* @param to the type to transform to
* @param factory a factory with all the required steps installed
*/
private BridgeTransform(Class<A> from, Class<B> to, TransformFactory factory) {
this.from = requireNonNull(from);
this.to = requireNonNull(to);
this.factory = requireNonNull(factory);
this.steps = new ArrayList<>();
this.end = requireNonNull(from);
}
/**
* Creates a shallow copy of a bridge.
*
* @param prototype the prototype
*/
private BridgeTransform(BridgeTransform<A, B> prototype) {
steps = new ArrayList<>(prototype.steps);
from = prototype.from;
to = prototype.to;
end = prototype.end;
factory = prototype.factory;
}
/**
* Transforms the specified model using this transform. A code generator is
* supplied so that the transform can initiate new generation processes to
* resolve dependencies.
*
* @param gen the current code generator
* @param model the model to transform
* @return the transformation result or empty if any of the steps
* returned empty
*/
@Override
public Optional<B> transform(Generator gen, A model) {<FILL_FUNCTION_BODY>}
/**
* Creates a bridge from one model type to another. A factory is supplied so
* that intermediate steps can be resolved.
*
* @param <A> the initial type of a model to transform
* @param <B> the final type of a model after transformation
* @param <T> the type of a transform between A and B
* @param factory a factory with all intermediate steps installed
* @param from the initial class of a model to transform
* @param to the final class of a model after transformation
* @return a <code>Stream</code> of all unique paths between A and B
*/
public static <A, B, T extends Transform<A, B>> Stream<T> create(TransformFactory factory, Class<A> from, Class<B> to) {
return create(factory, new BridgeTransform<>(from, to, factory));
}
/**
* Takes a bridge and completes it if it is not finished. Returns all valid
* paths through the graph as a <code>Stream</code>.
*
* @param <A> the initial type of a model to transform
* @param <B> the final type of a model after transformation
* @param <T> the type of a transform between A and B
* @param factory a factory with all intermediate steps installed
* @param bridge the incomplete bridge to finish
* @return a <code>Stream</code> of all unique paths between A and B
*/
private static <A, B, T extends Transform<A, B>> Stream<T> create(TransformFactory factory, BridgeTransform<A, B> bridge) {
requireNonNull(factory);
requireNonNull(bridge);
if (bridge.end.equals(bridge.to)) {
@SuppressWarnings("unchecked")
final T result = (T) bridge;
return Stream.of(result);
} else {
final List<Stream<T>> bridges = new ArrayList<>();
factory.allFrom(bridge.end).stream().forEachOrdered(e -> {
final BridgeTransform<A, B> br = new BridgeTransform<>(bridge);
@SuppressWarnings("unchecked")
Class<Object> a = (Class<Object>) bridge.end;
@SuppressWarnings("unchecked")
Class<Object> b = (Class<Object>) e.getKey();
@SuppressWarnings("unchecked")
Transform<Object, Object> transform = (Transform<Object, Object>) e.getValue();
if (br.addStep(a, b, transform)) {
bridges.add(create(factory, br));
}
});
return bridges.stream().flatMap(i -> i);
}
}
/**
* Returns true if this transform is or contains the specified
* transformer. This is used internally by the code generator to avoid
* circular paths.
*
* @param transformer the type of the transformer to check
* @return true if this transform is or contains the input
*/
@Override
public boolean is(Class<? extends Transform<?, ?>> transformer) {
return steps.stream().anyMatch(t -> t.is(requireNonNull(transformer)));
}
/**
* Attempts to add a new step to the bridge. If the step is already part of
* the bridge, it will not be added. Returns true if the step was added.
*
* @param <A2> the initial type of the step
* @param <B2> the output type of the step
* @param from the initial type of the step
* @param to the output type of the step
* @param step the step to attempt to add
* @return true if the step was added
*/
private <A2, B2> boolean addStep(Class<A2> from, Class<B2> to, Transform<A2, B2> step) {
requireNonNull(from);
requireNonNull(to);
requireNonNull(step);
if (end == null || from.equals(end)) {
if (steps.contains(step)) {
return false;
} else {
steps.add(step);
end = to;
return true;
}
} else {
throw new IllegalArgumentException("Transform " + step + " has a different entry class (" + from + ") than the last class in the current build (" + end + ").");
}
}
}
|
requireNonNull(gen);
requireNonNull(model);
Object o = model;
for (final Transform<?, ?> step : steps) {
if (o == null) {
return Optional.empty();
} else {
@SuppressWarnings("unchecked")
final Transform<Object, ?> step2 = (Transform<Object, ?>) step;
o = gen.transform(step2, o, factory)
.map(Meta::getResult)
.orElse(null);
}
}
if (o == null) {
return Optional.empty();
} else {
if (to.isAssignableFrom(o.getClass())) {
@SuppressWarnings("unchecked")
final B result = (B) o;
return Optional.of(result);
} else {
throw new IllegalStateException(
"The bridge between '" +
from.getSimpleName() +
"' to '" +
to.getSimpleName() +
"' is not complete."
);
}
}
| 1,598
| 278
| 1,876
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/DefaultRenderStack.java
|
DefaultRenderStack
|
all
|
class DefaultRenderStack implements RenderStack {
private final Deque<Object> stack;
/**
* Constructs the stack.
*/
public DefaultRenderStack() {
stack = new ArrayDeque<>();
}
/**
* Constructs the stack using an existing stack as a prototype. This creates
* a shallow copy of that stack.
*
* @param prototype the prototype
*/
public DefaultRenderStack(DefaultRenderStack prototype) {
stack = new ArrayDeque<>(requireNonNull(prototype).stack);
}
/**
* Put the specified object on the stack.
*
* @param obj the object to push
*/
public void push(Object obj) {
stack.push(requireNonNull(obj));
}
/**
* Returns the latest element from the stack, removes it.
*
* @return the latest added element
*/
public Object pop() {
return stack.pop();
}
@Override
public <T> Stream<T> fromBottom(Class<T> type) {
return all(requireNonNull(type), stack.descendingIterator());
}
@Override
public <T> Stream<T> fromTop(Class<T> type) {
return all(requireNonNull(type), stack.iterator());
}
@Override
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* Creates a <code>Stream</code> over all the elements of the stack using an
* <code>Iterator</code>. Only elements of the specified type is included.
*
* @param <T> the type to look for
* @param type the type to look for
* @param i the iterator
* @return a stream of all the models in the stack of that type
*/
@SuppressWarnings("unchecked")
private static <T> Stream<T> all(Class<T> type, Iterator<Object> i) {
requireNonNull(type);
requireNonNull(i);
return all(i).filter(o -> type.isAssignableFrom(o.getClass()))
.map(o -> (T) o);
}
/**
* Creates a <code>Stream</code> over all the elements of the stack using an
* <code>Iterator</code>.
*
* @param i the iterator
* @return a stream of all the models in the stack
*/
private static Stream<?> all(Iterator<Object> i) {<FILL_FUNCTION_BODY>}
}
|
requireNonNull(i);
final Iterable<Object> it = () -> i;
return StreamSupport.stream(it.spliterator(), false);
| 679
| 41
| 720
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/GeneratorImpl.java
|
GeneratorImpl
|
transform
|
class GeneratorImpl implements Generator {
private final DependencyManager mgr;
private final TransformFactory factory;
private final DefaultRenderStack renderStack;
private final LinkedList<RenderTree.Builder> renderTreeBuilder;
/**
* Creates a new generator.
*
* @param mgr the dependency manager to use
* @param factory the factory to use
*/
public GeneratorImpl(DependencyManager mgr, TransformFactory factory) {
this.factory = requireNonNull(factory);
this.mgr = requireNonNull(mgr);
this.renderStack = new DefaultRenderStack();
this.renderTreeBuilder = new LinkedList<>();
// Add initial builder.
this.renderTreeBuilder.add(RenderTree.builder());
}
@Override
public DependencyManager getDependencyMgr() {
return mgr;
}
@Override
public RenderStack getRenderStack() {
return renderStack;
}
@Override
@SuppressWarnings("unchecked")
public <A, B> Stream<Meta<A, B>> metaOn(A from, Class<B> to) {
requireNonNulls(from, to);
if (from instanceof Optional) {
throw new UnsupportedOperationException(
"Model must not be an Optional!"
);
}
return BridgeTransform.create(factory, from.getClass(), to)
.map(t -> (Transform<A, B>) t)
.map(t -> transform(t, from, factory))
.filter(Optional::isPresent)
.map(Optional::get)
;
}
@Override
public <A, B> Optional<Meta<A, B>> transform(Transform<A, B> transform, A model, TransformFactory factory) {<FILL_FUNCTION_BODY>}
}
|
requireNonNulls(transform, model, factory);
final RenderTree.Builder parent = renderTreeBuilder.peek();
final RenderTree.Builder branch = RenderTree.builder();
renderTreeBuilder.push(branch);
renderStack.push(model);
final Optional<Meta<A, B>> meta = transform
.transform(this, model)
.map(s -> Meta.builder(model, s)
.withTransform(transform)
.withFactory(factory)
.withRenderTree(branch.build())
.withRenderStack(new DefaultRenderStack(renderStack))
.build()
);
meta.ifPresent(parent::withBranch);
renderStack.pop();
renderTreeBuilder.pop();
return meta;
| 467
| 202
| 669
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/MetaImpl.java
|
MetaImpl
|
toString
|
class MetaImpl<A, B> implements Meta<A, B> {
private final A model;
private final B result;
private final Transform<A, B> transform;
private final TransformFactory factory;
private final RenderStack stack;
private final RenderTree tree;
private MetaImpl(
A model,
B result,
Transform<A, B> transform,
TransformFactory factory,
RenderStack stack,
RenderTree tree) {
this.model = requireNonNull(model);
this.result = requireNonNull(result);
this.transform = requireNonNull(transform);
this.factory = requireNonNull(factory);
this.stack = requireNonNull(stack);
this.tree = requireNonNull(tree);
}
@Override
public B getResult() {
return result;
}
@Override
public Transform<A, B> getTransform() {
return transform;
}
@Override
public TransformFactory getFactory() {
return factory;
}
@Override
public A getModel() {
return model;
}
@Override
public RenderStack getRenderStack() {
return stack;
}
@Override
public RenderTree getRenderTree() {
return tree;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public static final class MetaBuilder<A, B> implements Meta.Builder<A, B> {
private A model;
private B result;
private Transform<A, B> transform;
private TransformFactory factory;
private RenderStack stack;
private RenderTree tree;
public MetaBuilder(A model, B result) {
this.model = requireNonNull(model);
this.result = requireNonNull(result);
}
@Override
public Meta.Builder<A, B> withResult(B result) {
this.result = requireNonNull(result);
return this;
}
@Override
public Meta.Builder<A, B> withTransform(Transform<A, B> transform) {
this.transform = requireNonNull(transform);
return this;
}
@Override
public Meta.Builder<A, B> withFactory(TransformFactory factory) {
this.factory = requireNonNull(factory);
return this;
}
@Override
public Meta.Builder<A, B> withModel(A model) {
this.model = requireNonNull(model);
return this;
}
@Override
public Meta.Builder<A, B> withRenderStack(RenderStack stack) {
this.stack = requireNonNull(stack);
return this;
}
@Override
public Meta.Builder<A, B> withRenderTree(RenderTree tree) {
this.tree = requireNonNull(tree);
return this;
}
@Override
public Meta<A, B> build() {
return new MetaImpl<>(
model,
result,
transform,
factory,
stack,
tree
);
}
}
}
|
return "MetaImpl{" + "model=" + model + ", result=" + result + ", transform=" + transform + ", factory=" + factory + ", stack=" + stack + ", tree=" + tree + '}';
| 840
| 56
| 896
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/TransformFactoryImpl.java
|
TransformFactoryImpl
|
install
|
class TransformFactoryImpl implements TransformFactory {
private final Map<Class<?>, Set<Map.Entry<Class<?>, Supplier<? extends Transform<?, ?>>>>> transforms;
private final String name;
/**
* Instantiates the factory.
*
* @param name the unique name to use
*/
public TransformFactoryImpl(String name) {
this.name = requireNonNull(name);
this.transforms = new ConcurrentHashMap<>();
}
@Override
public String getName() {
return name;
}
@Override
public <A, B, T extends Transform<A, B>> TransformFactory install(Class<A> from, Class<B> to, Supplier<T> transform) {<FILL_FUNCTION_BODY>}
@Override
@SuppressWarnings("unchecked")
public <A, T extends Transform<A, ?>> Set<Map.Entry<Class<?>, T>> allFrom(Class<A> model) {
requireNonNull(model);
return transforms.entrySet().stream()
.filter(e -> e.getKey().isAssignableFrom(model))
.flatMap(e -> e.getValue().stream())
.map(e -> toEntry(e.getKey(), (T) e.getValue().get()))
.collect(toSet());
}
private static <A, T extends Transform<A, ?>> Map.Entry<Class<?>, T> toEntry(Class<?> key, T value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
}
|
requireNonNulls(from, to, transform);
transforms.computeIfAbsent(from, f -> new HashSet<>())
.add(new AbstractMap.SimpleEntry<>(to, transform));
return this;
| 414
| 60
| 474
|
<no_super_class>
|
speedment_speedment
|
speedment/common-parent/codegen/src/main/java/com/speedment/common/codegen/internal/java/JavaGenerator.java
|
JavaGenerator
|
compileAll
|
class JavaGenerator implements Generator {
private static final Pattern[] IGNORED = compileAll(
"^void$",
"^byte$",
"^short$",
"^char$",
"^int$",
"^long$",
"^boolean$",
"^float$",
"^double$",
"^java\\.lang\\.[^\\.]+$"
);
private final Generator inner;
/**
* Instantiates the JavaGenerator.
*/
public JavaGenerator() {
this(new JavaTransformFactory());
}
/**
* Instantiates the JavaGenerator using an array of custom
* {@link TransformFactory}.
* <p>
* Warning! If you use this constructor, no transforms will be installed
* by default!
*
* @param factory the transform factory to use
*/
public JavaGenerator(TransformFactory factory) {
inner = Generator.create(DependencyManager.create(IGNORED), factory);
}
@Override
public DependencyManager getDependencyMgr() {
return inner.getDependencyMgr();
}
@Override
public RenderStack getRenderStack() {
return inner.getRenderStack();
}
@Override
public <A, B> Stream<Meta<A, B>> metaOn(A from, Class<B> to) {
return inner.metaOn(from, to);
}
@Override
public <A, B> Stream<Meta<A, B>> metaOn(A from, Class<B> to, Class<? extends Transform<A, B>> transform) {
return inner.metaOn(from, to, transform);
}
@Override
public <M> Stream<Meta<M, String>> metaOn(M model) {
return inner.metaOn(model);
}
@Override
public <A> Stream<Meta<A, String>> metaOn(Collection<A> models) {
return inner.metaOn(models);
}
@Override
public <A, B> Stream<Meta<A, B>> metaOn(Collection<A> models, Class<B> to) {
return inner.metaOn(models, to);
}
@Override
public <A, B> Stream<Meta<A, B>> metaOn(Collection<A> models, Class<B> to, Class<? extends Transform<A, B>> transform) {
return inner.metaOn(models, to, transform);
}
@Override
public Optional<String> on(Object model) {
return inner.on(model);
}
@Override
public <M> Stream<String> onEach(Collection<M> models) {
return inner.onEach(models);
}
@Override
public <A, B> Optional<Meta<A, B>> transform(Transform<A, B> transform, A model, TransformFactory factory) {
return inner.transform(transform, model, factory);
}
public static Generator create(DependencyManager mgr, TransformFactory factory) {
return Generator.create(mgr, factory);
}
private static Pattern[] compileAll(String... regexp) {<FILL_FUNCTION_BODY>}
}
|
final Set<Pattern> patterns = Stream.of(regexp)
.map(Pattern::compile)
.collect(Collectors.toSet());
return patterns.toArray(new Pattern[patterns.size()]);
| 824
| 58
| 882
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.