Java Code Examples for spoon.reflect.code.CtBlock

The following examples show how to use spoon.reflect.code.CtBlock. 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
public void process(Bound annotation, CtParameter<?> element) {
	// Is to be process?
	CtExecutable<?> e = element.getParent();
	if (e.getBody() == null) {
		return;
	}

	// Use template.
	CtClass<?> type = e.getParent(CtClass.class);
	Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max());
	final CtBlock apply = (CtBlock) t.apply(type);

	// Apply transformation.
	for (int i = apply.getStatements().size() - 1; i >= 0; i--) {
		final CtStatement statement = apply.getStatement(i);
		statement.delete();
		e.getBody().insertBegin(statement);
	}
}
 
Example 3
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 4
Source Project: astor   Source File: InsertBeforeOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean applyChangesInModel(OperatorInstance operation, ProgramVariant p) {
	boolean successful = false;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtStatement fix = (CtStatement) operation.getModified();
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtBlock parentBlock = stmtoperator.getParentBlock();

	if (parentBlock != null) {
		ctst.insertBefore((CtStatement) fix);
		fix.setParent(parentBlock);
		successful = true;
		operation.setSuccessfulyApplied(successful);
		StatementSupporter.updateBlockImplicitly(parentBlock, true);
	} else {
		log.error("Operation not applied. Parent null ");
	}
	return successful;

}
 
Example 5
Source Project: astor   Source File: InsertAfterOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
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) {
		ctst.insertAfter((CtStatement) fix);
		fix.setParent(parentBlock);
		successful = true;
		operation.setSuccessfulyApplied(successful);
		StatementSupporter.updateBlockImplicitly(parentBlock, true);
	} else {
		log.error("Operation not applied. Parent null");
	}
	return successful;
}
 
Example 6
Source Project: astor   Source File: ReplaceOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 7
Source Project: astor   Source File: RemoveOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean applyChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	boolean successful = false;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtBlock parentBlock = stmtoperator.getParentBlock();

	if (parentBlock != null) {

		try {
			parentBlock.getStatements().remove(stmtoperator.getLocationInParent());
			successful = true;
			operation.setSuccessfulyApplied(successful);
			StatementSupporter.updateBlockImplicitly(parentBlock, false);
		} 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 8
Source Project: astor   Source File: RemoveOp.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean undoChangesInModel(OperatorInstance operation, ProgramVariant p) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtBlock<?> parentBlock = stmtoperator.getParentBlock();
	if (parentBlock != null) {
		if ((parentBlock.getStatements().isEmpty() && stmtoperator.getLocationInParent() == 0)
				|| (parentBlock.getStatements().size() >= stmtoperator.getLocationInParent())) {
			parentBlock.getStatements().add(stmtoperator.getLocationInParent(), ctst);
			parentBlock.setImplicit(stmtoperator.isParentBlockImplicit());
			return true;
		} else {
			log.error(
					"Problems to recover, re-adding " + ctst + " at location " + stmtoperator.getLocationInParent()
							+ " from parent size " + parentBlock.getStatements().size());
			throw new IllegalStateException("Undo:Not valid index");
		}

	}
	return false;
}
 
Example 9
Source Project: astor   Source File: StatementSupporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the implicitly of a block. Workarround for Spoon 5.4.0
 * 
 * @param block
 * @param isInsert
 */
public static void updateBlockImplicitly(CtBlock block, boolean isInsert) {

	if (!block.isImplicit() && block.getStatements().size() == 1 && !(block.getParent() instanceof CtExecutable)) {
		block.setImplicit(true);
	} else {
		if (isInsert) {
			if (block.isImplicit() && block.getStatements().size() > 1) {
				block.setImplicit(false);
			}
		} else {// Delete
			if (block.isImplicit() && block.getStatements().size() == 0) {
				block.setImplicit(false);
			}
		}
	}
}
 
Example 10
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 11
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 12
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 13
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 14
public boolean defineParentInformation(ModificationPoint genSusp) {
	CtElement targetStmt = genSusp.getCodeElement();
	CtElement cparent = targetStmt.getParent();
	if ((cparent != null && (cparent instanceof CtBlock))) {
		CtBlock parentBlock = (CtBlock) cparent;
		int location = locationInParent(parentBlock, targetStmt);
		if (location >= 0) {
			this.setParentBlock(parentBlock);
			this.setLocationInParent(location);
			return true;
		}

	} else {
		log.error("Parent null or it is not a block");
	}
	return false;
}
 
Example 15
Source Project: astor   Source File: StatamentTransformer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean doReplaceStatement(OperatorInstance operation) {
	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 16
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 17
Source Project: astor   Source File: StatamentTransformer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean undoRemoveStatement(OperatorInstance operation) {
	StatementOperatorInstance stmtoperator = (StatementOperatorInstance) operation;
	CtStatement ctst = (CtStatement) operation.getOriginal();
	CtBlock<?> parentBlock = stmtoperator.getParentBlock();
	if (parentBlock != null) {
		if ((parentBlock.getStatements().isEmpty() && stmtoperator.getLocationInParent() == 0)
				|| (parentBlock.getStatements().size() >= stmtoperator.getLocationInParent())) {

			parentBlock.getStatements().add(stmtoperator.getLocationInParent(), ctst);
			return true;
		} else {
			log.error(
					"Problems to recover, re-adding " + ctst + " at location " + stmtoperator.getLocationInParent()
							+ " from parent size " + parentBlock.getStatements().size());
			throw new IllegalStateException("Undo:Not valid index");
		}

	}
	return false;
}
 
Example 18
@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 19
Source Project: astor   Source File: MultiPatchTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private OperatorInstance createSecondPatch(ProgramVariant variant, ModificationPoint modificationPoint,
		CtElement fix, int currentGeneration) {

	CtElement targetStmt = modificationPoint.getCodeElement();

	StatementOperatorInstance operation = new StatementOperatorInstance();

	operation.setOperationApplied(new ReplaceOp());
	operation.setModificationPoint(modificationPoint);
	operation.setParentBlock((CtBlock) targetStmt.getParent());
	operation.setOriginal(targetStmt);
	operation.setModified(fix);
	operation.defineParentInformation(modificationPoint);

	variant.putModificationInstance(currentGeneration, operation);
	operation.setModificationPoint(modificationPoint);

	return operation;
}
 
Example 20
Source Project: astor   Source File: PatchValidationTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private OperatorInstance createDummyOperation1(ProgramVariant variant, int currentGeneration) {

		SuspiciousModificationPoint genSusp = searchSuspiciousElement(variant, "n += 3", " ", 93);
		assertNotNull(genSusp);

		CtElement targetStmt = genSusp.getCodeElement();
		CtElement fix = createFix1();
		assertEquals(fix.toString(), "n += 2");

		StatementOperatorInstance operation = new StatementOperatorInstance();

		operation.setOperationApplied(new ReplaceOp());
		operation.setModificationPoint(genSusp);
		operation.setParentBlock((CtBlock) targetStmt.getParent());
		operation.setOriginal(targetStmt);
		operation.setModified(fix);

		variant.putModificationInstance(currentGeneration, operation);
		operation.setModificationPoint(genSusp);

		return operation;
	}
 
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: SpoonStatementLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static CtBlock<?> asBlock(CtStatement statement, CtElement parent) {
    CtBlock<?> block;
    if (isBlock(statement)) {
        block = (CtBlock<?>) statement;
    } else {
        block = newBlock(statement.getFactory(), statement);
    }
    setParent(parent, block);
    return block;
}
 
Example 23
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 24
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 25
Source Project: nopol   Source File: InBlockFilter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean matches(T element) {
    CtBlock<?> elementBlock = element.getParent(CtBlock.class);
    if (elementBlock != null) {
        return blocks().contains(elementBlock);
    }
    return false;
}
 
Example 26
Source Project: nopol   Source File: TestExecutorProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void createMainTestClass(SpoonedFile spooner,
                                       String className) {
    Factory factory = spooner.spoonFactory();
    CtClass<Object> executeTestClass = factory.Class().create(className);

    CtTypeReference<String[]> typedReference = factory.Class()
            .createReference(String[].class);
    CtTypeReference<Object> returnTypedReference = factory.Class()
            .createReference("void");

    Set<ModifierKind> modifiers = new LinkedHashSet<>(2);
    modifiers.add(ModifierKind.PUBLIC);
    modifiers.add(ModifierKind.STATIC);

    HashSet<CtTypeReference<? extends Throwable>> exceptions = new HashSet<>();
    exceptions.add(factory.Class().createReference(Exception.class));

    CtBlock<?> body = spooner.spoonFactory().Core().createBlock();

    body.addStatement(factory
            .Code()
            .createCodeSnippetStatement(
                    "for (String method : methods) {\n\t\t"
                            + "String[] split = method.split(\"\\\\.\");\n\t\t"
                            + "Class.forName(method.replace(\".\" + split[split.length - 1], \"\")).getMethod(\"runJPFTest\", String[].class).invoke(null, new Object[] { new String[] { split[split.length - 1] }});}"));

    CtMethod<?> method = spooner
            .spoonFactory()
            .Method()
            .create(executeTestClass, modifiers, returnTypedReference,
                    "main", new ArrayList<CtParameter<?>>(), exceptions,
                    body);
    spooner.spoonFactory().Method()
            .createParameter(method, typedReference, "methods");
}
 
Example 27
@Override
public void process(CtMethod method) {
    final Factory factory = method.getFactory();

    CtBlock methodBody = method.getBody();

    List<CtComment> bodyComments = new ArrayList<>();

    ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements());
    for (CtStatement ctStatement : ctStatements) {
        String statement = ctStatement.toString();
        bodyComments.add(factory.createInlineComment(statement));
        methodBody.removeStatement(ctStatement);
    }

    CtClass<? extends Throwable> myExceptionClass = factory.Class().get(EXCEPTION_FQN);
    CtConstructorCall<? extends Throwable> myNewException = factory.createConstructorCall(myExceptionClass.getReference());

    CtThrow throwMyException = factory.createThrow();
    throwMyException.setThrownExpression(myNewException);
    methodBody.addStatement(throwMyException);

    bodyComments.add(factory.createInlineComment("FIXME: The private API type should never be return in a public API."));

    for (CtComment bodyComment : bodyComments) {
        throwMyException.addComment(bodyComment);
    }
}
 
Example 28
@Override
public void process(RetryOnFailure retryOnFailure, CtMethod<?> ctMethod) {
	RetryTemplate template = new RetryTemplate(
			ctMethod.getBody(),
			retryOnFailure.attempts(),
			retryOnFailure.delay(),
			retryOnFailure.verbose()
	);

	CtBlock newBody = template.apply(ctMethod.getDeclaringType());
	ctMethod.setBody(newBody);
}
 
Example 29
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a parent that is not a block
 * 
 * @param aStatement
 * @return
 */
public CtElement getParentNotBlock(CtElement aStatement) {

	if (aStatement == null)
		return null;
	if (aStatement.getParent() instanceof CtBlock)
		return getParentNotBlock(aStatement.getParent());

	return aStatement.getParent();
}
 
Example 30
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 5 votes vote down vote up
public static boolean whethereffectivetrycatch(CtTry trystatement, CtStatement targetstatement) {

		CtBlock tryblock = trystatement.getBody();

		if (tryblock != null) {
			List<CtStatement> trystatements = tryblock.getStatements();
			// if(trystatements.size()>0 && trystatements.get(0)==targetstatement)
			if (trystatements.size() > 0)
				return true;
		}

		return false;
	}