spoon.reflect.code.CtInvocation Java Examples

The following examples show how to use spoon.reflect.code.CtInvocation. 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: IngredientProcessorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testM70MethodInvocation() throws Exception {

	CommandSummary command = MathCommandsTests.getMath70Command();
	command.command.put("-parameters", ExtensionPoints.TARGET_CODE_PROCESSOR.identifier + File.pathSeparator
			+ MethodInvocationFixSpaceProcessor.class.getCanonicalName());
	command.command.put("-maxgen", "0");

	AstorMain main1 = new AstorMain();

	main1.execute(command.flat());
	List<ProgramVariant> variantss = main1.getEngine().getVariants();
	assertTrue(variantss.size() > 0);

	ProgramVariant pv = variantss.get(0);

	JGenProg jgp = (JGenProg) main1.getEngine();
	IngredientPoolLocationType ingSpace = (IngredientPoolLocationType) jgp.getIngredientSearchStrategy()
			.getIngredientSpace();
	checkModificationPointTypes(variantss, CtInvocation.class);
	checkIngredientTypes(ingSpace, CtInvocation.class);
}
 
Example #2
Source File: MethodCollector.java    From nopol with 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 #3
Source File: ConstructorAnalyzer.java    From coming with MIT License 6 votes vote down vote up
private void analyzeConstructorFeature_Extend (CtElement originalElement, Cntx<Object> context,
	CtClass parentClass, List<CtConstructorCall> allconstructorcallsFromClass, List<CtConstructorCall> constructorcallstostudy) {
	
	List<CtInvocation> emptyinvocationfromclass = new ArrayList<CtInvocation>();
	List<CtInvocation> emptyinvocationunderstudy = new ArrayList<CtInvocation>();

	for(CtConstructorCall constructorcallAffected : constructorcallstostudy) {
           
           boolean[] constructorcallfeature91012 = analyze_SamerMethodWithGuardOrTrywrap(originalElement, parentClass, emptyinvocationfromclass,
           		emptyinvocationunderstudy, allconstructorcallsFromClass, Arrays.asList(constructorcallAffected));

           if(constructorcallfeature91012 != null) {
			
           	writeGroupedInfo(context, adjustIdentifyInJson(constructorcallAffected), CodeFeatures.CON9_METHOD_CALL_WITH_NORMAL_GUARD, 
           			constructorcallfeature91012[0], "FEATURES_CONSTRUCTOR");
			
           	writeGroupedInfo(context, adjustIdentifyInJson(constructorcallAffected), CodeFeatures.CON10_METHOD_CALL_WITH_NULL_GUARD, 
           			constructorcallfeature91012[1], "FEATURES_CONSTRUCTOR");
           	
           	writeGroupedInfo(context, adjustIdentifyInJson(constructorcallAffected), CodeFeatures.CON12_METHOD_CALL_WITH_TRY_CATCH, 
           			constructorcallfeature91012[2], "FEATURES_CONSTRUCTOR");
		}         
	}	
}
 
Example #4
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public CtInvocation checkInvocationWithParemetrCompatibleType(List<CtInvocation> invocationsFromClass,
		CtTypeReference type) {

	for (CtInvocation anInvocation : invocationsFromClass) {

		for (Object anObjArgument : anInvocation.getArguments()) {
			CtExpression anArgument = (CtExpression) anObjArgument;

			if (compareTypes(type, anArgument.getType())) {
				return anInvocation;
			}
		}
	}

	return null;
}
 
Example #5
Source File: VariablesInSuspiciousCollector.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * get all dependencies added by a CtTypedElement
 *
 * @param element
 * @return all dependencies added by element
 */
private List<CtTypeReference<?>> getDependencies(CtTypedElement<?> element) {
    List<CtTypeReference<?>> listDependencies = new ArrayList<>();
    // Literal
    if (element instanceof CtAnnotation) {
        return listDependencies;
    }
    if (element instanceof CtLiteral<?>) {
        CtLiteral<?> literal = (CtLiteral<?>) element;
        literal.getValue();
        if (literal.getValue() instanceof CtTypeReference<?>) {
            listDependencies.add((CtTypeReference<?>) literal.getValue());
        } else if (literal.getValue() instanceof CtTypedElement<?>) {
            listDependencies.add(((CtTypedElement<?>) literal.getValue())
                    .getType());
        }
    }
    // method invocation
    if (element instanceof CtInvocation<?>) {
        CtInvocation<?> invocation = (CtInvocation<?>) element;
        // the class of the method
        listDependencies.add(invocation.getExecutable().getDeclaringType());
    }
    listDependencies.add(element.getType());
    return listDependencies;
}
 
Example #6
Source File: MethodAnalyzer.java    From coming with MIT License 6 votes vote down vote up
private void analyzeWhetherMethodSatrtsWithGetM11 (List<CtInvocation> invocationsaffected, Cntx<Object> context) {
	
	 try {
		 for (CtInvocation invAffected : invocationsaffected) {
			
			boolean M11SatrtWithGet = false;
			
			String name=invAffected.getExecutable().getSimpleName();
			
			if(name.toLowerCase().startsWith("get"))
				M11SatrtWithGet = true;
			
			writeGroupedInfo(context, adjustIdentifyInJson(invAffected),
					CodeFeatures.M11_Satrt_With_Get, 
					M11SatrtWithGet, "FEATURES_METHODS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example #7
Source File: MethodAnalyzer.java    From coming with MIT License 6 votes vote down vote up
private void analyzeMethodFeature_Extend (CtElement originalElement, Cntx<Object> context,
		CtClass parentClass, List<CtInvocation> invocationsFromClass, List<CtInvocation> invocations) {
	
	List<CtConstructorCall> emptyconstructorcallfromclass = new ArrayList<CtConstructorCall>();
	List<CtConstructorCall> emptyconstructorcallunderstudy = new ArrayList<CtConstructorCall>();

	for(CtInvocation invocationAffected : invocations) {
           
           boolean[] methdofeature91012 = analyze_SamerMethodWithGuardOrTrywrap(originalElement, parentClass, invocationsFromClass,
           		Arrays.asList(invocationAffected), emptyconstructorcallfromclass, emptyconstructorcallunderstudy);

           if(methdofeature91012 != null) {
			
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M9_METHOD_CALL_WITH_NORMAL_GUARD, 
           			methdofeature91012[0], "FEATURES_METHODS");
			
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M10_METHOD_CALL_WITH_NULL_GUARD, 
           			methdofeature91012[1], "FEATURES_METHODS");
           	
           	writeGroupedInfo(context, adjustIdentifyInJson(invocationAffected), CodeFeatures.M12_METHOD_CALL_WITH_TRY_CATCH, 
           			methdofeature91012[2], "FEATURES_METHODS");
		}         
	}	
}
 
Example #8
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 #9
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_t_209184_buggy_allopsNPE() throws Exception {
	AstComparator diff = new AstComparator();
	File fl = new File("src/test/resources/examples/t_209184/left_ActionCollaborationDiagram_1.28.java");
	File fr = new File("src/test/resources/examples/t_209184/right_ActionCollaborationDiagram_1.29.java");
	Diff result = diff.compare(fl, fr);

	List<Operation> actions = result.getAllOperations();
	assertEquals(1, actions.size());
	// assertTrue(result.containsOperation(OperationKind.Update, "Invocation",
	// "#getTarget()"));
	assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "getTarget"));

	UpdateOperation updateOp = (UpdateOperation) actions.get(0);
	CtElement dst = updateOp.getDstNode();
	assertNotNull(dst);
	assertTrue(CtInvocation.class.isInstance(dst));
	assertEquals(((CtInvocation) dst).getExecutable().toString(), "getModelTarget()");
}
 
Example #10
Source File: UnwrapfromMethodCallOp.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private MapList<CtInvocation, Ingredient> retrieveMethodHasCompatibleParameterAndReturnSameMethod(
		CtElement suspiciousElement) {

	MapList<CtInvocation, Ingredient> result = new MapList<CtInvocation, Ingredient>();
	List<CtInvocation> invocations = suspiciousElement.getElements(e -> (e instanceof CtInvocation)).stream()
			.map(CtInvocation.class::cast).collect(Collectors.toList());

	for (CtInvocation invocation : invocations) {

		for (Object oparameter : invocation.getArguments()) {
			CtExpression argument = (CtExpression) oparameter;

			if (SupportOperators.checkIsSubtype(argument.getType(), invocation.getType())) {

				CtExpression clonedExpressionArgument = argument.clone();
				MutationSupporter.clearPosition(clonedExpressionArgument);
				Ingredient newIngredient = new Ingredient(clonedExpressionArgument);
				result.add(invocation, newIngredient);

			}

		}
	}
	return result;
}
 
Example #11
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static List<CtInvocation> realInvocationsFromCombination(CtMethod anotherMethod, CtExpression target,
		List<List<CtExpression<?>>> possibleArguments) {
	List<CtInvocation> newInvocations = new ArrayList<>();

	for (List<CtExpression<?>> arguments : possibleArguments) {
		CtInvocation newInvocation = MutationSupporter.getFactory().createInvocation(target,
				anotherMethod.getReference(), arguments);
		newInvocation.setExecutable(anotherMethod.getReference());
		newInvocation.setArguments(arguments);
		newInvocation.setTarget(target);

		newInvocations.add(newInvocation);

	}
	return newInvocations;
}
 
Example #12
Source File: ClassCollector.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * get all dependencies added by a CtTypedElement
 *
 * @param element
 * @return all dependencies added by element
 */
private List<CtTypeReference<?>> getDependencies(CtTypedElement<?> element) {
    List<CtTypeReference<?>> listDependencies = new ArrayList<>();
    // Literal
    if (element instanceof CtAnnotation) {
        return listDependencies;
    }
    if (element instanceof CtLiteral<?>) {
        CtLiteral<?> literal = (CtLiteral<?>) element;
        literal.getValue();
        if (literal.getValue() instanceof CtTypeReference<?>) {
            listDependencies.add((CtTypeReference<?>) literal.getValue());
        } else if (literal.getValue() instanceof CtTypedElement<?>) {
            listDependencies.add(((CtTypedElement<?>) literal.getValue())
                    .getType());
        }
    }
    // method invocation
    if (element instanceof CtInvocation<?>) {
        CtInvocation<?> invocation = (CtInvocation<?>) element;
        // the class of the method
        listDependencies.add(invocation.getExecutable().getDeclaringType());
    }
    listDependencies.add(element.getType());
    return listDependencies;
}
 
Example #13
Source File: SpecialStatementFixSpaceProcessor.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void process(CtStatement element) {

	if (element instanceof CtIf) {
		add(((CtIf) element).getCondition());
	} else if (element instanceof CtFor) {
		add(((CtFor) element).getExpression());
	} else if (element instanceof CtWhile) {
		add(((CtWhile) element).getLoopingExpression());
	} else if (element instanceof CtDo) {
		add(((CtDo) element).getLoopingExpression());
	} else if (element instanceof CtThrow) {
		add(((CtThrow) element).getThrownExpression());
	} else if (element instanceof CtInvocation && (element.getParent() instanceof CtBlock)) {
		add(element);
	} else if (element instanceof CtAssignment || element instanceof CtConstructorCall
			|| element instanceof CtCFlowBreak || element instanceof CtLocalVariable) {
		add(element);
	}

}
 
Example #14
Source File: ExpressionRevolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static List<CtExpression<Boolean>> getExpressions(CtExpression<Boolean> element) {
	List<CtExpression<Boolean>> expsRetrieved = new ArrayList<CtExpression<Boolean>>();

	if (element instanceof CtUnaryOperator) {
		expsRetrieved.add(element);
		element = ((CtUnaryOperator) element).getOperand();
	}

	if (element instanceof CtBinaryOperator) {
		expsRetrieved.add(element);
		CtBinaryOperator bin = (CtBinaryOperator) element;
		if (bin.getKind().equals(BinaryOperatorKind.AND) || bin.getKind().equals(BinaryOperatorKind.OR)) {
			expsRetrieved.addAll(getExpressions(bin.getLeftHandOperand()));
			expsRetrieved.addAll(getExpressions(bin.getRightHandOperand()));
		}
	} else {
		if (element instanceof CtInvocation
				&& element.getType().getSimpleName().equals(boolean.class.getSimpleName())) {
			expsRetrieved.add(element);
		}
	}
	return expsRetrieved;
}
 
Example #15
Source File: TransformStrategy.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> void visitCtInvocation(CtInvocation<T> invocation) {
	super.visitCtInvocation(invocation);

	List<CtExpression<?>>  argumentlist = invocation.getArguments();
	for (int i = 0; i < argumentlist.size(); i++) {
		@SuppressWarnings("rawtypes")
		CtExpression p = argumentlist.get(i);
		if (candidates.containsKey(p)) {
			argumentlist.set(i, candidates.get(p));
		//	invocation.setArguments(argumentlist);
			saveSketchAndSynthesize();
			argumentlist.set(i, p);
			resoreDiskFile();
		//	invocation.setArguments(argumentlist);
		}
	}
}
 
Example #16
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_t_224542() throws Exception {
	AstComparator diff = new AstComparator();
	// meld src/test/resources/examples/t_224542/left_TestBot_1.75.java
	// src/test/resources/examples/t_224542/right_TestBot_1.76.java
	File fl = new File("src/test/resources/examples/t_224542/left_TestBot_1.75.java");
	File fr = new File("src/test/resources/examples/t_224542/right_TestBot_1.76.java");
	Diff result = diff.compare(fl, fr);

	result.debugInformation();

	CtElement ancestor = result.commonAncestor();
	assertTrue(ancestor instanceof CtInvocation);
	assertEquals("println", ((CtInvocation) ancestor).getExecutable().getSimpleName());
	assertEquals(344, ancestor.getPosition().getLine());

	List<Operation> actions = result.getRootOperations();
	assertTrue(actions.size() >= 3);
	assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "format"));
	assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "PLUS"));

	// the move can be either getEntity or getShortName
	assertTrue(result.containsOperation(OperationKind.Move, "Invocation"));
	assertEquals(344, result.changedNode(MoveOperation.class).getPosition().getLine());

}
 
Example #17
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private void fetchLibOverload(CtInvocation call) {
       
	List<String> origTypes = resolveTypes(call.getArguments());
	CtExpression exp = call.getTarget();
	String typename=exp.getType().getQualifiedName();
	if(typename==null||typename.isEmpty())
		return;
	
       CtClass classname = parser.getClassMap().get(typename); 

	if(classname!=null) {
		Set<CtMethod> overloadmethods=classname.getMethods();
           for(CtMethod methodoverloaded : overloadmethods) {
           	if(call.getExecutable().getSimpleName().equals(methodoverloaded.getSimpleName())) {
           	  List<CtParameter> paramlist=methodoverloaded.getParameters();
           	  List<String> target=resolveParams(paramlist);
           	  transformOneMethod(origTypes,target, call);
           	}
           }
	} else {
		List<Class[]> params = parser.fetchMethods(typename, call.getExecutable().getSimpleName());
		for (Class[] p : params)
			transformOneConstructor(origTypes, call, p);
	}
}
 
Example #18
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 #19
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 #20
Source File: MethodXVariableReplacementOp.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
protected List<Ingredient> computeIngredientsFromMInvokToReplace(ModificationPoint modificationPoint,
		CtInvocation invocationToReplace) {

	List<Ingredient> ingredients = new ArrayList<>();
	List<CtVariable> varsInContext = modificationPoint.getContextOfModificationPoint();

	for (CtVariable iVarInContext : varsInContext) {

		if (!SupportOperators.checkIsSubtype(iVarInContext.getType(), invocationToReplace.getType())) {
			continue;
		}

		CtVariableAccess iVarAccessFromContext = MutationSupporter.getFactory()
				.createVariableRead(iVarInContext.getReference(), false);
		Ingredient ingredient = new Ingredient(iVarAccessFromContext);
		// we use this property to indicate the old variable to replace
		ingredient.setDerivedFrom(invocationToReplace);
		ingredients.add(ingredient);

	}

	return ingredients;
}
 
Example #21
Source File: Collector.java    From spoon-examples with 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 #22
Source File: VariableAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private int[] argumentDiff(List<CtElement> argumentsoriginal, List<CtElement> argumentsother, CtVariableAccess varaccess) {
	
	int numberdiffargument =0;
	int numberdiffvarreplacebyvar =0;
	int numberdiffvarreplacebymethod =0;
	
	for(int index=0; index<argumentsoriginal.size(); index++) {
		
		CtElement original = argumentsoriginal.get(index);
		CtElement other = argumentsother.get(index);
		
		if(original.equals(other) || original.toString().equals(other.toString())) {
			// same
		} else {
			numberdiffargument+=1;
			if(original instanceof CtVariableAccess && original.equals(varaccess)) {
				if(other instanceof CtVariableAccess)
					numberdiffvarreplacebyvar+=1;
				else if(other instanceof CtInvocation || other instanceof CtConstructorCall)
					numberdiffvarreplacebymethod+=1;
				else {
					// do nothing
				}
			}
		}
	}

	int diffarray[]=new int[3];
	diffarray[0]=numberdiffargument;
	diffarray[1]=numberdiffvarreplacebyvar;
	diffarray[2]=numberdiffvarreplacebymethod;

       return diffarray;
}
 
Example #23
Source File: MethodXVariableReplacementOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected List<CtInvocation> getInvocations(CtElement suspiciousElement) {
	List<CtInvocation> invocations = null;
	if (targetElement == null)
		invocations = suspiciousElement.getElements(e -> (e instanceof CtInvocation));
	else {
		invocations = new ArrayList<>();
		invocations.add((CtInvocation) targetElement);
	}
	return invocations;
}
 
Example #24
Source File: SimpleMethodReplacement.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public SimpleMethodReplacement(ModificationPoint modificationPoint, CtInvocation previousOriginal,
		CtInvocation newExpression, AstorOperator astoroperator) {
	super();
	this.previousOriginal = previousOriginal;
	this.newExpression = newExpression;

	super.setOperationApplied(astoroperator);
	super.setModificationPoint(modificationPoint);
}
 
Example #25
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static List<CtInvocation> createRealInvocationsAllPosibilities(ModificationPoint point,
		CtMethod anotherMethod, CtExpression target) {

	// All the possibles variables
	List<List<CtExpression<?>>> possibleArguments = computeParameters(anotherMethod, point);
	if (possibleArguments == null || possibleArguments.isEmpty())
		return Collections.EMPTY_LIST;

	List<CtInvocation> newInvocations = realInvocationsFromCombination(anotherMethod, target, possibleArguments);
	return newInvocations;
}
 
Example #26
Source File: OperatorGenerator.java    From astor with 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 #27
Source File: AssertionAdder.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
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 #28
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> void visitCtInvocation(CtInvocation<T> invocation) {
	super.visitCtInvocation(invocation);
	
	if (fetchInClassOverload(invocation, this.modificationPoint.getCtClass())) {
		 log.info("sucesfully find overload methdods in the same class");
	 } else {
		 log.info("seek overload methdods in the imported libs");
		 fetchLibOverload(invocation);	
	 }
}
 
Example #29
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean fetchInClassOverload(CtInvocation call, CtClass classname) {
	
	if(!call.getTarget().getType().getQualifiedName().equals(classname.getQualifiedName())) {
		return false;
	}
	
	String name = call.getExecutable().getSimpleName();
	Set<CtMethod> methods=classname.getMethods();
	List<CtMethod> overloadmethods = new ArrayList<CtMethod>();
	for(CtMethod method: methods) {
		if(method.getSimpleName().equals(name))
			overloadmethods.add(method);
	}
	
	if (overloadmethods.size() == 0)
		return false;
	if (overloadmethods.size()== 1) {
		return true;
	}
	
	List<String> origTypes = resolveTypes(call.getArguments());

	if (origTypes == null)
		return true;
	for (CtMethod mtd : overloadmethods) {
		transformOneMethod(origTypes, resolveParams(mtd.getParameters()), call);
	}
	return true;
}
 
Example #30
Source File: IngredientProcessorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1PreconditionWithExpressionIngredientOnMethodInvocation() throws Exception {

	CommandSummary command = MathCommandsTests.getMath70Command();
	command.command.put("-mode", "jgenprog");
	command.command.put("-maxgen", "0");
	command.command.put("-loglevel", "DEBUG");
	command.command.put("-scope", "local");
	command.command.put("-stopfirst", "true");
	command.command.put("-flthreshold", "0.0");
	command.command.put("-saveall", "true");
	command.command.put(ExtensionPoints.TARGET_CODE_PROCESSOR.argument(),
			MethodInvocationFixSpaceProcessor.class.getName());
	command.command.put(ExtensionPoints.TARGET_INGREDIENT_CODE_PROCESSOR.argument(),
			ExpressionBooleanIngredientSpaceProcessor.class.getName());
	AstorMain main = new AstorMain();
	main.execute(command.flat());

	IngredientBasedEvolutionaryRepairApproachImpl approach = (IngredientBasedEvolutionaryRepairApproachImpl) main
			.getEngine();
	List<ModificationPoint> modificationPoints = approach.getVariants().get(0).getModificationPoints();
	for (ModificationPoint modificationPoint : modificationPoints) {
		assertTrue("type: " + modificationPoint.getCodeElement(),
				modificationPoint.getCodeElement() instanceof CtInvocation);
	}
	AstorCtIngredientPool pool = (AstorCtIngredientPool) approach.getIngredientPool();
	for (Ingredient ingredient : pool.getAllIngredients()) {
		assertTrue(ingredient.getCode() instanceof CtExpression);
		CtExpression expr = (CtExpression) ingredient.getCode();
		assertEquals("boolean", expr.getType().unbox().toString());
	}

	assertNotEquals(AstorOutputStatus.ERROR, main.getEngine().getOutputStatus());
}