spoon.reflect.declaration.CtField Java Examples

The following examples show how to use spoon.reflect.declaration.CtField. 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: ArithmeticOperatorMetaMutator.java    From metamutator with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isToBeProcessed(CtBinaryOperator<Boolean> element) {
	try {
		Selector.getTopLevelClass(element);
	} catch (NullPointerException e) {
		return false;
	}

	// not in constructors because we use static fields
	if (element.getParent(CtConstructor.class) != null) {
		return false;
	}

	// not in fields declaration because we use static fields
	if (element.getParent(CtField.class) != null) {
		return false;
	}

	return (ARITHMETIC_OPERATORS.contains(element.getKind()))
			&& (element.getParent(CtAnonymousExecutable.class) == null);
}
 
Example #2
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 #3
Source File: LogicalExpressionMetaMutator.java    From metamutator with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isToBeProcessed(CtBinaryOperator<Boolean> element) {
	// if (element.getParent(CtAnonymousExecutable.class)!=null) {
	// System.out.println(element.getParent(CtAnonymousExecutable.class));
	// }

	try {
		Selector.getTopLevelClass(element);
	} catch (NullPointerException e) {
		return false;
	}

	// not in constructors because we use static fields
	if (element.getParent(CtConstructor.class) != null) {
		return false;
	}

	// not in fields declaration because we use static fields
	if (element.getParent(CtField.class) != null) {
		return false;
	}
	
	return (LOGICAL_OPERATORS.contains(element.getKind()) || COMPARISON_OPERATORS
			.contains(element.getKind()))
			&& (element.getParent(CtAnonymousExecutable.class) == null) // not
																		// in
																		// static
																		// block
	;
}
 
Example #4
Source File: SpoonReferenceLibrary.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static Collection<CtField<?>> accessibleFieldsFrom(CtTypeReference<?> accessingType, CtTypeReference<?> accessedType) {
    Collection<CtField<?>> accessibleFields = MetaList.newLinkedList();
    try {
        Collection<CtFieldReference<?>> allFields = accessedType.getAllFields();
        for (CtFieldReference<?> field : allFields) {
            CtField<?> actualField = field.getDeclaration();
            if (actualField != null && isVisibleFrom(accessingType, actualField, field.getDeclaringType(), accessedType)) {
                accessibleFields.add(actualField);
            }
        }
    } catch (Throwable e) {
        logWarning(logger(), e.toString());
    }
    return accessibleFields;
}
 
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: RemoveOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean canBeAppliedToPoint(ModificationPoint point) {
	if (!(point.getCodeElement() instanceof CtStatement))
		return false;
	// Do not remove local declaration
	if (point.getCodeElement() instanceof CtLocalVariable) {
		CtLocalVariable lv = (CtLocalVariable) point.getCodeElement();
		boolean shadow = false;
		CtClass parentC = point.getCodeElement().getParent(CtClass.class);
		List<CtField> ff = parentC.getFields();
		for (CtField<?> f : ff) {
			if (f.getSimpleName().equals(lv.getSimpleName()))
				shadow = true;
		}
		if (!shadow)
			return false;
	}
	// do not remove the last statement
	CtMethod parentMethd = point.getCodeElement().getParent(CtMethod.class);
	if (point.getCodeElement() instanceof CtReturn
			&& parentMethd.getBody().getLastStatement().equals(point.getCodeElement())) {
		return false;
	}

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