Java Code Examples for com.sun.source.tree.Tree.Kind#IMPORT

The following examples show how to use com.sun.source.tree.Tree.Kind#IMPORT . 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: 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 2
Source File: ImportClass.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public FixImport(FileObject file, String fqn, ElementHandle<Element> toImport, String sortText, boolean isValid, CompilationInfo info, @NullAllowed TreePath replacePath, @NullAllowed String replaceSuffix, 
        boolean doOrganize) {
    super(file, fqn, toImport, sortText, isValid);
    if (replacePath != null) {
        this.replacePathHandle = TreePathHandle.create(replacePath, info);
        this.suffix = replaceSuffix;
        while (replacePath != null && replacePath.getLeaf().getKind() != Kind.IMPORT) {
            replacePath = replacePath.getParentPath();
        }
        this.statik = replacePath != null ? ((ImportTree) replacePath.getLeaf()).isStatic() : false;
    } else {
        this.replacePathHandle = null;
        this.suffix = null;
        this.statik = false;
    }
    this.doOrganize = doOrganize;
}
 
Example 3
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 4
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static CompilationUnit convertCompilationUnit(
    Options options, JavacEnvironment env, CompilationUnitTree javacUnit) {
  String sourceFilePath = getPath(javacUnit.getSourceFile());
  try {
    TreeConverter converter = new TreeConverter(javacUnit, env);
    JavaFileObject sourceFile = javacUnit.getSourceFile();
    String source = sourceFile.getCharContent(false).toString();
    String mainTypeName = FileUtil.getMainTypeName(sourceFile);
    TranslationEnvironment translationEnv = new TranslationEnvironment(options, env);
    converter.newUnit = new CompilationUnit(translationEnv, sourceFilePath, mainTypeName, source);
    TreePath path = new TreePath(javacUnit);
    converter.newUnit.setPackage(converter.convertPackage(path));
    for (Tree type : javacUnit.getTypeDecls()) {
      if (type.getKind() == Kind.IMPORT) {
        continue;
      }
      TreeNode newNode = converter.convert(type, path);
      if (newNode.getKind() != TreeNode.Kind.EMPTY_STATEMENT) {
        converter.newUnit.addType((AbstractTypeDeclaration) newNode);
      }
    }
    addOcniComments(converter.newUnit, options.jsniWarnings());

    // Enable this to debug tree conversion issues, otherwise let
    // TranslationProcessor.applyMutations() handle verification.
    // converter.newUnit.validate();

    return converter.newUnit;
  } catch (Throwable e) {
    ErrorUtil.fatalError(e, sourceFilePath);
    return null;
  }
}
 
Example 5
Source File: FindUsagesVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void addIfMatch(TreePath path, Tree tree, Element elementToFind) {
    if(isCancelled.get()) {
        return;
    }
    if (JavaPluginUtils.isSyntheticPath(workingCopy, path)) {
        if (ElementKind.CONSTRUCTOR != elementToFind.getKind()
                || tree.getKind() != Tree.Kind.IDENTIFIER
                || !"super".contentEquals(((IdentifierTree) tree).getName())) { // NOI18N
            // do not skip synthetic usages of constructor
            return;
        }
    }
    Trees trees = workingCopy.getTrees();
    Element el = trees.getElement(path);
    if (el == null) {
        path = path.getParentPath();
        if (path != null && path.getLeaf().getKind() == Kind.IMPORT) {
            ImportTree impTree = (ImportTree) path.getLeaf();
            if (!impTree.isStatic()) {
                return;
            }
            Tree idTree = impTree.getQualifiedIdentifier();
            if (idTree.getKind() != Kind.MEMBER_SELECT) {
                return;
            }
            final Name id = ((MemberSelectTree) idTree).getIdentifier();
            if (id.contentEquals("*")) {
                return;
            }
            Tree classTree = ((MemberSelectTree) idTree).getExpression();
            path = trees.getPath(workingCopy.getCompilationUnit(), classTree);
            el = trees.getElement(path);
            if (el == null) {
                return;
            }
            Iterator iter = workingCopy.getElementUtilities().getMembers(el.asType(), new ElementUtilities.ElementAcceptor() {
                @Override
                public boolean accept(Element e, TypeMirror type) {
                    return id.equals(e.getSimpleName());
                }
            }).iterator();
            if (iter.hasNext()) {
                el = (Element) iter.next();
            }
            if (iter.hasNext()) {
                return;
            }
        } else {
            return;
        }
    }
    if (elementToFind != null && elementToFind.getKind() == ElementKind.METHOD && el.getKind() == ElementKind.METHOD) {
        for (ExecutableElement executableElement : methods) {
            if (el.equals(executableElement) 
                    || workingCopy.getElements().overrides((ExecutableElement) el,
                    executableElement, (TypeElement) elementToFind.getEnclosingElement())) {
                addUsage(path);
            }
        }
    } else if (el.equals(elementToFind)) {
        final ElementKind kind = elementToFind.getKind();
        if(kind.isField() || kind == ElementKind.LOCAL_VARIABLE || kind == ElementKind.RESOURCE_VARIABLE || kind == ElementKind.PARAMETER) {
            JavaWhereUsedFilters.ReadWrite access;
            Element collectionElement = workingCopy.getElementUtilities().findElement("java.util.Collection"); //NOI18N
            Element mapElement = workingCopy.getElementUtilities().findElement("java.util.Map"); //NOI18N
            if(collectionElement != null &&
                    workingCopy.getTypes().isSubtype(
                            workingCopy.getTypes().erasure(el.asType()),
                            workingCopy.getTypes().erasure(collectionElement.asType()))) {
                access = analyzeCollectionAccess(path);
            } else if(mapElement != null &&
                    workingCopy.getTypes().isSubtype(
                            workingCopy.getTypes().erasure(el.asType()),
                            workingCopy.getTypes().erasure(mapElement.asType()))) {
                access = analyzeCollectionAccess(path);
            } else {
                access = analyzeVarAccess(path, elementToFind, tree);
            }
            addUsage(path, access);
        } else {
            addUsage(path);
        }
    }
}
 
Example 6
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private ImportTree findImport(TreePath tp) {
    while (tp != null && tp.getLeaf().getKind() != Kind.IMPORT) {
        tp = tp.getParentPath();
    }
    return tp != null ? (ImportTree)tp.getLeaf() : null;
}
 
Example 7
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private List<Documentation> documentationImpl(String code, int cursor, boolean computeJavadoc) {
    code = code.substring(0, cursor);
    if (code.trim().isEmpty()) { //TODO: comment handling
        code += ";";
    }

    if (guessKind(code) == Kind.IMPORT)
        return Collections.emptyList();

    OuterWrap codeWrap = proc.outerMap.wrapInTrialClass(Wrap.methodWrap(code));
    AnalyzeTask at = proc.taskFactory.new AnalyzeTask(codeWrap, keepParameterNames);
    SourcePositions sp = at.trees().getSourcePositions();
    CompilationUnitTree topLevel = at.firstCuTree();
    TreePath tp = pathFor(topLevel, sp, codeWrap.snippetIndexToWrapIndex(cursor));

    if (tp == null)
        return Collections.emptyList();

    TreePath prevPath = null;
    while (tp != null && tp.getLeaf().getKind() != Kind.METHOD_INVOCATION &&
           tp.getLeaf().getKind() != Kind.NEW_CLASS && tp.getLeaf().getKind() != Kind.IDENTIFIER &&
           tp.getLeaf().getKind() != Kind.MEMBER_SELECT) {
        prevPath = tp;
        tp = tp.getParentPath();
    }

    if (tp == null)
        return Collections.emptyList();

    Stream<Element> elements;
    Iterable<Pair<ExecutableElement, ExecutableType>> candidates;
    List<? extends ExpressionTree> arguments;

    if (tp.getLeaf().getKind() == Kind.METHOD_INVOCATION || tp.getLeaf().getKind() == Kind.NEW_CLASS) {
        if (tp.getLeaf().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) tp.getLeaf();
            candidates = methodCandidates(at, tp);
            arguments = mit.getArguments();
        } else {
            NewClassTree nct = (NewClassTree) tp.getLeaf();
            candidates = newClassCandidates(at, tp);
            arguments = nct.getArguments();
        }

        if (!isEmptyArgumentsContext(arguments)) {
            List<TypeMirror> actuals = computeActualInvocationTypes(at, arguments, prevPath);
            List<TypeMirror> fullActuals = actuals != null ? actuals : Collections.emptyList();

            candidates =
                    this.filterExecutableTypesByArguments(at, candidates, fullActuals)
                        .stream()
                        .filter(method -> parameterType(method.fst, method.snd, fullActuals.size(), true).findAny().isPresent())
                        .collect(Collectors.toList());
        }

        elements = Util.stream(candidates).map(method -> method.fst);
    } else if (tp.getLeaf().getKind() == Kind.IDENTIFIER || tp.getLeaf().getKind() == Kind.MEMBER_SELECT) {
        Element el = at.trees().getElement(tp);

        if (el == null ||
            el.asType().getKind() == TypeKind.ERROR ||
            (el.getKind() == ElementKind.PACKAGE && el.getEnclosedElements().isEmpty())) {
            //erroneous element:
            return Collections.emptyList();
        }

        elements = Stream.of(el);
    } else {
        return Collections.emptyList();
    }

    List<Documentation> result = Collections.emptyList();

    try (JavadocHelper helper = JavadocHelper.create(at.task, findSources())) {
        result = elements.map(el -> constructDocumentation(at, helper, el, computeJavadoc))
                         .filter(Objects::nonNull)
                         .collect(Collectors.toList());
    } catch (IOException ex) {
        proc.debug(ex, "JavadocHelper.close()");
    }

    return result;
}