javax.lang.model.type.TypeVariable Java Examples

The following examples show how to use javax.lang.model.type.TypeVariable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypeUtil.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public List<? extends TypeMirror> getUpperBounds(TypeMirror t) {
  if (t == null) {
    return Collections.singletonList(
        javacElements.getTypeElement("java.lang.Object").asType());
  }
  switch (t.getKind()) {
    case INTERSECTION:
      return ((IntersectionType) t).getBounds();
    case TYPEVAR:
      return getUpperBounds(((TypeVariable) t).getUpperBound());
    case WILDCARD:
      return getUpperBounds(((WildcardType) t).getExtendsBound());
    default:
      return Collections.singletonList(t);
  }
}
 
Example #2
Source File: DelegateAssignabilityChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean handleBothTypeVars( TypeMirror argType,
        TypeMirror varTypeArg, Types types )
{
    /*
     * Implementation of spec item :
     * the delegate type parameter and the bean type parameter are both 
     * type variables and the upper bound of the bean type
     * parameter is assignable to the upper bound, 
     * if any, of the delegate type parameter
     */
    TypeMirror upper = ((TypeVariable)argType).getUpperBound();
    TypeMirror upperVar = ((TypeVariable)varTypeArg).getUpperBound();
    
    if ( upperVar == null || upperVar.getKind() == TypeKind.NULL ){
        return true;
    }
    if ( upper == null || upper.getKind() == TypeKind.NULL ){
        return false;
    }
    
    return checkIsAssignable(types, upper, upperVar);
}
 
Example #3
Source File: Names.java    From featured with Apache License 2.0 6 votes vote down vote up
private TypeName getFeatureParameterTypeVariableName(DeclaredType featureType,
                                                     int featureParameterIndex) {
    Element paramElem = getFeatureParameterElement(featureType, featureParameterIndex);
    if (paramElem == null) {
        return null;
    }

    if (paramElem.getKind() == ElementKind.TYPE_PARAMETER) {
        return TypeVariableName.get((TypeVariable) paramElem.asType());

    } else if (paramElem.getKind() == ElementKind.CLASS) {
        return TypeName.get(paramElem.asType());
    }

    return null;
}
 
Example #4
Source File: MoreTypes.java    From auto-parcel with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitTypeVariable(TypeVariable a, EqualVisitorParam p) {
    if (p.type.getKind().equals(TYPEVAR)) {
        TypeVariable b = (TypeVariable) p.type;
        TypeParameterElement aElement = (TypeParameterElement) a.asElement();
        TypeParameterElement bElement = (TypeParameterElement) b.asElement();
        Set<ComparedElements> newVisiting = visitingSetPlus(p.visiting, aElement, bElement);
        if (newVisiting.equals(p.visiting)) {
            // We're already visiting this pair of elements.
            // This can happen with our friend Eclipse when looking at <T extends Comparable<T>>.
            // It incorrectly reports the upper bound of T as T itself.
            return true;
        }
        // We use aElement.getBounds() instead of a.getUpperBound() to avoid having to deal with
        // the different way intersection types (like <T extends Number & Comparable<T>>) are
        // represented before and after Java 8. We do have an issue that this code may consider
        // that <T extends Foo & Bar> is different from <T extends Bar & Foo>, but it's very
        // hard to avoid that, and not likely to be much of a problem in practice.
        return equalLists(aElement.getBounds(), bElement.getBounds(), newVisiting)
                && equal(a.getLowerBound(), b.getLowerBound(), newVisiting)
                && a.asElement().getSimpleName().equals(b.asElement().getSimpleName());
    }
    return false;
}
 
Example #5
Source File: DelegateAssignabilityChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean handleRequiredTypeVar( TypeMirror argType,
        TypeMirror varTypeArg, Types types )
{
    /*
     * Implementation of spec item : the delegate type parameter is a 
     * type variable, the bean type parameter is an actual type, and the 
     * actual type is assignable to the upper bound, if any, of the type variable
     */

    TypeMirror upper = ((TypeVariable)varTypeArg).getUpperBound();
    if (  upper == null || upper.getKind()== TypeKind.NULL ){
        return true;
    }
    return checkIsAssignable(types, argType, upper);
}
 
Example #6
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean verifyTypeVarAccessible(ExecutableElement method, TypeMirror forType, List<Element> usedLocalTypeVariables, Element target) {
    Collection<TypeVariable> typeVars = Utilities.containedTypevarsRecursively(forType);
    
    if (method != null) {
        for (Iterator<TypeVariable> it = typeVars.iterator(); it.hasNext(); ) {
            TypeVariable tvar = it.next();
            Element tvarEl = tvar.asElement();

            if (method.getTypeParameters().contains(tvarEl)) {
                usedLocalTypeVariables.add(tvarEl);
                it.remove();
            }
        }
    }
    
    return allTypeVarsAccessible(typeVars, target);
}
 
Example #7
Source File: TurbineTypeMirrorTest.java    From turbine with Apache License 2.0 6 votes vote down vote up
@Test
public void tyVar() {
  TypeVariable t =
      (TypeVariable)
          Iterables.getOnlyElement(
                  factory
                      .typeElement(new ClassSymbol("java/util/Collections"))
                      .getEnclosedElements()
                      .stream()
                      .filter(e -> e.getSimpleName().contentEquals("sort"))
                      .filter(ExecutableElement.class::isInstance)
                      .map(ExecutableElement.class::cast)
                      .filter(e -> e.getParameters().size() == 1)
                      .findFirst()
                      .get()
                      .getTypeParameters())
              .asType();
  assertThat(t.getKind()).isEqualTo(TypeKind.TYPEVAR);
  assertThat(t.getLowerBound().getKind()).isEqualTo(TypeKind.NONE);
  assertThat(t.getUpperBound().toString()).isEqualTo("java.lang.Comparable<? super T>");
}
 
Example #8
Source File: InternalDomainMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
TypeMirror inferType(
    TypeVariable typeVariable, TypeElement classElement, TypeMirror classMirror) {
  DeclaredType declaredType = ctx.getMoreTypes().toDeclaredType(classMirror);
  if (declaredType == null) {
    return null;
  }
  List<? extends TypeMirror> args = declaredType.getTypeArguments();
  if (args.isEmpty()) {
    return null;
  }
  int argsSize = args.size();
  int index = 0;
  for (TypeParameterElement typeParam : classElement.getTypeParameters()) {
    if (index >= argsSize) {
      break;
    }
    if (ctx.getMoreTypes().isSameTypeWithErasure(typeVariable, typeParam.asType())) {
      return args.get(index);
    }
    index++;
  }
  return null;
}
 
Example #9
Source File: TypeUtils.java    From Mixin with MIT License 6 votes vote down vote up
private static String describeGenericBound(TypeMirror type) {
    if (type instanceof TypeVariable) {
        StringBuilder description = new StringBuilder("<");
        TypeVariable typeVar = (TypeVariable)type;
        description.append(typeVar.toString());
        TypeMirror lowerBound = typeVar.getLowerBound();
        if (lowerBound.getKind() != TypeKind.NULL) {
            description.append(" super ").append(lowerBound);
        }
        TypeMirror upperBound = typeVar.getUpperBound();
        if (upperBound.getKind() != TypeKind.NULL) {
            description.append(" extends ").append(upperBound);
        }
        return description.append(">").toString();
    }
    
    return type.toString();
}
 
Example #10
Source File: TypeVariableName.java    From JReFrameworker with MIT License 6 votes vote down vote up
/** @see #get(java.lang.reflect.TypeVariable, Map) */
static TypeVariableName get(java.lang.reflect.TypeVariable<?> type,
    Map<Type, TypeVariableName> map) {
  TypeVariableName result = map.get(type);
  if (result == null) {
    List<TypeName> bounds = new ArrayList<>();
    List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
    result = new TypeVariableName(type.getName(), visibleBounds);
    map.put(type, result);
    for (Type bound : type.getBounds()) {
      bounds.add(TypeName.get(bound, map));
    }
    bounds.remove(OBJECT);
  }
  return result;
}
 
Example #11
Source File: GeneratedPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static String getErasedType(TypeMirror type) {
    switch (type.getKind()) {
        case DECLARED:
            DeclaredType declared = (DeclaredType) type;
            TypeElement element = (TypeElement) declared.asElement();
            return element.getQualifiedName().toString();
        case TYPEVAR:
            return getErasedType(((TypeVariable) type).getUpperBound());
        case WILDCARD:
            return getErasedType(((WildcardType) type).getExtendsBound());
        case ARRAY:
            return getErasedType(((ArrayType) type).getComponentType()) + "[]";
        default:
            return type.toString();
    }
}
 
Example #12
Source File: PluginGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void appendSimpleTypeName(StringBuilder ret, TypeMirror type) {
    switch (type.getKind()) {
        case DECLARED:
            DeclaredType declared = (DeclaredType) type;
            TypeElement element = (TypeElement) declared.asElement();
            ret.append(element.getSimpleName());
            break;
        case TYPEVAR:
            appendSimpleTypeName(ret, ((TypeVariable) type).getUpperBound());
            break;
        case WILDCARD:
            appendSimpleTypeName(ret, ((WildcardType) type).getExtendsBound());
            break;
        case ARRAY:
            appendSimpleTypeName(ret, ((ArrayType) type).getComponentType());
            ret.append("Array");
            break;
        default:
            ret.append(type);
    }
}
 
Example #13
Source File: TypeVariableName.java    From JReFrameworker with MIT License 6 votes vote down vote up
/**
 * Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
 * infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
 * thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
 * map before looking up the bounds. Then if we encounter this TypeVariable again while
 * constructing the bounds, we can just return it from the map. And, the code that put the entry
 * in {@code variables} will make sure that the bounds are filled in before returning.
 */
static TypeVariableName get(
    TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
  TypeParameterElement element = (TypeParameterElement) mirror.asElement();
  TypeVariableName typeVariableName = typeVariables.get(element);
  if (typeVariableName == null) {
    // Since the bounds field is public, we need to make it an unmodifiableList. But we control
    // the List that that wraps, which means we can change it before returning.
    List<TypeName> bounds = new ArrayList<>();
    List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
    typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
    typeVariables.put(element, typeVariableName);
    for (TypeMirror typeMirror : element.getBounds()) {
      bounds.add(TypeName.get(typeMirror, typeVariables));
    }
    bounds.remove(OBJECT);
  }
  return typeVariableName;
}
 
Example #14
Source File: AutoImport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitTypeVariable(TypeVariable type, Void p) {
    Element e = type.asElement();
    if (e != null) {
        CharSequence name = e.getSimpleName();
        if (!CAPTURED_WILDCARD.contentEquals(name)) {
            builder.append(name);
            return null;
        }
    }
    builder.append("?"); //NOI18N
    TypeMirror bound = type.getLowerBound();
    if (bound != null && bound.getKind() != TypeKind.NULL) {
        builder.append(" super "); //NOI18N
        visit(bound);
    } else {
        bound = type.getUpperBound();
        if (bound != null && bound.getKind() != TypeKind.NULL) {
            builder.append(" extends "); //NOI18N
            if (bound.getKind() == TypeKind.TYPEVAR)
                bound = ((TypeVariable)bound).getLowerBound();
            visit(bound);
        }
    }
    return null;
}
 
Example #15
Source File: JavadocCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * uses FQNs where possible since javadoc does not match imports for
 * parameter types
 */
private CharSequence resolveTypeName(TypeMirror asType, boolean isVarArgs) {
    CharSequence ptype;
    if (asType.getKind() == TypeKind.DECLARED) {
        // snip generics
        Element e = ((DeclaredType) asType).asElement();
        ptype = e.getKind().isClass() || e.getKind().isInterface()
                ? ((TypeElement) e).getQualifiedName()
                : e.getSimpleName();
    } else if (asType.getKind() == TypeKind.TYPEVAR) {
        do {
            // Type Erasure JLS 4.6
            asType = ((TypeVariable) asType).getUpperBound();
        } while (asType.getKind() == TypeKind.TYPEVAR);
        ptype = resolveTypeName(asType, isVarArgs);
    } else if (isVarArgs && asType.getKind() == TypeKind.ARRAY) {
        ptype = resolveTypeName(((ArrayType)asType).getComponentType(), false) + "..."; //NOI18N
    } else {
        ptype = asType.toString();
    }
    
    return ptype;
}
 
Example #16
Source File: Util.java    From revapi with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitTypeVariable(TypeVariable t, StringBuilderAndState<TypeMirror> state) {
    if (state.visitingMethod) {
        TypeMirror upperBound = IgnoreCompletionFailures.in(t::getUpperBound);
        upperBound.accept(this, state);
        return null;
    }

    if (state.visitedObjects.contains(t)) {
        state.bld.append("%");
        return null;
    }

    state.visitedObjects.add(t);

    TypeMirror lowerBound = IgnoreCompletionFailures.in(t::getLowerBound);

    if (lowerBound != null && lowerBound.getKind() != TypeKind.NULL) {
        lowerBound.accept(this, state);
        state.bld.append("-");
    }

    IgnoreCompletionFailures.in(t::getUpperBound).accept(this, state);
    state.bld.append("+");
    return null;
}
 
Example #17
Source File: StandaloneTypeVariableTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testToStringMultipleBounds() throws IOException {
  compile("class Foo<T extends java.lang.CharSequence & java.lang.Runnable> { }");

  TypeVariable typeVariable =
      (TypeVariable) elements.getTypeElement("Foo").getTypeParameters().get(0).asType();

  assertEquals("T", typeVariable.toString());
}
 
Example #18
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder visitTypeVariable(TypeVariable t, Boolean p) {
    Element e = t.asElement();
    if (e != null) {
        String name = e.getSimpleName().toString();
        if (!CAPTURED_WILDCARD.equals(name))
            return DEFAULT_VALUE.append(name);
    }
    DEFAULT_VALUE.append("?"); //NOI18N
    if (!insideCapturedWildcard) {
        insideCapturedWildcard = true;
        TypeMirror bound = t.getLowerBound();
        if (bound != null && bound.getKind() != TypeKind.NULL) {
            DEFAULT_VALUE.append(" super "); //NOI18N
            visit(bound, p);
        } else {
            bound = t.getUpperBound();
            if (bound != null && bound.getKind() != TypeKind.NULL) {
                DEFAULT_VALUE.append(" extends "); //NOI18N
                if (bound.getKind() == TypeKind.TYPEVAR)
                    bound = ((TypeVariable)bound).getLowerBound();
                visit(bound, p);
            }
        }
        insideCapturedWildcard = false;
    }
    return DEFAULT_VALUE;
}
 
Example #19
Source File: StandaloneTypeVariableTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUpperBoundUnbounded() throws IOException {
  compile("class Foo<T> { }");

  TypeMirror objectType = elements.getTypeElement("java.lang.Object").asType();

  TypeVariable tVar =
      (TypeVariable) elements.getTypeElement("Foo").getTypeParameters().get(0).asType();

  assertSameType(objectType, tVar.getUpperBound());
}
 
Example #20
Source File: StandaloneTypeVariableTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetLowerBoundMultipleBounds() throws IOException {
  compile("class Foo<T extends java.lang.Runnable & java.lang.CharSequence> { }");

  TypeVariable tVar =
      (TypeVariable) elements.getTypeElement("Foo").getTypeParameters().get(0).asType();

  assertSameType(types.getNullType(), tVar.getLowerBound());
}
 
Example #21
Source File: FindTypeVarScanner.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public Void visitTypeVariable(TypeVariable t, Void p) {
	Name name = null;
	try {
		name = ((Type) t).tsym.name;
	} catch (NullPointerException e) {}
	if (name != null) typeVariables.add(name.toString());
	subVisit(t.getLowerBound());
	subVisit(t.getUpperBound());
	return null;
}
 
Example #22
Source File: DelegateAssignabilityChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean handleWildCardTypeVar( TypeMirror argType, Types types,
        TypeMirror upperBound, TypeMirror lowerBound )
{
    /*
     * Implementation of spec item :
     * the delegate type parameter is a wildcard, the bean 
     * type parameter is a type variable and the upper bound of the type
     * variable is assignable to the upper bound, 
     * if any, of the wildcard and assignable from the lower bound, 
     * if any, of the wildcard
     */ 
    TypeMirror typeUpper = ((TypeVariable) argType).getUpperBound();

    if (typeUpper == null || typeUpper.getKind() == TypeKind.NULL) {
        return upperBound == null || upperBound.getKind() == TypeKind.NULL;
    }

    if (upperBound == null || upperBound.getKind() == TypeKind.NULL) {
        if (lowerBound == null || lowerBound.getKind() == TypeKind.NULL) {
            return true;
        }
        else {
            return checkIsAssignable(types, lowerBound, typeUpper);
        }
    }
    else {
        if (lowerBound == null || lowerBound.getKind() == TypeKind.NULL) {
            return checkIsAssignable(types, typeUpper, upperBound);
        }
        else{ 
            return checkIsAssignable(types, typeUpper, upperBound)
                        && checkIsAssignable(types, lowerBound, typeUpper);
        }
    }
}
 
Example #23
Source File: ApNavigator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeMirror visitTypeVariable(TypeVariable t, TypeElement typeElement) {
    // we are checking if T (declared as T extends A&B&C) is assignable to sup.
    // so apply bounds recursively.
    for (TypeMirror typeMirror : ((TypeParameterElement) t.asElement()).getBounds()) {
        TypeMirror m = visit(typeMirror, typeElement);
        if (m != null)
            return m;
    }
    return null;
}
 
Example #24
Source File: ControllerGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public TypeMirror visitTypeVariable(TypeVariable t, CompilationInfo p) {
    TypeMirror lb = t.getLowerBound() == null ? null : visit(t.getLowerBound(), p);
    TypeMirror ub = t.getUpperBound() == null ? null : visit(t.getUpperBound(), p);
    if (ub.getKind() == TypeKind.DECLARED) {
        DeclaredType dt = (DeclaredType)ub;
        TypeElement tel = (TypeElement)dt.asElement();
        if (tel.getQualifiedName().contentEquals("java.lang.Object")) { // NOI18N
            ub = null;
        } else if (tel.getSimpleName().length() == 0) {
            ub = null;
        }
    }
    return p.getTypes().getWildcardType(ub, lb);
}
 
Example #25
Source File: TurbineTypeMirror.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeVariable> getTypeVariables() {
  ImmutableList.Builder<TypeVariable> result = ImmutableList.builder();
  for (TyVarSymbol tyVar : type.tyParams()) {
    result.add((TypeVariable) factory.asTypeMirror(TyVar.create(tyVar, ImmutableList.of())));
  }
  return result.build();
}
 
Example #26
Source File: ExecutableTypeImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<? extends TypeVariable> getTypeVariables() {
	ArrayList<TypeVariable> list = new ArrayList<TypeVariable>();
	TypeVariableBinding[] typeVariables = ((MethodBinding) this._binding).typeVariables();
	if (typeVariables.length != 0) {
		for (TypeVariableBinding typeVariableBinding : typeVariables) {
			list.add((TypeVariable) _env.getFactory().newTypeMirror(typeVariableBinding));
		}
	}
	return Collections.unmodifiableList(list);
}
 
Example #27
Source File: TypeSimplifier.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
@Override public Void visitTypeVariable(TypeVariable t, Void p) {
  // Instead of visiting t.getUpperBound(), we explicitly visit the supertypes of t.
  // The reason is that for a variable like <T extends Foo & Bar>, t.getUpperBound() will be
  // the intersection type Foo & Bar, with no really simple way to extract Foo and Bar. But
  // directSupertypes(t) will be exactly [Foo, Bar]. For plain <T>, directSupertypes(t) will
  // be java.lang.Object, and it is harmless for us to record a reference to that since we won't
  // try to import it or use it in the output string for <T>.
  for (TypeMirror upper : typeUtils.directSupertypes(t)) {
    visit(upper, p);
  }
  return visit(t.getLowerBound(), p);
}
 
Example #28
Source File: ApNavigator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypeMirror visitTypeVariable(TypeVariable t, TypeElement typeElement) {
    // we are checking if T (declared as T extends A&B&C) is assignable to sup.
    // so apply bounds recursively.
    for (TypeMirror typeMirror : ((TypeParameterElement) t.asElement()).getBounds()) {
        TypeMirror m = visit(typeMirror, typeElement);
        if (m != null)
            return m;
    }
    return null;
}
 
Example #29
Source File: T6421111.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void test(TypeElement element, boolean fbound) {
    TypeParameterElement tpe = element.getTypeParameters().iterator().next();
    tpe.getBounds().getClass();
    if (fbound) {
        DeclaredType type = (DeclaredType)tpe.getBounds().get(0);
        if (type.asElement() != element)
            throw error("%s != %s", type.asElement(), element);
        TypeVariable tv = (TypeVariable)type.getTypeArguments().get(0);
        if (tv.asElement() != tpe)
            throw error("%s != %s", tv.asElement(), tpe);
    }
}
 
Example #30
Source File: NameUtil.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void buildTypeVariable(TypeVariable type, StringBuilder sb) {
  TypeParameterElement typeParam = (TypeParameterElement) type.asElement();
  if (isCapture(typeParam)) {
    String name = captureNames.get(typeParam);
    if (name == null) {
      name = "!CAP" + captureCount++ + '!';
      captureNames.put(typeParam, name);
    }
    sb.append(name);
  } else {
    sb.append("T:");
    buildElementSignature(typeParam.getEnclosingElement(), sb);
    sb.append(':').append(ElementUtil.getName(typeParam)).append(';');
  }
}