com.google.auto.common.MoreTypes Java Examples

The following examples show how to use com.google.auto.common.MoreTypes. 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: MemoizeExtension.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the contents of the {@code AutoValue.CopyAnnotations.exclude} element, as a set of
 * {@code TypeMirror} where each type is an annotation type.
 */
// TODO(b/122509249): Move code copied from com.google.auto.value.processor to auto-common.
private ImmutableSet<TypeMirror> getExcludedAnnotationTypes(Element element) {
  Optional<AnnotationMirror> maybeAnnotation =
      getAnnotationMirror(element, COPY_ANNOTATIONS_NAME);
  if (!maybeAnnotation.isPresent()) {
    return ImmutableSet.of();
  }

  @SuppressWarnings("unchecked")
  List<AnnotationValue> excludedClasses =
      (List<AnnotationValue>) getAnnotationValue(maybeAnnotation.get(), "exclude").getValue();
  return excludedClasses.stream()
      .map(
          annotationValue ->
              MoreTypes.equivalence().wrap((TypeMirror) annotationValue.getValue()))
      // TODO(b/122509249): Move TypeMirrorSet to common package instead of doing this.
      .distinct()
      .map(Wrapper::get)
      .collect(toImmutableSet());
}
 
Example #2
Source File: PropertyBuilderClassifier.java    From auto with Apache License 2.0 6 votes vote down vote up
private Optional<ExecutableElement> addAllPutAll(
    TypeElement barBuilderTypeElement,
    DeclaredType barBuilderDeclaredType,
    TypeMirror barTypeMirror) {
  return MoreElements.getLocalAndInheritedMethods(barBuilderTypeElement, typeUtils, elementUtils)
      .stream()
      .filter(
          method ->
              ADD_ALL_PUT_ALL.contains(method.getSimpleName().toString())
                  && method.getParameters().size() == 1)
      .filter(
          method -> {
            ExecutableType methodMirror =
                MoreTypes.asExecutable(typeUtils.asMemberOf(barBuilderDeclaredType, method));
            return typeUtils.isAssignable(barTypeMirror, methodMirror.getParameterTypes().get(0));
          })
      .findFirst();
}
 
Example #3
Source File: PaperParcelAutoValueExtension.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private static boolean needsContentDescriptor(Context context) {
  ProcessingEnvironment env = context.processingEnvironment();
  TypeElement autoValueTypeElement = context.autoValueClass();
  Elements elements = env.getElementUtils();
  @SuppressWarnings("deprecation") // Support for kapt2
  ImmutableSet<ExecutableElement> methods =
      MoreElements.getLocalAndInheritedMethods(autoValueTypeElement, elements);
  for (ExecutableElement element : methods) {
    if (element.getSimpleName().contentEquals("describeContents")
        && MoreTypes.isTypeOf(int.class, element.getReturnType())
        && element.getParameters().isEmpty()
        && !element.getModifiers().contains(ABSTRACT)) {
      return false;
    }
  }
  return true;
}
 
Example #4
Source File: TableEntry.java    From RapidORM with Apache License 2.0 6 votes vote down vote up
private void parse() throws Throwable {

        List<Element> allElements = new ArrayList<>();
        allElements.add(mSourceClassEle);
        Element currentClass = mSourceClassEle;
        do {
            Optional<DeclaredType> superClass = MoreTypes.nonObjectSuperclass(GlobalEnvironment.getProcessingEnv().getTypeUtils(),
                    GlobalEnvironment.getProcessingEnv().getElementUtils(), (DeclaredType) currentClass.asType());
            if (superClass.isPresent()) {
                currentClass = superClass.get().asElement();
                allElements.add(currentClass);
                LogUtil.logger("superclass.get().asElement().toString(): " + currentClass.toString());
            } else {
                currentClass = null;
            }
        } while (null != currentClass);

        for (int i = allElements.size() - 1; i >= 0; i--) {
            buildAllColumns(allElements.get(i));
        }

    }
 
Example #5
Source File: ReduceAction.java    From reductor with Apache License 2.0 6 votes vote down vote up
private static void validateActionCreator(ExecutableElement element,
                                          String actionName,
                                          TypeMirror actionCreator,
                                          ArrayList<VariableElement> args,
                                          Map<String, ActionCreatorElement> knownActionCreators,
                                          Env env) throws ValidationException {
    Element actionCreatorElement = MoreTypes.asElement(actionCreator);
    if (!MoreElements.isAnnotationPresent(actionCreatorElement, ActionCreator.class)) {
        throw new ValidationException(element, "Action creator %s should be annotated with @%s", actionCreator, ActionCreator.class.getSimpleName());
    }

    ActionCreatorElement creatorElement = knownActionCreators.get(env.getElements().getBinaryName((TypeElement) actionCreatorElement).toString());
    if (creatorElement == null) {
        throw new ElementNotReadyException();
    }
    if (!creatorElement.hasAction(actionName, args)) {
        throw new ValidationException(element, "Cannot find action creator for action \"%s\" and args %s in interface %s", actionName, toString(args), creatorElement.getName(env));
    }
}
 
Example #6
Source File: Key.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a key based on the type {@code type} and any {@link Qualifier}s in {@code
 * annotations}.
 *
 * <p>If {@code type} is a {@code Provider<T>}, the returned {@link Key}'s {@link #type()} is
 * {@code T}. If {@code type} is a primitive, the returned {@link Key}'s {@link #type()} is the
 * corresponding {@linkplain Types#boxedClass(PrimitiveType) boxed type}.
 *
 * <p>For example:
 * <table>
 *   <tr><th>Input type                <th>{@code Key.type()}
 *   <tr><td>{@code String}            <td>{@code String}
 *   <tr><td>{@code Provider<String>}  <td>{@code String}
 *   <tr><td>{@code int}               <td>{@code Integer}
 * </table>
 */
static Key create(
    TypeMirror type, Iterable<? extends AnnotationMirror> annotations, Types types) {
  ImmutableSet.Builder<AnnotationMirror> qualifiers = ImmutableSet.builder();
  for (AnnotationMirror annotation : annotations) {
    if (isAnnotationPresent(annotation.getAnnotationType().asElement(), Qualifier.class)) {
      qualifiers.add(annotation);
    }
  }

  // TODO(gak): check for only one qualifier rather than using the first
  Optional<AnnotationMirror> qualifier = FluentIterable.from(qualifiers.build()).first();

  TypeMirror keyType =
      isProvider(type)
          ? MoreTypes.asDeclared(type).getTypeArguments().get(0)
          : boxedType(type, types);
  return new AutoValue_Key(
      MoreTypes.equivalence().wrap(keyType),
      wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), qualifier));
}
 
Example #7
Source File: Utils.java    From reductor with Apache License 2.0 6 votes vote down vote up
public static DeclaredType getReducerSuperInterface(DeclaredType reducerType) {
    List<? extends TypeMirror> supertypes = MoreTypes.asTypeElement(reducerType).getInterfaces();

    for (TypeMirror supertype : supertypes) {
        boolean isReducer = MoreTypes.isTypeOf(Reducer.class, supertype);
        if (isReducer) {
            return MoreTypes.asDeclared(supertype);
        }
    }

    TypeMirror superclass = MoreTypes.asTypeElement(reducerType).getSuperclass();
    if (!MoreTypes.isTypeOf(Object.class, superclass)) {
        return getReducerSuperInterface(MoreTypes.asDeclared(superclass));
    }

    return null;
}
 
Example #8
Source File: Key.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a key of {@link Map}{@code <K, WrappingClass<V>>} if the input key represents a
 * {@code Map<K, V>}.
 */
private Optional<Key> maybeWrapMapValue(Key possibleMapKey, Class<?> wrappingClass) {
  if (MoreTypes.isTypeOf(Map.class, possibleMapKey.type())) {
    DeclaredType declaredMapType = MoreTypes.asDeclared(possibleMapKey.type());
    TypeMirror mapValueType = Util.getValueTypeOfMap(declaredMapType);
    if (!MoreTypes.isTypeOf(wrappingClass, mapValueType)) {
      DeclaredType keyType = Util.getKeyTypeOfMap(declaredMapType);
      TypeElement wrappingElement = getClassElement(wrappingClass);
      if (wrappingElement == null) {
        // This target might not be compiled with Producers, so wrappingClass might not have an
        // associated element.
        return Optional.absent();
      }
      DeclaredType wrappedType = types.getDeclaredType(wrappingElement, mapValueType);
      TypeMirror mapType = types.getDeclaredType(getMapElement(), keyType, wrappedType);
      return Optional.<Key>of(new AutoValue_Key(
          possibleMapKey.wrappedQualifier(),
          MoreTypes.equivalence().wrap(mapType)));
    }
  }
  return Optional.absent();
}
 
Example #9
Source File: ConfigurationAnnotations.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
/** Traverses includes from superclasses and adds them into the builder. */
private static void addIncludesFromSuperclasses(Types types, TypeElement element,
    ImmutableSet.Builder<TypeElement> builder, TypeMirror objectType) {
  // Also add the superclass to the queue, in case any @Module definitions were on that.
  TypeMirror superclass = element.getSuperclass();
  while (!types.isSameType(objectType, superclass)
      && superclass.getKind().equals(TypeKind.DECLARED)) {
    element = MoreElements.asType(types.asElement(superclass));
    Optional<AnnotationMirror> moduleMirror = getAnnotationMirror(element, Module.class)
        .or(getAnnotationMirror(element, ProducerModule.class));
    if (moduleMirror.isPresent()) {
      builder.addAll(MoreTypes.asTypeElements(getModuleIncludes(moduleMirror.get())));
    }
    superclass = element.getSuperclass();
  }
}
 
Example #10
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forInjectConstructorWithResolvedType() {
  TypeElement typeElement =
      compilationRule.getElements().getTypeElement(InjectedClass.class.getCanonicalName());
  ExecutableElement constructor =
      Iterables.getOnlyElement(ElementFilter.constructorsIn(typeElement.getEnclosedElements()));
  assertThat(
      keyFactory.forInjectConstructorWithResolvedType(constructor.getEnclosingElement().asType()))
      .isEqualTo(new AutoValue_Key(
          Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
          MoreTypes.equivalence().wrap(typeElement.asType())));
}
 
Example #11
Source File: BuilderSpec.java    From auto with Apache License 2.0 5 votes vote down vote up
private static String parameterTypeString(ExecutableElement setter, TypeMirror parameterType) {
  if (setter.isVarArgs()) {
    TypeMirror componentType = MoreTypes.asArray(parameterType).getComponentType();
    // This is a bit ugly. It's OK to annotate just the component type, because if it is
    // say `@Nullable String` then we will end up with `@Nullable String...`. Unlike the
    // normal array case, we can't have the situation where the array itself is annotated;
    // you can write `String @Nullable []` to mean that, but you can't write
    // `String @Nullable ...`.
    return TypeEncoder.encodeWithAnnotations(componentType) + "...";
  } else {
    return TypeEncoder.encodeWithAnnotations(parameterType);
  }
}
 
Example #12
Source File: AutoServiceProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
private void processAnnotations(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {

  Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class);

  log(annotations.toString());
  log(elements.toString());

  for (Element e : elements) {
    // TODO(gak): check for error trees?
    TypeElement providerImplementer = (TypeElement) e;
    AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get();
    Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror);
    if (providerInterfaces.isEmpty()) {
      error(MISSING_SERVICES_ERROR, e, annotationMirror);
      continue;
    }
    for (DeclaredType providerInterface : providerInterfaces) {
      TypeElement providerType = MoreTypes.asTypeElement(providerInterface);

      log("provider interface: " + providerType.getQualifiedName());
      log("provider implementer: " + providerImplementer.getQualifiedName());

      if (checkImplementer(providerImplementer, providerType)) {
        providers.put(getBinaryName(providerType), getBinaryName(providerImplementer));
      } else {
        String message = "ServiceProviders must implement their service provider interface. "
            + providerImplementer.getQualifiedName() + " does not implement "
            + providerType.getQualifiedName();
        error(message, e, annotationMirror);
      }
    }
  }
}
 
Example #13
Source File: BuilderSpec.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
/**
 * Finds any methods in the set that return the builder type. If the builder has type parameters
 * {@code <A, B>}, then the return type of the method must be {@code Builder<A, B>} with
 * the same parameter names. We enforce elsewhere that the names and bounds of the builder
 * parameters must be the same as those of the @RetroWeibo class. Here's a correct example:
 * <pre>
 * {@code @RetroWeibo abstract class Foo<A extends Number, B> {
 *   abstract int someProperty();
 *
 *   abstract Builder<A, B> toBuilder();
 *
 *   interface Builder<A extends Number, B> {...}
 * }}
 * </pre>
 * <p/>
 * <p>We currently impose that there cannot be more than one such method.</p>
 */
ImmutableSet<ExecutableElement> toBuilderMethods(
    Types typeUtils, Set<ExecutableElement> abstractMethods) {

  ImmutableList<String> builderTypeParamNames =
      FluentIterable.from(builderTypeElement.getTypeParameters())
          .transform(SimpleNameFunction.INSTANCE)
          .toList();

  ImmutableSet.Builder<ExecutableElement> methods = ImmutableSet.builder();
  for (ExecutableElement method : abstractMethods) {
    if (builderTypeElement.equals(typeUtils.asElement(method.getReturnType()))) {
      methods.add(method);
      DeclaredType returnType = MoreTypes.asDeclared(method.getReturnType());
      ImmutableList.Builder<String> typeArguments = ImmutableList.builder();
      for (TypeMirror typeArgument : returnType.getTypeArguments()) {
        if (typeArgument.getKind().equals(TypeKind.TYPEVAR)) {
          typeArguments.add(typeUtils.asElement(typeArgument).getSimpleName().toString());
        }
      }
      if (!builderTypeParamNames.equals(typeArguments.build())) {
        errorReporter.reportError(
            "Builder converter method should return "
                + builderTypeElement
                + TypeSimplifier.actualTypeParametersString(builderTypeElement),
            method);
      }
    }
  }
  ImmutableSet<ExecutableElement> builderMethods = methods.build();
  if (builderMethods.size() > 1) {
    errorReporter.reportError(
        "There can be at most one builder converter method", builderMethods.iterator().next());
  }
  return builderMethods;
}
 
Example #14
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forProducesMethod_sets() {
  TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName());
  TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType();
  TypeMirror setOfStringsType = types.getDeclaredType(setElement, stringType);
  TypeElement moduleElement =
      elements.getTypeElement(SetProducesMethodsModule.class.getCanonicalName());
  for (ExecutableElement producesMethod
      : ElementFilter.methodsIn(moduleElement.getEnclosedElements())) {
    assertThat(keyFactory.forProducesMethod(
        (ExecutableType) producesMethod.asType(), producesMethod))
        .isEqualTo(new AutoValue_Key(
                Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
                MoreTypes.equivalence().wrap(setOfStringsType)));
  }
}
 
Example #15
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forProducesMethod() {
  TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType();
  TypeElement moduleElement =
      elements.getTypeElement(ProducesMethodsModule.class.getCanonicalName());
  for (ExecutableElement producesMethod
      : ElementFilter.methodsIn(moduleElement.getEnclosedElements())) {
    assertThat(keyFactory.forProducesMethod(
        (ExecutableType) producesMethod.asType(), producesMethod))
            .isEqualTo(new AutoValue_Key(
                Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
                MoreTypes.equivalence().wrap(stringType)));
  }
}
 
Example #16
Source File: MemoizedValidator.java    From auto with Apache License 2.0 5 votes vote down vote up
private static boolean isAutoValue(Element element) {
  return element
      .getAnnotationMirrors()
      .stream()
      .map(annotation -> MoreTypes.asTypeElement(annotation.getAnnotationType()))
      .anyMatch(type -> type.getQualifiedName().contentEquals("com.google.auto.value.AutoValue"));
}
 
Example #17
Source File: Optionalish.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an instance wrapping the given TypeMirror, or null if it is not any kind of Optional.
 *
 * @param type the TypeMirror for the original optional type, for example {@code
 *     Optional<String>}.
 */
static Optionalish createIfOptional(TypeMirror type) {
  if (isOptional(type)) {
    return new Optionalish(MoreTypes.asDeclared(type));
  } else {
    return null;
  }
}
 
Example #18
Source File: JSONRegistrationProcessor.java    From domino-jackson with Apache License 2.0 5 votes vote down vote up
private TypeMirror getBeanType(Element element) {
    if (useInterface(element)) {
        TypeMirror objectReader = ((TypeElement) typeUtils.asElement(element.asType())).getInterfaces().get(0);
        return MoreTypes.asDeclared(objectReader).getTypeArguments().get(0);
    } else {
        return element.asType();
    }
}
 
Example #19
Source File: MethodSignatureFormatter.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Formats an ExecutableElement as if it were contained within the container, if the container is
 * present.
 */
public String format(ExecutableElement method, Optional<DeclaredType> container) {
  StringBuilder builder = new StringBuilder();
  TypeElement type = MoreElements.asType(method.getEnclosingElement());
  ExecutableType executableType = MoreTypes.asExecutable(method.asType());
  if (container.isPresent()) {
    executableType = MoreTypes.asExecutable(types.asMemberOf(container.get(), method));
    type = MoreElements.asType(container.get().asElement());
  }

  // TODO(cgruber): AnnotationMirror formatter.
  List<? extends AnnotationMirror> annotations = method.getAnnotationMirrors();
  if (!annotations.isEmpty()) {
    Iterator<? extends AnnotationMirror> annotationIterator = annotations.iterator();
    for (int i = 0; annotationIterator.hasNext(); i++) {
      if (i > 0) {
        builder.append(' ');
      }
      builder.append(ErrorMessages.format(annotationIterator.next()));
    }
    builder.append(' ');
  }
  builder.append(nameOfType(executableType.getReturnType()));
  builder.append(' ');
  builder.append(type.getQualifiedName());
  builder.append('.');
  builder.append(method.getSimpleName());
  builder.append('(');
  checkState(method.getParameters().size() == executableType.getParameterTypes().size());
  Iterator<? extends VariableElement> parameters = method.getParameters().iterator();
  Iterator<? extends TypeMirror> parameterTypes = executableType.getParameterTypes().iterator();
  for (int i = 0; parameters.hasNext(); i++) {
    if (i > 0) {
      builder.append(", ");
    }
    appendParameter(builder, parameters.next(), parameterTypes.next());
  }
  builder.append(')');
  return builder.toString();
}
 
Example #20
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forProvidesMethod_qualified() {
  TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType();
  TypeElement qualifierElement =
      elements.getTypeElement(TestQualifier.class.getCanonicalName());
  TypeElement moduleElement =
      elements.getTypeElement(QualifiedProvidesMethodModule.class.getCanonicalName());
  ExecutableElement providesMethod =
      Iterables.getOnlyElement(ElementFilter.methodsIn(moduleElement.getEnclosedElements()));
  Key key =
      keyFactory.forProvidesMethod((ExecutableType) providesMethod.asType(), providesMethod);
  assertThat(MoreTypes.equivalence().wrap(key.qualifier().get().getAnnotationType()))
      .isEqualTo(MoreTypes.equivalence().wrap(qualifierElement.asType()));
  assertThat(key.wrappedType()).isEqualTo(MoreTypes.equivalence().wrap(stringType));
}
 
Example #21
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forProvidesMethod_sets() {
  TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName());
  TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType();
  TypeMirror setOfStringsType = types.getDeclaredType(setElement, stringType);
  TypeElement moduleElement =
      elements.getTypeElement(SetProvidesMethodsModule.class.getCanonicalName());
  for (ExecutableElement providesMethod
      : ElementFilter.methodsIn(moduleElement.getEnclosedElements())) {
    assertThat(
        keyFactory.forProvidesMethod((ExecutableType) providesMethod.asType(), providesMethod))
            .isEqualTo(new AutoValue_Key(
                Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
                MoreTypes.equivalence().wrap(setOfStringsType)));
  }
}
 
Example #22
Source File: ComponentDescriptor.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
private static void findLocalAndInheritedMethods(Elements elements, TypeElement type,
    List<ExecutableElement> methods) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    findLocalAndInheritedMethods(
        elements, MoreElements.asType(MoreTypes.asElement(superInterface)), methods);
  }
  if (type.getSuperclass().getKind() != TypeKind.NONE) {
    // Visit the superclass after superinterfaces so we will always see the implementation of a
    // method after any interfaces that declared it.
    findLocalAndInheritedMethods(
        elements, MoreElements.asType(MoreTypes.asElement(type.getSuperclass())), methods);
  }
  // Add each method of this class, and in so doing remove any inherited method it overrides.
  // This algorithm is quadratic in the number of methods but it's hard to see how to improve
  // that while still using Elements.overrides.
  List<ExecutableElement> theseMethods = ElementFilter.methodsIn(type.getEnclosedElements());
  for (ExecutableElement method : theseMethods) {
    if (!method.getModifiers().contains(Modifier.PRIVATE)) {
      boolean alreadySeen = false;
      for (Iterator<ExecutableElement> methodIter = methods.iterator(); methodIter.hasNext();) {
        ExecutableElement otherMethod = methodIter.next();
        if (elements.overrides(method, otherMethod, type)) {
          methodIter.remove();
        } else if (method.getSimpleName().equals(otherMethod.getSimpleName())
            && method.getParameters().equals(otherMethod.getParameters())) {
          // If we inherit this method on more than one path, we don't want to add it twice.
          alreadySeen = true;
        }
      }
      if (!alreadySeen) {
        methods.add(method);
      }
    }
  }
}
 
Example #23
Source File: ConfigurationAnnotations.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the full set of modules transitively {@linkplain Module#includes included} from the
 * given seed modules.  If a module is malformed and a type listed in {@link Module#includes}
 * is not annotated with {@link Module}, it is ignored.
 */
static ImmutableSet<TypeElement> getTransitiveModules(
    Types types, Elements elements, Iterable<TypeElement> seedModules) {
  TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType();
  Queue<TypeElement> moduleQueue = Queues.newArrayDeque(seedModules);
  Set<TypeElement> moduleElements = Sets.newLinkedHashSet();
  for (TypeElement moduleElement = moduleQueue.poll();
      moduleElement != null;
      moduleElement = moduleQueue.poll()) {
    Optional<AnnotationMirror> moduleMirror = getAnnotationMirror(moduleElement, Module.class)
        .or(getAnnotationMirror(moduleElement, ProducerModule.class));
    if (moduleMirror.isPresent()) {
      ImmutableSet.Builder<TypeElement> moduleDependenciesBuilder = ImmutableSet.builder();
      moduleDependenciesBuilder.addAll(
          MoreTypes.asTypeElements(getModuleIncludes(moduleMirror.get())));
      // (note: we don't recurse on the parent class because we don't want the parent class as a
      // root that the component depends on, and also because we want the dependencies rooted
      // against this element, not the parent.)
      addIncludesFromSuperclasses(types, moduleElement, moduleDependenciesBuilder, objectType);
      ImmutableSet<TypeElement> moduleDependencies = moduleDependenciesBuilder.build();
      moduleElements.add(moduleElement);
      for (TypeElement dependencyType : moduleDependencies) {
        if (!moduleElements.contains(dependencyType)) {
          moduleQueue.add(dependencyType);
        }
      }
    }
  }
  return ImmutableSet.copyOf(moduleElements);
}
 
Example #24
Source File: BuilderSpec.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Finds any methods in the set that return the builder type. If the builder has type parameters
 * {@code <A, B>}, then the return type of the method must be {@code Builder<A, B>} with the
 * same parameter names. We enforce elsewhere that the names and bounds of the builder
 * parameters must be the same as those of the @AutoValue class. Here's a correct example:
 *
 * <pre>
 * {@code @AutoValue abstract class Foo<A extends Number, B> {
 *   abstract int someProperty();
 *
 *   abstract Builder<A, B> toBuilder();
 *
 *   interface Builder<A extends Number, B> {...}
 * }}
 * </pre>
 *
 * <p>We currently impose that there cannot be more than one such method.
 */
ImmutableSet<ExecutableElement> toBuilderMethods(
    Types typeUtils, Set<ExecutableElement> abstractMethods) {

  List<String> builderTypeParamNames =
      builderTypeElement.getTypeParameters().stream()
          .map(e -> e.getSimpleName().toString())
          .collect(toList());

  ImmutableSet.Builder<ExecutableElement> methods = ImmutableSet.builder();
  for (ExecutableElement method : abstractMethods) {
    if (builderTypeElement.equals(typeUtils.asElement(method.getReturnType()))) {
      methods.add(method);
      DeclaredType returnType = MoreTypes.asDeclared(method.getReturnType());
      List<String> typeArguments =
          returnType.getTypeArguments().stream()
              .filter(t -> t.getKind().equals(TypeKind.TYPEVAR))
              .map(t -> typeUtils.asElement(t).getSimpleName().toString())
              .collect(toList());
      if (!builderTypeParamNames.equals(typeArguments)) {
        errorReporter.reportError(
            method,
            "Builder converter method should return %s%s",
            builderTypeElement,
            TypeSimplifier.actualTypeParametersString(builderTypeElement));
      }
    }
  }
  ImmutableSet<ExecutableElement> builderMethods = methods.build();
  if (builderMethods.size() > 1) {
    errorReporter.reportError(
        builderMethods.iterator().next(), "There can be at most one builder converter method");
  }
  this.toBuilderMethods = builderMethods;
  return builderMethods;
}
 
Example #25
Source File: ProductionBinding.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
ProductionBinding forProducesMethod(
    ExecutableElement producesMethod, TypeMirror contributedBy) {
  checkNotNull(producesMethod);
  checkArgument(producesMethod.getKind().equals(METHOD));
  checkArgument(contributedBy.getKind().equals(TypeKind.DECLARED));
  Produces producesAnnotation = producesMethod.getAnnotation(Produces.class);
  checkArgument(producesAnnotation != null);
  DeclaredType declaredContainer = MoreTypes.asDeclared(contributedBy);
  ExecutableType resolvedMethod =
      MoreTypes.asExecutable(types.asMemberOf(declaredContainer, producesMethod));
  Key key = keyFactory.forProducesMethod(resolvedMethod, producesMethod);
  ImmutableSet<DependencyRequest> dependencies =
      dependencyRequestFactory.forRequiredResolvedVariables(
          declaredContainer,
          producesMethod.getParameters(),
          resolvedMethod.getParameterTypes());
  Kind kind = MoreTypes.isTypeOf(ListenableFuture.class, producesMethod.getReturnType())
      ? Kind.FUTURE_PRODUCTION
      : Kind.IMMEDIATE;
  return new AutoValue_ProductionBinding(
      key,
      producesMethod,
      dependencies,
      findBindingPackage(key),
      false,
      ConfigurationAnnotations.getNullableType(producesMethod),
      Optional.of(MoreTypes.asTypeElement(declaredContainer)),
      kind,
      producesAnnotation.type(),
      ImmutableList.copyOf(producesMethod.getThrownTypes()));
}
 
Example #26
Source File: SerializableAutoValueExtension.java    From auto with Apache License 2.0 5 votes vote down vote up
private static boolean hasSerializableAutoValueAnnotation(Context context) {
  return context.autoValueClass().getAnnotationMirrors().stream()
      .map(AnnotationMirror::getAnnotationType)
      .map(MoreTypes::asTypeElement)
      .map(TypeElement::getQualifiedName)
      .anyMatch(name -> name.contentEquals(SERIALIZABLE_AUTO_VALUE_NAME));
}
 
Example #27
Source File: Key.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
Key forProductionComponentMethod(ExecutableElement componentMethod) {
  checkNotNull(componentMethod);
  checkArgument(componentMethod.getKind().equals(METHOD));
  TypeMirror returnType = normalize(types, componentMethod.getReturnType());
  TypeMirror keyType = returnType;
  if (MoreTypes.isTypeOf(ListenableFuture.class, returnType)) {
    keyType = Iterables.getOnlyElement(MoreTypes.asDeclared(returnType).getTypeArguments());
  }
  return new AutoValue_Key(
      wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), getQualifier(componentMethod)),
      MoreTypes.equivalence().wrap(keyType));
}
 
Example #28
Source File: Key.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
Key forComponentMethod(ExecutableElement componentMethod) {
  checkNotNull(componentMethod);
  checkArgument(componentMethod.getKind().equals(METHOD));
  TypeMirror returnType = normalize(types, componentMethod.getReturnType());
  return new AutoValue_Key(
      wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), getQualifier(componentMethod)),
      MoreTypes.equivalence().wrap(returnType));
}
 
Example #29
Source File: Optionalish.java    From auto with Apache License 2.0 5 votes vote down vote up
static boolean isOptional(TypeMirror type) {
  if (type.getKind() != TypeKind.DECLARED) {
    return false;
  }
  DeclaredType declaredType = MoreTypes.asDeclared(type);
  TypeElement typeElement = MoreElements.asType(declaredType.asElement());
  return OPTIONAL_CLASS_NAMES.contains(typeElement.getQualifiedName().toString())
      && typeElement.getTypeParameters().size() == declaredType.getTypeArguments().size();
}
 
Example #30
Source File: TestStringSerializerFactory.java    From auto with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Serializer> getSerializer(
    TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv) {
  if (typeMirror.getKind() != TypeKind.DECLARED) {
    return Optional.empty();
  }

  DeclaredType declaredType = MoreTypes.asDeclared(typeMirror);
  TypeElement typeElement = MoreElements.asType(declaredType.asElement());
  if (typeElement.getQualifiedName().contentEquals("java.lang.String")) {
    return Optional.of(new TestStringSerializer(typeMirror));
  }

  return Optional.empty();
}