Java Code Examples for spoon.reflect.code.CtStatement

The following examples show how to use spoon.reflect.code.CtStatement. 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
public boolean applyChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	boolean successful = false;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtStatement fix = (CtStatement) operation.getModified();

	CtBlock parentBlock = stmtoperator.getParentBlock();

	if (parentBlock != null) {

		try {
			ctst.replace((CtStatement) fix);
			fix.setParent(parentBlock);
			successful = true;
			operation.setSuccessfulyApplied(successful);
		} catch (Exception ex) {
			log.error("Error applying an operation, exception: " + ex.getMessage());
			operation.setExceptionAtApplied(ex);
			operation.setSuccessfulyApplied(false);
		}
	} else {
		log.error("Operation not applied. Parent null ");
	}
	return successful;
}
 
Example 2
Source Project: astor   Source File: StatamentTransformer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean doRemoveStatement(OperatorInstance operation) {
	boolean successful = false;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtBlock parentBlock = stmtoperator.getParentBlock();

	if (parentBlock != null) {

		try {
			parentBlock.getStatements().remove(ctst);
			successful = true;
			operation.setSuccessfulyApplied(successful);
		} catch (Exception ex) {
			log.error("Error applying an operation, exception: " + ex.getMessage());
			operation.setExceptionAtApplied(ex);
			operation.setSuccessfulyApplied(false);
		}
	} else {
		log.error("Operation not applied. Parent null ");
	}
	return successful;
}
 
Example 3
Source Project: nopol   Source File: SpoonStatementLibrary.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean isLastStatementOfMethod(CtStatement statement) {
    CtElement statementParent = statement.getParent();
    if (!isStatementList(statementParent)) {
        return isLastStatementOfMethod((CtStatement) statementParent);
    }
    CtStatementList block = (CtStatementList) statementParent;
    if (isLastStatementOf(block, statement)) {
        CtElement blockParent = block.getParent();
        if (isStatement(blockParent)) {
            return isLastStatementOfMethod((CtStatement) blockParent);
        } else {
            return isMethod(blockParent);
        }
    }
    return false;
}
 
Example 4
Source Project: astor   Source File: VarMappingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNotMappedVars() {
	// Testing Not Mapped variables
	// We get a method setup(UnivariateRealFunction f) for testing the
	// insertion of a ingredient out of scope
	CtMethod mSetup = getMethod4Test1(engine);
	assertNotNull(mSetup);
	CtStatement stmSetup = mSetup.getBody().getStatement(0);
	List<CtVariable> varsScopeStmSetup = VariableResolver.searchVariablesInScope(stmSetup);
	assertFalse(varsScopeStmSetup.isEmpty());
	// field: private static final String NULL_FUNCTION_MESSAGE, parameter
	// UnivariateRealFunction f
	assertEquals(2, varsScopeStmSetup.size());
	log.debug("context of Setup method " + varsScopeStmSetup);

	VarMapping vmapping3 = VariableResolver.mapVariablesUsingCluster(varsScopeStmSetup, otherClassElementC8);
	assertTrue(vmapping3.getMappedVariables().isEmpty());
	assertFalse(vmapping3.getNotMappedVariables().isEmpty());
	assertEquals(2, vmapping3.getNotMappedVariables().size());

}
 
Example 5
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 6 votes vote down vote up
public boolean isElementBeforeVariable(CtVariableAccess variableAffected, CtElement element) {

		try {
			CtStatement stst = (element instanceof CtStatement) ? (CtStatement) element
					: element.getParent(CtStatement.class);

			CtStatement target = (variableAffected instanceof CtStatement) ? (CtStatement) variableAffected
					: variableAffected.getParent(CtStatement.class);

			return target.getPosition() != null && getParentNotBlock(stst) != null
					&& target.getPosition().getSourceStart() > stst.getPosition().getSourceStart();
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return false;

	}
 
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: 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 8
Source Project: nopol   Source File: LiteralReplacer.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void replaceDouble(CtExpression ctElement) {
    if (getValue() == null) {
        CtLocalVariable<Double> evaluation = newLocalVariableDeclaration(
                ctElement.getFactory(), double.class, "guess_fix",
                Debug.class.getCanonicalName() + ".makeSymbolicReal(\"guess_fix\")");

        CtStatement firstStatement = getFirstStatement(ctElement);
        if (firstStatement == null) {
            return;
        }
        SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation, firstStatement);
        // SpoonStatementLibrary.insertAfterUnderSameParent(getFactory().Code().createCodeSnippetStatement("System.out.println(\"guess_fix: \" + guess_fix)"),
        // getFirstStatement(ctElement));
        ctElement.replace(getFactory().Code().createCodeSnippetExpression("guess_fix"));
    } else {
        ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue()));
    }
}
 
Example 9
Source Project: nopol   Source File: LiteralReplacer.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void replaceInteger(CtExpression ctElement) {
    if (getValue() == null) {
        CtLocalVariable<Integer> evaluation = newLocalVariableDeclaration(
                ctElement.getFactory(), int.class, "guess_fix",
                Debug.class.getCanonicalName()
                        + ".makeSymbolicInteger(\"guess_fix\")");

        CtStatement firstStatement = getFirstStatement(ctElement);
        if (firstStatement == null) {
            return;
        }
        SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation, firstStatement);
        // SpoonStatementLibrary.insertAfterUnderSameParent(getFactory().Code().createCodeSnippetStatement("System.out.println(\"guess_fix: \" + guess_fix)"),
        // getFirstStatement(ctElement));

        ctElement.replace(getFactory().Code().createCodeSnippetExpression("guess_fix"));
    } else {
        ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue()));
    }
}
 
Example 10
Source Project: nopol   Source File: DelegatingProcessor.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @see spoon.processing.AbstractProcessor#isToBeProcessed(spoon.reflect.declaration.CtElement)
 */
@Override
public boolean isToBeProcessed(final CtStatement candidate) {
    boolean isPracticable = this.predicate.apply(candidate);
    if (isPracticable) {
        SourcePosition position = candidate.getPosition();
        if (position == null || position == SourcePosition.NOPOSITION) {
            return false;
        }
        boolean isSameFile = false;
        boolean isSameLine = position.getLine() == this.line;
        try {
            File f1 = position.getFile().getCanonicalFile().getAbsoluteFile();
            File f2 = file.getCanonicalFile();
            isSameFile = f1.getAbsolutePath().equals(f2.getAbsolutePath());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        isPracticable = this.process && isSameLine && isSameFile;
    }
    return isPracticable;
}
 
Example 11
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 12
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 5 votes vote down vote up
public boolean isStatementInControl(CtStatement targetstatement, CtStatement statementtocompare) {
	CtElement parentelement = targetstatement.getParent();
	int layer = 0;
	CtElement parent;
	parent = statementtocompare;
	do {
		parent = parent.getParent();
		layer++;
	} while (parent != parentelement && parent != null);

	if (layer > 1 && parent != null)
		return true;
	else
		return false;
}
 
Example 13
@Override
public boolean isToBeProcessed(CtStatement element) {
	for(Class<?> c : MODIFIABLE_STATEMENTS){
		if(c.isInstance(element)){
			return true;
		}
	}
	return false;
}
 
Example 14
@Override
public boolean undoChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtStatement fix = (CtStatement) operation.getModified();
	CtBlock<?> parentBlock = stmtoperator.getParentBlock();
	if (parentBlock != null) {
		fix.replace((CtStatement) ctst);
		return true;

	}
	return false;
}
 
Example 15
public static <T> CtStatement runtimeCollectionBefore(CtStatement location, Map<String, String> inputs, Multimap<String, String> getters, String output, RuntimeValues<T> runtime) {
    Factory factory = location.getFactory();
    List<CtStatement> newStatements = MetaList.newLinkedList();
    addCollectionStatementFor(newStatements, factory, runtime.invocationOnCollectionStart());
    addVariableCollection(inputs, runtime, factory, newStatements);
    addGetterCollection(getters, runtime, factory, newStatements);
    addCollectionStatementFor(newStatements, factory, runtime.invocationOnOutputCollection(output));
    addCollectionStatementFor(newStatements, factory, runtime.invocationOnCollectionEnd());
    return collectionWrappingIf(newStatements, runtime, location);
}
 
Example 16
private static <T> void addGetterCollection(Multimap<String, String> getters, RuntimeValues<T> runtime, Factory factory, List<CtStatement> newStatements) {
    String invocation;
    for (String receiver : getters.keySet()) {
        List<CtStatement> invocations = MetaList.newLinkedList();
        for (String getterName : getters.get(receiver)) {
            invocation = receiver + '.' + getterName + "()";
            addCollectionStatementFor(invocations, factory, runtime.invocationOnCollectionOf(invocation));
        }
        newStatements.add(newIf(factory, newExpressionFromSnippet(factory, receiver + "!=null", Boolean.class), newBlock(factory, invocations)));
    }
}
 
Example 17
Source Project: astor   Source File: SingleTryOperator.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean applyModification() {

	CtElement el = MetaGenerator.geOriginalElement(statementToWrap);
	if (!(el instanceof CtStatement)) {
		return false;
	}

	CtStatement original = (CtStatement) el;
	this.setParentBlock(original.getParent(CtBlock.class));

	CtTry tryNew = MutationSupporter.getFactory().createTry();
	List<CtCatch> catchers = new ArrayList<>();
	CtCatch catchEx1 = MutationSupporter.getFactory().createCtCatch("e", Exception.class, new CtBlockImpl());
	catchers.add(catchEx1);
	tryNew.setCatchers(catchers);
	CtBlock tryBoddy = new CtBlockImpl();
	tryNew.setBody(tryBoddy);

	CtStatement stmtC = statementToWrap.clone();

	MutationSupporter.clearPosition(stmtC);
	tryBoddy.addStatement(stmtC);

	//
	super.setOriginal(original);
	super.setModified(tryNew);
	//

	return super.applyModification();
}
 
Example 18
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 19
Source Project: nopol   Source File: SpoonModelLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static CtTry newTryCatch(Factory factory, CtStatement tryBlock, List<CtCatch> catchers, CtElement parent) {
    CtTry tryCatch = factory.Core().createTry();
    tryCatch.setBody(asBlock(tryBlock, tryCatch));
    tryCatch.setCatchers(catchers);
    setParent(tryCatch, catchers);
    setParent(parent, tryCatch);
    return tryCatch;
}
 
Example 20
Source Project: nopol   Source File: SpoonStatementLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void insertBeforeUnderSameParent(CtStatement toBeInserted, CtStatement insertionPoint) {
    CtElement parent;
    if (isBlock(insertionPoint)) {
        CtBlock<?> block = (CtBlock<?>) insertionPoint;
        block.insertBegin(toBeInserted);
        parent = block;
    } else {
        insertionPoint.insertBefore(toBeInserted);
        parent = insertionPoint.getParent();
    }
    setParent(parent, toBeInserted);
}
 
Example 21
Source Project: nopol   Source File: SpoonStatementLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void insertAfterUnderSameParent(CtStatement toBeInserted, CtStatement insertionPoint) {
    CtElement parent;
    if (isBlock(insertionPoint)) {
        CtBlock<?> block = (CtBlock<?>) insertionPoint;
        block.insertEnd(toBeInserted);
        parent = block;
    } else {
        insertionPoint.insertAfter(toBeInserted);
        parent = insertionPoint.getParent();
    }
    setParent(parent, toBeInserted);
}
 
Example 22
Source Project: astor   Source File: InsertAfterOp.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean undoChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtStatement fix = (CtStatement) operation.getModified();
	CtBlock<?> parentBlock = stmtoperator.getParentBlock();
	int position = stmtoperator.getLocationInParent();
	position += 1;
	boolean sucessful = StatementSupporter.remove(parentBlock, fix, position);
	parentBlock.setImplicit(stmtoperator.isParentBlockImplicit());
	return sucessful;
}
 
Example 23
Source Project: astor   Source File: ReplaceOp.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean undoChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtStatement fix = (CtStatement) operation.getModified();
	CtBlock<?> parentBlock = stmtoperator.getParentBlock();
	if (parentBlock != null) {
		fix.replace((CtStatement) ctst);
		return true;

	}
	return false;
}
 
Example 24
Source Project: nopol   Source File: SpoonMethodLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean isGetter(CtMethod<?> method) {
    if (hasNoArguments(method) && numberOfStatements(method) == 1) {
        CtStatement statement = lastStatementOf(method);
        return isReturnStatement(statement) && isFieldAccess(((CtReturn<?>) statement).getReturnedExpression());
    }
    return false;
}
 
Example 25
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: MIT License 5 votes vote down vote up
private boolean isTainted(CtStatement S) {
    if (S == null) return false;
    if (area.contains(S))
        return true;
    // why Prophet does not need the second condition ?
    if (S instanceof CtStatementList && compound_counter.containsKey(S)) {
        CtStatementList CS = (CtStatementList) S;
        return compound_counter.get(CS) >= 2 || (compound_counter.get(CS) == 1 && CS.getStatements().size() == 1);
    } else {
        return false;
    }
}
 
Example 26
Source Project: nopol   Source File: PatchGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private String getLine() {
	CtStatement parent = getParentLine(target);
	String[] split = getClassContent().split("\n");
	StringBuilder output = new StringBuilder();

	for (int i = parent.getPosition().getLine() - 1; i < parent.getPosition().getEndLine(); i++) {
		String s = split[i];
		output.append(s);
		output.append("\n");
	}

	return output.toString();
}
 
Example 27
Source Project: nopol   Source File: MethodFromLocation.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isToBeProcessed(CtStatement candidate) {
    CtClass parent = candidate.getParent(CtClass.class);
    if (parent == null || !parent.getQualifiedName().equals(this.location.getContainingClassName())) {
        return false;
    }
    return parent.getPosition().getLine() == location.getLineNumber();
}
 
Example 28
@Override
public void process(CtStatement element) {
	if (!(element instanceof CtBlock || element instanceof CtClass || element instanceof CtMethod
			|| element instanceof CtTry || element instanceof CtCatch) && 
			(element.getParent() instanceof CtBlock) && 
			(!(element.toString().startsWith("super"))
					|| ConfigurationProperties.getPropertyBool("manipulatesuper"))) {
		add(element);
	}
}
 
Example 29
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 30
Source Project: coming   Source File: Arja.java    License: MIT License 5 votes vote down vote up
private boolean canBeReproducedFromSrc(CtElement src, CtStatement target) {
	if (!checkSrcContainsTargetVarsAndMethods(src, target)) {
		return false;
	}

	if (!checkSrcIncludesDstTemplate(src, target))
		return false;

	return true;
}