Search in sources :

Example 16 with CtTypeMember

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

the class ImportScannerImpl method visitCtInterface.

@Override
public <T> void visitCtInterface(CtInterface<T> intrface) {
    addClassImport(intrface.getReference());
    for (CtTypeMember t : intrface.getTypeMembers()) {
        if (!(t instanceof CtType)) {
            continue;
        }
        addClassImport(((CtType) t).getReference());
    }
    super.visitCtInterface(intrface);
}
Also used : CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtType(spoon.reflect.declaration.CtType)

Example 17 with CtTypeMember

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

the class MetaModelTest method listValueRoleSetOn.

@Test
public void listValueRoleSetOn() {
    // contract: multi-value role supports set(int, Object)
    Launcher launcher = new Launcher();
    Factory factory = launcher.getFactory();
    CtClass<?> ctClass = factory.Class().create("some.test.TestClass");
    RoleHandler rh = RoleHandlerHelper.getRoleHandler(ctClass.getClass(), CtRole.TYPE_MEMBER);
    List<CtTypeMember> typeMembers = rh.asList(ctClass);
    assertEquals(0, typeMembers.size());
    CtField<?> field1 = createField(factory, "field1");
    CtField<?> field2 = createField(factory, "field2");
    CtField<?> field3 = createField(factory, "field3");
    // check that field was not added in type yet
    assertEquals(0, typeMembers.size());
    // contract: call of add on RoleHandler collection adds the item into real collection too
    typeMembers.add(field1);
    assertEquals(1, typeMembers.size());
    assertEquals(1, ctClass.getTypeMembers().size());
    assertSame(ctClass, field1.getDeclaringType());
    assertThat(asList("field1"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    // contract: call of add on RoleHandler collection adds the item into real collection too
    typeMembers.add(field2);
    assertSame(ctClass, field2.getDeclaringType());
    assertThat(asList("field1", "field2"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    // contract: call of set on RoleHandler collection replaces the item in real collection
    typeMembers.set(0, field3);
    assertSame(ctClass, field3.getDeclaringType());
    assertThat(asList("field3", "field2"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    typeMembers.set(1, field1);
    assertThat(asList("field3", "field1"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    // contract: call of remove(int) on RoleHandler collection removes the item in real collection
    assertSame(field3, typeMembers.remove(0));
    assertThat(asList("field1"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    // contract: call of remove(Object) which does not exist does nothing
    assertFalse(typeMembers.remove(field2));
    assertThat(asList("field1"), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
    // contract: call of remove(Object) on RoleHandler collection removes the item in real collection
    assertTrue(typeMembers.remove(field1));
    assertThat(asList(), is(ctClass.filterChildren(new TypeFilter(CtField.class)).map((CtField e) -> e.getSimpleName()).list()));
}
Also used : CtTypeMember(spoon.reflect.declaration.CtTypeMember) RoleHandler(spoon.reflect.meta.RoleHandler) CtField(spoon.reflect.declaration.CtField) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) Test(org.junit.Test)

Example 18 with CtTypeMember

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

the class JDTCommentBuilder method insertCommentInAST.

/**
 * Inserts the comment into the AST.
 * @param comment the comment to insert
 */
private void insertCommentInAST(final CtComment comment) {
    CtElement commentParent = findCommentParent(comment);
    if (commentParent == null) {
        File file = spoonUnit.getFile();
        if (file != null && file.getName().equals(DefaultJavaPrettyPrinter.JAVA_PACKAGE_DECLARATION)) {
            spoonUnit.getDeclaredPackage().addComment(comment);
        } else if (file != null && file.getName().equals(DefaultJavaPrettyPrinter.JAVA_MODULE_DECLARATION)) {
            spoonUnit.getDeclaredModule().addComment(comment);
        } else {
            comment.setCommentType(CtComment.CommentType.FILE);
            addCommentToNear(comment, new ArrayList<CtElement>(spoonUnit.getDeclaredTypes()));
        }
        return;
    }
    // visitor that inserts the comment in the element
    CtInheritanceScanner insertionVisitor = new CtInheritanceScanner() {

        private boolean isScanned = false;

        @Override
        public void scan(CtElement e) {
            if (e == null) {
                return;
            }
            // Do not visit the AST, only the first element
            if (!isScanned) {
                isScanned = true;
                if (e.getPosition().getSourceStart() == comment.getPosition().getSourceStart()) {
                    e.addComment(comment);
                    return;
                }
                super.scan(e);
            }
        }

        @Override
        public <R> void visitCtStatementList(CtStatementList e) {
            addCommentToNear(comment, new ArrayList<CtElement>(e.getStatements()));
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addStatement(comment);
            }
        }

        @Override
        public <T> void visitCtMethod(CtMethod<T> e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtConstructor(CtConstructor<T> e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtConditional(CtConditional<T> e) {
            List<CtElement> elements = new ArrayList<>();
            elements.add(e.getElseExpression());
            elements.add(e.getThenExpression());
            elements.add(e.getCondition());
            addCommentToNear(comment, elements);
        }

        @Override
        public <T> void visitCtBinaryOperator(CtBinaryOperator<T> e) {
            List<CtElement> elements = new ArrayList<>();
            elements.add(e.getLeftHandOperand());
            elements.add(e.getRightHandOperand());
            addCommentToNear(comment, elements);
        }

        @Override
        public <T> void visitCtClass(CtClass<T> e) {
            if (comment.getPosition().getLine() <= e.getPosition().getLine()) {
                e.addComment(comment);
                return;
            }
            final List<CtElement> elements = new ArrayList<>();
            for (CtTypeMember typeMember : e.getTypeMembers()) {
                if (typeMember instanceof CtField || typeMember instanceof CtMethod || typeMember instanceof CtConstructor) {
                    elements.add(typeMember);
                }
            }
            addCommentToNear(comment, elements);
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtInterface(CtInterface<T> e) {
            final List<CtElement> elements = new ArrayList<>();
            for (CtTypeMember typeMember : e.getTypeMembers()) {
                if (typeMember instanceof CtField || typeMember instanceof CtMethod) {
                    elements.add(typeMember);
                }
            }
            addCommentToNear(comment, elements);
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtField(CtField<T> e) {
            e.addComment(comment);
        }

        @Override
        public <E> void visitCtSwitch(CtSwitch<E> e) {
            List<CtCase<? super E>> cases = e.getCases();
            CtCase previous = null;
            for (int i = 0; i < cases.size(); i++) {
                CtCase<? super E> ctCase = cases.get(i);
                if (previous == null) {
                    if (comment.getPosition().getSourceStart() < ctCase.getPosition().getSourceStart() && e.getPosition().getSourceStart() < comment.getPosition().getSourceStart()) {
                        ctCase.addComment(comment);
                        return;
                    }
                } else {
                    if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart() && ctCase.getPosition().getSourceStart() > comment.getPosition().getSourceStart()) {
                        addCommentToNear(comment, new ArrayList<CtElement>(previous.getStatements()));
                        try {
                            comment.getParent();
                        } catch (ParentNotInitializedException ex) {
                            previous.addStatement(comment);
                        }
                        return;
                    }
                }
                previous = ctCase;
            }
            if (previous.getPosition().getSourceEnd() < comment.getPosition().getSourceStart()) {
                addCommentToNear(comment, new ArrayList<CtElement>(previous.getStatements()));
                try {
                    comment.getParent();
                } catch (ParentNotInitializedException ex) {
                    previous.addStatement(comment);
                }
                return;
            }
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public void visitCtIf(CtIf e) {
            if (!(e.getThenStatement() instanceof CtBlock)) {
                if (comment.getPosition().getSourceEnd() <= e.getThenStatement().getPosition().getSourceStart()) {
                    e.getThenStatement().addComment(comment);
                    return;
                }
            }
            if (e.getElseStatement() != null) {
                SourcePosition thenPosition = e.getThenStatement().getPosition() == null ? ((CtBlock) e.getThenStatement()).getStatement(0).getPosition() : e.getThenStatement().getPosition();
                SourcePosition elsePosition = e.getElseStatement().getPosition() == null ? ((CtBlock) e.getElseStatement()).getStatement(0).getPosition() : e.getElseStatement().getPosition();
                if (comment.getPosition().getSourceStart() > thenPosition.getSourceEnd() && comment.getPosition().getSourceEnd() < elsePosition.getSourceStart()) {
                    e.getElseStatement().addComment(comment);
                }
            }
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public void scanCtStatement(CtStatement s) {
            if (!(s instanceof CtStatementList || s instanceof CtSwitch)) {
                s.addComment(comment);
            }
        }

        @Override
        public void visitCtAnonymousExecutable(CtAnonymousExecutable e) {
            e.addComment(comment);
        }

        @Override
        public <T> void visitCtNewArray(CtNewArray<T> e) {
            addCommentToNear(comment, new ArrayList<CtElement>(e.getElements()));
            try {
                comment.getParent();
            } catch (ParentNotInitializedException ex) {
                e.addComment(comment);
            }
        }

        @Override
        public <T> void visitCtParameter(CtParameter<T> e) {
            e.addComment(comment);
        }

        @Override
        public void visitCtCatch(CtCatch e) {
            if (comment.getPosition().getLine() <= e.getPosition().getLine()) {
                e.addComment(comment);
                return;
            }
        }

        @Override
        public void visitCtModule(CtModule module) {
            addCommentToNear(comment, new ArrayList<>(module.getModuleDirectives()));
        }
    };
    insertionVisitor.scan(commentParent);
    try {
        comment.getParent();
    } catch (ParentNotInitializedException e) {
        LOGGER.error(comment + " is not added into the AST", e);
    }
}
Also used : CtConditional(spoon.reflect.code.CtConditional) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtSwitch(spoon.reflect.code.CtSwitch) ArrayList(java.util.ArrayList) CtParameter(spoon.reflect.declaration.CtParameter) CtNewArray(spoon.reflect.code.CtNewArray) CtStatement(spoon.reflect.code.CtStatement) CtField(spoon.reflect.declaration.CtField) SourcePosition(spoon.reflect.cu.SourcePosition) CtInheritanceScanner(spoon.reflect.visitor.CtInheritanceScanner) CtStatementList(spoon.reflect.code.CtStatementList) CtInterface(spoon.reflect.declaration.CtInterface) CtBinaryOperator(spoon.reflect.code.CtBinaryOperator) CtElement(spoon.reflect.declaration.CtElement) CtIf(spoon.reflect.code.CtIf) CtConstructor(spoon.reflect.declaration.CtConstructor) CtModule(spoon.reflect.declaration.CtModule) CtClass(spoon.reflect.declaration.CtClass) CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtBlock(spoon.reflect.code.CtBlock) CtCase(spoon.reflect.code.CtCase) CtCatch(spoon.reflect.code.CtCatch) File(java.io.File) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtMethod(spoon.reflect.declaration.CtMethod)

Example 19 with CtTypeMember

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

the class CtBiScannerGenerator method process.

public void process() {
    final CtLocalVariable<?> peekElement = getFactory().Class().get(GENERATING_BISCANNER_PACKAGE + ".PeekElementTemplate").getMethod("statement").getBody().getStatement(0);
    final CtClass<Object> target = createBiScanner();
    for (CtTypeMember tm : getFactory().Class().get(CtScanner.class).getTypeMembers()) {
        if (!(tm instanceof CtMethod)) {
            continue;
        }
        CtMethod<?> element = (CtMethod) tm;
        if (!element.getSimpleName().startsWith("visitCt")) {
            continue;
        }
        Factory factory = element.getFactory();
        CtMethod<?> clone = factory.Core().clone(element);
        clone.addComment(getFactory().Code().createComment("autogenerated by " + getClass().getSimpleName(), CtComment.CommentType.INLINE));
        // Peek element from Stack.
        final CtLocalVariable<?> peek = factory.Core().clone(peekElement);
        final CtTypeReference type = factory.Core().clone(clone.getParameters().get(0).getType());
        type.getActualTypeArguments().clear();
        peek.getDefaultExpression().addTypeCast(type);
        peek.setType(type);
        clone.getBody().insertBegin(peek);
        for (int i = 2; i < clone.getBody().getStatements().size() - 1; i++) {
            List<CtExpression> invArgs = ((CtInvocation) clone.getBody().getStatement(i)).getArguments();
            if (invArgs.size() <= 1) {
                throw new RuntimeException("You forget the role argument in line " + i + " of method " + element.getSimpleName() + " from " + element.getDeclaringType().getQualifiedName());
            }
            final CtInvocation targetInvocation = (CtInvocation) invArgs.get(1);
            if ("getValue".equals(targetInvocation.getExecutable().getSimpleName()) && "CtLiteral".equals(targetInvocation.getExecutable().getDeclaringType().getSimpleName())) {
                clone.getBody().getStatement(i--).delete();
                continue;
            }
            CtInvocation<?> replace = (CtInvocation<?>) clone.getBody().getStatement(i).clone();
            // Changes to biScan method.
            replace.getExecutable().setSimpleName("biScan");
            // Creates other inv.
            final CtVariableAccess<?> otherRead = factory.Code().createVariableRead(peek.getReference(), false);
            replace.addArgument(factory.Code().createInvocation(otherRead, ((CtInvocation) replace.getArguments().get(1)).getExecutable()));
            if ("Map".equals(targetInvocation.getExecutable().getType().getSimpleName())) {
                ((CtExpression) replace.getArguments().get(1)).replace(factory.Code().createInvocation(targetInvocation, factory.Executable().createReference("List Map#values()")));
                CtInvocation invocation = factory.Code().createInvocation(replace.getArguments().get(2).clone(), factory.Executable().createReference("List Map#values()"));
                replace.getArguments().get(2).replace(invocation);
            }
            clone.getBody().getStatement(i).replace(replace);
        }
        target.addMethod(clone);
    }
}
Also used : CtExpression(spoon.reflect.code.CtExpression) Factory(spoon.reflect.factory.Factory) CtInvocation(spoon.reflect.code.CtInvocation) CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtScanner(spoon.reflect.visitor.CtScanner) CtMethod(spoon.reflect.declaration.CtMethod)

Example 20 with CtTypeMember

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

the class TypeReferenceScanner method visitCtClass.

@Override
public <T> void visitCtClass(CtClass<T> ctClass) {
    addReference(ctClass.getReference());
    for (CtTypeMember typeMember : ctClass.getTypeMembers()) {
        if (typeMember instanceof CtType) {
            addReference(((CtType) typeMember).getReference());
        }
    }
    super.visitCtClass(ctClass);
}
Also used : CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtType(spoon.reflect.declaration.CtType)

Aggregations

CtTypeMember (spoon.reflect.declaration.CtTypeMember)22 CtType (spoon.reflect.declaration.CtType)9 CtField (spoon.reflect.declaration.CtField)6 CtConstructor (spoon.reflect.declaration.CtConstructor)5 CtMethod (spoon.reflect.declaration.CtMethod)5 Factory (spoon.reflect.factory.Factory)5 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)4 Launcher (spoon.Launcher)3 CtBlock (spoon.reflect.code.CtBlock)3 CtElement (spoon.reflect.declaration.CtElement)3 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)3 ClassTypingContext (spoon.support.visitor.ClassTypingContext)3 File (java.io.File)2 Annotation (java.lang.annotation.Annotation)2 Comparator (java.util.Comparator)2 HashSet (java.util.HashSet)2 List (java.util.List)2 CtAnnotation (spoon.reflect.declaration.CtAnnotation)2 CtAnnotationType (spoon.reflect.declaration.CtAnnotationType)2