Search in sources :

Example 51 with TypeVariable

use of javax.lang.model.type.TypeVariable in project graal by oracle.

the class OrganizedImports method createTypeReference.

public String createTypeReference(Element enclosedElement, TypeMirror type) {
    switch(type.getKind()) {
        case BOOLEAN:
        case BYTE:
        case CHAR:
        case DOUBLE:
        case FLOAT:
        case SHORT:
        case INT:
        case LONG:
        case VOID:
            return ElementUtils.getSimpleName(type);
        case DECLARED:
            return createDeclaredTypeName(enclosedElement, (DeclaredType) type);
        case ARRAY:
            return createTypeReference(enclosedElement, ((ArrayType) type).getComponentType()) + "[]";
        case WILDCARD:
            return createWildcardName(enclosedElement, (WildcardType) type);
        case TYPEVAR:
            TypeVariable var = (TypeVariable) type;
            String name;
            if (isTypeVariableDeclared(enclosedElement, var.asElement().getSimpleName().toString())) {
                // can be resolved with parent element
                name = var.asElement().getSimpleName().toString();
            } else {
                // cannot be resolved
                name = "?";
            }
            return name;
        default:
            throw new RuntimeException("Unknown type specified " + type.getKind() + " mirror: " + type);
    }
}
Also used : ArrayType(javax.lang.model.type.ArrayType) TypeVariable(javax.lang.model.type.TypeVariable)

Example 52 with TypeVariable

use of javax.lang.model.type.TypeVariable in project mapstruct by mapstruct.

the class TypeFactory method getTypeBound.

/**
 * Establishes the type bound:
 * <ol>
 * <li>{@code <? extends Number>}, returns Number</li>
 * <li>{@code <? super Number>}, returns Number</li>
 * <li>{@code <?>}, returns Object</li>
 * <li>{@code <T extends Number>, returns Number}</li>
 * </ol>
 *
 * @param typeMirror the type to return the bound for
 * @return the bound for this parameter
 */
public TypeMirror getTypeBound(TypeMirror typeMirror) {
    if (typeMirror.getKind() == TypeKind.WILDCARD) {
        WildcardType wildCardType = (WildcardType) typeMirror;
        if (wildCardType.getExtendsBound() != null) {
            return wildCardType.getExtendsBound();
        }
        if (wildCardType.getSuperBound() != null) {
            return wildCardType.getSuperBound();
        }
        String wildCardName = wildCardType.toString();
        if ("?".equals(wildCardName)) {
            return elementUtils.getTypeElement(Object.class.getCanonicalName()).asType();
        }
    } else if (typeMirror.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariableType = (TypeVariable) typeMirror;
        if (typeVariableType.getUpperBound() != null) {
            return typeVariableType.getUpperBound();
        }
    // Lowerbounds intentionally left out: Type variables otherwise have a lower bound of NullType.
    }
    return typeMirror;
}
Also used : WildcardType(javax.lang.model.type.WildcardType) TypeVariable(javax.lang.model.type.TypeVariable)

Example 53 with TypeVariable

use of javax.lang.model.type.TypeVariable in project mapstruct by mapstruct.

the class MethodMatcher method matches.

/**
 * Whether the given source and target types are matched by this matcher's candidate method.
 *
 * @param sourceTypes the source types
 * @param resultType the target type
 * @return {@code true} when both, source type and target types match the signature of this matcher's method;
 *         {@code false} otherwise.
 */
boolean matches(List<Type> sourceTypes, Type resultType) {
    // check & collect generic types.
    Map<TypeVariable, TypeMirror> genericTypesMap = new HashMap<TypeVariable, TypeMirror>();
    if (candidateMethod.getParameters().size() == sourceTypes.size()) {
        int i = 0;
        for (Parameter candidateParam : candidateMethod.getParameters()) {
            Type sourceType = sourceTypes.get(i++);
            if (sourceType == null || !matchSourceType(sourceType, candidateParam.getType(), genericTypesMap)) {
                return false;
            }
        }
    } else {
        return false;
    }
    // check if the method matches the proper result type to construct
    Parameter targetTypeParameter = candidateMethod.getTargetTypeParameter();
    if (targetTypeParameter != null) {
        Type returnClassType = typeFactory.classTypeOf(resultType);
        if (!matchSourceType(returnClassType, targetTypeParameter.getType(), genericTypesMap)) {
            return false;
        }
    }
    // check result type
    if (!matchResultType(resultType, genericTypesMap)) {
        return false;
    }
    // check if all type parameters are indeed mapped
    if (candidateMethod.getExecutable().getTypeParameters().size() != genericTypesMap.size()) {
        return false;
    }
    // check if all entries are in the bounds
    for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) {
        if (!isWithinBounds(entry.getValue(), getTypeParamFromCandidate(entry.getKey()))) {
            // checks if the found Type is in bounds of the TypeParameters bounds.
            return false;
        }
    }
    return true;
}
Also used : ArrayType(javax.lang.model.type.ArrayType) Type(org.mapstruct.ap.internal.model.common.Type) DeclaredType(javax.lang.model.type.DeclaredType) PrimitiveType(javax.lang.model.type.PrimitiveType) WildcardType(javax.lang.model.type.WildcardType) TypeVariable(javax.lang.model.type.TypeVariable) TypeMirror(javax.lang.model.type.TypeMirror) HashMap(java.util.HashMap) Parameter(org.mapstruct.ap.internal.model.common.Parameter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 54 with TypeVariable

use of javax.lang.model.type.TypeVariable in project st-js by st-js.

the class ClassWriter method getTypeDescription.

@SuppressWarnings("unused")
private JS getTypeDescription(WriterVisitor<JS> visitor, ClassTree tree, GenerationContext<JS> context) {
    // if (isGlobal(type)) {
    // printer.print(JavascriptKeywords.NULL);
    // return;
    // }
    TypeElement type = TreeUtils.elementFromDeclaration(tree);
    List<NameValue<JS>> props = new ArrayList<NameValue<JS>>();
    for (Element member : ElementUtils.getAllFieldsIn(type)) {
        TypeMirror memberType = ElementUtils.getType(member);
        if (JavaNodes.isJavaScriptPrimitive(memberType)) {
            continue;
        }
        if (member.getKind() == ElementKind.ENUM_CONSTANT) {
            continue;
        }
        if (memberType instanceof TypeVariable) {
            // what to do with fields of generic parameters !?
            continue;
        }
        if (!skipTypeDescForField(member)) {
            props.add(NameValue.of(member.getSimpleName(), getFieldTypeDesc(memberType, context)));
        }
    }
    return context.js().object(props);
}
Also used : NameValue(org.stjs.generator.javascript.NameValue) TypeMirror(javax.lang.model.type.TypeMirror) TypeVariable(javax.lang.model.type.TypeVariable) TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ArrayList(java.util.ArrayList)

Example 55 with TypeVariable

use of javax.lang.model.type.TypeVariable in project AndroidLife by CaMnter.

the class ButterKnifeProcessor method parseBindViews.

/**
 * 解析 BindViews
 *
 * 1.拿到 BindArray 注解元素 的 .java 类元素
 * 2.检查注解使用错误,或者注解所在的环境问题( 比如 private or static,所在的 .java 是 private 等 )
 * - 有错误就 return
 * 3.获取元素的类型
 * 4.校验是否是 Array 或者 List,不是则报错返回
 * 5.校验元素类型( 不是 View 的子类,并且不是接口类型 ),报错返回
 * 6.获取该 .java 元素对应的 BindingSet.Builder,没有则创建
 * 7.注解中抽出一组 Id,校验是否有重复 id
 * 8.包装成  FieldCollectionViewBinding 添加到 BindingSet.Builder
 * 9.记录 .java 元素 为要删除的目录
 *
 * @param element BindBitmap 注解元素
 * @param builderMap BindingSet.Builder 缓存 Map
 * @param erasedTargetNames 要删除元素的目录,存在的是 .java 的元素
 */
private void parseBindViews(Element element, Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    // Start by verifying common generated code restrictions.
    boolean hasError = isInaccessibleViaGeneratedCode(BindViews.class, "fields", element) || isBindingInWrongPackage(BindViews.class, element);
    // Verify that the type is a List or an array.
    TypeMirror elementType = element.asType();
    String erasedType = doubleErasure(elementType);
    TypeMirror viewType = null;
    FieldCollectionViewBinding.Kind kind = null;
    if (elementType.getKind() == TypeKind.ARRAY) {
        ArrayType arrayType = (ArrayType) elementType;
        viewType = arrayType.getComponentType();
        kind = FieldCollectionViewBinding.Kind.ARRAY;
    } else if (LIST_TYPE.equals(erasedType)) {
        DeclaredType declaredType = (DeclaredType) elementType;
        List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
        if (typeArguments.size() != 1) {
            error(element, "@%s List must have a generic component. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
            hasError = true;
        } else {
            viewType = typeArguments.get(0);
        }
        kind = FieldCollectionViewBinding.Kind.LIST;
    } else {
        error(element, "@%s must be a List or array. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
        hasError = true;
    }
    if (viewType != null && viewType.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typeVariable = (TypeVariable) viewType;
        viewType = typeVariable.getUpperBound();
    }
    // Verify that the target type extends from View.
    if (viewType != null && !isSubtypeOfType(viewType, VIEW_TYPE) && !isInterface(viewType)) {
        if (viewType.getKind() == TypeKind.ERROR) {
            note(element, "@%s List or array with unresolved type (%s) " + "must elsewhere be generated as a View or interface. (%s.%s)", BindViews.class.getSimpleName(), viewType, enclosingElement.getQualifiedName(), element.getSimpleName());
        } else {
            error(element, "@%s List or array type must extend from View or be an interface. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
            hasError = true;
        }
    }
    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int[] ids = element.getAnnotation(BindViews.class).value();
    if (ids.length == 0) {
        error(element, "@%s must specify at least one ID. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
        hasError = true;
    }
    Integer duplicateId = findDuplicate(ids);
    if (duplicateId != null) {
        error(element, "@%s annotation contains duplicate ID %d. (%s.%s)", BindViews.class.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName());
        hasError = true;
    }
    if (hasError) {
        return;
    }
    // Always false as hasError would have been true.
    assert viewType != null;
    TypeName type = TypeName.get(viewType);
    boolean required = isFieldRequired(element);
    List<Id> idVars = new ArrayList<>();
    for (int id : ids) {
        QualifiedId qualifiedId = elementToQualifiedId(element, id);
        idVars.add(getId(qualifiedId));
    }
    BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
    builder.addFieldCollection(new FieldCollectionViewBinding(name, type, kind, idVars, required));
    erasedTargetNames.add(enclosingElement);
}
Also used : TypeName(com.squareup.javapoet.TypeName) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) BindString(butterknife.BindString) BindViews(butterknife.BindViews) ArrayType(javax.lang.model.type.ArrayType) TypeMirror(javax.lang.model.type.TypeMirror) TypeVariable(javax.lang.model.type.TypeVariable) List(java.util.List) ArrayList(java.util.ArrayList) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

TypeVariable (javax.lang.model.type.TypeVariable)80 AnnotatedTypeVariable (org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable)38 TypeMirror (javax.lang.model.type.TypeMirror)30 AnnotatedTypeMirror (org.checkerframework.framework.type.AnnotatedTypeMirror)22 TypeElement (javax.lang.model.element.TypeElement)21 ArrayList (java.util.ArrayList)16 DeclaredType (javax.lang.model.type.DeclaredType)15 HashMap (java.util.HashMap)14 LinkedHashMap (java.util.LinkedHashMap)13 Map (java.util.Map)13 ExecutableElement (javax.lang.model.element.ExecutableElement)12 TypeParameterElement (javax.lang.model.element.TypeParameterElement)12 Test (org.junit.Test)10 ArrayType (javax.lang.model.type.ArrayType)9 WildcardType (javax.lang.model.type.WildcardType)9 AnnotationMirror (javax.lang.model.element.AnnotationMirror)8 Element (javax.lang.model.element.Element)8 AnnotationMirrorMap (org.checkerframework.framework.util.AnnotationMirrorMap)8 AnnotationMirrorSet (org.checkerframework.framework.util.AnnotationMirrorSet)8 VariableElement (javax.lang.model.element.VariableElement)7