Java Code Examples for spoon.reflect.code.CtVariableAccess#getType()

The following examples show how to use spoon.reflect.code.CtVariableAccess#getType() . 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: VariableAnalyzer.java    From coming with MIT License 6 votes vote down vote up
private void analyzeV19_VarWithSpecialName (List<CtVariableAccess> varsAffected, Cntx<Object> context) {
	
	 try {
		  for (CtVariableAccess aVarAffected : varsAffected) {
			
			boolean V19WithSpecialName = false;
			String varname= aVarAffected.getVariable().getSimpleName().toLowerCase(); 
			
			if(varname.endsWith("length") || varname.endsWith("size") || varname.endsWith("count") || varname.endsWith("value")
					|| varname.endsWith("key") || varname.equals("class"))
				V19WithSpecialName =true;
			
			if(!V19WithSpecialName && aVarAffected.getType()!=null && aVarAffected.getType().getSimpleName().toLowerCase().endsWith("exception"))
				V19WithSpecialName =true;
			
		
			writeGroupedInfo(context, adjustIdentifyInJson(aVarAffected),
					CodeFeatures.V19_With_Special_Name, 
					V19WithSpecialName, "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: VariableAnalyzer.java    From coming with MIT License 6 votes vote down vote up
private void analyzeV14_VarInstanceOfClass (List<CtVariableAccess> varsAffected, Cntx<Object> context,
		CtClass parentClass) {
	
	try {
		for (CtVariableAccess varAffected : varsAffected) {
			
			boolean v14VarInstanceOfClass= false;
			
			if(varAffected.getType()!=null) {
			   if(varAffected.getType().toString().equals(parentClass.getQualifiedName()) ||
					varAffected.getType().toString().endsWith(parentClass.getQualifiedName()) ||
					parentClass.getQualifiedName().endsWith(varAffected.getType().toString()))
				v14VarInstanceOfClass=true;
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(varAffected), 
					CodeFeatures.V14_VAR_INSTANCE_OF_CLASS,
					(v14VarInstanceOfClass), "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 3
Source File: VariableAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public boolean compareVarAccessAndLiteralType(String literaltype, CtVariableAccess varaccess) {
	
	Boolean typecompatiable=false;
	
	if(varaccess.getType()!=null) {
	   if(varaccess.getType().toString().toLowerCase().endsWith("string")) {
		   if(literaltype.equals("string"))
		      typecompatiable=true; 
	   }
	   else  {
	      if(varaccess.getType().isPrimitive()) {
		     if(varaccess.getType().toString().toLowerCase().endsWith("char")) {
			    if(literaltype.equals("char"))
				   typecompatiable=true; 
		     }
		     else if(varaccess.getType().toString().toLowerCase().endsWith("boolean")) {
			    if(literaltype.equals("boolean"))
			       typecompatiable=true; 
		     }
		     else {
			   if(literaltype.equals("numerical"))
			       typecompatiable=true; 
		     }
	     }
	  }
	}
	return typecompatiable;
}
 
Example 4
Source File: VariableResolver.java    From coming with 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 5
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 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 6
Source File: VariableAnalyzer.java    From coming with MIT License 4 votes vote down vote up
/**
 * Check is a variable affected is compatible with a method type or parameter
 * 
 * @param varsAffected
 * @param element
 * @param context
 */
private void analyzeV1_V6_V16(List<CtVariableAccess> varsAffected, CtElement element, Cntx<Object> context,
		List allMethods, List<CtInvocation> invocationsFromClass, CtClass parentclass) {
	
	try {
		// v1: For each involved variable, whether has method definitions or method calls
		// (in the fault class) that take the type of the involved variable as one of
		// its parameters and the return type of the method is type compatible with the
		// type of the involved variable
		
		// v6 :For each involved variable, whether has methods in scope(method definitions
		// or method calls in the faulty class) that return a type which is the same or
		// compatible with the typeof the involved variable.
		

		for (CtVariableAccess varAffected : varsAffected) {

			boolean v6CurrentVarReturnCompatible = false;
			boolean v1CurrentVarCompatibleReturnAndParameterTypes = false;
			boolean v16CurrentVarParameterCompatible = false;
			
			if(varAffected.getType()!=null && !varAffected.getType().getQualifiedName().toString().toLowerCase().endsWith("object") &&
					varAffected.getType().getQualifiedName().toString().toLowerCase().indexOf("java.lang.object")==-1) {

			  if (checkMethodDeclarationWithParameterReturnCompatibleType(allMethods, varAffected.getType()) != null
					|| checkInvocationWithParameterReturnCompatibleType(invocationsFromClass,
							varAffected.getType(), parentclass) != null) {
				  v1CurrentVarCompatibleReturnAndParameterTypes = true;
			  }

			  if (checkMethodDeclarationWithReturnCompatibleType(allMethods, varAffected.getType()) != null
					|| checkInvocationWithReturnCompatibleType(invocationsFromClass,
							varAffected.getType(), parentclass) != null) {
				  v6CurrentVarReturnCompatible = true;
			  }
			
			  if (checkMethodDeclarationWithParemetrCompatibleType(allMethods, varAffected.getType()) != null
					|| checkInvocationWithParemetrCompatibleType (invocationsFromClass,
							varAffected.getType()) != null) {
				  v16CurrentVarParameterCompatible = true;
			   }
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(varAffected), 
					CodeFeatures.V1_IS_TYPE_COMPATIBLE_METHOD_CALL_PARAM_RETURN,
					v1CurrentVarCompatibleReturnAndParameterTypes, "FEATURES_VARS");
			
			writeGroupedInfo(context, adjustIdentifyInJson(varAffected), 
					CodeFeatures.V6_IS_METHOD_RETURN_TYPE_VAR,
					v6CurrentVarReturnCompatible, "FEATURES_VARS");
			
			writeGroupedInfo(context, adjustIdentifyInJson(varAffected), 
					CodeFeatures.V16_IS_METHOD_PARAMETER_TYPE_VAR,
					v16CurrentVarParameterCompatible, "FEATURES_VARS");
			
		}

	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 7
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 4 votes vote down vote up
public boolean[] analyze_SametypewithGuard(List<CtVariableAccess> varsAffected, CtElement element,
			CtClass parentClass, List<CtStatement> statements) {

		boolean hasPrimitiveSimilarTypeWithNormalGuard = false;
		boolean hasObjectSimilarTypeWithNormalGuard = false;
		boolean hasPrimitiveSimilarTypeWithNullGuard = false;
		boolean hasObjectSimilarTypeWithNullGuard = false;

		try {
			CtExecutable faultyMethodParent = element.getParent(CtExecutable.class);

			if (faultyMethodParent == null)
				// the element is not in a method.
				return null;

			// For each variable affected
			for (CtVariableAccess variableAffected : varsAffected) {
				// for (CtStatement aStatement : statements) {
				CtStatement parent = variableAffected.getParent(new LineFilter());

				if (isNormalGuard(variableAffected, (parent)) || isNullCheckGuard(variableAffected, (parent)))
					continue;

				// For each statement in the method (it includes the statements inside the
				// blocks (then, while)!)
				for (CtStatement aStatement : statements) {
					// for (CtVariableAccess variableAffected : varsAffected) {

					if (parent == aStatement)
						continue;

					List<CtVariableAccess> varsFromStatement;

					if (aStatement instanceof CtIf || aStatement instanceof CtLoop) {
						varsFromStatement = VariableResolver.collectVariableRead(retrieveElementToStudy(aStatement));
					} else
						varsFromStatement = VariableResolver.collectVariableRead(aStatement);
//
//					// let's collect the var access in the statement
//					List<CtVariableAccess> varsFromStatement = VariableResolver
//							.collectVariableReadIgnoringBlocks(aStatement);
					// if the var access is the same that the affected
					for (CtVariableAccess varInStatement : varsFromStatement) {
						// Has similar type but different name
						if (compareTypes(variableAffected.getVariable().getType(),
								varInStatement.getVariable().getType())) {
							// && !hasSameName(variableAffected, varInStatement)) {
							// Now, let's check if the parent is a guard
							// if (isGuard(getParentNotBlock(aStatement))) {
							if (isNormalGuard(varInStatement, (aStatement))) {

								// it's ok, now let's check the type
								if (variableAffected.getType() != null) {
									// for primitive type variables, we require it to be the same global variable
									if (variableAffected.getType().isPrimitive() && varInStatement.getVariable()
											.getSimpleName().equals(variableAffected.getVariable().getSimpleName()))
										hasPrimitiveSimilarTypeWithNormalGuard = true;
									else
										hasObjectSimilarTypeWithNormalGuard = true;
								}
							}

							if (isNullCheckGuard(varInStatement, (aStatement))) {

								// it's ok, now let's check the type
								if (variableAffected.getType() != null) {

									if (variableAffected.getType().isPrimitive() && varInStatement.getVariable()
											.getSimpleName().equals(variableAffected.getVariable().getSimpleName()))
										hasPrimitiveSimilarTypeWithNullGuard = true;
									else
										hasObjectSimilarTypeWithNullGuard = true;
								}
							}

						}
					}
					// If we find both cases, we can stop
					if (hasPrimitiveSimilarTypeWithNormalGuard && hasObjectSimilarTypeWithNormalGuard
							&& hasPrimitiveSimilarTypeWithNullGuard && hasObjectSimilarTypeWithNullGuard)
						break;
				}
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}

		boolean[] expressionvalue = new boolean[4];
		expressionvalue[0] = hasObjectSimilarTypeWithNormalGuard;
		expressionvalue[1] = hasPrimitiveSimilarTypeWithNormalGuard;
		expressionvalue[2] = hasObjectSimilarTypeWithNullGuard;
		expressionvalue[3] = hasPrimitiveSimilarTypeWithNullGuard;

		return expressionvalue;

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

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

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

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

	List<OperatorInstance> opsOfVariant = new ArrayList();

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

	//
	List<CtVariableAccess> varAccessInModificationPoints = null;

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

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

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

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

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

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

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

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

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

		variableCounter++;

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

	} // End variable

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

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

	return opsMega;
}
 
Example 10
Source File: VariableResolver.java    From coming with MIT License 3 votes vote down vote up
/**
 * Return true if the variables are compatible
 * 
 * @param varOutScope
 * @param varInScope
 * @return
 */
public static boolean areVarsCompatible(CtVariableAccess varOutScope, CtVariable varInScope) {
	CtTypeReference refCluster = varInScope.getType();
	CtTypeReference refOut = varOutScope.getType();

	return areTypesCompatible(refCluster, refOut);
}
 
Example 11
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Return true if the variables are compatible
 * 
 * @param varOutScope
 * @param varInScope
 * @return
 */
public static boolean areVarsCompatible(CtVariableAccess varOutScope, CtVariable varInScope) {
	CtTypeReference refCluster = varInScope.getType();
	CtTypeReference refOut = varOutScope.getType();

	return areTypesCompatible(refCluster, refOut);
}