Java Code Examples for spoon.reflect.declaration.CtType

The following examples show how to use spoon.reflect.declaration.CtType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gumtree-spoon-ast-diff   Source File: AstComparator.java    License: 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 2
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: 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 3
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: 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 4
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
@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 6
Source Project: spoon-examples   Source File: BoundTest.java    License: 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 7
Source Project: coming   Source File: CodeFeatureDetectorTest.java    License: 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 8
Source Project: coming   Source File: AstPathTest.java    License: 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 9
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 10
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 11
Source Project: astor   Source File: EvoSuiteFacade.java    License: 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 12
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: 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 13
Source Project: astor   Source File: PackageBasicFixSpace.java    License: 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 14
Source Project: astor   Source File: NGramManager.java    License: 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 15
Source Project: astor   Source File: GramProcessor.java    License: 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 16
Source Project: nopol   Source File: SpoonedProject.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected CtType<?> modelledClass(String qualifiedName) {
    CtType<?> ctType = typeFactory().get(qualifiedName);
    // the modelled class can only be a top level class otherwise the class will not compile
    if (ctType != null && !ctType.isTopLevel()) {
        ctType = ctType.getTopLevelType();
    }
    return ctType;
}
 
Example 17
Source Project: nopol   Source File: SpoonedProject.java    License: GNU General Public License v2.0 5 votes vote down vote up
public SpoonedClass forked(String qualifiedName) {
    CtType<?> modelledClass = modelledClass(qualifiedName);
    if (modelledClass == null) {
        return null;
    }
    return new SpoonedClass(this, modelledClass, nopolContext);
}
 
Example 18
Source Project: nopol   Source File: SpoonedFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected synchronized void processModelledClasses(Collection<? extends CtType<?>> modelledClasses, Collection<? extends Processor<?>> processors) {
    setProcessors(processors);
    for (CtType<?> modelledClass : modelledClasses) {
        String qualifiedName = modelledClass.getQualifiedName();
        //logDebug(logger(), format("[Spoon processing of %s]", qualifiedName));
        try {
            processingManager().process(modelledClass);
        } catch (ProcessInterruption e) {
            continue;
        }
    }
}
 
Example 19
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_Path_ScannerWithSpoon_both() 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");

	// So, if we create a new factory, it works.
	// Reusing the same factory, the path fails.
	factory = spoon.createFactory();
	spoon.createCompiler(factory,
			SpoonResourceHelper.resources("src/test/resources/examples/roots/test8/left_QuickNotepad_1.13.java"))
			.build();

	CtType<?> astRight = factory.Type().get("QuickNotepad");

	PathScanner pscanner = new PathScanner();

	assertNotNull(astLeft.getPath());
	assertNotNull(astLeft);
	astLeft.accept(pscanner);

	assertNotNull(astRight.getPath());
	assertNotNull(astRight);
	astRight.accept(pscanner);

}
 
Example 20
Source Project: nopol   Source File: SpoonMethodLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static Collection<CtMethod<?>> methodsOf(CtTypeReference<?> type) {
    CtType<?> declaration = type.getDeclaration();
    if (isType(declaration)) {
        return ((CtType<?>) declaration).getAllMethods();
    }
    return asList();
}
 
Example 21
Source Project: nopol   Source File: Main.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * this method analyze all java class in generatedTestDir and return a list of all Junit method
 * @param generatedTestFolder
 * @param classPath
 * @return List<CtMethod> list of methods
 */
public static List<CtMethod<?>> getNewTestsMethods(String generatedTestFolder, String classPath){
    List<CtMethod<?>>  testsMethods = new ArrayList<CtMethod<?>>();

    logger.debug("--------------------------------------------------");
    logger.debug(" ##### Search tests methods ##### ");
    Launcher spoon = new Launcher();
    spoon.getEnvironment().setAutoImports(true);
    spoon.addInputResource(generatedTestFolder);
    spoon.getEnvironment().setSourceClasspath(classPath.split(File.pathSeparator));
    spoon.buildModel();
    //getannotatedMethod.. could be better
    for(CtType<?> clazz : spoon.getFactory().Class().getAll()){
        methodLoop:
            for(CtMethod<?> method : clazz.getAllMethods()){
                for(CtAnnotation<? extends Annotation> annotation : method.getAnnotations()){
                    if (annotation.getType().equals(method.getFactory().Annotation().createReference(org.junit.Test.class))) {
                        logger.debug("[FOUND] "+method.getSignature());
                        testsMethods.add(method);
                        continue methodLoop;
                    }
                }
            }
    }

    return testsMethods;
}
 
Example 22
Source Project: spoon-examples   Source File: Analyzer.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Map<CtMethod, List<CtLocalVariable>> analyze(CtType<?> ctClass) {
	CtTypeReference<Test> reference =
			ctClass.getFactory().Type().createReference(Test.class);
	return ctClass.getMethods().stream()
			.filter(ctMethod -> ctMethod.getAnnotation(reference) != null)
			.collect(Collectors.toMap(
					ctMethod -> ctMethod,
					this::analyze)
			);
}
 
Example 23
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 24
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: Apache License 2.0 5 votes vote down vote up
private void pathOfStmt(CtType<?> ast) {
	for (CtMethod method : ast.getAllMethods()) {

		CtPath path = method.getPath();
		assertNotNull(path);

		for (CtStatement stmt : method.getBody().getStatements()) {
			path = stmt.getPath();
			assertNotNull(path);
		}

	}
}
 
Example 25
Source Project: coming   Source File: AstPathTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test_Path_from_Spoon() throws Exception {
	AstComparator diff = new AstComparator();
	File fl = new File("src/main/resources/diffcases/1139461/WildcardQuery/1139461_WildcardQuery_0_s.java");

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

	assertNotNull(astLeft);
	assertEquals("WildcardQuery", astLeft.getSimpleName());

	CtPath pathLeft = astLeft.getPath();
	assertNotNull(pathLeft);

}
 
Example 26
Source Project: coming   Source File: AstPathTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test_Paths() throws Exception {
	AstComparator diff = new AstComparator();
	File fl = new File("src/main/resources/diffcases/1139461/WildcardQuery/1139461_WildcardQuery_0_s.java");
	File fr = new File("src/main/resources/diffcases/1139461/WildcardQuery/1139461_WildcardQuery_0_t.java");

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

	assertNotNull(astLeft);
	assertEquals("WildcardQuery", astLeft.getSimpleName());

	CtPath pathLeft = astLeft.getPath();
	assertNotNull(pathLeft);

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

	assertNotNull(astRight);
	assertEquals("WildcardQuery", astRight.getSimpleName());
	assertEquals("org.apache.lucene.search.WildcardQuery", astRight.getQualifiedName());

	CtPath pathRight = astRight.getPath();
	assertNotNull(pathRight);

	retrievePathOfStmt(astLeft);
	retrievePathOfStmt(astRight);

}
 
Example 27
Source Project: coming   Source File: AstPathTest.java    License: MIT License 5 votes vote down vote up
private void retrievePathOfStmt(CtType<?> ast) {
	for (CtMethod method : ast.getAllMethods()) {

		CtPath path = method.getPath();
		assertNotNull(path);

		for (CtStatement stmt : method.getBody().getStatements()) {
			path = stmt.getPath();
			assertNotNull(path);
		}

	}
}
 
Example 28
Source Project: astor   Source File: IngredientScopeTest.java    License: 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 29
Source Project: astor   Source File: LiteralsSpace.java    License: 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 30
Source Project: astor   Source File: VarMappingTest.java    License: 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;
	//
}