spoon.reflect.declaration.CtType Java Examples

The following examples show how to use spoon.reflect.declaration.CtType. 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: AstPathTest.java    From coming with MIT License 6 votes vote down vote up
protected void test_Path_of_affected_nodes(File fl, File fr) throws Exception {
	AstComparator comparator = new AstComparator();

	CtType<?> astLeft = comparator.getCtType(fl);

	assertNotNull(astLeft);
	assertNotNull(fl.getPath());

	CtType<?> astRight = comparator.getCtType(fr);
	assertNotNull(astRight);
	assertNotNull(fr.getPath());

	retrievePathOfStmt(astLeft);
	retrievePathOfStmt(astRight);

	Diff diffResult = comparator.compare(astLeft, astRight);
	List<Operation> rootOperations = diffResult.getRootOperations();
	retrievePathOFAffectedElements(rootOperations);
	List<Operation> allOperations = diffResult.getAllOperations();
	retrievePathOFAffectedElements(allOperations);

}
 
Example #2
Source File: APICheckingProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean isToBeProcessed(CtMethod method) {
    // get the CtClass the method is attached to
    CtType parentClass = method.getParent(CtType.class);

    // check that the class belongs to the public API
    if (parentClass.getQualifiedName().contains(PACKAGE_PUBLIC_API)) {
        // check that the method is public
        if (method.isPublic()) {
            // check that the return type belongs to the private API
            CtTypeReference returnType = method.getType();
            return returnType.getQualifiedName().contains(PACKAGE_PRIVATE_API);
        }
    }
    return false;
}
 
Example #3
Source File: TreeTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_JSON_from_GT() throws Exception {

	Launcher spoon = new Launcher();
	Factory factory = spoon.createFactory();
	spoon.createCompiler(factory,
			SpoonResourceHelper.resources("src/test/resources/examples/roots/test8/right_QuickNotepad_1.14.java"))
			.build();

	CtType<?> astLeft = factory.Type().get("QuickNotepad");
	SpoonGumTreeBuilder builder = new SpoonGumTreeBuilder();
	ITree generatedTree = builder.getTree(astLeft);

	TreeContext tcontext = new TreeContext();
	tcontext.setRoot(generatedTree);
	TreeSerializer ts = TreeIoUtils.toJson(tcontext);
	String out = ts.toString();
	assertNotNull(out);
}
 
Example #4
Source File: ReferenceProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
public void process(CtPackage element) {
	CtPackageReference pack = element.getReference();
	Set<CtPackageReference> refs = new HashSet<>();
	for (CtType t : element.getTypes()) {
		List<CtTypeReference<?>> listReferences = Query.getReferences(t, new ReferenceTypeFilter<>(CtTypeReference.class));

		for (CtTypeReference<?> tref : listReferences) {
			if (tref.getPackage() != null && !tref.getPackage().equals(pack)) {
				if (ignoredTypes.contains(tref))
					continue;
				refs.add(tref.getPackage());
			}
		}
	}
	if (!refs.isEmpty()) {
		packRefs.put(pack, refs);
	}
}
 
Example #5
Source File: BoundTest.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testBoundTemplate() throws Exception {
	SpoonAPI launcher = new Launcher();
	launcher.getEnvironment().setNoClasspath(true);
	launcher.addInputResource("./src/main/java");
	launcher.setSourceOutputDirectory("./target/spoon-template");
	launcher.addProcessor(new BoundTemplateProcessor());
	launcher.run();

	final CtType<Main> target = launcher.getFactory().Type().get(Main.class);
	final CtMethod<?> m = target.getMethodsByName("m").get(0);

	assertTrue(m.getBody().getStatements().size() >= 2);
	assertTrue(m.getBody().getStatement(0) instanceof CtIf);
	assertTrue(m.getBody().getStatement(1) instanceof CtIf);
}
 
Example #6
Source File: EvoSuiteFacade.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private List<CtType> obtainBuggyButLatterModif(ProgramVariant variant) {
	List<CtType> types = new ArrayList<>();
	for (CtType affected : variant.getAffectedClasses()) {

		boolean add = false;
		for (CtType modif : variant.getModifiedClasses()) {
			if (modif.getQualifiedName().equals(affected.getQualifiedName())) {
				add = true;
				break;
			}
			if (add) {
				types.add(affected);
			}
		}
	}
	return types;
}
 
Example #7
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 #8
Source File: CloneIngredientSearchStrategy4Exhaustive.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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 #9
Source File: PackageBasicFixSpace.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void defineSpace(ProgramVariant variant) {
	List<CtType<?>> affected = variant.getAffectedClasses();

	List<CtPackage> packageAnalyzed = new ArrayList<>();
	for (CtType<?> ing : affected) {

		CtPackage p = ing.getParent(CtPackage.class);
		if (!packageAnalyzed.contains(p)) {
			packageAnalyzed.add(p);
			for (CtType<?> t : p.getTypes()) {
				this.createFixSpaceFromAClass(t);
			}

		}

	}

}
 
Example #10
Source File: NGramManager.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void init() throws JSAPException {
	this.ngglobal = new NGrams();
	this.ngramsSplitted = new HashMap<>();
	logger.debug("Calculating N-grams");

	TargetElementProcessor<?> elementProcessor = new SpecialStatementFixSpaceProcessor();
	Boolean mustCloneOriginalValue = ConfigurationProperties.getPropertyBool("duplicateingredientsinspace");
	// Forcing to duplicate
	ConfigurationProperties.setProperty("duplicateingredientsinspace", "true");

	List<CtType<?>> all = MutationSupporter.getFactory().Type().getAll();

	GramProcessor pt = new GramProcessor(elementProcessor);
	for (CtType<?> ctType : all) {
		NGrams ng = pt.calculateGrams4Class(ctType);
		ngramsSplitted.put(ctType.getQualifiedName(), ng);

	}
	ngglobal = pt.calculateGlobal(all);

	// reset property clone
	ConfigurationProperties.setProperty("duplicateingredientsinspace", Boolean.toString(mustCloneOriginalValue));

}
 
Example #11
Source File: AstComparator.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
public CtType getCtType(SpoonResource resource) {
	Factory factory = createFactory();
	factory.getModel().setBuildModelIsFinished(false);
	SpoonModelBuilder compiler = new JDTBasedSpoonCompiler(factory);
	compiler.getFactory().getEnvironment().setLevel("OFF");
	compiler.addInputSource(resource);
	compiler.build();

	if (factory.Type().getAll().size() == 0) {
		return null;
	}

	// let's first take the first type.
	CtType type = factory.Type().getAll().get(0);
	// Now, let's ask to the factory the type (which it will set up the
	// corresponding
	// package)
	return factory.Type().get(type.getQualifiedName());
}
 
Example #12
Source File: TreeTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_Path_ScannerWithSpoon_left() throws Exception {

	Launcher spoon = new Launcher();
	Factory factory = spoon.createFactory();
	spoon.createCompiler(factory,
			SpoonResourceHelper.resources("src/test/resources/examples/roots/test8/left_QuickNotepad_1.13.java"))
			.build();

	CtType<?> astLeft = factory.Type().get("QuickNotepad");
	assertNotNull(astLeft.getPath());
	assertNotNull(astLeft);
	PathScanner pscanner = new PathScanner();
	astLeft.accept(pscanner);

}
 
Example #13
Source File: GramProcessor.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Deprecated
public Map<String, NGrams> calculateByPackage(List<CtType<?>> all) throws JSAPException {

	Map<String, NGrams> result = new HashedMap();
	CodeParserLauncher ingp = new CodeParserLauncher<>(ingredientProcessor);
	int allElements = 0;

	for (CtType<?> ctType : all) {
		NGrams ns = new NGrams();
		CtPackage parent = (CtPackage) ctType.getParent(CtPackage.class);
		if (!result.containsKey(parent.getQualifiedName())) {
			allElements += getNGramsFromCodeElements(parent, ns, ingp);
			result.put(parent.getQualifiedName(), ns);
		}
	}
	logger.debug("allElements " + allElements);
	return result;
}
 
Example #14
Source File: CodeFeatureDetectorTest.java    From coming with MIT License 6 votes vote down vote up
protected CtType getCtType(SpoonResource resource) {
	Factory factory = createFactory();
	factory.getModel().setBuildModelIsFinished(false);
	SpoonModelBuilder compiler = new JDTBasedSpoonCompiler(factory);
	compiler.getFactory().getEnvironment().setLevel("OFF");
	compiler.addInputSource(resource);
	compiler.build();

	if (factory.Type().getAll().size() == 0) {
		return null;
	}

	// let's first take the first type.
	CtType type = factory.Type().getAll().get(0);
	// Now, let's ask to the factory the type (which it will set up the
	// corresponding
	// package)
	return factory.Type().get(type.getQualifiedName());
}
 
Example #15
Source File: TreeTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_Path_ScannerWithSpoon_Right() throws Exception {

	Launcher spoon = new Launcher();
	Factory factory = spoon.createFactory();
	spoon.createCompiler(factory,
			SpoonResourceHelper.resources("src/test/resources/examples/roots/test8/right_QuickNotepad_1.14.java"))
			.build();

	CtType<?> astLeft = factory.Type().get("QuickNotepad");
	assertNotNull(astLeft.getPath());
	assertNotNull(astLeft);
	PathScanner pscanner = new PathScanner();
	astLeft.accept(pscanner);

}
 
Example #16
Source File: LocalIngredientSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement original) {

	if (original instanceof CtType<?>)
		return ((CtType) original).getQualifiedName();
	return original.getParent(CtType.class).getQualifiedName();

}
 
Example #17
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
private static CtType getSpoonType(Factory factory, String content) {
	try {
		canBuild(factory, content);
	} catch (Exception e) {
		// must fails
	}
	List<CtType<?>> types = factory.Type().getAll();
	if (types.isEmpty()) {
		throw new RuntimeException("No Type was created by spoon");
	}
	CtType spt = types.get(0);
	spt.getPackage().getTypes().remove(spt);

	return spt;
}
 
Example #18
Source File: GramProcessor.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public NGrams calculateGrams4Class(CtType type) throws JSAPException {

		Boolean mustCloneOriginalValue = ConfigurationProperties.getPropertyBool("duplicateingredientsinspace");
		// Forcing to duplicate
		ConfigurationProperties.setProperty("duplicateingredientsinspace", "true");

		
		NGrams gramsFromClass = new NGrams();

		CodeParserLauncher ingp = new CodeParserLauncher<>(ingredientProcessor);
		int allElements = 0;
		CtType typeToProcess = type;
		while (typeToProcess != null // &&
										// !ngramsStore.containsKey(typeToProcess.getQualifiedName())
		) {
			logger.debug("Extracting Ngram from " + typeToProcess.getQualifiedName());
			allElements += getNGramsFromCodeElements(typeToProcess, gramsFromClass, ingp);
			if (typeToProcess.getSuperclass() != null)
				typeToProcess = typeToProcess.getSuperclass().getDeclaration();
			else
				typeToProcess = null;

		}
		// reset property clone
		ConfigurationProperties.setProperty("duplicateingredientsinspace", Boolean.toString(mustCloneOriginalValue));


		return gramsFromClass;
	}
 
Example #19
Source File: GramProcessor.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Deprecated
public Map<String, NGrams> calculateByType(List<CtType<?>> all) throws JSAPException {

	Map<String, NGrams> result = new HashedMap();
	CodeParserLauncher ingp = new CodeParserLauncher<>(ingredientProcessor);
	int allElements = 0;

	for (CtType<?> ctType : all) {
		NGrams ns = new NGrams();
		allElements += getNGramsFromCodeElements(ctType, ns, ingp);
		result.put(ctType.getQualifiedName(), ns);
	}
	logger.debug("allElements " + allElements);
	return result;
}
 
Example #20
Source File: ProgramVariant.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the classes affected by the variant. Note that those classes are
 * shared between all variant, so, they do not have applied the changes proposed
 * by the variant after the variant is validated.
 * 
 * @return
 */
public List<CtType<?>> getAffectedClasses() {
	List<CtType<?>> r = new ArrayList<CtType<?>>();
	for (CtClass c : loadClasses.values()) {
		r.add(c);
	}
	return Collections.unmodifiableList(r);
}
 
Example #21
Source File: ProgramVariant.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public List<CtType<?>> computeAffectedClassesByOperators() {
	List<CtType<?>> typesToProcess = new ArrayList<>();
	for (List<OperatorInstance> modifofGeneration : this.getOperations().values()) {
		for (OperatorInstance modificationInstance : modifofGeneration) {
			typesToProcess.add(modificationInstance.getModificationPoint().getCtClass());
		}
	}
	return typesToProcess;
}
 
Example #22
Source File: CocoFaultLocalization.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void parseModel() {
	WatcherProcessor processor = new WatcherProcessor();
	ProcessingManager manager = new RuntimeProcessingManager(MutationSupporter.getFactory());
	manager.addProcessor(processor);

	for (CtType<?> modelledClass : MutationSupporter.getFactory().Type().getAll()) {

		try {
			manager.process(modelledClass);
		} catch (ProcessInterruption e) {
			continue;
		}
	}
}
 
Example #23
Source File: ExpressionTypeIngredientSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #24
Source File: AstorCoreEngine.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void initModel() throws Exception {

		if (!MutationSupporter.getFactory().Type().getAll().isEmpty()) {
			if (ConfigurationProperties.getPropertyBool("resetmodel")) {
				Factory fcurrent = MutationSupporter.getFactory();
				log.debug("The Spoon Model was already built.");
				Factory fnew = MutationSupporter.cleanFactory();
				log.debug("New factory created? " + !fnew.equals(fcurrent));
			} else {
				log.debug("we keep previous factory");
				// we do not generate a new model
				return;
			}
		}

		this.mutatorSupporter.buildSpoonModel(this.projectFacade);

		log.info("Number of CtTypes created: " + mutatorSupporter.getFactory().Type().getAll().size());

		///// ONCE ASTOR HAS BUILT THE MODEL,
		///// We apply different processes and manipulation over it.

		// We process the model to add blocks as parent of statement which are
		// not contained in a block
		BlockReificationScanner visitor = new BlockReificationScanner();
		for (CtType c : mutatorSupporter.getFactory().Type().getAll()) {
			c.accept(visitor);
		}

	}
 
Example #25
Source File: IngredientScopeTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the ct type from the collection according tho the class passed as
 * parameter.
 * 
 * @param classes
 * @param target
 * @return
 */
private CtType returnByName(Collection<?> classes, CtClass target) {

	for (Object ctClass : classes) {
		if (((CtType) ctClass).getSimpleName().equals(target.getSimpleName())) {
			return (CtType) ctClass;
		}
	}
	return null;
}
 
Example #26
Source File: LiteralsSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #27
Source File: FinderTestCases.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isValidConstructor(CtType<?> type) {
	if (type instanceof CtClass<?>) {
		CtClass<?> ctClass = ((CtClass<?>) type);
		if (ctClass.getSuperclass() == null || !ctClass.getSuperclass().getSimpleName().equals("TestCase")) {
			return true;
		}
		return ((CtClass<?>) type).getConstructor() != null || ((CtClass<?>) type)
				.getConstructor(type.getFactory().Class().createReference(String.class)) != null;
	}
	return false;
}
 
Example #28
Source File: TreeTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void test_bug_Possition() throws Exception {
	AstComparator comparator = new AstComparator();
	File fl = new File("src/test/resources/examples/roots/test8/left_QuickNotepad_1.13.java");
	File fr = new File("src/test/resources/examples/roots/test8/right_QuickNotepad_1.14.java");

	CtType<?> astLeft = comparator.getCtType(fl);

	assertNotNull(astLeft);

	CtType<?> astRight = comparator.getCtType(fr);
	assertNotNull(astRight);

	Diff diffResult = comparator.compare(astLeft, astRight);
	List<Operation> rootOperations = diffResult.getRootOperations();
	getPaths(rootOperations);
	List<Operation> allOperations = diffResult.getAllOperations();
	getPaths(allOperations);

	assertEquals(1, rootOperations.size());

	SourcePosition position = rootOperations.get(0).getSrcNode().getPosition();
	assertTrue(position.getLine() > 0);
	assertEquals(113, position.getLine());

	assertTrue(!(position instanceof NoSourcePosition));

}
 
Example #29
Source File: VarMappingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected CtMethod getMethodFromClass(AstorCoreEngine core, String classname, String methodName) {
	//
	log.debug("Searching for class " + classname);
	List<CtType<?>> classes = core.getMutatorSupporter().getFactory().Type().getAll();
	CtType cUniv = classes.stream().filter(x -> x.getQualifiedName().equals(classname)).findFirst().get();
	CtMethod mSetup = (CtMethod) cUniv.getAllMethods().stream()
			.filter(x -> ((CtMethod) x).getSimpleName().equals(methodName)).findFirst().get();
	return mSetup;
	//
}
 
Example #30
Source File: CloneIngredientSearchStrategy.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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;
}