javax.lang.model.type.TypeKind Java Examples

The following examples show how to use javax.lang.model.type.TypeKind. 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: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
private ImmutableSet<ExecutableElement> methodsToImplement(List<ExecutableElement> methods) {
  ImmutableSet.Builder<ExecutableElement> toImplement = ImmutableSet.builder();
  boolean errors = false;
  for (ExecutableElement method : methods) {
    if (method.getModifiers().contains(Modifier.ABSTRACT)
        && objectMethodToOverride(method) == ObjectMethodToOverride.NONE) {
      if (method.getParameters().isEmpty() && method.getReturnType().getKind() != TypeKind.VOID) {
        if (isReferenceArrayType(method.getReturnType())) {
          errorReporter.reportError("An @RetroFacebook class cannot define an array-valued property"
              + " unless it is a primitive array", method);
          errors = true;
        }
        toImplement.add(method);
      } else {
        toImplement.add(method);
      }
    }
  }
  if (errors) {
    throw new AbortProcessingException();
  }
  return toImplement.build();
}
 
Example #2
Source File: SpringXMLConfigCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
    DEFAULT_VALUE.append("?"); //NOI18N
    TypeMirror bound = t.getSuperBound();
    if (bound == null) {
        bound = t.getExtendsBound();
        if (bound != null) {
            DEFAULT_VALUE.append(" extends "); //NOI18N
            if (bound.getKind() == TypeKind.WILDCARD)
                bound = ((WildcardType)bound).getSuperBound();
            visit(bound, p);
        } else {
            bound = SourceUtils.getBound(t);
            if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N
                DEFAULT_VALUE.append(" extends "); //NOI18N
                visit(bound, p);
            }
        }
    } else {
        DEFAULT_VALUE.append(" super "); //NOI18N
        visit(bound, p);
    }
    return DEFAULT_VALUE;
}
 
Example #3
Source File: BuilderSpec.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
private void addAbstractMethods(
    TypeMirror typeMirror, List<ExecutableElement> abstractMethods) {
  if (typeMirror.getKind() != TypeKind.DECLARED) {
    return;
  }

  TypeElement typeElement = MoreElements.asType(typeMirror.accept(AS_ELEMENT_VISITOR, null));
  addAbstractMethods(typeElement.getSuperclass(), abstractMethods);
  for (TypeMirror interfaceMirror : typeElement.getInterfaces()) {
    addAbstractMethods(interfaceMirror, abstractMethods);
  }
  for (ExecutableElement method : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
    for (Iterator<ExecutableElement> it = abstractMethods.iterator(); it.hasNext(); ) {
      ExecutableElement maybeOverridden = it.next();
      if (elementUtils.overrides(method, maybeOverridden, typeElement)) {
        it.remove();
      }
    }
    if (method.getModifiers().contains(Modifier.ABSTRACT)) {
      abstractMethods.add(method);
    }
  }
}
 
Example #4
Source File: StateProcessor.java    From android-state with Eclipse Public License 1.0 6 votes vote down vote up
private CompatibilityType getCompatibilityType(Element field) {
    TypeMirror typeMirror = field.asType();
    for (CompatibilityType compatibilityType : CompatibilityType.values()) {
        if (compatibilityType == CompatibilityType.PARCELABLE_ARRAY) {
            TypeMirror arrayType = getArrayType(field);
            if (arrayType != null && isAssignable(arrayType, PARCELABLE_CLASS_NAME)) {
                return CompatibilityType.PARCELABLE_ARRAY;
            }

        } else if (compatibilityType.mGenericClass == null) {
            if (isAssignable(typeMirror, compatibilityType.mClass)) {
                return compatibilityType;
            }

        } else if (typeMirror.getKind() != TypeKind.WILDCARD) {
            if (isAssignable(mTypeUtils.erasure(typeMirror), compatibilityType.mClass)) {
                List<? extends TypeMirror> typeArguments = ((DeclaredType) typeMirror).getTypeArguments();
                if (typeArguments != null && typeArguments.size() >= 1 && isAssignable(typeArguments.get(0), compatibilityType.mGenericClass)) {
                    return compatibilityType;
                }
            }
        }
    }
    return null;
}
 
Example #5
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<TypeElement> getAllClasses(TypeElement of) {
    List<TypeElement> result = new ArrayList<>();
    TypeMirror sup = of.getSuperclass();
    TypeElement te = sup.getKind() == TypeKind.DECLARED ? (TypeElement) ((DeclaredType)sup).asElement() : null;
    
    result.add(of);
    
    if (te != null) {
        result.addAll(getAllClasses(te));
    } else {
        if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
            ERR.log(ErrorManager.INFORMATIONAL, "te=null, t=" + of);
        }
    }
    
    return result;
}
 
Example #6
Source File: GetterFactory.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private static Optional<String> inferName(ExecutableElement element) {
  Encodable.Field annotation = element.getAnnotation(Encodable.Field.class);
  if (annotation != null && !annotation.name().isEmpty()) {
    return Optional.of(annotation.name());
  }

  String methodName = element.getSimpleName().toString();
  ExecutableType method = (ExecutableType) element.asType();

  if (methodName.startsWith("is")
      && methodName.length() != 2
      && method.getReturnType().getKind() == TypeKind.BOOLEAN) {
    return Optional.of(Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3));
  }

  if (methodName.startsWith("get")
      && methodName.length() != 3
      && method.getReturnType().getKind() != TypeKind.VOID) {
    return Optional.of(Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4));
  }
  return Optional.empty();
}
 
Example #7
Source File: Mirrors.java    From immutables with Apache License 2.0 6 votes vote down vote up
static AttributeTypeKind from(TypeMirror type) {
  if (type.getKind() == TypeKind.DECLARED) {
    TypeElement typeElement = toElement(type);
    if (typeElement.getKind() == ElementKind.ENUM) {
      return ENUM;
    }
    if (typeElement.getKind() == ElementKind.ANNOTATION_TYPE) {
      return ANNOTATION;
    }
    Name qualifiedName = typeElement.getQualifiedName();
    if (qualifiedName.contentEquals(Class.class.getName())) {
      return TYPE;
    }
    if (qualifiedName.contentEquals(String.class.getName())) {
      return STRING;
    }
  } else if (type.getKind().isPrimitive()) {
    return PRIMITIVE;
  }
  throw new AssertionError();
}
 
Example #8
Source File: MoreElementsTest.java    From auto with Apache License 2.0 6 votes vote down vote up
private Set<ExecutableElement> visibleMethodsFromObject() {
  Types types = compilation.getTypes();
  TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT);
  TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG);
  Set<ExecutableElement> methods = new HashSet<ExecutableElement>();
  for (ExecutableElement method : ElementFilter.methodsIn(objectElement.getEnclosedElements())) {
    if (method.getModifiers().contains(Modifier.PUBLIC)
        || method.getModifiers().contains(Modifier.PROTECTED)) {
      methods.add(method);
    }
  }
  assertThat(methods)
      .containsAtLeast(
          getMethod(Object.class, "clone"),
          getMethod(Object.class, "finalize"),
          getMethod(Object.class, "wait"),
          getMethod(Object.class, "wait", longMirror),
          getMethod(Object.class, "wait", longMirror, intMirror));
  return methods;
}
 
Example #9
Source File: KratosProcessor.java    From Kratos with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void parseOnKStringUpdate(Element element, Map<TypeElement, BindingClass> targetClassMap,
                                  Set<String> erasedTargetNames) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false);
    TypeMirror mirror = element.asType();
    if (!(mirror.getKind() == TypeKind.EXECUTABLE))
        return;
    String method = element.toString().trim();
    String methodName = method.substring(0, method.indexOf("("));
    Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method);
    if (m.find()) {
        String[] methodTypes = m.group(1).split(",");
        UpdateKStringBinding binding = new UpdateKStringBinding(methodName, methodTypes);
        String kstring = element.getAnnotation(OnKStringChanged.class).value();
        bindingClass.addKStringUpdateBinding(kstring, binding);
    }
    erasedTargetNames.add(enclosingElement.toString());
}
 
Example #10
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeUnary(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    UnaryTree tree = (UnaryTree) parent.getLeaf();
    
    if (tree.getExpression() == error) {
        List<? extends TypeMirror> parentTypes = resolveType(types, info, parent.getParentPath(), tree, offset, null, null);
        
        if (parentTypes != null) {
            //may contain only "void", ignore:
            if (parentTypes.size() != 1) {
                return parentTypes;
            }
            if (parentTypes.get(0).getKind() != TypeKind.VOID) {
                return parentTypes;
            }
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);

        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
    }
    
    return null;
}
 
Example #11
Source File: GetterFactory.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/** Returns all getters of a given type. */
public Set<Getter> allGetters(DeclaredType type) {
  if (types.isSameType(type, elements.getTypeElement("java.lang.Object").asType())) {
    return Collections.emptySet();
  }
  Set<Getter> result = new LinkedHashSet<>();
  TypeMirror superclass = ((TypeElement) types.asElement(type)).getSuperclass();

  if (!superclass.getKind().equals(TypeKind.NONE)) {
    result.addAll(allGetters((DeclaredType) superclass));
  }
  for (ExecutableElement method :
      ElementFilter.methodsIn(types.asElement(type).getEnclosedElements())) {
    create(type, method).ifPresent(result::add);
  }
  return result;
}
 
Example #12
Source File: ArrayCreateQueryMetaFactory.java    From doma with Apache License 2.0 6 votes vote down vote up
@Override
protected void doParameters(ArrayCreateQueryMeta queryMeta) {
  List<? extends VariableElement> parameters = methodElement.getParameters();
  int size = parameters.size();
  if (size != 1) {
    throw new AptException(Message.DOMA4002, methodElement, new Object[] {});
  }
  QueryParameterMeta parameterMeta = createParameterMeta(parameters.get(0));
  if (parameterMeta.getType().getKind() != TypeKind.ARRAY) {
    throw new AptException(Message.DOMA4076, parameterMeta.getElement(), new Object[] {});
  }
  queryMeta.setElementsParameterName(parameterMeta.getName());
  queryMeta.addParameterMeta(parameterMeta);
  if (parameterMeta.isBindable()) {
    queryMeta.addBindableParameterCtType(parameterMeta.getName(), parameterMeta.getCtType());
  }
}
 
Example #13
Source File: TypeAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void locateNestedTypes(Type type, TypeAnnotationPosition p) {
    // The number of "steps" to get from the full type to the
    // left-most outer type.
    ListBuffer<TypePathEntry> depth = new ListBuffer<>();

    Type encl = type.getEnclosingType();
    while (encl != null &&
            encl.getKind() != TypeKind.NONE &&
            encl.getKind() != TypeKind.ERROR) {
        depth = depth.append(TypePathEntry.INNER_TYPE);
        encl = encl.getEnclosingType();
    }
    if (depth.nonEmpty()) {
        p.location = p.location.prependList(depth.toList());
    }
}
 
Example #14
Source File: JCTree.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public TypeKind getPrimitiveTypeKind() {
    switch (typetag) {
        case TypeTags.BOOLEAN:
            return TypeKind.BOOLEAN;
        case TypeTags.BYTE:
            return TypeKind.BYTE;
        case TypeTags.SHORT:
            return TypeKind.SHORT;
        case TypeTags.INT:
            return TypeKind.INT;
        case TypeTags.LONG:
            return TypeKind.LONG;
        case TypeTags.CHAR:
            return TypeKind.CHAR;
        case TypeTags.FLOAT:
            return TypeKind.FLOAT;
        case TypeTags.DOUBLE:
            return TypeKind.DOUBLE;
        case TypeTags.VOID:
            return TypeKind.VOID;
        default:
            throw new AssertionError("unknown primitive type " + this);
    }
}
 
Example #15
Source File: TestTypeKind.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static int testIsPrimitive() {
    int failures = 0;
    // The eight primitive types
    Set<TypeKind> primitives = EnumSet.of(BOOLEAN,  // 1
                                          BYTE,     // 2
                                          CHAR,     // 3
                                          DOUBLE,   // 4
                                          FLOAT,    // 5
                                          INT,      // 6
                                          LONG,     // 7
                                          SHORT);   // 8

    for(TypeKind tk : TypeKind.values()) {
        boolean primitiveness;
        if ((primitiveness=tk.isPrimitive()) != primitives.contains(tk) ) {
            failures++;
            System.err.println("Unexpected isPrimitive value " + primitiveness +
                               "for " + tk);
        }
    }
    return failures;
}
 
Example #16
Source File: Type.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public TypeKind getKind() {
    switch (tag) {
    case BYTE:      return TypeKind.BYTE;
    case CHAR:      return TypeKind.CHAR;
    case SHORT:     return TypeKind.SHORT;
    case INT:       return TypeKind.INT;
    case LONG:      return TypeKind.LONG;
    case FLOAT:     return TypeKind.FLOAT;
    case DOUBLE:    return TypeKind.DOUBLE;
    case BOOLEAN:   return TypeKind.BOOLEAN;
    case VOID:      return TypeKind.VOID;
    case BOT:       return TypeKind.NULL;
    case NONE:      return TypeKind.NONE;
    default:        return TypeKind.OTHER;
    }
}
 
Example #17
Source File: TypeTag.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TypeKind getPrimitiveTypeKind() {
    switch (this) {
    case BOOLEAN:
        return TypeKind.BOOLEAN;
    case BYTE:
        return TypeKind.BYTE;
    case SHORT:
        return TypeKind.SHORT;
    case INT:
        return TypeKind.INT;
    case LONG:
        return TypeKind.LONG;
    case CHAR:
        return TypeKind.CHAR;
    case FLOAT:
        return TypeKind.FLOAT;
    case DOUBLE:
        return TypeKind.DOUBLE;
    case VOID:
        return TypeKind.VOID;
    default:
        throw new AssertionError("unknown primitive type " + this);
    }
}
 
Example #18
Source File: ResourceStringFoldProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String bundleFileFromClass(TreePath classTreePath, String bfn) {
    TypeMirror tm = info.getTrees().getTypeMirror(classTreePath);
    if (tm.getKind() != TypeKind.DECLARED) {
        return null;
    }
    Element clazz = ((DeclaredType)tm).asElement();
    while ((clazz instanceof TypeElement)) {
        clazz = ((TypeElement)clazz).getEnclosingElement();
    }
    if (clazz.getKind() == ElementKind.PACKAGE) {
        PackageElement pack = ((PackageElement)clazz);
        if (pack.isUnnamed()) {
            return null;
        }
        return pack.getQualifiedName().toString().replaceAll("\\.", "/") + "/" + bfn;
    }
    return null;
}
 
Example #19
Source File: AccessorAttributesCollector.java    From immutables with Apache License 2.0 6 votes vote down vote up
static TypeMirror resolveReturnType(
    ProcessingEnvironment processing,
    ExecutableElement method,
    TypeElement typeElement) {
  method = CachingElements.getDelegate(method);
  TypeMirror returnType = method.getReturnType();

  // We do not support parametrized accessor methods,
  // but we do support inheriting parametrized accessors, which
  // we supposedly parametrized with actual type parameters as
  // our target class could not define formal type parameters also.
  if (returnType.getKind() == TypeKind.TYPEVAR) {
    return asInheritedMemberReturnType(processing, typeElement, method);
  } else if (returnType.getKind() == TypeKind.DECLARED
      || returnType.getKind() == TypeKind.ERROR) {
    if (!((DeclaredType) returnType).getTypeArguments().isEmpty()) {
      return asInheritedMemberReturnType(processing, typeElement, method);
    }
  }
  return returnType;
}
 
Example #20
Source File: ButterKnifeProcessor.java    From butterknife with Apache License 2.0 5 votes vote down vote up
private @Nullable TypeElement getSuperClass(TypeElement typeElement) {
  TypeMirror type = typeElement.getSuperclass();
  if (type.getKind() == TypeKind.NONE) {
    return null;
  }
  return (TypeElement) ((DeclaredType) type).asElement();
}
 
Example #21
Source File: AnnotationParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Object getValue(AnnotationValue elementValue) {
    Object value = elementValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror type = (TypeMirror)value;
        if (TypeKind.DECLARED.equals(type.getKind())) {
            return ((TypeElement)(((DeclaredType)value).asElement())).getQualifiedName().toString();
        }
    }
    return getDefaultValue();
}
 
Example #22
Source File: DataBeanModel.java    From PowerfulRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public BeanInfo visitType(TypeElement element, Void aVoid) {
    //check element type
    if (!VALIDATED_CLASS_NAME.equals(getQualifiedName(element)))
        checkElementType(element, VALIDATED_CLASS_NAME);
    TypeMirror typeMirror = null;
    BeanInfo beanInfo = new BeanInfo();
    //get annotated Element info.
    String annotatedElementPackage = getPackageName(element);
    beanInfo.holderName = getSimpleName(element);
    beanInfo.holderPackage = annotatedElementPackage;
    //get annotation info
    try {
        DataBean dataBean = element.getAnnotation(DataBean.class);
        beanInfo.dataBeanName = dataBean.beanName();
        beanInfo.dataBeanPackage = annotatedElementPackage + ".databean";
        beanInfo.layoutId = dataBean.layout();
        //Get type of Data,may throw exception
        dataBean.data();
    } catch (MirroredTypeException mte) {
        typeMirror = mte.getTypeMirror();
    }
    if (typeMirror != null) {
        if (typeMirror.getKind() == TypeKind.DECLARED) {
            DeclaredType declaredType = (DeclaredType) typeMirror;
            TypeElement dataBeanElement = (TypeElement) declaredType.asElement();
            beanInfo.dataPackage = getPackageName(dataBeanElement);
            beanInfo.dataName = getSimpleName(dataBeanElement);
        }
    }
    //log
    logger.log(Diagnostic.Kind.NOTE,
            beanInfo.toString());
    return beanInfo;
}
 
Example #23
Source File: SrcFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean compareTypes(CompilationController ctrl, List<TypeMirror> types, List<? extends VariableElement> params) {
    if (types.size() != params.size()) {
        return false;
    }
    
    Iterator<? extends VariableElement> itParams = params.iterator();
    Iterator<TypeMirror> itTypes = types.iterator();
    while (itParams.hasNext()) {
        VariableElement varEl = itParams.next();
        TypeMirror paramType = varEl.asType();
        TypeMirror type = itTypes.next();
        
        // check types are the same kind
        if (type.getKind() != paramType.getKind()) {
            return false;
        }
        
        // check elements since javadoc ignores generics
        if (type.getKind() == TypeKind.DECLARED) {
            Element paramElm = ((DeclaredType) paramType).asElement();
            Element typeElm = ((DeclaredType) type).asElement();
            if (paramElm != typeElm) {
                return false;
            }
        } else if (!ctrl.getTypes().isSameType(type, paramType)) { // arrays, primitives
            return false;
        }
        
    }
    return true;
}
 
Example #24
Source File: FactoryMethodCompletor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected Iterable<? extends Element> filter(Iterable<? extends Element> methods) {
    List<ExecutableElement> ret = new ArrayList<ExecutableElement>();
    for (Element e : methods) {
        ExecutableElement method = (ExecutableElement) e;
        if (method.getReturnType().getKind() != TypeKind.VOID) {
            ret.add(method);
        }
    }

    return ret;
}
 
Example #25
Source File: Checker.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitReturn(ReturnTree tree, Void ignore) {
    Element e = env.trees.getElement(env.currPath);
    if (e.getKind() != ElementKind.METHOD
            || ((ExecutableElement) e).getReturnType().getKind() == TypeKind.VOID)
        env.messages.error(REFERENCE, tree, "dc.invalid.return");
    foundReturn = true;
    warnIfEmpty(tree, tree.getDescription());
    return super.visitReturn(tree, ignore);
}
 
Example #26
Source File: ExpandEnhancedForLoop.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPattern("for ($type $varName : $expression) { $stmts$; }")
public static ErrorDescription run(HintContext ctx) {
    TreePath tp = ctx.getPath();
    EnhancedForLoopTree efl = (EnhancedForLoopTree) tp.getLeaf();
    long statementStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), efl.getStatement());
    int caret = ctx.getCaretLocation();

    if (caret >= statementStart) {
        return null;
    }
    
    TypeMirror expressionType = ctx.getInfo().getTrees().getTypeMirror(new TreePath(tp, efl.getExpression()));

    if (expressionType == null || expressionType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    ExecutableElement iterator = findIterable(ctx.getInfo());
    Types t = ctx.getInfo().getTypes();
    if (iterator == null || !t.isSubtype(((DeclaredType) expressionType), t.erasure(iterator.getEnclosingElement().asType()))) {
        return null;
    }

    FixImpl fix = new FixImpl(TreePathHandle.create(tp, ctx.getInfo()));
    List<Fix> fixes = Collections.<Fix>singletonList(fix.toEditorFix());
    return ErrorDescriptionFactory.createErrorDescription(ctx.getSeverity(),
                                                          NbBundle.getMessage(ExpandEnhancedForLoop.class, "ERR_ExpandEhancedForLoop"),
                                                          fixes,
                                                          ctx.getInfo().getFileObject(),
                                                          caret,
                                                          caret);
    
}
 
Example #27
Source File: Main.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitAssignment(AssignmentTree node, Void ignored) {
    TreePath path = TreePath.getPath(getCurrentPath(), node.getExpression());
    if (trees.getTypeMirror(path).getKind() == TypeKind.ERROR)
        throw new AssertionError(path.getLeaf());
    return null;
}
 
Example #28
Source File: BuilderSpec.java    From RetroFacebook 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 @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 #29
Source File: TypeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIsCastable() throws Exception {
        JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])), ClassPathSupport.createClassPath(new URL[0]), ClassPathSupport.createClassPath(new URL[0])));
        
        js.runUserActionTask(new Task<CompilationController>() {
            public void run(CompilationController info)  {
                TypeElement jlStringElement = info.getElements().getTypeElement("java.lang.String");
                TypeMirror jlString = info.getTypes().getDeclaredType(jlStringElement);
                TypeElement jlIntegerElement = info.getElements().getTypeElement("java.lang.Integer");
                TypeMirror jlInteger = info.getTypes().getDeclaredType(jlIntegerElement);
                TypeElement juListElement = info.getElements().getTypeElement("java.util.List");
                TypeMirror juListString = info.getTypes().getDeclaredType(juListElement, jlString);
                TypeMirror juListInteger = info.getTypes().getDeclaredType(juListElement, jlInteger);
                TypeElement jlObjectElement = info.getElements().getTypeElement("java.lang.Object");
                TypeMirror jlObject = info.getTypes().getDeclaredType(jlObjectElement);
                TypeMirror primitiveChar = info.getTypes().getPrimitiveType(TypeKind.CHAR);
                
                TypeUtilities u = info.getTypeUtilities();
                
                assertTrue(u.isCastable(jlObject, jlString));
                assertTrue(u.isCastable(jlObject, jlInteger));
                assertTrue(u.isCastable(jlObject, juListString));
                
                assertFalse(u.isCastable(jlString, jlInteger));
                assertFalse(u.isCastable(jlInteger, jlString));
                assertFalse(u.isCastable(juListString, juListInteger));
                assertFalse(u.isCastable(juListInteger, juListString));
                
                //verify that the order of arguments is understood correctly:
                //(requires 1.5):
                //XXX: after d3ead6731a91, the types are castable in both directions
//                assertFalse(u.isCastable(jlObject, primitiveChar));
//                assertTrue(u.isCastable(primitiveChar, jlObject));
            }
        }, true);
        
    }
 
Example #30
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;
}