Search in sources :

Example 36 with CtTypeReference

use of spoon.reflect.reference.CtTypeReference in project spoon by INRIA.

the class CtAnnotationImpl method convertValueToExpression.

private CtExpression convertValueToExpression(Object value) {
    CtExpression res;
    if (value.getClass().isArray()) {
        // Value should be converted to a CtNewArray.
        res = getFactory().Core().createNewArray();
        Object[] values = (Object[]) value;
        res.setType(getFactory().Type().createArrayReference(getFactory().Type().createReference(value.getClass().getComponentType())));
        for (Object o : values) {
            ((CtNewArray) res).addElement(convertValueToExpression(o));
        }
    } else if (value instanceof Collection) {
        // Value should be converted to a CtNewArray.
        res = getFactory().Core().createNewArray();
        Collection values = (Collection) value;
        res.setType(getFactory().Type().createArrayReference(getFactory().Type().createReference(values.toArray()[0].getClass())));
        for (Object o : values) {
            ((CtNewArray) res).addElement(convertValueToExpression(o));
        }
    } else if (value instanceof Class) {
        // Value should be a field access to a .class.
        res = getFactory().Code().createClassAccess(getFactory().Type().createReference((Class) value));
    } else if (value instanceof Field) {
        // Value should be a field access to a field.
        CtFieldReference<Object> variable = getFactory().Field().createReference((Field) value);
        variable.setStatic(true);
        CtTypeAccess target = getFactory().Code().createTypeAccess(getFactory().Type().createReference(((Field) value).getDeclaringClass()));
        CtFieldRead fieldRead = getFactory().Core().createFieldRead();
        fieldRead.setVariable(variable);
        fieldRead.setTarget(target);
        fieldRead.setType(target.getAccessedType());
        res = fieldRead;
    } else if (isPrimitive(value.getClass()) || value instanceof String) {
        // Value should be a literal.
        res = getFactory().Code().createLiteral(value);
    } else if (value.getClass().isEnum()) {
        final CtTypeReference declaringClass = getFactory().Type().createReference(((Enum) value).getDeclaringClass());
        final CtFieldReference variableRef = getFactory().Field().createReference(declaringClass, declaringClass, ((Enum) value).name());
        CtTypeAccess target = getFactory().Code().createTypeAccess(declaringClass);
        CtFieldRead fieldRead = getFactory().Core().createFieldRead();
        fieldRead.setVariable(variableRef);
        fieldRead.setTarget(target);
        fieldRead.setType(declaringClass);
        res = fieldRead;
    } else {
        throw new SpoonException("Please, submit a valid value.");
    }
    return res;
}
Also used : CtFieldRead(spoon.reflect.code.CtFieldRead) CtExpression(spoon.reflect.code.CtExpression) SpoonException(spoon.SpoonException) CtFieldReference(spoon.reflect.reference.CtFieldReference) CtNewArray(spoon.reflect.code.CtNewArray) CtField(spoon.reflect.declaration.CtField) MetamodelPropertyField(spoon.reflect.annotations.MetamodelPropertyField) Field(java.lang.reflect.Field) CtTypeReference(spoon.reflect.reference.CtTypeReference) Collection(java.util.Collection) CtTypeAccess(spoon.reflect.code.CtTypeAccess)

Example 37 with CtTypeReference

use of spoon.reflect.reference.CtTypeReference in project spoon by INRIA.

the class ClassTypingContext method resolveTypeParameters.

/**
 * resolve typeRefs declared in scope of declarer using actual type arguments registered in typeScopeToActualTypeArguments
 * @param typeRefs to be resolved type references
 * @return resolved type references - one for each `typeRefs`
 * @throws SpoonException if they cannot be resolved. It should not normally happen. If it happens then spoon AST model is probably not consistent.
 */
private List<CtTypeReference<?>> resolveTypeParameters(List<CtTypeReference<?>> typeRefs) {
    List<CtTypeReference<?>> result = new ArrayList<>(typeRefs.size());
    for (CtTypeReference<?> typeRef : typeRefs) {
        if (typeRef instanceof CtTypeParameterReference) {
            CtTypeParameterReference typeParamRef = (CtTypeParameterReference) typeRef;
            CtTypeParameter typeParam = typeParamRef.getDeclaration();
            CtFormalTypeDeclarer declarer = typeParam.getTypeParameterDeclarer();
            typeRef = resolveTypeParameter(declarer, typeParamRef, typeParam, typeRef);
        }
        result.add(typeRef);
    }
    return result;
}
Also used : CtTypeParameterReference(spoon.reflect.reference.CtTypeParameterReference) CtTypeParameter(spoon.reflect.declaration.CtTypeParameter) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtFormalTypeDeclarer(spoon.reflect.declaration.CtFormalTypeDeclarer) ArrayList(java.util.ArrayList)

Example 38 with CtTypeReference

use of spoon.reflect.reference.CtTypeReference in project spoon by INRIA.

the class ClassTypingContext method adaptTypeParameter.

/**
 * adapts `typeParam` to the {@link CtTypeReference}
 * of scope of this {@link ClassTypingContext}
 * In can be {@link CtTypeParameterReference} again - depending actual type arguments of this {@link ClassTypingContext}.
 *
 * @param typeParam to be resolved {@link CtTypeParameter}
 * @return {@link CtTypeReference} or {@link CtTypeParameterReference} adapted to scope of this {@link ClassTypingContext}
 *  or null if `typeParam` cannot be adapted to target `scope`
 */
@Override
protected CtTypeReference<?> adaptTypeParameter(CtTypeParameter typeParam) {
    if (typeParam == null) {
        throw new SpoonException("You cannot adapt a null type parameter.");
    }
    CtFormalTypeDeclarer declarer = typeParam.getTypeParameterDeclarer();
    if ((declarer instanceof CtType<?>) == false) {
        return null;
    }
    // get the actual type argument values for the declarer of `typeParam`
    List<CtTypeReference<?>> actualTypeArguments = resolveActualTypeArgumentsOf(((CtType<?>) declarer).getReference());
    if (actualTypeArguments == null) {
        if (enclosingClassTypingContext != null) {
            // try to adapt parameter using enclosing class typing context
            return enclosingClassTypingContext.adaptType(typeParam);
        }
        return null;
    }
    return getValue(actualTypeArguments, typeParam, declarer);
}
Also used : CtType(spoon.reflect.declaration.CtType) SpoonException(spoon.SpoonException) CtFormalTypeDeclarer(spoon.reflect.declaration.CtFormalTypeDeclarer) CtTypeReference(spoon.reflect.reference.CtTypeReference)

Example 39 with CtTypeReference

use of spoon.reflect.reference.CtTypeReference in project spoon by INRIA.

the class AnnotationTest method testGetAnnotationFromParameter.

@Test
public void testGetAnnotationFromParameter() {
    // contract: Java 8 receiver parameters are handled
    Launcher spoon = new Launcher();
    spoon.addInputResource("src/test/resources/noclasspath/Initializer.java");
    String output = "target/spooned-" + this.getClass().getSimpleName() + "-firstspoon/";
    spoon.setSourceOutputDirectory(output);
    spoon.getEnvironment().setNoClasspath(true);
    Factory factory = spoon.getFactory();
    spoon.buildModel();
    List<CtMethod> methods = factory.getModel().getElements(new NamedElementFilter<>(CtMethod.class, "setField"));
    assertThat(methods.size(), is(1));
    CtMethod methodSet = methods.get(0);
    assertThat(methodSet.getSimpleName(), is("setField"));
    List<CtParameter> parameters = methodSet.getParameters();
    assertThat(parameters.size(), is(1));
    CtParameter thisParameter = parameters.get(0);
    assertThat(thisParameter.getSimpleName(), is("this"));
    CtTypeReference thisParamType = thisParameter.getType();
    assertThat(thisParamType.getSimpleName(), is("Initializer"));
    List<CtAnnotation<?>> annotations = thisParameter.getType().getAnnotations();
    assertThat(annotations.size(), is(2));
    CtAnnotation unknownInit = annotations.get(0);
    CtAnnotation raw = annotations.get(1);
    assertThat(unknownInit.getAnnotationType().getSimpleName(), is("UnknownInitialization"));
    assertThat(raw.getAnnotationType().getSimpleName(), is("Raw"));
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtTypeReference(spoon.reflect.reference.CtTypeReference) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) CtParameter(spoon.reflect.declaration.CtParameter) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Example 40 with CtTypeReference

use of spoon.reflect.reference.CtTypeReference in project spoon by INRIA.

the class AnnotationTest method testUsageOfTypeAnnotationInExtendsImplementsOfAClass.

@Test
public void testUsageOfTypeAnnotationInExtendsImplementsOfAClass() throws Exception {
    final Launcher launcher = new Launcher();
    launcher.addInputResource("./src/test/java/spoon/test/annotation/testclasses/AnnotationsAppliedOnAnyTypeInAClass.java");
    launcher.buildModel();
    Factory factory = launcher.getFactory();
    final CtClass<?> ctClass = (CtClass<?>) factory.Type().get("spoon.test.annotation.testclasses.AnnotationsAppliedOnAnyTypeInAClass");
    final CtClass<?> innerClass = ctClass.getElements(new NamedElementFilter<>(CtClass.class, "DummyClass")).get(0);
    final CtTypeReference<?> extendsActual = innerClass.getSuperclass();
    final List<CtAnnotation<? extends Annotation>> extendsTypeAnnotations = extendsActual.getAnnotations();
    final String superClassExpected = "spoon.test.annotation.testclasses.@spoon.test.annotation.testclasses.TypeAnnotation" + System.lineSeparator() + "AnnotArrayInnerClass";
    assertEquals("Extends with a type annotation must have it in its model", 1, extendsTypeAnnotations.size());
    assertEquals("Type annotation on a extends must be typed by TypeAnnotation", TypeAnnotation.class, extendsTypeAnnotations.get(0).getAnnotationType().getActualClass());
    assertEquals(CtAnnotatedElementType.TYPE_USE, extendsTypeAnnotations.get(0).getAnnotatedElementType());
    assertEquals("Extends with an type annotation must be well printed", superClassExpected, extendsActual.toString());
    final Set<CtTypeReference<?>> superInterfaces = innerClass.getSuperInterfaces();
    final CtTypeReference<?> firstSuperInterface = superInterfaces.toArray(new CtTypeReference<?>[0])[0];
    final List<CtAnnotation<? extends Annotation>> implementsTypeAnnotations = firstSuperInterface.getAnnotations();
    final String superInterfaceExpected = "spoon.test.annotation.testclasses.@spoon.test.annotation.testclasses.TypeAnnotation" + System.lineSeparator() + "BasicAnnotation";
    assertEquals("Implements with a type annotation must have it in its model", 1, implementsTypeAnnotations.size());
    assertEquals("Type annotation on a extends must be typed by TypeAnnotation", TypeAnnotation.class, implementsTypeAnnotations.get(0).getAnnotationType().getActualClass());
    assertEquals(CtAnnotatedElementType.TYPE_USE, implementsTypeAnnotations.get(0).getAnnotatedElementType());
    assertEquals("Extends with an type annotation must be well printed", superInterfaceExpected, firstSuperInterface.toString());
    final CtEnum<?> enumActual = ctClass.getElements(new NamedElementFilter<>(CtEnum.class, "DummyEnum")).get(0);
    final Set<CtTypeReference<?>> superInterfacesOfEnum = enumActual.getSuperInterfaces();
    final CtTypeReference<?> firstSuperInterfaceOfEnum = superInterfacesOfEnum.toArray(new CtTypeReference<?>[0])[0];
    final List<CtAnnotation<? extends Annotation>> enumTypeAnnotations = firstSuperInterfaceOfEnum.getAnnotations();
    final String enumExpected = "public enum DummyEnum implements spoon.test.annotation.testclasses.@spoon.test.annotation.testclasses.TypeAnnotation" + System.lineSeparator() + "BasicAnnotation {" + System.lineSeparator() + "    ;" + System.lineSeparator() + "}";
    assertEquals("Implements in a enum with a type annotation must have it in its model", 1, enumTypeAnnotations.size());
    assertEquals("Type annotation on a implements in a enum must be typed by TypeAnnotation", TypeAnnotation.class, enumTypeAnnotations.get(0).getAnnotationType().getActualClass());
    assertEquals(CtAnnotatedElementType.TYPE_USE, enumTypeAnnotations.get(0).getAnnotatedElementType());
    assertEquals("Implements in a enum with an type annotation must be well printed", enumExpected, enumActual.toString());
    final CtInterface<?> interfaceActual = ctClass.getElements(new NamedElementFilter<>(CtInterface.class, "DummyInterface")).get(0);
    final Set<CtTypeReference<?>> superInterfacesOfInterface = interfaceActual.getSuperInterfaces();
    final CtTypeReference<?> firstSuperInterfaceOfInterface = superInterfacesOfInterface.toArray(new CtTypeReference<?>[0])[0];
    final List<CtAnnotation<? extends Annotation>> interfaceTypeAnnotations = firstSuperInterfaceOfInterface.getAnnotations();
    final String interfaceExpected = "public interface DummyInterface extends spoon.test.annotation.testclasses.@spoon.test.annotation.testclasses.TypeAnnotation" + System.lineSeparator() + "BasicAnnotation {}";
    assertEquals("Implements in a interface with a type annotation must have it in its model", 1, interfaceTypeAnnotations.size());
    assertEquals("Type annotation on a implements in a enum must be typed by TypeAnnotation", TypeAnnotation.class, interfaceTypeAnnotations.get(0).getAnnotationType().getActualClass());
    assertEquals(CtAnnotatedElementType.TYPE_USE, interfaceTypeAnnotations.get(0).getAnnotatedElementType());
    assertEquals("Implements in a interface with an type annotation must be well printed", interfaceExpected, interfaceActual.toString());
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation) Factory(spoon.reflect.factory.Factory) TypeAnnotation(spoon.test.annotation.testclasses.TypeAnnotation) GlobalAnnotation(spoon.test.annotation.testclasses.GlobalAnnotation) SuperAnnotation(spoon.test.annotation.testclasses.SuperAnnotation) AnnotationDefaultAnnotation(spoon.test.annotation.testclasses.AnnotationDefaultAnnotation) InnerAnnotation(spoon.test.annotation.testclasses.Foo.InnerAnnotation) Annotation(java.lang.annotation.Annotation) MiddleAnnotation(spoon.test.annotation.testclasses.Foo.MiddleAnnotation) OuterAnnotation(spoon.test.annotation.testclasses.Foo.OuterAnnotation) CtAnnotation(spoon.reflect.declaration.CtAnnotation) CtClass(spoon.reflect.declaration.CtClass) CtTypeReference(spoon.reflect.reference.CtTypeReference) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) Launcher(spoon.Launcher) Test(org.junit.Test)

Aggregations

CtTypeReference (spoon.reflect.reference.CtTypeReference)121 Test (org.junit.Test)56 Launcher (spoon.Launcher)43 Factory (spoon.reflect.factory.Factory)32 CtMethod (spoon.reflect.declaration.CtMethod)26 CtType (spoon.reflect.declaration.CtType)24 ArrayList (java.util.ArrayList)22 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)17 CtClass (spoon.reflect.declaration.CtClass)16 CtField (spoon.reflect.declaration.CtField)16 List (java.util.List)15 CtElement (spoon.reflect.declaration.CtElement)14 CtInvocation (spoon.reflect.code.CtInvocation)13 CtReference (spoon.reflect.reference.CtReference)13 CtParameter (spoon.reflect.declaration.CtParameter)12 CtExpression (spoon.reflect.code.CtExpression)11 CtExecutableReference (spoon.reflect.reference.CtExecutableReference)11 CtTypeParameterReference (spoon.reflect.reference.CtTypeParameterReference)11 CtStatement (spoon.reflect.code.CtStatement)9 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)9