Search in sources :

Example 71 with MethodTree

use of com.sun.source.tree.MethodTree in project st-js by st-js.

the class ClassDuplicateMemberNameCheck method checkMethod.

private void checkMethod(TypeElement classElement, Tree member, GenerationContext<Void> context, Multimap<String, Element> existingNames) {
    if (member instanceof MethodTree) {
        MethodTree method = (MethodTree) member;
        ExecutableElement methodElement = TreeUtils.elementFromDeclaration(method);
        if (JavaNodes.isNative(methodElement)) {
            // generic version of the overloaded method
            return;
        }
        TreeWrapper<Tree, Void> tw = context.getCurrentWrapper().child(member);
        if (MemberWriters.shouldSkip(tw)) {
            return;
        }
        if (methodElement.getKind() != ElementKind.METHOD) {
            // skip the constructors
            return;
        }
        checkMethodName(classElement, method, methodElement, context, existingNames);
    }
}
Also used : MethodTree(com.sun.source.tree.MethodTree) ExecutableElement(javax.lang.model.element.ExecutableElement) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree)

Example 72 with MethodTree

use of com.sun.source.tree.MethodTree in project st-js by st-js.

the class IdentifierGlobalScopeNameClashCheck method findVariablesInMethod.

private static void findVariablesInMethod(final String name, final GenerationContext<Void> context) {
    MethodTree enclosingMethod = getEnclosingMethod(context.getCurrentPath());
    if (enclosingMethod == null) {
        // don't see a reason why!?
        return;
    }
    enclosingMethod.accept(new TreeScanner<Void, Void>() {

        private boolean checkStopped;

        @Override
        public Void visitClass(ClassTree arg0, Void arg1) {
            // stop the checks if a new type is encountered
            checkStopped = true;
            return super.visitClass(arg0, arg1);
        }

        @Override
        public Void visitVariable(VariableTree var, Void arg1) {
            if (!checkStopped && var.getName().toString().equals(name)) {
                context.addError(var, "A variable with the same name as your global variable is already defined in this method's scope. " + "Please rename either the local variable/parameter or the global variable.");
            }
            return super.visitVariable(var, arg1);
        }
    }, null);
}
Also used : MethodTree(com.sun.source.tree.MethodTree) ClassTree(com.sun.source.tree.ClassTree) VariableTree(com.sun.source.tree.VariableTree)

Example 73 with MethodTree

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

the class JointJavacJavaParserVisitor method visitAnonymousClassBody.

/**
 * Visits the the members of an anonymous class body.
 *
 * <p>In normal classes, javac inserts a synthetic no-argument constructor if no constructor is
 * explicitly defined, which is skipped when visiting members. Anonymous class bodies may
 * introduce constructors that take arguments if the constructor invocation that created them was
 * passed arguments. For example, if {@code MyClass} has a constructor taking a single integer
 * argument, then writing {@code new MyClass(5) { }} expands to the javac tree
 *
 * <pre>{@code
 * new MyClass(5) {
 *     (int arg) {
 *         super(arg);
 *     }
 * }
 * }</pre>
 *
 * <p>This method skips these synthetic constructors.
 *
 * @param javacBody body of an anonymous class body
 * @param javaParserMembers list of members for the anonymous class body of an {@code
 *     ObjectCreationExpr}
 */
public void visitAnonymousClassBody(ClassTree javacBody, List<BodyDeclaration<?>> javaParserMembers) {
    List<Tree> javacMembers = new ArrayList<>(javacBody.getMembers());
    if (!javacMembers.isEmpty()) {
        Tree member = javacMembers.get(0);
        if (member.getKind() == Tree.Kind.METHOD) {
            MethodTree methodTree = (MethodTree) member;
            if (methodTree.getName().contentEquals("<init>")) {
                javacMembers.remove(0);
            }
        }
    }
    visitClassMembers(javacMembers, javaParserMembers);
}
Also used : MethodTree(com.sun.source.tree.MethodTree) ArrayList(java.util.ArrayList) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) LiteralTree(com.sun.source.tree.LiteralTree) ExportsTree(com.sun.source.tree.ExportsTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) ForLoopTree(com.sun.source.tree.ForLoopTree) InstanceOfTree(com.sun.source.tree.InstanceOfTree) ModuleTree(com.sun.source.tree.ModuleTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) OpensTree(com.sun.source.tree.OpensTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) ThrowTree(com.sun.source.tree.ThrowTree) BlockTree(com.sun.source.tree.BlockTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) ReturnTree(com.sun.source.tree.ReturnTree) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) LabeledStatementTree(com.sun.source.tree.LabeledStatementTree) UnaryTree(com.sun.source.tree.UnaryTree) VariableTree(com.sun.source.tree.VariableTree) TypeParameterTree(com.sun.source.tree.TypeParameterTree) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) BreakTree(com.sun.source.tree.BreakTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) IntersectionTypeTree(com.sun.source.tree.IntersectionTypeTree) WildcardTree(com.sun.source.tree.WildcardTree) RequiresTree(com.sun.source.tree.RequiresTree) UnionTypeTree(com.sun.source.tree.UnionTypeTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) AnnotatedTypeTree(com.sun.source.tree.AnnotatedTypeTree) PackageTree(com.sun.source.tree.PackageTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) NewArrayTree(com.sun.source.tree.NewArrayTree) ContinueTree(com.sun.source.tree.ContinueTree) UsesTree(com.sun.source.tree.UsesTree) CaseTree(com.sun.source.tree.CaseTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) SwitchTree(com.sun.source.tree.SwitchTree) PrimitiveTypeTree(com.sun.source.tree.PrimitiveTypeTree) SynchronizedTree(com.sun.source.tree.SynchronizedTree) AssertTree(com.sun.source.tree.AssertTree) StatementTree(com.sun.source.tree.StatementTree) ModifiersTree(com.sun.source.tree.ModifiersTree) WhileLoopTree(com.sun.source.tree.WhileLoopTree) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) BinaryTree(com.sun.source.tree.BinaryTree) EmptyStatementTree(com.sun.source.tree.EmptyStatementTree) ClassTree(com.sun.source.tree.ClassTree) IfTree(com.sun.source.tree.IfTree) ProvidesTree(com.sun.source.tree.ProvidesTree) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) ErroneousTree(com.sun.source.tree.ErroneousTree) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) TryTree(com.sun.source.tree.TryTree)

Example 74 with MethodTree

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

the class WholeProgramInferenceJavaParserStorage method createWrappersForClass.

/**
 * The first two arugments are a javac tree and a JavaParser node representing the same class.
 * This method creates wrappers around all the classes, fields, and methods in that class, and
 * stores those wrappers in {@code sourceAnnos}.
 *
 * @param javacClass javac tree for class
 * @param javaParserClass JavaParser node corresponding to the same class as {@code javacClass}
 * @param sourceAnnos compilation unit wrapper to add new wrappers to
 */
private void createWrappersForClass(ClassTree javacClass, TypeDeclaration<?> javaParserClass, CompilationUnitAnnos sourceAnnos) {
    JointJavacJavaParserVisitor visitor = new DefaultJointVisitor() {

        @Override
        public void processClass(ClassTree javacTree, ClassOrInterfaceDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processClass(ClassTree javacTree, EnumDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processClass(ClassTree javacTree, RecordDeclaration javaParserNode) {
            addClass(javacTree);
        }

        @Override
        public void processNewClass(NewClassTree javacTree, ObjectCreationExpr javaParserNode) {
            if (javacTree.getClassBody() != null) {
                addClass(javacTree.getClassBody());
            }
        }

        /**
         * Creates a wrapper around the class for {@code tree} and stores it in {@code
         * sourceAnnos}.
         *
         * @param tree tree to add
         */
        private void addClass(ClassTree tree) {
            TypeElement classElt = TreeUtils.elementFromDeclaration(tree);
            String className = ElementUtils.getBinaryName(classElt);
            ClassOrInterfaceAnnos typeWrapper = new ClassOrInterfaceAnnos();
            if (!classToAnnos.containsKey(className)) {
                classToAnnos.put(className, typeWrapper);
            }
            sourceAnnos.types.add(typeWrapper);
        }

        @Override
        public void processMethod(MethodTree javacTree, MethodDeclaration javaParserNode) {
            addCallableDeclaration(javacTree, javaParserNode);
        }

        @Override
        public void processMethod(MethodTree javacTree, ConstructorDeclaration javaParserNode) {
            addCallableDeclaration(javacTree, javaParserNode);
        }

        /**
         * Creates a wrapper around {@code javacTree} with the corresponding declaration {@code
         * javaParserNode} and stores it in {@code sourceAnnos}.
         *
         * @param javacTree javac tree for declaration to add
         * @param javaParserNode JavaParser node for the same class as {@code javacTree}
         */
        private void addCallableDeclaration(MethodTree javacTree, CallableDeclaration<?> javaParserNode) {
            ExecutableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            String className = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(className);
            String executableSignature = JVMNames.getJVMMethodSignature(javacTree);
            if (!enclosingClass.callableDeclarations.containsKey(executableSignature)) {
                enclosingClass.callableDeclarations.put(executableSignature, new CallableDeclarationAnnos(javaParserNode));
            }
        }

        @Override
        public void processVariable(VariableTree javacTree, EnumConstantDeclaration javaParserNode) {
            VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            if (!elt.getKind().isField()) {
                throw new BugInCF(elt + " is not a field but a " + elt.getKind());
            }
            String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
            String fieldName = javacTree.getName().toString();
            enclosingClass.enumConstants.add(fieldName);
            // Ensure that if an enum constant defines a class, that class gets registered properly.
            // See e.g. https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.1 for
            // the specification of an enum constant, which does permit it to define an anonymous
            // class.
            NewClassTree constructor = (NewClassTree) javacTree.getInitializer();
            if (constructor.getClassBody() != null) {
                addClass(constructor.getClassBody());
            }
        }

        @Override
        public void processVariable(VariableTree javacTree, VariableDeclarator javaParserNode) {
            // below call to TreeUtils.elementFromDeclaration causes a crash.
            if (TreeUtils.elementFromTree(javacTree) == null) {
                return;
            }
            VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
            if (!elt.getKind().isField()) {
                return;
            }
            String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
            ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
            String fieldName = javacTree.getName().toString();
            if (!enclosingClass.fields.containsKey(fieldName)) {
                enclosingClass.fields.put(fieldName, new FieldAnnos(javaParserNode));
            }
        }
    };
    visitor.visitClass(javacClass, javaParserClass);
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodTree(com.sun.source.tree.MethodTree) TypeElement(javax.lang.model.element.TypeElement) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ExecutableElement(javax.lang.model.element.ExecutableElement) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) VariableElement(javax.lang.model.element.VariableElement) BugInCF(org.checkerframework.javacutil.BugInCF) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) RecordDeclaration(com.github.javaparser.ast.body.RecordDeclaration) EnumConstantDeclaration(com.github.javaparser.ast.body.EnumConstantDeclaration) JointJavacJavaParserVisitor(org.checkerframework.framework.ajava.JointJavacJavaParserVisitor) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) DefaultJointVisitor(org.checkerframework.framework.ajava.DefaultJointVisitor)

Example 75 with MethodTree

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

the class FormatterVisitor method visitMethodInvocation.

@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
    FormatterTreeUtil ftu = atypeFactory.treeUtil;
    FormatCall fc = ftu.create(node, atypeFactory);
    if (fc != null) {
        MethodTree enclosingMethod = TreePathUtil.enclosingMethod(atypeFactory.getPath(fc.invocationTree));
        Result<String> errMissingFormat = fc.errMissingFormatAnnotation();
        if (errMissingFormat != null) {
            // The string's type has no @Format annotation.
            if (isWrappedFormatCall(fc, enclosingMethod)) {
            // Nothing to do, because call is legal.
            } else {
                // I.1
                ftu.failure(errMissingFormat, "format.string", errMissingFormat.value());
            }
        } else {
            // The string has a @Format annotation.
            Result<InvocationType> invc = fc.getInvocationType();
            ConversionCategory[] formatCats = fc.getFormatCategories();
            switch(invc.value()) {
                case VARARG:
                    Result<TypeMirror>[] argTypes = fc.getArgTypes();
                    int argl = argTypes.length;
                    int formatl = formatCats.length;
                    if (argl < formatl) {
                        // For assignments, format.missing.arguments is issued from commonAssignmentCheck.
                        // II.1
                        ftu.failure(invc, "format.missing.arguments", formatl, argl);
                    } else {
                        if (argl > formatl) {
                            // II.2
                            ftu.warning(invc, "format.excess.arguments", formatl, argl);
                        }
                        for (int i = 0; i < formatl; ++i) {
                            ConversionCategory formatCat = formatCats[i];
                            Result<TypeMirror> arg = argTypes[i];
                            TypeMirror argType = arg.value();
                            switch(formatCat) {
                                case UNUSED:
                                    // I.2
                                    ftu.warning(arg, "format.argument.unused", " " + (1 + i));
                                    break;
                                case NULL:
                                    // I.3
                                    if (argType.getKind() == TypeKind.NULL) {
                                        ftu.warning(arg, "format.specifier.null", " " + (1 + i));
                                    } else {
                                        ftu.failure(arg, "format.specifier.null", " " + (1 + i));
                                    }
                                    break;
                                case GENERAL:
                                    break;
                                default:
                                    if (!fc.isValidArgument(formatCat, argType)) {
                                        // II.3
                                        ExecutableElement method = TreeUtils.elementFromUse(node);
                                        CharSequence methodName = ElementUtils.getSimpleNameOrDescription(method);
                                        ftu.failure(arg, "argument", "in varargs position", methodName, argType, formatCat);
                                    }
                                    break;
                            }
                        }
                    }
                    break;
                case ARRAY:
                    // III
                    if (!isWrappedFormatCall(fc, enclosingMethod)) {
                        ftu.warning(invc, "format.indirect.arguments");
                    }
                // fall through
                case NULLARRAY:
                    for (ConversionCategory cat : formatCats) {
                        if (cat == ConversionCategory.NULL) {
                            // I.3
                            if (invc.value() == FormatterTreeUtil.InvocationType.NULLARRAY) {
                                ftu.warning(invc, "format.specifier.null", "");
                            } else {
                                ftu.failure(invc, "format.specifier.null", "");
                            }
                        }
                        if (cat == ConversionCategory.UNUSED) {
                            // I.2
                            ftu.warning(invc, "format.argument.unused", "");
                        }
                    }
                    break;
            }
        }
        // Support -Ainfer command-line argument.
        WholeProgramInference wpi = atypeFactory.getWholeProgramInference();
        if (wpi != null && forwardsArguments(node, enclosingMethod)) {
            wpi.addMethodDeclarationAnnotation(TreeUtils.elementFromDeclaration(enclosingMethod), atypeFactory.FORMATMETHOD);
        }
    }
    return super.visitMethodInvocation(node, p);
}
Also used : ConversionCategory(org.checkerframework.checker.formatter.qual.ConversionCategory) FormatCall(org.checkerframework.checker.formatter.FormatterTreeUtil.FormatCall) MethodTree(com.sun.source.tree.MethodTree) ExecutableElement(javax.lang.model.element.ExecutableElement) InvocationType(org.checkerframework.checker.formatter.FormatterTreeUtil.InvocationType) Result(org.checkerframework.checker.formatter.FormatterTreeUtil.Result) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) WholeProgramInference(org.checkerframework.common.wholeprograminference.WholeProgramInference)

Aggregations

MethodTree (com.sun.source.tree.MethodTree)127 ClassTree (com.sun.source.tree.ClassTree)66 Tree (com.sun.source.tree.Tree)65 VariableTree (com.sun.source.tree.VariableTree)58 ExpressionTree (com.sun.source.tree.ExpressionTree)54 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)43 ExecutableElement (javax.lang.model.element.ExecutableElement)39 NewClassTree (com.sun.source.tree.NewClassTree)38 TreePath (com.sun.source.util.TreePath)33 LambdaExpressionTree (com.sun.source.tree.LambdaExpressionTree)32 MemberSelectTree (com.sun.source.tree.MemberSelectTree)28 AnnotationTree (com.sun.source.tree.AnnotationTree)25 IdentifierTree (com.sun.source.tree.IdentifierTree)25 AnnotatedTypeMirror (org.checkerframework.framework.type.AnnotatedTypeMirror)23 ReturnTree (com.sun.source.tree.ReturnTree)22 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)22 ArrayList (java.util.ArrayList)22 TypeElement (javax.lang.model.element.TypeElement)21 AssignmentTree (com.sun.source.tree.AssignmentTree)20 ConditionalExpressionTree (com.sun.source.tree.ConditionalExpressionTree)20