Search in sources :

Example 71 with JCVariableDecl

use of com.sun.tools.javac.tree.JCTree.JCVariableDecl in project error-prone by google.

the class SelfEquals method fieldFix.

@Nullable
protected static Fix fieldFix(Tree toReplace, VisitorState state) {
    TreePath path = state.getPath();
    while (path != null && path.getLeaf().getKind() != Kind.CLASS && path.getLeaf().getKind() != Kind.BLOCK) {
        path = path.getParentPath();
    }
    if (path == null) {
        return null;
    }
    List<? extends JCTree> members;
    // Must be block or class
    if (path.getLeaf().getKind() == Kind.CLASS) {
        members = ((JCClassDecl) path.getLeaf()).getMembers();
    } else {
        members = ((JCBlock) path.getLeaf()).getStatements();
    }
    for (JCTree jcTree : members) {
        if (jcTree.getKind() == Kind.VARIABLE) {
            JCVariableDecl declaration = (JCVariableDecl) jcTree;
            TypeSymbol variableTypeSymbol = state.getTypes().erasure(ASTHelpers.getType(declaration)).tsym;
            if (ASTHelpers.getSymbol(toReplace).isMemberOf(variableTypeSymbol, state.getTypes())) {
                if (toReplace.getKind() == Kind.IDENTIFIER) {
                    return SuggestedFix.prefixWith(toReplace, declaration.getName() + ".");
                } else {
                    return SuggestedFix.replace(((JCFieldAccess) toReplace).getExpression(), declaration.getName().toString());
                }
            }
        }
    }
    return null;
}
Also used : TreePath(com.sun.source.util.TreePath) JCTree(com.sun.tools.javac.tree.JCTree) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Nullable(javax.annotation.Nullable)

Example 72 with JCVariableDecl

use of com.sun.tools.javac.tree.JCTree.JCVariableDecl in project error-prone by google.

the class NonOverridingEquals method matchMethod.

@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
    if (!MATCHER.matches(methodTree, state)) {
        return Description.NO_MATCH;
    }
    // this is a type-specific helper method and give advice to either inline it or rename it.
    if (enclosingClassOverridesEquals.matches(methodTree, state)) {
        return buildDescription(methodTree).setMessage(MESSAGE_BASE + "; if this is a type-specific helper for a method that does" + " override Object.equals, either inline it into the callers or rename it to" + " avoid ambiguity").build();
    }
    // Don't provide a fix if the method is static, non-public, or returns a boxed Boolean
    if (noFixMatcher.matches(methodTree, state)) {
        return describeMatch(methodTree);
    }
    JCClassDecl cls = (JCClassDecl) state.findEnclosing(ClassTree.class);
    if ((cls.getModifiers().flags & ENUM) != 0) {
        /* If the enclosing class is an enum, then just delete the equals method since enums
       * should always be compared for reference equality. Enum defines a final equals method for
       * just this reason. */
        return buildDescription(methodTree).setMessage(MESSAGE_BASE + "; enum instances can safely be compared by reference " + "equality, so please delete this").addFix(SuggestedFix.delete(methodTree)).build();
    } else {
        /* Otherwise, change the covariant equals method to override Object.equals. */
        SuggestedFix.Builder fix = SuggestedFix.builder();
        // Add @Override annotation if not present.
        if (ASTHelpers.getAnnotation(methodTree, Override.class) == null) {
            fix.prefixWith(methodTree, "@Override\n");
        }
        // Change method signature, substituting Object for parameter type.
        JCTree parameterType = (JCTree) methodTree.getParameters().get(0).getType();
        Name parameterName = ((JCVariableDecl) methodTree.getParameters().get(0)).getName();
        fix.replace(parameterType, "Object");
        // If there is a method body...
        if (methodTree.getBody() != null) {
            // Add type check at start
            String typeCheckStmt = "if (!(" + parameterName + " instanceof " + parameterType + ")) {\n" + "  return false;\n" + "}\n";
            fix.prefixWith(methodTree.getBody().getStatements().get(0), typeCheckStmt);
            // Cast all uses of the parameter name using a recursive TreeScanner.
            new CastScanner().scan(methodTree.getBody(), new CastState(parameterName, parameterType.toString(), fix));
        }
        return describeMatch(methodTree, fix.build());
    }
}
Also used : JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) ClassTree(com.sun.source.tree.ClassTree) JCTree(com.sun.tools.javac.tree.JCTree) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name)

Example 73 with JCVariableDecl

use of com.sun.tools.javac.tree.JCTree.JCVariableDecl in project lombok by rzwitserloot.

the class JavacJavaUtilMapSingularizer method generateSingularMethod.

private void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();
    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
    Name keyName = builderType.toName(data.getSingularName().toString() + "Key");
    Name valueName = builderType.toName(data.getSingularName().toString() + "Value");
    /* this.pluralname$key.add(singularnameKey); */
    {
        JCExpression thisDotKeyFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$key", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotKeyFieldDotAdd, List.<JCExpression>of(maker.Ident(keyName)));
        statements.append(maker.Exec(invokeAdd));
    }
    /* this.pluralname$value.add(singularnameValue); */
    {
        JCExpression thisDotValueFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$value", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotValueFieldDotAdd, List.<JCExpression>of(maker.Ident(valueName)));
        statements.append(maker.Exec(invokeAdd));
    }
    if (returnStatement != null)
        statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    Name name = data.getSingularName();
    if (!fluent)
        name = builderType.toName(HandlerUtil.buildAccessorName("put", name.toString()));
    JCExpression paramTypeKey = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
    JCExpression paramTypeValue = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
    JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, paramTypeKey, null);
    JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, paramTypeValue, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(paramKey, paramValue), thrown, body, null);
    injectMethod(builderType, method);
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers)

Example 74 with JCVariableDecl

use of com.sun.tools.javac.tree.JCTree.JCVariableDecl in project lombok by rzwitserloot.

the class TreeMirrorMaker method visitVariable.

// Monitor issue 205 and issue 694 when making changes here.
@Override
public JCTree visitVariable(VariableTree node, Void p) {
    JCVariableDecl original = node instanceof JCVariableDecl ? (JCVariableDecl) node : null;
    JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p);
    if (original == null)
        return copy;
    copy.sym = original.sym;
    if (copy.sym != null)
        copy.type = original.type;
    if (copy.type != null) {
        boolean wipeSymAndType = copy.type.isErroneous();
        if (!wipeSymAndType) {
            TypeTag typeTag = TypeTag.typeTag(copy.type);
            wipeSymAndType = (CTC_NONE.equals(typeTag) || CTC_ERROR.equals(typeTag) || CTC_UNKNOWN.equals(typeTag) || CTC_UNDETVAR.equals(typeTag));
        }
        if (wipeSymAndType) {
            copy.sym = null;
            copy.type = null;
        }
    }
    return copy;
}
Also used : JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) TypeTag(lombok.javac.JavacTreeMaker.TypeTag)

Example 75 with JCVariableDecl

use of com.sun.tools.javac.tree.JCTree.JCVariableDecl in project lombok by rzwitserloot.

the class PrettyPrinter method printLambda0.

private void printLambda0(JCTree tree) {
    List<JCVariableDecl> params = readObject(tree, "params", List.<JCVariableDecl>nil());
    boolean explicit = true;
    int paramLength = params.size();
    try {
        explicit = readObject(tree, "paramKind", new Object()).toString().equals("EXPLICIT");
    } catch (Exception e) {
    }
    boolean useParens = paramLength != 1 || explicit;
    if (useParens)
        print("(");
    if (explicit) {
        boolean first = true;
        for (JCVariableDecl vd : params) {
            if (!first)
                print(", ");
            first = false;
            printVarDefInline(vd);
        }
    } else {
        String sep = "";
        for (JCVariableDecl param : params) {
            print(sep);
            print(param.name);
            sep = ", ";
        }
    }
    if (useParens)
        print(")");
    print(" -> ");
    JCTree body = readObject(tree, "body", (JCTree) null);
    if (body instanceof JCBlock) {
        println("{");
        indent++;
        print(((JCBlock) body).stats, "");
        indent--;
        aPrint("}");
    } else {
        print(body);
    }
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCTree(com.sun.tools.javac.tree.JCTree) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException)

Aggregations

JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)98 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)56 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)36 JCTree (com.sun.tools.javac.tree.JCTree)31 JCMethodDecl (com.sun.tools.javac.tree.JCTree.JCMethodDecl)31 Name (com.sun.tools.javac.util.Name)31 JCBlock (com.sun.tools.javac.tree.JCTree.JCBlock)27 JavacNode (lombok.javac.JavacNode)27 ListBuffer (com.sun.tools.javac.util.ListBuffer)25 JCTypeParameter (com.sun.tools.javac.tree.JCTree.JCTypeParameter)24 JCClassDecl (com.sun.tools.javac.tree.JCTree.JCClassDecl)22 JCModifiers (com.sun.tools.javac.tree.JCTree.JCModifiers)18 JavacTreeMaker (lombok.javac.JavacTreeMaker)18 Tree (com.redhat.ceylon.compiler.typechecker.tree.Tree)13 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)12 Type (com.redhat.ceylon.model.typechecker.model.Type)11 SyntheticName (com.redhat.ceylon.compiler.java.codegen.Naming.SyntheticName)9 JCMethodInvocation (com.sun.tools.javac.tree.JCTree.JCMethodInvocation)9 JCPrimitiveTypeTree (com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree)8 Type (com.sun.tools.javac.code.Type)7