spoon.reflect.code.CtAssignment Java Examples

The following examples show how to use spoon.reflect.code.CtAssignment. 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: AddAssignmentOp.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<OperatorInstance> createOperatorInstances(ModificationPoint modificationPoint) {
	List<OperatorInstance> opInstances = new ArrayList<>();

	CtStatement statementPointed = (targetElement == null) ? (CtStatement) modificationPoint.getCodeElement()
			: (CtStatement) targetElement;

	List<CtVariable> varsInScope = modificationPoint.getContextOfModificationPoint().stream()
			.filter(e -> e.getType().isPrimitive()).collect(Collectors.toList());

	for (CtVariable aVarInScope : varsInScope) {

		CtAssignment assigment = MutationSupporter.getFactory().Code().createVariableAssignment(
				aVarInScope.getReference(), aVarInScope.isStatic(),
				// TO replace
				MutationSupporter.getFactory().createCodeSnippetExpression("0"));

		OperatorInstance opI = new OperatorInstance(modificationPoint, this, statementPointed, assigment);
		opInstances.add(opI);

	}

	return opInstances;
}
 
Example #2
Source File: TransformStrategy.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T, A extends T> void visitCtAssignment(CtAssignment<T, A> assignement) {
	super.visitCtAssignment(assignement);
	
	CtExpression exper=assignement.getAssigned();
	if (candidates.containsKey(exper)) {
		assignement.setAssigned(candidates.get(exper));
		saveSketchAndSynthesize();
		assignement.setAssigned(exper);
		resoreDiskFile();
	}
	
	exper=assignement.getAssignment();
	if (candidates.containsKey(exper)) {
		assignement.setAssignment(candidates.get(exper));
		saveSketchAndSynthesize();
		assignement.setAssignment(exper);
		resoreDiskFile();
	}
}
 
Example #3
Source File: SpecialStatementFixSpaceProcessor.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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 #4
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 #5
Source File: LiteralReplacer.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtStatement ctStatement) {
    if (!(ctStatement instanceof CtLocalVariable<?>) && !(ctStatement instanceof CtAssignment<?, ?>))
        return;

    Class<?> localVariableClass = ((CtTypedElement<?>) ctStatement).getType().getActualClass();
    if (localVariableClass.equals(Integer.class) || localVariableClass.equals(int.class)) {
        if (ctStatement instanceof CtAssignment<?, ?>) {
            replaceInteger(((CtAssignment<?, ?>) ctStatement).getAssignment());
        } else {
            replaceInteger(((CtLocalVariable<?>) ctStatement).getDefaultExpression());
        }
    } else if (localVariableClass.equals(Double.class) || localVariableClass.equals(double.class)) {
        if (ctStatement instanceof CtAssignment<?, ?>) {
            replaceDouble(((CtAssignment<?, ?>) ctStatement).getAssignment());
        } else {
            replaceDouble(((CtLocalVariable<?>) ctStatement).getDefaultExpression());
        }
    } else if (localVariableClass.equals(Boolean.class) || localVariableClass.equals(boolean.class)) {
        if (ctStatement instanceof CtAssignment<?, ?>) {
            replaceBoolean(((CtAssignment<?, ?>) ctStatement).getAssignment());
        } else {
            replaceBoolean(((CtLocalVariable<?>) ctStatement).getDefaultExpression());
        }
    }
}
 
Example #6
Source File: TransformStrategy.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<String> transform () {
	CtStatement targetStmt = (CtStatement) this.modificationPoint.getCodeElement();
	if (targetStmt instanceof CtInvocation)
		this.visitCtInvocation((CtInvocation) targetStmt);
	else if (targetStmt instanceof CtConstructorCall)
		this.visitCtConstructorCall((CtConstructorCall) targetStmt);
	else if (targetStmt instanceof CtIf)
		this.visitCtIf ((CtIf)targetStmt);
	else if (targetStmt instanceof CtReturn)
		this.visitCtReturn((CtReturn) targetStmt);
	else if (targetStmt instanceof CtSwitch)
		this.visitCtSwitch((CtSwitch) targetStmt);
	else if (targetStmt instanceof CtCase)
		this.visitCtCase((CtCase) targetStmt);
	else if (targetStmt instanceof CtAssignment)
		this.visitCtAssignment((CtAssignment) targetStmt);
	else if (targetStmt instanceof CtAssert)
		this.visitCtAssert((CtAssert) targetStmt);
	else if (targetStmt instanceof CtFor)
		this.visitCtFor((CtFor) targetStmt);
	else if (targetStmt instanceof CtForEach)
		this.visitCtForEach((CtForEach) targetStmt);
	else if (targetStmt instanceof CtWhile)
		this.visitCtWhile((CtWhile) targetStmt);
	else if (targetStmt instanceof CtUnaryOperator)
		this.visitCtUnaryOperator((CtUnaryOperator) targetStmt);
	else if (targetStmt instanceof CtSynchronized)
		this.visitCtSynchronized((CtSynchronized) targetStmt);

	return list;
}
 
Example #7
Source File: ExpressionIngredientSpaceProcessor.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtExpression element) {

	if (element instanceof CtAssignment || element instanceof CtNewArray || element instanceof CtTypeAccess
			|| element instanceof CtVariableAccess || element instanceof CtLiteral)
		return;
	if (element.getType() != null)
		this.add(element);

}
 
Example #8
Source File: VariableAssignmentFilter.java    From nopol with GNU General Public License v2.0 4 votes vote down vote up
public VariableAssignmentFilter(CtVariable<?> variable) {
    super(CtAssignment.class);
    this.variable = variable;
}
 
Example #9
Source File: VariableAssignmentFilter.java    From nopol with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean matches(CtAssignment<?, ?> element) {
    return element.getAssigned().getShortRepresentation().equals(variable().getShortRepresentation());
}
 
Example #10
Source File: VariableAnalyzer.java    From coming with MIT License 4 votes vote down vote up
/**
 * For each involved variable, is there any other variable in scope that is a
 * certain function transformation of the involved variable
 * 
 * @param varsAffected
 * @param element
 * @param context
 */
@SuppressWarnings("rawtypes")
private void analyzeV5_AffectedVariablesInTransformation(List<CtVariableAccess> varsAffected, CtElement element,
		Cntx<Object> context) {
	try {
		CtMethod methodParent = element.getParent(CtMethod.class);

		List<CtExpression> assignments = new ArrayList<>();

		CtScanner assignmentScanner = new CtScanner() {

			@Override
			public <T, A extends T> void visitCtAssignment(CtAssignment<T, A> assignement) {
				if (assignement.getAssignment() != null)
					assignments.add(assignement.getAssignment());
			}

			@Override
			public <T> void visitCtLocalVariable(CtLocalVariable<T> localVariable) {
				if (localVariable.getAssignment() != null)
					assignments.add(localVariable.getAssignment());
			}

		};
		assignmentScanner.scan(methodParent);

		for (CtVariableAccess variableAffected : varsAffected) {

			boolean v5_currentVarHasvar = false;

			for (CtExpression assignment : assignments) {

				if (!isElementBeforeVariable(variableAffected, assignment))
					continue;

				// let's collect the var access in the right part
				List<CtVariableAccess> varsInRightPart = VariableResolver.collectVariableRead(assignment); // VariableResolver.collectVariableAccess(assignment);

				// if the var access in the right is the same that the affected
				for (CtVariableAccess varInAssign : varsInRightPart) {
					if (hasSameName(variableAffected, varInAssign)) {

						v5_currentVarHasvar = true;
						break;
					}
				}
			}

			writeGroupedInfo(context, adjustIdentifyInJson(variableAffected), 
					CodeFeatures.V5_HAS_VAR_IN_TRANSFORMATION,
					(v5_currentVarHasvar), "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example #11
Source File: PatternMatchingTest.java    From coming with MIT License 4 votes vote down vote up
@Test
public void testDiff5Pattern_assignment_1_instance() throws Exception {
	// Assignment on if
	System.out.println("Case 2 instances");
	File s = getFile("patterns_examples/case5/1205753_EmbedPooledConnection_0_s.java");
	File t = getFile("patterns_examples/case5/1205753_EmbedPooledConnection_0_t.java");
	FineGrainDifftAnalyzer r = new FineGrainDifftAnalyzer();

	Diff diff2Inserts = r.getDiff(s, t);
	System.out.println(diff2Inserts.getRootOperations());

	ChangePatternSpecification pattern = new ChangePatternSpecification();
	PatternEntity entityIf = new PatternEntity("If");
	ParentPatternEntity parentWrapper = new ParentPatternEntity(entityIf, 3);

	PatternEntity entityAssignement = new PatternEntity("Assignment", parentWrapper);

	PatternAction paInsertAssignment = new PatternAction(entityAssignement, ActionType.INS);
	pattern.addChange(paInsertAssignment);
	PatternAction paInsertIf = new PatternAction(entityIf, ActionType.INS);
	pattern.addChange(paInsertIf);

	PatternRelations calculateRelations = pattern.calculateRelations();
	assertEquals(2, calculateRelations.getPaEntity().size());
	assertEquals(1, calculateRelations.getPaEntity().get(paInsertAssignment).size());
	assertEquals(1, calculateRelations.getPaEntity().get(paInsertIf).size());

	DetectorChangePatternInstanceEngine detector = new DetectorChangePatternInstanceEngine();
	ResultMapping mappings = detector.mappingActions(pattern, diff2Inserts);
	assertFalse(mappings.getMappings().isEmpty());
	assertTrue(mappings.getNotMapped().isEmpty());

	List<ChangePatternInstance> allCombinations = detector.allCombinations(pattern, mappings.getMappings());
	for (ChangePatternInstance changePatternInstance : allCombinations) {
		System.out.println("-->" + changePatternInstance.getActions());
	}

	List<ChangePatternInstance> linkedInstances = detector.calculateValidInstancesFromMapping(pattern,
			mappings.getMappings());
	// Instances
	assertEquals(1, linkedInstances.size());
	// Actions per instance

	assertEquals(2, linkedInstances.get(0).getActions().size());
	System.out.println("final matching:");
	for (ChangePatternInstance finalInstance : linkedInstances) {
		System.out.println("-fi->\n " + finalInstance);
	}
	ChangePatternInstance instance = linkedInstances.get(0);
	MatchingAction maInvo = instance.getMapping().get(paInsertAssignment);
	assertTrue(maInvo.getMatching().get(0).getAffectedNode() instanceof CtAssignment);
}
 
Example #12
Source File: PatternMatchingTest.java    From coming with MIT License 4 votes vote down vote up
@Test
public void testDiff5_Two_patterns_1_instance_each() throws Exception {
	// Method Invocation on if
	System.out.println("Case 2 instances");
	File s = getFile("patterns_examples/case5/1205753_EmbedPooledConnection_0_s.java");
	File t = getFile("patterns_examples/case5/1205753_EmbedPooledConnection_0_t.java");
	FineGrainDifftAnalyzer r = new FineGrainDifftAnalyzer();

	Diff diff2Inserts = r.getDiff(s, t);
	System.out.println(diff2Inserts.getRootOperations());

	ChangePatternSpecification pattern = new ChangePatternSpecification();
	PatternEntity entityIf = new PatternEntity("If");
	ParentPatternEntity parentWrapper = new ParentPatternEntity(entityIf, 3);

	// Pattern 1: if-assignment
	PatternEntity entityAssignement = new PatternEntity("Assignment", parentWrapper);
	PatternAction paInsertAssignment = new PatternAction(entityAssignement, ActionType.INS);
	pattern.addChange(paInsertAssignment);
	PatternAction paInsertIf = new PatternAction(entityIf, ActionType.INS);
	pattern.addChange(paInsertIf);

	PatternRelations calculateRelations = pattern.calculateRelations();
	assertEquals(2, calculateRelations.getPaEntity().size());
	assertEquals(1, calculateRelations.getPaEntity().get(paInsertAssignment).size());
	assertEquals(1, calculateRelations.getPaEntity().get(paInsertIf).size());

	DetectorChangePatternInstanceEngine detector = new DetectorChangePatternInstanceEngine();
	ResultMapping mappings = detector.mappingActions(pattern, diff2Inserts);
	assertFalse(mappings.getMappings().isEmpty());
	assertTrue(mappings.getNotMapped().isEmpty());

	List<ChangePatternInstance> allCombinations = detector.allCombinations(pattern, mappings.getMappings());
	for (ChangePatternInstance changePatternInstance : allCombinations) {
		System.out.println("-->" + changePatternInstance.getActions());
	}

	List<ChangePatternInstance> linkedInstancesPattern1 = detector.calculateValidInstancesFromMapping(pattern,
			mappings.getMappings());
	// Instances
	assertEquals(1, linkedInstancesPattern1.size());
	// Actions per instance
	assertEquals(2, linkedInstancesPattern1.get(0).getActions().size());
	System.out.println("final matching:");
	for (ChangePatternInstance finalInstance : linkedInstancesPattern1) {
		System.out.println("-fi->\n " + finalInstance);
	}

	System.out.println("******Pattern 2*****");

	// Pattern 2- If with invication
	ChangePatternSpecification pattern2 = new ChangePatternSpecification();
	PatternEntity anotherEntityIf = new PatternEntity("If");
	ParentPatternEntity anotherParentWrapper = new ParentPatternEntity(anotherEntityIf, 3);
	PatternEntity entityInvocation = new PatternEntity("Invocation", anotherParentWrapper);

	PatternAction paInsertInvocation = new PatternAction(entityInvocation, ActionType.INS);
	pattern2.addChange(paInsertInvocation);
	PatternAction paAnotherInsertIf = new PatternAction(anotherEntityIf, ActionType.INS);
	pattern2.addChange(paAnotherInsertIf);

	detector = new DetectorChangePatternInstanceEngine();
	ResultMapping mappingsp2 = detector.mappingActions(pattern2, diff2Inserts);
	assertFalse(mappingsp2.getMappings().isEmpty());
	assertTrue(mappingsp2.getNotMapped().isEmpty());

	List<ChangePatternInstance> linkedInstancesPattern2 = detector.calculateValidInstancesFromMapping(pattern2,
			mappingsp2.getMappings());
	assertEquals(1, linkedInstancesPattern2.size());

	/// Now, checking entities
	ChangePatternInstance instanceIfAssignment = linkedInstancesPattern1.get(0);
	MatchingAction maAssigb = instanceIfAssignment.getMapping().get(paInsertAssignment);
	assertTrue(maAssigb.getMatching().get(0).getAffectedNode() instanceof CtAssignment);

	ChangePatternInstance instanceIfInvocation = linkedInstancesPattern2.get(0);
	MatchingAction maInvo = instanceIfInvocation.getMapping().get(paInsertInvocation);
	assertTrue(maInvo.getMatching().get(0).getAffectedNode() instanceof CtInvocation);

	// Now, lets check the poited If
	MatchingAction maifpattern1 = instanceIfAssignment.getMapping().get(paInsertIf);
	MatchingAction maifpattern2 = instanceIfInvocation.getMapping().get(paAnotherInsertIf);

	CtElement affectedNodeIfpattern1 = maifpattern1.getMatching().get(0).getAffectedNode();
	CtElement affectedNodeIfpattern2 = maifpattern2.getMatching().get(0).getAffectedNode();
	assertTrue(affectedNodeIfpattern1 instanceof CtIf);
	assertTrue(affectedNodeIfpattern2 instanceof CtIf);
	assertTrue(affectedNodeIfpattern1 != affectedNodeIfpattern2);
	assertNotEquals(affectedNodeIfpattern1, affectedNodeIfpattern2);
}
 
Example #13
Source File: LabelFinder.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
@Override
public <T, A extends T> void visitCtAssignment(CtAssignment<T, A> e) {
	label = "=";
}
 
Example #14
Source File: VariableResolverTest.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void testBugVariableResolver2() {

	File projectLocation = new File("./examples/exampleVarResolver/");
	AstorMain main1 = new AstorMain();
	Launcher launcher = new Launcher();
	launcher.addInputResource("");

	Factory factory = launcher.createFactory();
	factory.getEnvironment().setComplianceLevel(6);
	SpoonModelBuilder compiler = launcher.createCompiler(factory);
	compiler.setSourceClasspath(dep.split(File.pathSeparator));
	compiler.addInputSource(new File(projectLocation.getAbsolutePath()));
	compiler.build();

	List<CtType<?>> types = factory.Type().getAll();
	assertTrue(types.size() > 0);
	log.info(types.get(0).toString());

	List<CtMethod> mts = new ArrayList<>(types.get(0).getAllMethods());
	CtMethod mt = types.get(0).getAllMethods().stream().filter(x -> x.getSimpleName().equals("test2")).findFirst()
			.get();

	log.debug("Mthd : " + mt);

	CtStatement l1 = mt.getBody().getStatement(1);
	log.debug(l1);
	CtStatement l2 = mt.getBody().getStatement(2);
	log.debug(l2);

	List<CtVariableAccess> vars2 = l2.getElements(new VAFilter());
	log.debug("vars access l2: " + vars2);

	List<CtVariable> fields = l2.getParent(CtClass.class).getFields();

	Map<VarAccessWrapper, List<CtVariable>> mapsVariables = new HashMap<>();

	// let's take the second one (l2) and maps with fields
	mapsVariables.put(new VarAccessWrapper(vars2.get(1)), fields);

	assertTrue(l2.toString().startsWith("l1 = l2"));

	VarMapping vm = new VarMapping(mapsVariables, new ArrayList<>());

	assertTrue(vm.getMappedVariables().size() > 0);

	log.debug(vm.getMappedVariables());

	List<Map<String, CtVariable>> allCombinations = VariableResolver
			.findAllVarMappingCombination(vm.getMappedVariables());

	assertTrue(allCombinations.size() > 0);

	log.debug("Combinations: " + allCombinations);
	Map<VarAccessWrapper, CtVariableAccess> result = VariableResolver.convertIngredient(vm, allCombinations.get(0));

	try {
		// We force to print the line 2 (transformed)
		log.debug(l2);

		assertTrue(l2.toString().startsWith("l1 = f1"));

	} catch (ClassCastException e) {

		e.printStackTrace();
		Assert.fail();
	}
	//
	log.debug("before reset " + l2.toString());

	CtAssignment assingL2 = (CtAssignment) l2;

	CtVariableAccess assignment = (CtVariableAccess) assingL2.getAssignment();

	assertTrue(assignment.getType().toString().startsWith("java.lang.String"));

	// Revert

	VariableResolver.resetIngredient(result);

	assertTrue(l2.toString().startsWith("l1 = l2"));

	log.debug("After reset " + l2.toString());

}
 
Example #15
Source File: VariableResolverTest.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void testBugVariableResolver4() {

	File projectLocation = new File("./examples/exampleVarResolver/");
	AstorMain main1 = new AstorMain();
	Launcher launcher = new Launcher();
	launcher.addInputResource("");

	Factory factory = launcher.createFactory();
	factory.getEnvironment().setComplianceLevel(6);
	SpoonModelBuilder compiler = launcher.createCompiler(factory);
	compiler.setSourceClasspath(dep.split(File.pathSeparator));
	compiler.addInputSource(new File(projectLocation.getAbsolutePath()));
	compiler.build();

	List<CtType<?>> types = factory.Type().getAll();
	assertTrue(types.size() > 0);
	log.info(types.get(0).toString());

	List<CtMethod> mts = new ArrayList<>(types.get(0).getAllMethods());
	CtMethod mt = types.get(0).getAllMethods().stream().filter(x -> x.getSimpleName().equals("test2")).findFirst()
			.get();

	log.debug("Mthd : " + mt);

	CtStatement l2 = mt.getBody().getStatement(2);
	log.debug(l2);

	List<CtVariableAccess> vars2 = l2.getElements(new VAFilter());
	log.debug("vars access l2: " + vars2);

	List<CtVariable> fields = l2.getParent(CtClass.class).getFields();

	Map<VarAccessWrapper, List<CtVariable>> mapsVariables = new HashMap<>();

	// let's take the second one (l1) and maps with fields
	// L1 is a WRITE
	mapsVariables.put(new VarAccessWrapper(vars2.get(0)), fields);

	assertTrue(l2.toString().startsWith("l1 = l2"));

	VarMapping vm = new VarMapping(mapsVariables, new ArrayList<>());

	assertTrue(vm.getMappedVariables().size() > 0);

	log.debug(vm.getMappedVariables());

	List<Map<String, CtVariable>> allCombinations = VariableResolver
			.findAllVarMappingCombination(vm.getMappedVariables());

	assertTrue(allCombinations.size() > 0);

	log.debug("Combinations: " + allCombinations);
	Map<VarAccessWrapper, CtVariableAccess> result = VariableResolver.convertIngredient(vm, allCombinations.get(0));

	try {
		// We force to print the line 2 (transformed)
		log.debug(l2);

		assertTrue(l2.toString().startsWith("f1 = l2"));

	} catch (ClassCastException e) {

		e.printStackTrace();
		Assert.fail();
	}
	//
	// log.debug("before reset " + l2.toString());

	CtAssignment assingL2 = (CtAssignment) l2;

	CtVariableAccess assignment = (CtVariableAccess) assingL2.getAssignment();

	assertTrue(assignment.getType().toString().startsWith("java.lang.String"));

	// Revert

	VariableResolver.resetIngredient(result);

	assertTrue(l2.toString().startsWith("l1 = l2"));

	log.debug("After reset " + l2.toString());

}