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

The following are top voted examples for showing how to use javax.lang.model.element.ElementKind. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: IntroduceLocalExtensionPlugin.java   View source code 6 votes vote down vote up
@Override
protected Problem preCheck(CompilationController info) throws IOException {
    fireProgressListenerStart(AbstractRefactoring.PRE_CHECK, 4);
    Problem preCheckProblem = null;
    info.toPhase(JavaSource.Phase.RESOLVED);
    preCheckProblem = isElementAvail(treePathHandle, info);
    if (preCheckProblem != null) {
        return preCheckProblem;
    }
    Element el = treePathHandle.resolveElement(info);
    if (!(el.getKind() == ElementKind.CLASS || el.getKind() == ElementKind.INTERFACE)) {
        preCheckProblem = createProblem(preCheckProblem, true, NbBundle.getMessage(IntroduceLocalExtensionPlugin.class, "ERR_IntroduceLEWrongType")); // NOI18N
        return preCheckProblem;
    }
    for (Element element : el.getEnclosedElements()) {
        if((element.getKind().isClass() || element.getKind().isInterface()) && !element.getModifiers().contains(Modifier.PRIVATE)) {
            preCheckProblem = createProblem(preCheckProblem, true, NbBundle.getMessage(IntroduceLocalExtensionPlugin.class, "ERR_IntroduceLEInnerType")); // NOI18N
            return preCheckProblem;
        }
    }
    return preCheckProblem;
}
 
Example 2
Project: incubator-netbeans   File: LucenePerformanceTest.java   View source code 6 votes vote down vote up
private static List<Pair<Pair<BinaryName,String>,Object[]>> prepareData (final int count, final int pkgLimit, final int refLimit) {
    final List<Pair<Pair<BinaryName,String>,Object[]>> result = new ArrayList<> ();
    final List<String> refs = new LinkedList<String>();
    final Random r = new Random (System.currentTimeMillis());
    for (int i=0; i<count; i++) {
        final int refCount = r.nextInt(refLimit);
        final List<String> l = new ArrayList<String>(refCount);            
        for (int j=0; j<refCount && refs.size()>0; j++) {
            int index = r.nextInt(refs.size());
            String s = refs.get (index) + "+++++";
            if (!l.contains(s)) {
                l.add(s);
            }
        }
        String name = String.format("pkg%d.Class%dC",r.nextInt(pkgLimit),i);
        result.add(Pair.<Pair<BinaryName,String>,Object[]>of(
                Pair.<BinaryName,String>of(BinaryName.create(name, ElementKind.CLASS),null),
                new Object[]{l,null,null}));
        refs.add (name);                    
    }
    return result;
}
 
Example 3
Project: GitHub   File: TypeStringProvider.java   View source code 6 votes vote down vote up
private boolean tryToUseSourceAsAWorkaround() {
  if (element.getKind() != ElementKind.METHOD) {
    // we don't bother with non-method attributes
    // (like factory builder, where attributes are parameters)
    return false;
  }

  CharSequence returnTypeString = SourceExtraction.getReturnTypeString((ExecutableElement) element);
  if (returnTypeString.length() == 0) {
    // no source could be extracted for some reason, workaround will not work
    return false;
  }

  Entry<String, List<String>> extractedTypes = SourceTypes.extract(returnTypeString);

  // forces source imports based resolution,
  // we should not rely that types would be fully qualified
  Entry<String, List<String>> resolvedTypes = resolveTypes(extractedTypes);

  this.rawTypeName = resolvedTypes.getKey();
  this.workaroundTypeParameters = resolvedTypes.getValue();
  this.workaroundTypeString = SourceTypes.stringify(resolvedTypes);

  // workaround may have successed, need to continue with whatever we have
  return true;
}
 
Example 4
Project: incubator-netbeans   File: IntroduceHint.java   View source code 6 votes vote down vote up
static TypeMirror resolveType(CompilationInfo info, TreePath path) {
    TypeMirror tm = info.getTrees().getTypeMirror(path);
    
    if (tm != null && tm.getKind() == TypeKind.NULL) {
        List<? extends TypeMirror> targetType = CreateElementUtilities.resolveType(new HashSet<ElementKind>(), info, path.getParentPath(), path.getLeaf(), (int) info.getTrees().getSourcePositions().getStartPosition(path.getCompilationUnit(), path.getLeaf()), new TypeMirror[1], new int[1]);
        
        if (targetType != null && !targetType.isEmpty()) {
            tm = targetType.get(0);
        } else {
            TypeElement object = info.getElements().getTypeElement("java.lang.Object");
            tm = object != null ? object.asType() : null;
        }
    }
    if (!Utilities.isValidType(tm)) {
        return null;
    } else {
        return tm;
    }
}
 
Example 5
Project: incubator-netbeans   File: NPECheck.java   View source code 6 votes vote down vote up
@Override
public State visitMemberSelect(MemberSelectTree node, Void p) {
    State expr = scan(node.getExpression(), p);
    boolean wasNPE = false;
    
    if (expr == State.NULL || expr == State.NULL_HYPOTHETICAL || expr == State.POSSIBLE_NULL || expr == State.POSSIBLE_NULL_REPORT) {
        wasNPE = true;
    }
    
    Element site = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));
    
    if (isVariableElement(site) && wasNPE && (variable2State.get((VariableElement) site) == null || !variable2State.get((VariableElement) site).isNotNull())) {
        variable2State.put((VariableElement) site, NOT_NULL_BE_NPE);
    }
    // special case: if the memberSelect selects enum field = constant, it is never null.
    if (site != null && site.getKind() == ElementKind.ENUM) {
        Element enumConst = info.getTrees().getElement(getCurrentPath());
        if (enumConst != null && enumConst.getKind() == ElementKind.ENUM_CONSTANT) {
            return State.NOT_NULL;
        }
    }
    
    return getStateFromAnnotations(info, info.getTrees().getElement(getCurrentPath()));
}
 
Example 6
Project: incubator-netbeans   File: ElementUtilities.java   View source code 6 votes vote down vote up
static TypeElement enclosingTypeElementImpl( Element element ) throws IllegalArgumentException {

if( element.getKind() == ElementKind.PACKAGE ) {
    throw new IllegalArgumentException();
}

       element = element.getEnclosingElement();

       if (element.getKind() == ElementKind.PACKAGE) {
           //element is a top level class, returning null according to the contract:
           return null;
       }
       
while(element != null && !(element.getKind().isClass() || element.getKind().isInterface())) {
    element = element.getEnclosingElement();
}

return (TypeElement)element;
   }
 
Example 7
Project: incubator-netbeans   File: FileToURL.java   View source code 6 votes vote down vote up
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static ErrorDescription computeTreeKind(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();

    if (!mit.getArguments().isEmpty() || !mit.getTypeArguments().isEmpty()) {
        return null;
    }

    CompilationInfo info = ctx.getInfo();
    Element e = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));

    if (e == null || e.getKind() != ElementKind.METHOD) {
        return null;
    }

    if (e.getSimpleName().contentEquals("toURL") && info.getElementUtilities().enclosingTypeElement(e).getQualifiedName().contentEquals("java.io.File")) {
        ErrorDescription w = ErrorDescriptionFactory.forName(ctx, mit, "Use of java.io.File.toURL()");

        return w;
    }

    return null;
}
 
Example 8
Project: incubator-netbeans   File: BinaryNameTest.java   View source code 6 votes vote down vote up
public void testRawName() throws Exception {
    BinaryName name = BinaryName.create("java.lang.String", ElementKind.CLASS);
    assertEquals("java.lang", name.getPackage());
    assertEquals("String", name.getClassName());
    assertEquals("String", name.getSimpleName());
    name = BinaryName.create("InUnnamedPkg", ElementKind.CLASS);
    assertEquals("", name.getPackage());
    assertEquals("InUnnamedPkg", name.getClassName());
    assertEquals("InUnnamedPkg", name.getSimpleName());
    name = BinaryName.create("java.util.Map$Entry", ElementKind.INTERFACE);
    assertEquals("java.util", name.getPackage());
    assertEquals("Map$Entry", name.getClassName());
    assertEquals("Entry", name.getSimpleName());
    name = BinaryName.create("ru.$stl.Class", ElementKind.CLASS);
    assertEquals("ru.$stl", name.getPackage());
    assertEquals("Class", name.getClassName());
    assertEquals("Class", name.getSimpleName());
    name = BinaryName.create("ru.$stl.Class$Inner", ElementKind.CLASS);
    assertEquals("ru.$stl", name.getPackage());
    assertEquals("Class$Inner", name.getClassName());
    assertEquals("Inner", name.getSimpleName());
}
 
Example 9
Project: RIBs   File: InteractorAnnotationVerifier.java   View source code 6 votes vote down vote up
/**
 * Validates the constructor. Requirements:
 *
 * <ul>
 *   <li>There should only be one or zero constructors (to avoid making multiple creators).
 * </ul>
 *
 * @param type Interactor type to validate.
 * @return {@code true} when valid, {@code false} when invalid.
 */
private boolean validateNoConstructors(TypeElement type) {
  List<ExecutableElement> constructors = new LinkedList<>();
  for (Element element : elementUtils.getAllMembers(type)) {
    if (element.getKind().equals(ElementKind.CONSTRUCTOR)) {
      constructors.add((ExecutableElement) element);
    }
  }

  if (constructors.size() != 1 || !constructors.get(0).getParameters().isEmpty()) {
    errorReporter.reportError(
        "Interactor cannot have custom constructors - all dependencies and setup should happen in "
            + "the builder of ",
        type);
    return false;
  } else {
    return true;
  }
}
 
Example 10
Project: incubator-netbeans   File: LoggerNotStaticFinal.java   View source code 6 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG;"), //NOI18N
    @TriggerPattern(value="$mods$ java.util.logging.Logger $LOG = $init;") //NOI18N
})
public static ErrorDescription checkLoggerDeclaration(HintContext ctx) {
    Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());
    if (e != null && e.getEnclosingElement().getKind() == ElementKind.CLASS &&
        (!e.getModifiers().contains(Modifier.STATIC) || !e.getModifiers().contains(Modifier.FINAL)) &&
        ctx.getInfo().getElementUtilities().outermostTypeElement(e) == e.getEnclosingElement()
    ) {
        return ErrorDescriptionFactory.forName(
                ctx,
                ctx.getPath(),
                NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration", e), //NOI18N
                new LoggerNotStaticFinalFix(NbBundle.getMessage(LoggerNotStaticFinal.class, "MSG_LoggerNotStaticFinal_checkLoggerDeclaration_fix", e), TreePathHandle.create(e, ctx.getInfo())).toEditorFix() //NOI18N
        );
    } else {
        return null;
    }
}
 
Example 11
Project: RxPay   File: EntityHandler.java   View source code 6 votes vote down vote up
public Map<String, ClassEntity> handlerElement(RoundEnvironment env, BaseProcessor processor) {
    this.env = env;
    for (Class<? extends Annotation> support : processor.getSupportedAnnotations()) {
        for (Element element : env.getElementsAnnotatedWith(support)) {
            if (element.getKind() == ElementKind.FIELD){
                handlerField((VariableElement) element);
            }
            if (element.getKind() == ElementKind.METHOD){
                handlerMethod((ExecutableElement) element);
            }
            if (element.getKind() == ElementKind.CLASS) {
                handlerClass((TypeElement) element);
            }
        }
    }
    return classEntityMap;
}
 
Example 12
Project: incubator-netbeans   File: JavadocCompletionQuery.java   View source code 6 votes vote down vote up
private void addTypes(EnumSet<ElementKind> kinds, DeclaredType baseType,
        Set<? extends Element> toExclude, String prefix,
        int substitutionOffset, JavadocContext jdctx) {
    
    if (queryType == CompletionProvider.COMPLETION_ALL_QUERY_TYPE) {
        if (baseType == null) {
            addAllTypes(jdctx, kinds, toExclude, prefix, substitutionOffset);
        } else {
            Elements elements = jdctx.javac.getElements();
            for(DeclaredType subtype : getSubtypesOf(baseType, prefix, jdctx)) {
                TypeElement elem = (TypeElement)subtype.asElement();
                if ((toExclude == null || !toExclude.contains(elem)) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(elem)))
                    items.add(JavaCompletionItem.createTypeItem(jdctx.javac, elem, subtype, substitutionOffset, jdctx.getReferencesCount(), elements.isDeprecated(elem), false, false, false, false, false, null));
            }
        }
    } else {
        addLocalAndImportedTypes(jdctx, kinds, baseType, toExclude, prefix, substitutionOffset);
        hasAdditionalItems = true;
    }
}
 
Example 13
Project: GitHub   File: OkJsons.java   View source code 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 14
Project: GitHub   File: MvpCompiler.java   View source code 6 votes vote down vote up
private boolean throwableProcess(RoundEnvironment roundEnv) {
	checkInjectors(roundEnv, InjectPresenter.class, new PresenterInjectorRules(ElementKind.FIELD, Modifier.PUBLIC, Modifier.DEFAULT));

	ViewStateProviderClassGenerator viewStateProviderClassGenerator = new ViewStateProviderClassGenerator();
	PresenterBinderClassGenerator presenterBinderClassGenerator = new PresenterBinderClassGenerator();
	processInjectors(roundEnv, InjectViewState.class, ElementKind.CLASS, viewStateProviderClassGenerator);
	processInjectors(roundEnv, InjectPresenter.class, ElementKind.FIELD, presenterBinderClassGenerator);

	ViewStateClassGenerator viewStateClassGenerator = new ViewStateClassGenerator();
	Set<TypeElement> usedViews = viewStateProviderClassGenerator.getUsedViews();

	for (TypeElement usedView : usedViews) {
		generateCode(ElementKind.INTERFACE, viewStateClassGenerator, usedView);
	}

	String moxyReflector = MoxyReflectorGenerator.generate(viewStateProviderClassGenerator.getPresenterClassNames(), presenterBinderClassGenerator.getPresentersContainers(), viewStateClassGenerator.getStrategyClasses());

	ClassGeneratingParams classGeneratingParams = new ClassGeneratingParams();
	classGeneratingParams.setName("com.arellomobile.mvp.MoxyReflector");
	classGeneratingParams.setBody(moxyReflector);

	createSourceFile(classGeneratingParams);

	return true;
}
 
Example 15
Project: immu   File: ImmuObjectElement.java   View source code 6 votes vote down vote up
/**
 * Returns a list of the super-properties, i.e. properties inherited from the extending tree of {@code iface}.
 * @param env the environment, must not be null
 * @param iface the @Immu/@SuperImmu interface for which to recursively find the properties, must not be null
 * @return the list of properties, in order from the most super interface to the provided one
 */
private List<ImmuProperty> superProperties(ProcessingEnvironment env, TypeMirror iface) {
  final LinkedList<ImmuProperty> properties = new LinkedList<>();

  final Element ifaceElement = env.getTypeUtils().asElement(iface);

  final TypeElement typeElement = (TypeElement) ifaceElement;

  for (TypeMirror mirror : typeElement.getInterfaces()) {
    properties.addAll(superProperties(env, mirror));
  }

  for (Element element : ifaceElement.getEnclosedElements()) {
    if (ElementKind.METHOD.equals(element.getKind())) {
      properties.add(ImmuProperty.from(element));
    }
  }

  return properties;
}
 
Example 16
Project: incubator-netbeans   File: InstantRenamePerformer.java   View source code 6 votes vote down vote up
/**
 * computes accessibility of members of nested classes
 * @param e member
 * @return {@code true} if the member cannot be accessed outside the outer class
 * @see <a href="http://www.netbeans.org/issues/show_bug.cgi?id=169377">169377</a>
 */
private static boolean isInaccessibleOutsideOuterClass(Element e, ElementUtilities eu) {
    Element enclosing = e.getEnclosingElement();
    boolean isStatic = e.getModifiers().contains(Modifier.STATIC);
    ElementKind kind = e.getKind();
    if (isStatic || kind.isClass() || kind.isInterface() || kind.isField()) {
        // static declaration of nested class, interface, enum, ann type, method, field
        // or inner class
        return isAnyEncloserPrivate(e);
    } else if (enclosing != null && kind == ElementKind.METHOD) {
        // final is enum, ann type and some classes
        ElementKind enclosingKind = enclosing.getKind();
        boolean isEnclosingFinal = enclosing.getModifiers().contains(Modifier.FINAL)
                // ann type is not final even if it cannot be subclassed
                || enclosingKind == ElementKind.ANNOTATION_TYPE;
        return isAnyEncloserPrivate(e) && !eu.overridesMethod((ExecutableElement) e) && !eu.implementsMethod((ExecutableElement)e) &&
                (isEnclosingFinal || !isOverriddenInsideOutermostEnclosingClass((ExecutableElement)e, eu));
    }
    return false;
}
 
Example 17
Project: react4j   File: ProcessorUtil.java   View source code 6 votes vote down vote up
private static void enumerateFieldElements( @Nonnull final TypeElement element,
                                            @Nonnull final Map<String, VariableElement> fields )
{
  final TypeMirror superclass = element.getSuperclass();
  if ( TypeKind.NONE != superclass.getKind() )
  {
    enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
  }
  for ( final Element member : element.getEnclosedElements() )
  {
    if ( member.getKind() == ElementKind.FIELD )
    {
      fields.put( member.getSimpleName().toString(), (VariableElement) member );
    }
  }
}
 
Example 18
Project: incubator-netbeans   File: Tiny.java   View source code 6 votes vote down vote up
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
    Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
    
    //we can't say much currently about non-private fields:
    if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
    
    FlowResult flow = Flow.assignmentsForUse(ctx);
    
    if (flow == null || ctx.isCanceled()) return null;
    
    if (flow.getFinalCandidates().contains(ve)) {
        VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
        Fix fix = null;
        if (flow.getFieldInitConstructors(ve).size() <= 1) {
            fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
        }
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
    }
    
    return null;
}
 
Example 19
Project: incubator-netbeans   File: TooStrongCast.java   View source code 6 votes vote down vote up
private static boolean isPolymorphicSignature(CompilationInfo info, TreePath path) {
    TypeElement polymorphicEl=  info.getElements().getTypeElement("java.lang.invoke.MethodHandle.PolymorphicSignature"); // NOI18N
    if (polymorphicEl == null) {
        // unsuitable platform
        return false;
    }
    TypeMirror polyType = polymorphicEl.asType();
    Element target = info.getTrees().getElement(path);
    if (target == null || target.getKind() != ElementKind.METHOD) {
        return false;
    }
    if (target.getEnclosingElement() == null || !target.getEnclosingElement().getKind().isClass()) {
        return false;
    }
    ExecutableElement ee = (ExecutableElement)target;
    TypeElement parent = (TypeElement)target.getEnclosingElement();
    if (!parent.getQualifiedName().toString().startsWith("java.lang.invoke.")) { // NOI18N
        return false;
    }
    for (AnnotationMirror am : ee.getAnnotationMirrors()) {
        if (info.getTypes().isSameType(polyType, am.getAnnotationType())) {
            return true;
        }
    }
    return false;
}
 
Example 20
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 6 votes vote down vote up
private static List<? extends TypeMirror> computeConditionalExpression(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ConditionalExpressionTree cet = (ConditionalExpressionTree) parent.getLeaf();
    
    if (cet.getCondition() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.BOOLEAN));
    }
    
    if (cet.getTrueExpression() == error || cet.getFalseExpression() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return resolveType(types, info, parent.getParentPath(), cet, offset, null, null);
    }
    
    return null;
}
 
Example 21
Project: incubator-netbeans   File: StaticImport.java   View source code 5 votes vote down vote up
private static boolean hasMethodWithSimpleName(CompilationInfo info, Element element, final String sn) {
    Iterable<? extends Element> members =
            info.getElementUtilities().getMembers(element.asType(), new ElementUtilities.ElementAcceptor() {

        @Override
        public boolean accept(Element e, TypeMirror type) {
            return e.getKind() == ElementKind.METHOD && e.getSimpleName().toString().equals(sn);
        }
    });
    return members.iterator().hasNext();
}
 
Example 22
Project: Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming   File: Aptools.java   View source code 5 votes vote down vote up
private String getKindName(ElementKind kind) {
  Element element = this.element;
  while (element != null && element.getKind() != kind) {
    element = element.getEnclosingElement();
  }
  if (kind.equals(ElementKind.PACKAGE)) {
    return ((PackageElement) element).getQualifiedName().toString();
  } else {
    return element.getSimpleName().toString();
  }
}
 
Example 23
Project: EgTest   File: AnnotationCollector.java   View source code 5 votes vote down vote up
private void addExample(EgItem<?> data) {
    Element classEl = JavaModelUtil.topLevelClass(data.getElement());
    if (classEl.getKind().equals(ElementKind.CLASS)) {
        String name = className(classEl);
        itemsByClassName.computeIfAbsent(name, x -> new ArrayList<>())
                .add(data);
    }
    else {
        messageHandler.error("Container is not a class: "+data.getElement());
    }
}
 
Example 24
Project: incubator-netbeans   File: AbstractTestGenerator.java   View source code 5 votes vote down vote up
/**
 * Checks whether the given type object represents type
 * {@literal java.lang.Object}.
 * 
 * @param  type  type to be checked
 * @return  {@literal true} if the passed type object represents type
 *          {@literal java.lang.Object}, {@literal false} otherwise
 */
private static boolean isRootObjectType(DeclaredType type) {
    if (type.getKind() != TypeKind.DECLARED) {
        return false;
    }

    TypeElement elem = (TypeElement) type.asElement();
    return (elem.getKind() == ElementKind.CLASS)
           && (elem.getSuperclass().getKind() == TypeKind.NONE);
}
 
Example 25
Project: incubator-netbeans   File: JavadocCompletionItem.java   View source code 5 votes vote down vote up
public static List<CompletionItem> addBlockTagItems(ElementKind kind,
        String prefix, int startOffset) {
    
    List<TagEntry> tags = TagRegistery.getDefault().getTags(kind, false);
    List<CompletionItem> items = new ArrayList<CompletionItem>(tags.size());
    for (TagEntry tagEntry : tags) {
        if (tagEntry.name.startsWith(prefix)) {
            items.add(new JavadocCompletionItem(tagEntry.name, startOffset,
                    null, null, JAVADOC_TAG_ICON, 500));
        }
    }
    return items;
}
 
Example 26
Project: incubator-netbeans   File: CodeGenerator.java   View source code 5 votes vote down vote up
static CompilationUnitTree generateCode(WorkingCopy wc, Element te) {
    TreeMaker make = wc.getTreeMaker();
    Tree clazz = new TreeBuilder(make, wc).visit(te);
    CompilationUnitTree cut = make.CompilationUnit(
            te.getKind() == ElementKind.MODULE ? null : make.Identifier(((PackageElement) te.getEnclosingElement()).getQualifiedName()),
            Collections.<ImportTree>emptyList(),
            Collections.singletonList(clazz),
            wc.getCompilationUnit().getSourceFile());

    return cut;
}
 
Example 27
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 5 votes vote down vote up
private static List<? extends TypeMirror> computeAssignment(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    AssignmentTree at = (AssignmentTree) parent.getLeaf();
    TypeMirror     type = null;
    
    if (at.getVariable() == error) {
        type = info.getTrees().getTypeMirror(new TreePath(parent, at.getExpression()));

        if (type != null) {
            //anonymous class?
            type = JavaPluginUtils.convertIfAnonymous(type);

            if (type.getKind() == TypeKind.EXECUTABLE) {
                //TODO: does not actualy work, attempt to solve situations like:
                //t = Collections.emptyList()
                //t = Collections.<String>emptyList();
                //see also testCreateFieldMethod1 and testCreateFieldMethod2 tests:
                type = ((ExecutableType) type).getReturnType();
            }
        }
    }
    
    if (at.getExpression() == error) {
        type = info.getTrees().getTypeMirror(new TreePath(parent, at.getVariable()));
    }
    
    //class or field:
    if (type == null) {
        return null;
    }
    
    types.add(ElementKind.PARAMETER);
    types.add(ElementKind.LOCAL_VARIABLE);
    types.add(ElementKind.FIELD);
    
    return Collections.singletonList(type);
}
 
Example 28
Project: glimpse   File: StyleableField.java   View source code 5 votes vote down vote up
StyleableField(final Element element, final StyleableAnnotationValues annotationValues) {
    if (element == null || element.getAnnotation(Styleable.class) == null || element.getKind() != ElementKind.FIELD || element.getModifiers().contains(Modifier.PRIVATE)) {
        throw new IllegalArgumentException("Element parameter in StyleableField constructor must represent a non-private field annotated with the Styleable annotation");
    }

    final Styleable styleable = element.getAnnotation(Styleable.class);

    this.fieldName = element.getSimpleName().toString();
    this.typeName = TypeName.get(element.asType());
    this.styleableReference = annotationValues.getStyleableValue();
    this.defaultReference = annotationValues.getDefaultValue();
    this.hasDefaultValue = annotationValues.getDefaultValue() != null;
    this.styleableGroupName = annotationValues.getStyleableValue().getRClassName().packageName() + "." + annotationValues.getStyleableValue().getGroupName();

    for (final AnnotationMirror mirror : element.getAnnotationMirrors()) {
        String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString();

        if (annotationName.equals(COLOR_INT_CLASS_NAME)) {
            colorInt = true;
        } else if (annotationName.equals(DIMENSION_CLASS_NAME)) {
            dimension = true;

            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
                if (entry.getKey().getSimpleName().contentEquals(DIMENSION_UNIT_FIELD_NAME)) {
                    int value = (int) entry.getValue().getValue();

                    if (value == 0) {
                        dimensionUnit = DimensionUnit.DP;
                    } else if (value == 1) {
                        dimensionUnit = DimensionUnit.PX;
                    } else if (value == 2) {
                        dimensionUnit = DimensionUnit.SP;
                    }
                }
            }
        }
    }
}
 
Example 29
Project: NullAway   File: NullAway.java   View source code 5 votes vote down vote up
private Description checkForReadBeforeInit(ExpressionTree tree, VisitorState state) {
  // do a bunch of filtering.  first, filter out anything outside an initializer
  TreePath path = state.getPath();
  TreePath enclosingBlockPath = NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(path);
  if (enclosingBlockPath == null) {
    // is this possible?
    return Description.NO_MATCH;
  }
  if (!relevantInitializerMethodOrBlock(enclosingBlockPath, state)) {
    return Description.NO_MATCH;
  }

  // now, make sure we have a field read
  Symbol symbol = ASTHelpers.getSymbol(tree);
  if (symbol == null) {
    return Description.NO_MATCH;
  }
  if (!symbol.getKind().equals(ElementKind.FIELD)) {
    return Description.NO_MATCH;
  }
  if (okToReadBeforeInitialized(path)) {
    // writing the field, not reading it
    return Description.NO_MATCH;
  }

  // check that the field might actually be problematic to read
  FieldInitEntities entities = class2Entities.get(enclosingClassSymbol(enclosingBlockPath));
  if (!(entities.nonnullInstanceFields().contains(symbol)
      || entities.nonnullStaticFields().contains(symbol))) {
    // field is either nullable or initialized at declaration
    return Description.NO_MATCH;
  }
  if (symbolHasSuppressInitalizationWarningsAnnotation(symbol)) {
    // also suppress checking read before init, as we may not find explicit initialization
    return Description.NO_MATCH;
  }
  return checkPossibleUninitFieldRead(tree, state, symbol, path, enclosingBlockPath);
}
 
Example 30
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 5 votes vote down vote up
private static List<? extends TypeMirror> computeReferenceType(Set<ElementKind> types, CompilationInfo info, Tree expression, Tree error, String type) {
    if (expression == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getElements().getTypeElement(type).asType());
    }
    
    return null;
}
 
Example 31
Project: incubator-netbeans   File: JShellOptions2.java   View source code 5 votes vote down vote up
private void cbMemberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMemberActionPerformed
    Object o = cbMember.getSelectedItem();
    if (o != null && !disableUpdates) {
        MemberDescription md = (MemberDescription)o;
        if (md.kind == ElementKind.METHOD) {
            changedOptions.put(PropertyNames.JSHELL_FROM_FIELD, null);
            changedOptions.put(PropertyNames.JSHELL_FROM_METHOD, md.name);
        } else {
            changedOptions.put(PropertyNames.JSHELL_FROM_METHOD, null);
            changedOptions.put(PropertyNames.JSHELL_FROM_FIELD, md.name);
        }
        message = null;
        storeChanges();
    }
}
 
Example 32
Project: incubator-netbeans   File: ElementHandle.java   View source code 5 votes vote down vote up
/**
 * Creates an {@link ElementHandle} representing a {@link ModuleElement}.
 * @param moduleName the name of the module
 * @return the created {@link ElementHandle}
 * @since 2.26
 */
@NonNull
public static ElementHandle<ModuleElement> createModuleElementHandle(
        @NonNull final String moduleName) {
    Parameters.notNull("moduleName", moduleName); //NOI18N
    return new ElementHandle<>(ElementKind.MODULE, moduleName);
}
 
Example 33
Project: syndesis   File: SyndesisExtensionActionProcessor.java   View source code 5 votes vote down vote up
/**
 * Explicitly add properties that elude reflection implicit strategy
 * @param element
 * @param props
 */
protected boolean augmentProperties(TypeElement element, Properties props) throws InvocationTargetException, IllegalAccessException {
    final Elements elements = processingEnv.getElementUtils();
    final TypeElement extensionTypeElement = elements.getTypeElement(stepClass.getName());

    if (extensionTypeElement != null && processingEnv.getTypeUtils().isAssignable(element.asType(), extensionTypeElement.asType())) {
        props.put("kind", "STEP");
        props.put("entrypoint", element.getQualifiedName().toString());
    } else {
        props.put("kind", "BEAN");
        props.put("entrypoint", element.getQualifiedName().toString());

        for (Element method: element.getEnclosedElements()) {
            if (method.getAnnotation(handlerAnnotationClass) != null) {

                // Process method
                augmentProperties((ExecutableElement)method, props);
                addActionProperties(method, props);

                // Found a method annotated with Handler, let's search for
                // fields annotated with SyndesisActionProperty
                for (Element field: element.getEnclosedElements()) {
                    if (field.getKind() == ElementKind.FIELD) {
                        addActionProperties(field, props);
                    }
                }

                return true;
            }
        }
    }

    return false;
}
 
Example 34
Project: openjdk-jdk10   File: Utils.java   View source code 5 votes vote down vote up
private List<Element> getItems0(Element te, boolean filter, Set<ElementKind> kinds) {
    List<Element> elements = new ArrayList<>();
    for (Element e : te.getEnclosedElements()) {
        if (kinds.contains(e.getKind())) {
            if (!filter || shouldDocument(e)) {
                elements.add(e);
            }
        }
    }
    return elements;
}
 
Example 35
Project: openjdk-jdk10   File: ApNavigator.java   View source code 5 votes vote down vote up
public VariableElement[] getEnumConstants(TypeElement clazz) {
    List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz);
    Collection<VariableElement> constants = new ArrayList<VariableElement>();
    for (Element element : elements) {
        if (element.getKind().equals(ElementKind.ENUM_CONSTANT)) {
            constants.add((VariableElement) element);
        }
    }
    return constants.toArray(new VariableElement[constants.size()]);
}
 
Example 36
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 5 votes vote down vote up
private static List<? extends TypeMirror> computeNewArray(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewArrayTree nat = (NewArrayTree) parent.getLeaf();
    
    if (nat.getType() == error) {
        types.add(ElementKind.CLASS);
        types.add(ElementKind.ENUM);
        types.add(ElementKind.INTERFACE);
        
        return null;
    }
    
    for (Tree dimension : nat.getDimensions()) {
        if (dimension == error) {
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
        }
    }
    
    for (Tree init : nat.getInitializers()) {
        if (init == error) {
            TypeMirror whole = info.getTrees().getTypeMirror(parent);
            
            if (whole == null || whole.getKind() != TypeKind.ARRAY)
                return null;
            
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(((ArrayType) whole).getComponentType());
        }
    }
    
    return null;
}
 
Example 37
Project: incubator-netbeans   File: AbstractTestGenerator.java   View source code 5 votes vote down vote up
/**
 */
private boolean isTestableMethod(ExecutableElement method) {
    if (method.getKind() != ElementKind.METHOD) {
        throw new IllegalArgumentException();
    }

    return setup.isMethodTestable(method);
}
 
Example 38
Project: incubator-netbeans   File: TagRegistery.java   View source code 5 votes vote down vote up
public List<TagEntry> getTags(ElementKind kind, boolean inline) {
    List<TagEntry> selection = new ArrayList<TagEntry>();
    for (TagEntry te : tags) {
        if (te.isInline == inline && te.whereUsed.contains(kind)) {
            selection.add(te);
        }
    }
    return selection;
}
 
Example 39
Project: incubator-netbeans   File: ProfileSupport.java   View source code 5 votes vote down vote up
private void validateBinaryFile(
        @NonNull final FileObject fo,
        @NonNull final ViolationCollector collector) {
    final Profile profileToCheck = context.getRequredProfile();
    final TypeCache tc = context.getTypeCache();
    try {
        try (InputStream in = fo.getInputStream()) {
            ClassFile cf = new ClassFile(in);
            for (ClassName className : cf.getAllClassNames()) {
                final Profile p = tc.profileForType(className);
                if (p != null && profileToCheck.compareTo(p) < 0) {
                    collector.reportProfileViolation(
                        new Violation(
                            root,
                            p,
                            map(fo),
                            ElementHandleAccessor.getInstance().create(ElementKind.CLASS, className.getInternalName().replace('/', '.'))    //NOI18N
                    ));
                }
            }
        }
    } catch (IOException ioe) {
        LOG.log(
            Level.INFO,
            "Cannot validate file: {0}",    //NOI18N
            FileUtil.getFileDisplayName(fo));
    }
}
 
Example 40
Project: incubator-netbeans   File: MagicSurroundWithTryCatchFix.java   View source code 5 votes vote down vote up
private StatementTree createFinallyCloseBlockStatement(VariableTree origDeclaration) {
    Trees trees = info.getTrees();
    TypeMirror tm = trees.getTypeMirror(statement);
    ElementUtilities elUtils = info.getElementUtilities();
    Iterable iterable = elUtils.getMembers(tm, new ElementAcceptor() {
        public boolean accept(Element e, TypeMirror type) {
            return e.getKind() == ElementKind.METHOD && "close".equals(e.getSimpleName().toString()); // NOI18N
        }
    });
    boolean throwsIO = false;
    for (Iterator iter = iterable.iterator(); iter.hasNext(); ) {
        ExecutableElement elem = (ExecutableElement) iter.next();
        if (!elem.getParameters().isEmpty()) {
            continue;
        } else {
             for (TypeMirror typeMirror : elem.getThrownTypes()) {
                 if ("java.io.IOException".equals(typeMirror.toString())) { // NOI18N
                     throwsIO = true;
                     break;
                 }
             }
        }
    }
    
    CharSequence name = origDeclaration.getName();
    StatementTree close = make.ExpressionStatement(make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier(name), "close"), Collections.<ExpressionTree>emptyList()));
    StatementTree result = close;
    if (throwsIO) {
        result = make.Try(make.Block(Collections.singletonList(close), false), Collections.singletonList(createCatch(info, make, statement, inferName(info, statement), info.getElements().getTypeElement("java.io.IOException").asType())), null);
        }
    
    return result;
}