Java Code Examples for spoon.reflect.declaration.CtParameter

The following examples show how to use spoon.reflect.declaration.CtParameter. 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
@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 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
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 4
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: 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 5
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: 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 Project: astor   Source File: SupportOperators.java    License: 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 7
Source Project: astor   Source File: MetaGenerator.java    License: 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 8
@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 9
@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 10
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 11
Source Project: coming   Source File: MethodAnalyzer.java    License: 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 12
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 13
Source Project: astor   Source File: WrapwithIfNullCheck.java    License: 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 14
Source Project: astor   Source File: SupportOperators.java    License: 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 Project: astor   Source File: SupportOperators.java    License: 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 16
Source Project: astor   Source File: SupportOperators.java    License: 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 17
Source Project: astor   Source File: SupportOperators.java    License: 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 18
Source Project: astor   Source File: WrapwithIfOp.java    License: 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 19
Source Project: astor   Source File: MetaGenerator.java    License: 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
@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 21
Source Project: astor   Source File: StaSynthBuilder.java    License: 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 22
@Override
public boolean isToBeProcessed(CtParameter<?> element) {
	return !element.getType().isPrimitive();// only for objects
}
 
Example 23
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 4 votes vote down vote up
public CtMethod checkMethodDeclarationWithParemetrCompatibleType(List allMethods, CtTypeReference typeToMatch) {

		for (Object omethod : allMethods) {

			if (!(omethod instanceof CtMethod))
				continue;

			CtMethod anotherMethodInBuggyClass = (CtMethod) omethod;

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

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

					return anotherMethodInBuggyClass;
				}
			}
		}

		return null;
	}
 
Example 24
Source Project: coming   Source File: VariableResolver.java    License: MIT License 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);
	if (parentblock != null) {
		int positionEl = parentblock.getStatements().indexOf(element);
		variables.addAll(VariableResolver.retrieveLocalVariables(positionEl, parentblock));
	}

	return variables;

}
 
Example 25
Source Project: coming   Source File: OriginalFeatureExtractor.java    License: MIT License 4 votes vote down vote up
private EnumSet<ValueFeature> getValueFeature(final String valueStr, final Repair repair, Map<String, CtElement> valueExprInfo) {
        EnumSet<ValueFeature> valueFeatures = EnumSet.noneOf(ValueFeature.class);
        if (repair.oldRExpr != null && repair.newRExpr != null) {
            String oldStr = repair.oldRExpr.toString();
            String newStr = repair.newRExpr.toString();
            if (valueStr.equals(newStr))
                valueFeatures.add(ValueFeature.MODIFIED_VF);
            // I can not figure out the meaning of MODIFIED_SIMILAR_VF
            if (oldStr.length() > 0 && newStr.length() > 0) {
                double ratio = ((double)oldStr.length()) / newStr.length();
                if (ratio > 0.5 && ratio < 2 && oldStr.length() > 3 && newStr.length() > 3)
                    if (oldStr.contains(newStr) || newStr.contains(oldStr))
                        valueFeatures.add(ValueFeature.MODIFIED_SIMILAR_VF);
            }
        }
        CtElement element = repair.dstElem;
        if (element != null) {
            CtMethod FD = element.getParent(new TypeFilter<>(CtMethod.class));
            if (FD != null) {
                for (Object parameter: FD.getParameters()) {
                    if (parameter instanceof CtParameter) {
                        CtParameter VD = (CtParameter) parameter;
                        if (VD.getSimpleName().equals(valueStr))
                            valueFeatures.add(ValueFeature.FUNC_ARGUMENT_VF);
                    }
                }
            }
        }
        assert(valueExprInfo.containsKey(valueStr));
        CtElement E = valueExprInfo.get(valueStr);
        if (E instanceof CtVariableAccess || E instanceof CtArrayAccess || E instanceof CtLocalVariable) {
            if (E instanceof CtLocalVariable) {
                valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
            } else {
                valueFeatures.add(ValueFeature.GLOBAL_VARIABLE_VF);
            }
        } else if (E instanceof CtExecutableReference){
            // just make CALLEE_AF be meaningful
            if (((CtExecutableReference) E).getParameters().size() > 0){
                valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
            }
        } else if (E instanceof CtIf){
            // just make R_STMT_COND_AF be meaningful
            valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
        }
//        if (E instanceof CtVariable) {
//            if (E instanceof CtLocalVariable)
//                valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
//            else
//                valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
//        } else if (E instanceof CtVariableReference) {
//            if (E instanceof CtLocalVariableReference)
//                valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
//            else
//                valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
//        }
        if (valueStr.contains("length") || valueStr.contains("size"))
            valueFeatures.add(ValueFeature.SIZE_LITERAL_VF);
        if (E.getElements(new TypeFilter<>(CtField.class)).size() > 0)
            valueFeatures.add(ValueFeature.MEMBER_VF);
        if (E instanceof CtLiteral) {
            Object value = ((CtLiteral)E).getValue();
            if (value instanceof String) {
                valueFeatures.add(ValueFeature.STRING_LITERAL_VF);
            } else if (value instanceof Integer) { // ?
                if ((Integer) value == 0) {
                    valueFeatures.add(ValueFeature.ZERO_CONST_VF);
                } else {
                    valueFeatures.add(ValueFeature.NONZERO_CONST_VF);
                }
            }
        }
        return valueFeatures;
    }
 
Example 26
Source Project: coming   Source File: S4ROFeatureExtractor.java    License: MIT License 4 votes vote down vote up
private EnumSet<ValueFeature> getValueFeature(final String valueStr, final Repair repair, Map<String, CtElement> valueExprInfo) {
        EnumSet<ValueFeature> valueFeatures = EnumSet.noneOf(ValueFeature.class);
        if (repair.oldRExpr != null && repair.newRExpr != null) {
            String oldStr = repair.oldRExpr.toString();
            String newStr = repair.newRExpr.toString();
            if (valueStr.equals(newStr))
                valueFeatures.add(ValueFeature.MODIFIED_VF);
            // I can not figure out the meaning of MODIFIED_SIMILAR_VF
            if (oldStr.length() > 0 && newStr.length() > 0) {
                double ratio = ((double)oldStr.length()) / newStr.length();
                if (ratio > 0.5 && ratio < 2 && oldStr.length() > 3 && newStr.length() > 3)
                    if (oldStr.contains(newStr) || newStr.contains(oldStr))
                        valueFeatures.add(ValueFeature.MODIFIED_SIMILAR_VF);
            }
        }
        CtElement element = repair.dstElem;
        if (element != null) {
            CtMethod FD = element.getParent(new TypeFilter<>(CtMethod.class));
            if (FD != null) {
                for (Object parameter: FD.getParameters()) {
                    if (parameter instanceof CtParameter) {
                        CtParameter VD = (CtParameter) parameter;
                        if (VD.getSimpleName().equals(valueStr))
                            valueFeatures.add(ValueFeature.FUNC_ARGUMENT_VF);
                    }
                }
            }
        }
        assert(valueExprInfo.containsKey(valueStr));
        CtElement E = valueExprInfo.get(valueStr);
        if (E instanceof CtVariableAccess || E instanceof CtArrayAccess || E instanceof CtLocalVariable) {
            if (E instanceof CtLocalVariable) {
                valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
            } else {
                valueFeatures.add(ValueFeature.GLOBAL_VARIABLE_VF);
            }
        } else if (E instanceof CtExecutableReference){
            // just make CALLEE_AF be meaningful
            if (((CtExecutableReference) E).getParameters().size() > 0){
                valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
            }
        } else if (E instanceof CtIf){
            // just make R_STMT_COND_AF be meaningful
            valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
        }
//        if (E instanceof CtVariable) {
//            if (E instanceof CtLocalVariable)
//                valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
//            else
//                valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
//        } else if (E instanceof CtVariableReference) {
//            if (E instanceof CtLocalVariableReference)
//                valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
//            else
//                valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
//        }
        if (valueStr.contains("length") || valueStr.contains("size"))
            valueFeatures.add(ValueFeature.SIZE_LITERAL_VF);
        if (E.getElements(new TypeFilter<>(CtField.class)).size() > 0)
            valueFeatures.add(ValueFeature.MEMBER_VF);
        if (E instanceof CtLiteral) {
            Object value = ((CtLiteral)E).getValue();
            if (value instanceof String) {
                valueFeatures.add(ValueFeature.STRING_LITERAL_VF);
            } else if (value instanceof Integer) { // ?
                if ((Integer) value == 0) {
                    valueFeatures.add(ValueFeature.ZERO_CONST_VF);
                } else {
                    valueFeatures.add(ValueFeature.NONZERO_CONST_VF);
                }
            }
        }
        return valueFeatures;
    }
 
Example 27
@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<CtInvocation> invocationsFromModifPoints = getInvocations(modificationPoint.getCodeElement());

	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 (CtInvocation invocationToReplace : invocationsFromModifPoints) {

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

		List<Ingredient> ingredients = this.computeIngredientsFromMInvokToReplace(modificationPoint,
				invocationToReplace);

		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 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()));
		}

		variableCounter++;

		MetaGenerator.createMetaForSingleElement(opMega, modificationPoint, invocationToReplace, 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;
}
 
Example 28
Source Project: astor   Source File: ConstReplacementOp.java    License: 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();

	List<MetaOperatorInstance> opsMega = new ArrayList();

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

	List<CtLiteral> literalsInModificationPoints = null;

	if (targetElement == null) {
		literalsInModificationPoints = modificationPoint.getCodeElement()
				.getElements(new TypeFilter<>(CtLiteral.class));
	} else {
		literalsInModificationPoints = new ArrayList<>();
		literalsInModificationPoints.add((CtLiteral) targetElement);
	}

	List<CtLiteral> getAllLiteralsFromClass = modificationPoint.getCtClass()
			.getElements(new TypeFilter<>(CtLiteral.class)).stream().distinct().collect(Collectors.toList());

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

	int variableCounter = 0;
	for (CtLiteral variableAccessToReplace : literalsInModificationPoints) {

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

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

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

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

		// 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);

	opsMega.add(opMega);

	return opsMega;
}
 
Example 29
@Override
public List<MetaOperatorInstance> createMetaOperatorInstances(ModificationPoint modificationPoint) {

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

	// Let's create one meta per modif point
	List<OperatorInstance> metaOperations = new ArrayList();
	List<MetaOperatorInstance> opsMega = new ArrayList();

	// Map that allows to trace the mutant id with the ingredient used
	Map<Integer, Ingredient> ingredientOfMapped = new HashMap<>();

	//
	List<CtVariableAccess> varAccessInModificationPoints = null;

	if (targetElement == null) {
		varAccessInModificationPoints = VariableResolver.collectVariableAccess(modificationPoint.getCodeElement(),
				false);
	} else {
		varAccessInModificationPoints = new ArrayList<>();
		varAccessInModificationPoints.add((CtVariableAccess) targetElement);
	}

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

	MapList<CtTypeReference, CtInvocation> cacheIngredientsPerType = new MapList<>();

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

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

		if (ingredients.isEmpty()) {
			continue;
		}

		// The parameters to be included in the new method
		List<CtVariableAccess> varsToBeParametersTemp = ingredients.stream()
				.map(e -> e.getCode().getElements(new TypeFilter<>(CtVariableAccess.class))).flatMap(List::stream)
				.map(CtVariableAccess.class::cast).distinct().collect(Collectors.toList());

		// The variable to be replaced must also be a parameter

		varsToBeParametersTemp.add(variableAccessToReplace);
		// Let's check the names (the previous filter does not filter all duplicates, so
		// to avoid problems we do it manually):

		List<CtVariableAccess> varsToBeParameters = new ArrayList();
		for (CtVariableAccess parameterFound : varsToBeParametersTemp) {
			boolean hasname = false;
			for (CtVariableAccess parameterConsiderer : varsToBeParameters) {
				if (parameterConsiderer.getVariable().getSimpleName()
						.equals(parameterFound.getVariable().getSimpleName())) {
					hasname = true;
					break;
				}
			}
			// any variable with that name, so we add in parameters
			if (!hasname) {
				varsToBeParameters.add(parameterFound);
			}
		}

		// 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++;

		CtTypeReference returnType = variableAccessToReplace.getType();

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

	} // End variable
	opMega.setOperatorInstances(metaOperations);
	opsMega.add(opMega);
	opMega.setAllIngredients(ingredientOfMapped);
	opMega.setOperationApplied(this);
	opMega.setOriginal(modificationPoint.getCodeElement());
	opMega.setModificationPoint(modificationPoint);

	return opsMega;
}
 
Example 30
@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;
}