Search in sources :

Example 76 with Types

use of javax.lang.model.util.Types in project checker-framework by typetools.

the class AnnotatedTypes method fixUpRawTypes.

/**
 * Some times we create type arguments for types that were raw. When we do an asSuper we lose
 * these arguments. If in the converted type (i.e. the subtype as super) is missing type arguments
 * AND those type arguments should come from the original subtype's type arguments then we copy
 * the original type arguments to the converted type. e.g. We have a type W, that "wasRaw" {@code
 * ArrayList<? extends Object>} When W is converted to type A, List, using asSuper it no longer
 * has its type argument. But since the type argument to List should be the same as that to
 * ArrayList we copy over the type argument of W to A. A becomes {@code List<? extends Object>}
 *
 * @param originalSubtype the subtype before being converted by asSuper
 * @param asSuperType he subtype after being converted by asSuper
 * @param supertype the supertype for which asSuperType should have the same underlying type
 * @param types the types utility
 */
private static void fixUpRawTypes(final AnnotatedTypeMirror originalSubtype, final AnnotatedTypeMirror asSuperType, final AnnotatedTypeMirror supertype, final Types types) {
    if (asSuperType == null || asSuperType.getKind() != TypeKind.DECLARED || originalSubtype.getKind() != TypeKind.DECLARED) {
        return;
    }
    final AnnotatedDeclaredType declaredAsSuper = (AnnotatedDeclaredType) asSuperType;
    final AnnotatedDeclaredType declaredSubtype = (AnnotatedDeclaredType) originalSubtype;
    if (!declaredAsSuper.isUnderlyingTypeRaw() || !declaredAsSuper.getTypeArguments().isEmpty() || declaredSubtype.getTypeArguments().isEmpty()) {
        return;
    }
    Set<Pair<Integer, Integer>> typeArgMap = TypeArgumentMapper.mapTypeArgumentIndices((TypeElement) declaredSubtype.getUnderlyingType().asElement(), (TypeElement) declaredAsSuper.getUnderlyingType().asElement(), types);
    if (typeArgMap.size() != declaredSubtype.getTypeArguments().size()) {
        return;
    }
    List<Pair<Integer, Integer>> orderedByDestination = new ArrayList<>(typeArgMap);
    orderedByDestination.sort(Comparator.comparingInt(o -> o.second));
    if (typeArgMap.size() == ((AnnotatedDeclaredType) supertype).getTypeArguments().size()) {
        List<? extends AnnotatedTypeMirror> subTypeArgs = declaredSubtype.getTypeArguments();
        List<AnnotatedTypeMirror> newTypeArgs = CollectionsPlume.mapList(mapping -> subTypeArgs.get(mapping.first).deepCopy(), orderedByDestination);
        declaredAsSuper.setTypeArguments(newTypeArgs);
    } else {
        declaredAsSuper.setTypeArguments(Collections.emptyList());
    }
}
Also used : AnnotatedArrayType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType) AnnotatedIntersectionType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType) BugInCF(org.checkerframework.javacutil.BugInCF) QualifierHierarchy(org.checkerframework.framework.type.QualifierHierarchy) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) CanonicalName(org.checkerframework.checker.signature.qual.CanonicalName) Map(java.util.Map) Pair(org.checkerframework.javacutil.Pair) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) Collection(java.util.Collection) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) AnnotatedWildcardType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) WildcardType(com.sun.tools.javac.code.Type.WildcardType) TypeKind(javax.lang.model.type.TypeKind) List(java.util.List) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) Attribute(com.sun.tools.javac.code.Attribute) TypeVariable(javax.lang.model.type.TypeVariable) TypesUtils(org.checkerframework.javacutil.TypesUtils) Type(com.sun.tools.javac.code.Type) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) HashMap(java.util.HashMap) Deque(java.util.Deque) ArrayList(java.util.ArrayList) SyntheticArrays(org.checkerframework.framework.type.SyntheticArrays) LinkedHashMap(java.util.LinkedHashMap) NewClassTree(com.sun.source.tree.NewClassTree) DeclaredType(javax.lang.model.type.DeclaredType) ElementFilter(javax.lang.model.util.ElementFilter) Tree(com.sun.source.tree.Tree) AnnotationUtils(org.checkerframework.javacutil.AnnotationUtils) LinkedHashSet(java.util.LinkedHashSet) Nullable(org.checkerframework.checker.nullness.qual.Nullable) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) ExpressionTree(com.sun.source.tree.ExpressionTree) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) ExecutableElement(javax.lang.model.element.ExecutableElement) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AsSuperVisitor(org.checkerframework.framework.type.AsSuperVisitor) TypeParameterElement(javax.lang.model.element.TypeParameterElement) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) TypeMirror(javax.lang.model.type.TypeMirror) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) StringsPlume(org.plumelib.util.StringsPlume) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) Collections(java.util.Collections) ElementUtils(org.checkerframework.javacutil.ElementUtils) CollectionsPlume(org.plumelib.util.CollectionsPlume) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) ArrayList(java.util.ArrayList) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) Pair(org.checkerframework.javacutil.Pair)

Example 77 with Types

use of javax.lang.model.util.Types in project dubbo by alibaba.

the class MapTypeDefinitionBuilder method accept.

@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
    Elements elements = processingEnv.getElementUtils();
    TypeElement mapTypeElement = elements.getTypeElement(Map.class.getTypeName());
    TypeMirror mapType = mapTypeElement.asType();
    Types types = processingEnv.getTypeUtils();
    TypeMirror erasedType = types.erasure(type);
    return types.isAssignable(erasedType, mapType);
}
Also used : Types(javax.lang.model.util.Types) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) Map(java.util.Map)

Example 78 with Types

use of javax.lang.model.util.Types in project auto by google.

the class MoreElements method getAllMethods.

private static ImmutableSet<ExecutableElement> getAllMethods(TypeElement type, Overrides overrides) {
    SetMultimap<String, ExecutableElement> methodMap = LinkedHashMultimap.create();
    getAllMethods(type, methodMap);
    // Find methods that are overridden. We do this using `Elements.overrides`, which means
    // that it is inherently a quadratic operation, since we have to compare every method against
    // every other method. We reduce the performance impact by (a) grouping methods by name, since
    // a method cannot override another method with a different name, and (b) making sure that
    // methods in ancestor types precede those in descendant types, which means we only have to
    // check a method against the ones that follow it in that order.
    Set<ExecutableElement> overridden = new LinkedHashSet<ExecutableElement>();
    for (Collection<ExecutableElement> methods : methodMap.asMap().values()) {
        List<ExecutableElement> methodList = ImmutableList.copyOf(methods);
        for (int i = 0; i < methodList.size(); i++) {
            ExecutableElement methodI = methodList.get(i);
            for (int j = i + 1; j < methodList.size(); j++) {
                ExecutableElement methodJ = methodList.get(j);
                if (overrides.overrides(methodJ, methodI, type)) {
                    overridden.add(methodI);
                    break;
                }
            }
        }
    }
    return methodMap.values().stream().filter(m -> !overridden.contains(m)).collect(toImmutableSet());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PackageElement(javax.lang.model.element.PackageElement) Modifier(javax.lang.model.element.Modifier) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) MoreStreams.toImmutableSet(com.google.auto.common.MoreStreams.toImmutableSet) ImmutableList(com.google.common.collect.ImmutableList) Optional(com.google.common.base.Optional) ElementFilter(javax.lang.model.util.ElementFilter) SimpleElementVisitor8(javax.lang.model.util.SimpleElementVisitor8) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) LinkedHashSet(java.util.LinkedHashSet) ExplicitOverrides(com.google.auto.common.Overrides.ExplicitOverrides) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) ExecutableElement(javax.lang.model.element.ExecutableElement) Set(java.util.Set) Element(javax.lang.model.element.Element) PACKAGE(javax.lang.model.element.ElementKind.PACKAGE) Types(javax.lang.model.util.Types) AnnotationMirror(javax.lang.model.element.AnnotationMirror) SetMultimap(com.google.common.collect.SetMultimap) Beta(com.google.common.annotations.Beta) TypeParameterElement(javax.lang.model.element.TypeParameterElement) TypeKind(javax.lang.model.type.TypeKind) STATIC(javax.lang.model.element.Modifier.STATIC) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) Predicate(com.google.common.base.Predicate) Annotation(java.lang.annotation.Annotation) ExecutableElement(javax.lang.model.element.ExecutableElement)

Example 79 with Types

use of javax.lang.model.util.Types in project auto by google.

the class AutoValueishProcessor method process.

@Override
public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (annotationType == null) {
        // This should not happen. If the annotation type is not found, how did the processor get
        // triggered?
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Did not process @" + annotationClassName + " because the annotation class was not found");
        return false;
    }
    List<TypeElement> deferredTypes = deferredTypeNames.stream().map(name -> elementUtils().getTypeElement(name)).collect(toList());
    if (roundEnv.processingOver()) {
        // was in deferredTypes.
        for (TypeElement type : deferredTypes) {
            errorReporter.reportError(type, "[%sUndefined] Did not generate @%s class for %s because it references" + " undefined types", simpleAnnotationName, simpleAnnotationName, type.getQualifiedName());
        }
        return false;
    }
    Collection<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotationType);
    List<TypeElement> types = new ImmutableList.Builder<TypeElement>().addAll(deferredTypes).addAll(ElementFilter.typesIn(annotatedElements)).build();
    deferredTypeNames.clear();
    for (TypeElement type : types) {
        try {
            validateType(type);
            processType(type);
        } catch (AbortProcessingException e) {
        // We abandoned this type; continue with the next.
        } catch (MissingTypeException e) {
            // We abandoned this type, but only because we needed another type that it references and
            // that other type was missing. It is possible that the missing type will be generated by
            // further annotation processing, so we will try again on the next round (perhaps failing
            // again and adding it back to the list).
            addDeferredType(type);
        } catch (RuntimeException e) {
            String trace = Throwables.getStackTraceAsString(e);
            errorReporter.reportError(type, "[%sException] @%s processor threw an exception: %s", simpleAnnotationName, simpleAnnotationName, trace);
            throw e;
        }
    }
    // never claim annotation, because who knows what other processors want?
    return false;
}
Also used : Arrays(java.util.Arrays) AbstractProcessor(javax.annotation.processing.AbstractProcessor) Modifier(javax.lang.model.element.Modifier) Inherited(java.lang.annotation.Inherited) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) MoreStreams.toImmutableSet(com.google.auto.common.MoreStreams.toImmutableSet) Diagnostic(javax.tools.Diagnostic) Sets.union(com.google.common.collect.Sets.union) Map(java.util.Map) MoreElements.isAnnotationPresent(com.google.auto.common.MoreElements.isAnnotationPresent) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) EnumMap(java.util.EnumMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) Collectors.joining(java.util.stream.Collectors.joining) Serializable(java.io.Serializable) TypeKind(javax.lang.model.type.TypeKind) AnnotationMirrors.getAnnotationValue(com.google.auto.common.AnnotationMirrors.getAnnotationValue) JavaFileObject(javax.tools.JavaFileObject) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) Writer(java.io.Writer) Optional(java.util.Optional) AnnotationValue(javax.lang.model.element.AnnotationValue) GeneratedAnnotations.generatedAnnotation(com.google.auto.common.GeneratedAnnotations.generatedAnnotation) IntStream(java.util.stream.IntStream) MoreTypes(com.google.auto.common.MoreTypes) COPY_ANNOTATIONS_NAME(com.google.auto.value.processor.ClassNames.COPY_ANNOTATIONS_NAME) VariableElement(javax.lang.model.element.VariableElement) MissingTypeException(com.google.auto.value.processor.MissingTypes.MissingTypeException) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) AUTO_VALUE_PACKAGE_NAME(com.google.auto.value.processor.ClassNames.AUTO_VALUE_PACKAGE_NAME) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Collectors.toCollection(java.util.stream.Collectors.toCollection) MoreElements.getPackage(com.google.auto.common.MoreElements.getPackage) ImmutableList(com.google.common.collect.ImmutableList) DeclaredType(javax.lang.model.type.DeclaredType) QualifiedNameable(javax.lang.model.element.QualifiedNameable) ElementFilter(javax.lang.model.util.ElementFilter) ElementFilter.constructorsIn(javax.lang.model.util.ElementFilter.constructorsIn) Name(javax.lang.model.element.Name) SimpleAnnotationValueVisitor8(javax.lang.model.util.SimpleAnnotationValueVisitor8) MoreElements(com.google.auto.common.MoreElements) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) Throwables(com.google.common.base.Throwables) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) IOException(java.io.IOException) Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) Visibility(com.google.auto.common.Visibility) AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeParameterElement(javax.lang.model.element.TypeParameterElement) MoreStreams.toImmutableList(com.google.auto.common.MoreStreams.toImmutableList) Collectors.toList(java.util.stream.Collectors.toList) TypeMirror(javax.lang.model.type.TypeMirror) RoundEnvironment(javax.annotation.processing.RoundEnvironment) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) MissingTypeException(com.google.auto.value.processor.MissingTypes.MissingTypeException) TypeElement(javax.lang.model.element.TypeElement) ImmutableList(com.google.common.collect.ImmutableList) MoreStreams.toImmutableList(com.google.auto.common.MoreStreams.toImmutableList)

Example 80 with Types

use of javax.lang.model.util.Types in project auto by google.

the class BuilderMethodClassifierForAutoBuilder method rewriteParameterTypes.

// Rewrites the parameter types of the executable so they use the type variables of the builder
// where appropriate.
// 
// Suppose we have something like this:
// 
// static <E> Set<E> singletonSet(E elem) {...}
// 
// @AutoBuilder(callMethod = "singletonSet")
// interface SingletonSetBuilder<E> {
// SingletonSetBuilder<E> setElem(E elem);
// Set<E> build();
// }
// 
// We want to check that the type of the setter `setElem` matches the type of the
// parameter it is setting. But in fact it doesn't: the type of the setter is
// E-of-SingletonSetBuilder while the type of the parameter is E-of-singletonSet. So we
// need to rewrite any type variables mentioned in parameters so that they use the corresponding
// types from the builder. We want to return a map where "elem" is mapped to
// E-of-SingletonSetBuilder, even though the `elem` that we get from the parameters of
// singletonSet is going to be E-of-singletonSet. And we also want that to work if the parameter
// is something more complicated, like List<? extends E>.
// 
// For the corresponding situation with AutoValue, we have a way of dodging the problem somewhat.
// For an @AutoValue class Foo<E> with a builder Builder<E>, we can craft a DeclaredType
// Foo<E> where the E comes from Builder<E>, and we can use Types.asMemberOf to determine the
// return types of methods (which are what we want to rewrite in that case). But that doesn't
// work here because singletonSet is static and Types.asMemberOf would have no effect on it.
// 
// So instead we take the type of each parameter and feed it through a TypeVisitor that rewrites
// type variables, rewriting from E-of-singletonSet to E-of-SingletonSetBuilder. Then we can use
// Types.isSameType or Types.isAssignable and it will work as we expect.
// 
// In principle a similar situation arises with the return type Set<E> of singletonSet versus
// the return type Set<E> of SingletonSetBuilder.build(). But in fact we only use
// MoreTypes.equivalence to compare those, and that returns true for distinct type variables if
// they have the same name and bounds.
private static ImmutableMap<String, TypeMirror> rewriteParameterTypes(ExecutableElement executable, TypeElement builderType, ErrorReporter errorReporter, Types typeUtils) {
    ImmutableList<TypeParameterElement> executableTypeParams = executableTypeParams(executable);
    List<? extends TypeParameterElement> builderTypeParams = builderType.getTypeParameters();
    if (!BuilderSpec.sameTypeParameters(executableTypeParams, builderTypeParams)) {
        errorReporter.abortWithError(builderType, "[AutoBuilderTypeParams] Builder type parameters %s must match type parameters %s of %s", TypeEncoder.typeParametersString(builderTypeParams), TypeEncoder.typeParametersString(executableTypeParams), AutoBuilderProcessor.executableString(executable));
    }
    if (executableTypeParams.isEmpty()) {
        // variables to substitute.
        return executable.getParameters().stream().collect(toImmutableMap(v -> v.getSimpleName().toString(), Element::asType));
    }
    Map<Equivalence.Wrapper<TypeVariable>, TypeMirror> typeVariables = new LinkedHashMap<>();
    for (int i = 0; i < executableTypeParams.size(); i++) {
        TypeVariable from = MoreTypes.asTypeVariable(executableTypeParams.get(i).asType());
        TypeVariable to = MoreTypes.asTypeVariable(builderTypeParams.get(i).asType());
        typeVariables.put(MoreTypes.equivalence().wrap(from), to);
    }
    Function<TypeVariable, TypeMirror> substitute = v -> typeVariables.get(MoreTypes.equivalence().wrap(v));
    return executable.getParameters().stream().collect(toImmutableMap(v -> v.getSimpleName().toString(), v -> TypeVariables.substituteTypeVariables(v.asType(), substitute, typeUtils)));
}
Also used : VerifyException(com.google.common.base.VerifyException) MoreElements(com.google.auto.common.MoreElements) ImmutableSet(com.google.common.collect.ImmutableSet) MoreTypes(com.google.auto.common.MoreTypes) Equivalence(com.google.common.base.Equivalence) ImmutableMap(com.google.common.collect.ImmutableMap) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableElement(javax.lang.model.element.VariableElement) MoreStreams.toImmutableMap(com.google.auto.common.MoreStreams.toImmutableMap) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) Types(javax.lang.model.util.Types) Function(java.util.function.Function) TypeParameterElement(javax.lang.model.element.TypeParameterElement) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) LinkedHashMap(java.util.LinkedHashMap) MoreStreams.toImmutableBiMap(com.google.auto.common.MoreStreams.toImmutableBiMap) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Optional(java.util.Optional) TypeVariable(javax.lang.model.type.TypeVariable) TypeMirror(javax.lang.model.type.TypeMirror) TypeVariable(javax.lang.model.type.TypeVariable) TypeParameterElement(javax.lang.model.element.TypeParameterElement) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

Types (javax.lang.model.util.Types)113 TypeMirror (javax.lang.model.type.TypeMirror)77 TypeElement (javax.lang.model.element.TypeElement)52 Elements (javax.lang.model.util.Elements)48 ExecutableElement (javax.lang.model.element.ExecutableElement)34 Element (javax.lang.model.element.Element)30 SupportedAnnotationTypes (javax.annotation.processing.SupportedAnnotationTypes)27 DeclaredType (javax.lang.model.type.DeclaredType)26 ArrayList (java.util.ArrayList)25 Map (java.util.Map)24 VariableElement (javax.lang.model.element.VariableElement)24 List (java.util.List)21 AnnotationMirror (javax.lang.model.element.AnnotationMirror)20 TypeKind (javax.lang.model.type.TypeKind)18 Set (java.util.Set)16 Collection (java.util.Collection)15 HashMap (java.util.HashMap)13 ElementKind (javax.lang.model.element.ElementKind)13 Modifier (javax.lang.model.element.Modifier)13 IOException (java.io.IOException)12