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

The following examples show how to use com.sun.source.tree.Tree.Kind#MEMBER_SELECT . 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: ImmutableTreeTranslator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Visitor method: Translate a single node.
    *  return type is guaranteed to be the same as the input type
    */
   public <T extends Tree> T translateStable(T tree) {
Tree t2 = translate(tree);
if(t2!=null && t2.getClass()!=tree.getClass()) {
    if(t2.getClass()!=tree.getClass()) {
               //possibly import analysis rewrote QualIdentTree->IdentifierTree or QIT->MemberSelectTree:
               if (   tree.getClass() != QualIdentTree.class
                   || (t2.getKind() != Kind.IDENTIFIER) && (t2.getKind() != Kind.MEMBER_SELECT)) {
                   System.err.println("Rewrite stability problem: got "+t2.getClass()
                       +"\n\t\texpected "+tree.getClass());
                   return tree;
               }
    }
}
return (T)t2;
   }
 
Example 2
Source File: EqualsMethodHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
    if (node.getArguments().isEmpty()) {
        if (node.getMethodSelect().getKind() == Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree) node.getMethodSelect();
            Element e = info.getTrees().getElement(new TreePath(new TreePath(getCurrentPath(), mst), mst.getExpression()));

            if (parameter.equals(e) && mst.getIdentifier().contentEquals("getClass")) { // NOI18N
                throw new Found();
            }
        } else if (node.getMethodSelect().getKind() == Kind.IDENTIFIER) {
            IdentifierTree it = (IdentifierTree) node.getMethodSelect();

            if (it.getName().contentEquals("getClass")) { // NOI18N
                throw new Found();
            }
        }
    }
    
    return super.visitMethodInvocation(node, p);
}
 
Example 3
Source File: FieldEncapsulation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.privateField", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.FieldEncapsulation.privateField", category="encapsulation", suppressWarnings={"AccessingNonPublicFieldOfAnotherObject"}, enabled=false, options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.MEMBER_SELECT)
public static ErrorDescription privateField(final HintContext ctx) {
    assert ctx != null;
    final TreePath tp = ctx.getPath();
    final Element selectElement = ctx.getInfo().getTrees().getElement(tp);
    if (selectElement == null ||
        selectElement.getKind()!= ElementKind.FIELD ||
        !((VariableElement)selectElement).getModifiers().contains(Modifier.PRIVATE)||
        ((VariableElement)selectElement).getModifiers().contains(Modifier.STATIC)) {
        return null;
    }
    final ExpressionTree subSelect = ((MemberSelectTree)tp.getLeaf()).getExpression();
    if ((subSelect.getKind() == Tree.Kind.IDENTIFIER && KW_THIS.contentEquals(((IdentifierTree)subSelect).getName())) ||
        (subSelect.getKind() == Tree.Kind.MEMBER_SELECT && KW_THIS.contentEquals(((MemberSelectTree)subSelect).getIdentifier()))){
        return null;
    }
    final TypeElement selectOwner = getEnclosingClass(tp, ctx.getInfo().getTrees());
    if (selectOwner == null ||
        SourceUtils.getOutermostEnclosingTypeElement(selectElement) != SourceUtils.getOutermostEnclosingTypeElement(selectOwner)) {
        return null;
    }
    SourceUtils.getOutermostEnclosingTypeElement(selectElement);
    return ErrorDescriptionFactory.forName(ctx, tp,
            NbBundle.getMessage(FieldEncapsulation.class, "TXT_OtherPrivateField"));
}
 
Example 4
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 5
Source File: FindUsagesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private JavaWhereUsedFilters.ReadWrite analyzeCollectionAccess(TreePath path) {
    JavaWhereUsedFilters.ReadWrite result = null;
    TreePath parentPath = path.getParentPath();
    Tree parentTree = parentPath.getLeaf();
    Kind parentKind = parentTree.getKind();
    if(parentKind == Kind.MEMBER_SELECT) {
        Element member = workingCopy.getTrees().getElement(parentPath);
        if(member != null && member.getKind() == ElementKind.METHOD) {
            ExecutableElement method = (ExecutableElement) member;
            if (writeMethods.contains(method.getSimpleName().toString())) {
                result = JavaWhereUsedFilters.ReadWrite.WRITE;
            } else if (readMethods.contains(method.getSimpleName().toString())) {
                result = JavaWhereUsedFilters.ReadWrite.READ;
            } else if (readWriteMethods.contains(method.getSimpleName().toString())) {
                result = JavaWhereUsedFilters.ReadWrite.READ_WRITE;
            }
        }
    }
    return result;
}
 
Example 6
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean sameKind(Tree t1, Tree t2) {
    Kind k1 = t1.getKind();
    Kind k2 = t2.getKind();

    if (k1 == k2) {
        return true;
    }

    if (isSingleStatemenBlockAndStatement(t1, t2) || isSingleStatemenBlockAndStatement(t2, t1)) {
        return true;
    }

    if (k2 == Kind.BLOCK && StatementTree.class.isAssignableFrom(k1.asInterface())) {
        BlockTree bt = (BlockTree) t2;

        if (bt.isStatic()) {
            return false;
        }

        switch (bt.getStatements().size()) {
            case 1:
                return true;
            case 2:
                return    isMultistatementWildcardTree(bt.getStatements().get(0))
                       || isMultistatementWildcardTree(bt.getStatements().get(1));
            case 3:
                return    isMultistatementWildcardTree(bt.getStatements().get(0))
                       || isMultistatementWildcardTree(bt.getStatements().get(2));
        }

        return false;
    }

    if (    (k1 != Kind.MEMBER_SELECT && k1 != Kind.IDENTIFIER)
         || (k2 != Kind.MEMBER_SELECT && k2 != Kind.IDENTIFIER)) {
        return false;
    }

    return isPureMemberSelect(t1, true) && isPureMemberSelect(t2, true);
}
 
Example 7
Source File: JavaFixAllImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitImport(ImportTree node, Object d) {
    if (node.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) {
        ExpressionTree exp = ((MemberSelectTree) node.getQualifiedIdentifier()).getExpression();
        if (exp.toString().equals(currentPackage)) {
            imports.add(TreePathHandle.create(getCurrentPath(), info));
        }
    }

    super.visitImport(node, null);
    return null;
}
 
Example 8
Source File: IndexFileParser.java    From annotation-tools with MIT License 5 votes vote down vote up
private static boolean selectsExpression(ASTPath astPath) {
    int n = astPath.size();
    if (--n >= 0) {
        ASTPath.ASTEntry entry = astPath.get(n);
        while (--n >= 0 && entry.getTreeKind() == Kind.MEMBER_SELECT
                && entry.childSelectorIs(ASTPath.EXPRESSION)) {
          entry = astPath.get(n);
        }
        return !isTypeSelector(entry.getChildSelector());
    }
    return false;
}
 
Example 9
Source File: Unbalanced.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind({Kind.IDENTIFIER, Kind.MEMBER_SELECT})
@TriggerOptions(TriggerOptions.PROCESS_GUARDED)
public static ErrorDescription before(HintContext ctx) {
    TreePath tp = ctx.getPath();
    VariableElement var = testElement(ctx);

    if (var == null) return null;

    if (tp.getParentPath().getLeaf().getKind() == Kind.MEMBER_SELECT && tp.getParentPath().getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION) {
        String methodName = ((MemberSelectTree) tp.getParentPath().getLeaf()).getIdentifier().toString();
        if (READ_METHODS.contains(methodName)) {
            if (tp.getParentPath().getParentPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) {
                record(ctx.getInfo(), var, State.READ);
            }
            return null;
        } else if (WRITE_METHODS.contains(methodName)) {
            if (tp.getParentPath().getParentPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) {
                record(ctx.getInfo(), var, State.WRITE, State.READ);
            } else {
                record(ctx.getInfo(), var, State.WRITE);
            }
            return null;
        }
    }

    record(ctx.getInfo(), var, State.WRITE, State.READ);

    return null;
}
 
Example 10
Source File: CallHierarchyTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CompilationController javac) throws Exception {
    TreePath tpath = null;
    Element method = null;
    
    javac.toPhase(JavaSource.Phase.RESOLVED);
    if (tHandle == null) {
        tpath = javac.getTreeUtilities().pathFor(offset);
    } else {
        tpath = tHandle.resolve(javac);
    }
    
    while (tpath != null) {
        Kind kind = tpath.getLeaf().getKind();
        if (kind == Kind.METHOD || kind == Kind.METHOD_INVOCATION || kind == Kind.MEMBER_SELECT || kind == Kind.NEW_CLASS) {
            method = ScanUtils.checkElement(javac, javac.getTrees().getElement(tpath));
            if (RefactoringUtils.isExecutableElement(method)) {
                break;
            }
            method = null;
        }
        tpath = tpath.getParentPath();
    }
    
    if (method != null) {
        if(isCallerGraph && this.searchFromBase) {
            Collection<ExecutableElement> overriddenMethods = JavaRefactoringUtils.getOverriddenMethods((ExecutableElement)method, javac);
            if(!overriddenMethods.isEmpty()) {
                method = overriddenMethods.iterator().next();
            }
        }
        root = Call.createRoot(javac, tpath, method, isCallerGraph);
    }
}
 
Example 11
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isKeyword(Tree tree) {
    if (tree.getKind() == Kind.IDENTIFIER) {
        return keywords.contains(((IdentifierTree) tree).getName().toString());
    }
    if (tree.getKind() == Kind.MEMBER_SELECT) {
        return keywords.contains(((MemberSelectTree) tree).getIdentifier().toString());
    }
    
    return false;
}
 
Example 12
Source File: TreeBackedTypeResolutionSimulator.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean isResolvable() {
  if (location.getLeaf().getKind() == Kind.MEMBER_SELECT) {
    return true;
  } else if (referencedElement.getKind() == ElementKind.PACKAGE) {
    return true;
  }

  TypeElement referencedType = (TypeElement) referencedElement;
  return (imports != null && imports.isSingleTypeImported(referencedType))
      || isTopLevelInReferencingPackage(referencedType);
}
 
Example 13
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Name getSimpleName(Tree t) {
    if (t.getKind() == Kind.IDENTIFIER) {
        return ((IdentifierTree) t).getName();
    }
    if (t.getKind() == Kind.MEMBER_SELECT) {
        return ((MemberSelectTree) t).getIdentifier();
    }

    throw new UnsupportedOperationException();
}
 
Example 14
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 15
Source File: Unbalanced.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Kind.IDENTIFIER, Kind.MEMBER_SELECT})
@TriggerOptions(TriggerOptions.PROCESS_GUARDED)
public static ErrorDescription before(HintContext ctx) {
    VariableElement var = testElement(ctx);

    if (var == null) return null;

    TreePath tp = ctx.getPath();
    
    if (tp.getParentPath().getLeaf().getKind() == Kind.ARRAY_ACCESS) {
        State accessType = State.READ;
        State secondAccess = null;
        Tree access = tp.getParentPath().getLeaf();
        Tree assign = tp.getParentPath().getParentPath().getLeaf();
        
        switch (assign.getKind()) {
            case ASSIGNMENT:
                if (((AssignmentTree) assign).getVariable() == access) {
                    accessType = State.WRITE;
                }
                break;
            case AND_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case LEFT_SHIFT_ASSIGNMENT:
            case MINUS_ASSIGNMENT: case MULTIPLY_ASSIGNMENT: case OR_ASSIGNMENT:
            case PLUS_ASSIGNMENT: case REMAINDER_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT:
            case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: case XOR_ASSIGNMENT:
                if (((CompoundAssignmentTree) assign).getVariable() == access) {
                    secondAccess = State.WRITE;
                }
                break;
            case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: case PREFIX_DECREMENT:
            case PREFIX_INCREMENT:
                secondAccess = State.WRITE;
                break;
        }
        record(ctx.getInfo(), var, accessType);
        if (secondAccess != null) {
            record(ctx.getInfo(), var, secondAccess);
        }
    } else {
        record(ctx.getInfo(), var, State.WRITE, State.READ);
    }

    return null;
}
 
Example 16
Source File: TreeConverter.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private TreeNode convertFieldAccess(MemberSelectTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  String fieldName = node.getIdentifier().toString();
  SourcePosition pos = getPosition(node);
  ExpressionTree selected = node.getExpression();
  TreePath selectedPath = getTreePath(path, selected);
  Element element = getElement(path);
  TypeMirror typeMirror = getTypeMirror(path);
  if (fieldName.equals("this")) {
    return new ThisExpression()
        .setQualifier((Name) convert(selected, path))
        .setTypeMirror(typeMirror);
  }
  if ("super".equals(getMemberName(selected))) {
    SuperFieldAccess newNode =
        new SuperFieldAccess()
            .setVariableElement((VariableElement) element)
            .setTypeMirror(typeMirror);
    if (selected.getKind() == Kind.MEMBER_SELECT) {
      newNode.setQualifier(
          (Name) convert(((MemberSelectTree) selected).getExpression(), selectedPath));
    }
    return newNode;
  }
  if (node.getIdentifier().toString().equals("class")) {
    Type type = convertType(getTypeMirror(selectedPath), pos, false);
    type.setPosition(getPosition(node));
    return new TypeLiteral(typeMirror).setType(type);
  }
  if (selected.getKind() == Kind.IDENTIFIER
      && (!element.getKind().isField() || ElementUtil.isConstant((VariableElement) element))) {
    if (selected.toString().equals("this")) {
      // Just return the constant.
      return new SimpleName(element);
    }
    return new QualifiedName()
        .setName(convertSimpleName(element, typeMirror, pos))
        .setQualifier(
            convertSimpleName(getElement(selectedPath), getTypeMirror(selectedPath), pos))
        .setElement(element);
  }
  if (selected.getKind() == Kind.MEMBER_SELECT) {
    TreeNode newSelected = convertFieldAccess((MemberSelectTree) selected, path).setPosition(pos);
    if (newSelected.getKind() == TreeNode.Kind.QUALIFIED_NAME) {
      return new QualifiedName()
          .setName(convertSimpleName(element, typeMirror, pos))
          .setQualifier((QualifiedName) newSelected)
          .setElement(element);
    }
  }
  if (ElementUtil.isConstant((VariableElement) element)
      && ElementUtil.isStatic(element)
      && !(selected.getKind() == Kind.METHOD_INVOCATION)
      && !(selected.getKind() == Kind.MEMBER_SELECT)
      && !(selected.getKind() == Kind.PARENTHESIZED)) {
    return new QualifiedName()
        .setName(convertSimpleName(element, typeMirror, pos))
        .setQualifier((Name) convert(selected, path))
        .setElement(element);
  }
  return new FieldAccess()
      .setVariableElement((VariableElement) element)
      .setExpression((Expression) convert(selected, path))
      .setName(convertSimpleName(element, typeMirror, pos).setTypeMirror(typeMirror));
}
 
Example 17
Source File: StaticImport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.MEMBER_SELECT)
public static List<ErrorDescription> run(HintContext ctx) {
    CompilationInfo info = ctx.getInfo();
    TreePath treePath = ctx.getPath();

    Element e = info.getTrees().getElement(treePath);
    EnumSet<ElementKind> supportedTypes = EnumSet.of(ElementKind.METHOD, ElementKind.ENUM_CONSTANT, ElementKind.FIELD);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC) || !supportedTypes.contains(e.getKind())) {
        return null;
    }

    if (ElementKind.METHOD.equals(e.getKind())) {
        TreePath mitp = treePath.getParentPath();
        if (mitp == null || mitp.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
        return null;
    }
        if (((MethodInvocationTree) mitp.getLeaf()).getMethodSelect() != treePath.getLeaf()) {
        return null;
    }
        List<? extends Tree> typeArgs = ((MethodInvocationTree) mitp.getLeaf()).getTypeArguments();
        if (typeArgs != null && !typeArgs.isEmpty()) {
        return null;
    }
    }
    Element enclosingEl = e.getEnclosingElement();
    if (enclosingEl == null) {
        return null;
    }
    String sn = e.getSimpleName().toString();
    // rules out .class, but who knows what keywords will be abused in the future.
    if (SourceVersion.isKeyword(sn)) {
        return null;
    }
    TreePath cc = getContainingClass(treePath);
    if (cc == null){
        return null;
    }
    Element klass = info.getTrees().getElement(cc);
    if (klass == null || klass.getKind() != ElementKind.CLASS) {
        return null;
    }
    String fqn = null;
    String fqn1 = getFqn(info, e);
    if (!isSubTypeOrInnerOfSubType(info, klass, enclosingEl) && !isStaticallyImported(info, fqn1)) {
        if (hasMethodNameClash(info, klass, sn) || hasStaticImportSimpleNameClash(info, sn)) {
            return null;
        }
        fqn = fqn1;
    }
    Scope currentScope = info.getTrees().getScope(treePath);
    TypeMirror enclosingType = e.getEnclosingElement().asType();
    if (enclosingType == null || enclosingType.getKind() != TypeKind.DECLARED || !info.getTrees().isAccessible(currentScope, e, (DeclaredType) enclosingType)) {
        return null;
    }
    String desc = NbBundle.getMessage(StaticImport.class, "ERR_StaticImport");
    ErrorDescription ed = ErrorDescriptionFactory.forTree(ctx, treePath, desc, new FixImpl(TreePathHandle.create(treePath, info), fqn, sn).toEditorFix());
    if (ctx.isCanceled()) {
        return null;
    }
    return Collections.singletonList(ed);
}
 
Example 18
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String simpleName(Tree t) {
    if (t == null) {
        return Bundle.DisplayName_Unknown();
    }
    if (t.getKind() == Kind.IDENTIFIER) {
        return ((IdentifierTree) t).getName().toString();
    }

    if (t.getKind() == Kind.MEMBER_SELECT) {
        return ((MemberSelectTree) t).getIdentifier().toString();
    }

    if (t.getKind() == Kind.METHOD_INVOCATION) {
        return scan(t, null);
    }

    if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return simpleName(((ParameterizedTypeTree) t).getType()) + "<...>"; // NOI18N
    }

    if (t.getKind() == Kind.ARRAY_ACCESS) {
        return simpleName(((ArrayAccessTree) t).getExpression()) + "[]"; //NOI18N
    }

    if (t.getKind() == Kind.PARENTHESIZED) {
        return "(" + simpleName(((ParenthesizedTree)t).getExpression()) + ")"; //NOI18N
    }

    if (t.getKind() == Kind.TYPE_CAST) {
        return simpleName(((TypeCastTree)t).getType());
    }

    if (t.getKind() == Kind.ARRAY_TYPE) {
        return simpleName(((ArrayTypeTree)t).getType());
    }

    if (t.getKind() == Kind.PRIMITIVE_TYPE) {
        return ((PrimitiveTypeTree) t).getPrimitiveTypeKind().name().toLowerCase();
    }
    
    throw new IllegalStateException("Currently unsupported kind of tree: " + t.getKind()); // NOI18N
}
 
Example 19
Source File: StaticAccess.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected static Fix computeFixes(CompilationInfo info, TreePath treePath, int[] bounds, int[] kind, String[] simpleName) {
    if (treePath.getLeaf().getKind() != Kind.MEMBER_SELECT) {
        return null;
    }
    MemberSelectTree mst = (MemberSelectTree)treePath.getLeaf();
    Tree expression = mst.getExpression();
    TreePath expr = new TreePath(treePath, expression);
    
    TypeMirror tm = info.getTrees().getTypeMirror(expr);
    if (!Utilities.isValidType(tm)) {
        return null;
    }
    Element el = info.getTypes().asElement(tm);
    if (el == null || (!el.getKind().isClass() && !el.getKind().isInterface())) {
        return null;
    }
    
    TypeElement type = (TypeElement)el;
    
    if (isError(type)) {
        return null;
    }
    
    Name idName = null;
    
    if (expression.getKind() == Kind.MEMBER_SELECT) {
        MemberSelectTree exprSelect = (MemberSelectTree)expression;
        idName = exprSelect.getIdentifier();
    }
    
    if (expression.getKind() == Kind.IDENTIFIER) {
        IdentifierTree idt = (IdentifierTree)expression;
        idName = idt.getName();
    }
    
    if (idName != null) {
        if (idName.equals(type.getSimpleName())) {
            return null;
        }
        if (idName.equals(type.getQualifiedName())) {
            return null;
        }
    }
    
    Element used = info.getTrees().getElement(treePath);
    
    if (used == null || !used.getModifiers().contains(Modifier.STATIC)) {
        return null;
    }
    
    if (isError(used)) {
        return null;
    }
    
    if (used.getKind().isField()) {
        kind[0] = 0;
    } else {
        if (used.getKind() == ElementKind.METHOD) {
            kind[0] = 1;
        } else {
            kind[0] = 2;
        }
    }
    
    simpleName[0] = used.getSimpleName().toString();
    
    return new FixImpl(info, expr, type).toEditorFix();
}
 
Example 20
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;
}