Java Code Examples for spoon.reflect.code.CtInvocation

The following examples show how to use spoon.reflect.code.CtInvocation. 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
/**
 * 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 2
Source Project: nopol   Source File: ClassCollector.java    License: 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 3
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 4
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: 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 Project: coming   Source File: ConstructorAnalyzer.java    License: 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 6
Source Project: coming   Source File: MethodAnalyzer.java    License: 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 Project: coming   Source File: MethodAnalyzer.java    License: 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 Project: coming   Source File: MethodAnalyzer.java    License: 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 Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: 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 Project: astor   Source File: UnwrapfromMethodCallOp.java    License: 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
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 12
Source Project: astor   Source File: SupportOperators.java    License: 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 13
Source Project: astor   Source File: MetaGenerator.java    License: 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 14
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 15
@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 16
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: 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 Project: astor   Source File: TransformStrategy.java    License: 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 18
Source Project: astor   Source File: ExpressionRevolver.java    License: 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 19
@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 20
@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 21
Source Project: spoon-examples   Source File: Collector.java    License: GNU General Public License v2.0 5 votes vote down vote up
void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
	List<CtMethod> getters = getGetters(localVariable);
	getters.forEach(getter -> {
		CtInvocation invocationToGetter =
				invok(getter, localVariable);
		CtInvocation invocationToObserve =
				createObserve(getter, invocationToGetter);
		testMethod.getBody().insertEnd(invocationToObserve);
	});
}
 
Example 22
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 23
@SuppressWarnings("unchecked")
void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) {
	List<CtMethod> getters =
			getGetters(localVariable);
	getters.forEach(getter -> {
		String key = getKey(getter);
		CtInvocation invocationToGetter =
				invok(getter, localVariable);
		CtInvocation invocationToAssert = createAssert("assertEquals",
				factory.createLiteral(Logger.observations.get(key)), // expected
				invocationToGetter); // actual
		testMethod.getBody().insertEnd(invocationToAssert);
	});
}
 
Example 24
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 25
Source Project: coming   Source File: VariableAnalyzer.java    License: 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 26
Source Project: coming   Source File: WholeStatementAnalyzer.java    License: MIT License 5 votes vote down vote up
private void analyzeS15_HasObjectiveInvocations(CtElement element, Cntx<Object> context, CtClass parentClass,
		List<CtInvocation> invocationstostudy) {

	try {
		boolean S15anyReturnObjective = false;

		for (CtInvocation invocation : invocationstostudy) {

			CtStatement parent = invocation.getParent(new LineFilter());

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

			if ((invocation.getType() != null && !invocation.getType().isPrimitive())
					|| whetherhasobjective(inferPotentionalTypes(invocation, parentClass))) {
				S15anyReturnObjective = true;
			}

			if (S15anyReturnObjective)
				break;
		}

		context.put(CodeFeatures.S15_HAS_OBJECTIVE_METHOD_CALL, S15anyReturnObjective);
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 27
Source Project: coming   Source File: ExpressionAnalyzer.java    License: MIT License 5 votes vote down vote up
private boolean[] analyzeExpression(CtExpression expressionToStudy, Cntx<Object> context, List allMethods,
		List<CtInvocation> invocationsFromClass, CtClass parentclass) {
	
	try {
		
		if(expressionToStudy instanceof CtVariableAccess)
			return null;
		
		boolean hasExpressionReturnParmeterCompatible = false;
		boolean hasExpressionParmeterCompatible = false;
		
		if(checkMethodDeclarationWithParameterReturnCompatibleType(allMethods, expressionToStudy.getType()) != null 
			|| checkInvocationWithParameterReturnCompatibleType(invocationsFromClass,
						expressionToStudy.getType(), parentclass) != null) {
			hasExpressionReturnParmeterCompatible = true;
		}
		
		if (checkMethodDeclarationWithParemetrCompatibleType(allMethods, expressionToStudy.getType()) != null
				|| checkInvocationWithParemetrCompatibleType (invocationsFromClass,
						expressionToStudy.getType()) != null) {
			hasExpressionParmeterCompatible = true;
		}

		boolean[] expressionTypeFeatures= new boolean[2];
		
		expressionTypeFeatures[0] = hasExpressionReturnParmeterCompatible;
		
		expressionTypeFeatures[1] = hasExpressionParmeterCompatible;

		return expressionTypeFeatures;

	} catch (Throwable e) {
		e.printStackTrace();
	}
	
	return null;
}
 
Example 28
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: MIT License 5 votes vote down vote up
/**
 * // For any variable involved in a logical expression,whether exist methods //
 * (method declaration or method call) in scope (that is in the same faulty //
 * class // since we do not assume full program) that take variable whose type
 * is same // with vas one of its parameters and return boolean
 * 
 * @param logicalExperssions
 * @param context
 * @param allMethods
 * @param logicalExperssions
 * @param invocationsFromClass
 * @param parentclass
 */
private void analyzeLE2_AffectedVariablesInMethod(List<CtExpression> logicalExperssions,
		Cntx<Object> context, List allMethods, List<CtInvocation> invocationsFromClass, CtClass parentclass) {
	
	try {

		for (int indexlogical=0; indexlogical<logicalExperssions.size(); indexlogical++) {
			
               CtExpression logicalexpression = logicalExperssions.get(indexlogical);
			
			List<CtVariableAccess> varsAffected = VariableResolver.collectVariableAccess(logicalexpression, false);
			
			boolean hasAnyLES2paramCompatibleWithBooleanReturn = false;

			for (CtVariableAccess varAffected : varsAffected) {

				if (// First, Let's analyze the method declaration
				checkBooleanMethodDeclarationWithTypeInParameter(allMethods, varAffected) != null
						// Second, let's inspect invocations
						|| checkBooleanInvocationWithParameterReturn(invocationsFromClass, varAffected, parentclass) != null) {
					hasAnyLES2paramCompatibleWithBooleanReturn = true;
				}

                   if(hasAnyLES2paramCompatibleWithBooleanReturn)
                   	break;
			}

			writeGroupedInfo(context, "logical_expression_"+Integer.toString(indexlogical)+"_"+logicalexpression, 
					CodeFeatures.LE2_IS_BOOLEAN_METHOD_PARAM_TYPE_VAR,
					hasAnyLES2paramCompatibleWithBooleanReturn, "FEATURES_LOGICAL_EXPRESSION");
		}

	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 29
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 5 votes vote down vote up
private void analyzeVarMethodNameSimilarM12 (List<CtInvocation> invocationsaffected, List<CtVariable> scopevars, Cntx<Object> context) {
	
	 try {
		 for (CtInvocation invAffected : invocationsaffected) {
			
			boolean M12hasvarsimiplarinname = false;
			
			String methodname=invAffected.getExecutable().getSimpleName(); 
			
			for (CtVariable aVarInScope : scopevars) {
				
				String varname=aVarInScope.getSimpleName();
				varname=varname.replaceAll("[^a-zA-Z0-9]", "");
				if(varname.length()>3) {
					if(methodname.toLowerCase().endsWith(varname.toLowerCase()) || methodname.toLowerCase().equals("length") ||
							methodname.toLowerCase().contains("version") || methodname.toLowerCase().contains("clone")) {
						M12hasvarsimiplarinname = true;
						break;
					}
				}
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(invAffected),
					CodeFeatures.M12_Has_Var_Similar_In_Name, 
					M12hasvarsimiplarinname, "FEATURES_METHODS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 30
Source Project: coming   Source File: MethodAnalyzer.java    License: MIT License 5 votes vote down vote up
private int[] argumentDiffMethod(List<CtElement> argumentsoriginal, List<CtElement> argumentsother, 
	   CtInvocation invocationaccess) {
	
	int numberdiffargument =0;
	int numberdiffmethodreplacebyvar =0;
	int numberdiffmethodreplacebymethod =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 CtInvocation && original.equals(invocationaccess)) {
				if(other instanceof CtVariableAccess)
					numberdiffmethodreplacebyvar+=1;
				else if(other instanceof CtInvocation || other instanceof CtConstructorCall)
					numberdiffmethodreplacebymethod+=1;
				else {
					// do nothing
				}
			}
		}
	}

	int diffarray[]=new int[3];
	diffarray[0]=numberdiffargument;
	diffarray[1]=numberdiffmethodreplacebyvar;
	diffarray[2]=numberdiffmethodreplacebymethod;

      return diffarray;
}