Java Code Examples for com.google.auto.common.MoreTypes#asDeclared()
The following examples show how to use
com.google.auto.common.MoreTypes#asDeclared() .
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: ProducesMethodValidator.java From dagger2-sample with Apache License 2.0 | 6 votes |
private void validateSetType(ValidationReport.Builder<? extends Element> reportBuilder, TypeMirror type) { if (!type.getKind().equals(DECLARED)) { reportBuilder.addItem(PRODUCES_METHOD_SET_VALUES_RETURN_SET, reportBuilder.getSubject()); return; } // TODO(gak): should we allow "covariant return" for set values? DeclaredType declaredType = MoreTypes.asDeclared(type); if (!declaredType.asElement().equals(getSetElement())) { reportBuilder.addItem(PRODUCES_METHOD_SET_VALUES_RETURN_SET, reportBuilder.getSubject()); } else if (declaredType.getTypeArguments().isEmpty()) { reportBuilder.addItem(formatErrorMessage(BINDING_METHOD_SET_VALUES_RAW_SET), reportBuilder.getSubject()); } else { validateSingleReturnType(reportBuilder, Iterables.getOnlyElement(declaredType.getTypeArguments())); } }
Example 2
Source File: Key.java From dagger2-sample with Apache License 2.0 | 6 votes |
/** * 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 3
Source File: Utils.java From reductor with Apache License 2.0 | 6 votes |
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 4
Source File: EclipseHack.java From auto with Apache License 2.0 | 5 votes |
/** * Returns the enclosing type of {@code type}, if {@code type} is an inner class. Otherwise * returns a {@code NoType}. This is what {@link DeclaredType#getEnclosingType()} is supposed to * do. However, some versions of Eclipse have a bug where, for example, asking for the enclosing * type of {@code PrimitiveIterator.OfInt} will return {@code PrimitiveIterator<T, T_CONS>} rather * than plain {@code PrimitiveIterator}, as if {@code OfInt} were an inner class rather than a * static one. This would lead us to write a reference to {@code OfInt} as {@code * PrimitiveIterator<T, T_CONS>.OfInt}, which would obviously break. We attempt to avert this by * detecting that: * * <ul> * <li>there is an enclosing type that is a {@code DeclaredType}, which should mean that {@code * type} is an inner class; * <li>we are in the Eclipse compiler; * <li>the type arguments of the purported enclosing type are all type variables with the same * names as the corresponding type parameters. * </ul> * * <p>If all these conditions are met, we assume we're hitting the Eclipse bug, and we return no * enclosing type instead. That does mean that in the unlikely event where we really do have an * inner class of an instantiation of the outer class with type arguments that happen to be type * variables with the same names as the corresponding parameters, we will do the wrong thing on * Eclipse. But doing the wrong thing in that case is better than doing the wrong thing in the * usual case. */ static TypeMirror getEnclosingType(DeclaredType type) { TypeMirror enclosing = type.getEnclosingType(); if (!enclosing.getKind().equals(TypeKind.DECLARED) || !enclosing.getClass().getName().contains("eclipse")) { // If the class representing the enclosing type comes from the Eclipse compiler, it will be // something like org.eclipse.jdt.internal.compiler.apt.model.DeclaredTypeImpl. If we're not // in the Eclipse compiler then we don't expect to see "eclipse" in the name of this // implementation class. return enclosing; } DeclaredType declared = MoreTypes.asDeclared(enclosing); List<? extends TypeMirror> arguments = declared.getTypeArguments(); if (!arguments.isEmpty()) { boolean allVariables = arguments.stream().allMatch(t -> t.getKind().equals(TypeKind.TYPEVAR)); if (allVariables) { List<Name> argumentNames = arguments.stream() .map(t -> MoreTypes.asTypeVariable(t).asElement().getSimpleName()) .collect(toList()); TypeElement enclosingElement = MoreTypes.asTypeElement(declared); List<Name> parameterNames = enclosingElement.getTypeParameters().stream() .map(Element::getSimpleName) .collect(toList()); if (argumentNames.equals(parameterNames)) { // We're going to return a NoType. We don't have a Types to hand so we can't call // Types.getNoType(). Instead, just keep going through outer types until we get to // the outside, which will be a NoType. while (enclosing.getKind().equals(TypeKind.DECLARED)) { enclosing = MoreTypes.asDeclared(enclosing).getEnclosingType(); } return enclosing; } } } return declared; }
Example 5
Source File: BuilderSpec.java From auto with Apache License 2.0 | 5 votes |
/** * 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 6
Source File: AutoValueOrOneOfProcessor.java From auto with Apache License 2.0 | 5 votes |
/** * Returns the subset of property methods in the given set of abstract methods, with their actual * return types. A property method has no arguments, is not void, and is not {@code hashCode()} or * {@code toString()}. */ ImmutableMap<ExecutableElement, TypeMirror> propertyMethodsIn( Set<ExecutableElement> abstractMethods, TypeElement autoValueOrOneOfType) { DeclaredType declaredType = MoreTypes.asDeclared(autoValueOrOneOfType.asType()); ImmutableSet.Builder<ExecutableElement> properties = ImmutableSet.builder(); for (ExecutableElement method : abstractMethods) { if (method.getParameters().isEmpty() && (method.getReturnType().getKind() != TypeKind.VOID || propertiesCanBeVoid()) && objectMethodToOverride(method) == ObjectMethod.NONE) { properties.add(method); } } return new EclipseHack(processingEnv).methodReturnTypes(properties.build(), declaredType); }
Example 7
Source File: Optionalish.java From auto with Apache License 2.0 | 5 votes |
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 8
Source File: Optionalish.java From auto with Apache License 2.0 | 5 votes |
/** * 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 9
Source File: AutoOneOfProcessor.java From auto with Apache License 2.0 | 5 votes |
private DeclaredType mirrorForKindType(TypeElement autoOneOfType) { Optional<AnnotationMirror> oneOfAnnotation = getAnnotationMirror(autoOneOfType, AUTO_ONE_OF_NAME); if (!oneOfAnnotation.isPresent()) { // This shouldn't happen unless the compilation environment is buggy, // but it has happened in the past and can crash the compiler. errorReporter() .abortWithError( autoOneOfType, "annotation processor for @AutoOneOf was invoked with a type" + " that does not have that annotation; this is probably a compiler bug"); } AnnotationValue kindValue = AnnotationMirrors.getAnnotationValue(oneOfAnnotation.get(), "value"); Object value = kindValue.getValue(); if (value instanceof TypeMirror) { TypeMirror kindType = (TypeMirror) value; switch (kindType.getKind()) { case DECLARED: return MoreTypes.asDeclared(kindType); case ERROR: throw new MissingTypeException(MoreTypes.asError(kindType)); default: break; } } throw new MissingTypeException(null); }
Example 10
Source File: BuilderSpec.java From SimpleWeibo with Apache License 2.0 | 5 votes |
/** * 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 11
Source File: ProvisionBinding.java From dagger2-sample with Apache License 2.0 | 5 votes |
ProvisionBinding forProvidesMethod(ExecutableElement providesMethod, TypeMirror contributedBy) { checkNotNull(providesMethod); checkArgument(providesMethod.getKind().equals(METHOD)); checkArgument(contributedBy.getKind().equals(TypeKind.DECLARED)); Provides providesAnnotation = providesMethod.getAnnotation(Provides.class); checkArgument(providesAnnotation != null); DeclaredType declaredContainer = MoreTypes.asDeclared(contributedBy); ExecutableType resolvedMethod = MoreTypes.asExecutable(types.asMemberOf(declaredContainer, providesMethod)); Key key = keyFactory.forProvidesMethod(resolvedMethod, providesMethod); ImmutableSet<DependencyRequest> dependencies = dependencyRequestFactory.forRequiredResolvedVariables( declaredContainer, providesMethod.getParameters(), resolvedMethod.getParameterTypes()); Optional<AnnotationMirror> scope = getScopeAnnotation(providesMethod); return new AutoValue_ProvisionBinding( key, providesMethod, dependencies, findBindingPackage(key), false /* no non-default parameter types */, ConfigurationAnnotations.getNullableType(providesMethod), Optional.of(MoreTypes.asTypeElement(declaredContainer)), Kind.PROVISION, providesAnnotation.type(), wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), scope), Optional.<DependencyRequest>absent()); }
Example 12
Source File: ProductionBinding.java From dagger2-sample with Apache License 2.0 | 5 votes |
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 13
Source File: ProducesMethodValidator.java From dagger2-sample with Apache License 2.0 | 5 votes |
private void validateSingleReturnType(ValidationReport.Builder<? extends Element> reportBuilder, TypeMirror type) { if (type.getKind().equals(DECLARED) && MoreTypes.isTypeOf(ListenableFuture.class, type)) { DeclaredType declaredType = MoreTypes.asDeclared(type); if (declaredType.getTypeArguments().isEmpty()) { reportBuilder.addItem(PRODUCES_METHOD_RAW_FUTURE, reportBuilder.getSubject()); } else { validateKeyType(reportBuilder, Iterables.getOnlyElement(declaredType.getTypeArguments())); } } else { validateKeyType(reportBuilder, type); } }
Example 14
Source File: PaperParcelAutoValueExtension.java From paperparcel with Apache License 2.0 | 5 votes |
private MethodSpec constructor(Context context) { Types types = context.processingEnvironment().getTypeUtils(); DeclaredType declaredValueType = MoreTypes.asDeclared(context.autoValueClass().asType()); ImmutableList.Builder<ParameterSpec> parameterBuilder = ImmutableList.builder(); for (Map.Entry<String, ExecutableElement> entry : context.properties().entrySet()) { ExecutableType resolvedExecutableType = MoreTypes.asExecutable(types.asMemberOf(declaredValueType, entry.getValue())); TypeName typeName = TypeName.get(resolvedExecutableType.getReturnType()); ParameterSpec.Builder spec = ParameterSpec.builder(typeName, entry.getKey()); AnnotationMirror nullableAnnotation = Utils.getAnnotationWithSimpleName(entry.getValue(), NULLABLE_ANNOTATION_NAME); if (nullableAnnotation != null) { spec.addAnnotation(AnnotationSpec.get(nullableAnnotation)); } parameterBuilder.add(spec.build()); } ImmutableList<ParameterSpec> parameters = parameterBuilder.build(); CodeBlock parameterList = CodeBlocks.join(FluentIterable.from(parameters) .transform(new Function<ParameterSpec, CodeBlock>() { @Override public CodeBlock apply(ParameterSpec parameterSpec) { return CodeBlock.of("$N", parameterSpec.name); } }), ", "); return MethodSpec.constructorBuilder() .addParameters(parameters) .addStatement("super($L)", parameterList) .build(); }
Example 15
Source File: BuilderMethodClassifier.java From auto with Apache License 2.0 | 5 votes |
/** * Returns an {@code Optional} describing how to convert a value from the setter's parameter type * to the getter's return type using one of the given methods, or {@code Optional.empty()} if the * conversion isn't possible. An error will have been reported in the latter case. */ private Optional<Function<String, String>> getConvertingSetterFunction( ImmutableList<ExecutableElement> copyOfMethods, ExecutableElement valueGetter, ExecutableElement setter, TypeMirror parameterType) { DeclaredType targetType = MoreTypes.asDeclared(getterToPropertyType.get(valueGetter)); for (ExecutableElement copyOfMethod : copyOfMethods) { Optional<Function<String, String>> function = getConvertingSetterFunction(copyOfMethod, targetType, parameterType); if (function.isPresent()) { return function; } } String targetTypeSimpleName = targetType.asElement().getSimpleName().toString(); errorReporter.reportError( setter, "Parameter type %s of setter method should be %s to match getter %s.%s," + " or it should be a type that can be passed to %s.%s to produce %s", parameterType, targetType, autoValueClass, valueGetter.getSimpleName(), targetTypeSimpleName, copyOfMethods.get(0).getSimpleName(), targetType); return Optional.empty(); }
Example 16
Source File: BuilderSpec.java From RetroFacebook with Apache License 2.0 | 5 votes |
/** * 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 @RetroFacebook class. Here's a correct example: * <pre> * {@code @RetroFacebook 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 17
Source File: Util.java From dagger2-sample with Apache License 2.0 | 4 votes |
/** * Returns the key type for a {@link Map} type like Map<K, Provider<V>>} */ public static DeclaredType getKeyTypeOfMap(DeclaredType mapType) { checkState(MoreTypes.isTypeOf(Map.class, mapType), "%s is not a Map.", mapType); List<? extends TypeMirror> mapArgs = mapType.getTypeArguments(); return MoreTypes.asDeclared(mapArgs.get(0)); }
Example 18
Source File: DependencyRequest.java From dagger2-sample with Apache License 2.0 | 4 votes |
static DeclaredType getEnclosingType(Element element) { while (!MoreElements.isType(element)) { element = element.getEnclosingElement(); } return MoreTypes.asDeclared(element.asType()); }
Example 19
Source File: MembersInjectionBinding.java From dagger2-sample with Apache License 2.0 | 4 votes |
/** Returns an unresolved version of this binding. */ MembersInjectionBinding unresolve(MembersInjectionBinding binding) { checkState(binding.hasNonDefaultTypeParameters()); DeclaredType unresolved = MoreTypes.asDeclared(binding.bindingElement().asType()); return forInjectedType(unresolved, Optional.<TypeMirror>absent()); }
Example 20
Source File: TypeEncoder.java From auto with Apache License 2.0 | 4 votes |
private DeclaredType classForName(String className) { TypeElement typeElement = elementUtils.getTypeElement(className); checkState(typeElement != null, "Could not find referenced class %s", className); return MoreTypes.asDeclared(typeElement.asType()); }