Java源码示例:spoon.reflect.code.CtIf
示例1
private boolean isElseIf(CtStatement original, CtStatement parentLine) {
if (parentLine.getParent() instanceof CtIf) {
CtStatement elseStatement = ((CtIf) parentLine.getParent()).getElseStatement();
if (elseStatement == original) {
return true;
} else if (elseStatement instanceof CtBlock) {
CtBlock block = (CtBlock) elseStatement;
if (block.isImplicit() && block.getStatement(0) == original) {
return true;
}
}
}
if (parentLine.getParent() instanceof CtBlock) {
return isElseIf(original, (CtStatement) parentLine.getParent());
}
return false;
}
示例2
@Override
public CtIf processCondition(CtStatement element, String newCondition) {
//logger.debug("##### {} ##### Before:\n{}", element, element.getParent());
// if the element is not a line
if (!new LineFilter().matches(element)) {
element = element.getParent(new LineFilter());
}
CtElement parent = element.getParent();
CtIf newIf = element.getFactory().Core().createIf();
CtCodeSnippetExpression<Boolean> condition = element.getFactory().Core().createCodeSnippetExpression();
condition.setValue(newCondition);
newIf.setCondition(condition);
// Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
newIf.setParent(parent);
element.replace(newIf);
// this should be after the replace to avoid an StackOverflowException caused by the circular reference.
newIf.setThenStatement(element);
//logger.debug("##### {} ##### After:\n{}", element, element.getParent().getParent());
return newIf;
}
示例3
public void process(Bound annotation, CtParameter<?> element) {
final CtMethod parent = element.getParent(CtMethod.class);
// Build if check for min.
CtIf anIf = getFactory().Core().createIf();
anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min()));
CtThrow throwStmt = getFactory().Core().createThrow();
throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")"));
anIf.setThenStatement(throwStmt);
parent.getBody().insertBegin(anIf);
anIf.setParent(parent);
// Build if check for max.
anIf = getFactory().Core().createIf();
anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max()));
anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")"));
parent.getBody().insertBegin(anIf);
anIf.setParent(parent);
}
示例4
@Test
public void testBoundTemplate() throws Exception {
SpoonAPI launcher = new Launcher();
launcher.getEnvironment().setNoClasspath(true);
launcher.addInputResource("./src/main/java");
launcher.setSourceOutputDirectory("./target/spoon-template");
launcher.addProcessor(new BoundTemplateProcessor());
launcher.run();
final CtType<Main> target = launcher.getFactory().Type().get(Main.class);
final CtMethod<?> m = target.getMethodsByName("m").get(0);
assertTrue(m.getBody().getStatements().size() >= 2);
assertTrue(m.getBody().getStatement(0) instanceof CtIf);
assertTrue(m.getBody().getStatement(1) instanceof CtIf);
}
示例5
@Test
public void testBoundProcessor() throws Exception {
SpoonAPI launcher = new Launcher();
launcher.getEnvironment().setNoClasspath(true);
launcher.addInputResource("./src/main/java");
launcher.setSourceOutputDirectory("./target/spoon-processor");
launcher.addProcessor(new BoundProcessor());
launcher.run();
final CtType<Main> target = launcher.getFactory().Type().get(Main.class);
final CtMethod<?> m = target.getMethodsByName("m").get(0);
assertTrue(m.getBody().getStatements().size() >= 2);
assertTrue(m.getBody().getStatement(0) instanceof CtIf);
assertTrue(m.getBody().getStatement(1) instanceof CtIf);
}
示例6
public static boolean whethereffectiveguard(CtIf ifstatement, CtStatement targetstatement) {
CtBlock thenBlock = ifstatement.getThenStatement();
CtBlock elseBlock = ifstatement.getElseStatement();
if (thenBlock != null) {
List<CtStatement> thenstatements = thenBlock.getStatements();
if (thenstatements.size() > 0 && thenstatements.get(0) == targetstatement)
return true;
}
if (elseBlock != null) {
List<CtStatement> elsestatements = elseBlock.getStatements();
if (elsestatements.size() > 0 && elsestatements.get(0) == targetstatement)
return true;
}
return false;
}
示例7
public CtElement retrieveElementToStudy(CtElement element) {
if (element instanceof CtIf) {
return (((CtIf) element).getCondition());
} else if (element instanceof CtWhile) {
return (((CtWhile) element).getLoopingExpression());
} else if (element instanceof CtFor) {
return (((CtFor) element).getExpression());
} else if (element instanceof CtDo) {
return (((CtDo) element).getLoopingExpression());
} else if (element instanceof CtForEach) {
return (((CtForEach) element).getExpression());
} else if (element instanceof CtSwitch) {
return (((CtSwitch) element).getSelector());
} else
return (element);
}
示例8
private CtElement retrieveElementToStudy(CtElement element) {
if (element instanceof CtIf) {
return (((CtIf) element).getCondition());
} else if (element instanceof CtWhile) {
return (((CtWhile) element).getLoopingExpression());
} else if (element instanceof CtFor) {
return (((CtFor) element).getExpression());
} else if (element instanceof CtDo) {
return (((CtDo) element).getLoopingExpression());
} else if (element instanceof CtForEach) {
return (((CtForEach) element).getExpression());
} else if (element instanceof CtSwitch) {
return (((CtSwitch) element).getSelector());
} else
return (element);
}
示例9
public static List<CtVariableAccess> collectVariableReadIgnoringBlocks(CtElement element) {
if (element instanceof CtIf) {
return collectVariableRead(((CtIf) element).getCondition());
}
if (element instanceof CtWhile) {
return collectVariableRead(((CtWhile) element).getLoopingExpression());
}
if (element instanceof CtFor) {
return collectVariableRead(((CtFor) element).getExpression());
}
return collectVariableRead(element);
}
示例10
public static List<CtVariableAccess> collectVariableAccessIgnoringBlocks(CtElement element) {
if (element instanceof CtIf) {
return collectVariableAccess(((CtIf) element).getCondition());
}
if (element instanceof CtWhile) {
return collectVariableAccess(((CtWhile) element).getLoopingExpression());
}
if (element instanceof CtFor) {
return collectVariableAccess(((CtFor) element).getExpression());
}
return collectVariableAccess(element);
}
示例11
private void genTightCondition(CtIf n) {
CtExpression<Boolean> oldCondition = n.getCondition();
CtLiteral<Boolean> placeholder = factory.createLiteral();
placeholder.setValue(true); // consider the placeholder, should this be more concrete?
CtUnaryOperator<Boolean> tmpCondition = factory.createUnaryOperator();
tmpCondition.setKind(UnaryOperatorKind.NOT);
tmpCondition.setOperand(placeholder);
CtBinaryOperator<Boolean> newCondition = factory.createBinaryOperator();
newCondition.setKind(BinaryOperatorKind.AND);
newCondition.setLeftHandOperand(oldCondition);
newCondition.setRightHandOperand(placeholder);
CtIf S = n.clone();
S.setParent(n.getParent());
S.setCondition(newCondition);
Repair repair = new Repair();
repair.kind = RepairKind.TightenConditionKind;
repair.isReplace = true;
repair.srcElem = n;
repair.dstElem = S;
repair.atoms.addAll(repairAnalyzer.getCondCandidateVars(n));
repairs.add(repair);
// we do not consider the case of short-circuit evaluation at all
}
示例12
private void genLooseCondition(CtIf n) {
CtExpression<Boolean> oldCondition = n.getCondition();
CtLiteral<Boolean> placeholder = factory.createLiteral();
placeholder.setValue(true); // consider the placeholder, should this be more concrete?
CtBinaryOperator<Boolean> newCondition = factory.createBinaryOperator();
newCondition.setKind(BinaryOperatorKind.OR);
newCondition.setLeftHandOperand(oldCondition);
newCondition.setRightHandOperand(placeholder);
CtIf S = n.clone();
S.setParent(n.getParent());
S.setCondition(newCondition);
Repair repair = new Repair();
repair.kind = RepairKind.LoosenConditionKind;
repair.isReplace = true;
repair.srcElem = n;
repair.dstElem = S;
repair.atoms.addAll(repairAnalyzer.getCondCandidateVars(n));
repairs.add(repair);
// we do not consider the case of short-circuit evaluation at all
}
示例13
private void genAddIfGuard(CtStatement n) {
CtLiteral<Boolean> placeholder = factory.createLiteral();
placeholder.setValue(true); // consider the placeholder, should this be more concrete?
CtUnaryOperator<Boolean> guardCondition = factory.createUnaryOperator();
guardCondition.setKind(UnaryOperatorKind.NOT);
guardCondition.setOperand(placeholder);
CtIf guardIf = factory.createIf();
guardIf.setParent(n.getParent());
guardIf.setCondition(guardCondition);
guardIf.setThenStatement(n.clone());
Repair repair = new Repair();
repair.kind = RepairKind.GuardKind;
repair.isReplace = true;
repair.srcElem = n;
repair.dstElem = guardIf;
repair.atoms.addAll(repairAnalyzer.getCondCandidateVars(n));
repairs.add(repair);
// we do not consider the case of if statement as special at all
}
示例14
private Set<CtElement> fuzzyLocator(CtElement statement) {
Set<CtElement> locations = new HashSet<>();
if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
locations.add(statement);
} else {
// "int a;" is not CtStatement?
CtElement parent = statement.getParent();
if (parent != null) {
List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
if (parent instanceof CtStatement) {
statements = statements.subList(1, statements.size());
}
int idx = statements.indexOf(statement);
if (idx >= 0) {
if (idx > 0)
locations.add(statements.get(idx - 1));
locations.add(statements.get(idx));
if (idx < statements.size() - 1)
locations.add(statements.get(idx + 1));
}
}
}
return locations;
}
示例15
@Override
public boolean applyModification() {
CtStatement original = (CtStatement) MetaGenerator.geOriginalElement(statementToWrap);
this.setParentBlock(original.getParent(CtBlock.class));
//
CtIf ifNew = MutationSupporter.getFactory().createIf();
ifNew.setParent(original.getParent());
CtStatement originalCloned = original.clone();
MutationSupporter.clearPosition(originalCloned);
ifNew.setThenStatement(originalCloned);
// as difference with the meta, here we put the ingredient evaluated in the
// meta.
ifNew.setCondition((CtExpression<Boolean>) ifcondition);
//
super.setOriginal(original);
super.setModified(ifNew);
//
return super.applyModification();
}
示例16
@SuppressWarnings({ "static-access", "rawtypes", "unchecked" })
public void visitCtIf(CtIf ifElement) {
super.visitCtIf(ifElement);
CtExpression cond = ifElement.getCondition();
CtLiteral<Boolean> literalvalue = this.mutSupporter.getFactory().Core().createLiteral();
Boolean bval=false;
literalvalue.setValue(bval);
CtBinaryOperator<?> newcond = this.mutSupporter.getFactory().Core().createBinaryOperator();
newcond.setKind(BinaryOperatorKind.AND);
newcond.setRightHandOperand(literalvalue);
newcond.setLeftHandOperand(cond);
ifElement.setCondition((CtExpression<Boolean>) newcond);
saveSketchAndSynthesize();
ifElement.setCondition(cond);
resoreDiskFile();
}
示例17
public static List<CtVariableAccess> collectVariableReadIgnoringBlocks(CtElement element) {
if (element instanceof CtIf) {
return collectVariableRead(((CtIf) element).getCondition());
}
if (element instanceof CtWhile) {
return collectVariableRead(((CtWhile) element).getLoopingExpression());
}
if (element instanceof CtFor) {
return collectVariableRead(((CtFor) element).getExpression());
}
return collectVariableRead(element);
}
示例18
public static List<CtVariableAccess> collectVariableAccessIgnoringBlocks(CtElement element) {
if (element instanceof CtIf) {
return collectVariableAccess(((CtIf) element).getCondition());
}
if (element instanceof CtWhile) {
return collectVariableAccess(((CtWhile) element).getLoopingExpression());
}
if (element instanceof CtFor) {
return collectVariableAccess(((CtFor) element).getExpression());
}
return collectVariableAccess(element);
}
示例19
@Override
public void process(CtStatement element) {
if (element instanceof CtIf) {
add(((CtIf) element).getCondition());
} else if (element instanceof CtFor) {
add(((CtFor) element).getExpression());
} else if (element instanceof CtWhile) {
add(((CtWhile) element).getLoopingExpression());
} else if (element instanceof CtDo) {
add(((CtDo) element).getLoopingExpression());
} else if (element instanceof CtThrow) {
add(((CtThrow) element).getThrownExpression());
} else if (element instanceof CtInvocation && (element.getParent() instanceof CtBlock)) {
add(element);
} else if (element instanceof CtAssignment || element instanceof CtConstructorCall
|| element instanceof CtCFlowBreak || element instanceof CtLocalVariable) {
add(element);
}
}
示例20
@Test
public void test_t_222894() throws Exception {
AstComparator diff = new AstComparator();
// meld src/test/resources/examples/t_222894/left_Client_1.150.java
// src/test/resources/examples/t_222894/right_Client_1.151.java
File fl = new File("src/test/resources/examples/t_222894/left_Client_1.150.java");
File fr = new File("src/test/resources/examples/t_222894/right_Client_1.151.java");
Diff result = diff.compare(fl, fr);
CtElement ancestor = result.commonAncestor();
assertTrue(ancestor instanceof CtIf);
result.getRootOperations();
result.debugInformation();
assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "AND"));
// TODO there is a move that is not detected but should be
// assertTrue(result.containsOperation(OperationKind.Move, VariableRead",
// "Settings.keepServerlog"));
// this is the case if gumtree.match.gt.minh" = "0" (but bad for other tests)
}
示例21
private void SetElseStatementWithReturn(CtIf ifStatement){
//search the first parent method
CtMethod parentMethod = ifStatement.getParent(CtMethod.class);
//we go out of while with null of a CtMethod. If null, return without method in parents...?
if(parentMethod == null){
return;
}
//create returned expression from template.
CtLiteral returnedExpression = null;
Class classOfReturn = parentMethod.getType().getActualClass();
if(PrimitiveTemplateExpressions.containsKey(classOfReturn)){
CtLiteral templateExpression = PrimitiveTemplateExpressions.get(classOfReturn);
returnedExpression = getFactory().Core().clone(templateExpression);
}else{
returnedExpression = new CtLiteralImpl().setValue(null);
}
CtReturn theReturn = getFactory().Core().createReturn();
theReturn.setReturnedExpression(returnedExpression);
CtBlock elseBlock = ifStatement.getElseStatement();
if(elseBlock == null){
elseBlock = getFactory().Core().createBlock();
}
elseBlock.addStatement(theReturn);
ifStatement.setElseStatement(elseBlock);
}
示例22
@Override
public Map<SourceLocation, List<TestResult>> getTestListPerStatement() {
SpoonedProject spooner = new SpoonedProject(nopolContext.getProjectSources(), nopolContext);
final List<SourcePosition> l = new ArrayList<>();
spooner.process(new AbstractProcessor<CtIf>(){
@Override
public void process(CtIf ctIf) {
l.add(ctIf.getCondition().getPosition());
}
});
Map<SourceLocation, List<TestResult>> countPerSourceLocation = new HashMap<>();
List<TestResult> res = new ArrayList<>();
for (String testClass : nopolContext.getProjectTests()) {
try {
URLClassLoader urlClassLoader = new URLClassLoader(nopolContext.getProjectClasspath(), this.getClass().getClassLoader());
Class klass = urlClassLoader.loadClass(testClass);
// does not work, see https://stackoverflow.com/a/29865611
//for (FrameworkMethod desc : new BlockJUnit4ClassRunner(klass).getChildren()) {
// so we get the methods ourselves
// only support basic Junit4
for (String m : getTestMethods(klass)) {
res.add(new TestResultImpl(TestCase.from(m), false));
}
} catch (Exception e) {
System.out.println(testClass);
}
}
for(SourcePosition pos : l) {
SourceLocation loc = new SourceLocation(pos.getCompilationUnit().getMainType().getQualifiedName(), pos.getLine());
countPerSourceLocation.put(loc, Collections.unmodifiableList(res));
}
return countPerSourceLocation;
}
示例23
private static <T> CtIf collectionWrappingIf(List<CtStatement> collectingStatements, RuntimeValues<T> runtimeValues, CtStatement insertionPoint) {
Factory factory = insertionPoint.getFactory();
CtStatement newBlock = newBlock(factory, collectingStatements);
CtExpression<Boolean> isEnabled = newExpressionFromSnippet(factory, runtimeValues.isEnabledInquiry(), Boolean.class);
CtIf newIf = newIf(factory, isEnabled, newBlock);
insertBeforeUnderSameParent(newIf, insertionPoint);
return newIf;
}
示例24
private CtElement getTarget() {
CtType type = factory.Type().get(patch.getSourceLocation().getRootClassName());
EarlyTerminatingScanner<CtElement> targetFinder = new EarlyTerminatingScanner<CtElement>() {
@Override
protected void enter(CtElement e) {
if (e.getPosition() instanceof NoSourcePosition) {
return;
}
if (e.getPosition().getSourceStart() == patch.getSourceLocation().getBeginSource()
&& e.getPosition().getSourceEnd() == patch.getSourceLocation().getEndSource() && e.isImplicit() == false) {
if (patch.getType() == RepairType.CONDITIONAL && e instanceof CtIf) {
setResult(((CtIf) e).getCondition());
} else {
setResult(e);
}
terminate();
return;
}
if (e.getPosition().getSourceStart() <= patch.getSourceLocation().getBeginSource()
&& e.getPosition().getSourceEnd() >= patch.getSourceLocation().getEndSource()) {
super.enter(e);
}
}
};
type.accept(targetFinder);
return targetFinder.getResult();
}
示例25
public static CtExpression<Boolean> getCondition(CtElement element) {
CtExpression<Boolean> condition;
if (element instanceof CtIf) {
condition = ((CtIf) element).getCondition();
} else if (element instanceof CtConditional) {
condition = ((CtConditional<?>) element).getCondition();
} else {
throw new IllegalStateException("Unknown conditional class: " + element.getClass());
}
return condition;
}
示例26
@Override
public CtIf processCondition(CtStatement element, String newCondition) {
CtCodeSnippetExpression<Boolean> snippet = element.getFactory().Core().createCodeSnippetExpression();
snippet.setValue(newCondition);
CtExpression<Boolean> condition = getCondition(element);
condition.replace(snippet);
return (CtIf) element;
}
示例27
public void appendValueCollection(CtStatement element, String outputName) {
CollectableValueFinder finder;
if (CtIf.class.isInstance(element)) {
finder = CollectableValueFinder.valueFinderFromIf((CtIf) element);
} else {
finder = CollectableValueFinder.valueFinderFrom(element);
}
Collection<String> collectables = finder.reachableVariables();
Multimap<String, String> getters = finder.accessibleGetters();
collectables.remove(outputName);
RuntimeValuesInstrumenter.runtimeCollectionBefore(element,
MetaMap.autoMap(collectables), getters, outputName,
runtimeValues());
}
示例28
public void process(CtStatement element) {
logger.debug("##### {} ##### Before:\n{}", element, element.getParent());
CtElement parent = element.getParent();
CtIf newIf = element.getFactory().Core().createIf();
CtCodeSnippetExpression<Boolean> condition;
if (getValue() != null) {
switch (getValue()) {
case "1":
condition = element.getFactory().Code()
.createCodeSnippetExpression("true");
break;
case "0":
condition = element.getFactory().Code()
.createCodeSnippetExpression("false");
break;
default:
condition = element.getFactory().Code()
.createCodeSnippetExpression(getValue());
}
} else {
condition = element
.getFactory()
.Code()
.createCodeSnippetExpression(
Debug.class.getCanonicalName()
+ ".makeSymbolicBoolean(\"guess_fix\")");
}
newIf.setCondition(condition);
// Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
newIf.setParent(parent);
element.replace(newIf);
// this should be after the replace to avoid an StackOverflowException caused by the circular reference.
newIf.setThenStatement(element);
// Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
newIf.getThenStatement().setParent(newIf);
logger.debug("##### {} ##### After:\n{}", element, element.getParent().getParent());
}
示例29
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void collectSubexpressionValues() {
CtElement element = elementInNopolProject(8, "((((a * b) < 11) || productLowerThan100(a, b)) || (!(a < b))) || ((a = -b) > 0)");
CtIf ifStatement = (CtIf) testReachedVariableNames(element, "a", "b");
List<String> expected = asList("0", "11", "a", "b", "-b",
"(a * b)",
"(a < b)",
"(!(a < b))",
"((a * b) < 11)");
checkFoundFromIf(ifStatement, expected, (Multimap) Multimap.newSetMultimap());
}
示例30
private boolean whetherConditionalStat(CtElement input) {
if(input instanceof CtIf || input instanceof CtWhile || input instanceof CtFor || input
instanceof CtForEach)
return true;
else return false;
}