Search in sources :

Example 1 with CtConstructor

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

the class CommentTest method testBlockComment.

@Test
public void testBlockComment() {
    Factory f = getSpoonFactory();
    CtClass<?> type = (CtClass<?>) f.Type().get(BlockComment.class);
    String strType = type.toString();
    List<CtComment> comments = type.getElements(new TypeFilter<CtComment>(CtComment.class));
    // verify that the number of comment present in the AST is correct
    assertEquals(51, comments.size());
    // verify that all comments present in the AST is printed
    for (CtComment comment : comments) {
        if (comment.getCommentType() == CtComment.CommentType.FILE) {
            // the header of the file is not printed with the toString
            continue;
        }
        assertNotNull(comment.getParent());
        assertTrue(comment.toString() + ":" + comment.getParent() + " is not printed", strType.contains(comment.toString()));
    }
    assertEquals(4, type.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment class"), type.getComments().get(1));
    CtField<?> field = type.getField("field");
    assertEquals(2, field.getComments().size());
    assertEquals(createFakeBlockComment(f, "Comment Field"), field.getComments().get(0));
    assertEquals("/* Comment Field */" + newLine + "/* comment in field */" + newLine + "private int field = 10;", field.toString());
    CtAnonymousExecutable ctAnonymousExecutable = type.getAnonymousExecutables().get(0);
    assertEquals(1, ctAnonymousExecutable.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment static block"), ctAnonymousExecutable.getComments().get(0));
    assertEquals(createFakeBlockComment(f, "comment inside static"), ctAnonymousExecutable.getBody().getStatement(0));
    assertEquals("/* comment static block */" + newLine + "static {" + newLine + "    /* comment inside static */" + newLine + "}", ctAnonymousExecutable.toString());
    CtConstructor constructor = type.getConstructor();
    assertEquals(1, constructor.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment constructor"), constructor.getComments().get(0));
    // index 0 is the implicit super call
    assertEquals(createFakeBlockComment(f, "Comment in constructor"), constructor.getBody().getStatement(1));
    assertEquals("/* comment constructor */" + newLine + "public BlockComment() {" + newLine + "    /* Comment in constructor */" + newLine + "}", constructor.toString());
    CtMethod<Object> m = type.getMethod("m");
    assertEquals(1, m.getComments().size());
    assertEquals(createFakeBlockComment(f, "comment method"), m.getComments().get(0));
    assertEquals(createFakeBlockComment(f, "comment empty method block"), m.getBody().getStatement(0));
    assertEquals("/* comment method */" + newLine + "public void m() {" + newLine + "    /* comment empty method block */" + newLine + "}", m.toString());
    CtMethod<Object> m1 = type.getMethod("m1");
    CtSwitch ctSwitch = m1.getBody().getStatement(0);
    assertEquals(createFakeBlockComment(f, "comment switch"), ctSwitch.getComments().get(0));
    assertEquals("/* comment switch */" + newLine + "switch (1) {" + newLine + "    /* before first case */" + newLine + "    case 0 :" + newLine + "        /* comment case 0: empty case */" + newLine + "    case 1 :" + newLine + "        /* comment case 1 */" + newLine + "        int i = 0;" + newLine + "    default :" + newLine + "        /* comment default */" + newLine + "}", ctSwitch.toString());
    CtFor ctFor = m1.getBody().getStatement(1);
    assertEquals(createFakeBlockComment(f, "comment for"), ctFor.getComments().get(0));
    assertEquals("/* comment for */" + newLine + "for (int i = 0; i < 10; i++) {" + newLine + "    /* comment for block */" + newLine + "}", ctFor.toString());
    CtIf ctIf = m1.getBody().getStatement(2);
    assertEquals(createFakeBlockComment(f, "comment if"), ctIf.getComments().get(0));
    assertEquals("/* comment if */" + newLine + "if ((1 % 2) == 0) {" + newLine + "    /* comment unary operator */" + newLine + "    (field)++;" + newLine + "}", ctIf.toString());
    CtConstructorCall ctConstructorCall = m1.getBody().getStatement(3);
    assertEquals(createFakeBlockComment(f, "comment constructor call"), ctConstructorCall.getComments().get(0));
    assertEquals("/* comment constructor call */" + newLine + "new spoon.test.comment.testclasses.BlockComment()", ctConstructorCall.toString());
    CtInvocation ctInvocation = m1.getBody().getStatement(4);
    assertEquals(createFakeBlockComment(f, "comment invocation"), ctInvocation.getComments().get(0));
    assertEquals("/* comment invocation */" + newLine + "this.m()", ctInvocation.toString());
    CtLocalVariable ctLocalVariable = m1.getBody().getStatement(5);
    assertEquals(createFakeBlockComment(f, "comment local variable"), ctLocalVariable.getComments().get(0));
    assertEquals("/* comment local variable */" + newLine + "int i = 0", ctLocalVariable.toString());
    CtLocalVariable ctLocalVariable2 = m1.getBody().getStatement(6);
    assertEquals(createFakeBlockComment(f, "comment multi assignments"), ctLocalVariable2.getComments().get(0));
    assertEquals("/* comment multi assignments */" + newLine + "int j = 2", ctLocalVariable2.toString());
    CtDo ctDo = m1.getBody().getStatement(7);
    assertEquals(createFakeBlockComment(f, "comment dowhile"), ctDo.getComments().get(0));
    assertEquals("/* comment dowhile */" + newLine + "do {" + newLine + "    /* comment in do while */" + newLine + "    i++;" + newLine + "    /* comment end do while */" + newLine + "} while (i < 10 )", ctDo.toString());
    CtTry ctTry = m1.getBody().getStatement(8);
    assertEquals(createFakeBlockComment(f, "comment try"), ctTry.getComments().get(0));
    assertEquals("/* comment try */" + newLine + "try {" + newLine + "    /* comment in try */" + newLine + "    i++;" + newLine + "} catch (java.lang.Exception e) {" + newLine + "    /* comment in catch */" + newLine + "}", ctTry.toString());
    CtSynchronized ctSynchronized = m1.getBody().getStatement(9);
    assertEquals(createFakeBlockComment(f, "comment synchronized"), ctSynchronized.getComments().get(0));
    assertEquals("/* comment synchronized */" + newLine + "synchronized(this) {" + newLine + "    /* comment in synchronized */" + newLine + "}", ctSynchronized.toString());
    CtReturn ctReturn = m1.getBody().getStatement(10);
    assertEquals(createFakeBlockComment(f, "comment return"), ctReturn.getComments().get(0));
    assertEquals("/* comment return */" + newLine + "return", ctReturn.toString());
    CtMethod m2 = type.getMethodsByName("m2").get(0);
    assertEquals(6, m2.getComments().size());
    CtParameter ctParameter = (CtParameter) m2.getParameters().get(0);
    assertEquals(4, ctParameter.getComments().size());
    assertEquals("/* comment before type */" + newLine + "/* comment after parameter */" + newLine + "/* comment before throws */" + newLine + "/* comment before exception 1 */" + newLine + "/* comment before exception 2 */" + newLine + "/* comment before block */" + newLine + "public void m2(/* comment before name */" + newLine + "/* comment before parameters */" + newLine + "/* comment before type parameter */" + newLine + "/* comment before name parameter */" + newLine + "int i) throws java.lang.Error, java.lang.Exception {" + newLine + "}", m2.toString());
}
Also used : CtComment(spoon.reflect.code.CtComment) CtSwitch(spoon.reflect.code.CtSwitch) DefaultCoreFactory(spoon.support.DefaultCoreFactory) Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) CtTry(spoon.reflect.code.CtTry) CtSynchronized(spoon.reflect.code.CtSynchronized) CtInvocation(spoon.reflect.code.CtInvocation) CtReturn(spoon.reflect.code.CtReturn) CtDo(spoon.reflect.code.CtDo) CtFor(spoon.reflect.code.CtFor) BlockComment(spoon.test.comment.testclasses.BlockComment) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtIf(spoon.reflect.code.CtIf) CtConstructor(spoon.reflect.declaration.CtConstructor) CtClass(spoon.reflect.declaration.CtClass) CtConstructorCall(spoon.reflect.code.CtConstructorCall) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 2 with CtConstructor

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

the class CtClassTest method getConstructor.

@Test
public void getConstructor() throws Exception {
    final Factory build = build(Foo.class);
    final CtClass<?> foo = (CtClass<?>) build.Type().get(Foo.class);
    assertEquals(3, foo.getConstructors().size());
    CtTypeReference<Object> typeString = build.Code().createCtTypeReference(String.class);
    CtConstructor<?> constructor = foo.getConstructor(typeString);
    assertEquals(typeString, constructor.getParameters().get(0).getType());
    CtArrayTypeReference<Object> typeStringArray = build.Core().createArrayTypeReference();
    typeStringArray.setComponentType(typeString);
    constructor = foo.getConstructor(typeStringArray);
    assertEquals(typeStringArray, constructor.getParameters().get(0).getType());
    CtArrayTypeReference<Object> typeStringArrayArray = build.Core().createArrayTypeReference();
    typeStringArrayArray.setComponentType(typeStringArray);
    constructor = foo.getConstructor(typeStringArrayArray);
    assertEquals(typeStringArrayArray, constructor.getParameters().get(0).getType());
    // contract: one could add a type member that already exists (equals but not same) and modify it afterwards
    // this adds some flexibility for client code
    // see https://github.com/INRIA/spoon/issues/1862
    CtConstructor cons = foo.getConstructors().toArray(new CtConstructor[0])[0].clone();
    foo.addConstructor(cons);
    // as long as we have not changed the signature, getConstructors, which is based on signatures,
    // thinks there is one single constructor (and that's OK)
    assertEquals(3, foo.getConstructors().size());
    cons.addParameter(cons.getFactory().createParameter().setType(cons.getFactory().Type().OBJECT));
    // now that we have changed the signature we can call getConstructors safely
    assertEquals(4, foo.getConstructors().size());
    // we cloned the first constructor, so it has the same position, and comes before the 2nd and 3rd constructor
    assertSame(cons, foo.getTypeMembers().get(1));
    // the parent is set (the core problem described in the issue has been fixed)
    assertSame(foo, cons.getParent());
    // now we clone and reset the position
    CtConstructor cons2 = foo.getConstructors().toArray(new CtConstructor[0])[0].clone();
    cons2.setPosition(null);
    // adding the constructor, this time, without a position
    foo.addConstructor(cons2);
    // without position, it has been addded at the end
    assertSame(cons2, foo.getTypeMembers().get(4));
}
Also used : CtClass(spoon.reflect.declaration.CtClass) Foo(spoon.test.ctClass.testclasses.Foo) Factory(spoon.reflect.factory.Factory) CtConstructor(spoon.reflect.declaration.CtConstructor) Test(org.junit.Test)

Example 3 with CtConstructor

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

the class TargetedExpressionTest method testTargetOfFieldAccess.

@Test
public void testTargetOfFieldAccess() throws Exception {
    Factory factory = build(Foo.class, Bar.class, SuperClass.class);
    final CtClass<Object> type = factory.Class().get(Foo.class);
    CtConstructor<?> constructor = type.getConstructors().toArray(new CtConstructor<?>[0])[0];
    final List<CtFieldAccess<?>> elements = constructor.getElements(new TypeFilter<CtFieldAccess<?>>(CtFieldAccess.class));
    assertEquals(2, elements.size());
    assertEquals("Target is CtThisAccessImpl if there is a 'this' explicit.", CtThisAccessImpl.class, elements.get(0).getTarget().getClass());
    assertNotNull("Target isn't null if there is a 'this' explicit.", elements.get(1).getTarget());
    assertTrue(elements.get(1).getTarget().isImplicit());
}
Also used : CtFieldAccess(spoon.reflect.code.CtFieldAccess) Factory(spoon.reflect.factory.Factory) CtConstructor(spoon.reflect.declaration.CtConstructor) Test(org.junit.Test)

Example 4 with CtConstructor

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

the class CtTypeImpl method addTypeMemberAt.

@Override
public <C extends CtType<T>> C addTypeMemberAt(int position, CtTypeMember member) {
    if (member == null) {
        return (C) this;
    }
    if (this.typeMembers == CtElementImpl.<CtTypeMember>emptyList()) {
        this.typeMembers = new ArrayList<>();
    }
    if (!this.typeMembers.stream().anyMatch(m -> m == member)) {
        member.setParent(this);
        CtRole role;
        if (member instanceof CtMethod) {
            role = METHOD;
        } else if (member instanceof CtConstructor) {
            role = CONSTRUCTOR;
        } else if (member instanceof CtField) {
            role = FIELD;
        } else if (member instanceof CtAnonymousExecutable) {
            role = ANNONYMOUS_EXECUTABLE;
        } else {
            role = NESTED_TYPE;
        }
        getFactory().getEnvironment().getModelChangeListener().onListAdd(this, role, this.typeMembers, position, member);
        if (position < typeMembers.size()) {
            this.typeMembers.add(position, member);
        } else {
            this.typeMembers.add(member);
        }
    }
    return (C) this;
}
Also used : CtPackageReference(spoon.reflect.reference.CtPackageReference) Arrays(java.util.Arrays) CtRole(spoon.reflect.path.CtRole) CtType(spoon.reflect.declaration.CtType) QualifiedNameBasedSortedSet(spoon.support.util.QualifiedNameBasedSortedSet) SnippetCompilationHelper(spoon.support.compiler.SnippetCompilationHelper) CtExecutable(spoon.reflect.declaration.CtExecutable) Query(spoon.reflect.visitor.Query) ClassTypingContext(spoon.support.visitor.ClassTypingContext) CtField(spoon.reflect.declaration.CtField) CtTypeParameterReference(spoon.reflect.reference.CtTypeParameterReference) SpoonException(spoon.SpoonException) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) Collection(java.util.Collection) Set(java.util.Set) ANNONYMOUS_EXECUTABLE(spoon.reflect.path.CtRole.ANNONYMOUS_EXECUTABLE) CtModifiable(spoon.reflect.declaration.CtModifiable) AllTypeMembersFunction(spoon.reflect.visitor.filter.AllTypeMembersFunction) CtIntersectionTypeReference(spoon.reflect.reference.CtIntersectionTypeReference) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) List(java.util.List) Annotation(java.lang.annotation.Annotation) CtBlock(spoon.reflect.code.CtBlock) UnsettableProperty(spoon.support.UnsettableProperty) CtFormalTypeDeclarer(spoon.reflect.declaration.CtFormalTypeDeclarer) INTERFACE(spoon.reflect.path.CtRole.INTERFACE) CtMethod(spoon.reflect.declaration.CtMethod) SignatureBasedSortedSet(spoon.support.util.SignatureBasedSortedSet) EarlyTerminatingScanner(spoon.reflect.visitor.EarlyTerminatingScanner) TYPE_TYPE_PARAMETERS_CONTAINER_DEFAULT_CAPACITY(spoon.reflect.ModelElementContainerDefaultCapacities.TYPE_TYPE_PARAMETERS_CONTAINER_DEFAULT_CAPACITY) CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtExtendedModifier(spoon.support.reflect.CtExtendedModifier) CtPackage(spoon.reflect.declaration.CtPackage) TYPE_PARAMETER(spoon.reflect.path.CtRole.TYPE_PARAMETER) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Refactoring(spoon.refactoring.Refactoring) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) CtModifierHandler(spoon.support.reflect.CtModifierHandler) CtArrayTypeReference(spoon.reflect.reference.CtArrayTypeReference) FIELD(spoon.reflect.path.CtRole.FIELD) IS_SHADOW(spoon.reflect.path.CtRole.IS_SHADOW) DerivedProperty(spoon.support.DerivedProperty) CtLineElementComparator(spoon.support.comparator.CtLineElementComparator) CtShadowable(spoon.reflect.declaration.CtShadowable) CtConstructor(spoon.reflect.declaration.CtConstructor) CONSTRUCTOR(spoon.reflect.path.CtRole.CONSTRUCTOR) MetamodelPropertyField(spoon.reflect.annotations.MetamodelPropertyField) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtTypeParameter(spoon.reflect.declaration.CtTypeParameter) ReferenceTypeFilter(spoon.reflect.visitor.filter.ReferenceTypeFilter) METHOD(spoon.reflect.path.CtRole.METHOD) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtConsumer(spoon.reflect.visitor.chain.CtConsumer) ModifierKind(spoon.reflect.declaration.ModifierKind) CtFieldReference(spoon.reflect.reference.CtFieldReference) NESTED_TYPE(spoon.reflect.path.CtRole.NESTED_TYPE) Comparator(java.util.Comparator) Collections(java.util.Collections) CtAnnotationType(spoon.reflect.declaration.CtAnnotationType) CtField(spoon.reflect.declaration.CtField) CtRole(spoon.reflect.path.CtRole) CtAnonymousExecutable(spoon.reflect.declaration.CtAnonymousExecutable) CtMethod(spoon.reflect.declaration.CtMethod) CtConstructor(spoon.reflect.declaration.CtConstructor)

Example 5 with CtConstructor

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

the class CtTypeImpl method getNestedType.

@Override
@SuppressWarnings("unchecked")
public <N extends CtType<?>> N getNestedType(final String name) {
    class NestedTypeScanner extends EarlyTerminatingScanner<CtType<?>> {

        private boolean checkType(CtType<?> type) {
            if (type.getSimpleName().equals(name) && CtTypeImpl.this.equals(type.getDeclaringType())) {
                setResult(type);
                terminate();
                return true;
            }
            return false;
        }

        @Override
        public <U> void visitCtClass(spoon.reflect.declaration.CtClass<U> ctClass) {
            if (!checkType(ctClass)) {
                final List<CtTypeMember> typeMembers = new ArrayList<>();
                for (CtTypeMember typeMember : ctClass.getTypeMembers()) {
                    if (typeMember instanceof CtType || typeMember instanceof CtConstructor || typeMember instanceof CtMethod) {
                        typeMembers.add(typeMember);
                    }
                }
                scan(typeMembers);
            }
        }

        @Override
        public <U> void visitCtInterface(spoon.reflect.declaration.CtInterface<U> intrface) {
            if (!checkType(intrface)) {
                final List<CtTypeMember> typeMembers = new ArrayList<>();
                for (CtTypeMember typeMember : intrface.getTypeMembers()) {
                    if (typeMember instanceof CtType || typeMember instanceof CtMethod) {
                        typeMembers.add(typeMember);
                    }
                }
                scan(typeMembers);
            }
        }

        @Override
        public <U extends java.lang.Enum<?>> void visitCtEnum(spoon.reflect.declaration.CtEnum<U> ctEnum) {
            if (!checkType(ctEnum)) {
                final List<CtTypeMember> typeMembers = new ArrayList<>();
                for (CtTypeMember typeMember : ctEnum.getTypeMembers()) {
                    if (typeMember instanceof CtType || typeMember instanceof CtConstructor || typeMember instanceof CtMethod) {
                        typeMembers.add(typeMember);
                    }
                }
                scan(typeMembers);
            }
        }

        @Override
        public <A extends Annotation> void visitCtAnnotationType(CtAnnotationType<A> annotationType) {
            if (!checkType(annotationType)) {
                scan(annotationType.getNestedTypes());
            }
        }
    }
    NestedTypeScanner scanner = new NestedTypeScanner();
    scanner.scan(this);
    return (N) scanner.getResult();
}
Also used : ArrayList(java.util.ArrayList) EarlyTerminatingScanner(spoon.reflect.visitor.EarlyTerminatingScanner) Annotation(java.lang.annotation.Annotation) CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtConstructor(spoon.reflect.declaration.CtConstructor) CtType(spoon.reflect.declaration.CtType) CtTypeMember(spoon.reflect.declaration.CtTypeMember) CtAnnotationType(spoon.reflect.declaration.CtAnnotationType) CtMethod(spoon.reflect.declaration.CtMethod)

Aggregations

CtConstructor (spoon.reflect.declaration.CtConstructor)21 CtMethod (spoon.reflect.declaration.CtMethod)10 CtClass (spoon.reflect.declaration.CtClass)9 Test (org.junit.Test)7 Factory (spoon.reflect.factory.Factory)6 CtAnonymousExecutable (spoon.reflect.declaration.CtAnonymousExecutable)5 CtParameter (spoon.reflect.declaration.CtParameter)5 CtTypeMember (spoon.reflect.declaration.CtTypeMember)5 ArrayList (java.util.ArrayList)4 CtType (spoon.reflect.declaration.CtType)4 Annotation (java.lang.annotation.Annotation)3 CtBlock (spoon.reflect.code.CtBlock)3 CtConstructorCall (spoon.reflect.code.CtConstructorCall)3 CtIf (spoon.reflect.code.CtIf)3 CtSwitch (spoon.reflect.code.CtSwitch)3 CtAnnotation (spoon.reflect.declaration.CtAnnotation)3 CtElement (spoon.reflect.declaration.CtElement)3 CtExecutable (spoon.reflect.declaration.CtExecutable)3 CtField (spoon.reflect.declaration.CtField)3 Executable (java.lang.reflect.Executable)2