Java Code Examples for com.sun.source.util.Trees#getTypeMirror()

The following examples show how to use com.sun.source.util.Trees#getTypeMirror() . 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: FindSubtypesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitClass(ClassTree node, Element elementToFind) {
    if (workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
        return super.visitClass(node, elementToFind);
    }
    Trees trees = workingCopy.getTrees();
    Types types = workingCopy.getTypes();
    TypeMirror type2 = elementToFind.asType();
    type2 = types.erasure(type2);
    
    if (recursive) {
        TypeMirror type1 = trees.getTypeMirror(getCurrentPath());
        if (type1 != null) {
            type1 = types.erasure(type1);
            if (isSubtype(type1, type2)) {
                addUsage(getCurrentPath());
            }
        }
    } else {
        TypeElement el = (TypeElement) workingCopy.getTrees().getElement(getCurrentPath());
        if (el != null && el.getSuperclass()!=null && types.isSameType(types.erasure(el.getSuperclass()), type2) || containsType(el.getInterfaces(), type2)) {
            addUsage(getCurrentPath());
        }
    }
    return super.visitClass(node, elementToFind);
}
 
Example 2
Source File: FindSubtypesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitLambdaExpression(LambdaExpressionTree node, Element elementToFind) {
    if (workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
        return super.visitLambdaExpression(node, elementToFind);
    }
    Trees trees = workingCopy.getTrees();
    Types types = workingCopy.getTypes();
    TypeMirror type1 = trees.getTypeMirror(getCurrentPath());
    if(type1 == null) {
        return super.visitLambdaExpression(node, elementToFind);
    }
    type1 = types.erasure(type1);
    TypeMirror type2 = elementToFind.asType();
    type2 = types.erasure(type2);
    
    if (types.isSameType(type1, type2) || (recursive && isSubtype(type1, type2))) {
        addUsage(getCurrentPath());
    }
    return super.visitLambdaExpression(node, elementToFind);
}
 
Example 3
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitIdentifier(IdentifierTree that, Trees trees) {

    TypeMirror type = trees.getTypeMirror(this.getCurrentPath());
    if (type == null /* will work even with error types || type.getKind() == TypeKind.ERROR */) {
        return super.visitIdentifier(that, trees);
    }
    if (type.getKind().isPrimitive()) {
        this.varToType.put(that.getName(), workingCopy.getTypes().boxedClass((PrimitiveType) type).toString());
    } else {
        this.varToType.put(that.getName(), type.toString());
    }
    TreePath currentTreePath = this.getCurrentPath();
    Element el = trees.getElement(currentTreePath);
    if (el != null && isExternalNEF(el, that)) {
        checkIfRefactorableMutation(currentTreePath, that);
    }
    return super.visitIdentifier(that, trees);
}
 
Example 4
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private StatementTree createFinallyCloseBlockStatement(VariableTree origDeclaration) {
    Trees trees = info.getTrees();
    TypeMirror tm = trees.getTypeMirror(statement);
    ElementUtilities elUtils = info.getElementUtilities();
    Iterable iterable = elUtils.getMembers(tm, new ElementAcceptor() {
        public boolean accept(Element e, TypeMirror type) {
            return e.getKind() == ElementKind.METHOD && "close".equals(e.getSimpleName().toString()); // NOI18N
        }
    });
    boolean throwsIO = false;
    for (Iterator iter = iterable.iterator(); iter.hasNext(); ) {
        ExecutableElement elem = (ExecutableElement) iter.next();
        if (!elem.getParameters().isEmpty()) {
            continue;
        } else {
             for (TypeMirror typeMirror : elem.getThrownTypes()) {
                 if ("java.io.IOException".equals(typeMirror.toString())) { // NOI18N
                     throwsIO = true;
                     break;
                 }
             }
        }
    }
    
    CharSequence name = origDeclaration.getName();
    StatementTree close = make.ExpressionStatement(make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier(name), "close"), Collections.<ExpressionTree>emptyList()));
    StatementTree result = close;
    if (throwsIO) {
        result = make.Try(make.Block(Collections.singletonList(close), false), Collections.singletonList(createCatch(info, make, statement, inferName(info, statement), info.getElements().getTypeElement("java.io.IOException").asType())), null);
        }
    
    return result;
}
 
Example 5
Source File: IntroduceLocalExtensionTransformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitAssignment(AssignmentTree node, Element p) {
    if (!refactoring.getReplace()) {
        return super.visitAssignment(node, p);
    }
    ExpressionTree variable = node.getVariable();
    boolean isArray = false;
    while (variable.getKind() == Tree.Kind.ARRAY_ACCESS) {
        isArray = true;
        // int[] a; a[a[0]][a[1]] = 0; // scan also array indices
        scan(((ArrayAccessTree) variable).getIndex(), p);
        variable = ((ArrayAccessTree) variable).getExpression();
    }

    Element el = workingCopy.getTrees().getElement(new TreePath(getCurrentPath(), variable));
    if(el != null) {
    Element enclosingElement = el.getEnclosingElement();
    if (enclosingElement != null && enclosingElement.equals(p)
            && (isArray || checkAssignmentInsideExpression())) {
        ElementHandle<Element> handle = ElementHandle.create(el);
        String[] getterSetter = getterSetterMap.get(handle); // TODO: Check for null and solve !
        if (getterSetter != null) {
            if (isArray) {
                ExpressionTree invkgetter = createGetterInvokation(variable, getterSetter[0]);
                rewrite(variable, invkgetter);
            } else {
                ExpressionTree setter = createMemberSelection(variable, getterSetter[1]);

                // resolve types
                Trees trees = workingCopy.getTrees();
                ExpressionTree expTree = node.getExpression();
                ExpressionTree newExpTree;
                TreePath varPath = trees.getPath(workingCopy.getCompilationUnit(), variable);
                TreePath expPath = trees.getPath(workingCopy.getCompilationUnit(), expTree);
                TypeMirror varType = trees.getTypeMirror(varPath);
                TypeMirror expType = trees.getTypeMirror(expPath);
                if (workingCopy.getTypes().isSubtype(expType, varType)) {
                    newExpTree = expTree;
                } else {
                    newExpTree = make.TypeCast(make.Type(varType), expTree);
                }

                MethodInvocationTree invksetter = make.MethodInvocation(
                        Collections.<ExpressionTree>emptyList(),
                        setter,
                        Collections.singletonList(newExpTree));

                rewrite(node, invksetter);
            }
        }
        }
    }
    return scan(node.getExpression(), p);
}
 
Example 6
Source File: IntroduceLocalExtensionTransformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitUnary(UnaryTree node, Element p) {
    if (!refactoring.getReplace()) {
        return super.visitUnary(node, p);
    }
    ExpressionTree t = node.getExpression();
    Tree.Kind kind = node.getKind();
    boolean isArrayOrImmutable = kind != Tree.Kind.POSTFIX_DECREMENT
            && kind != Tree.Kind.POSTFIX_INCREMENT
            && kind != Tree.Kind.PREFIX_DECREMENT
            && kind != Tree.Kind.PREFIX_INCREMENT;
    while (t.getKind() == Tree.Kind.ARRAY_ACCESS) {
        isArrayOrImmutable = true;
        t = ((ArrayAccessTree) t).getExpression();
    }
    Element el = workingCopy.getTrees().getElement(new TreePath(getCurrentPath(), t));
    if (el != null) {
        Element enclosingElement = el.getEnclosingElement();
        if (enclosingElement != null && enclosingElement.equals(p)
                && (isArrayOrImmutable || checkAssignmentInsideExpression())) {
            ElementHandle<Element> handle = ElementHandle.create(el);
            String[] getterSetter = getterSetterMap.get(handle); // TODO: Check for null and solve !
            // check (++field + 3)
            if (getterSetter != null) {
                ExpressionTree invkgetter = createGetterInvokation(t, getterSetter[0]);
                if (isArrayOrImmutable) {
                    rewrite(t, invkgetter);
                } else {
                    ExpressionTree setter = createMemberSelection(node.getExpression(), getterSetter[1]);

                    Tree.Kind operator = kind == Tree.Kind.POSTFIX_INCREMENT || kind == Tree.Kind.PREFIX_INCREMENT
                            ? Tree.Kind.PLUS
                            : Tree.Kind.MINUS;

                    // resolve types
                    Trees trees = workingCopy.getTrees();
                    ExpressionTree expTree = node.getExpression();
                    TreePath varPath = trees.getPath(workingCopy.getCompilationUnit(), expTree);
                    TypeMirror varType = trees.getTypeMirror(varPath);
                    TypeMirror expType = workingCopy.getTypes().getPrimitiveType(TypeKind.INT);
                    ExpressionTree newExpTree = make.Binary(operator, invkgetter, make.Literal(1));
                    if (!workingCopy.getTypes().isSubtype(expType, varType)) {
                        newExpTree = make.TypeCast(make.Type(varType), make.Parenthesized(newExpTree));
                    }

                    MethodInvocationTree invksetter = make.MethodInvocation(
                            Collections.<ExpressionTree>emptyList(),
                            setter,
                            Collections.singletonList(newExpTree));
                    rewrite(node, invksetter);
                }
            }
        }
    }
    return null;
}
 
Example 7
Source File: EncapsulateFieldRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitAssignment(AssignmentTree node, Element field) {
    ExpressionTree variable = node.getVariable();
    boolean isArray = false;
    while (variable.getKind() == Tree.Kind.ARRAY_ACCESS) {
        isArray = true;
        // int[] a; a[a[0]][a[1]] = 0; // scan also array indices
        scan(((ArrayAccessTree) variable).getIndex(), field);
        variable = ((ArrayAccessTree) variable).getExpression();
    }

    Element el = workingCopy.getTrees().getElement(new TreePath(getCurrentPath(), variable));
    EncapsulateDesc desc = fields.get(el);
    if (desc != null && desc.useAccessors && desc.refactoring.getSetterName() != null
            // check (field = 3) == 3
            && (isArray || checkAssignmentInsideExpression())
            && !isInConstructorOfFieldClass(getCurrentPath(), desc.field)
            && !isInGetterSetter(getCurrentPath(), desc.currentGetter, desc.currentSetter)) {
        if (isArray) {
            ExpressionTree invkgetter = createGetterInvokation(variable, desc.refactoring.getGetterName());
            rewrite(variable, invkgetter);
        } else {
            ExpressionTree setter = createMemberSelection(variable, desc.refactoring.getSetterName());

            // resolve types
            Trees trees = workingCopy.getTrees();
            ExpressionTree expTree = node.getExpression();
            ExpressionTree newExpTree;
            TreePath varPath = trees.getPath(workingCopy.getCompilationUnit(), variable);
            TreePath expPath = trees.getPath(workingCopy.getCompilationUnit(), expTree);
            TypeMirror varType = trees.getTypeMirror(varPath);
            TypeMirror expType = trees.getTypeMirror(expPath);
            if (workingCopy.getTypes().isSubtype(expType, varType)) {
                newExpTree = expTree;
            } else {
                newExpTree = make.TypeCast(make.Type(varType), expTree);
            }

            MethodInvocationTree invksetter = make.MethodInvocation(
                    Collections.<ExpressionTree>emptyList(),
                    setter,
                    Collections.singletonList(newExpTree));
            
            rewrite(node, invksetter);
            
            setterUsed = true;
        }
    }
    return scan(node.getExpression(), field);
}
 
Example 8
Source File: EncapsulateFieldRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitUnary(UnaryTree node, Element field) {
    ExpressionTree t = node.getExpression();
    Kind kind = node.getKind();
    boolean isArrayOrImmutable = kind != Kind.POSTFIX_DECREMENT
            && kind != Kind.POSTFIX_INCREMENT
            && kind != Kind.PREFIX_DECREMENT
            && kind != Kind.PREFIX_INCREMENT;
    while (t.getKind() == Tree.Kind.ARRAY_ACCESS) {
        isArrayOrImmutable = true;
        t = ((ArrayAccessTree) t).getExpression();
    }
    Element el = workingCopy.getTrees().getElement(new TreePath(getCurrentPath(), t));
    EncapsulateDesc desc = el == null ? null : fields.get(el);
    if (desc != null && desc.useAccessors
            && desc.refactoring.getGetterName() != null
            && (isArrayOrImmutable || checkAssignmentInsideExpression())
            && !isInConstructorOfFieldClass(getCurrentPath(), desc.field)
            && !isInGetterSetter(getCurrentPath(), desc.currentGetter, desc.currentSetter)) {
        // check (++field + 3)
        ExpressionTree invkgetter = createGetterInvokation(t, desc.refactoring.getGetterName());
        if (isArrayOrImmutable) {
            rewrite(t, invkgetter);
        } else if (desc.refactoring.getSetterName() != null) {
            ExpressionTree setter = createMemberSelection(node.getExpression(), desc.refactoring.getSetterName());

            Tree.Kind operator = kind == Tree.Kind.POSTFIX_INCREMENT || kind == Tree.Kind.PREFIX_INCREMENT
                    ? Tree.Kind.PLUS
                    : Tree.Kind.MINUS;

            // resolve types
            Trees trees = workingCopy.getTrees();
            ExpressionTree expTree = node.getExpression();
            TreePath varPath = trees.getPath(workingCopy.getCompilationUnit(), expTree);
            TypeMirror varType = trees.getTypeMirror(varPath);
            TypeMirror expType = workingCopy.getTypes().getPrimitiveType(TypeKind.INT);
            ExpressionTree newExpTree = make.Binary(operator, invkgetter, make.Literal(1));
            if (!workingCopy.getTypes().isSubtype(expType, varType)) {
                newExpTree = make.TypeCast(make.Type(varType), make.Parenthesized(newExpTree));
            }

            MethodInvocationTree invksetter = make.MethodInvocation(
                    Collections.<ExpressionTree>emptyList(),
                    setter,
                    Collections.singletonList(newExpTree));
            rewrite(node, invksetter);
        }
    }
    return null;
}
 
Example 9
Source File: UnnecessaryBoxing.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean checkMethodInvocation(HintContext ctx, TreePath invPath, TreePath valPath) {
    Trees trees = ctx.getInfo().getTrees();
    Tree invLeaf = invPath.getLeaf();
    List<? extends ExpressionTree> arguments;
    TypeMirror m;
    
    switch (invLeaf.getKind()) {
        case METHOD_INVOCATION: {
            MethodInvocationTree mit = (MethodInvocationTree)invLeaf;
            arguments = mit.getArguments();
            m = trees.getTypeMirror(new TreePath(invPath, mit.getMethodSelect()));
            break;
        }
        case NEW_CLASS: {
            NewClassTree nct = (NewClassTree)invLeaf;
            arguments = nct.getArguments();
            Element e = trees.getElement(invPath);
            TypeMirror cl = trees.getTypeMirror(invPath);
            if (!Utilities.isValidType(cl) || cl.getKind().isPrimitive()) {
                return false;
            }
            m = ctx.getInfo().getTypes().asMemberOf((DeclaredType)cl, e);
            break;
        }
        default:
            return false;
    }
    
    if (!Utilities.isValidType(m) || m.getKind() != TypeKind.EXECUTABLE) {
        return false;
    }
    ExecutableType execType = (ExecutableType)m;
    int idx = arguments.indexOf(ctx.getPath().getLeaf());
    if (idx < 0 || idx >= execType.getParameterTypes().size()) {
        return false;
    }
    TypeMirror paramType = execType.getParameterTypes().get(idx);
    TypeMirror curType = trees.getTypeMirror(ctx.getPath());
    TypeMirror valType = trees.getTypeMirror(valPath);
    
    if (!paramType.getKind().isPrimitive() && valType.getKind().isPrimitive()) {
        valType = ctx.getInfo().getTypes().boxedClass((PrimitiveType)valType).asType();
        // ensure that the passed INSTANCE type will not change when the boxing is removed
        if (!ctx.getInfo().getTypes().isSameType(curType, valType)) {
            return false;
        }
    }
            
    return Utilities.checkAlternativeInvocation(ctx.getInfo(), invPath, ctx.getPath(), valPath, null);
}
 
Example 10
Source File: WrongStringComparison.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="$left == $right", constraints={@ConstraintVariableType(variable="$left", type=STRING_TYPE),
                                                          @ConstraintVariableType(variable="$right", type=STRING_TYPE)}),
    @TriggerPattern(value="$left != $right", constraints={@ConstraintVariableType(variable="$left", type=STRING_TYPE),
                                                          @ConstraintVariableType(variable="$right", type=STRING_TYPE)})
})
public static ErrorDescription run(HintContext ctx) {
    CompilationInfo info = ctx.getInfo();
    TreePath treePath = ctx.getPath();
    Tree t = treePath.getLeaf();
    
    BinaryTree bt = (BinaryTree) t;
    
    TreePath left = new TreePath(treePath, bt.getLeftOperand() );
    TreePath right = new TreePath(treePath, bt.getRightOperand() );
    
    Trees trees = info.getTrees(); 
    TypeMirror leftType = left == null ? null : trees.getTypeMirror(left);
    TypeMirror rightType = right == null ? null : trees.getTypeMirror(right);

    if ( leftType != null && rightType != null && 
         STRING_TYPE.equals(leftType.toString()) && 
         STRING_TYPE.equals(rightType.toString())) {
        
        if (checkInsideGeneratedEquals(ctx, treePath, left.getLeaf(), right.getLeaf())) {
            return null;
        }

        FileObject file = info.getFileObject();
        TreePathHandle tph = TreePathHandle.create(treePath, info);
        ArrayList<Fix> fixes = new ArrayList<Fix>();
        boolean reverseOperands = false;
        if (bt.getLeftOperand().getKind() != Tree.Kind.STRING_LITERAL) {
            if (bt.getRightOperand().getKind() == Tree.Kind.STRING_LITERAL) {
                if (getStringLiteralsFirst(ctx.getPreferences())) {
                    reverseOperands = true;
                } else {
                    fixes.add(new WrongStringComparisonFix(tph, WrongStringComparisonFix.Kind.NULL_CHECK).toEditorFix());
                }
            } else {
                fixes.add(new WrongStringComparisonFix(tph, WrongStringComparisonFix.Kind.ternaryNullCheck(getTernaryNullCheck(ctx.getPreferences()))).toEditorFix());
            }
        }
        fixes.add(new WrongStringComparisonFix(tph, WrongStringComparisonFix.Kind.reverseOperands(reverseOperands)).toEditorFix());
        return ErrorDescriptionFactory.forTree(
                  ctx,
                  t,
                  NbBundle.getMessage(WrongStringComparison.class, "LBL_WrongStringComparison"), 
                  fixes.toArray(new Fix[0]));

    }
    
    return null;
}