spoon.reflect.declaration.CtVariable Java Examples

The following examples show how to use spoon.reflect.declaration.CtVariable. 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: VariableResolver.java    From astor with 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 #2
Source File: VariableResolver.java    From coming with 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 #3
Source File: VarMappingTest.java    From astor with 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 #4
Source File: VariableResolver.java    From astor with 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 #5
Source File: VariableResolver.java    From astor with 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 #6
Source File: VariableResolver.java    From coming with 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 #7
Source File: VariableResolver.java    From astor with 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 #8
Source File: VariableResolver.java    From coming with 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 #9
Source File: AddAssignmentOp.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<OperatorInstance> createOperatorInstances(ModificationPoint modificationPoint) {
	List<OperatorInstance> opInstances = new ArrayList<>();

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

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

	for (CtVariable aVarInScope : varsInScope) {

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

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

	}

	return opInstances;
}
 
Example #10
Source File: ASTData.java    From coming with 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 #11
Source File: PatchGenerator.java    From astor with 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 #12
Source File: ConstantAnalyzer.java    From coming with 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 #13
Source File: MethodAnalyzer.java    From coming with 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 #14
Source File: ExpressionGenerator.java    From astor with 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 File: VarMappingTest.java    From astor with 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 #16
Source File: VariableAnalyzer.java    From coming with 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 #17
Source File: VariableResolver.java    From astor with 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 #18
Source File: ASTData.java    From coming with 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 #19
Source File: NodeCreator.java    From gumtree-spoon-ast-diff with 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);
	}
}
 
Example #20
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 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 #21
Source File: VariableResolverTest.java    From astor with 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 #22
Source File: DynamicIngredient.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CtElement getCode() {

	if (this.ingredientCode == null) {
		Map<String, CtVariable> selectedTransformation = this.combination.getCombination();

		Map<VarAccessWrapper, CtVariableAccess> originalMap = VariableResolver.convertIngredient(mapping,
				selectedTransformation);
		// Cloned transformed element
		this.ingredientCode = MutationSupporter.clone((CtCodeElement) this.getDerivedFrom());

		VariableResolver.resetIngredient(originalMap);
	}
	return this.ingredientCode;
}
 
Example #23
Source File: ProbabilisticTransformationStrategy.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void sortPotentialVarsByProb(Map<VarAccessWrapper, List<CtVariable>> mappedVars, NGrams ngrams) {

		MapCounter mc1 = ngrams.ngrams[1];
		Map<?, Double> probabilities = mc1.getProbabilies();
		logger.debug("Var probabilistics: " + probabilities);
		for (VarAccessWrapper keyVar : mappedVars.keySet()) {
			List<CtVariable> vars = mappedVars.get(keyVar);
			// Collections.sort(vars, (e1, e2) ->
			// (Double.compare(probabilities.get(e2.getSimpleName()),
			// probabilities.get(e1.getSimpleName()))));
			logger.debug("All Vars " + vars);
			Collections.sort(vars, new Comparator<CtVariable>() {

				@Override
				public int compare(CtVariable e1, CtVariable e2) {
					Double d2 = probabilities.get(e2.getSimpleName());
					Double d1 = probabilities.get(e1.getSimpleName());

					if (d2 == null && d1 == null)
						return 0;

					if (d2 == null) {
						logger.debug("nf2 " + e2.getSimpleName());
						return -1;
					}
					if (d1 == null) {
						logger.debug("nf1 " + e1.getSimpleName());
						return 1;
					}
					return Double.compare(d2, d1);
				}
			});
		}

	}
 
Example #24
Source File: ConditionAddTransform.java    From astor with 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 #25
Source File: ProgramVariantFactory.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static ModificationPoint clonePoint(ModificationPoint existingGen, CtElement modified) {
	CtClass ctClass = existingGen.getCtClass();
	List<CtVariable> context = existingGen.getContextOfModificationPoint();
	ModificationPoint newGen = new ModificationPoint(modified, ctClass, context);
	return newGen;

}
 
Example #26
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 #27
Source File: VariableTransformation.java    From astor with 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 #28
Source File: VarMappingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws Exception 
 * 
 */
@Test
public void testAllVarCombinationLimited() throws Exception {
	
	
	String[] args = createCommandM70(learningDir, typeCloneGranularityClass, 100, true,
			CtClassIngredientSpace.class.getCanonicalName());
	CommandSummary cs = new CommandSummary(args);
	//We one only one combination of variables:
	cs.command.put("-maxVarCombination", "1");
	
	AstorMain main1 = new AstorMain();
	MutationSupporter.factory = null;
	main1.execute(cs.flat());
	engine = (JGenProg) main1.getEngine();

	searchCtElements();

	assertEquals(1,(int)ConfigurationProperties.getPropertyInt("maxVarCombination"));
	List<CtVariable> varContextC3 = VariableResolver.searchVariablesInScope(c3);//

	// We try to insert C8 (a + b ...) in the place ofC3 (clearResult)
	VarMapping vmapping2 = VariableResolver.mapVariablesUsingCluster(varContextC3, otherClassElementC8);

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

	System.out.println(allCombinations);
	
	assertFalse(allCombinations.isEmpty());
	//As difference of  the default case, we keep one combination
	assertEquals(1, allCombinations.size());


}
 
Example #29
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 #30
Source File: ClusterIngredientTransformation.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a combination of variables.
 * 
 * @param allCombinations
 * @return
 */
public Map<String, CtVariable> getOneCombination(List<Map<String, CtVariable>> allCombinations) {

	if (ConfigurationProperties.getPropertyBool("randomcombination")) {
		int value = RandomManager.nextInt(allCombinations.size());
		return allCombinations.get(value);
	} else {
		return allCombinations.get(0);
	}
}