Java Code Examples for spoon.reflect.reference.CtExecutableReference

The following examples show how to use spoon.reflect.reference.CtExecutableReference. 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: nopol   Source File: MethodCollector.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void process(CtInvocation ctElement) {
    CtExecutableReference executable = ctElement.getExecutable();
    if (executable.isConstructor()) {
        return;
    }
    String key = executable.toString();
    CtTypeReference declaringType = executable.getDeclaringType();
    if (declaringType.getPackage() != null) {
        key = declaringType.getPackage().getSimpleName() + "." + executable.getSimpleName();
    }
    if (!statMethod.containsKey(key)) {
        statMethod.put(key, 1);
    } else {
        statMethod.put(key, statMethod.get(key) + 1);
    }
}
 
Example 2
Source Project: nopol   Source File: DynamothDataCollector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Call static methods on imported class
 *  @param ctExecutableReferences
 * @param threadRef
 * @param argsCandidates
 */
private Candidates collectStaticMethods(Set<CtExecutableReference> ctExecutableReferences, ThreadReference threadRef, Candidates argsCandidates) {
    Candidates results = new Candidates();
    Iterator<CtExecutableReference> it = ctExecutableReferences.iterator();
    while (it.hasNext()) {
        CtExecutableReference next = it.next();
        List<ReferenceType> refs = threadRef.virtualMachine().classesByName(next.getDeclaringType().getQualifiedName());
        if (refs.size() == 0) {
            continue;
        }

        ReferenceType ref = refs.get(0);
        Expression exp = AccessFactory.variable(next.getDeclaringType().getQualifiedName(), ref, nopolContext);
        List<Method> methods = getMethods(exp, ref, true, threadRef, next.getSimpleName());
        results.addAll(callMethods(exp, threadRef, methods, argsCandidates));
    }
    return results;
}
 
Example 3
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 4
Source Project: nopol   Source File: AssertReplacer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
 public boolean isToBeProcessed(CtInvocation<?> candidate) {
     if (!candidate.getExecutable().getSimpleName().contains("assert")) {
         return false;
     }
     CtExecutableReference<?> executable = candidate.getExecutable();
     CtPackageReference executablePackage = executable.getDeclaringType()
             .getPackage();
     if (executablePackage == null
             || !executablePackage.getSimpleName().contains("junit")) {
         return false;
     }
     CtMethod<?> parentMethod = candidate.getParent(CtMethod.class);
     if (parentMethod == null) {
         return false;
     }
     createExecutionMethod(candidate);
     return super.isToBeProcessed(candidate);
     /*
* boolean found = false; for (TestCase testCase : faillingTest) { if
* (testCase.className().equals(parentClass.getQualifiedName())) { if
* (testCase.testName().equals(parentMethod.getSimpleName())) { found =
* true; break; } } }
* 
* return found;
*/
 }
 
Example 5
Source Project: spoon-examples   Source File: Collector.java    License: GNU General Public License v2.0 5 votes vote down vote up
CtInvocation createObserve(CtMethod getter, CtInvocation invocationToGetter) {
	CtTypeAccess accessToLogger =
			factory.createTypeAccess(factory.createCtTypeReference(Logger.class));
	CtExecutableReference refObserve = factory.Type().get(Logger.class)
			.getMethodsByName("observe").get(0).getReference();
	return factory.createInvocation(
			accessToLogger,
			refObserve,
			factory.createLiteral(getKey(getter)),
			invocationToGetter
	);
}
 
Example 6
public static CtInvocation createAssert(String name, CtExpression... parameters) {
	final Factory factory = parameters[0].getFactory();
	CtTypeAccess accessToAssert =
			factory.createTypeAccess(factory.createCtTypeReference(Assert.class));
	CtExecutableReference assertEquals = factory.Type().get(Assert.class)
			.getMethodsByName(name).get(0).getReference();
	return factory.createInvocation(
			accessToAssert,
			assertEquals,
			parameters[0],
			parameters[1]
	);
}
 
Example 7
private List<CtTypeReference<?>> getCreatedTypes() {
	if (createdTypes == null) {
		createdTypes = new ArrayList<CtTypeReference<?>>();
		for (CtExecutableReference<?> m : getFactoryType().getDeclaredExecutables()) {
			createdTypes.add(m.getType());
		}
	}
	return createdTypes;
}
 
Example 8
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 5 votes vote down vote up
private boolean checkTypeInParameter(CtMethod anotherMethod, CtExecutableReference minvokedInAffected) {
	
	for (Object oparameter : anotherMethod.getParameters()) {
		CtParameter parameter = (CtParameter) oparameter;

		if (compareTypes(minvokedInAffected.getType(), parameter.getType())) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 5 votes vote down vote up
private boolean checkTypeInParameter(CtExecutableReference anotherMethod, CtExecutableReference minvokedInAffected) {
	for (Object oparameter : anotherMethod.getParameters()) {
		CtTypeReference parameter = (CtTypeReferenceImpl) oparameter;

		if (compareTypes(minvokedInAffected.getType(), parameter)) {
			return true;
		}
	}
	return false;
}
 
Example 10
Source Project: astor   Source File: InvocationPlaceholder.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void apply() {
	CtExecutableReference execr = this.getInvocation().getExecutable();
	this.oldName = execr.getSimpleName();
	execr.setSimpleName(newName);

}
 
Example 11
Source Project: astor   Source File: PatchGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void createTransformations(InvocationPlaceholder varplaceholder, List<Transformation> transformed,
		CtExecutableReference executableTarget) {
	if (executableTarget.getType().equals(varplaceholder.getType()) && varplaceholder.getInvocation()
			.getExecutable().getParameters().equals(executableTarget.getParameters())) {

		InvocationTransformation it = new InvocationTransformation(varplaceholder, executableTarget);

		transformed.add(it);
	}
}
 
Example 12
Source Project: astor   Source File: OperatorGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "static-access" })
public static CtExpression fetchROP(CtBinaryOperator operator, MutationSupporter mutSupporter, 
		ModificationPoint modificationPoint, String type, String querytype) {
	if (type == null || type.equals(""))
		return null;
	
	CtCodeSnippetExpression typeexper = mutSupporter.getFactory().Code().createCodeSnippetExpression(type+".class");

	ArrayList<CtExpression> param = getParameter(mutSupporter.getFactory(), operator);
	param.add(1, mutSupporter.getFactory().Code().createCodeSnippetExpression(Integer.toString(0)));

	param.add(3, typeexper);
	
       CtExpression[] arr = param.toArray(new CtExpression[param.size()]);
	
	CtExecutableReference<Object> ref = mutSupporter.getFactory().Core().createExecutableReference();
	ref.setSimpleName(querytype);
	
	CtInvocation methodcall=mutSupporter.getFactory().Code().createInvocation(mutSupporter.getFactory().Code().
			createCodeSnippetExpression("fr.inria.astor.approaches.scaffold.scaffoldsynthesis.ScaffoldSynthesisEntry"),
			ref, 
			arr);
	
	CtCodeSnippetExpression invokemethod = mutSupporter.getFactory().Code().createCodeSnippetExpression(methodcall.toString()
			+".invoke()".toString());	
	
	return invokemethod;
}
 
Example 13
Source Project: nopol   Source File: StatCollector.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Map<CtExecutableReference, Integer> getStatMethod() {
    return statMethod;
}
 
Example 14
Source Project: spoon-examples   Source File: Util.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) {
	final CtExecutableReference reference = method.getReference();
	final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false);
	return method.getFactory().createInvocation(variableRead, reference);
}
 
Example 15
Source Project: coming   Source File: OriginalFeatureExtractor.java    License: 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 16
Source Project: coming   Source File: S4ROFeatureExtractor.java    License: 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 17
Source Project: coming   Source File: CodeFeatureDetectorTest.java    License: MIT License 4 votes vote down vote up
@Test
public void testProperty_Missing_S6_METHOD_THROWS_EXCEPTION() {

	String content = "" + "class X {"
	//
			+ "public X() {" + "int b = 0;" + "}"
			//
			+ "public Object foo() {" //
			+ "int a = 1;"//
			+ "int b = a;" + "float f = 0;" + "" + "return f;" + "}" //
			+ "public float getFloat(){return 1.0;}"//
			+ "public double getConvertFloat(int i){return 0.0;}"//
			+ "public double getConvert2Float(int i){String s2;Integer.valueOf(s2);return 0.0;}"//
			+ "};";

	CtType type = getCtType(content);

	assertNotNull(type);
	CtExecutable method = (CtExecutable) type.getAllExecutables().stream()
			.filter(e -> ((CtExecutableReference) e).getExecutableDeclaration().getSimpleName().equals("X")
					|| ((CtExecutableReference) e).getExecutableDeclaration().getSimpleName().equals("<init>"))
			.findFirst().get().getExecutableDeclaration();

	assertNotNull(method);
	System.out.println(method);
	CtElement stassig = method.getBody().getStatements().stream().filter(e -> e.toString().startsWith("int b = 0"))
			.findFirst().get();
	System.out.println(stassig);
	CodeFeatureDetector cntxResolver = new CodeFeatureDetector();
	Cntx cntx = cntxResolver.analyzeFeatures(stassig);

	printJSon(cntx.toJSON());

	Cntx feat_vars = (Cntx) cntx.getInformation().get("FEATURES_VARS");
	assertTrue(feat_vars.getInformation().isEmpty());

	Boolean hasFeat_method = cntx.getInformation().containsKey("FEATURES_METHOD_INVOCATION");
	assertTrue(hasFeat_method);

	Cntx feat_method = (Cntx) cntx.getInformation().get("FEATURES_METHOD_INVOCATION");
	assertTrue(feat_method.getInformation().isEmpty());

	Boolean hasS6 = cntx.getInformation().containsKey(CodeFeatures.S6_METHOD_THROWS_EXCEPTION.toString());

	assertTrue(hasS6);

}
 
Example 18
Source Project: coming   Source File: CodeFeatureDetectorTest.java    License: MIT License 4 votes vote down vote up
@Test
public void testProperty_Missing_Feature_Groups() {

	String content = "" + "class X {" +
	//
			"public X() {" + "int b = 0;" + "System.out.println(b);" + "}"
			//
			+ "public Object foo() {" //
			+ "int a = 1;"//
			+ "int b = a;" + "float f = 0;" + "" + "return f;" + "}" //
			+ "public float getFloat(){return 1.0;}"//
			+ "public double getConvertFloat(int i){return 0.0;}"//
			+ "public double getConvert2Float(int i){String s2;Integer.valueOf(s2);return 0.0;}"//
			+ "};";

	CtType type = getCtType(content);

	assertNotNull(type);
	CtExecutable method = (CtExecutable) type.getAllExecutables().stream()
			.filter(e -> ((CtExecutableReference) e).getExecutableDeclaration().getSimpleName().equals("X")
					|| ((CtExecutableReference) e).getExecutableDeclaration().getSimpleName().equals("<init>"))
			.findFirst().get().getExecutableDeclaration();

	assertNotNull(method);

	CtElement stassig = method.getBody().getStatements().stream()
			.filter(e -> e.toString().contains("System.out.println(b)")).findFirst().get();

	CodeFeatureDetector cntxResolver = new CodeFeatureDetector();
	Cntx cntx = cntxResolver.analyzeFeatures(stassig);

	printJSon(cntx.toJSON());

	Boolean hasFeat_vars = cntx.getInformation().containsKey("FEATURES_VARS");
	assertTrue(hasFeat_vars);

	Boolean hasFeat_method = cntx.getInformation().containsKey("FEATURES_METHODS");
	assertTrue(hasFeat_method);

	Cntx feat_vars = (Cntx) cntx.getInformation().get("FEATURES_VARS");
	assertFalse(feat_vars.getInformation().isEmpty());

	Cntx feat_method = (Cntx) cntx.getInformation().get("FEATURES_METHODS");
	assertFalse(feat_method.getInformation().isEmpty());

	Boolean hasS6 = cntx.getInformation().containsKey(CodeFeatures.S6_METHOD_THROWS_EXCEPTION.toString());

	assertTrue(hasS6);

}
 
Example 19
Source Project: astor   Source File: InvocationPlaceholder.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public void revert() {
	CtExecutableReference execr = this.getInvocation().getExecutable();
	execr.setSimpleName(oldName);

}
 
Example 20
public InvocationTransformation(InvocationPlaceholder varplaceholder,
		CtExecutableReference selectedExecutableTarget) {
	this.selectedExecutableTarget = selectedExecutableTarget;
	this.varplaceholder = varplaceholder;
}
 
Example 21
Source Project: astor   Source File: InvocationResolver.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static boolean chechSignatures(Collection<CtExecutableReference<?>> allExecutables,
		CtExecutableReference executable, boolean constructor) {

	String signatureTarget = executable.getSignature();

	for (CtExecutableReference<?> ctExecutableReferenceOfMethod : allExecutables) {

		if (constructor && !ctExecutableReferenceOfMethod.isConstructor())
			continue;

		if (ctExecutableReferenceOfMethod.getSignature().equals(signatureTarget))
			return true;
	}

	return false;
}