Java Code Examples for spoon.reflect.declaration.CtExecutable

The following examples show how to use spoon.reflect.declaration.CtExecutable. 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
@Override
public void process(CtParameter<?> element) {
	// we declare a new snippet of code to be inserted.
	CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();

	// this snippet contains an if check.
	final String value = String.format("if (%s == null) "
			+ "throw new IllegalArgumentException(\"[Spoon inserted check] null passed as parameter\");",
			element.getSimpleName());
	snippet.setValue(value);

	// we insert the snippet at the beginning of the method body.
	if (element.getParent(CtExecutable.class).getBody() != null) {
		element.getParent(CtExecutable.class).getBody().insertBegin(snippet);
	}
}
 
Example 2
public void process(Bound annotation, CtParameter<?> element) {
	// Is to be process?
	CtExecutable<?> e = element.getParent();
	if (e.getBody() == null) {
		return;
	}

	// Use template.
	CtClass<?> type = e.getParent(CtClass.class);
	Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max());
	final CtBlock apply = (CtBlock) t.apply(type);

	// Apply transformation.
	for (int i = apply.getStatements().size() - 1; i >= 0; i--) {
		final CtStatement statement = apply.getStatement(i);
		statement.delete();
		e.getBody().insertBegin(statement);
	}
}
 
Example 3
Source Project: astor   Source File: StatementSupporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the implicitly of a block. Workarround for Spoon 5.4.0
 * 
 * @param block
 * @param isInsert
 */
public static void updateBlockImplicitly(CtBlock block, boolean isInsert) {

	if (!block.isImplicit() && block.getStatements().size() == 1 && !(block.getParent() instanceof CtExecutable)) {
		block.setImplicit(true);
	} else {
		if (isInsert) {
			if (block.isImplicit() && block.getStatements().size() > 1) {
				block.setImplicit(false);
			}
		} else {// Delete
			if (block.isImplicit() && block.getStatements().size() == 0) {
				block.setImplicit(false);
			}
		}
	}
}
 
Example 4
private void setfilter() {
	if (cls.equals(CtType.class)) {
		typeFilter = new TypeFilter<CtType>(CtType.class) {
			@Override
			public boolean matches(CtType element) {
				// Definition of "top level" CtType.
				return element.getParent(CtType.class) == null
						&& !element.isImplicit();
			}
		};
	} else if (cls.equals(CtExecutable.class)) {
		typeFilter = new TypeFilter<CtExecutable>(CtExecutable.class) {
			@Override
			public boolean matches(CtExecutable element) {
				// Definition of "top level" CtExecutable.
				return element.getParent(CtExecutable.class) == null
						&& !element.isImplicit()
						&& !(element instanceof CtAnonymousExecutable);
			}
		};
	} else {
		log.error("Invalid clonegranularity");
		throw new IllegalArgumentException();
	}
	log.debug("clonegranularity: " + cls.getName());
}
 
Example 5
Source Project: astor   Source File: DeepRepairEngine.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void loadCloneGranularity() throws Exception {
	ExtensionPoints cloneGranularityEP = ExtensionPoints.CLONE_GRANULARITY;

	String property = ConfigurationProperties.getProperty(cloneGranularityEP.identifier);

	Class cloneGranularity = null;
	if (property == null || property.trim().isEmpty() || property.equals("type")) {
		cloneGranularity = CtType.class;

	} else if (property.equals("executable")) {
		cloneGranularity = CtExecutable.class;
	} else {
		cloneGranularity = PlugInLoader.loadClassFromProperty(cloneGranularityEP);
		if (cloneGranularity == null) {
			cloneGranularity = CtType.class;
		}
	}
	ConfigurationProperties.setProperty("clonegranularity", cloneGranularity.getName());
}
 
Example 6
Source Project: nopol   Source File: StatCollector.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean isMethod(CtElement ctElement) {
    CtExecutable parent = ctElement.getParent(CtExecutable.class);
    if (parent == null) {
        return false;
    }
    return parent.getSimpleName().equals(buggyMethod);
}
 
Example 7
Source Project: spoon-examples   Source File: DocProcessor.java    License: 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 8
Source Project: spoon-examples   Source File: LogProcessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtExecutable element) {
	CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();

	// Snippet which contains the log.
	final String value = String.format("System.out.println(\"Enter in the method %s from class %s\");",
			element.getSimpleName(),
			element.getParent(CtClass.class).getSimpleName());
	snippet.setValue(value);

	// Inserts the snippet at the beginning of the method body.
	if (element.getBody() != null) {
		element.getBody().insertBegin(snippet);
	}
}
 
Example 9
Source Project: astor   Source File: IngredientPoolTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testMath85ScopeMethodSpace() throws Exception {

	AstorMain main1 = new AstorMain();
	String dep = new File("./examples/libs/junit-4.4.jar").getAbsolutePath();
	String[] args = new String[] { "-dependencies", dep, "-mode", "jgenprog", "-failing",
			"org.apache.commons.math.distribution.NormalDistributionTest", "-location",
			new File("./examples/math_85").getAbsolutePath(), "-package", "org.apache.commons", "-srcjavafolder",
			"/src/java/", "-srctestfolder", "/src/test/", "-binjavafolder", "/target/classes", "-bintestfolder",
			"/target/test-classes", "-javacompliancelevel", "7", "-flthreshold", "0.5", "-stopfirst", "false",
			// We put 0 as max generation, so we force to not evolve the
			// population
			"-maxgen", "0", "-scope", MethodBasicIngredientScope.class.getCanonicalName(), //
			"-seed", "10", "-ingredientstrategy", ShortestIngredientSearchStrategy.class.getName() };

	main1.execute(args);
	JGenProg astor = (JGenProg) main1.getEngine();
	IngredientSearchStrategy ingStrategy = astor.getIngredientSearchStrategy();

	//
	AstorOperator operator = new ReplaceOp();
	// Let's take a modification point from the first variant. I take the
	// element at 12, it's an assignement.
	ModificationPoint mpoint = astor.getVariants().get(0).getModificationPoints().get(12);
	Ingredient ingLast = ingStrategy.getFixIngredient(mpoint, operator);
	Assert.assertNotNull(ingLast);

	List<String> methods = ingStrategy.getIngredientSpace().getLocations();
	Assert.assertTrue(methods.size() > 0);

	List<Ingredient> ingredients = ingStrategy.getIngredientSpace().getIngredients(mpoint.getCodeElement());
	Assert.assertTrue(ingredients.size() > 0);
	Assert.assertTrue(hasIngredient(ingredients, ingLast));

	CtExecutable exec = (mpoint.getCodeElement().getParent(CtExecutable.class));
	for (Ingredient ctCodeElement : ingredients) {
		assertEquals(exec, ctCodeElement.getCode().getParent(CtExecutable.class));
	}

}
 
Example 10
private String getkey(T element) {
	String key;
	if (element instanceof CtExecutable) {
		key = element.getParent(CtType.class).getQualifiedName() + "#" + ((CtExecutable<?>) element).getSignature();
	} else if (element instanceof CtType) {
		key = ((CtType<?>) element).getQualifiedName();
	} else {
		log.error("Invalid clonegranularity");
		throw new IllegalArgumentException();
	}
	return key;
}
 
Example 11
@Override
public boolean matches(CtExecutable element) {
	// Definition of "top level" CtExecutable.
	boolean t = element.getParent(CtExecutable.class) == null && !element.isImplicit()
			&& !(element instanceof CtAnonymousExecutable);
	return t;
}
 
Example 12
private String getkey(T element) {
	String key;
	if (element instanceof CtExecutable) {
		key = element.getParent(CtType.class).getQualifiedName() + "#" + ((CtExecutable<?>) element).getSignature();
	} else if (element instanceof CtType) {
		key = ((CtType<?>) element).getQualifiedName();
	} else {
		log.error("Invalid clonegranularity");
		throw new IllegalArgumentException();
	}
	return key;
}
 
Example 13
Source Project: coming   Source File: VariableAnalyzer.java    License: MIT License 4 votes vote down vote up
private void analyzeV15_LastthreeVariableIntroduction (List<CtVariableAccess> varsAffected, CtElement element,
		Cntx<Object> context) {
	try {
		
		CtExecutable methodParent = element.getParent(CtExecutable.class);

		if (methodParent == null)
			// the element is not in a method.
			return;
		
		List<CtStatement> statements=methodParent.getElements(new LineFilter());

		// For each variable affected
		for (CtVariableAccess variableAffected : varsAffected) {

			List<CtStatement> statementbefore = new ArrayList<>();
			
			boolean lastthreesametypeloc=false;

			for (CtStatement aStatement : statements) {

				CtStatement parent = variableAffected.getParent(new LineFilter());
									
				if (!isElementBeforeVariable(variableAffected, aStatement))
					continue;
				
				if (isStatementInControl(parent, aStatement) || parent==aStatement)
					continue;
				
				if(aStatement instanceof CtIf || aStatement instanceof CtLoop) 
					continue;
				
				statementbefore.add(aStatement);
			}
			
			List<CtStatement> statinterest = new ArrayList<>();
			
			if(statementbefore.size()<=4)
				statinterest=statementbefore;
			else {
				statinterest.add(statementbefore.get(statementbefore.size()-1));
				statinterest.add(statementbefore.get(statementbefore.size()-2));
				statinterest.add(statementbefore.get(statementbefore.size()-3));
				statinterest.add(statementbefore.get(statementbefore.size()-4));
			}

			for (int index=0; index< statinterest.size(); index++) {
				if(statinterest.get(index) instanceof CtLocalVariable) {
					CtLocalVariable ctLocalVariable=(CtLocalVariable)statinterest.get(index);

					if (!ctLocalVariable.getReference().getSimpleName()
							.equals(variableAffected.getVariable().getSimpleName()) 
							&& compareTypes(ctLocalVariable.getType(), variableAffected.getType())) {
						lastthreesametypeloc = true;
						break;
					}
				}
			}
			
			writeGroupedInfo(context, adjustIdentifyInJson(variableAffected), 
					CodeFeatures.V15_VAR_LAST_THREE_SAME_TYPE_LOC,
					(lastthreesametypeloc), "FEATURES_VARS");
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 14
Source Project: coming   Source File: WholeStatementAnalyzer.java    License: MIT License 4 votes vote down vote up
/**
 * whether the associated method or class for the faulty line throws exception
 * 
 * @param element
 * @param context
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private void analyzeS6S11_Method_Method_Features(CtElement element, Cntx<Object> context) {
	try {

		CtExecutable parentMethod = element.getParent(CtExecutable.class);

		CtClass parentClass = element.getParent(CtClass.class);

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

		if (potentionalTryCatch != null && whethereffectivetrycatch(potentionalTryCatch, parent)) {

			context.put(CodeFeatures.S6_METHOD_THROWS_EXCEPTION, false);
			context.put(CodeFeatures.S11_FAULTY_CLASS_EXCEPTION_TYPE, false);

		} else {

			if (parentMethod != null) {
				// Exception
				context.put(CodeFeatures.S6_METHOD_THROWS_EXCEPTION, parentMethod.getThrownTypes().size() > 0);
			}

			boolean s11ExceptionType = false;

			if (parentClass != null) {

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

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

				if (superInterfaces.size() > 0) {
					for (CtTypeReference specificreference : superInterfaces) {
						if (specificreference != null
								&& specificreference.getQualifiedName().toLowerCase().indexOf("exception") != -1) {
							s11ExceptionType = true;
							break;
						}
					}
				}
				context.put(CodeFeatures.S11_FAULTY_CLASS_EXCEPTION_TYPE, s11ExceptionType);
			}
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example 15
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: MIT License 4 votes vote down vote up
public boolean[] analyze_SametypewithGuard(List<CtVariableAccess> varsAffected, CtElement element,
			CtClass parentClass, List<CtStatement> statements) {

		boolean hasPrimitiveSimilarTypeWithNormalGuard = false;
		boolean hasObjectSimilarTypeWithNormalGuard = false;
		boolean hasPrimitiveSimilarTypeWithNullGuard = false;
		boolean hasObjectSimilarTypeWithNullGuard = false;

		try {
			CtExecutable faultyMethodParent = element.getParent(CtExecutable.class);

			if (faultyMethodParent == null)
				// the element is not in a method.
				return null;

			// For each variable affected
			for (CtVariableAccess variableAffected : varsAffected) {
				// for (CtStatement aStatement : statements) {
				CtStatement parent = variableAffected.getParent(new LineFilter());

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

				// For each statement in the method (it includes the statements inside the
				// blocks (then, while)!)
				for (CtStatement aStatement : statements) {
					// for (CtVariableAccess variableAffected : varsAffected) {

					if (parent == aStatement)
						continue;

					List<CtVariableAccess> varsFromStatement;

					if (aStatement instanceof CtIf || aStatement instanceof CtLoop) {
						varsFromStatement = VariableResolver.collectVariableRead(retrieveElementToStudy(aStatement));
					} else
						varsFromStatement = VariableResolver.collectVariableRead(aStatement);
//
//					// let's collect the var access in the statement
//					List<CtVariableAccess> varsFromStatement = VariableResolver
//							.collectVariableReadIgnoringBlocks(aStatement);
					// if the var access is the same that the affected
					for (CtVariableAccess varInStatement : varsFromStatement) {
						// Has similar type but different name
						if (compareTypes(variableAffected.getVariable().getType(),
								varInStatement.getVariable().getType())) {
							// && !hasSameName(variableAffected, varInStatement)) {
							// Now, let's check if the parent is a guard
							// if (isGuard(getParentNotBlock(aStatement))) {
							if (isNormalGuard(varInStatement, (aStatement))) {

								// it's ok, now let's check the type
								if (variableAffected.getType() != null) {
									// for primitive type variables, we require it to be the same global variable
									if (variableAffected.getType().isPrimitive() && varInStatement.getVariable()
											.getSimpleName().equals(variableAffected.getVariable().getSimpleName()))
										hasPrimitiveSimilarTypeWithNormalGuard = true;
									else
										hasObjectSimilarTypeWithNormalGuard = true;
								}
							}

							if (isNullCheckGuard(varInStatement, (aStatement))) {

								// it's ok, now let's check the type
								if (variableAffected.getType() != null) {

									if (variableAffected.getType().isPrimitive() && varInStatement.getVariable()
											.getSimpleName().equals(variableAffected.getVariable().getSimpleName()))
										hasPrimitiveSimilarTypeWithNullGuard = true;
									else
										hasObjectSimilarTypeWithNullGuard = true;
								}
							}

						}
					}
					// If we find both cases, we can stop
					if (hasPrimitiveSimilarTypeWithNormalGuard && hasObjectSimilarTypeWithNormalGuard
							&& hasPrimitiveSimilarTypeWithNullGuard && hasObjectSimilarTypeWithNullGuard)
						break;
				}
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}

		boolean[] expressionvalue = new boolean[4];
		expressionvalue[0] = hasObjectSimilarTypeWithNormalGuard;
		expressionvalue[1] = hasPrimitiveSimilarTypeWithNormalGuard;
		expressionvalue[2] = hasObjectSimilarTypeWithNullGuard;
		expressionvalue[3] = hasPrimitiveSimilarTypeWithNullGuard;

		return expressionvalue;

	}
 
Example 16
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 17
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 18
/**
 *
 * 
 * @param suspiciousElement
 * @param context
 * @return
 */
@Override
public MapList<CtInvocation, Ingredient> retrieveInvocationIngredient(ModificationPoint point) {
	CtElement suspiciousElement = point.getCodeElement();

	CtClass classUnderAnalysis = suspiciousElement.getParent(CtClass.class);

	MapList<CtInvocation, Ingredient> similarInvocationResult = new MapList<>();

	List<CtInvocation> invocations = getInvocations(suspiciousElement);
	for (CtInvocation invocationToReplace : invocations) {

		CtExecutable minvokedInAffected = invocationToReplace.getExecutable().getDeclaration();

		if (minvokedInAffected == null || !(minvokedInAffected instanceof CtMethod))
			continue;

		CtMethod affectedMethod = (CtMethod) minvokedInAffected;

		CtType typeOfTarget = invocationToReplace.getTarget().getType().getTypeDeclaration();

		if (!(typeOfTarget instanceof CtClass))
			continue;

		CtClass targetOfInvocation = (CtClass) typeOfTarget;

		List allMethods = SupportOperators.getAllMethodsFromClass(targetOfInvocation);

		for (Object omethod : allMethods) {

			if (!(omethod instanceof CtMethod))
				continue;

			CtMethod anotherMethod = (CtMethod) omethod;

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

			if (anotherMethod.getSignature().equals(affectedMethod.getSignature()))
				// It's the same, we discard it.
				continue;

			// Only if the target is the class we can call to non public methods
			if (!targetOfInvocation.equals(classUnderAnalysis) && !anotherMethod.isPublic())
				continue;

			// The name must be the same
			if (anotherMethod.getSimpleName().equals(affectedMethod.getSimpleName())) {

				if (anotherMethod.getType() != null && minvokedInAffected.getType() != null) {

					boolean compatibleReturnTypes = SupportOperators.checkIsSubtype(anotherMethod.getType(),
							minvokedInAffected.getType());
					// must return the same object
					if (compatibleReturnTypes) {

						// Case 3: Different number argument
						if (anotherMethod.getParameters().size() != affectedMethod.getParameters().size()
								// check the types
								|| (!anotherMethod.getParameters().isEmpty()
										&& !affectedMethod.getParameters().isEmpty()
										&& !anotherMethod.getParameters().equals(affectedMethod.getParameters()))) {

							List<CtInvocation> newInvToMethods = SupportOperators
									.createRealInvocationsReusingVars(point, anotherMethod, invocationToReplace);

							for (CtInvocation ctInvocation : newInvToMethods) {
								CtInvocation newInvocation = ctInvocation.clone();
								newInvocation.setExecutable(anotherMethod.getReference());
								Ingredient newIngredient = new Ingredient(newInvocation);
								newIngredient.setDerivedFrom(invocationToReplace);
								similarInvocationResult.add(invocationToReplace, newIngredient);
								newIngredient.getMetadata().put("original", invocationToReplace);
								newIngredient.getMetadata().put("replacement", ctInvocation);

							}

						}
					}

				}
			}
		}

	}
	return similarInvocationResult;

}
 
Example 19
/**
 * Case 1: Argument removement
 * 
 * @param suspiciousElement
 * @param context
 * @return
 */
@Override
public MapList<CtInvocation, Ingredient> retrieveInvocationIngredient(ModificationPoint point) {

	CtElement suspiciousElement = point.getCodeElement();
	CtClass classUnderAnalysis = suspiciousElement.getParent(CtClass.class);

	MapList<CtInvocation, Ingredient> similarInvocationResult = new MapList<>();

	List<CtInvocation> invocations = getInvocations(suspiciousElement);

	for (CtInvocation invocationToReplace : invocations) {

		CtExecutable minvokedInAffected = invocationToReplace.getExecutable().getDeclaration();

		if (minvokedInAffected == null || !(minvokedInAffected instanceof CtMethod))
			continue;

		CtMethod affectedMethod = (CtMethod) minvokedInAffected;

		CtType typeOfTarget = invocationToReplace.getTarget().getType().getTypeDeclaration();

		if (!(typeOfTarget instanceof CtClass))
			continue;

		CtClass targetOfInvocation = (CtClass) typeOfTarget;

		List allMethods = SupportOperators.getAllMethodsFromClass(targetOfInvocation);

		for (Object omethod : allMethods) {

			if (!(omethod instanceof CtMethod))
				continue;

			CtMethod anotherMethod = (CtMethod) omethod;

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

			if (anotherMethod.getSignature().equals(affectedMethod.getSignature()))
				// It's the same, we discard it.
				continue;

			// Only if the target is the class we can call to non public methods
			if (!targetOfInvocation.equals(classUnderAnalysis) && !anotherMethod.isPublic())
				continue;

			// The name must be the same
			if (anotherMethod.getSimpleName().equals(affectedMethod.getSimpleName())) {

				if (anotherMethod.getType() != null && minvokedInAffected.getType() != null) {

					boolean compatibleReturnTypes = SupportOperators.checkIsSubtype(anotherMethod.getType(),
							minvokedInAffected.getType());
					// must return the same object
					if (compatibleReturnTypes) {

						// CASE 1: Different method name
						if (anotherMethod.getParameters().size() < affectedMethod.getParameters().size()) {

							List newArguments = SupportOperators.checkOcurrenceOfOtherParameters(anotherMethod,
									affectedMethod, invocationToReplace.getArguments());
							if (newArguments != null) {

								CtInvocation newInvocation = MutationSupporter.getFactory().createInvocation(
										invocationToReplace.getTarget(), anotherMethod.getReference(),
										newArguments);
								newInvocation.setExecutable(anotherMethod.getReference());
								newInvocation.setArguments(newArguments);
								newInvocation.setTarget(invocationToReplace.getTarget());

								Ingredient newIngredient = new Ingredient(newInvocation);
								newIngredient.setDerivedFrom(invocationToReplace);

								similarInvocationResult.add(invocationToReplace, newIngredient);

								newIngredient.getMetadata().put("original", invocationToReplace);
								newIngredient.getMetadata().put("replacement", newInvocation);
							}
						}
					}

				}
			}
		}

	}
	return similarInvocationResult;

}
 
Example 20
@Override
public String calculateLocation(CtElement original) {
	CtExecutable method =  original.getParent(CtExecutable.class);
	return method.getReference().toString();
}
 
Example 21
Source Project: astor   Source File: LangTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
public CommandSummary commandLang8(String dep, File out, boolean step) {

		ClassLoader classLoader = getClass().getClassLoader();
		File learningDir = new File(classLoader.getResource("learninglang8").getFile());
		Class cloneGranularityClass = CtExecutable.class;
		String scope = CtClassIngredientSpace.class.getCanonicalName();

		String[] args = new String[] { "-dependencies", dep, "-mode", "jgenprog", "-failing",
				"org.apache.commons.lang3.time.FastDateFormat_PrinterTest" + File.pathSeparator
						+ "org.apache.commons.lang3.time.FastDatePrinterTest",
				//
				"-location", new File("./examples/lang_8/").getAbsolutePath(),
				//
				//
				// "-package", "org.apache.commons",
				"-srcjavafolder", "/src/main/java/", "-srctestfolder", "/src/test/java/", "-binjavafolder",
				"/target/classes/", //
				"-bintestfolder", "/target/tests/", "-javacompliancelevel", "6", "-flthreshold", "0.1",
				//
				"-out", out.getAbsolutePath(), "-scope", "package", "-seed", "60", "-maxgen", "200",
				//
				"-stopfirst", "true", "-maxtime", "10", (step) ? "-testbystep" : "",
				// "-validation", RegressionValidation.class.getName(),
				//
				// "-ignoredtestcases",
				// "org.apache.commons.lang.LocaleUtilsTest",
				"-timezone", "America/New_York",
				//
				"-scope", scope,
				//
				"-learningdir", learningDir.getAbsolutePath(),
				//
				"-clonegranularity", cloneGranularityClass.getCanonicalName(),
				//
				"-ingredientstrategy", CloneIngredientSearchStrategy.class.getName(),
				//
				"-transformingredient",

		};
		return new CommandSummary(args);
	}
 
Example 22
@Override
public boolean matches(CtExecutable element) {
	// Definition of "top level" CtExecutable.
	return element.getParent(CtExecutable.class) == null && !element.isImplicit()
			&& !(element instanceof CtAnonymousExecutable);
}
 
Example 23
/**
 * For case 2
 * 
 * @param suspiciousElement
 * @param context
 * @return
 */
@Override
public MapList<CtInvocation, Ingredient> retrieveInvocationIngredient(ModificationPoint point) {
	CtElement suspiciousElement = point.getCodeElement();

	CtClass classUnderAnalysis = suspiciousElement.getParent(CtClass.class);

	MapList<CtInvocation, Ingredient> similarInvocationResult = new MapList<>();

	List<CtInvocation> invocations = getInvocations(suspiciousElement);

	for (CtInvocation invocationToReplace : invocations) {

		CtExecutable minvokedInAffected = invocationToReplace.getExecutable().getDeclaration();

		if (minvokedInAffected == null || !(minvokedInAffected instanceof CtMethod))
			continue;

		CtMethod affectedMethod = (CtMethod) minvokedInAffected;

		CtType typeOfTarget = invocationToReplace.getTarget().getType().getTypeDeclaration();

		if (!(typeOfTarget instanceof CtClass))
			continue;

		CtClass targeClasstOfInvocation = (CtClass) typeOfTarget;

		List allMethods = SupportOperators.getAllMethodsFromClass(targeClasstOfInvocation);

		for (Object omethod : allMethods) {

			if (!(omethod instanceof CtMethod))
				continue;

			CtMethod anotherMethod = (CtMethod) omethod;

			if (anotherMethod.getSignature().equals(affectedMethod.getSignature()))
				// It's the same, we discard it.
				continue;

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

			// Only if the target is the class we can call to non public methods
			if (!targeClasstOfInvocation.equals(classUnderAnalysis) && !anotherMethod.isPublic())
				continue;

			if (anotherMethod.getSimpleName().equals(affectedMethod.getSimpleName())) {
				// It's override
				// TODO:
				// similarInvocationResult.add(affectedMethod, anotherMethod);

			}

			if (anotherMethod.getType() != null && minvokedInAffected.getType() != null) {

				boolean compatibleReturnTypes = SupportOperators.checkIsSubtype(anotherMethod.getType(),
						minvokedInAffected.getType());
				if (compatibleReturnTypes) {

					// CASE 2: Different method name
					if (anotherMethod.getParameters().size() == affectedMethod.getParameters().size()
							&& anotherMethod.getParameters().equals(affectedMethod.getParameters())) {

						List<CtInvocation> newInvToMethods = SupportOperators
								.createRealInvocationsReusingVars(point, anotherMethod, invocationToReplace);

						for (CtInvocation aNewInvocation : newInvToMethods) {
							CtInvocation newInvocationCloned = aNewInvocation.clone();
							newInvocationCloned.setExecutable(anotherMethod.getReference());
							Ingredient newIngredient = new Ingredient(newInvocationCloned);
							newIngredient.setDerivedFrom(invocationToReplace);
							newIngredient.getMetadata().put("original", invocationToReplace);
							newIngredient.getMetadata().put("replacement", aNewInvocation);

							similarInvocationResult.add(invocationToReplace, newIngredient);

						}
					}
				}

			}

		}

	}
	return similarInvocationResult;

}