Search in sources :

Example 36 with TypeParameterElement

use of javax.lang.model.element.TypeParameterElement in project auto by google.

the class TypeSimplifier method formalTypeParametersString.

// The formal type parameters of the given type.
// If we have @AutoValue abstract class Foo<T extends SomeClass> then this method will
// return <T extends Something> for Foo. Likewise it will return the angle-bracket part of:
// Foo<SomeClass>
// Foo<T extends Number>
// Foo<E extends Enum<E>>
// Foo<K, V extends Comparable<? extends K>>
// Type variables need special treatment because we only want to include their bounds when they
// are declared, not when they are referenced. We don't want to include the bounds of the second E
// in <E extends Enum<E>> or of the second K in <K, V extends Comparable<? extends K>>. That's
// why we put the "extends" handling here and not in ToStringTypeVisitor.
String formalTypeParametersString(TypeElement type) {
    List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
    if (typeParameters.isEmpty()) {
        return "";
    } else {
        StringBuilder sb = new StringBuilder("<");
        String sep = "";
        for (TypeParameterElement typeParameter : typeParameters) {
            sb.append(sep);
            sep = ", ";
            appendTypeParameterWithBounds(sb, typeParameter);
        }
        return sb.append(">").toString();
    }
}
Also used : TypeParameterElement(javax.lang.model.element.TypeParameterElement)

Example 37 with TypeParameterElement

use of javax.lang.model.element.TypeParameterElement in project lombok by rzwitserloot.

the class HandleDelegate method checkConflictOfTypeVarNames.

/**
	 * There's a rare but problematic case if a delegate method has its own type variables, and the delegated type does too, and the method uses both.
	 * If for example the delegated type has {@code <E>}, and the method has {@code <T>}, but in our class we have a {@code <T>} at the class level, then we have two different
	 * type variables both named {@code T}. We detect this situation and error out asking the programmer to rename their type variable.
	 * 
	 * @throws CantMakeDelegates If there's a conflict. Conflict list is in ex.conflicted.
	 */
public void checkConflictOfTypeVarNames(MethodSig sig, JavacNode annotation) throws CantMakeDelegates {
    if (sig.elem.getTypeParameters().isEmpty())
        return;
    Set<String> usedInOurType = new HashSet<String>();
    JavacNode enclosingType = annotation;
    while (enclosingType != null) {
        if (enclosingType.getKind() == Kind.TYPE) {
            List<JCTypeParameter> typarams = ((JCClassDecl) enclosingType.get()).typarams;
            if (typarams != null)
                for (JCTypeParameter param : typarams) {
                    if (param.name != null)
                        usedInOurType.add(param.name.toString());
                }
        }
        enclosingType = enclosingType.up();
    }
    Set<String> usedInMethodSig = new HashSet<String>();
    for (TypeParameterElement param : sig.elem.getTypeParameters()) {
        usedInMethodSig.add(param.getSimpleName().toString());
    }
    usedInMethodSig.retainAll(usedInOurType);
    if (usedInMethodSig.isEmpty())
        return;
    // We might be delegating a List<T>, and we are making method <T> toArray(). A conflict is possible.
    // But only if the toArray method also uses type vars from its class, otherwise we're only shadowing,
    // which is okay as we'll add a @SuppressWarnings.
    FindTypeVarScanner scanner = new FindTypeVarScanner();
    sig.elem.asType().accept(scanner, null);
    Set<String> names = new HashSet<String>(scanner.getTypeVariables());
    names.removeAll(usedInMethodSig);
    if (!names.isEmpty()) {
        // We have a confirmed conflict. We could dig deeper as this may still be a false alarm, but its already an exceedingly rare case.
        CantMakeDelegates cmd = new CantMakeDelegates();
        cmd.conflicted = usedInMethodSig;
        throw cmd;
    }
}
Also used : JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) FindTypeVarScanner(lombok.javac.FindTypeVarScanner) JavacNode(lombok.javac.JavacNode) HashSet(java.util.HashSet) TypeParameterElement(javax.lang.model.element.TypeParameterElement)

Example 38 with TypeParameterElement

use of javax.lang.model.element.TypeParameterElement in project robolectric by robolectric.

the class RobolectricModel method registerType.

private void registerType(TypeElement type) {
    if (!Objects.equal(ANYTHING, type) && !importMap.containsKey(type)) {
        typeMap.put(type.getSimpleName().toString(), type);
        importMap.put(type, type);
        for (TypeParameterElement typeParam : type.getTypeParameters()) {
            for (TypeMirror bound : typeParam.getBounds()) {
                // FIXME: get rid of cast using a visitor
                TypeElement boundElement = typeElementVisitor.visit(types.asElement(bound));
                registerType(boundElement);
            }
        }
    }
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) TypeParameterElement(javax.lang.model.element.TypeParameterElement)

Example 39 with TypeParameterElement

use of javax.lang.model.element.TypeParameterElement in project robolectric by robolectric.

the class ShadowProviderGenerator method generate.

void generate(String shadowPackage, PrintWriter writer) {
    writer.print("package " + shadowPackage + ";\n");
    for (String name : model.getImports()) {
        writer.println("import " + name + ';');
    }
    writer.println();
    writer.println("/**");
    writer.println(" * Shadow mapper. Automatically generated by the Robolectric Annotation Processor.");
    writer.println(" */");
    writer.println("@Generated(\"" + RobolectricProcessor.class.getCanonicalName() + "\")");
    writer.println("@SuppressWarnings({\"unchecked\",\"deprecation\"})");
    writer.println("public class " + GEN_CLASS + " implements ShadowProvider {");
    final int shadowSize = model.getAllShadowTypes().size();
    writer.println("  private static final Map<String, String> SHADOW_MAP = new HashMap<>(" + shadowSize + ");");
    writer.println();
    writer.println("  static {");
    for (Map.Entry<TypeElement, TypeElement> entry : model.getAllShadowTypes().entrySet()) {
        final String shadow = elements.getBinaryName(entry.getKey()).toString();
        final String actual = entry.getValue().getQualifiedName().toString();
        writer.println("    SHADOW_MAP.put(\"" + actual + "\", \"" + shadow + "\");");
    }
    for (Map.Entry<String, String> entry : model.getExtraShadowTypes().entrySet()) {
        final String shadow = entry.getKey();
        final String actual = entry.getValue();
        writer.println("    SHADOW_MAP.put(\"" + actual + "\", \"" + shadow + "\");");
    }
    writer.println("  }");
    writer.println();
    for (Map.Entry<TypeElement, TypeElement> entry : model.getShadowOfMap().entrySet()) {
        final TypeElement shadowType = entry.getKey();
        final TypeElement actualType = entry.getValue();
        if (!actualType.getModifiers().contains(Modifier.PUBLIC)) {
            continue;
        }
        int paramCount = 0;
        StringBuilder paramDef = new StringBuilder("<");
        StringBuilder paramUse = new StringBuilder("<");
        for (TypeParameterElement typeParam : entry.getValue().getTypeParameters()) {
            if (paramCount > 0) {
                paramDef.append(',');
                paramUse.append(',');
            }
            boolean first = true;
            paramDef.append(typeParam);
            paramUse.append(typeParam);
            for (TypeMirror bound : model.getExplicitBounds(typeParam)) {
                if (first) {
                    paramDef.append(" extends ");
                    first = false;
                } else {
                    paramDef.append(" & ");
                }
                paramDef.append(model.getReferentFor(bound));
            }
            paramCount++;
        }
        String paramDefStr = "";
        String paramUseStr = "";
        if (paramCount > 0) {
            paramDefStr = paramDef.append("> ").toString();
            paramUseStr = paramUse.append('>').toString();
        }
        final String actual = model.getReferentFor(actualType) + paramUseStr;
        final String shadow = model.getReferentFor(shadowType) + paramUseStr;
        if (shadowType.getAnnotation(Deprecated.class) != null) {
            writer.println("  @Deprecated");
        }
        writer.println("  public static " + paramDefStr + shadow + " shadowOf(" + actual + " actual) {");
        writer.println("    return (" + shadow + ") ShadowExtractor.extract(actual);");
        writer.println("  }");
        writer.println();
    }
    writer.println("  public void reset() {");
    for (Map.Entry<TypeElement, ExecutableElement> entry : model.getResetters().entrySet()) {
        Implements annotation = entry.getKey().getAnnotation(Implements.class);
        int minSdk = annotation.minSdk();
        int maxSdk = annotation.maxSdk();
        String ifClause;
        if (minSdk != -1 && maxSdk != -1) {
            ifClause = "if (org.robolectric.RuntimeEnvironment.getApiLevel() >= " + minSdk + " && org.robolectric.RuntimeEnvironment.getApiLevel() <= " + maxSdk + ") ";
        } else if (maxSdk != -1) {
            ifClause = "if (org.robolectric.RuntimeEnvironment.getApiLevel() <= " + maxSdk + ") ";
        } else if (minSdk != -1) {
            ifClause = "if (org.robolectric.RuntimeEnvironment.getApiLevel() >= " + minSdk + ") ";
        } else {
            ifClause = "";
        }
        writer.println("    " + ifClause + model.getReferentFor(entry.getKey()) + "." + entry.getValue().getSimpleName() + "();");
    }
    writer.println("  }");
    writer.println();
    writer.println("  @Override");
    writer.println("  public Map<String, String> getShadowMap() {");
    writer.println("    return SHADOW_MAP;");
    writer.println("  }");
    writer.println();
    writer.println("  @Override");
    writer.println("  public String[] getProvidedPackageNames() {");
    writer.println("    return new String[] {");
    if (shouldInstrumentPackages) {
        writer.println("      " + Joiner.on(",\n      ").join(model.getShadowedPackages()));
    }
    writer.println("    };");
    writer.println("  }");
    writer.println('}');
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) RobolectricProcessor(org.robolectric.annotation.processing.RobolectricProcessor) TypeParameterElement(javax.lang.model.element.TypeParameterElement) Implements(org.robolectric.annotation.Implements) TypeMirror(javax.lang.model.type.TypeMirror) Map(java.util.Map)

Example 40 with TypeParameterElement

use of javax.lang.model.element.TypeParameterElement in project vertx-docgen by vert-x3.

the class Helper method toString.

/**
 * Compute the string representation of a type mirror.
 *
 * @param mirror the type mirror
 * @param buffer the buffer appended with the string representation
 */
static void toString(TypeMirror mirror, StringBuilder buffer) {
    if (mirror instanceof DeclaredType) {
        DeclaredType dt = (DeclaredType) mirror;
        TypeElement elt = (TypeElement) dt.asElement();
        buffer.append(elt.getQualifiedName().toString());
        List<? extends TypeMirror> args = dt.getTypeArguments();
        if (args.size() > 0) {
            buffer.append("<");
            for (int i = 0; i < args.size(); i++) {
                if (i > 0) {
                    buffer.append(",");
                }
                toString(args.get(i), buffer);
            }
            buffer.append(">");
        }
    } else if (mirror instanceof PrimitiveType) {
        PrimitiveType pm = (PrimitiveType) mirror;
        buffer.append(pm.getKind().name().toLowerCase());
    } else if (mirror instanceof javax.lang.model.type.WildcardType) {
        javax.lang.model.type.WildcardType wt = (javax.lang.model.type.WildcardType) mirror;
        buffer.append("?");
        if (wt.getSuperBound() != null) {
            buffer.append(" super ");
            toString(wt.getSuperBound(), buffer);
        } else if (wt.getExtendsBound() != null) {
            buffer.append(" extends ");
            toString(wt.getExtendsBound(), buffer);
        }
    } else if (mirror instanceof javax.lang.model.type.TypeVariable) {
        javax.lang.model.type.TypeVariable tv = (TypeVariable) mirror;
        TypeParameterElement elt = (TypeParameterElement) tv.asElement();
        buffer.append(elt.getSimpleName().toString());
        if (tv.getUpperBound() != null && !tv.getUpperBound().toString().equals("java.lang.Object")) {
            buffer.append(" extends ");
            toString(tv.getUpperBound(), buffer);
        } else if (tv.getLowerBound() != null && tv.getLowerBound().getKind() != TypeKind.NULL) {
            buffer.append(" super ");
            toString(tv.getUpperBound(), buffer);
        }
    } else if (mirror instanceof javax.lang.model.type.ArrayType) {
        javax.lang.model.type.ArrayType at = (ArrayType) mirror;
        toString(at.getComponentType(), buffer);
        buffer.append("[]");
    } else {
        throw new UnsupportedOperationException("todo " + mirror + " " + mirror.getKind());
    }
}
Also used : ArrayType(javax.lang.model.type.ArrayType) TypeElement(javax.lang.model.element.TypeElement) TypeParameterElement(javax.lang.model.element.TypeParameterElement) ArrayType(javax.lang.model.type.ArrayType) TypeVariable(javax.lang.model.type.TypeVariable) TypeVariable(javax.lang.model.type.TypeVariable) PrimitiveType(javax.lang.model.type.PrimitiveType) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

TypeParameterElement (javax.lang.model.element.TypeParameterElement)40 TypeElement (javax.lang.model.element.TypeElement)20 TypeMirror (javax.lang.model.type.TypeMirror)17 Test (org.junit.Test)17 TypeVariable (javax.lang.model.type.TypeVariable)6 ArrayList (java.util.ArrayList)5 ExecutableElement (javax.lang.model.element.ExecutableElement)5 DeclaredType (javax.lang.model.type.DeclaredType)5 Element (javax.lang.model.element.Element)4 VariableElement (javax.lang.model.element.VariableElement)4 AbstractJClass (com.helger.jcodemodel.AbstractJClass)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 ArrayType (javax.lang.model.type.ArrayType)2 PrimitiveType (javax.lang.model.type.PrimitiveType)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2 JsonMapper (com.bluelinelabs.logansquare.JsonMapper)1 LoganSquare (com.bluelinelabs.logansquare.LoganSquare)1 ParameterizedType (com.bluelinelabs.logansquare.ParameterizedType)1