Search in sources :

Example 41 with Type

use of com.sun.tools.javac.code.Type in project error-prone by google.

the class FindIdentifiers method isVisible.

private static boolean isVisible(VarSymbol var, final TreePath path) {
    switch(var.getKind()) {
        case ENUM_CONSTANT:
        case FIELD:
            // TODO(eaftan): Switch collector to ImmutableList.toImmutableList() when released
            List<ClassSymbol> enclosingClasses = StreamSupport.stream(path.spliterator(), false).filter(tree -> tree instanceof ClassTree).map(ClassTree.class::cast).map(ASTHelpers::getSymbol).collect(Collectors.toCollection(ArrayList::new));
            if (!var.isStatic()) {
                // Instance fields are not visible if we are in a static context...
                if (inStaticContext(path)) {
                    return false;
                }
                // the enclosing static nested class (JLS 8.5.1).
                if (lowerThan(path, (curr, unused) -> curr instanceof ClassTree && ASTHelpers.getSymbol((ClassTree) curr).isStatic(), (curr, unused) -> curr instanceof ClassTree && ASTHelpers.getSymbol((ClassTree) curr).equals(var.owner))) {
                    return false;
                }
            }
            // fields (JLS 6.6.1).
            if (enclosingClasses.contains(ASTHelpers.enclosingClass(var))) {
                return true;
            }
            PackageSymbol enclosingPackage = ((JCCompilationUnit) path.getCompilationUnit()).packge;
            Set<Modifier> modifiers = var.getModifiers();
            // (JLS 6.6.1).
            if (Objects.equals(enclosingPackage, ASTHelpers.enclosingPackage(var))) {
                return !modifiers.contains(Modifier.PRIVATE);
            }
            // in the enclosing class or a superclass).
            return modifiers.contains(Modifier.PUBLIC) || modifiers.contains(Modifier.PROTECTED);
        case PARAMETER:
        case LOCAL_VARIABLE:
            // final or effectively final (JLS 8.1.3).
            if (lowerThan(path, (curr, parent) -> curr.getKind() == Kind.LAMBDA_EXPRESSION || (curr.getKind() == Kind.NEW_CLASS && ((NewClassTree) curr).getClassBody() != null) || (curr.getKind() == Kind.CLASS && parent.getKind() == Kind.BLOCK), (curr, unused) -> Objects.equals(var.owner, ASTHelpers.getSymbol(curr)))) {
                if ((var.flags() & (Flags.FINAL | Flags.EFFECTIVELY_FINAL)) == 0) {
                    return false;
                }
            }
            return true;
        case EXCEPTION_PARAMETER:
        case RESOURCE_VARIABLE:
            return true;
        default:
            throw new IllegalArgumentException("Unexpected variable type: " + var.getKind());
    }
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassType(com.sun.tools.javac.code.Type.ClassType) Modifier(javax.lang.model.element.Modifier) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) Method(java.lang.reflect.Method) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) TreePath(com.sun.source.util.TreePath) ImmutableSet(com.google.common.collect.ImmutableSet) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Env(com.sun.tools.javac.comp.Env) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreeScanner(com.sun.source.util.TreeScanner) Objects(java.util.Objects) List(java.util.List) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) Flags(com.sun.tools.javac.code.Flags) Name(com.sun.tools.javac.util.Name) Scope(com.sun.tools.javac.code.Scope) Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) MemberEnter(com.sun.tools.javac.comp.MemberEnter) VariableTree(com.sun.source.tree.VariableTree) AttrContext(com.sun.tools.javac.comp.AttrContext) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) BiPredicate(java.util.function.BiPredicate) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) NewClassTree(com.sun.source.tree.NewClassTree) StreamSupport(java.util.stream.StreamSupport) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) Enter(com.sun.tools.javac.comp.Enter) ElementKind(javax.lang.model.element.ElementKind) KindSelector(com.sun.tools.javac.code.Kinds.KindSelector) TryTree(com.sun.source.tree.TryTree) Resolve(com.sun.tools.javac.comp.Resolve) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) NewClassTree(com.sun.source.tree.NewClassTree) Modifier(javax.lang.model.element.Modifier)

Example 42 with Type

use of com.sun.tools.javac.code.Type in project error-prone by google.

the class BoxedPrimitiveConstructor method maybeCast.

private String maybeCast(VisitorState state, Type type, Type argType) {
    if (doubleAndFloatStatus(state, type, argType) == DoubleAndFloatStatus.PRIMITIVE_DOUBLE_INTO_FLOAT) {
        // e.g.: new Float(3.0d) => (float) 3.0d
        return "(float) ";
    }
    // primitive widening conversions can't be combined with autoboxing, so add a
    // explicit widening cast unless we're sure the expression doesn't get autoboxed
    Tree parent = state.getPath().getParentPath().getLeaf();
    // TODO(cushon): de-dupe with UnnecessaryCast
    Type targetType = parent.accept(new TreeScanner<Type, Void>() {

        @Override
        public Type visitAssignment(AssignmentTree node, Void unused) {
            return getType(node.getVariable());
        }

        @Override
        public Type visitCompoundAssignment(CompoundAssignmentTree node, Void unused) {
            return getType(node.getVariable());
        }

        @Override
        public Type visitReturn(ReturnTree node, Void unused) {
            return getType(state.findEnclosing(MethodTree.class).getReturnType());
        }

        @Override
        public Type visitVariable(VariableTree node, Void unused) {
            return getType(node.getType());
        }
    }, null);
    if (!isSameType(type, argType, state) && !isSameType(targetType, type, state)) {
        return String.format("(%s) ", type);
    }
    return "";
}
Also used : Matchers.toType(com.google.errorprone.matchers.Matchers.toType) ASTHelpers.getType(com.google.errorprone.util.ASTHelpers.getType) ASTHelpers.isSameType(com.google.errorprone.util.ASTHelpers.isSameType) Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) ReturnTree(com.sun.source.tree.ReturnTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) LiteralTree(com.sun.source.tree.LiteralTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) AssignmentTree(com.sun.source.tree.AssignmentTree) NewClassTree(com.sun.source.tree.NewClassTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) AssignmentTree(com.sun.source.tree.AssignmentTree) ReturnTree(com.sun.source.tree.ReturnTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree)

Example 43 with Type

use of com.sun.tools.javac.code.Type in project error-prone by google.

the class CanBeStaticAnalyzer method visitNewClass.

@Override
public void visitNewClass(JCTree.JCNewClass tree) {
    super.visitNewClass(tree);
    // check for constructor invocations where the type is a member of an enclosing class,
    // the enclosing instance is passed as an explicit argument
    Type type = ASTHelpers.getType(tree.clazz);
    if (type == null) {
        return;
    }
    if (memberOfEnclosing(owner, state, type.tsym)) {
        referencesOuter = true;
    }
}
Also used : Type(com.sun.tools.javac.code.Type)

Example 44 with Type

use of com.sun.tools.javac.code.Type in project error-prone by google.

the class ClassNewInstance method fixThrows.

// if there wasn't a try/catch to add new catch clauses to, update the enclosing
// method declaration's throws clause to declare the new checked exceptions
private void fixThrows(VisitorState state, SuggestedFix.Builder fix) {
    MethodTree methodTree = state.findEnclosing(MethodTree.class);
    if (methodTree == null || methodTree.getThrows().isEmpty()) {
        return;
    }
    ImmutableMap.Builder<Type, ExpressionTree> thrown = ImmutableMap.builder();
    for (ExpressionTree e : methodTree.getThrows()) {
        thrown.put(ASTHelpers.getType(e), e);
    }
    UnhandledResult<ExpressionTree> result = unhandled(thrown.build(), state);
    if (result.unhandled.isEmpty()) {
        return;
    }
    List<String> newThrows = new ArrayList<>();
    for (Type handle : result.unhandled) {
        newThrows.add(handle.tsym.getSimpleName().toString());
    }
    Collections.sort(newThrows);
    fix.postfixWith(Iterables.getLast(methodTree.getThrows()), ", " + Joiner.on(", ").join(newThrows));
    // the other exceptions are in java.lang
    fix.addImport("java.lang.reflect.InvocationTargetException");
}
Also used : Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) ArrayList(java.util.ArrayList) ExpressionTree(com.sun.source.tree.ExpressionTree) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 45 with Type

use of com.sun.tools.javac.code.Type in project error-prone by google.

the class ClassNewInstance method unhandled.

/**
   * Given a map of handled exception types and the trees of those handlers (i.e. catch clauses or
   * method throws clauses), determine which handlers are for reflective exceptions, and whether
   * all exceptions thrown by {#link Constructor#newInstance} are handled.
   */
private <T> UnhandledResult<T> unhandled(ImmutableMap<Type, T> handles, VisitorState state) {
    LinkedHashSet<Type> toHandle = new LinkedHashSet<>();
    for (Class<?> e : Arrays.asList(InstantiationException.class, IllegalAccessException.class, InvocationTargetException.class, NoSuchMethodException.class)) {
        Type type = state.getTypeFromString(e.getName());
        if (type != null) {
            toHandle.add(type);
        }
    }
    Type roe = state.getTypeFromString(ReflectiveOperationException.class.getName());
    ImmutableMap.Builder<Type, T> newHandles = ImmutableMap.builder();
    for (Map.Entry<Type, T> entry : handles.entrySet()) {
        Type type = entry.getKey();
        if (ASTHelpers.isSubtype(type, roe, state)) {
            newHandles.put(type, entry.getValue());
        }
        for (Type precise : type.isUnion() ? ((Type.UnionClassType) type).getAlternativeTypes() : Collections.singleton(type)) {
            Iterator<Type> it = toHandle.iterator();
            while (it.hasNext()) {
                if (ASTHelpers.isSubtype(it.next(), precise, state)) {
                    it.remove();
                }
            }
        }
    }
    return new UnhandledResult<>(ImmutableSet.copyOf(toHandle), newHandles.build());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Type(com.sun.tools.javac.code.Type) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

Type (com.sun.tools.javac.code.Type)254 Symbol (com.sun.tools.javac.code.Symbol)64 ClassType (com.sun.tools.javac.code.Type.ClassType)55 ArrayType (com.sun.tools.javac.code.Type.ArrayType)47 MethodType (com.sun.tools.javac.code.Type.MethodType)42 WildcardType (com.sun.tools.javac.code.Type.WildcardType)42 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)36 UnionClassType (com.sun.tools.javac.code.Type.UnionClassType)33 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)32 JCTree (com.sun.tools.javac.tree.JCTree)27 TypeSymbol (com.sun.tools.javac.code.Symbol.TypeSymbol)24 VarSymbol (com.sun.tools.javac.code.Symbol.VarSymbol)23 Types (com.sun.tools.javac.code.Types)22 ExpressionTree (com.sun.source.tree.ExpressionTree)21 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)17 ArrayList (java.util.ArrayList)17 PackageSymbol (com.sun.tools.javac.code.Symbol.PackageSymbol)16 Tree (com.sun.source.tree.Tree)14 Name (com.sun.tools.javac.util.Name)14 DynamicMethodSymbol (com.sun.tools.javac.code.Symbol.DynamicMethodSymbol)13