Java Code Examples for spoon.reflect.declaration.CtVariable

The following examples show how to use spoon.reflect.declaration.CtVariable. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: coming   Source File: VariableAnalyzer.java    License: MIT License 6 votes vote down vote up
private void analyzV10_AffectedWithCompatibleTypes(List<CtVariableAccess> varsAffected, List<CtVariable> varsInScope,
		CtElement element, Cntx<Object> context) {
	try {
		
		for (CtVariableAccess aVariableAccessInStatement : varsAffected) {
			boolean currentHasSimType = false;
			for (CtVariable aVariableInScope : varsInScope) {
				if (!aVariableInScope.getSimpleName().equals(aVariableAccessInStatement.getVariable().getSimpleName())) {
					if (compareTypes(aVariableInScope.getType(), aVariableAccessInStatement.getType())) {
						currentHasSimType=true;
						break;
					}
				}
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(aVariableAccessInStatement),
					CodeFeatures.V10_VAR_TYPE_Similar_VAR, currentHasSimType, "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 2
Source Project: coming   Source File: ConstantAnalyzer.java    License: MIT License 6 votes vote down vote up
public boolean compareLiteralAndConstantType(String literaltype, CtVariable var) {
	
	Boolean typecompatiable=false;
	if(var.getType().toString().toLowerCase().endsWith("string")) {
		if(literaltype.equals("string"))
		    typecompatiable=true; 
	}
	else  {
	    if(var.getType().isPrimitive()) {
		   if(var.getType().toString().toLowerCase().endsWith("char")) {
			   if(literaltype.equals("char"))
				   typecompatiable=true; 
		   }
		   else if(var.getType().toString().toLowerCase().endsWith("boolean")) {
			   if(literaltype.equals("boolean"))
			       typecompatiable=true; 
		   }
		   else {
			   if(literaltype.equals("numerical"))
			       typecompatiable=true; 
		   }
	    }
	}
	return typecompatiable;
}
 
Example 3
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 6 votes vote down vote up
private void analyzeM5(CtElement element, Cntx<Object> context, List<CtInvocation> invocations,
		List<CtVariable> varsInScope) {
	
	try {
		for (CtInvocation invocation : invocations) {
			boolean currentInvocationWithCompVar = false;
			CtTypeReference type = invocation.getType();

			if (type != null) {
				// for the variables in scope
				for (CtVariable varInScope : varsInScope) {
					if (compareTypes(type, varInScope.getType())) {
						currentInvocationWithCompVar = true;
						break;
					}
				}
			}

			writeGroupedInfo(context, adjustIdentifyInJson(invocation),
					CodeFeatures.M5_MI_WITH_COMPATIBLE_VAR_TYPE, 
					currentInvocationWithCompVar, "FEATURES_METHODS");			
		}
	  } catch (Exception e) {
	}
}
 
Example 4
Source Project: coming   Source File: VariableResolver.java    License: MIT License 6 votes vote down vote up
/**
 * For a given VariableAccess, we search the list of Variables contains
 * compatible types (i.e. sub types)
 * 
 * @param varContext
 * @param vartofind
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected static List<CtVariable> compatiblesSubType(List<CtVariable> varContext, CtTypeReference typeToFind) {

	List<CtVariable> result = new ArrayList<CtVariable>();

	for (CtVariable ctVariable_i : varContext) {

		CtTypeReference typeref_i = ctVariable_i.getType();
		try {
			if (typeref_i.isSubtypeOf(typeToFind)) {
				result.add(ctVariable_i);
			}
		} catch (Exception e) {
			result.add(ctVariable_i);
		}

	}
	return result;
}
 
Example 5
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a map between the variables with name conflicts.
 * 
 * @param varsFromContext
 * @param varInductionCollected
 * @return
 */
public static Map<CtVariableAccess, List<CtVariable>> searchVarNameConflicts(List<CtVariable> varsFromContext,
		List<CtVariableAccess> varInductionCollected) {

	Map<CtVariableAccess, List<CtVariable>> mappingConflicts = new HashMap<>();

	for (CtVariableAccess inductionVar : varInductionCollected) {

		List<CtVariable> varsConf = new ArrayList<>();
		String nameInduction = inductionVar.getVariable().getSimpleName();

		for (CtVariable ctVariableContext : varsFromContext) {
			String nameVarContexr = ctVariableContext.getSimpleName();
			if (nameInduction.equals(nameVarContexr)) {
				varsConf.add(ctVariableContext);
			}
		}
		if (varsConf.size() > 0) {
			mappingConflicts.put(inductionVar, varsConf);
		}

	}
	return mappingConflicts;
}
 
Example 6
Source Project: coming   Source File: VariableResolver.java    License: MIT License 6 votes vote down vote up
/**
 * It retrieves all variables access which declarations are inside the
 * ingredient.
 * 
 * @param ingredientRootElement
 * @param varAccessCollected
 * @return
 */
public static List<CtVariableAccess> collectInductionVariableAccess(CtElement ingredientRootElement,
		List<CtVariableAccess> varAccessCollected) {

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

	for (CtVariableAccess ctVariableAccess : varAccessCollected) {

		CtVariableReference varref = ctVariableAccess.getVariable();

		// We are interesting in induction vars, they are modeled as
		// LocalVariables
		if (!(varref instanceof CtLocalVariableReference))
			continue;

		CtVariable var = varref.getDeclaration();

		boolean insideIngredient = checkParent(var, ingredientRootElement);
		if (insideIngredient)
			induction.add(ctVariableAccess);

	}
	return induction;
}
 
Example 7
Source Project: coming   Source File: VariableResolver.java    License: MIT License 6 votes vote down vote up
/**
 * 
 * @param var
 * @param rootElement
 * @return
 */
private static boolean checkParent(CtVariable var, CtElement rootElement) {

	if (rootElement == null)
		logger.error("Error! root element null");
	CtElement parent = var;
	while (parent != null
			&& !(parent instanceof CtPackage)/*
												 * && !CtPackage. TOP_LEVEL_PACKAGE_NAME. equals(parent.toString())
												 */) {
		if (parent.equals(rootElement))
			return true;
		parent = parent.getParent();
	}

	return false;
}
 
Example 8
Source Project: coming   Source File: ASTData.java    License: MIT License 6 votes vote down vote up
public ASTData(CtElement rootNode) {
	executableInvocations = new HashSet<>();
	variablesAndLiterals = new HashSet<>();

	List<CtElement> allElements = rootNode.getElements(null);
	for (CtElement element : allElements) {
		if (element instanceof CtAbstractInvocation) {
			executableInvocations.add(getExecutableQualifiedSignature(element));
		} else if (element instanceof CtVariableAccess || element instanceof CtLiteral) {
			variablesAndLiterals.add(ASTInfoResolver.getCleanedName(element));
		} else if (element instanceof CtMethod) {
			executableInvocations.add(getExecutableQualifiedSignature(element));
		} else if (element instanceof CtVariable) {
			variablesAndLiterals
					.add(ASTInfoResolver.getCleanedName(((CtVariable) element).getReference().toString()));
			if (element instanceof CtField) {
				variablesAndLiterals.add(ASTInfoResolver.getCleanedName(((CtField) element).getSimpleName()));
			}
		}
	}
}
 
Example 9
Source Project: coming   Source File: ASTData.java    License: MIT License 6 votes vote down vote up
public boolean canArjaFindVarsAndMethods(CtElement target) {
	List<CtElement> allElements = target.getElements(null);

	for (CtElement element : allElements) {
		if (element instanceof CtAbstractInvocation) {
			if (!executableInvocations.contains(getExecutableQualifiedSignature(element)))
				return false;
		} else if (element instanceof CtVariableAccess) {
			if (!variablesAndLiterals.contains(ASTInfoResolver.getCleanedName(element)))
				return false;
		} else if (element instanceof CtVariable) {
			if (!variablesAndLiterals
					.contains(ASTInfoResolver.getCleanedName(((CtVariable) element).getReference().toString())))
				return false;
		}
	}

	return true;
}
 
Example 10
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @param var
 * @param rootElement
 * @return
 */
private static boolean checkParent(CtVariable var, CtElement rootElement) {

	if (rootElement == null)
		logger.error("Error! root element null");
	CtElement parent = var;
	while (parent != null
			&& !(parent instanceof CtPackage)/*
												 * && !CtPackage. TOP_LEVEL_PACKAGE_NAME. equals(parent.toString())
												 */) {
		if (parent.equals(rootElement))
			return true;
		parent = parent.getParent();
	}

	return false;
}
 
Example 11
Source Project: astor   Source File: VarMappingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testIngredientWithoutVars() {
	// We will try to put c3 (clearResult()) in c1.
	List<CtVariable> varContextC1 = VariableResolver.searchVariablesInScope(c1);

	VarMapping vmapping2 = VariableResolver.mapVariablesUsingCluster(varContextC1, c3);
	// As the ingredient has not value, all collections must be empty
	assertTrue(vmapping2.getNotMappedVariables().isEmpty());
	assertTrue(vmapping2.getNotMappedVariables().isEmpty());

	List<Map<String, CtVariable>> allCombinationsOne = VariableResolver
			.findAllVarMappingCombination(vmapping2.getMappedVariables());

	log.debug(allCombinationsOne);
	assertTrue(allCombinationsOne.isEmpty());

}
 
Example 12
Source Project: astor   Source File: AddAssignmentOp.java    License: 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 13
Source Project: astor   Source File: PatchGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public List<VarCombinationForIngredient> findAllVarMappingCombinationUsingRandom(
		Map<VarAccessWrapper, List<CtVariable>> mappedVars) {

	List<VarCombinationForIngredient> allCom = new ArrayList<>();

	List<Map<String, CtVariable>> allWithoutOrder = VariableResolver.findAllVarMappingCombination(mappedVars, null);

	for (Map<String, CtVariable> varMapping : allWithoutOrder) {
		try {
			VarCombinationForIngredient varCombinationWrapper = new VarCombinationForIngredient(varMapping);
			// In random mode, all same probabilities
			varCombinationWrapper.setProbality((double) 1 / (double) allWithoutOrder.size());
			allCom.add(varCombinationWrapper);
		} catch (Exception e) {
			logger.error("Error for obtaining a string representation of combination with " + varMapping.size()
					+ " variables");
		}
	}
	Collections.shuffle(allCom, RandomManager.getRandom());

	logger.debug("Number combination RANDOMLY sorted : " + allCom.size() + " over " + allWithoutOrder.size());

	return allCom;

}
 
Example 14
Source Project: astor   Source File: ExpressionGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static CtExpression fetchExpressionOnType(Factory factory, List<CtVariable> visiablevars, String type, String query, Boolean whetherEnum) {
	if (type == null || type.equals(""))
		return null;
	CtCodeSnippetExpression typeexper = factory.Code().createCodeSnippetExpression(type+".class");
	ArrayList<CtExpression> param = getParameter(factory, visiablevars, type, whetherEnum);
	
	param.add(1, factory.Code().createCodeSnippetExpression(Integer.toString(0)));

	param.add(3, typeexper);
	
	CtExpression[] arr = param.toArray(new CtExpression[param.size()]);
	
	CtExecutableReference<Object> ref = factory.Core().createExecutableReference();
	ref.setSimpleName(query);
	
	CtInvocation methodcall=factory.Code().createInvocation(factory.Code().createCodeSnippetExpression("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"),
			ref, 
			arr);
			
	String castType = primToObj.containsKey(type) ? primToObj.get(type) : type;  
	CtCodeSnippetExpression castedexp = factory.Code().createCodeSnippetExpression("(" + castType+ ")"+"("+methodcall.toString()+
			".invoke()".toString()+")");
	return castedexp;
}
 
Example 15
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * It retrieves all variables access which declarations are inside the
 * ingredient.
 * 
 * @param ingredientRootElement
 * @param varAccessCollected
 * @return
 */
public static List<CtVariableAccess> collectInductionVariableAccess(CtElement ingredientRootElement,
		List<CtVariableAccess> varAccessCollected) {

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

	for (CtVariableAccess ctVariableAccess : varAccessCollected) {

		CtVariableReference varref = ctVariableAccess.getVariable();

		// We are interesting in induction vars, they are modeled as
		// LocalVariables
		if (!(varref instanceof CtLocalVariableReference))
			continue;

		CtVariable var = varref.getDeclaration();

		boolean insideIngredient = checkParent(var, ingredientRootElement);
		if (insideIngredient)
			induction.add(ctVariableAccess);

	}
	return induction;
}
 
Example 16
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * For a given VariableAccess, we search the list of Variables contains
 * compatible types (i.e. sub types)
 * 
 * @param varContext
 * @param vartofind
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected static List<CtVariable> compatiblesSubType(List<CtVariable> varContext, CtTypeReference typeToFind) {

	List<CtVariable> result = new ArrayList<CtVariable>();

	for (CtVariable ctVariable_i : varContext) {

		CtTypeReference typeref_i = ctVariable_i.getType();
		try {
			if (typeref_i.isSubtypeOf(typeToFind)) {
				result.add(ctVariable_i);
			}
		} catch (Exception e) {
			result.add(ctVariable_i);
		}

	}
	return result;
}
 
Example 17
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static List<CtVariableAccess> checkMapping(Map<CtVariableAccess, List<CtVariable>> matched) {
	List<CtVariableAccess> notMapped = new ArrayList<>();

	if (matched == null)
		return notMapped;

	// Now, we analyze if all access were matched
	for (CtVariableAccess ctVariableAccess : matched.keySet()) {
		List<CtVariable> mapped = matched.get(ctVariableAccess);
		if (mapped.isEmpty()) {
			// One var access was not mapped
			// return false;
			notMapped.add(ctVariableAccess);
		}
	}
	// All VarAccess were mapped
	// return true;
	return notMapped;
}
 
Example 18
Source Project: astor   Source File: VarMappingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testMappingTwoVars() {
	// We try to insert C8 (a + b ...) in the place ofC3 (clearResult)
	List<CtVariable> varContextC3 = VariableResolver.searchVariablesInScope(c3);
	VarMapping vmapping2 = VariableResolver.mapVariablesUsingCluster(varContextC3, otherClassElementC8);

	Map<VarAccessWrapper, List<CtVariable>> mapsVariablesOutC2 = vmapping2.getMappedVariables();

	log.debug("mapping 2 -->" + mapsVariablesOutC2 + "\n to we put in context: " + varContextC3);
	// Here, the mapping must not be empty
	assertFalse(mapsVariablesOutC2.values().isEmpty());
	// one key for each unmapped var
	assertTrue(mapsVariablesOutC2.keySet().size() == 2);
	// all vars were mapped
	log.debug("not mapped " + vmapping2.getNotMappedVariables());
	assertTrue(vmapping2.getNotMappedVariables().isEmpty());

	// We get a method setup(UnivariateRealFunction f) for testing the
	// insertion of a ingredient out of scope
	// CtMethod mSetup = getMethod4Test1(engine);
	// assertNotNull(mSetup);

}
 
Example 19
/**
 * Return a combination of variables.
 * 
 * @param allCombinations
 * @return
 */
public Map<String, CtVariable> obtainCombination(List<Map<String, CtVariable>> allCombinations) {

	if (ConfigurationProperties.getPropertyBool("randomcombination")) {
		int value = RandomManager.nextInt(allCombinations.size());
		return allCombinations.get(value);
	} else {
		return allCombinations.get(0);
	}
}
 
Example 20
Source Project: coming   Source File: ConstantAnalyzer.java    License: MIT License 5 votes vote down vote up
public static boolean isConstantVariable(CtVariable ctVariable) {
	
	Set<ModifierKind> modifiers = ctVariable.getModifiers();
	if (modifiers.contains(ModifierKind.FINAL)) {
		return true;
	} else {
		String simpleName = ctVariable.getSimpleName();
		if (simpleName.toUpperCase().equals(simpleName)) {
			return true;
		}
	}

	return false;
}
 
Example 21
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 5 votes vote down vote up
private void analyzeVarMethodNameSimilarM12 (List<CtInvocation> invocationsaffected, List<CtVariable> scopevars, Cntx<Object> context) {
	
	 try {
		 for (CtInvocation invAffected : invocationsaffected) {
			
			boolean M12hasvarsimiplarinname = false;
			
			String methodname=invAffected.getExecutable().getSimpleName(); 
			
			for (CtVariable aVarInScope : scopevars) {
				
				String varname=aVarInScope.getSimpleName();
				varname=varname.replaceAll("[^a-zA-Z0-9]", "");
				if(varname.length()>3) {
					if(methodname.toLowerCase().endsWith(varname.toLowerCase()) || methodname.toLowerCase().equals("length") ||
							methodname.toLowerCase().contains("version") || methodname.toLowerCase().contains("clone")) {
						M12hasvarsimiplarinname = true;
						break;
					}
				}
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(invAffected),
					CodeFeatures.M12_Has_Var_Similar_In_Name, 
					M12hasvarsimiplarinname, "FEATURES_METHODS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 22
Source Project: coming   Source File: VariableResolver.java    License: MIT License 5 votes vote down vote up
/**
 * Return a list of variables that match with the variable access passed as
 * parameter. The last argument indicate if we map also the vars name
 * 
 * @param varContext
 * @param vartofind
 * @param mapName
 * @return
 */
protected static List<CtVariable> matchVariable(List<CtVariable> varContext, CtVariableAccess vartofind,
		boolean mapName) {
	List<CtVariable> varMatched = new ArrayList<>();
	try {
		CtTypeReference typeToFind = vartofind.getType();

		// First we search for compatible variables according to the type
		List<CtVariable> types = compatiblesSubType(varContext, typeToFind);
		if (types.isEmpty()) {
			return varMatched;
		}
		// Then, we search
		for (CtVariable ctVariableWithTypes : types) {
			// comparing name is optional, according to argument.
			boolean matchName = !mapName
					|| ctVariableWithTypes.getSimpleName().equals(vartofind.getVariable().getSimpleName());
			if (matchName) {
				varMatched.add(ctVariableWithTypes);
			}
		}

	} catch (Exception ex) {
		logger.error("Variable verification error", ex);
	}

	return varMatched;
}
 
Example 23
Source Project: coming   Source File: VariableResolver.java    License: MIT License 5 votes vote down vote up
/**
 * Maps a variable access with a variable declaration.
 * 
 * @param varContext
 * @param varacc
 * @return
 */
public static Map<CtVariableAccess, List<CtVariable>> matchVars(List<CtVariable> varContext,
		List<CtVariableAccess> varacc, boolean mapName) {

	Map<CtVariableAccess, List<CtVariable>> mapping = new HashMap<>();

	for (CtVariableAccess ctVariableAccess : varacc) {
		List<CtVariable> matched = matchVariable(varContext, ctVariableAccess, mapName);
		mapping.put(ctVariableAccess, matched);
	}

	return mapping;
}
 
Example 24
Source Project: coming   Source File: VariableResolver.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the variables that have as name the string passed as argument.
 * 
 * @param varContext      variables
 * @param wordFromCluster name of a variable
 * @return
 */
public static List<CtVariable> existVariableWithName(List<CtVariable> varContext, String wordFromCluster) {
	List<CtVariable> founds = new ArrayList<>();
	for (CtVariable ctVariable : varContext) {
		if (ctVariable.getSimpleName().equals(wordFromCluster))
			founds.add(ctVariable);
	}
	return founds;
}
 
Example 25
Source Project: astor   Source File: VariableTransformation.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String toStringMap() {
	String r = "";
	for (String ph_name : this.varplaceholder.getPalceholders().keySet()) {

		List<CtVariableAccess> va = this.varplaceholder.getPalceholders().get(ph_name);
		CtVariableAccess va1 = va.get(0);

		CtVariable vcomb = this.combination.getCombination().get(va1.getVariable().getSimpleName());
		r += vcomb.getSimpleName() + " -->  " + ph_name;
		r += ", ";

	}

	return r;
}
 
Example 26
Source Project: astor   Source File: VariableResolverTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test2VariablesInScope() throws Exception {

	AstorMain main1 = new AstorMain();
	String dep = new File("./examples/libs/junit-4.4.jar").getAbsolutePath();
	String[] args = new String[] { "-dependencies", dep, "-mode", "jgenprog", "-failing",
			"org.apache.commons.math.distribution.NormalDistributionTest", "-location",
			new File("./examples/math_85").getAbsolutePath(), "-package", "org.apache.commons", "-srcjavafolder",
			"/src/java/", "-srctestfolder", "/src/test/", "-binjavafolder", "/target/classes", "-bintestfolder",
			"/target/test-classes", "-javacompliancelevel", "7", "-flthreshold", "0.5", "-stopfirst", "false",
			// Force not running
			"-maxgen", "0", "-scope", "package", "-seed", "10" };
	log.debug(Arrays.toString(args));
	main1.execute(args);

	List<ProgramVariant> variants = main1.getEngine().getVariants();

	ProgramVariant pv = variants.get(0);
	ModificationPoint mp = pv.getModificationPoints().get(0);
	assertEquals(97, ((SuspiciousModificationPoint) mp).getSuspicious().getLineNumber());
	List<CtVariable> vars = VariableResolver.searchVariablesInScope(mp.getCodeElement());
	// remember that we exclude serialId fields
	assertEquals((0 + 4 + 1), vars.size());

	ModificationPoint mp4 = pv.getModificationPoints().get(4);
	assertEquals(181, ((SuspiciousModificationPoint) mp4).getSuspicious().getLineNumber());

	List<CtVariable> vars4 = VariableResolver.searchVariablesInScope(mp4.getCodeElement());
	// method local + block local + par + fields
	assertEquals((1 + 3 + 4 + 6), vars4.size());
}
 
Example 27
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 28
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 29
Source Project: astor   Source File: ConditionAddTransform.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public <R> void visitCtBlock(CtBlock<R> block) {
	int id = 0;
	List<CtStatement>  statlist = block.getStatements();
	boolean flag = false;
	for (; id < statlist.size(); id++)
		if (statlist.get(id).equals((CtStatement) this.modificationPoint.getCodeElement())) {
			flag = true;
			break;
		}
	if (!flag)
		return;
	
	List<CtVariable> varsavilable = modificationPoint.getContextOfModificationPoint();
	PriorityQueue<CtVariable> queue = new PriorityQueue<CtVariable>(new Comparator<CtVariable>() {
		@Override
		public int compare(CtVariable o1, CtVariable o2) {
			return o2.getPosition().getLine()-o1.getPosition().getLine();
		}
	});	
	queue.addAll(varsavilable);
	
	List<String> types = new ArrayList<String>();
	while (!queue.isEmpty()) {
		CtVariable var = queue.poll();
	    String type = var.getType().getQualifiedName();
		type = type.replaceAll("\\d","");
		if (!types.contains(type)) {
			types.add(type);
			log.info(type);
			writeCondition(type, block, id);
			writeIfReturn(type, block, id);
		}
	}
}
 
Example 30
Source Project: gumtree-spoon-ast-diff   Source File: NodeCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> void scanCtVariable(CtVariable<T> e) {
	CtTypeReference<T> type = e.getType();
	if (type != null) {
		ITree variableType = builder.createNode("VARIABLE_TYPE", type.getQualifiedName());
		variableType.setMetadata(SpoonGumTreeBuilder.SPOON_OBJECT, type);
		type.putMetadata(SpoonGumTreeBuilder.GUMTREE_NODE, variableType);
		builder.addSiblingNode(variableType);
	}
}