spoon.reflect.code.CtStatement Java Examples

The following examples show how to use spoon.reflect.code.CtStatement. 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: 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 #2
Source File: VarMappingTest.java    From astor with 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 #3
Source File: NullPreconditionOperator.java    From astor with 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 #4
Source File: StatamentTransformer.java    From astor with 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 #5
Source File: DelegatingProcessor.java    From nopol with 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 #6
Source File: AbstractCodeAnalyzer.java    From coming with 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 #7
Source File: LiteralReplacer.java    From nopol with 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 #8
Source File: LiteralReplacer.java    From nopol with 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 File: SpoonStatementLibrary.java    From nopol with 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 #10
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 #11
Source File: AbstractCodeAnalyzer.java    From coming with 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 #12
Source File: MutationTester.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
private void replace(CtElement e, CtElement op) {
	if (e instanceof CtStatement  && op instanceof CtStatement) {
		e.replace(op);
		return;
	}
	if (e instanceof CtExpression && op instanceof CtExpression) {
		e.replace(op);
		return;
	}
	throw new IllegalArgumentException(e.getClass()+" "+op.getClass());
}
 
Example #13
Source File: LiteralReplacer.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public LiteralReplacer(Class<?> cl, CtStatement statement, RepairType repairType) {
    super(statement, repairType);
    if (statement instanceof CtAssignment<?, ?>) {
        super.setDefaultValue(((CtAssignment<?, ?>) statement).getAssignment().toString());
    } else if (statement instanceof CtLocalVariable<?>) {
        super.setDefaultValue(((CtLocalVariable<?>) statement).getDefaultExpression().toString());
    }
    super.setType(cl);
}
 
Example #14
Source File: DBAccessProcessor.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public void process(DBAccess dbAccess, CtClass<?> target) {
	Factory f = target.getFactory();
	DBType t = dbAccess.type();
	if (t != DBType.RELATIONAL)
		f.getEnvironment().report(
				this,
				Level.ERROR,
				target.getAnnotation(f.Type().createReference(
						DBAccess.class)), "unsupported DB system");

	DBCodeTemplate template = new DBCodeTemplate(f, dbAccess.database(),
			dbAccess.username(), dbAccess.password(), dbAccess.tableName());
	Substitution.insertField(target, template, f.Class().get(
			DBCodeTemplate.class).getField("connection"));
	for (CtConstructor<?> c : target.getConstructors()) {
		c.getBody().insertBegin((CtStatement)
				Substitution.substituteMethodBody(target, template,
						"initializerCode"));
	}
	for (CtMethod<?> m : target.getMethods()) {
		template._columnName_ = m.getSimpleName().substring(3)
				.toLowerCase();
		m.getBody().replace(
				Substitution.substituteMethodBody(target, template,
						"accessCode"));
	}
}
 
Example #15
Source File: ValuesCollectorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private CtStatement testReachedVariableNames(CtElement element, Collection<String> expectedNames, Multimap<String, String> expectedGetters) {
	assertTrue(CtCodeElement.class.isInstance(element));
	CtStatement statement = SpoonStatementLibrary.statementOf((CtCodeElement) element);
	CollectableValueFinder finder = CollectableValueFinder.valueFinderFrom(statement);
	checkFoundInFinder(finder, expectedNames, expectedGetters);
	return statement;
}
 
Example #16
Source File: DelegatingProcessor.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtStatement element) {
    for (Processor processor : this.processors) {
        processor.process(element);
    }
    this.process = false;
}
 
Example #17
Source File: StatamentTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static boolean undoReplaceStatement(OperatorInstance operation) {
	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 #18
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 5 votes vote down vote up
/**
 * Return if the element is a guard
 * 
 * @param element
 * @return
 */
public boolean isNormalGuard(CtElement element, CtStatement parentStatement) {

	// Two cases: if and conditional
	CtExpression condition = null;
	CtConditional parentConditional = element.getParent(CtConditional.class);

	if (parentConditional != null) { // TODO, maybe force that the var must be in the condition, or not.
		CtConditional cond = (CtConditional) parentConditional;
		condition = cond.getCondition();
		return checkNormalGuardCondition(condition);
	} else {
		CtElement parentElement = getParentNotBlock(parentStatement);
		// First, find the condition

		if (parentElement instanceof CtIf) {

			CtIf guardCandidateIf = (CtIf) parentElement;

			if (whethereffectiveguard(guardCandidateIf, parentStatement)) {
				condition = guardCandidateIf.getCondition();
				boolean isConditionAGuard = checkNormalGuardCondition(condition);
				return isConditionAGuard;
			}
		}
	}
	return false;
}
 
Example #19
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public boolean isNullCheckGuard(CtElement element, CtStatement parentStatement) {

		// Two cases: if and conditional
		CtExpression condition = null;
		CtConditional parentConditional = element.getParent(CtConditional.class);

		if (parentConditional != null) {// TODO, maybe force that the var must be in the condition, or not.
			CtConditional cond = (CtConditional) parentConditional;
			condition = cond.getCondition();
			return checkNullCheckGuardCondition(condition);

		} else {
			CtElement parentElement = getParentNotBlock(parentStatement);
			// First, find the condition

			if (parentElement instanceof CtIf) {

				CtIf guardCandidateIf = (CtIf) parentElement;

				if (whethereffectiveguard(guardCandidateIf, parentStatement)) {
					condition = guardCandidateIf.getCondition();
					boolean isConditionAGuard = checkNullCheckGuardCondition(condition);
					return isConditionAGuard;
				}
			}
		}
		return false;
	}
 
Example #20
Source File: NopolProcessorBuilder.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private void preconditionalReplacer(CtStatement statement) {
    if (SpoonPredicate.canBeRepairedByAddingPrecondition(statement)) {
        if (nopolContext.getOracle() == NopolContext.NopolOracle.ANGELIC) {
            nopolProcessors.add(new ConditionalAdder(statement));
        } else if (nopolContext.getOracle() == NopolContext.NopolOracle.SYMBOLIC) {
            nopolProcessors.add(new SymbolicConditionalAdder(statement));
        }
    }
}
 
Example #21
Source File: PatchGenerator.java    From nopol with 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 #22
Source File: NullPreconditionOperatorMI.java    From astor with 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 #23
Source File: LiteralReplacer.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private void replaceBoolean(CtExpression ctElement) {
    if (getValue() == null) {
        CtLocalVariable<Boolean> evaluation = newLocalVariableDeclaration(
                ctElement.getFactory(), boolean.class, "guess_fix",
                Debug.class.getCanonicalName() + ".makeSymbolicBoolean(\"guess_fix\")");
        CtStatement firstStatement = getFirstStatement(ctElement);
        if (firstStatement == null) {
            return;
        }
        SpoonStatementLibrary.insertBeforeUnderSameParent(evaluation,
                firstStatement);
        ctElement.replace(getFactory().Code().createCodeSnippetExpression(
                "guess_fix"));
    } else {
        switch (getValue()) {
            case "1":
                ctElement.replace(getFactory().Code().createCodeSnippetExpression("true"));
                break;
            case "0":
                ctElement.replace(getFactory().Code().createCodeSnippetExpression("false"));
                break;
            default:
                ctElement.replace(getFactory().Code().createCodeSnippetExpression(getValue()));
                break;
        }
    }
}
 
Example #24
Source File: NopolProcessorBuilder.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private void conditionalReplacer(CtStatement statement) {
    if (SpoonPredicate.canBeRepairedByChangingCondition(statement)) {
        if (nopolContext.getOracle() == NopolContext.NopolOracle.ANGELIC) {
            nopolProcessors.add(new ConditionalReplacer(statement));
        } else if (nopolContext.getOracle() == NopolContext.NopolOracle.SYMBOLIC) {
            nopolProcessors.add(new SymbolicConditionalReplacer(statement));
        }
    }
}
 
Example #25
Source File: LoggingInstrumenter.java    From nopol with 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 #26
Source File: Arja.java    From coming with 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;
}
 
Example #27
Source File: ConditionalReplacer.java    From nopol with 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 #28
Source File: SingleStatementFixSpaceProcessor.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 File: MethodFromLocation.java    From nopol with 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 #30
Source File: AbstractCodeAnalyzer.java    From coming with 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;
}