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

The following examples show how to use javax.lang.model.element.ElementKind#ENUM_CONSTANT . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & PARAMETER) != 0) {
        if (isExceptionParameter())
            return ElementKind.EXCEPTION_PARAMETER;
        else
            return ElementKind.PARAMETER;
    } else if ((flags & ENUM) != 0) {
        return ElementKind.ENUM_CONSTANT;
    } else if (owner.kind == TYP || owner.kind == ERR) {
        return ElementKind.FIELD;
    } else if (isResourceVariable()) {
        return ElementKind.RESOURCE_VARIABLE;
    } else {
        return ElementKind.LOCAL_VARIABLE;
    }
}
 
Example 2
Source Project: netbeans   File: TranslateIdentifier.java    License: Apache License 2.0 6 votes vote down vote up
public Void visitIdentifier(IdentifierTree node, Void p) {
    TreePath path = getCurrentPath();
    Element element = info.getTrees().getElement(path);
    
    if (element != null && element.asType().getKind() != TypeKind.ERROR) {
        // solve the imports only when declared type!!!
        if (element.getKind().isClass() || element.getKind().isInterface()
                || (element.getKind().isField() && ((Symbol) element).isStatic())) {
            Tree parent = path.getParentPath() != null ? path.getParentPath().getLeaf() : null;
            
            if (   (parent != null && parent.getKind() == Kind.CASE && ((CaseTree) parent).getExpression() == node && element.getKind() == ElementKind.ENUM_CONSTANT)
                || (path.getCompilationUnit() != null && ((Symbol) element).enclClass() != null && path.getCompilationUnit().getSourceFile() == ((Symbol) element).enclClass().sourcefile)) {
                translateMap.put(node, make.Identifier(element.getSimpleName()));
            } else {
                translateMap.put(node, make.QualIdent(element));
            }
        } 
    }
    
    return null;
}
 
Example 3
@DefinedBy(Api.LANGUAGE_MODEL)
public ElementKind getKind() {
    long flags = flags();
    if ((flags & PARAMETER) != 0) {
        if (isExceptionParameter())
            return ElementKind.EXCEPTION_PARAMETER;
        else
            return ElementKind.PARAMETER;
    } else if ((flags & ENUM) != 0) {
        return ElementKind.ENUM_CONSTANT;
    } else if (owner.kind == TYP || owner.kind == ERR) {
        return ElementKind.FIELD;
    } else if (isResourceVariable()) {
        return ElementKind.RESOURCE_VARIABLE;
    } else {
        return ElementKind.LOCAL_VARIABLE;
    }
}
 
Example 4
Source Project: netbeans   File: NPECheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public State visitIdentifier(IdentifierTree node, Void p) {
    super.visitIdentifier(node, p);
    
    Element e = info.getTrees().getElement(getCurrentPath());

    if (e == null || !isVariableElement(e)) {
        return State.POSSIBLE_NULL;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        // enum constants are never null
        return State.NOT_NULL;
    }

    State s = variable2State.get((VariableElement) e);
    if (s != null) {
        return s;
    }
    
    return getStateFromAnnotations(info, e);
}
 
Example 5
protected boolean generateClassBody(TreePath p) throws Exception {
    Element e = copy.getTrees().getElement(p);
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    if (isUsableElement) {
        return true;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        VariableTree var = (VariableTree) p.getLeaf();
        if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) var.getInitializer();
            if (nct.getClassBody() != null) {
                return true;
            }
        }
    }
    return !generateClassBody2(copy, p);
}
 
Example 6
private Pair<String, Object> calculateValue(Object value) {
    String format = "L";
    if (value instanceof CharSequence) {
        format = "S";
    } else if (value instanceof Class) {
        format = "T";
    } else if (value instanceof VariableElement) {
        final VariableElement variableElement = (VariableElement) value;
        final ElementKind kind = variableElement.getKind();
        if (kind == ElementKind.ENUM_CONSTANT) {
            final Element classElement = ((VariableElement) value).getEnclosingElement();
            value = classElement + SourceTextUtils.PACKAGE_SEPARATOR + variableElement;
            format = "L";
        }
    }
    return Pair.of("$" + format, value);
}
 
Example 7
@Override
@SuppressWarnings("ConstantConditions")
protected void doVisitField(@Nullable JavaFieldElement oldField, @Nullable JavaFieldElement newField) {
    if (!shouldCheck(oldField, newField)) {
        return;
    }

    Predicate<VariableElement> isNotEnumConstant = v -> v.getKind() != ElementKind.ENUM_CONSTANT;

    List<? extends VariableElement> fields = ElementFilter.fieldsIn(oldField.getDeclaringElement().
            getEnclosingElement().getEnclosedElements());
    fields.removeIf(isNotEnumConstant);

    int oldIdx = fields.indexOf(oldField.getDeclaringElement());

    fields = ElementFilter.fieldsIn(newField.getDeclaringElement().getEnclosingElement().getEnclosedElements());
    fields.removeIf(isNotEnumConstant);

    int newIdx = fields.indexOf(newField.getDeclaringElement());

    if (newIdx != oldIdx) {
        pushActive(oldField, newField, oldIdx, newIdx);
    }
}
 
Example 8
Source Project: immutables   File: OkJsons.java    License: Apache License 2.0 6 votes vote down vote up
EnumDefinition(TypeElement element, String qualified, String simple) {
  this.qualified = qualified;
  this.simple = simple;

  for (Element e : element.getEnclosedElements()) {
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
      Optional<OkNamedMirror> nameAnnotation = OkNamedMirror.find(e);
      String name = e.getSimpleName().toString();
      String jsonName = name;

      if (nameAnnotation.isPresent()) {
        String s = nameAnnotation.get().name();
        // just ignore annotation with empty name
        if (!s.isEmpty()) {
          jsonName = s;
        }
      }
      byFirstLetter.put(
          jsonName.charAt(0),
          new EnumConstant(name, jsonName));
    }
  }
}
 
Example 9
Source Project: netbeans   File: Type.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String[] getEnumConstants() {
    if(enumConstants == null){
        Element elt = po != null ? getTypeElement(po) : element;
        if(elt != null){
            ArrayList<String> constants = new ArrayList<String>();
            for( Element el:elt.getEnclosedElements() ){
                if(el.getKind() == ElementKind.ENUM_CONSTANT){
                    constants.add(el.getSimpleName().toString());
                }
            }
            enumConstants = constants.toArray(new String[]{});
        } else if (type != null) {
            if (!type.isEnum()) {
                enumConstants = new String[]{};
            } else {
                Object[] enumC = type.getEnumConstants();
                enumConstants = new String[enumC.length];

                for (int index = enumC.length; --index >= 0;) {
                    enumConstants[index] = ((Enum<?>) enumC[index]).name();
                }

            }
        } else {
            enumConstants = new String[]{};
        }
    }
    return enumConstants;
}
 
Example 10
Source Project: immutables   File: SwitcherModel.java    License: Apache License 2.0 5 votes vote down vote up
private ImmutableList<SwitchOption> constructOptions() {
  ImmutableList.Builder<SwitchOption> builder = ImmutableList.builder();

  for (Element v : containedTypeElement.getEnclosedElements()) {
    if (v.getKind() == ElementKind.ENUM_CONSTANT) {
      String name = v.getSimpleName().toString();
      builder.add(new SwitchOption(name, defaultName.equals(name)));
    }
  }

  return builder.build();
}
 
Example 11
Source Project: netbeans   File: Tiny.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean tryResolveIdentifier(CompilationInfo info, TreePath place, 
        TypeMirror expectedType, Set<Element> resolved, String ident) {
    SourcePositions[] positions = new SourcePositions[1];
    ExpressionTree et = info.getTreeUtilities().parseExpression(ident, positions);
    TypeMirror unqType = info.getTreeUtilities().attributeTree(et, info.getTrees().getScope(place));
    Element e = info.getTrees().getElement(new TreePath(place, et));
    if (!Utilities.isValidType(unqType) || e == null || 
            (e.getKind() != ElementKind.FIELD && e.getKind() != ElementKind.ENUM_CONSTANT)) {
        return false;
    }
    if (!resolved.add(e)) {
        return false;
    }
    return info.getTypes().isAssignable(unqType, expectedType);
}
 
Example 12
@Override
protected boolean executeRound(Element el, int round) throws Exception {
    if (el.getKind() != ElementKind.ENUM) {
        return false;
    }
    ClassTree ct = (ClassTree)path.getLeaf();
    for (ListIterator<? extends Tree> it = ct.getMembers().listIterator(ct.getMembers().size()); it.hasPrevious(); ) {
        Tree t = it.previous();
        
        if (t.getKind() != Tree.Kind.VARIABLE) {
            continue;
        }
        TreePath p = new TreePath(path, t);
        Element e = copy.getTrees().getElement(p);
        if (e == null || e.getKind() != ElementKind.ENUM_CONSTANT) {
            continue;
        }

        switch (round) {
            case 0:
                if (!generateClassBody(p)) {
                    return false;
                }
                break;
            case 1:
                if (!generateImplementation(el, p)) {
                    return false;
                }
                break;
            default:
                throw new IllegalStateException();
        }
    }
    return true;
}
 
Example 13
Source Project: buck   File: AccessFlags.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the field access flags (see JVMS8 4.5) for the given variable element, augmented by the
 * special ASM pseudo-access flag for @Deprecated fields.
 */
public int getAccessFlags(VariableElement variableElement) {
  int result = getCommonAccessFlags(variableElement);

  if (variableElement.getKind() == ElementKind.ENUM_CONSTANT) {
    result = result | Opcodes.ACC_ENUM;
  }

  return result;
}
 
Example 14
Source Project: netbeans   File: JavaI18nSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the target position within the source class element.
 * In the current implementation, the target position is just below
 * the last static field of the class; if there is no static field
 * in the class, the target position is the top of the class.
 * 
 * @param  classMembers  list of all members of the class
 * @param  fields  list of the fields in the class
 * @return  target position ({@code 0}-based) of the field,
 *          or {@code -1} if the field should be added to the end
 *          of the class
 */
private int findTargetPosition(
        List<? extends javax.lang.model.element.Element> classMembers,
        List<? extends VariableElement> fields) {
    if (fields.isEmpty()) {
        return 0;
    }

    int target = 0;
    boolean skippingStaticFields = false;
    Iterator<? extends javax.lang.model.element.Element> membersIt
            = classMembers.iterator();
    for (int index = 0; membersIt.hasNext(); index++) {
        javax.lang.model.element.Element member = membersIt.next();
        ElementKind kind = member.getKind();
        if (kind.isField()
                && (kind != ElementKind.ENUM_CONSTANT)
                && member.getModifiers().contains(Modifier.STATIC)) {
            /* it is a static field - skip it! */
            skippingStaticFields = true;
        } else if (skippingStaticFields) {
            /* we were skipping all static fields - until now */
            skippingStaticFields = false;
            target = index;
        }
    }

    return !skippingStaticFields ? target : -1;
}
 
Example 15
Source Project: netbeans   File: EnumValueCompleter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<CompletionItem> complete() {
    List<String> valueStrings = new ArrayList<String>();
    if (isBooleanType()) {
        valueStrings.add(Boolean.FALSE.toString());
        valueStrings.add(Boolean.TRUE.toString());
    } else {
        for (Element e : enumType.getEnclosedElements()) {
            if (e.getKind() == ElementKind.ENUM_CONSTANT) {
                valueStrings.add(e.getSimpleName().toString());
            }
        }
    }
    
    String prefix = ctx.getPrefix();
    if (!prefix.isEmpty()) {
        if (prefix.charAt(0) == '"' || prefix.charAt(0) == '\'') {
            prefix = prefix.substring(1);
        }
        for (Iterator<String> it = valueStrings.iterator(); it.hasNext(); ) {
            String s = it.next();
            if (!CompletionUtils.startsWith(s, prefix)) {
                it.remove();
            }
        }
    }
    
    List<CompletionItem> items = new ArrayList<CompletionItem>();
    for (String v : valueStrings) {
        ValueItem vi = new ValueItem(ctx, v, ICON_ENUM_VALUE);
        items.add(vi);
    }
    
    return items;
}
 
Example 16
@Override
public ElementKind getKind() {
	if (_binding instanceof FieldBinding) {
		if (((FieldBinding)_binding).declaringClass.isEnum()) {
			return ElementKind.ENUM_CONSTANT;
		}
		else {
			return ElementKind.FIELD;
		}
	}
	else {
		return ElementKind.PARAMETER;
	}
}
 
Example 17
Source Project: j2objc   File: ElementUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isVariable(Element element) {
  ElementKind kind = element.getKind();
  return kind == ElementKind.FIELD || kind == ElementKind.LOCAL_VARIABLE
      || kind == ElementKind.PARAMETER || kind == ElementKind.EXCEPTION_PARAMETER
      || kind == ElementKind.RESOURCE_VARIABLE || kind == ElementKind.ENUM_CONSTANT;
}
 
Example 18
private boolean shouldCheck(JavaFieldElement oldField, JavaFieldElement newField) {
    return isEnumClass && isBothAccessible(oldField, newField)
            && oldField.getDeclaringElement().getKind() == ElementKind.ENUM_CONSTANT
            && newField.getDeclaringElement().getKind() == ElementKind.ENUM_CONSTANT;
}
 
Example 19
public List<Fix> run(final CompilationInfo info, String diagnosticKey, final int offset, TreePath treePath, Data<Object> data) {
    TreePath path = deepTreePath(info, offset);
    if (path == null) {
        return null;
    }

    Map<Tree, Object> holder = data == null ? null : (Map)data.getData();
    Object saved = null;
    if (holder != null) {
        saved = holder.get(path.getLeaf());
    }
    if (Boolean.TRUE == saved) {
        return null;
    }
    Element e = info.getTrees().getElement(path);
    final Tree leaf = path.getLeaf();
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    boolean containsDefaultMethod = saved == Boolean.FALSE;

    boolean completingAnonymous = e != null && e.getKind() == ElementKind.CONSTRUCTOR && 
            leaf.getKind() == Tree.Kind.NEW_CLASS;
    TypeElement tel = findTypeElement(info, path);
    
    if (!Utilities.isValidElement(tel)) {
        return null;
    }
    List<Fix> fixes = new ArrayList<>();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(leaf.getKind()) || leaf.getKind().toString().equals(RECORD)) {
        CompilationUnitTree cut = info.getCompilationUnit();
        // do not offer for class declarations without body
        long start = info.getTrees().getSourcePositions().getStartPosition(cut, leaf);
        long end = info.getTrees().getSourcePositions().getEndPosition(cut, leaf);
        for (Diagnostic d : info.getDiagnostics()) {
            long position = d.getPosition();
            if (d.getCode().equals(PREMATURE_EOF_CODE) && position > start && position < end) {
                return null;
            }
        }
    }
    
    if (completingAnonymous) {
        //if the parent of path.getLeaf is an error, the situation probably is like:
        //new Runnable {}
        //(missing '()' for constructor)
        //do not propose the hint in this case:
        final boolean[] parentError = new boolean[] {false};
        new ErrorAwareTreePathScanner() {
            @Override
            public Object visitNewClass(NewClassTree nct, Object o) {
                if (leaf == nct) {
                    parentError[0] = getCurrentPath().getParentPath().getLeaf().getKind() == Kind.ERRONEOUS;
                }
                return super.visitNewClass(nct, o);
            }
        }.scan(path.getParentPath(), null);
        if (parentError[0]) {
            // ignore
            return null;
        }
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    boolean someAbstract = false;
    X: if (isUsableElement) {
        for (ExecutableElement ee : ElementFilter.methodsIn(e.getEnclosedElements())) {
            if (ee.getModifiers().contains(Modifier.ABSTRACT)) {
                // make class abstract. In case of enums, suggest to implement the
                // abstract methods on all enum values.
                if (e.getKind() == ElementKind.ENUM) {
                    // cannot make enum abstract, but can generate abstract methods skeleton
                    // to all enum members
                    fixes.add(new ImplementOnEnumValues2(info,  tel, containsDefaultMethod));
                    // avoid other possible fixes:
                    break X;
                } else if (e.getKind().isClass()) {
                    someAbstract = true;
                    break;
                }
            }
        }
        // offer to fix all abstract methods
        if (!someAbstract) {
            fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
        }
        if (e.getKind() == ElementKind.CLASS && e.getSimpleName() != null && !e.getSimpleName().contentEquals("")) {
            fixes.add(new MakeAbstractFix(info, path, e.getSimpleName().toString()).toEditorFix());
        }
    } 
    if (e != null && e.getKind() == ElementKind.ENUM_CONSTANT) {
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    return fixes;
}
 
Example 20
Source Project: sundrio   File: ToPojo.java    License: Apache License 2.0 4 votes vote down vote up
private static String getDefaultValue(Property p) {
    Object value = p.getAttribute(DEFAULT_VALUE);
    String stringVal = value != null ? String.valueOf(value) : null;

    if (p.getTypeRef().getDimensions() > 0) {
        StringBuilder sb = new StringBuilder();
        if  (p.getTypeRef() instanceof PrimitiveRef)  {
            sb.append(((PrimitiveRef) p.getTypeRef()).getName());
        } else if (p.getTypeRef() instanceof ClassRef) {
            sb.append("new ").append(((ClassRef) p.getTypeRef()).getFullyQualifiedName());
        }
        for (int d = 0; d < p.getTypeRef().getDimensions(); d++)  {
            if (value == null || String.valueOf(value).isEmpty()) {
                sb.append("[0]");
            } else {
                sb.append("[]");
            }
        }
        return sb.toString();
    }
    if (Constants.STRING_REF.equals(p.getTypeRef()) && value != null && !String.valueOf(value).startsWith("\"")) {
        return "\"" + value + "\"";
    } else if (value instanceof Element)  {
        Element element = (Element) value;
        if (element.getKind() == ElementKind.ENUM_CONSTANT) {
          return  element.getEnclosingElement() + "." +element.getSimpleName();
        }
    } else if (stringVal != null && stringVal.startsWith("@"))  {
       String annotationFQCN = stringVal.substring(1);
       TypeDef annotationDef = DefinitionRepository.getRepository().getDefinition(annotationFQCN);
       if  (annotationDef != null) {
           TypeDef pojoDef = ClazzAs.POJO.apply(annotationDef);
           if (BuilderUtils.hasDefaultConstructor(pojoDef)) {
              return "new " + pojoDef.getFullyQualifiedName() + "()";
           }
       }
        return "null";
    } else if (stringVal == null && p.getTypeRef() instanceof PrimitiveRef) {
        if (((PrimitiveRef) p.getTypeRef()).getName().equals("boolean")) {
            return "false";
        } else {
            return "0";
        }
    }
    return stringVal;
}