Java Code Examples for javax.lang.model.element.ElementKind#ENUM

The following examples show how to use javax.lang.model.element.ElementKind#ENUM . 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: 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 2
Source File: EnumValueCompleter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Completer createCompleter(CompletionContext ctx) {
    FxProperty p = ctx.getEnclosingProperty();
    if (p == null || p.getType() == null) {
        return null;
    }
    TypeMirror m = p.getType().resolve(ctx.getCompilationInfo());
    if (m.getKind() == TypeKind.BOOLEAN) {
        return new EnumValueCompleter(ctx);
    }
    if (m.getKind() != TypeKind.DECLARED) {
        return null;
    }
    DeclaredType t = (DeclaredType)m;
    TypeElement tel = (TypeElement)t.asElement();
    if (tel.getQualifiedName().contentEquals("java.lang.Boolean")) {
        return new EnumValueCompleter(ctx);
    }
    if (tel.getKind() == ElementKind.ENUM) {
        return new EnumValueCompleter(ctx, tel);
    } else {
        return null;
    }
}
 
Example 3
Source File: DocumentUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
static ElementKind decodeKind (char kind) {
    switch (kind) {
        case EK_CLASS:
        case EK_LOCAL_CLASS:
            return ElementKind.CLASS;
        case EK_INTERFACE:
        case EK_LOCAL_INTERFACE:
            return ElementKind.INTERFACE;
        case EK_ENUM:
        case EK_LOCAL_ENUM:
            return ElementKind.ENUM;
        case EK_ANNOTATION:
        case EK_LOCAL_ANNOTATION:
            return ElementKind.ANNOTATION_TYPE;
        case EK_MODULE:
            return ElementKind.MODULE;
        case EK_RECORD:
        case EK_LOCAL_RECORD:
            return ElementKind.valueOf("RECORD");
        default:
            throw new IllegalArgumentException ();
    }
}
 
Example 4
Source File: JavaEnvironment.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private List<String> getClassComponents(javax.lang.model.type.TypeVariable typeVariable) {
  Element enclosingElement = typeVariable.asElement().getEnclosingElement();
  if (enclosingElement.getKind() == ElementKind.CLASS
      || enclosingElement.getKind() == ElementKind.INTERFACE
      || enclosingElement.getKind() == ElementKind.ENUM) {
    return ImmutableList.<String>builder()
        .addAll(getClassComponents(enclosingElement))
        .add(
            // If it is a class-level type variable, use the simple name (with prefix "C_") as the
            // current name component.
            "C_" + typeVariable)
        .build();
  } else {
    return ImmutableList.<String>builder()
        .addAll(getClassComponents(enclosingElement.getEnclosingElement()))
        .add(
            "M_"
                + enclosingElement.getSimpleName()
                + "_"
                + typeVariable.asElement().getSimpleName())
        .build();
  }
}
 
Example 5
Source File: ElementGrip.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ElementGrip(TreePathHandle delegateElementHandle, Element elm, CompilationInfo info) {
        this.delegateElementHandle = delegateElementHandle;
        this.handle = elm == null ? null : ElementHandle.create(elm);
        if (elm != null) {
            if (elm.getKind() == ElementKind.CLASS && elm.getSimpleName().length() == 0) {
                this.toString = ((TypeElement) elm).asType().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
            } else if(elm.getKind() == ElementKind.ENUM 
                    && elm.getSimpleName().length() == 0
                    && elm.getEnclosingElement() != null) {
                final Element enclosingElement = elm.getEnclosingElement();
                this.toString = enclosingElement.getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(enclosingElement.getKind(), enclosingElement.getModifiers());
            } else {
                // workaround for issue 171692
                this.toString = elm.getKind() != ElementKind.CONSTRUCTOR
                        ? elm.getSimpleName().toString()
                        : elm.getEnclosingElement().getSimpleName().toString();
                this.icon = ElementIcons.getElementIcon(elm.getKind(), elm.getModifiers());
//            this.toString = ElementHeaders.getHeader(treePath, info, ElementHeaders.NAME);
            }
        }
        this.fileObject = info.getFileObject();
    }
 
Example 6
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isEnum(CompilationController controller, 
        TypeElement classEl) 
{
    if (classEl != null) {
        return classEl.getKind() == ElementKind.ENUM;
    }
    return false;
}
 
Example 7
Source File: Proto.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if this element is a regular POJO (not an interface or abstract class) simple
 * class with getters and setters
 */
@Value.Derived
@Value.Auxiliary
public boolean isJavaBean() {
  return element().getKind().isClass()
      &&
      element().getKind() != ElementKind.ENUM
      &&
      !element().getModifiers().contains(Modifier.PRIVATE)
      &&
      !element().getModifiers().contains(Modifier.ABSTRACT)
      &&
      // restrict to Criteria and Repository annotations for now
      (CriteriaMirror.find(element()).isPresent() || CriteriaRepositoryMirror.find(element()).isPresent());
}
 
Example 8
Source File: CreateElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ElementKind getClassType(Set<ElementKind> types) {
    if (types.contains(ElementKind.CLASS))
        return ElementKind.CLASS;
    if (types.contains(ElementKind.ANNOTATION_TYPE))
        return ElementKind.ANNOTATION_TYPE;
    if (types.contains(ElementKind.INTERFACE))
        return ElementKind.INTERFACE;
    if (types.contains(ElementKind.ENUM))
        return ElementKind.ENUM;

    return null;
}
 
Example 9
Source File: Proto.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Some validations, not exhaustive.
 */
@Value.Check
protected void validate() {
  if (include().isPresent() && !isTopLevel()) {
    report()
        .annotationNamed(IncludeMirror.simpleName())
        .error("@%s could not be used on nested types.", IncludeMirror.simpleName());
  }
  if (builderInclude().isPresent() && !isTopLevel()) {
    report()
        .annotationNamed(FIncludeMirror.simpleName())
        .error("@%s could not be used on nested types.", FIncludeMirror.simpleName());
  }
  if (isEnclosing() && !isTopLevel()) {
    report()
        .annotationNamed(EnclosingMirror.simpleName())
        .error("@%s should only be used on a top-level types.", EnclosingMirror.simpleName());
  }
  if (isImmutable() && element().getKind() == ElementKind.ENUM) {
    report()
        .annotationNamed(ImmutableMirror.simpleName())
        .error("@%s is not supported on enums", ImmutableMirror.simpleName());
  }
  if (isModifiable() && (isEnclosed() || isEnclosing())) {
    report()
        .annotationNamed(ModifiableMirror.simpleName())
        .error("@%s could not be used with or within @%s",
            ModifiableMirror.simpleName(),
            EnclosingMirror.simpleName());
  }
}
 
Example 10
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
private boolean isValidInjectedElementKind(VariableElement injectedTypeElement) {
  Element typeElement = typeUtils.asElement(injectedTypeElement.asType());
  // typeElement can be null for primitives.
  // https://github.com/stephanenicolas/toothpick/issues/261
  if (typeElement == null //
      || typeElement.getKind() != ElementKind.CLASS //
          && typeElement.getKind() != ElementKind.INTERFACE //
          && typeElement.getKind() != ElementKind.ENUM) {

    // find the class containing the element
    // the element can be a field or a parameter
    Element enclosingElement = injectedTypeElement.getEnclosingElement();
    final String typeName;
    if (typeElement != null) {
      typeName = typeElement.toString();
    } else {
      typeName = injectedTypeElement.asType().toString();
    }
    if (enclosingElement instanceof TypeElement) {
      error(
          injectedTypeElement,
          "Field %s#%s is of type %s which is not supported by Toothpick.",
          ((TypeElement) enclosingElement).getQualifiedName(),
          injectedTypeElement.getSimpleName(),
          typeName);
    } else {
      Element methodOrConstructorElement = enclosingElement;
      enclosingElement = enclosingElement.getEnclosingElement();
      error(
          injectedTypeElement,
          "Parameter %s in method/constructor %s#%s is of type %s which is not supported by Toothpick.",
          injectedTypeElement.getSimpleName(), //
          ((TypeElement) enclosingElement).getQualifiedName(), //
          methodOrConstructorElement.getSimpleName(), //
          typeName);
    }
    return false;
  }
  return true;
}
 
Example 11
Source File: JndiResourcesObjectProviders.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<T> createObjects(TypeElement type) {
    final List<T> result = new ArrayList<T>();
    if (type.getKind() == ElementKind.CLASS || type.getKind() == ElementKind.INTERFACE || type.getKind() == ElementKind.ENUM) {
        if (helper.hasAnyAnnotation(type.getAnnotationMirrors(), Collections.singleton(annotationType))) {
            result.add(createObject(helper, type));
        }
    }
    return result;
}
 
Example 12
Source File: Symbol.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & ANNOTATION) != 0)
        return ElementKind.ANNOTATION_TYPE;
    else if ((flags & INTERFACE) != 0)
        return ElementKind.INTERFACE;
    else if ((flags & ENUM) != 0)
        return ElementKind.ENUM;
    else
        return ElementKind.CLASS;
}
 
Example 13
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isEnum(CompilationController controller, String type) {
    TypeElement classEl = controller.getElements().getTypeElement(getCanonicalClassName(type));
    if (classEl != null) {
        return classEl.getKind() == ElementKind.ENUM;
    }
    return false;
}
 
Example 14
Source File: ProcessUtils.java    From RxAndroidOrm with Apache License 2.0 4 votes vote down vote up
private static boolean isNotVariable(VariableElement variableElement) {
    return variableElement.getKind() == ElementKind.ENUM ||
            variableElement.getKind() == ElementKind.INTERFACE ||
            variableElement.getKind() == ElementKind.CLASS;
}
 
Example 15
Source File: JavaEnvironment.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private boolean isEnumSyntheticMethod(ExecutableElement methodElement) {
  // Enum synthetic methods are not marked as such because per JLS 13.1 these methods are
  // implicitly declared but are not marked as synthetic.
  return getEnclosingType(methodElement).getKind() == ElementKind.ENUM
      && (isValuesMethod(methodElement) || isValueOfMethod(methodElement));
}
 
Example 16
Source File: ValueAttribute.java    From immutables with Apache License 2.0 4 votes vote down vote up
public boolean hasEnumFirstTypeParameter() {
  return typeKind().isEnumKeyed()
      && containedTypeElement.getKind() == ElementKind.ENUM;
}
 
Example 17
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static ErrorDescription enumHint(HintContext ctx, String baseName, String targetTypeName, String key, Fix... fixes) {
    Element type = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$param"));

    if (type == null || type.getKind() != ElementKind.ENUM) {
        return null;
    }

    Element coll = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$coll"));

    if (coll == null || coll.getKind() != ElementKind.CLASS) {
        return null;
    }
    
    TypeElement base = ctx.getInfo().getElements().getTypeElement(baseName);
    
    if (base == null) {
        return null;
    }

    Types t = ctx.getInfo().getTypes();

    if (!t.isSubtype(t.erasure(coll.asType()), t.erasure(base.asType()))) {
        return null;
    }

    if (targetTypeName != null) {
        TypeElement target = ctx.getInfo().getElements().getTypeElement(targetTypeName);

        if (target == null) {
            return null;
        }

        if (t.isSubtype(t.erasure(coll.asType()), t.erasure(target.asType()))) {
            return null;
        }
        
        List<? extends TypeMirror> assignedTo = CreateElementUtilities.resolveType(EnumSet.noneOf(ElementKind.class), ctx.getInfo(), ctx.getPath().getParentPath(), ctx.getPath().getLeaf(), (int) ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), ctx.getPath().getLeaf()), new TypeMirror[1], new int[1]);
        
        if (assignedTo != null && assignedTo.size() == 1) {
            if (t.isSubtype(t.erasure(assignedTo.get(0)), t.erasure(coll.asType())))
                return null;
        }
    }

    String displayName = NbBundle.getMessage(Tiny.class, key);

    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName, fixes);
}
 
Example 18
Source File: TypeUtil.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public static boolean isEnum(TypeMirror t) {
  return getDeclaredTypeKind(t) == ElementKind.ENUM;
}
 
Example 19
Source File: CreateSubclass.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
    TreePath tp = context.getPath();
    ClassTree cls = (ClassTree) tp.getLeaf();
    CompilationInfo info = context.getInfo();
    SourcePositions sourcePositions = info.getTrees().getSourcePositions();
    long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
    if (startPos > Integer.MAX_VALUE) {
        return null;
    }
    int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
    if (bodySpan == null || bodySpan[0] <= startPos) {
        return null;
    }
    int caret = context.getCaretLocation();
    if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
        return null;
    }

    // #222487
    // If there is a compile-time error on the class, then don't offer to
    // create a subclass.
    List<Diagnostic> errors = info.getDiagnostics();
    if (!errors.isEmpty()) {
        for (Diagnostic d : errors) {
            if (d.getKind() != Diagnostic.Kind.ERROR) {
                continue;
            }
            // Check that the error's start position is within the class header
            // Note: d.getEndPosition() is not used because, for example,
            // a "compiler.err.does.not.override.abstract" error ends at
            // the end of the class tree.
            if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
                return null;
            }
        }
    }

    TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
    
    if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;

    Element outer = typeElement.getEnclosingElement();
    // do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
    if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
        if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
            return null;
        }
        if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
            return null;
        }
    }

    
    ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
    FileObject root = cp.findOwnerRoot(info.getFileObject());
    if (root == null) { //File not part of any project
        return null;
    }

    PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
    CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
    return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
            ? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}
 
Example 20
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * For member select, find the most generic type which declares that member.
 * When traversing up the inheritance tree, the return type must be checked, as it may
 * become too general to fit the parent expression's requirements.
 */
@Override
public List<? extends TypeMirror> visitMemberSelect(MemberSelectTree tree, Object v) {
    if (casted != null) {
        // if the casted type is a primitive, the cast is NOT redundant as member select is applied to
        // the originally primitive value.
        TypeMirror castedType = info.getTrees().getTypeMirror(casted);
        if (castedType != null && castedType.getKind().isPrimitive()) {
            notRedundant = true;
        }
    }
    // must compute expected type of the method:
    TreePath[] p = new TreePath[1];
    ExpressionTree[] e = new ExpressionTree[1];
    Tree[] l = new Tree[1];
    List<TypeMirror> tt = new ArrayList<TypeMirror>();
    Element el = info.getTrees().getElement(getCurrentPath());
    
    if (el == null) {
        return null;
    }
    
    if (el.getKind() == ElementKind.METHOD) {
        // special hack: if the casted value is a lambda, we NEED to assign it a type prior to method invocation:
        TreePath exp = getExpressionWithoutCasts();
        if (exp != null && exp.getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
            return null;
        }
        TreePath methodInvocation = getCurrentPath().getParentPath();
        TreePath invocationParent = methodInvocation.getParentPath();
        ExpectedTypeResolver subResolver = new ExpectedTypeResolver(methodInvocation, info);
        subResolver.theExpression = methodInvocation;
        subResolver.typeCastDepth++;
        List<? extends TypeMirror> parentTypes = subResolver.scan(invocationParent, v);
        TypeMirror castable = null;
        if (parentTypes == null) {
            castable = subResolver.getCastableTo();
        }
        if (parentTypes != null || castable != null) {
            TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            if (!(exprType instanceof DeclaredType)) {
                return null;
            }
            ExecutableElement elem = (ExecutableElement)el;
            TreePath method = getCurrentPath();
            while (method != null && method.getLeaf().getKind() != Tree.Kind.METHOD) {
                method = method.getParentPath();
            }
            if (method == null) {
                method = getCurrentPath();
            }
            List<TypeMirror> cans = findBaseTypes(info, elem, (DeclaredType)exprType,
                    parentTypes, 
                    castable, 
                    info.getTrees().getScope(method));
            if (!cans.isEmpty()) {
                return cans;
            }
        } else {
            TypeMirror exprm = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), tree.getExpression()));
            return Collections.singletonList(exprm);
        }
    } else if (el.getKind() == ElementKind.FIELD) {
        // access to a field
        Element parent = el.getEnclosingElement();
        if (parent.getKind() == ElementKind.CLASS || parent.getKind() == ElementKind.INTERFACE || parent.getKind() == ElementKind.ENUM) {
            return Collections.singletonList(parent.asType());
        }
    }
    return null;
}