Java Code Examples for com.sun.source.tree.ImportTree#isStatic()

The following examples show how to use com.sun.source.tree.ImportTree#isStatic() . 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: FindLocalUsagesQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Stack<Tree> p) {
    if (node.isStatic() && toFind.getModifiers().contains(Modifier.STATIC)) {
        Tree qualIdent = node.getQualifiedIdentifier();
        if (qualIdent.getKind() == Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree) qualIdent;
            if (toFind.getSimpleName().contentEquals(mst.getIdentifier())) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), mst.getExpression()));
                if (el != null && el.equals(toFind.getEnclosingElement())) {
                    Token<JavaTokenId> t = Utilities.getToken(info, doc, new TreePath(getCurrentPath(), mst));
                    if (t != null)
                        usages.add(t);
                }
            }
        }
    }
    return super.visitImport(node, p);
}
 
Example 2
Source File: UnusedImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void handleUnresolvableImports(Element decl,
        boolean methodInvocation, boolean removeStarImports) {
    Name simpleName = decl.getSimpleName();
    if (simpleName != null) {
        Collection<ImportTree> imps = simpleName2UnresolvableImports.get(simpleName.toString());

        if (imps != null) {
            for (ImportTree imp : imps) {
                if (!methodInvocation || imp.isStatic()) {
                    import2Highlight.remove(imp);
                }
            }
        } else {
            if (removeStarImports) {
                //TODO: explain
                for (ImportTree unresolvable : unresolvablePackageImports) {
                    if (!methodInvocation || unresolvable.isStatic()) {
                        import2Highlight.remove(unresolvable);
                    }
                }
            }
        }
    }
}
 
Example 3
Source File: FindLocalUsagesQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Void p) {
    if (node.isStatic() && toFind.getModifiers().contains(Modifier.STATIC)) {
        Tree qualIdent = node.getQualifiedIdentifier();
        if (qualIdent.getKind() == Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree) qualIdent;
            if (toFind.getSimpleName().contentEquals(mst.getIdentifier())) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), mst.getExpression()));
                if (el != null && el.equals(toFind.getEnclosingElement())) {
                    try {
                        int[] span = treeUtils.findNameSpan(mst);
                        if(span != null) {
                            MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                            usages.add(region);
                        }
                    } catch (BadLocationException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            }
        }
    }
    return super.visitImport(node, p);
}
 
Example 4
Source File: Imports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_Imports_EXCLUDED", description = "#DESC_Imports_EXCLUDED", category="imports", id="Imports_EXCLUDED", options=Options.QUERY)
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription exlucded(HintContext ctx) throws IOException {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
    String pkg = ms.getExpression().toString();
    String klass = ms.getIdentifier().toString();
    String exp = pkg + "." + (!klass.equals("*") ? klass : ""); //NOI18N
    if (Utilities.isExcluded(exp)) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_EXCLUDED"));
    }

    return null;
}
 
Example 5
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("TreeToString")
@Override
public Description matchImport(ImportTree importTree, VisitorState visitorState) {
  if (importTree.isStatic()) {
    Tree importIdentifier = importTree.getQualifiedIdentifier();
    if (importIdentifier.getKind().equals(Kind.MEMBER_SELECT)) {
      MemberSelectTree memberSelectTree = (MemberSelectTree) importIdentifier;
      if (memberSelectTree.getIdentifier().toString().endsWith(xpFlagName)
          || (treatmentGroupsEnum != null
              && memberSelectTree.getExpression().toString().startsWith(treatmentGroupsEnum))) {
        return buildDescription(importTree)
            .addFix(SuggestedFix.replace(importTree, "", 0, 1))
            .build();
      } else if (treatmentGroup.length() > 0 && treatmentGroupsEnum == null) {
        // Check if this import is for values in the same enum that includes the treatmentGroup
        Symbol importSymbol = ASTHelpers.getSymbol(memberSelectTree.getExpression());
        if (importSymbol.getKind().equals(ElementKind.ENUM)
            && isTreatmentGroupEnum((Symbol.ClassSymbol) importSymbol)) {
          treatmentGroupsEnum = ((Symbol.ClassSymbol) importSymbol).fullname.toString();
          return buildDescription(importTree)
              .addFix(SuggestedFix.replace(importTree, "", 0, 1))
              .build();
        }
      }
    }
  }
  return Description.NO_MATCH;
}
 
Example 6
Source File: ImportsTrackerTestHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
private static void handleImport(Trees trees, ImportsTracker imports, TreePath importTreePath) {
  ImportTree importTree = (ImportTree) importTreePath.getLeaf();
  MemberSelectTree importedExpression = (MemberSelectTree) importTree.getQualifiedIdentifier();
  TreePath importedExpressionPath = new TreePath(importTreePath, importedExpression);
  Name simpleName = importedExpression.getIdentifier();
  boolean isStarImport = simpleName.contentEquals("*");

  if (!isStarImport && !importTree.isStatic()) {
    TypeElement importedType = (TypeElement) trees.getElement(importedExpressionPath);
    imports.importType(importedType, importedExpressionPath);
  } else {
    ExpressionTree containingElementExpression = importedExpression.getExpression();
    TreePath containingElementExpressionPath =
        new TreePath(importedExpressionPath, containingElementExpression);
    QualifiedNameable containingElement =
        (QualifiedNameable) trees.getElement(containingElementExpressionPath);

    if (importTree.isStatic()) {
      TypeElement containingType = (TypeElement) containingElement;
      if (isStarImport) {
        imports.importStaticMembers((TypeElement) containingElement);
      } else {
        imports.importStatic(containingType, simpleName);
      }
    } else {
      // Normal star import
      imports.importMembers(containingElement, containingElementExpressionPath);
    }
  }
}
 
Example 7
Source File: JavacJ2ObjCIncompatibleStripper.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Void aVoid) {
  String name = getLastComponent(node.getQualifiedIdentifier());
  if (node.isStatic()) {
    unusedStaticImports.put(name, node);
  } else {
    unusedImports.put(name, node);
  }
  return null;
}
 
Example 8
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Void unused) {
  sync(node);
  token("import");
  builder.space();
  if (node.isStatic()) {
    token("static");
    builder.space();
  }
  visitName(node.getQualifiedIdentifier());
  token(";");
  // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed
  dropEmptyDeclarations();
  return null;
}
 
Example 9
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Void unused) {
    sync(node);
    token("import");
    builder.space();
    if (node.isStatic()) {
        token("static");
        builder.space();
    }
    visitName(node.getQualifiedIdentifier());
    token(";");
    // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed
    dropEmptyDeclarations();
    return null;
}
 
Example 10
Source File: StaticImport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isStaticallyImported(CompilationInfo info, String fqn) {
    for (ImportTree i : info.getCompilationUnit().getImports()) {
        if (!i.isStatic()) {
            continue;
        }
        String q = i.getQualifiedIdentifier().toString();
        if (q.endsWith(".*") && fqn.startsWith(q.substring(0, q.length() - 1))) { //NOI18N
            return true;
        }
        if (q.equals(fqn)) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: StaticImport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param info
 * @param simpleName of static method.
 * @return true if a static import exists with the same simple name.
 * Caveat, expect false positives on protected and default visibility methods from wildcard static imports.
 */
private static boolean hasStaticImportSimpleNameClash(CompilationInfo info, String simpleName) {
    for (ImportTree i : info.getCompilationUnit().getImports()) {
        if (!i.isStatic()) {
            continue;
        }
        String q = i.getQualifiedIdentifier().toString();
        if (q.endsWith(".*")) { //NOI18N
            TypeElement ie = info.getElements().getTypeElement(q.substring(0, q.length() - 2));
            if (ie == null) {
                continue;
            }
            for (Element enclosed : ie.getEnclosedElements()) {
                Set<Modifier> modifiers = enclosed.getModifiers();
                if (enclosed.getKind() != ElementKind.METHOD || !modifiers.contains(Modifier.STATIC) || modifiers.contains(Modifier.PRIVATE)) {
                    continue;
                }
                String sn1 = enclosed.getSimpleName().toString();
                if (simpleName.equals(sn1)) {
                    return true;
                }
            }
        } else {
            int endIndex = q.lastIndexOf("."); //NOI18N
            if (endIndex == -1 || endIndex >= q.length() - 1) {
                continue;
            }
            if (q.substring(endIndex).equals(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 12
Source File: Imports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<TreePathHandle> getAllImportsOfKind(CompilationInfo ci, ImportHintKind kind) {
    //allow only default and samepackage
    assert (kind == ImportHintKind.DEFAULT_PACKAGE || kind == ImportHintKind.SAME_PACKAGE);

    CompilationUnitTree cut = ci.getCompilationUnit();
    TreePath topLevel = new TreePath(cut);
    List<TreePathHandle> result = new ArrayList<TreePathHandle>(3);

    List<? extends ImportTree> imports = cut.getImports();
    for (ImportTree it : imports) {
        if (it.isStatic()) {
            continue; // XXX
        }
        if (it.getQualifiedIdentifier() instanceof MemberSelectTree) {
            MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
            if (kind == ImportHintKind.DEFAULT_PACKAGE) {
                if (ms.getExpression().toString().equals(DEFAULT_PACKAGE)) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
            if (kind == ImportHintKind.SAME_PACKAGE) {
                ExpressionTree packageName = cut.getPackageName();
                if (packageName != null &&
                    ms.getExpression().toString().equals(packageName.toString())) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
        }
    }
    return result;
}
 
Example 13
Source File: Imports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_Imports_STAR", description = "#DESC_Imports_STAR", category="imports", id="Imports_STAR", enabled=false, options=Options.QUERY, suppressWarnings={"", "OnDemandImport"})
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription starImport(HintContext ctx) {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();

    if (!"*".equals(ms.getIdentifier().toString())) return null;

    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_STAR"));
}
 
Example 14
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitImport(ImportTree node, Void unused) {
    sync(node);
    token("import");
    builder.space();
    if (node.isStatic()) {
        token("static");
        builder.space();
    }
    visitName(node.getQualifiedIdentifier());
    token(";");
    // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed
    dropEmptyDeclarations();
    return null;
}
 
Example 15
Source File: OrganizeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Performs 'organize imports' in two modes. If 'addImports' is null, it optimizes imports according to coding style.
 * However if addImports is not null && not empty, it will add the elements in addImports, and reorder the set
 * of import statements, but will not remove unused imports.
 * Combination of bulk + addImports is not tested.
 * 
 * @param copy working copy to change
 * @param addImports if not null, just adds and reorders imports. If null, performs optimization
 * @param isBulkMode called from batch processing
 * @throws IllegalStateException 
 */
public static void doOrganizeImports(WorkingCopy copy, Set<Element> addImports, boolean isBulkMode) throws IllegalStateException {
    CompilationUnitTree cu = copy.getCompilationUnit();
    List<? extends ImportTree> imports = cu.getImports();
    if (imports.isEmpty()) {
        if (addImports == null) {
            return;
        }
    } else if (addImports == null) {
        // check diag code only if in the 'optimize all' mode.
        List<Diagnostic> diags = copy.getDiagnostics();
        if (!diags.isEmpty()) {
            SourcePositions sp = copy.getTrees().getSourcePositions();
            long startPos = sp.getStartPosition(cu, imports.get(0));
            long endPos = sp.getEndPosition(cu, imports.get(imports.size() - 1));
            for (Diagnostic d : diags) {
                if (startPos <= d.getPosition() && d.getPosition() <= endPos) {
                    if (ERROR_CODE.contentEquals(d.getCode()))
                        return;
                }
            }
        }
    }
    final CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    Set<Element> starImports = new HashSet<Element>();
    Set<Element> staticStarImports = new HashSet<Element>();
    Set<Element> toImport = getUsedElements(copy, cu, starImports, staticStarImports);
    List<ImportTree> imps = new LinkedList<ImportTree>();  
    TreeMaker maker = copy.getTreeMaker();
    
    if (addImports != null) {
        // copy over all imports to be added + existing imports.
        toImport.addAll(addImports);
        imps.addAll(cu.getImports());
    } else if (!toImport.isEmpty() || isBulkMode) {
        // track import star import scopes, so only one star import/scope appears in imps - #251977
        Set<Element> starImportScopes = new HashSet<>();
        Trees trees = copy.getTrees();
        for (ImportTree importTree : cu.getImports()) {
            Tree qualIdent = importTree.getQualifiedIdentifier();
            if (qualIdent.getKind() == Tree.Kind.MEMBER_SELECT && "*".contentEquals(((MemberSelectTree)qualIdent).getIdentifier())) {
                ImportTree imp = null;
                Element importedScope = trees.getElement(TreePath.getPath(cu, ((MemberSelectTree)qualIdent).getExpression()));
                
                if (importTree.isStatic()) {
                    if (staticStarImports != null && 
                        staticStarImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, true);
                    }
                } else {
                    if (starImports != null && 
                        starImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, false);
                    }
                }
                if (imp != null) {
                    starImportScopes.add(importedScope);
                    imps.add(imp);
                }
            }
        }
    } else {
        return;
    }
    if (!imps.isEmpty()) {
        Collections.sort(imps, new Comparator<ImportTree>() {

            private CodeStyle.ImportGroups groups = cs.getImportGroups();

            @Override
            public int compare(ImportTree o1, ImportTree o2) {
                if (o1 == o2)
                    return 0;
                String s1 = o1.getQualifiedIdentifier().toString();
                String s2 = o2.getQualifiedIdentifier().toString();
                int bal = groups.getGroupId(s1, o1.isStatic()) - groups.getGroupId(s2, o2.isStatic());
                return bal == 0 ? s1.compareTo(s2) : bal;
            }
        });
    }
    CompilationUnitTree cut = maker.CompilationUnit(cu.getPackageAnnotations(), cu.getPackageName(), imps, cu.getTypeDecls(), cu.getSourceFile());
    ((JCCompilationUnit)cut).packge = ((JCCompilationUnit)cu).packge;
    if (starImports != null || staticStarImports != null) {
        ((JCCompilationUnit)cut).starImportScope = ((JCCompilationUnit)cu).starImportScope;
    }
    CompilationUnitTree ncu = toImport.isEmpty() ? cut : GeneratorUtilities.get(copy).addImports(cut, toImport);
    copy.rewrite(cu, ncu);
}
 
Example 16
Source File: UseNbBundleMessages.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
            TreeMaker make = wc.getTreeMaker();
            if (treePath.getLeaf().getKind() == Kind.METHOD_INVOCATION) {
                MethodInvocationTree mit = (MethodInvocationTree) treePath.getLeaf();
                CompilationUnitTree cut = wc.getCompilationUnit();
                boolean imported = false;
                String importBundleStar = cut.getPackageName() + ".Bundle.*";
                for (ImportTree it : cut.getImports()) {
                    if (it.isStatic() && it.getQualifiedIdentifier().toString().equals(importBundleStar)) {
                        imported = true;
                        break;
                    }
                }
                if (!imported) {
                    wc.rewrite(cut, make.addCompUnitImport(cut, make.Import(make.Identifier(importBundleStar), true)));
                }
                List<? extends ExpressionTree> args = mit.getArguments();
                List<? extends ExpressionTree> params;
                if (args.size() == 3 && args.get(2).getKind() == Kind.NEW_ARRAY) {
                    params = ((NewArrayTree) args.get(2)).getInitializers();
                } else {
                    params = args.subList(2, args.size());
                }
                wc.rewrite(mit, make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.Identifier(toIdentifier(key)), params));
            } // else annotation value, nothing to change
            if (!isAlreadyRegistered) {
                EditableProperties ep = new EditableProperties(true);
                InputStream is = ctx.getResourceContent(bundleProperties);
                try {
                    ep.load(is);
                } finally {
                    is.close();
                }
                List<ExpressionTree> lines = new ArrayList<ExpressionTree>();
                for (String comment : ep.getComment(key)) {
                    lines.add(make.Literal(comment));
                }
                lines.add(make.Literal(key + '=' + ep.remove(key)));
                TypeElement nbBundleMessages = wc.getElements().getTypeElement("org.openide.util.NbBundle.Messages");
                if (nbBundleMessages == null) {
                    throw new IllegalArgumentException("cannot resolve org.openide.util.NbBundle.Messages");
                }
                GeneratorUtilities gu = GeneratorUtilities.get(wc);
                Tree enclosing = findEnclosingElement(wc, treePath);
                Tree modifiers;
                Tree nueModifiers;
                ExpressionTree[] linesA = lines.toArray(new ExpressionTree[lines.size()]);
                switch (enclosing.getKind()) {
                case METHOD:
                    modifiers = wc.resolveRewriteTarget(((MethodTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                case VARIABLE:
                    modifiers = wc.resolveRewriteTarget(((VariableTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                case COMPILATION_UNIT:
                    modifiers = wc.resolveRewriteTarget(enclosing);
                    nueModifiers = gu.appendToAnnotationValue((CompilationUnitTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                default:
                    modifiers = wc.resolveRewriteTarget(((ClassTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                }
                wc.rewrite(modifiers, nueModifiers);
            // XXX remove NbBundle import if now unused
            OutputStream os = ctx.getResourceOutput(bundleProperties);
            try {
                ep.store(os);
            } finally {
                os.close();
            }
        }
    // XXX after JavaFix rewrite, Savable.save (on DataObject.find(src)) no longer works (JG13 again)
}
 
Example 17
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
private SrcClass makeSrcClass( String fqn, SrcClass enclosing, Symbol.ClassSymbol classSymbol, CompilationUnitTree compilationUnit, BasicJavacTask javacTask, IModule module, JavaFileManager.Location location, DiagnosticListener<JavaFileObject> errorHandler, boolean withMembers )
  {
    SrcClass srcClass;
    if( enclosing == null )
    {
      srcClass = new SrcClass( fqn, SrcClass.Kind.from( classSymbol.getKind() ), location, module, errorHandler )
        .modifiers( classSymbol.getModifiers() );
    }
    else
    {
      srcClass = new SrcClass( fqn, enclosing, SrcClass.Kind.from( classSymbol.getKind() ) )
        .modifiers( classSymbol.getModifiers() );
    }
    if( classSymbol.getEnclosingElement() instanceof Symbol.PackageSymbol && compilationUnit != null )
    {
      for( ImportTree imp: compilationUnit.getImports() )
      {
        if( imp.isStatic() )
        {
          srcClass.addStaticImport( imp.getQualifiedIdentifier().toString() );
        }
        else
        {
          srcClass.addImport( imp.getQualifiedIdentifier().toString() );
        }
      }
    }
    addAnnotations( srcClass, classSymbol );
    for( Symbol.TypeVariableSymbol typeVar: classSymbol.getTypeParameters() )
    {
      srcClass.addTypeVar( makeTypeVarType( typeVar ) );
    }
    Type superclass = classSymbol.getSuperclass();
    if( !(superclass instanceof NoType) )
    {
      srcClass.superClass( makeNestedType( superclass ) );
    }
    for( Type iface: classSymbol.getInterfaces() )
    {
      srcClass.addInterface( makeNestedType( iface ) );
    }
    if( withMembers )
    {
      java.util.List<Symbol> members = classSymbol.getEnclosedElements();
      for( Symbol sym: members )
      {
// include private members because:
// 1. @Jailbreak can expose private members
// 2. Compiler error messages are better when referencing an inaccessible method vs. a non-existent one
//        long modifiers = SrcAnnotated.modifiersFrom( sym.getModifiers() );
//        if( Modifier.isPrivate( (int)modifiers ) )
//        {
//          continue;
//        }

        if( sym instanceof Symbol.ClassSymbol )
        {
          addInnerClass( module, srcClass, sym, javacTask );
        }
        else if( sym instanceof Symbol.VarSymbol )
        {
          addField( srcClass, sym );
        }
        else if( sym instanceof Symbol.MethodSymbol )
        {
          if( !isEnumMethod( sym ) )
          {
            addMethod( module, srcClass, (Symbol.MethodSymbol)sym, javacTask );
          }
        }
      }

      addDefaultCtorForEnum( classSymbol, srcClass, members );
    }
    return srcClass;
  }
 
Example 18
Source File: TreeAnalyzer.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
  CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();

  long firstLine = 0;

  for (ImportTree imp : cut.getImports()) {
    JCTree.JCImport jcImport = (JCTree.JCImport) imp;
    int startPos = jcImport.getPreferredPosition();
    int endPos = jcImport.getEndPosition(endPosTable);
    Range range = Range.create(src, startPos + 1, endPos);
    firstLine = range.begin.line;

    String importClass = imp.getQualifiedIdentifier().toString();
    String simpleName = ClassNameUtils.getSimpleName(importClass);

    if (imp.isStatic()) {
      // TODO static asterisk
      Tree tree = imp.getQualifiedIdentifier();
      if (tree instanceof JCTree.JCFieldAccess) {
        JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
        com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
        JCTree.JCExpression expression = fieldAccess.getExpression();
        String methodName = name.toString();
        String decClazz = expression.toString();
        src.addStaticImport(methodName, decClazz);
      } else {
        log.warn("Not impl");
      }
    } else {
      if (simpleName.equals("*")) {
        // wild
        for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
          src.addImport(s);
        }
      } else {
        src.addImport(importClass);
      }
    }
  }
  src.setClassStartLine(firstLine);
}
 
Example 19
Source File: UnusedImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitImport(ImportTree tree, Void d) {
    if (parseErrorInImport(tree)) {
        return super.visitImport(tree, null);
    }
    if (tree.getQualifiedIdentifier() == null ||
        tree.getQualifiedIdentifier().getKind() != Tree.Kind.MEMBER_SELECT) {
        return super.visitImport(tree, null);
    }
    MemberSelectTree qualIdent = (MemberSelectTree) tree.getQualifiedIdentifier();
    boolean assign = false;
    
    // static imports and star imports only use the qualifier part
    boolean star = isStar(tree);
    TreePath tp = tree.isStatic() || star ?
            new TreePath(new TreePath(getCurrentPath(), qualIdent), qualIdent.getExpression()) :
            new TreePath(getCurrentPath(), tree.getQualifiedIdentifier());
    Element decl = info.getTrees().getElement(tp);
    
    import2Highlight.put(tree, getCurrentPath());
    if (decl != null && !isErroneous(decl)) {
        if (!tree.isStatic()) {
            if (star) {
                List<TypeElement> types = ElementFilter.typesIn(decl.getEnclosedElements());
                for (TypeElement te : types) {
                    assign = true;
                    if (!element2Import.containsKey(te)) {
                        element2Import.put(te, tree);
                    }
                }
            } else {
                element2Import.put(decl, tree);
                importedBySingleImport.add(decl);
            }
        } else if (decl.getKind().isClass() || decl.getKind().isInterface()) {
            Name simpleName = star ? null : qualIdent.getIdentifier();

            for (Element e : info.getElements().getAllMembers((TypeElement) decl)) {
                if (!e.getModifiers().contains(Modifier.STATIC)) continue;
                if (simpleName != null && !e.getSimpleName().equals(simpleName)) {
                    continue;
                }
                if (!star || !element2Import.containsKey(e)) {
                    element2Import.put(e, tree);
                }
                assign = true;
            }
        }
    }
    if (!assign) {
        if (!tree.isStatic() && star) {
            unresolvablePackageImports.add(tree);
        } else {
            addUnresolvableImport(qualIdent.getIdentifier(), tree);
        }
    }
    super.visitImport(tree, null);
    return null;
}
 
Example 20
Source File: ImportAnalysis2.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addImport(ImportTree imp) {
    String fqn = getFQN(imp);

    if (!imp.isStatic()) {
        Element resolve = overlay.resolve(model, elements, fqn);

        if (resolve != null) {
            imported.add(resolve);
            simpleNames2Elements.put(resolve.getSimpleName().toString(), resolve);
        } else {
            //.*?:
            if (fqn.endsWith(".*")) {
                fqn = fqn.substring(0, fqn.length() - 2);

                List<TypeElement> classes = Collections.<TypeElement>emptyList();
                Element clazz = overlay.resolve(model, elements, fqn);

                if (clazz != null) {
                    classes = ElementFilter.typesIn(clazz.getEnclosedElements());
                }

                for (TypeElement te : classes) {
                    imported.add(te);
                    simpleNames2Elements.put(te.getSimpleName().toString(), te);
                }
            } else {
                //cannot resolve - the imports will probably not work correctly...
            }
        }
    } else {
        int dot = fqn.lastIndexOf('.');

        if (dot != (-1)) {
            String className = fqn.substring(0, dot);
            String memberName = fqn.substring(dot + 1);
            boolean isStarred = "*".equals(memberName);
            Element resolved = overlay.resolve(model, elements, className);

            if (resolved != null) {
                boolean added = false;
                for (Element e : resolved.getEnclosedElements()) {
                    if (!e.getModifiers().contains(Modifier.STATIC)) {
                        continue;
                    }
                    if (isStarred || memberName.contains(e.getSimpleName().toString())) {
                        imported.add(e);
                        simpleNames2Elements.put(e.getSimpleName().toString(), e);
                    }
                }
            } else {
                //cannot resolve - the imports will probably not work correctly...
            }
        } else {
            //no dot?
        }
    }
}