Java Code Examples for spoon.reflect.code.CtIf#setThenStatement()

The following examples show how to use spoon.reflect.code.CtIf#setThenStatement() . 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 File: ConditionalAdder.java    From nopol with 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 2
Source File: BoundProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
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 3
Source File: ExtendedRepairGenerator.java    From coming with 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 4
Source File: SingleWrapIfOperator.java    From astor with 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 5
Source File: SymbolicConditionalAdder.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
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 6
Source File: ReplaceReturnOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
private CtElement createReturn(CtElement rootElement) {
	CtMethod method = rootElement.getParent(CtMethod.class);

	if (method == null) {
		log.info("Element without method parent");
		return null;
	}
	// We create the "if(true)"{}
	CtIf ifReturn = MutationSupporter.getFactory().Core().createIf();
	CtExpression ifTrueExpression = MutationSupporter.getFactory().Code().createCodeSnippetExpression("true");
	ifReturn.setCondition(ifTrueExpression);

	// Now we create the return statement
	CtReturn<?> returnStatement = null;
	CtTypeReference typeR = method.getType();
	if (typeR == null || "void".equals(typeR.getSimpleName())) {
		returnStatement = MutationSupporter.getFactory().Core().createReturn();
	} else {
		String codeExpression = "";
		if (prim.contains(typeR.getSimpleName())) {
			codeExpression = getZeroValue(typeR.getSimpleName().toLowerCase());
		} else if (typeR.getSimpleName().toLowerCase().equals("boolean")) {
			codeExpression = "false";
		} else {
			codeExpression = "null";
		}
		CtExpression returnExpression = MutationSupporter.getFactory().Code()
				.createCodeSnippetExpression(codeExpression);
		returnStatement = MutationSupporter.getFactory().Core().createReturn();
		returnStatement.setReturnedExpression(returnExpression);
	}
	// Now, we associate if(true){return [...]}
	ifReturn.setThenStatement(returnStatement);
	return ifReturn;

}
 
Example 7
Source File: ConditionAddTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
private void writeCondition(String type, CtBlock parent, int id) {
	CtExpression conditionExp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype);
       
	CtIf ifStmt = this.mutSupporter.getFactory().Core().createIf();
	ifStmt.setCondition(conditionExp);
	ifStmt.setThenStatement((CtStatement)this.modificationPoint.getCodeElement());
	parent.addStatement(id, ifStmt);
	parent.removeStatement((CtStatement)this.modificationPoint.getCodeElement());
	saveSketchAndSynthesize();
	parent.addStatement(id, (CtStatement)this.modificationPoint.getCodeElement());
	parent.removeStatement(ifStmt);
	resoreDiskFile();
}
 
Example 8
Source File: ConditionAddTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "static-access", "unchecked" })
private void writeIfReturn(String type, CtBlock parent, int id) {
	
	CtExpression conditionExp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype);

	CtIf ifstmt = this.mutSupporter.getFactory().Core().createIf();
	ifstmt.setCondition(conditionExp);
	
	CtElement parentmethod=parent;
	
	do {
		parentmethod=parentmethod.getParent();
	} while (!(parentmethod instanceof CtMethod));
	
	String returntype="void";
	returntype=((CtMethod)parentmethod).getType().getQualifiedName();
	returntype = returntype.replaceAll("\\d","");
	
	CtReturn returnstmt = this.mutSupporter.getFactory().Core().createReturn();

	if (!returntype.toLowerCase().equals("void")) {
		CtExpression returnexp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, returntype, "EXP");
		returnstmt.setReturnedExpression(returnexp);
	}
	
	ifstmt.setThenStatement(returnstmt);
	
	parent.addStatement(id, ifstmt);
	saveSketchAndSynthesize();
	parent.removeStatement(ifstmt);
	resoreDiskFile();
}
 
Example 9
Source File: StatementDeletionMetaMutator.java    From metamutator with GNU General Public License v3.0 4 votes vote down vote up
private void mutateOperator(final CtStatement expression) {
	
	
	/*if (alreadyInHotsSpot(expression)) {
		System.out
				.println(String
						.format("Expression '%s' ignored because it is included in previous hot spot",
								expression));
		return;
	}*/
	int thisIndex = ++selectorIndex;
	
	ACTIVABLE kind = ACTIVABLE.ENABLED;
	String expressionContent =  String.format("("+ PREFIX + "%s.is(%s))",
			thisIndex, kind.getClass().getCanonicalName()+"."+kind.name());
	
	//create IfChoice with right condition
	CtIf ifChoice = getFactory().Core().createIf();
	CtCodeSnippetExpression expIf = getFactory().Code().createCodeSnippetExpression(expressionContent);
	ifChoice.setCondition(expIf);
		
	
	
	//create block from a clone of expression
	CtStatement exp2 = getFactory().Core().clone(expression);
	CtBlock thenBlock = getFactory().Code().createCtBlock(exp2);
	
	//set if and replace the expression with the new if
	ifChoice.setThenStatement(thenBlock);
	expression.replace(ifChoice);
	
	//to be sure
	ifChoice.getParent().updateAllParentsBelow();
	
	//if there are return or throws, set else with value of return.
	Filter<CtCFlowBreak> filterReturn = new ReturnOrThrowFilter();
	if(!thenBlock.getElements(filterReturn).isEmpty()){
		SetElseStatementWithReturn(ifChoice);
	}

	
	//to avoid to delete assignement in statement, we assign a default value to all local variable.
	Filter<CtLocalVariable> filterLocalVariable =  new TypeFilter<CtLocalVariable>(CtLocalVariable.class);
	CtMethod method = ifChoice.getParent(CtMethod.class);
	if(method != null && !method.getElements(filterLocalVariable).isEmpty()){
		for(CtLocalVariable var : method.getElements(filterLocalVariable)){
			if(var.getAssignment() == null){
				//create right side expression from template.
				Class classOfAssignment = var.getType().getActualClass();
				CtLiteral rightHand = null;
				
				//Particular case of ForEach (int x : numbers) can't be (int x = 0 : numbers)
				if(var.getParent() instanceof CtForEach){
					continue;
				}
				if(PrimitiveTemplateExpressions.containsKey(classOfAssignment)){
					CtLiteral templateExpression = PrimitiveTemplateExpressions.get(classOfAssignment);
					rightHand = getFactory().Core().clone(templateExpression);
				}else{
					rightHand = getFactory().createLiteral().setValue(null);
				}
				var.setAssignment(rightHand);
			}
		}
	}
	
	Selector.generateSelector(expression, ACTIVABLE.ENABLED, thisIndex, ActivableSet, PREFIX);
	//hotSpots.add(expression);

}
 
Example 10
Source File: MetaGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static MetaOperatorInstance createMetaStatementReplacement(ModificationPoint modificationPoint,
		CtElement elementSource, CtExpression defaultReturnElement, int variableCounter,
		List<Ingredient> ingredients, List<CtParameter<?>> parameters, List<CtExpression<?>> realParameters,
		AstorOperator parentOperator, CtTypeReference returnType) {

	MetaOperatorInstance opMega = new MetaOperatorInstance((MetaOperator) parentOperator,
			MetaGenerator.getNewIdentifier());

	List<OperatorInstance> opsOfVariant = new ArrayList();
	Map<Integer, Ingredient> ingredientOfMapped = new HashMap<>();

	realParameters = filterParameter(realParameters);
	// Creation of mega method
	CtMethod<?> megaMethod = createMegaMethod(opMega, modificationPoint, defaultReturnElement, variableCounter,
			ingredients, parameters, ingredientOfMapped, returnType);

	CtInvocation newInvocationToMega = creationInvocationToMega(modificationPoint, realParameters, megaMethod);

	// Now the if to be inserted:

	CtIf ifNew = MutationSupporter.getFactory().createIf();

	CtStatement statementPointed = (CtStatement) modificationPoint.getCodeElement();
	CtStatement statementPointedCloned = statementPointed.clone();
	statementPointedCloned.setPosition(new NoSourcePosition());
	MutationSupporter.clearPosition(statementPointedCloned);

	ifNew.setThenStatement(statementPointedCloned);
	ifNew.setCondition(newInvocationToMega);

	// Let's create the operations
	OperatorInstance opInstace = new StatementOperatorInstance(modificationPoint, parentOperator, statementPointed,
			ifNew);
	opsOfVariant.add(opInstace);

	// The meta method to be added
	OperatorInstance opMethodAdd = new OperatorInstance();
	opMethodAdd.setOperationApplied(new InsertMethodOperator());
	opMethodAdd.setOriginal(modificationPoint.getCodeElement());
	opMethodAdd.setModified(megaMethod);
	opMethodAdd.setModificationPoint(modificationPoint);
	opsOfVariant.add(opMethodAdd);

	//
	log.debug("method: \n" + megaMethod);

	log.debug("invocation: \n" + newInvocationToMega);

	opMega.setOperatorInstances(opsOfVariant);
	opMega.setAllIngredients(ingredientOfMapped);
	opMega.setOperationApplied(parentOperator);
	opMega.setOriginal(modificationPoint.getCodeElement());
	opMega.setModificationPoint(modificationPoint);

	return opMega;
}
 
Example 11
Source File: NullPreconditionWithExpressionOperator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<OperatorInstance> createOperatorInstances(ModificationPoint modificationPoint, Ingredient ingredient,
		IngredientTransformationStrategy transformationStrategy) {

	List<OperatorInstance> instances = new ArrayList<>();

	List<Ingredient> ingredientsTransformed = transformationStrategy.transform(modificationPoint, ingredient);

	for (Ingredient iIngredient : ingredientsTransformed) {

		CtExpression condition = (CtExpression) iIngredient.getCode();
		CtIf precondition = MutationSupporter.factory.createIf();
		precondition.setCondition(condition);
		precondition.setThenStatement((CtStatement) modificationPoint.getCodeElement().clone());

		OperatorInstance operatorInstance = new StatementOperatorInstance(modificationPoint, this, precondition);

		instances.add(operatorInstance);

	}

	return instances;

}
 
Example 12
Source File: NullPreconditionOperator.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<OperatorInstance> createOperatorInstances(ModificationPoint modificationPoint) {

	List<OperatorInstance> instances = new ArrayList<>();

	List<CtVariableAccess> varAccess = VariableResolver.collectVariableAccess(modificationPoint.getCodeElement());

	for (CtVariableAccess iVariableAccess : varAccess) {

		if (!iVariableAccess.getType().isPrimitive()) {

			CtIf precodition = MutationSupporter.factory.createIf();

			CtExpression ifcondition = MutationSupporter.factory.createBinaryOperator(iVariableAccess,
					MutationSupporter.factory.createCodeSnippetExpression("null").compile(), BinaryOperatorKind.NE);

			precodition.setCondition(ifcondition);
			precodition.setThenStatement((CtStatement) modificationPoint.getCodeElement().clone());

			OperatorInstance operatorInstance = new StatementOperatorInstance(modificationPoint, this, precodition);

			instances.add(operatorInstance);
		}
	}
	return instances;

}
 
Example 13
Source File: NullPreconditionOperatorMI.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<OperatorInstance> createOperatorInstances(ModificationPoint modificationPoint) {
	List<OperatorInstance> instances = new ArrayList<>();

	CtInvocation invocation = (CtInvocation) modificationPoint.getCodeElement();

	CtExpression targetExpresionOfMI = invocation.getTarget();

	if (targetExpresionOfMI instanceof CtVariableAccess) {

		CtStatement parentStatement = modificationPoint.getCodeElement().getParent(CtStatement.class);

		CtExpression ifcondition = MutationSupporter.factory.createBinaryOperator(targetExpresionOfMI,
				MutationSupporter.factory.createCodeSnippetExpression("null").compile(), BinaryOperatorKind.NE);

		CtIf precodition = MutationSupporter.factory.createIf();
		precodition.setCondition(ifcondition);
		precodition.setThenStatement(parentStatement);

		OperatorInstance operatorInstance = new StatementOperatorInstance(modificationPoint, this, parentStatement,
				precodition);

		instances.add(operatorInstance);
	}
	return instances;

}