Java Code Examples for spoon.reflect.code.CtIf

The following examples show how to use spoon.reflect.code.CtIf. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: nopol   Source File: PatchGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source Project: nopol   Source File: ConditionalAdder.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 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);
}
 
Example 4
Source Project: spoon-examples   Source File: BoundTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source Project: spoon-examples   Source File: BoundTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 6
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 7
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 6 votes vote down vote up
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);
	}
 
Example 8
Source Project: coming   Source File: CodeElementInfo.java    License: MIT License 6 votes vote down vote up
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);
	}
 
Example 9
Source Project: coming   Source File: VariableResolver.java    License: MIT License 6 votes vote down vote up
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);

	}
 
Example 10
Source Project: coming   Source File: VariableResolver.java    License: MIT License 6 votes vote down vote up
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);

	}
 
Example 11
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 6 votes vote down vote up
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
}
 
Example 12
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 6 votes vote down vote up
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
}
 
Example 13
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 6 votes vote down vote up
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
}
 
Example 14
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 15
Source Project: astor   Source File: SingleWrapIfOperator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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();
}
 
Example 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();
}
 
Example 17
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);

	}
 
Example 18
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);

	}
 
Example 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);
	}

}
 
Example 20
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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)
}
 
Example 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);
}
 
Example 22
Source Project: nopol   Source File: DumbFaultLocalizerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 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;
}
 
Example 24
Source Project: nopol   Source File: PatchGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example 25
Source Project: nopol   Source File: ConditionalProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 26
Source Project: nopol   Source File: ConditionalReplacer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 27
Source Project: nopol   Source File: LoggingInstrumenter.java    License: GNU General Public License v2.0 5 votes vote down vote up
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());
}
 
Example 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());
}
 
Example 29
Source Project: nopol   Source File: ValuesCollectorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example 30
Source Project: coming   Source File: VariableAnalyzer.java    License: MIT License 5 votes vote down vote up
private boolean whetherConditionalStat(CtElement input) {
	
	if(input instanceof CtIf || input instanceof CtWhile || input instanceof CtFor || input
			instanceof CtForEach)
		return true;
	else return false;	
}