spoon.reflect.declaration.CtParameter Java Examples

The following examples show how to use spoon.reflect.declaration.CtParameter. 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: MetaGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static MetaOperatorInstance createMetaFineGrainedReplacement(ModificationPoint modificationPoint,
		CtExpression elementSource, 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<>();

	createMetaForSingleElement(opMega, modificationPoint, elementSource, variableCounter, ingredients, parameters,
			realParameters, returnType, opsOfVariant, ingredientOfMapped);

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

	return opMega;
}
 
Example #2
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T> void visitCtConstructorCall(CtConstructorCall<T> ctConstructorCall) {
	super.visitCtConstructorCall(ctConstructorCall);
	
	String type = ctConstructorCall.getType().getQualifiedName();
	List<CtExpression<?>>  argumentlist = ctConstructorCall.getArguments();
	List<String> orig = resolveTypes(argumentlist);

	CtClass classname = parser.getClassMap().get(type); 
	
	if(classname!=null) {
		Set<CtConstructor<T>> constructors=classname.getConstructors();
           for(CtConstructor constructor:constructors) {
           	List<CtParameter> paramlist=constructor.getParameters();
           	List<String> target=resolveParams(paramlist);
           	transformOneMethod(orig,target,ctConstructorCall);
           }
	} else {
		List<Class[]> params = parser.fetchMethods(type, type);
		for (Class[] p : params)
			transformOneConstructor(orig, ctConstructorCall, p);
	}
}
 
Example #3
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private void fetchLibOverload(CtInvocation call) {
       
	List<String> origTypes = resolveTypes(call.getArguments());
	CtExpression exp = call.getTarget();
	String typename=exp.getType().getQualifiedName();
	if(typename==null||typename.isEmpty())
		return;
	
       CtClass classname = parser.getClassMap().get(typename); 

	if(classname!=null) {
		Set<CtMethod> overloadmethods=classname.getMethods();
           for(CtMethod methodoverloaded : overloadmethods) {
           	if(call.getExecutable().getSimpleName().equals(methodoverloaded.getSimpleName())) {
           	  List<CtParameter> paramlist=methodoverloaded.getParameters();
           	  List<String> target=resolveParams(paramlist);
           	  transformOneMethod(origTypes,target, call);
           	}
           }
	} else {
		List<Class[]> params = parser.fetchMethods(typename, call.getExecutable().getSimpleName());
		for (Class[] p : params)
			transformOneConstructor(origTypes, call, p);
	}
}
 
Example #4
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static List<CtExpression> checkOcurrenceOfOtherParameters(CtMethod anotherMethod, CtMethod affectedMethod,
		List realParameters) {

	List newRealParameters = new ArrayList();

	for (Object parameterFromAnotherM : anotherMethod.getParameters()) {
		CtParameter parAnother = (CtParameter) parameterFromAnotherM;

		int indexOfParameter = affectedMethod.getParameters().indexOf(parAnother);
		// The parameter does not exist in the previous version
		if (indexOfParameter < 0) {
			return null;
		} else {
			CtExpression parameterAtI = (CtExpression) realParameters.get(indexOfParameter);
			newRealParameters.add(parameterAtI);
		}

	}
	// all parameters exist
	return newRealParameters;
}
 
Example #5
Source File: LogicalExpressionAnalyzer.java    From coming with MIT License 6 votes vote down vote up
/**
 * Check if a method declaration has a parameter compatible with that one from
 * the var affected
 * 
 * @param allMethods
 * @param varAffected
 * @return
 */
public CtMethod checkBooleanMethodDeclarationWithTypeInParameter(List allMethods, CtVariableAccess varAffected) {
	
	for (Object omethod : allMethods) {

		if (!(omethod instanceof CtMethod))
			continue;

		CtMethod anotherMethodInBuggyClass = (CtMethod) omethod;

		for (Object oparameter : anotherMethodInBuggyClass.getParameters()) {
			CtParameter parameter = (CtParameter) oparameter;

			if (compareTypes(varAffected.getType(), parameter.getType())) {
				if (anotherMethodInBuggyClass.getType().unbox().toString().equals("boolean")) {

					return anotherMethodInBuggyClass;
				}
			}
		}
	}
	return null;
}
 
Example #6
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 6 votes vote down vote up
/**
 * Check if a method declaration has a parameter compatible and return with the
 * cttype as argument
 * 
 * @param allMethods
 * @param typeToMatch
 * @return
 */
public CtMethod checkMethodDeclarationWithParameterReturnCompatibleType(List allMethods,
		CtTypeReference typeToMatch) {
	for (Object omethod : allMethods) {

		if (!(omethod instanceof CtMethod))
			continue;

		CtMethod anotherMethodInBuggyClass = (CtMethod) omethod;

		// Check the parameters
		for (Object oparameter : anotherMethodInBuggyClass.getParameters()) {
			CtParameter parameter = (CtParameter) oparameter;

			if (compareTypes(typeToMatch, parameter.getType())
					&& compareTypes(typeToMatch, anotherMethodInBuggyClass.getType())) {

				return anotherMethodInBuggyClass;
			}
		}
	}

	return null;
}
 
Example #7
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 #8
Source File: BoundTemplateProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
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 #9
Source File: NotNullCheckAdderProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void process(CtParameter<?> element) {
	// we declare a new snippet of code to be inserted.
	CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();

	// this snippet contains an if check.
	final String value = String.format("if (%s == null) "
			+ "throw new IllegalArgumentException(\"[Spoon inserted check] null passed as parameter\");",
			element.getSimpleName());
	snippet.setValue(value);

	// we insert the snippet at the beginning of the method body.
	if (element.getParent(CtExecutable.class).getBody() != null) {
		element.getParent(CtExecutable.class).getBody().insertBegin(snippet);
	}
}
 
Example #10
Source File: WrapwithIfOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<MetaOperatorInstance> createMetaOperatorInstances(ModificationPoint modificationPoint,
		List<IngredientFromDyna> ingredients) {

	// The parameters to be included in the new method
	List<CtVariableAccess> varsToBeParameters = SupportOperators.collectAllVarsFromDynaIngredients(ingredients,
			modificationPoint);

	// List of parameters
	List<CtParameter<?>> parameters = new ArrayList<>();
	List<CtExpression<?>> realParameters = new ArrayList<>();
	for (CtVariableAccess ctVariableAccess : varsToBeParameters) {
		// the parent is null, it is setter latter
		CtParameter pari = MutationSupporter.getFactory().createParameter(null, ctVariableAccess.getType(),
				ctVariableAccess.getVariable().getSimpleName());
		parameters.add(pari);
		realParameters.add(ctVariableAccess.clone().setPositions(new NoSourcePosition()));
	}

	// let's start with one, and let's keep the Zero for the default (all ifs are
	// false)
	int candidateNumber = 0;
	CtTypeReference returnType = MutationSupporter.getFactory().createCtTypeReference(Boolean.class);

	CtElement codeElement = (targetElement == null) ? modificationPoint.getCodeElement() : targetElement;

	// let's create the meta

	MetaOperatorInstance megaOp = MetaGenerator.createMetaStatementReplacement(modificationPoint, codeElement,
			MutationSupporter.getFactory().createCodeSnippetExpression("true"), candidateNumber,
			ingredients.stream().map(Ingredient.class::cast).collect(Collectors.toList())//
			, parameters, realParameters, this, returnType);
	List<MetaOperatorInstance> opsMega = new ArrayList();
	opsMega.add(megaOp);

	return opsMega;
}
 
Example #11
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static boolean checkOcurrenceOfOtherParameters(CtMethod anotherMethod, CtMethod affectedMethod) {
	// anotherMethod.getParameters().stream().map(CtParameter.class::cast)
	// .collect(Collectors.toList()

	for (Object parameterFromAnotherM : anotherMethod.getParameters()) {
		CtParameter parAnother = (CtParameter) parameterFromAnotherM;

		// The parameter does not exist in the previous version
		if (!affectedMethod.getParameters().contains(parAnother)) {
			return false;
		}
	}
	// all parameters exist
	return true;
}
 
Example #12
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static long getMaxCombinations(List<CtParameter> parameterType, MapList<CtTypeReference, CtElement> types) {

		long max = 1;
		for (CtParameter ctTypeParameter : parameterType) {

			max *= types.get(ctTypeParameter.getType()).size();

		}
		int maxComb = ConfigurationProperties.getPropertyInt("maxVarCombination");
		if (max > maxComb || max < 0) {
			return (int) maxComb;
		}

		return max;
	}
 
Example #13
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static List<List<CtExpression<?>>> createAllParametersCombinations(List<CtParameter> parameterType,
		MapList<CtTypeReference, CtElement> candidateMappings) {
	List<List<CtExpression<?>>> candidateArguments = new ArrayList();

	long maxCombinations = getMaxCombinations(parameterType, candidateMappings);
	// number of arguments
	for (int i = 0; i < maxCombinations; i++) {
		List<CtExpression<?>> callArguments = new ArrayList();
		for (CtParameter ctTypeParameter : parameterType) {

			List<CtElement> compVar = candidateMappings.get(ctTypeParameter.getType());
			CtElement elSelected = compVar.get(RandomManager.nextInt(compVar.size()));
			if (elSelected instanceof CtVariable) {
				CtVariable varSelected = (CtVariable) elSelected;
				callArguments.add(MutationSupporter.getFactory().createVariableRead(varSelected.getReference(),
						varSelected.isStatic()));
			} else {
				if (elSelected instanceof CtExpression) {
					// for the moment, we dont clone
					callArguments.add((CtExpression<?>) elSelected);
				}
			}

		}
		// check if the arguments are not already considered
		if (!candidateArguments.contains(callArguments)) {
			candidateArguments.add(callArguments);
		}
	}
	return candidateArguments;
}
 
Example #14
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static List<List<CtExpression<?>>> computeParameters(CtMethod anotherMethod, ModificationPoint point) {

		List<CtVariable> variablesInScope = point.getContextOfModificationPoint();

		List<CtParameter> parameterTypes = anotherMethod.getParameters();

		MapList<CtTypeReference, CtElement> candidateMappings = new MapList<>();
		// Groups vars according to types
		for (CtParameter ctTypeParameter : parameterTypes) {
			CtTypeReference parType = ctTypeParameter.getType();

			if (!candidateMappings.containsKey(parType)) {
				List compatible = variablesInScope.stream().filter(e -> e.getType().isSubtypeOf(parType))
						.collect(Collectors.toList());
				// A par without a var
				if (compatible.isEmpty())
					return null;

				candidateMappings.put(parType, compatible);

			}

		}
		List<List<CtExpression<?>>> candidateArguments = createAllParametersCombinations(parameterTypes,
				candidateMappings);

		return candidateArguments;
	}
 
Example #15
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private List<String> resolveParams(List<CtParameter> origParam) {
	List<String> types = new ArrayList<String>();
	for (int i = 0; i < origParam.size(); i++) {
		String type =  origParam.get(i).getType().getQualifiedName();
	//	type = objToPrim.containsKey(type) ? objToPrim.get(type) : type;
		types.add(type);
		if (!typeCandidates.containsKey(type))
			typeCandidates.put(type, ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype));
	}
	return types; 
}
 
Example #16
Source File: TestExecutorProcessor.java    From nopol with 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 #17
Source File: WrapwithIfNullCheck.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public List<MetaOperatorInstance> createMetaOperatorInstances(ModificationPoint modificationPoint) {

		//
		CtElement codeElement = (targetElement == null) ? modificationPoint.getCodeElement() : targetElement;

		List<CtVariableAccess> varAccessInModificationPoints = VariableResolver.collectVariableAccess(codeElement);

		List<Ingredient> ingredients = this.computeIngredientsNullCheck(modificationPoint,
				varAccessInModificationPoints);

		// The parameters to be included in the new method
		List<CtVariableAccess> varsToBeParameters = varAccessInModificationPoints;

		// List of parameters
		List<CtParameter<?>> parameters = new ArrayList<>();
		List<CtExpression<?>> realParameters = new ArrayList<>();
		for (CtVariableAccess ctVariableAccess : varsToBeParameters) {
			// the parent is null, it is setter latter
			CtParameter pari = MutationSupporter.getFactory().createParameter(null, ctVariableAccess.getType(),
					ctVariableAccess.getVariable().getSimpleName());
			parameters.add(pari);
			realParameters.add(ctVariableAccess.clone().setPositions(new NoSourcePosition()));
		}
///
		// let's start with one, and let's keep the Zero for the default (all ifs are
		// false)
		int candidateNumber = 0;
		CtTypeReference returnType = MutationSupporter.getFactory().createCtTypeReference(Boolean.class);

		MetaOperatorInstance megaOp = MetaGenerator.createMetaStatementReplacement(modificationPoint, codeElement,
				MutationSupporter.getFactory().createCodeSnippetExpression("true"), candidateNumber, ingredients,
				parameters, realParameters, this, returnType);
		List<MetaOperatorInstance> opsMega = new ArrayList();
		opsMega.add(megaOp);

		return opsMega;
	}
 
Example #18
Source File: VarReplacementByAnotherVarOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected List<Ingredient> computeIngredientsFromVarToReplace(ModificationPoint modificationPoint,
		CtVariableAccess variableAccessToReplace) {

	List<Ingredient> ingredients = new ArrayList<>();
	List<CtVariable> varsInContext = modificationPoint.getContextOfModificationPoint();

	for (CtVariable iVarInContext : varsInContext) {

		boolean compatibleVariables = VariableResolver.areVarsCompatible(variableAccessToReplace, iVarInContext);
		if (!compatibleVariables
				|| iVarInContext.getSimpleName().equals(variableAccessToReplace.getVariable().getSimpleName())) {
			continue;
		}

		CtParameter pr = MutationSupporter.getFactory().createParameter(null, iVarInContext.getType(),
				iVarInContext.getSimpleName());

		CtVariableAccess iVarAccessFromContext = MutationSupporter.getFactory()
				.createVariableRead(pr.getReference(), false);

		Ingredient ingredient = new Ingredient(iVarAccessFromContext);
		// we use this property to indicate the old variable to replace
		ingredient.setDerivedFrom(variableAccessToReplace);
		ingredients.add(ingredient);

	}

	return ingredients;
}
 
Example #19
Source File: MetaGenerator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static List<CtParameter<?>> filterParameters(List<CtParameter<?>> parameters) {
	List<CtParameter<?>> parametersN = new ArrayList<>();
	Set<String> seen = new HashSet();
	for (CtParameter<?> ctParameter : parameters) {
		if (!seen.contains(ctParameter.getSimpleName())) {
			parametersN.add(ctParameter);
			seen.add(ctParameter.getSimpleName());
		}
	}

	return parametersN;
}
 
Example #20
Source File: StaSynthBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unused" })
private List<List<CtExpression>> createAllPossibleArgsListForMethod(CtMethod method, List<CtExpression> variables) {
	try {

		List<CtParameter> argumentTypes = method.getParameters();
		List<List<CtExpression>> argumentCandidates = new ArrayList<>();
		for (int j = 0; j < argumentTypes.size(); j++) {
			CtParameter par = argumentTypes.get(j);

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

			for (CtExpression ctVariableRead : variables) {

				if (ctVariableRead.getType().isSubtypeOf(par.getType())) {
					compatiblePar.add(ctVariableRead);
				}

			}
			argumentCandidates.add(compatiblePar);
		}
		return argumentCandidates;

	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #21
Source File: MethodAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private boolean checkTypeInParameter(CtMethod anotherMethod, CtExecutableReference minvokedInAffected) {
	
	for (Object oparameter : anotherMethod.getParameters()) {
		CtParameter parameter = (CtParameter) oparameter;

		if (compareTypes(minvokedInAffected.getType(), parameter.getType())) {
			return true;
		}
	}
	return false;
}
 
Example #22
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 #23
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static List<CtInvocation> createRealInvocationsReusingVars(ModificationPoint point, CtMethod anotherMethod,
		CtInvocation invocationToReplace) {

	List<CtParameter> parameterTypes = anotherMethod.getParameters();
	CtExpression target = invocationToReplace.getTarget();
	MapList<CtTypeReference, CtElement> candidateMappings = new MapList<>();

	List<CtVariable> variablesInScope = point.getContextOfModificationPoint();

	for (CtParameter aParameterAnotherMethod : parameterTypes) {

		CtTypeReference aTypePar = aParameterAnotherMethod.getType();

		List similarExpression = (List<CtExpression>) invocationToReplace.getArguments().stream()
				// .filter(e -> e.equals(aTypePar)).collect(Collectors.toList());
				.filter(e -> ((CtExpression) e).getType().equals(aTypePar)).collect(Collectors.toList());
		// TODO: put a configuration point here.
		if (similarExpression.size() > 0) {

			if (!candidateMappings.containsKey(aTypePar)) {

				candidateMappings.put(aTypePar, similarExpression);
			}

		} else {

			if (!candidateMappings.containsKey(aTypePar)) {
				List compatible = variablesInScope.stream().filter(e -> e.getType().isSubtypeOf(aTypePar))
						.collect(Collectors.toList());
				// A par without a var
				if (compatible.isEmpty())
					return null;

				candidateMappings.put(aTypePar, compatible);
			}
		}

	}

	List<List<CtExpression<?>>> candidateArguments = createAllParametersCombinations(parameterTypes,
			candidateMappings);

	if (candidateArguments == null || candidateArguments.isEmpty())
		return Collections.EMPTY_LIST;

	List<CtInvocation> newInvocations = realInvocationsFromCombination(anotherMethod, target, candidateArguments);

	return newInvocations;
}
 
Example #24
Source File: MethodInstantialization.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public MethodInstantialization(CtMethod method,
		Map<CtParameter, List> candidates) {
	super();
	this.method = method;
	this.candidates = candidates;
}
 
Example #25
Source File: MethodInstantialization.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Map<CtParameter, List> getCandidates() {
	return candidates;
}
 
Example #26
Source File: MethodInstantialization.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void setCandidates(Map<CtParameter, List> candidates) {
	this.candidates = candidates;
}
 
Example #27
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns all variables in scope, reachable from the ctelement passes as
 * argument
 * 
 * @param element
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<CtVariable> searchVariablesInScope(CtElement element) {
	List<CtVariable> variables = new ArrayList();

	if (element == null) {
		return variables;
	}

	if (element instanceof CtField) {
		return variables;
	}
	// We find the CtClass and returns the fields
	CtClass ctclass = element.getParent(CtClass.class);
	if (ctclass != null) {
		Collection<CtFieldReference<?>> vars = ctclass.getAllFields();
		for (CtFieldReference<?> ctFieldReference : vars) {
			// We dont add private fields from parent classes
			if ((!ctFieldReference.getModifiers().contains(ModifierKind.PRIVATE)
					|| ctclass.getFields().contains(ctFieldReference.getDeclaration()))) {

				// We ignore "serialVersionUID'
				if ((ctFieldReference.getDeclaration() != null)
						&& !"serialVersionUID".equals(ctFieldReference.getDeclaration().getSimpleName()))
					variables.add(ctFieldReference.getDeclaration());
			}
		}

	}

	// We find the parent method and we extract the parameters
	CtMethod method = element.getParent(CtMethod.class);
	if (method != null) {
		List<CtParameter> pars = method.getParameters();
		for (CtParameter ctParameter : pars) {
			variables.add(ctParameter);
		}
	}

	// We find the parent block and we extract the local variables before
	// the element under analysis
	CtBlock parentblock = element.getParent(CtBlock.class);
	CtElement currentElement = element;
	if (parentblock != null) {
		int positionEl = parentblock.getStatements().indexOf(currentElement);
		variables.addAll(VariableResolver.retrieveLocalVariables(positionEl, parentblock));
		if (ConfigurationProperties.getPropertyBool("consideryvarloops")) {
			variables.addAll(getVarsInFor(currentElement));
			variables.addAll(getVarsInForEach(currentElement));
		}

	}

	return variables;

}
 
Example #28
Source File: MetaGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static void createMetaForSingleElement(MetaOperatorInstance opMega, ModificationPoint modificationPoint,
		CtExpression elementSource, int variableCounter, List<Ingredient> ingredients,
		List<CtParameter<?>> parameters, List<CtExpression<?>> realParameters, CtTypeReference returnType,
		List<OperatorInstance> opsOfVariant, Map<Integer, Ingredient> ingredientOfMapped) {
	CtExpression defaultReturnElement = elementSource;

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

	// Invocation to mega
	CtInvocation newInvocationToMega = creationInvocationToMega(modificationPoint, realParameters, megaMethod);

	//
	for (Ingredient ingredient : ingredients) {
		ingredient.getMetadata().put("meta_object", newInvocationToMega);
	}

	// Now the if to be inserted:
	// 1:

	// Let's create the operations

	OperatorInstance opInvocation = new OperatorInstance();
	opInvocation.setOperationApplied(new FineGrainedExpressionReplaceOperator());
	opInvocation.setOriginal(elementSource);
	opInvocation.setModified(newInvocationToMega);
	opInvocation.setModificationPoint(modificationPoint);

	opsOfVariant.add(opInvocation);

	// 2:
	// 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);
}
 
Example #29
Source File: MethodXMethodReplacementOp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public List<MetaOperatorInstance> createMetaOperatorInstances(ModificationPoint modificationPoint) {

	List<MetaOperatorInstance> opsMega = new ArrayList();

	MapList<CtInvocation, Ingredient> ingredientsPerInvocation = this
			.retrieveInvocationIngredient(modificationPoint);
	if (ingredientsPerInvocation.isEmpty()) {
		log.debug("Any ingredient (other invocations) for modif point " + modificationPoint.identified);
		// Nothing to replace
		return opsMega;
	}

	log.debug("\nMethodInvoReplacement: \n" + modificationPoint);

	// let's start with one, and let's keep the Zero for the default (all ifs are
	// false)

	// As difference with var replacement, a metamutant for each invocation
	for (CtInvocation invocationToReplace : ingredientsPerInvocation.keySet()) {

		int invocationCounter = 0;

		List<Ingredient> ingredients = ingredientsPerInvocation.get(invocationToReplace);

		List<CtVariableAccess> varsToBeParameters = new ArrayList<>();

		// The parameters to be included in the new method
		for (Ingredient ingredient : ingredients) {
			SupportOperators.putVarsNotDuplicated(ingredient.getCode(), varsToBeParameters);

		}

		// The variable from the existing invocation must also be a parameter
		SupportOperators.putVarsNotDuplicated(modificationPoint.getCodeElement(), varsToBeParameters);

		// List of parameters
		List<CtParameter<?>> parameters = new ArrayList<>();
		List<CtExpression<?>> realParameters = new ArrayList<>();
		for (CtVariableAccess ctVariableAccess : varsToBeParameters) {
			// the parent is null, it is setter latter
			CtParameter pari = MutationSupporter.getFactory().createParameter(null, ctVariableAccess.getType(),
					ctVariableAccess.getVariable().getSimpleName());
			parameters.add(pari);
			realParameters.add(ctVariableAccess.clone().setPositions(new NoSourcePosition()));
		}

		invocationCounter++;

		/// Let's start creating the body of the new method.
		// first the main try
		CtTypeReference returnTypeOfInvocation = invocationToReplace.getType();

		MetaOperatorInstance megaOp = MetaGenerator.createMetaFineGrainedReplacement(modificationPoint,
				invocationToReplace, invocationCounter, ingredients, parameters, realParameters, this,
				returnTypeOfInvocation);
		opsMega.add(megaOp);

	} // End invocation

	return opsMega;
}
 
Example #30
Source File: VarReplacementByAnotherVarOp.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public List<MetaOperatorInstance> createMetaOperatorInstances(ModificationPoint modificationPoint) {

	MetaOperatorInstance opMega = new MetaOperatorInstance(this, MetaGenerator.getNewIdentifier());

	List<OperatorInstance> opsOfVariant = new ArrayList();

	Map<Integer, Ingredient> ingredientOfMapped = new HashMap<>();

	//
	List<CtVariableAccess> varAccessInModificationPoints = null;

	if (targetElement == null) {
		varAccessInModificationPoints = VariableResolver.collectVariableAccess(modificationPoint.getCodeElement(),
				// it must be true because, even we have vars with different names, they are
				// different access.
				true);
	} else {
		varAccessInModificationPoints = new ArrayList<>();
		varAccessInModificationPoints.add((CtVariableAccess) targetElement);
	}

	log.debug("\nModifcationPoint: \n" + modificationPoint);

	// let's start with one, and let's keep the Zero for the default (all ifs are
	// false)
	// TODO: we only can activate one mutant

	int variableCounter = 0;
	for (CtVariableAccess variableAccessToReplace : varAccessInModificationPoints) {

		// The return type of the new method correspond to the type of variable to
		// change
		CtTypeReference returnType = variableAccessToReplace.getType();

		List<Ingredient> ingredients = this.computeIngredientsFromVarToReplace(modificationPoint,
				variableAccessToReplace);

		if (ingredients.isEmpty()) {
			// Nothing to replace
			continue;
		}

		// The parameters to be included in the new method
		List<CtVariableAccess> varsToBeParameters = ingredients.stream().map(e -> e.getCode())
				.map(CtVariableAccess.class::cast).collect(Collectors.toList());
		// The variable to be replaced must also be a parameter
		varsToBeParameters.add(variableAccessToReplace);

		// List of parameters
		List<CtParameter<?>> parameters = new ArrayList<>();
		List<CtExpression<?>> realParameters = new ArrayList<>();
		for (CtVariableAccess ctVariableAccess : varsToBeParameters) {
			// the parent is null, it is setter latter
			CtParameter pari = MutationSupporter.getFactory().createParameter(null, ctVariableAccess.getType(),
					ctVariableAccess.getVariable().getSimpleName());
			parameters.add(pari);
			realParameters.add(ctVariableAccess.clone().setPositions(new NoSourcePosition()));
		}

		variableCounter++;

		MetaGenerator.createMetaForSingleElement(opMega, modificationPoint, variableAccessToReplace,
				variableCounter, ingredients, parameters, realParameters, returnType, opsOfVariant,
				ingredientOfMapped);

	} // End variable

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

	List<MetaOperatorInstance> opsMega = new ArrayList();
	opsMega.add(opMega);

	return opsMega;
}