Search in sources :

Example 81 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class TemplateTest method testTemplateMatcher.

@Test
public void testTemplateMatcher() throws Exception {
    // contract: the given templates should match the expected elements
    Launcher spoon = new Launcher();
    Factory factory = spoon.getFactory();
    spoon.createCompiler(factory, SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/bounds/CheckBound.java"), SpoonResourceHelper.resources("./src/test/java/spoon/test/template/testclasses/bounds/CheckBoundMatcher.java")).build();
    {
        // testing matcher1
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher1")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(2, matcher.find(klass).size());
        assertThat(asList("foo", "fbar"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    {
        // testing matcher2
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher2")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(1, matcher.find(klass).size());
        assertThat(asList("bov"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    {
        // testing matcher3
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher3")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(2, matcher.find(klass).size());
        assertThat(asList("foo", "fbar"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    {
        // testing matcher4
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher4")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(3, matcher.find(klass).size());
        assertThat(asList("foo", "foo2", "fbar"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    {
        // testing matcher5
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher5")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(6, matcher.find(klass).size());
        assertThat(asList("foo", "foo2", "fbar", "baz", "bou", "bov"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    {
        // testing matcher6
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher6")).get(0)).getBody().getStatement(0);
        TemplateMatcher matcher = new TemplateMatcher(templateRoot);
        assertEquals(2, matcher.find(klass).size());
        assertThat(asList("baz", "bou"), is(klass.filterChildren(matcher).map((CtElement e) -> e.getParent(CtMethod.class).getSimpleName()).list()));
    }
    // testing with named elements, at the method level
    {
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtMethod meth = (CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher3")).get(0);
        // exact match
        meth.setSimpleName("foo");
        TemplateMatcher matcher = new TemplateMatcher(meth);
        List<CtMethod> ctElements = matcher.find(klass);
        assertEquals(1, ctElements.size());
        assertEquals("foo", ctElements.get(0).getSimpleName());
    }
    {
        // contract: the name to be matched does not have to be an exact match
        CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
        CtClass<?> klass = factory.Class().get(CheckBound.class);
        CtMethod meth = (CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class, "matcher5")).get(0);
        // together with the appropriate @Parameter _w_, this means
        // we match all methods with name f*, because parameter _w_ acts as a wildcard
        meth.setSimpleName("f_w_");
        TemplateMatcher matcher = new TemplateMatcher(meth);
        List<CtMethod> ctElements = matcher.find(klass);
        assertEquals(3, ctElements.size());
        assertEquals("foo", ctElements.get(0).getSimpleName());
        assertEquals("foo2", ctElements.get(1).getSimpleName());
        assertEquals("fbar", ctElements.get(2).getSimpleName());
    }
}
Also used : CheckBoundMatcher(spoon.test.template.testclasses.bounds.CheckBoundMatcher) CtClass(spoon.reflect.declaration.CtClass) CheckBound(spoon.test.template.testclasses.bounds.CheckBound) CtElement(spoon.reflect.declaration.CtElement) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) TemplateMatcher(spoon.template.TemplateMatcher) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) CtIf(spoon.reflect.code.CtIf) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 82 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class ImportTest method testSuperInheritanceHierarchyFunctionListener.

@Test
public void testSuperInheritanceHierarchyFunctionListener() throws Exception {
    CtType<?> clientClass = (CtClass<?>) ModelUtils.buildClass(ClientClass.class);
    CtTypeReference<?> childClass = clientClass.getSuperclass();
    CtTypeReference<?> superClass = childClass.getSuperclass();
    // contract: the enter and exit are always called with CtTypeReference instance
    List<String> result = clientClass.map(new SuperInheritanceHierarchyFunction().includingSelf(true).setListener(new CtScannerListener() {

        @Override
        public ScanningMode enter(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
            return ScanningMode.NORMAL;
        }

        @Override
        public void exit(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
        }
    })).map(e -> {
        assertTrue(e instanceof CtType);
        return ((CtType) e).getQualifiedName();
    }).list();
    assertTrue(result.contains(clientClass.getQualifiedName()));
    assertTrue(result.contains(childClass.getQualifiedName()));
    assertTrue(result.contains(superClass.getQualifiedName()));
    assertTrue(result.contains(Object.class.getName()));
    // contract: if listener skips ALL, then skipped element and all super classes are not returned
    result = clientClass.map(new SuperInheritanceHierarchyFunction().includingSelf(true).setListener(new CtScannerListener() {

        @Override
        public ScanningMode enter(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
            if (superClass.getQualifiedName().equals(((CtTypeReference<?>) element).getQualifiedName())) {
                return ScanningMode.SKIP_ALL;
            }
            return ScanningMode.NORMAL;
        }

        @Override
        public void exit(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
        }
    })).map(e -> {
        assertTrue(e instanceof CtType);
        return ((CtType) e).getQualifiedName();
    }).list();
    assertTrue(result.contains(clientClass.getQualifiedName()));
    assertTrue(result.contains(childClass.getQualifiedName()));
    assertFalse(result.contains(superClass.getQualifiedName()));
    assertFalse(result.contains(Object.class.getName()));
    // contract: if listener skips CHIDLREN, then skipped element is returned but all super classes are not returned
    result = clientClass.map(new SuperInheritanceHierarchyFunction().includingSelf(true).setListener(new CtScannerListener() {

        @Override
        public ScanningMode enter(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
            if (superClass.getQualifiedName().equals(((CtTypeReference<?>) element).getQualifiedName())) {
                return ScanningMode.SKIP_CHILDREN;
            }
            return ScanningMode.NORMAL;
        }

        @Override
        public void exit(CtElement element) {
            assertTrue(element instanceof CtTypeReference);
        }
    })).map(e -> {
        assertTrue(e instanceof CtType);
        return ((CtType) e).getQualifiedName();
    }).list();
    assertTrue(result.contains(clientClass.getQualifiedName()));
    assertTrue(result.contains(childClass.getQualifiedName()));
    assertTrue(result.contains(superClass.getQualifiedName()));
    assertFalse(result.contains(Object.class.getName()));
}
Also used : Arrays(java.util.Arrays) Launcher(spoon.Launcher) SortedList(spoon.support.util.SortedList) Assert.assertThat(org.junit.Assert.assertThat) CtType(spoon.reflect.declaration.CtType) CtElement(spoon.reflect.declaration.CtElement) Reflection(spoon.test.imports.testclasses.Reflection) CtTypeAccess(spoon.reflect.code.CtTypeAccess) Assert.fail(org.junit.Assert.fail) Query(spoon.reflect.visitor.Query) ClientClass(spoon.test.imports.testclasses.ClientClass) CtThisAccess(spoon.reflect.code.CtThisAccess) CtImport(spoon.reflect.declaration.CtImport) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtField(spoon.reflect.declaration.CtField) CtReference(spoon.reflect.reference.CtReference) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) SpoonResourceHelper(spoon.compiler.SpoonResourceHelper) SpoonException(spoon.SpoonException) Collection(java.util.Collection) ImportScannerImpl(spoon.reflect.visitor.ImportScannerImpl) Set(java.util.Set) ModelUtils(spoon.testing.utils.ModelUtils) Collectors(java.util.stream.Collectors) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) IOUtils(org.apache.commons.io.IOUtils) NotImportExecutableType(spoon.test.imports.testclasses.NotImportExecutableType) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) CtParameter(spoon.reflect.declaration.CtParameter) CtMethod(spoon.reflect.declaration.CtMethod) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CompilationUnit(spoon.reflect.cu.CompilationUnit) CtStatement(spoon.reflect.code.CtStatement) ArrayList(java.util.ArrayList) SpoonModelBuilder(spoon.SpoonModelBuilder) ClassWithInvocation(spoon.test.imports.testclasses.ClassWithInvocation) HashSet(java.util.HashSet) Assert.assertSame(org.junit.Assert.assertSame) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) ChildClass(spoon.test.imports.testclasses.internal.ChildClass) ModelUtils.canBeBuilt(spoon.testing.utils.ModelUtils.canBeBuilt) StringTokenizer(java.util.StringTokenizer) SpoonResource(spoon.compiler.SpoonResource) ScanningMode(spoon.reflect.visitor.chain.ScanningMode) CtLineElementComparator(spoon.support.comparator.CtLineElementComparator) CtScannerListener(spoon.reflect.visitor.chain.CtScannerListener) PrettyPrinter(spoon.reflect.visitor.PrettyPrinter) A(spoon.test.imports.testclasses.A) ImportScanner(spoon.reflect.visitor.ImportScanner) CtInvocation(spoon.reflect.code.CtInvocation) CtImportKind(spoon.reflect.declaration.CtImportKind) Assert.assertNotNull(org.junit.Assert.assertNotNull) SuperInheritanceHierarchyFunction(spoon.reflect.visitor.filter.SuperInheritanceHierarchyFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) Factory(spoon.reflect.factory.Factory) Mole(spoon.test.imports.testclasses.Mole) Tacos(spoon.test.imports.testclasses.Tacos) File(java.io.File) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Pozole(spoon.test.imports.testclasses.Pozole) CtTypeReference(spoon.reflect.reference.CtTypeReference) StaticNoOrdered(spoon.test.imports.testclasses.StaticNoOrdered) Assert.assertNull(org.junit.Assert.assertNull) SubClass(spoon.test.imports.testclasses.SubClass) CtConstructorCall(spoon.reflect.code.CtConstructorCall) CtModel(spoon.reflect.CtModel) CtClass(spoon.reflect.declaration.CtClass) ModifierKind(spoon.reflect.declaration.ModifierKind) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) FileReader(java.io.FileReader) Assert.assertEquals(org.junit.Assert.assertEquals) SuperInheritanceHierarchyFunction(spoon.reflect.visitor.filter.SuperInheritanceHierarchyFunction) CtElement(spoon.reflect.declaration.CtElement) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ClientClass(spoon.test.imports.testclasses.ClientClass) ScanningMode(spoon.reflect.visitor.chain.ScanningMode) CtClass(spoon.reflect.declaration.CtClass) CtType(spoon.reflect.declaration.CtType) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtScannerListener(spoon.reflect.visitor.chain.CtScannerListener) Test(org.junit.Test)

Example 83 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class InsertMethodsTest method insertBeforeAndUpdateParent.

@Test
public void insertBeforeAndUpdateParent() throws Exception {
    /**
     * if (condition)
     *     while (loop_condition)
     *
     * In this case the 'while' is inside an implicit block, but
     * when we insert a new statement
     *
     * if (condition) {
     *     newStatement
     *     while (loop_condition)
     *     ...
     * }
     *
     * Now the while is inside an explicit block.
     */
    Launcher spoon = new Launcher();
    Factory factory = spoon.createFactory();
    spoon.createCompiler(factory, SpoonResourceHelper.resources("./src/test/resources/spoon/test/intercession/insertBefore/InsertBeforeExample2.java")).build();
    // Get the 'while'
    List<CtWhile> elements = Query.getElements(factory, new TypeFilter<CtWhile>(CtWhile.class));
    assertTrue(1 == elements.size());
    CtWhile theWhile = elements.get(0);
    // We make sure the parent of the while is the CtIf and not the block
    CtElement parent = theWhile.getParent();
    assertTrue(parent instanceof CtBlock);
    assertTrue(parent.isImplicit());
    CtIf ifParent = (CtIf) parent.getParent();
    // Create a new statement to be inserted before the while
    CtStatement insert = factory.Code().createCodeSnippetStatement("System.out.println()");
    // Insertion of the new statement
    theWhile.insertBefore(insert);
    // We make sure the parent of the while is updated
    CtElement newParent = theWhile.getParent();
    assertTrue(newParent != ifParent);
    assertTrue(newParent instanceof CtBlock);
    assertFalse(newParent.isImplicit());
}
Also used : CtBlock(spoon.reflect.code.CtBlock) CtStatement(spoon.reflect.code.CtStatement) CtElement(spoon.reflect.declaration.CtElement) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) CtWhile(spoon.reflect.code.CtWhile) CtIf(spoon.reflect.code.CtIf) Test(org.junit.Test)

Example 84 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class ParentContractTest method createCompatibleObject.

public static Object createCompatibleObject(CtTypeReference<?> parameterType) {
    Class<?> c = parameterType.getActualClass();
    for (CtType t : allInstantiableMetamodelInterfaces) {
        if (c.isAssignableFrom(t.getActualClass())) {
            CtElement argument = factory.Core().create(t.getActualClass());
            // we have to give it a name
            if (argument instanceof CtPackage) {
                ((CtPackage) argument).setSimpleName(argument.getShortRepresentation());
            }
            return argument;
        }
    }
    if (Set.class.isAssignableFrom(c)) {
        // we create one set with one element
        HashSet<Object> objects = new HashSet<>();
        objects.add(createCompatibleObject(parameterType.getActualTypeArguments().get(0)));
        return objects;
    }
    if (Collection.class.isAssignableFrom(c)) {
        // we create one list with one element
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(createCompatibleObject(parameterType.getActualTypeArguments().get(0)));
        return objects;
    }
    throw new IllegalArgumentException("cannot instantiate " + parameterType);
}
Also used : CtType(spoon.reflect.declaration.CtType) CtElement(spoon.reflect.declaration.CtElement) ArrayList(java.util.ArrayList) CtPackage(spoon.reflect.declaration.CtPackage) HashSet(java.util.HashSet)

Example 85 with CtElement

use of spoon.reflect.declaration.CtElement in project spoon by INRIA.

the class PathTest method testIncorrectPathFromString.

@Test
public void testIncorrectPathFromString() throws Exception {
    // match the else part of the if in Foo.bar() method which does not exist (Test non existing unique element)
    Collection<CtElement> results = new CtPathStringBuilder().fromString(".spoon.test.path.Foo.bar#body#statement[index=2]#else").evaluateOn(factory.getModel().getRootPackage());
    assertEquals(results.size(), 0);
    // match the third statement of Foo.foo() method which does not exist (Test non existing element of a list)
    results = new CtPathStringBuilder().fromString(".spoon.test.path.Foo.foo#body#statement[index=3]").evaluateOn(factory.getModel().getRootPackage());
    assertEquals(results.size(), 0);
    // match an non existing package (Test non existing element of a set)
    results = new CtPathStringBuilder().fromString("#subPackage[name=nonExistingPackage]").evaluateOn(factory.getModel().getRootPackage());
    assertEquals(results.size(), 0);
    // match a non existing field of an annotation (Test non existing element of a map)
    results = new CtPathStringBuilder().fromString(".spoon.test.path.Foo.bar##annotation[index=0]#value[key=misspelled]").evaluateOn(factory.getModel().getRootPackage());
    assertEquals(results.size(), 0);
}
Also used : CtPathStringBuilder(spoon.reflect.path.CtPathStringBuilder) CtElement(spoon.reflect.declaration.CtElement) Test(org.junit.Test)

Aggregations

CtElement (spoon.reflect.declaration.CtElement)86 Test (org.junit.Test)39 Launcher (spoon.Launcher)23 Factory (spoon.reflect.factory.Factory)18 ArrayList (java.util.ArrayList)17 CtMethod (spoon.reflect.declaration.CtMethod)17 CtType (spoon.reflect.declaration.CtType)15 CtStatement (spoon.reflect.code.CtStatement)14 CtTypeReference (spoon.reflect.reference.CtTypeReference)14 List (java.util.List)12 CtClass (spoon.reflect.declaration.CtClass)12 CtField (spoon.reflect.declaration.CtField)12 CtIf (spoon.reflect.code.CtIf)11 CtInvocation (spoon.reflect.code.CtInvocation)11 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)11 CtLocalVariable (spoon.reflect.code.CtLocalVariable)10 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)9 CtScanner (spoon.reflect.visitor.CtScanner)9 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)9 Collection (java.util.Collection)8