spoon.reflect.declaration.ModifierKind Java Examples

The following examples show how to use spoon.reflect.declaration.ModifierKind. 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: NumericVariableMetaMutator.java    From metamutator with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Accept Numeric Variable
 */
@Override
public boolean isToBeProcessed(CtVariableRead candidate) {
	
	// SKIP not declared variable and Finale variable
	if(candidate.getVariable() == null) return false;

	if(candidate.getVariable().getSimpleName().equals("class")) return false;

	if(candidate.getVariable().getModifiers().contains(ModifierKind.FINAL)) return false;
	
	
	// SKIP IF VARIABLE IS CASTED
	if(candidate.getTypeCasts().size() > 0) return false;
	for(CtTypeReference type : candidate.getReferencedTypes()) {
		if(!this.isNumber(type)) return false;
	}
	
	if( candidate.getParent().getClass().equals(CtUnaryOperatorImpl.class)) return false;
	
	if(this.isNumber(candidate.getVariable().getType())){
		return true;
	}
	return false;
}
 
Example #2
Source File: MetaGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static CtInvocation creationInvocationToMega(ModificationPoint modificationPoint,
		List<CtExpression<?>> realParameters, CtMethod<?> megaMethod) {
	CtType target = modificationPoint.getCodeElement().getParent(CtType.class);
	CtExpression invocationTarget = MutationSupporter.getFactory().createThisAccess(target.getReference());

	// Here, we have to consider if the parent method is static.
	CtMethod parentMethod = modificationPoint.getCodeElement().getParent(CtMethod.class);
	if (parentMethod != null) {

		if (parentMethod.getModifiers().contains(ModifierKind.STATIC)) {
			// modifiers.add(ModifierKind.STATIC);
			invocationTarget = MutationSupporter.getFactory().createTypeAccess(target.getReference());

		}
	}

	// Invocation to mega

	CtInvocation newInvocationToMega = MutationSupporter.getFactory().createInvocation(invocationTarget,
			megaMethod.getReference(), realParameters);
	return newInvocationToMega;
}
 
Example #3
Source File: NodeCreator.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Override
public void scanCtModifiable(CtModifiable m) {

	if (m.getModifiers().isEmpty())
		return;

	// We add the type of modifiable element
	String type = MODIFIERS + getClassName(m.getClass().getSimpleName());
	ITree modifiers = builder.createNode(type, "");

	// We create a virtual node
	modifiers.setMetadata(SpoonGumTreeBuilder.SPOON_OBJECT, new CtVirtualElement(type, m, m.getModifiers()));

	// ensuring an order (instead of hashset)
	// otherwise some flaky tests in CI
	Set<ModifierKind> modifiers1 = new TreeSet<>(new Comparator<ModifierKind>() {
		@Override
		public int compare(ModifierKind o1, ModifierKind o2) {
			return o1.name().compareTo(o2.name());
		}
	});
	modifiers1.addAll(m.getModifiers());

	for (ModifierKind kind : modifiers1) {
		ITree modifier = builder.createNode("Modifier", kind.toString());
		modifiers.addChild(modifier);
		// We wrap the modifier (which is not a ctelement)
		modifier.setMetadata(SpoonGumTreeBuilder.SPOON_OBJECT, new CtWrapper(kind, m));
	}
	builder.addSiblingNode(modifiers);

}
 
Example #4
Source File: ConstantAnalyzer.java    From coming with 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 #5
Source File: DocProcessor.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public void process(CtElement element) {
	if (element instanceof CtType || element instanceof CtField || element instanceof CtExecutable) {
		Set<ModifierKind> modifiers = ((CtModifiable) element).getModifiers();
		if (modifiers.contains(PUBLIC) || modifiers.contains(PROTECTED)) {
			String docComment = element.getDocComment();
			if (docComment == null || docComment.equals("")) {
				System.out.println("undocumented element at " + element.getPosition());
				undocumentedElements.add(element);
			}
		}
	}
}
 
Example #6
Source File: TestExecutorProcessor.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static void createMainTestClass(SpoonedFile spooner,
                                       String className) {
    Factory factory = spooner.spoonFactory();
    CtClass<Object> executeTestClass = factory.Class().create(className);

    CtTypeReference<String[]> typedReference = factory.Class()
            .createReference(String[].class);
    CtTypeReference<Object> returnTypedReference = factory.Class()
            .createReference("void");

    Set<ModifierKind> modifiers = new LinkedHashSet<>(2);
    modifiers.add(ModifierKind.PUBLIC);
    modifiers.add(ModifierKind.STATIC);

    HashSet<CtTypeReference<? extends Throwable>> exceptions = new HashSet<>();
    exceptions.add(factory.Class().createReference(Exception.class));

    CtBlock<?> body = spooner.spoonFactory().Core().createBlock();

    body.addStatement(factory
            .Code()
            .createCodeSnippetStatement(
                    "for (String method : methods) {\n\t\t"
                            + "String[] split = method.split(\"\\\\.\");\n\t\t"
                            + "Class.forName(method.replace(\".\" + split[split.length - 1], \"\")).getMethod(\"runJPFTest\", String[].class).invoke(null, new Object[] { new String[] { split[split.length - 1] }});}"));

    CtMethod<?> method = spooner
            .spoonFactory()
            .Method()
            .create(executeTestClass, modifiers, returnTypedReference,
                    "main", new ArrayList<CtParameter<?>>(), exceptions,
                    body);
    spooner.spoonFactory().Method()
            .createParameter(method, typedReference, "methods");
}
 
Example #7
Source File: IntegerConstantReplacementMetaMutator.java    From metamutator with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isToBeProcessed(CtVariableRead element){
	try {
		if((element.getType().toString().contains("int"))&&
				(!(element.getVariable().getDeclaration().getDefaultExpression() == null))){
					if(!(element.getVariable().getDeclaration().getDefaultExpression().toString().contains(PREFIX))
							&& (!element.getVariable().getDeclaration().getModifiers().contains(ModifierKind.STATIC)))
								return true;				
		}
	} catch (Exception e) {

	}
	return false;	
}
 
Example #8
Source File: EmptyMethodBodyProcessor.java    From spoon-examples with GNU General Public License v2.0 4 votes vote down vote up
public void process(CtMethod<?> element) {
	if (element.getParent(CtClass.class) != null && !element.getModifiers().contains(ModifierKind.ABSTRACT) && element.getBody().getStatements().isEmpty()) {
		emptyMethods.add(element);
	}
}
 
Example #9
Source File: SpoonMethodLibrary.java    From nopol with GNU General Public License v2.0 4 votes vote down vote up
public static boolean isAbstract(CtMethod<?> method) {
    return hasModifier(method, ModifierKind.ABSTRACT);
}
 
Example #10
Source File: WholeStatementAnalyzer.java    From coming with MIT License 4 votes vote down vote up
private void analyzeS18_InSynchronizedMethod(CtElement element, Cntx<Object> context) {

		try {
			boolean S18Insynchronizedmethod = false;

			CtStatement parent = element.getParent(new LineFilter());
			CtTry potentionalTryCatch = element.getParent(CtTry.class);

			if (potentionalTryCatch != null && whethereffectivetrycatch(potentionalTryCatch, parent)) {
				context.put(CodeFeatures.S18_In_Synchronized_Method, false);
			} else {
				CtMethod methodParent = element.getParent(CtMethod.class);
				CtClass parentClass = element.getParent(CtClass.class);

				if (methodParent != null) {
					if (methodParent.getModifiers().contains(ModifierKind.SYNCHRONIZED))
						S18Insynchronizedmethod = true;
				}

				if (!S18Insynchronizedmethod && parentClass != null) {

					Set<CtTypeReference<?>> superInterfaces = parentClass.getSuperInterfaces();
					CtTypeReference<?> superType = parentClass.getSuperclass();

					if (superType != null && superType.getQualifiedName().toLowerCase().indexOf("thread") != -1)
						S18Insynchronizedmethod = true;

					if (superInterfaces.size() > 0) {
						for (CtTypeReference specificreference : superInterfaces) {
							if (specificreference != null
									&& specificreference.getQualifiedName().toLowerCase().indexOf("thread") != -1) {
								S18Insynchronizedmethod = true;
								break;
							}
						}
					}
				}

				context.put(CodeFeatures.S18_In_Synchronized_Method, S18Insynchronizedmethod);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
 
Example #11
Source File: VariableResolver.java    From coming with 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 #12
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static List<CtInvocation> retrieveInvocationsFromMethod(CtTypeReference variableToReplaceType,
		CtClass classUnderAnalysis, ModificationPoint point) {
	List<CtInvocation> newInvocations = new ArrayList<>();

	boolean isParentMethodStatic = isParentMethodStatic(point.getCodeElement());

	List allMethods = SupportOperators.getAllMethodsFromClass(classUnderAnalysis);

	CtThisAccess<Object> createThisAccess = MutationSupporter.getFactory()
			.createThisAccess(MutationSupporter.getFactory().Type().objectType(), true);

	for (Object omethod : allMethods) {

		if (!(omethod instanceof CtMethod))
			continue;

		CtMethod anotherMethod = (CtMethod) omethod;

		if (isParentMethodStatic && //
				!anotherMethod.getModifiers().contains(ModifierKind.STATIC)) {
			// if the modification point is in a static method, the method to call must be
			// static
			continue;
		}

		if (anotherMethod.getSimpleName().startsWith(VarReplacementByMethodCallOp.META_METHOD_LABEL))
			// It's a meta-method, discard
			continue;

		boolean compatibleReturnTypes = SupportOperators.checkIsSubtype(anotherMethod.getType(),
				variableToReplaceType);

		if (compatibleReturnTypes) {

			List<CtInvocation> newInvToMethods = createRealInvocationsAllPosibilities(point, anotherMethod,
					createThisAccess);
			newInvocations.addAll(newInvToMethods);
		}
	}

	return newInvocations;
}
 
Example #13
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static List<CtInvocation> retrieveInvocationsFromVar(CtTypeReference variableToReplaceType,
		CtClass classUnderAnalysis, ModificationPoint point) {
	List<CtInvocation> newInvocations = new ArrayList<>();

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

	boolean isParentMethodStatic = isParentMethodStatic(point.getCodeElement());

	for (CtVariable varInScope : variablesInScope) {

		if (varInScope.getType() == null || varInScope.getType().isPrimitive()) {
			continue;
		}

		//

		if (isParentMethodStatic && //
				!varInScope.getModifiers().contains(ModifierKind.STATIC)) {
			// if the modification point is in a static method, the variable to target must
			// be
			// static
			continue;
		}
		//
		List<CtMethod> allMethods = varInScope.getType().getAllExecutables().stream()
				.filter(e -> e.getExecutableDeclaration() instanceof CtMethod)
				.map(e -> e.getExecutableDeclaration()).map(CtMethod.class::cast).collect(Collectors.toList());

		for (CtMethod anotherMethod : allMethods) {

			if (anotherMethod.getSimpleName().startsWith(VarReplacementByMethodCallOp.META_METHOD_LABEL))
				// It's a meta-method, discard
				continue;

			if (!anotherMethod.isPublic())
				continue;

			boolean compatibleReturnTypes = SupportOperators.checkIsSubtype(anotherMethod.getType(),
					variableToReplaceType);

			if (compatibleReturnTypes) {

				List<CtInvocation> newInvToMethods = createRealInvocationsAllPosibilities(point, anotherMethod,
						MutationSupporter.getFactory().createVariableRead(varInScope.getReference(),
								varInScope.isStatic()));
				newInvocations.addAll(newInvToMethods);

			}
		}
	}
	return newInvocations;
}
 
Example #14
Source File: UniqueTestGenerator.java    From metamutator with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean isToBeProcessed(CtClass element) {
	return element.getElements(new AnnotationFilter<>((Class<? extends Annotation>) Test.class)).size()>0
			&& !element.getModifiers().contains(ModifierKind.ABSTRACT)
			&& element.isTopLevel();
}
 
Example #15
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns all variables in scope, reachable from the ctelement passes as
 * argument
 * 
 * @param element
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<CtVariable> searchVariablesInScope(CtElement element) {
	List<CtVariable> variables = new ArrayList();

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

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

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

	}

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

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

	}

	return variables;

}
 
Example #16
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Adapt the ingredient to the destination according to the mapping. We directly
 * manipulate the variables from the ingredient, which are stored in VarMapping
 * 
 * @param varMapping
 * @param destination
 * @return it returns the original variable reference of each converted variable
 */
@SuppressWarnings("unchecked")
public static Map<VarAccessWrapper, CtVariableAccess> convertIngredient(VarMapping varMapping,
		Map<String, CtVariable> mapToFollow) {

	Map<VarAccessWrapper, CtVariableAccess> originalMap = new HashMap<>();

	Map<VarAccessWrapper, List<CtVariable>> mappedVars = varMapping.getMappedVariables();
	for (VarAccessWrapper var : mappedVars.keySet()) {
		CtVariable varNew = mapToFollow.get(var.getVar().getVariable().getSimpleName());
		//
		CtVariableReference newVarReference = varNew.getReference();

		CtVariableAccess originalVarAccessDestination = var.getVar();
		CtVariableAccess newVarAccessDestination = null;

		// if the var to reference is a local or parameter
		if (newVarReference instanceof CtLocalVariableReference
				|| newVarReference instanceof CtParameterReference) {
			// let's check the destination Writes or Reads
			if (originalVarAccessDestination instanceof CtFieldWrite
					|| originalVarAccessDestination instanceof CtVariableWrite) {
				// We replace the Write by a Var writter
				newVarAccessDestination = MutationSupporter.getFactory().Core().createVariableWrite();
				newVarAccessDestination.setVariable(newVarReference);

			} else { // read
				newVarAccessDestination = MutationSupporter.getFactory().Code().createVariableRead(newVarReference,
						varNew.hasModifier(ModifierKind.STATIC));
			}

		} else
		// else, if we want to reference a field
		if (newVarReference instanceof CtFieldReference) {
			// let's check the destination, write or read
			if (originalVarAccessDestination instanceof CtFieldWrite<?>
					|| originalVarAccessDestination instanceof CtFieldRead<?>) {
				newVarAccessDestination = MutationSupporter.getFactory().Core().createFieldWrite();

			} else {
				newVarAccessDestination = MutationSupporter.getFactory().Core().createFieldRead();

			}
			newVarAccessDestination.setVariable(newVarReference);
		}
		// At the end, for all cases:
		if (newVarAccessDestination != null) {
			originalMap.put(new VarAccessWrapper(newVarAccessDestination), originalVarAccessDestination);
			originalVarAccessDestination.replace(newVarAccessDestination);
		} else {
			logger.error("No destination resolved");
		}

	} // end for
	return originalMap;
}
 
Example #17
Source File: Selector.java    From metamutator with GNU General Public License v3.0 4 votes vote down vote up
/** Generates a field containing a new selector for this element and adds it to the current class 
 * 
 */
public static <E> void generateSelector(CtElement element, E initialChoice, int selectorId, EnumSet<?> possibleChoices, String prefix ) {
	
	Class<?> choiceClass = possibleChoices.iterator().next().getClass();
	
	long hashCode = (element.getPosition().toString() + element.getParent()
	.toString()).hashCode();

	CtTypeReference<Object> fieldType = element.getFactory().Type().createTypeParameterReference(ISelector.class.getCanonicalName());
	
	//doesn't work with spoon for the moment
	//CtTypeReference<Object> genericRefs = element.getFactory().Type().createTypeParameterReference(choiceClass.getCanonicalName());
	//fieldType.addActualTypeArgument(genericRefs);
	
	String selectorFieldName = prefix + selectorId;
	
	CtCodeSnippetExpression<Object> codeSnippet = element.getFactory().Core()
			.createCodeSnippetExpression();
	StringBuilder sb = new StringBuilder(Selector.class.getCanonicalName() + ".of(");
	
	// we disable the ids
	// sb.append(procId+""+selectorId);
	// sb.append(',');

	// now the options
	sb.append("new "+choiceClass.getCanonicalName()+"[]{");
	
	// the original operator, always the first one
	sb.append(initialChoice.getClass().getCanonicalName()+"."+initialChoice.toString());
	
	// the other alternatives
	for (Object choose : possibleChoices) {
		if (choose.equals(initialChoice)) {
			continue;
		}
		sb.append(',').append(choose.getClass().getCanonicalName()+"."+choose.toString());
	}
	
	sb.append("})");
	
	// adding location
	if (element.getParent(CtType.class).isTopLevel()) {
		sb.append(".in("
				+ element.getParent(CtType.class).getQualifiedName()
				+ ".class)");
	}
	
	// adding identifier
	sb.append(".id(\"" + selectorFieldName + "\")");
	
	codeSnippet.setValue(sb.toString());
	
	CtClass<?> type = getTopLevelClass(element);
	
	CtField<Object> field = element.getFactory().Field().create(
			type,
			EnumSet.of(ModifierKind.FINAL, ModifierKind.PRIVATE,
					ModifierKind.STATIC), fieldType, selectorFieldName,
			codeSnippet);
	
	type.addField(field);
}
 
Example #18
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
public static boolean isParentMethodStatic(CtElement codeElement) {

		CtMethod parentMethod = codeElement.getParent(CtMethod.class);
		if (parentMethod != null) {

			return parentMethod.getModifiers().contains(ModifierKind.STATIC);
		}

		return false;
	}