Search in sources :

Example 6 with MethodTree

use of com.sun.source.tree.MethodTree 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 7 with MethodTree

use of com.sun.source.tree.MethodTree in project error-prone by google.

the class RefasterRuleBuilderScanner method extractRules.

public static Collection<? extends CodeTransformer> extractRules(ClassTree tree, Context context) {
    ClassSymbol sym = ASTHelpers.getSymbol(tree);
    RefasterRuleBuilderScanner scanner = new RefasterRuleBuilderScanner(context);
    // visit abstract methods first
    List<MethodTree> methods = new Ordering<MethodTree>() {

        @Override
        public int compare(MethodTree l, MethodTree r) {
            return Boolean.compare(l.getModifiers().getFlags().contains(Modifier.ABSTRACT), r.getModifiers().getFlags().contains(Modifier.ABSTRACT));
        }
    }.reverse().immutableSortedCopy(Iterables.filter(tree.getMembers(), MethodTree.class));
    scanner.visit(methods, null);
    UTemplater templater = new UTemplater(context);
    List<UType> types = templater.templateTypes(sym.type.getTypeArguments());
    return scanner.createMatchers(Iterables.filter(types, UTypeVar.class), sym.getQualifiedName().toString(), UTemplater.annotationMap(sym));
}
Also used : MethodTree(com.sun.source.tree.MethodTree) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) Ordering(com.google.common.collect.Ordering)

Example 8 with MethodTree

use of com.sun.source.tree.MethodTree in project checker-framework by typetools.

the class TreeUtils method isTreeInStaticScope.

/**
 * Returns whether or not the leaf of the tree path is in a static scope.
 *
 * @param path TreePath whose leaf may or may not be in static scope
 * @return returns whether or not the leaf of the tree path is in a static scope
 */
public static boolean isTreeInStaticScope(TreePath path) {
    MethodTree enclosingMethod = TreeUtils.enclosingMethod(path);
    if (enclosingMethod != null) {
        return enclosingMethod.getModifiers().getFlags().contains(Modifier.STATIC);
    }
    // no enclosing method, check for static or initializer block
    BlockTree block = enclosingTopLevelBlock(path);
    if (block != null) {
        return block.isStatic();
    }
    // check if its in a variable initializer
    Tree t = enclosingVariable(path);
    if (t != null) {
        return ((VariableTree) t).getModifiers().getFlags().contains((Modifier.STATIC));
    }
    ClassTree classTree = enclosingClass(path);
    if (classTree != null) {
        return classTree.getModifiers().getFlags().contains((Modifier.STATIC));
    }
    return false;
}
Also used : MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) BlockTree(com.sun.source.tree.BlockTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) LiteralTree(com.sun.source.tree.LiteralTree) AnnotatedTypeTree(com.sun.source.tree.AnnotatedTypeTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) IdentifierTree(com.sun.source.tree.IdentifierTree) NewArrayTree(com.sun.source.tree.NewArrayTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) BlockTree(com.sun.source.tree.BlockTree) PrimitiveTypeTree(com.sun.source.tree.PrimitiveTypeTree) StatementTree(com.sun.source.tree.StatementTree) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) BinaryTree(com.sun.source.tree.BinaryTree) VariableTree(com.sun.source.tree.VariableTree) TypeParameterTree(com.sun.source.tree.TypeParameterTree) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree)

Example 9 with MethodTree

use of com.sun.source.tree.MethodTree in project checker-framework by typetools.

the class WholeProgramInferenceScenes method updateInferredParameterType.

/**
 * Updates the parameter type represented by lhs of the method methodTree in the Scene of the
 * receiverTree's enclosing class based on assignments to the parameter inside the method body.
 *
 * <ul>
 *   <li>If the Scene does not contain an annotated type for that parameter, then the type of
 *       the respective value passed as argument in the method call methodInvNode will be added
 *       to the parameter in the Scene.
 *   <li>If the Scene previously contained an annotated type for that parameter, then its new
 *       type will be the LUB between the previous type and the type of the respective value
 *       passed as argument in the method call.
 * </ul>
 *
 * <p>
 *
 * @param lhs the node representing the parameter
 * @param rhs the node being assigned to the parameter
 * @param classTree the tree of the class that contains the parameter
 * @param methodTree the tree of the method that contains the parameter
 * @param atf the annotated type factory of a given type system, whose type hierarchy will be
 *     used to update the parameter type
 */
@Override
public void updateInferredParameterType(LocalVariableNode lhs, Node rhs, ClassTree classTree, MethodTree methodTree, AnnotatedTypeFactory atf) {
    ClassSymbol classSymbol = getEnclosingClassSymbol(classTree, lhs);
    // https://github.com/typetools/checker-framework/issues/682
    if (classSymbol == null)
        return;
    String className = classSymbol.flatname.toString();
    String jaifPath = helper.getJaifPath(className);
    AClass clazz = helper.getAClass(className, jaifPath);
    String methodName = JVMNames.getJVMMethodName(methodTree);
    AMethod method = clazz.methods.vivify(methodName);
    List<? extends VariableTree> params = methodTree.getParameters();
    // Look-up parameter by name:
    for (int i = 0; i < params.size(); i++) {
        VariableTree vt = params.get(i);
        if (vt.getName().contentEquals(lhs.getName())) {
            Tree treeNode = rhs.getTree();
            if (treeNode == null) {
                // https://github.com/typetools/checker-framework/issues/682
                continue;
            }
            AnnotatedTypeMirror paramATM = atf.getAnnotatedType(vt);
            AnnotatedTypeMirror argATM = atf.getAnnotatedType(treeNode);
            AField param = method.parameters.vivify(i);
            helper.updateAnnotationSetInScene(param.type, atf, jaifPath, argATM, paramATM, TypeUseLocation.PARAMETER);
            break;
        }
    }
}
Also used : ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) VariableTree(com.sun.source.tree.VariableTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) AClass(scenelib.annotations.el.AClass) AMethod(scenelib.annotations.el.AMethod) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) AField(scenelib.annotations.el.AField)

Example 10 with MethodTree

use of com.sun.source.tree.MethodTree in project checker-framework by typetools.

the class CFAbstractTransfer method initialStore.

/**
 * The initial store maps method formal parameters to their currently most refined type.
 */
@Override
public S initialStore(UnderlyingAST underlyingAST, @Nullable List<LocalVariableNode> parameters) {
    if (fixedInitialStore != null && underlyingAST.getKind() != Kind.LAMBDA && underlyingAST.getKind() != Kind.METHOD) {
        return fixedInitialStore;
    }
    S info = analysis.createEmptyStore(sequentialSemantics);
    if (underlyingAST.getKind() == Kind.METHOD) {
        if (fixedInitialStore != null) {
            // copy knowledge
            info = analysis.createCopiedStore(fixedInitialStore);
        }
        AnnotatedTypeFactory factory = analysis.getTypeFactory();
        for (LocalVariableNode p : parameters) {
            AnnotatedTypeMirror anno = factory.getAnnotatedType(p.getElement());
            info.initializeMethodParameter(p, analysis.createAbstractValue(anno));
        }
        // add properties known through precondition
        CFGMethod method = (CFGMethod) underlyingAST;
        MethodTree methodTree = method.getMethod();
        ExecutableElement methodElem = TreeUtils.elementFromDeclaration(methodTree);
        addInformationFromPreconditions(info, factory, method, methodTree, methodElem);
        final ClassTree classTree = method.getClassTree();
        addFieldValues(info, factory, classTree, methodTree);
        addFinalLocalValues(info, methodElem);
        if (shouldPerformWholeProgramInference(methodTree, methodElem)) {
            Map<AnnotatedDeclaredType, ExecutableElement> overriddenMethods = AnnotatedTypes.overriddenMethods(analysis.atypeFactory.getElementUtils(), analysis.atypeFactory, methodElem);
            for (Map.Entry<AnnotatedDeclaredType, ExecutableElement> pair : overriddenMethods.entrySet()) {
                AnnotatedExecutableType overriddenMethod = AnnotatedTypes.asMemberOf(analysis.atypeFactory.getProcessingEnv().getTypeUtils(), analysis.atypeFactory, pair.getKey(), pair.getValue());
                // Infers parameter and receiver types of the method based
                // on the overridden method.
                analysis.atypeFactory.getWholeProgramInference().updateInferredMethodParameterTypes(methodTree, methodElem, overriddenMethod, analysis.getTypeFactory());
                analysis.atypeFactory.getWholeProgramInference().updateInferredMethodReceiverType(methodTree, methodElem, overriddenMethod, analysis.getTypeFactory());
            }
        }
        return info;
    } else if (underlyingAST.getKind() == Kind.LAMBDA) {
        // Create a copy and keep only the field values (nothing else applies).
        info = analysis.createCopiedStore(fixedInitialStore);
        info.localVariableValues.clear();
        info.classValues.clear();
        info.arrayValues.clear();
        info.methodValues.clear();
        AnnotatedTypeFactory factory = analysis.getTypeFactory();
        for (LocalVariableNode p : parameters) {
            AnnotatedTypeMirror anno = factory.getAnnotatedType(p.getElement());
            info.initializeMethodParameter(p, analysis.createAbstractValue(anno));
        }
        CFGLambda lambda = (CFGLambda) underlyingAST;
        Tree enclosingTree = TreeUtils.enclosingOfKind(factory.getPath(lambda.getLambdaTree()), new HashSet<>(Arrays.asList(Tree.Kind.METHOD, // Tree.Kind for which TreeUtils.isClassTree is true
        Tree.Kind.CLASS, Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE, Tree.Kind.ENUM)));
        Element enclosingElement = null;
        if (enclosingTree.getKind() == Tree.Kind.METHOD) {
            // If it is in an initializer, we need to use locals from the initializer.
            enclosingElement = TreeUtils.elementFromTree(enclosingTree);
        } else if (TreeUtils.isClassTree(enclosingTree)) {
            // Try to find an enclosing initializer block
            // Would love to know if there was a better way
            // Find any enclosing element of the lambda (using trees)
            // Then go up the elements to find an initializer element (which can't be found with
            // the tree).
            TreePath loopTree = factory.getPath(lambda.getLambdaTree()).getParentPath();
            Element anEnclosingElement = null;
            while (loopTree.getLeaf() != enclosingTree) {
                Element sym = TreeUtils.elementFromTree(loopTree.getLeaf());
                if (sym != null) {
                    anEnclosingElement = sym;
                    break;
                }
                loopTree = loopTree.getParentPath();
            }
            while (anEnclosingElement != null && !anEnclosingElement.equals(TreeUtils.elementFromTree(enclosingTree))) {
                if (anEnclosingElement.getKind() == ElementKind.INSTANCE_INIT || anEnclosingElement.getKind() == ElementKind.STATIC_INIT) {
                    enclosingElement = anEnclosingElement;
                    break;
                }
                anEnclosingElement = anEnclosingElement.getEnclosingElement();
            }
        }
        if (enclosingElement != null) {
            addFinalLocalValues(info, enclosingElement);
        }
        // We want the initialization stuff, but need to throw out any refinements.
        Map<FieldAccess, V> fieldValuesClone = new HashMap<>(info.fieldValues);
        for (Entry<FieldAccess, V> fieldValue : fieldValuesClone.entrySet()) {
            AnnotatedTypeMirror declaredType = factory.getAnnotatedType(fieldValue.getKey().getField());
            V lubbedValue = analysis.createAbstractValue(declaredType).leastUpperBound(fieldValue.getValue());
            info.fieldValues.put(fieldValue.getKey(), lubbedValue);
        }
    }
    return info;
}
Also used : CFGMethod(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod) MethodTree(com.sun.source.tree.MethodTree) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ClassTree(com.sun.source.tree.ClassTree) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) LocalVariableNode(org.checkerframework.dataflow.cfg.node.LocalVariableNode) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) Entry(java.util.Map.Entry) TreePath(com.sun.source.util.TreePath) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) GenericAnnotatedTypeFactory(org.checkerframework.framework.type.GenericAnnotatedTypeFactory) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) CFGLambda(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

MethodTree (com.sun.source.tree.MethodTree)91 Tree (com.sun.source.tree.Tree)46 ClassTree (com.sun.source.tree.ClassTree)45 VariableTree (com.sun.source.tree.VariableTree)39 ExpressionTree (com.sun.source.tree.ExpressionTree)36 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)28 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)22 LambdaExpressionTree (com.sun.source.tree.LambdaExpressionTree)20 TreePath (com.sun.source.util.TreePath)20 IdentifierTree (com.sun.source.tree.IdentifierTree)19 NewClassTree (com.sun.source.tree.NewClassTree)19 ReturnTree (com.sun.source.tree.ReturnTree)18 ExecutableElement (javax.lang.model.element.ExecutableElement)17 Symbol (com.sun.tools.javac.code.Symbol)16 ArrayList (java.util.ArrayList)15 AssignmentTree (com.sun.source.tree.AssignmentTree)14 BlockTree (com.sun.source.tree.BlockTree)14 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)14 ConditionalExpressionTree (com.sun.source.tree.ConditionalExpressionTree)14 MemberSelectTree (com.sun.source.tree.MemberSelectTree)14