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

The following examples show how to use javax.lang.model.element.ElementKind#PACKAGE . 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: ElementsReader.java    From buck with Apache License 2.0 6 votes vote down vote up
private void addAllElements(Element rootElement, Map<Path, Element> elements) {
  if (rootElement.getKind() == ElementKind.PACKAGE) {
    PackageElement packageElement = (PackageElement) rootElement;
    if (!packageElement.getAnnotationMirrors().isEmpty()) {
      elements.put(
          getRelativePathToClass(packageElement.getQualifiedName() + ".package-info"),
          packageElement);
    }
  }

  if (!rootElement.getKind().isClass() && !rootElement.getKind().isInterface()) {
    return;
  }

  TypeElement typeElement = (TypeElement) rootElement;
  elements.put(getRelativePath(typeElement), typeElement);
  for (Element enclosed : typeElement.getEnclosedElements()) {
    addAllElements(enclosed, elements);
  }
}
 
Example 2
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ExpressionTree qualIdentFor(Element e) {
    TreeMaker tm = copy.getTreeMaker();
    if (e.getKind() == ElementKind.PACKAGE) {
        String name = ((PackageElement)e).getQualifiedName().toString();
        if (e instanceof Symbol) {
            int lastDot = name.lastIndexOf('.');
            if (lastDot < 0)
                return tm.Identifier(e);
            return tm.MemberSelect(qualIdentFor(name.substring(0, lastDot)), e);
        }
        return qualIdentFor(name);
    }
    Element ee = e.getEnclosingElement();
    if (e instanceof Symbol)
        return ee.getSimpleName().length() > 0 ? tm.MemberSelect(qualIdentFor(ee), e) : tm.Identifier(e);
    return ee.getSimpleName().length() > 0 ? tm.MemberSelect(qualIdentFor(ee), e.getSimpleName()) : tm.Identifier(e.getSimpleName());
}
 
Example 3
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String fqnFor(Tree t) {
    Element el = ASTService.getElementImpl(t);

    if (el != null) {
        if (el.getKind().isClass() || el.getKind().isInterface() || el.getKind() == ElementKind.PACKAGE) {
            return ((QualifiedNameable) el).getQualifiedName().toString();
        } else {
            Logger.getLogger(ElementOverlay.class.getName()).log(Level.SEVERE, "Not a QualifiedNameable: {0}", el);
            return null;
        }
    } else if (t instanceof QualIdentTree) {
        return ((QualIdentTree) t).getFQN();
    } else if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return fqnFor(((ParameterizedTypeTree) t).getType());
    } else {
        Logger.getLogger(ElementOverlay.class.getName()).log(Level.FINE, "No element and no QualIdent");
        return null;
    }
}
 
Example 4
Source File: QualifiedName.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link QualifiedName} for {@code type}.
 */
public static QualifiedName of(TypeElement type) {
  switch (type.getNestingKind()) {
    case TOP_LEVEL:
      PackageElement pkg = (PackageElement) type.getEnclosingElement();
      return QualifiedName.of(pkg.getQualifiedName().toString(), type.getSimpleName().toString());

    case MEMBER:
      List<String> reversedNames = new ArrayList<String>();
      reversedNames.add(type.getSimpleName().toString());
      Element parent = type.getEnclosingElement();
      while (parent.getKind() != ElementKind.PACKAGE) {
        reversedNames.add(parent.getSimpleName().toString());
        parent = parent.getEnclosingElement();
      }
      return new QualifiedName(
          ((PackageElement) parent).getQualifiedName().toString(),
          ImmutableList.copyOf(Lists.reverse(reversedNames)));

    default:
      throw new IllegalArgumentException("Cannot determine qualified name of " + type);
  }
}
 
Example 5
Source File: ToothpickProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
protected boolean isNonStaticInnerClass(TypeElement typeElement) {
  Element outerClassOrPackage = typeElement.getEnclosingElement();
  if (outerClassOrPackage.getKind() != ElementKind.PACKAGE
      && !typeElement.getModifiers().contains(Modifier.STATIC)) {
    error(
        typeElement,
        "Class %s is a non static inner class. @Inject constructors are not allowed in non static inner classes.",
        typeElement.getQualifiedName());
    return true;
  }
  return false;
}
 
Example 6
Source File: ElementJavadoc.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isLocalized(final URL docURL, final Element element) {
    if (docURL == null) {
        return false;
    }
    Element pkg = element;
    while (pkg.getKind() != ElementKind.PACKAGE) {
        pkg = pkg.getEnclosingElement();
        if (pkg == null) {
            return false;
        }
    }
    String pkgBinName = ((PackageElement)pkg).getQualifiedName().toString();
    String surl = docURL.toString();
    int index = surl.lastIndexOf('/');      //NOI18N
    if (index < 0) {
        return false;
    }
    index-=(pkgBinName.length()+1);
    if (index < 0) {
        return false;
    }
    index-=API.length();        
    if (index < 0 || !surl.regionMatches(index,API,0,API.length())) {
        return false;
    }
    int index2 = surl.lastIndexOf('/', index-1);  //NOI18N
    if (index2 < 0) {
        return false;
    }
    String lang = surl.substring(index2+1, index);        
    return LANGS.contains(lang);
}
 
Example 7
Source File: Proto.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
@Value.Derived
@Value.Auxiliary
public DeclaringPackage packageOf() {
  Element e = element();
  for (; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) {
  }
  return interner().forPackage(
      ImmutableProto.DeclaringPackage.builder()
          .environment(environment())
          .interner(interner())
          .element((PackageElement) e)
          .build());
}
 
Example 8
Source File: NoPrivateTypesExported.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private TypeElement outermostTypeElement(Element el) {
    while (el.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        el = el.getEnclosingElement();
    }

    return (TypeElement) el;
}
 
Example 9
Source File: ElementHandle.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@link ElementHandle} representing a {@link PackageElement}.
 * @param packageName the name of the package
 * @return the created {@link ElementHandle}
 * @since 0.98
 */
@NonNull
public static ElementHandle<PackageElement> createPackageElementHandle (
    @NonNull final String packageName) {
    Parameters.notNull("packageName", packageName); //NOI18N
    return new ElementHandle<PackageElement>(ElementKind.PACKAGE, packageName);
}
 
Example 10
Source File: GoToSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Element handlePossibleAnonymousInnerClass(CompilationInfo info, final Element el) {
    Element encl = el.getEnclosingElement();
    Element doubleEncl = encl != null ? encl.getEnclosingElement() : null;
    
    if (   doubleEncl != null
        && !doubleEncl.getKind().isClass()
        && !doubleEncl.getKind().isInterface()
        && doubleEncl.getKind() != ElementKind.PACKAGE
        && encl.getKind() == ElementKind.CLASS) {
        TreePath enclTreePath = info.getTrees().getPath(encl);
        Tree enclTree = enclTreePath != null ? enclTreePath.getLeaf() : null;
        
        if (enclTree != null && TreeUtilities.CLASS_TREE_KINDS.contains(enclTree.getKind()) && enclTreePath.getParentPath().getLeaf().getKind() == Tree.Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) enclTreePath.getParentPath().getLeaf();
            
            if (nct.getClassBody() != null) {
                Element parentElement = info.getTrees().getElement(new TreePath(enclTreePath, nct.getIdentifier()));
                
                if (parentElement == null || parentElement.getKind().isInterface()) {
                    return parentElement;
                } else {
                    //annonymous innerclass extending a class. Find out which constructor is used:
                    TreePath superConstructorCall = new FindSuperConstructorCall().scan(enclTreePath, null);
                    
                    if (superConstructorCall != null) {
                        return info.getTrees().getElement(superConstructorCall);
                    }
                }
            }
        }
        
        return null;//prevent jumps to incorrect positions
    } else {
        if (encl != null) {
            return encl;
        } else {
            return el;
        }
    }
}
 
Example 11
Source File: Metaservices.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Nullable
private TypeElement validated(Element element) {
  Element enclosingElement = element.getEnclosingElement();

  if (element.getKind() == ElementKind.CLASS
      && element.getModifiers().contains(Modifier.PUBLIC)
      && enclosingElement != null) {

    if (enclosingElement.getKind() == ElementKind.PACKAGE
        && !element.getModifiers().contains(Modifier.ABSTRACT)
        && !((PackageElement) enclosingElement).isUnnamed()) {
      return (TypeElement) element;
    }

    if (enclosingElement.getKind() == ElementKind.CLASS
       && element.getModifiers().contains(Modifier.STATIC)) {
        return (TypeElement) element;
    }
  }

  processing().getMessager()
      .printMessage(Diagnostic.Kind.ERROR,
          "Element annotated with @Metainf.Service annotation should be public top-level non-abstract or static class in a package",
          element);

  return null;
}
 
Example 12
Source File: ImportAnalysis2.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private PackageElement getPackageOf(Element el) {
    while ((el != null) && (el.getKind() != ElementKind.PACKAGE)) el = el.getEnclosingElement();

    return (PackageElement) el;
}
 
Example 13
Source File: SafeDeleteUI.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public RefactoringUI create(CompilationInfo info, TreePathHandle[] handles, FileObject[] files, NonRecursiveFolder[] packages) {
    final boolean b = lookup.lookup(ExplorerContext.class)!=null;
    if (packages != null && packages.length == 1) {
        return new SafeDeleteUI(packages[0], b);
    }
    if (handles != null && handles.length == 0 || (files!=null && files.length > 1)) {
        return new SafeDeleteUI(files, Arrays.asList(handles), b);
    }
    
    if (b && files!=null && files.length == 1) {
        return new SafeDeleteUI(files, Arrays.asList(handles), b);
    }
    
    if (info == null) {
        return new SafeDeleteUI(handles);
    }
    
    TreePathHandle selectedElement = handles[0];
    Element selected = selectedElement.resolveElement(info);
    TreePath selectedTree = selectedElement.resolve(info);
    if (selected == null || selectedTree == null) {
        return null;
    }
    if (selected.getKind() == ElementKind.PACKAGE || selected.getEnclosingElement().getKind() == ElementKind.PACKAGE) {
        ElementHandle<Element> handle = ElementHandle.create(selected);
        FileObject file = SourceUtils.getFile(handle, info.getClasspathInfo());
        if (file == null) {
            return null;
        }
        if (file.getName().equals(selected.getSimpleName().toString())) {
            return new SafeDeleteUI(new FileObject[]{file}, Collections.singleton(selectedElement), b);
        }
    }
    if(!TreeUtilities.CLASS_TREE_KINDS.contains(selectedTree.getParentPath().getLeaf().getKind())
            && selectedTree.getParentPath().getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT
            && selectedTree.getLeaf().getKind() == Tree.Kind.VARIABLE) {
        switch (selectedTree.getParentPath().getLeaf().getKind()) {
            case BLOCK:
            case METHOD:
                break;
            default:
                return null;
        }
    }
    return new SafeDeleteUI(new TreePathHandle[]{selectedElement});
}
 
Example 14
Source File: ProcessorUtils.java    From nalu with Apache License 2.0 4 votes vote down vote up
public PackageElement getPackage(Element type) {
  while (type.getKind() != ElementKind.PACKAGE) {
    type = type.getEnclosingElement();
  }
  return (PackageElement) type;
}
 
Example 15
Source File: ArgProcessor.java    From fragmentargs with Apache License 2.0 4 votes vote down vote up
private PackageElement getPackage(Element element) {
    while (element.getKind() != ElementKind.PACKAGE) {
        element = element.getEnclosingElement();
    }
    return (PackageElement) element;
}
 
Example 16
Source File: HTMLDialogProcessor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static PackageElement findPkg(Element e) {
    while (e.getKind() != ElementKind.PACKAGE) {
        e = e.getEnclosingElement();
    }
    return (PackageElement)e;
}
 
Example 17
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 18
Source File: PersistentClassIndex.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public <T> void search (
        @NonNull final ElementHandle<?> element,
        @NonNull final Set<? extends UsageType> usageType,
        @NonNull final Set<? extends ClassIndex.SearchScopeType> scope,
        @NonNull final Convertor<? super Document, T> convertor,
        @NonNull final Set<? super T> result) throws InterruptedException, IOException {
    Parameters.notNull("element", element); //NOI18N
    Parameters.notNull("usageType", usageType); //NOI18N
    Parameters.notNull("scope", scope); //NOI18N
    Parameters.notNull("convertor", convertor); //NOI18N
    Parameters.notNull("result", result);   //NOI18N
    final Pair<Convertor<? super Document, T>,Index> ctu = indexPath.getPatch(convertor);
    try {
        final String binaryName = SourceUtils.getJVMSignature(element)[0];
        final ElementKind kind = element.getKind();
        if (kind == ElementKind.PACKAGE) {
            IndexManager.priorityAccess(() -> {
                final Query q = QueryUtil.scopeFilter(
                        QueryUtil.createPackageUsagesQuery(binaryName,usageType,Occur.SHOULD),
                        scope);
                if (q != null) {
                    index.query(result, ctu.first(), DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), q);
                    if (ctu.second() != null) {
                        ctu.second().query(result, convertor, DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), q);
                    }
                }
                return null;
            });
        } else if (kind.isClass() ||
                   kind.isInterface() ||
                   kind == ElementKind.OTHER) {
            if (BinaryAnalyser.OBJECT.equals(binaryName)) {
                getDeclaredElements(
                    "", //NOI18N
                    ClassIndex.NameKind.PREFIX,
                    scope,
                    DocumentUtil.declaredTypesFieldSelector(false, false),
                    convertor,
                    result);
            } else {
                IndexManager.priorityAccess(() -> {
                    final Query usagesQuery = QueryUtil.scopeFilter(
                            QueryUtil.createUsagesQuery(binaryName, usageType, Occur.SHOULD),
                            scope);
                    if (usagesQuery != null) {
                        index.query(result, ctu.first(), DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), usagesQuery);
                        if (ctu.second() != null) {
                            ctu.second().query(result, convertor, DocumentUtil.declaredTypesFieldSelector(false, false), cancel.get(), usagesQuery);
                        }
                    }
                    return null;
                });
            }
        } else {
            throw new IllegalArgumentException(element.toString());
        }
    } catch (IOException ioe) {
        this.<Void,IOException>handleException(null, ioe, root);
    }
}
 
Example 19
Source File: ClassName.java    From JReFrameworker with MIT License 4 votes vote down vote up
private static PackageElement getPackage(Element type) {
  while (type.getKind() != ElementKind.PACKAGE) {
    type = type.getEnclosingElement();
  }
  return (PackageElement) type;
}
 
Example 20
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public int compare(Object o1, Object o2) {
    if (o1 == o2)
        return 0;
    
    boolean isStatic1 = false;
    StringBuilder sb1 = new StringBuilder();
    if (o1 instanceof ImportTree) {
        isStatic1 = ((ImportTree)o1).isStatic();
        sb1.append(((ImportTree)o1).getQualifiedIdentifier().toString());
    } else if (o1 instanceof Element) {
        Element e1 = (Element)o1;
        if (e1.getKind().isField() || e1.getKind() == ElementKind.METHOD) {
            sb1.append('.').append(e1.getSimpleName());
            e1 = e1.getEnclosingElement();
            isStatic1 = true;
        }
        if (e1.getKind().isClass() || e1.getKind().isInterface()) {
            sb1.insert(0, ((TypeElement)e1).getQualifiedName());
        } else if (e1.getKind() == ElementKind.PACKAGE) {
            sb1.insert(0, ((PackageElement)e1).getQualifiedName());
        }
    }
    String s1 = sb1.toString();
        
    boolean isStatic2 = false;
    StringBuilder sb2 = new StringBuilder();
    if (o2 instanceof ImportTree) {
        isStatic2 = ((ImportTree)o2).isStatic();
        sb2.append(((ImportTree)o2).getQualifiedIdentifier().toString());
    } else if (o2 instanceof Element) {
        Element e2 = (Element)o2;
        if (e2.getKind().isField() || e2.getKind() == ElementKind.METHOD) {
            sb2.append('.').append(e2.getSimpleName());
            e2 = e2.getEnclosingElement();
            isStatic2 = true;
        }
        if (e2.getKind().isClass() || e2.getKind().isInterface()) {
            sb2.insert(0, ((TypeElement)e2).getQualifiedName());
        } else if (e2.getKind() == ElementKind.PACKAGE) {
            sb2.insert(0, ((PackageElement)e2).getQualifiedName());
        }
    }
    String s2 = sb2.toString();

    int bal = groups.getGroupId(s1, isStatic1) - groups.getGroupId(s2, isStatic2);

    return bal == 0 ? s1.compareTo(s2) : bal;
}