Search in sources :

Example 1 with JCExpression

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

the class HandleBuilder method handle.

@Override
public void handle(AnnotationValues<Builder> annotation, JCAnnotation ast, JavacNode annotationNode) {
    Builder builderInstance = annotation.getInstance();
    // These exist just to support the 'old' lombok.experimental.Builder, which had these properties. lombok.Builder no longer has them.
    boolean fluent = toBoolean(annotation.getActualExpression("fluent"), true);
    boolean chain = toBoolean(annotation.getActualExpression("chain"), true);
    String builderMethodName = builderInstance.builderMethodName();
    String buildMethodName = builderInstance.buildMethodName();
    String builderClassName = builderInstance.builderClassName();
    String toBuilderMethodName = "toBuilder";
    boolean toBuilder = builderInstance.toBuilder();
    java.util.List<Name> typeArgsForToBuilder = null;
    if (builderMethodName == null)
        builderMethodName = "builder";
    if (buildMethodName == null)
        buildMethodName = "build";
    if (builderClassName == null)
        builderClassName = "";
    if (!checkName("builderMethodName", builderMethodName, annotationNode))
        return;
    if (!checkName("buildMethodName", buildMethodName, annotationNode))
        return;
    if (!builderClassName.isEmpty()) {
        if (!checkName("builderClassName", builderClassName, annotationNode))
            return;
    }
    @SuppressWarnings("deprecation") Class<? extends Annotation> oldExperimentalBuilder = lombok.experimental.Builder.class;
    deleteAnnotationIfNeccessary(annotationNode, Builder.class, oldExperimentalBuilder);
    JavacNode parent = annotationNode.up();
    java.util.List<BuilderFieldData> builderFields = new ArrayList<BuilderFieldData>();
    JCExpression returnType;
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrownExceptions = List.nil();
    Name nameOfBuilderMethod;
    JavacNode tdParent;
    JavacNode fillParametersFrom = parent.get() instanceof JCMethodDecl ? parent : null;
    boolean addCleaning = false;
    boolean isStatic = true;
    if (parent.get() instanceof JCClassDecl) {
        tdParent = parent;
        JCClassDecl td = (JCClassDecl) tdParent.get();
        ListBuffer<JavacNode> allFields = new ListBuffer<JavacNode>();
        @SuppressWarnings("deprecation") boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation(lombok.experimental.Value.class, parent));
        for (JavacNode fieldNode : HandleConstructor.findAllFields(tdParent)) {
            JCVariableDecl fd = (JCVariableDecl) fieldNode.get();
            // Value will only skip making a field final if it has an explicit @NonFinal annotation, so we check for that.
            if (fd.init != null && valuePresent && !hasAnnotation(NonFinal.class, fieldNode))
                continue;
            BuilderFieldData bfd = new BuilderFieldData();
            bfd.rawName = fd.name;
            bfd.name = removePrefixFromField(fieldNode);
            bfd.type = fd.vartype;
            bfd.singularData = getSingularData(fieldNode);
            addObtainVia(bfd, fieldNode);
            builderFields.add(bfd);
            allFields.append(fieldNode);
        }
        new HandleConstructor().generateConstructor(tdParent, AccessLevel.PACKAGE, List.<JCAnnotation>nil(), allFields.toList(), false, null, SkipIfConstructorExists.I_AM_BUILDER, annotationNode);
        returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
        typeParams = td.typarams;
        thrownExceptions = List.nil();
        nameOfBuilderMethod = null;
        if (builderClassName.isEmpty())
            builderClassName = td.name.toString() + "Builder";
    } else if (fillParametersFrom != null && fillParametersFrom.getName().toString().equals("<init>")) {
        JCMethodDecl jmd = (JCMethodDecl) fillParametersFrom.get();
        if (!jmd.typarams.isEmpty()) {
            annotationNode.addError("@Builder is not supported on constructors with constructor type parameters.");
            return;
        }
        tdParent = parent.up();
        JCClassDecl td = (JCClassDecl) tdParent.get();
        returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
        typeParams = td.typarams;
        thrownExceptions = jmd.thrown;
        nameOfBuilderMethod = null;
        if (builderClassName.isEmpty())
            builderClassName = td.name.toString() + "Builder";
    } else if (fillParametersFrom != null) {
        tdParent = parent.up();
        JCClassDecl td = (JCClassDecl) tdParent.get();
        JCMethodDecl jmd = (JCMethodDecl) fillParametersFrom.get();
        isStatic = (jmd.mods.flags & Flags.STATIC) != 0;
        JCExpression fullReturnType = jmd.restype;
        returnType = fullReturnType;
        typeParams = jmd.typarams;
        thrownExceptions = jmd.thrown;
        nameOfBuilderMethod = jmd.name;
        if (returnType instanceof JCTypeApply) {
            returnType = ((JCTypeApply) returnType).clazz;
        }
        if (builderClassName.isEmpty()) {
            if (returnType instanceof JCFieldAccess) {
                builderClassName = ((JCFieldAccess) returnType).name.toString() + "Builder";
            } else if (returnType instanceof JCIdent) {
                Name n = ((JCIdent) returnType).name;
                for (JCTypeParameter tp : typeParams) {
                    if (tp.name.equals(n)) {
                        annotationNode.addError("@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type.");
                        return;
                    }
                }
                builderClassName = n.toString() + "Builder";
            } else if (returnType instanceof JCPrimitiveTypeTree) {
                builderClassName = returnType.toString() + "Builder";
                if (Character.isLowerCase(builderClassName.charAt(0))) {
                    builderClassName = Character.toTitleCase(builderClassName.charAt(0)) + builderClassName.substring(1);
                }
            } else {
                // This shouldn't happen.
                System.err.println("Lombok bug ID#20140614-1651: javac HandleBuilder: return type to name conversion failed: " + returnType.getClass());
                builderClassName = td.name.toString() + "Builder";
            }
        }
        if (toBuilder) {
            final String TO_BUILDER_NOT_SUPPORTED = "@Builder(toBuilder=true) is only supported if you return your own type.";
            if (returnType instanceof JCArrayTypeTree) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }
            Name simpleName;
            String pkg;
            List<JCExpression> tpOnRet = List.nil();
            if (fullReturnType instanceof JCTypeApply) {
                tpOnRet = ((JCTypeApply) fullReturnType).arguments;
            }
            if (returnType instanceof JCIdent) {
                simpleName = ((JCIdent) returnType).name;
                pkg = null;
            } else if (returnType instanceof JCFieldAccess) {
                JCFieldAccess jcfa = (JCFieldAccess) returnType;
                simpleName = jcfa.name;
                pkg = unpack(jcfa.selected);
                if (pkg.startsWith("ERR:")) {
                    String err = pkg.substring(4, pkg.indexOf("__ERR__"));
                    annotationNode.addError(err);
                    return;
                }
            } else {
                annotationNode.addError("Expected a (parameterized) type here instead of a " + returnType.getClass().getName());
                return;
            }
            if (pkg != null && !parent.getPackageDeclaration().equals(pkg)) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }
            if (!tdParent.getName().contentEquals(simpleName)) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }
            List<JCTypeParameter> tpOnMethod = jmd.typarams;
            List<JCTypeParameter> tpOnType = ((JCClassDecl) tdParent.get()).typarams;
            typeArgsForToBuilder = new ArrayList<Name>();
            for (JCTypeParameter tp : tpOnMethod) {
                int pos = -1;
                int idx = -1;
                for (JCExpression tOnRet : tpOnRet) {
                    idx++;
                    if (!(tOnRet instanceof JCIdent))
                        continue;
                    if (((JCIdent) tOnRet).name != tp.name)
                        continue;
                    pos = idx;
                }
                if (pos == -1 || tpOnType.size() <= pos) {
                    annotationNode.addError("@Builder(toBuilder=true) requires that each type parameter on the static method is part of the typeargs of the return value. Type parameter " + tp.name + " is not part of the return type.");
                    return;
                }
                typeArgsForToBuilder.add(tpOnType.get(pos).name);
            }
        }
    } else {
        annotationNode.addError("@Builder is only supported on types, constructors, and methods.");
        return;
    }
    if (fillParametersFrom != null) {
        for (JavacNode param : fillParametersFrom.down()) {
            if (param.getKind() != Kind.ARGUMENT)
                continue;
            BuilderFieldData bfd = new BuilderFieldData();
            JCVariableDecl raw = (JCVariableDecl) param.get();
            bfd.name = raw.name;
            bfd.rawName = raw.name;
            bfd.type = raw.vartype;
            bfd.singularData = getSingularData(param);
            addObtainVia(bfd, param);
            builderFields.add(bfd);
        }
    }
    JavacNode builderType = findInnerClass(tdParent, builderClassName);
    if (builderType == null) {
        builderType = makeBuilderClass(isStatic, annotationNode, tdParent, builderClassName, typeParams, ast);
    } else {
        JCClassDecl builderTypeDeclaration = (JCClassDecl) builderType.get();
        if (isStatic && !builderTypeDeclaration.getModifiers().getFlags().contains(Modifier.STATIC)) {
            annotationNode.addError("Existing Builder must be a static inner class.");
            return;
        } else if (!isStatic && builderTypeDeclaration.getModifiers().getFlags().contains(Modifier.STATIC)) {
            annotationNode.addError("Existing Builder must be a non-static inner class.");
            return;
        }
        sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode);
        /* generate errors for @Singular BFDs that have one already defined node. */
        {
            for (BuilderFieldData bfd : builderFields) {
                SingularData sd = bfd.singularData;
                if (sd == null)
                    continue;
                JavacSingularizer singularizer = sd.getSingularizer();
                if (singularizer == null)
                    continue;
                if (singularizer.checkForAlreadyExistingNodesAndGenerateError(builderType, sd)) {
                    bfd.singularData = null;
                }
            }
        }
    }
    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            if (bfd.singularData.getSingularizer().requiresCleaning()) {
                addCleaning = true;
                break;
            }
        }
        if (bfd.obtainVia != null) {
            if (bfd.obtainVia.field().isEmpty() == bfd.obtainVia.method().isEmpty()) {
                bfd.obtainViaNode.addError("The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\").");
                return;
            }
            if (bfd.obtainVia.method().isEmpty() && bfd.obtainVia.isStatic()) {
                bfd.obtainViaNode.addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set.");
                return;
            }
        }
    }
    generateBuilderFields(builderType, builderFields, ast);
    if (addCleaning) {
        JavacTreeMaker maker = builderType.getTreeMaker();
        JCVariableDecl uncleanField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), builderType.toName("$lombokUnclean"), maker.TypeIdent(CTC_BOOLEAN), null);
        injectFieldAndMarkGenerated(builderType, uncleanField);
    }
    if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) {
        JCMethodDecl cd = HandleConstructor.createConstructor(AccessLevel.PACKAGE, List.<JCAnnotation>nil(), builderType, List.<JavacNode>nil(), false, annotationNode);
        if (cd != null)
            injectMethod(builderType, cd);
    }
    for (BuilderFieldData bfd : builderFields) {
        makeSetterMethodsForBuilder(builderType, bfd, annotationNode, fluent, chain);
    }
    if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) {
        JCMethodDecl md = generateBuildMethod(isStatic, buildMethodName, nameOfBuilderMethod, returnType, builderFields, builderType, thrownExceptions, ast, addCleaning);
        if (md != null)
            injectMethod(builderType, md);
    }
    if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
        java.util.List<JavacNode> fieldNodes = new ArrayList<JavacNode>();
        for (BuilderFieldData bfd : builderFields) {
            fieldNodes.addAll(bfd.createdFields);
        }
        JCMethodDecl md = HandleToString.createToString(builderType, fieldNodes, true, false, FieldAccess.ALWAYS_FIELD, ast);
        if (md != null)
            injectMethod(builderType, md);
    }
    if (addCleaning)
        injectMethod(builderType, generateCleanMethod(builderFields, builderType, ast));
    if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) {
        JCMethodDecl md = generateBuilderMethod(isStatic, builderMethodName, builderClassName, annotationNode, tdParent, typeParams);
        recursiveSetGeneratedBy(md, ast, annotationNode.getContext());
        if (md != null)
            injectMethod(tdParent, md);
    }
    if (toBuilder) {
        switch(methodExists(toBuilderMethodName, tdParent, 0)) {
            case EXISTS_BY_USER:
                annotationNode.addWarning("Not generating toBuilder() as it already exists.");
                return;
            case NOT_EXISTS:
                List<JCTypeParameter> tps = typeParams;
                if (typeArgsForToBuilder != null) {
                    ListBuffer<JCTypeParameter> lb = new ListBuffer<JCTypeParameter>();
                    JavacTreeMaker maker = tdParent.getTreeMaker();
                    for (Name n : typeArgsForToBuilder) {
                        lb.append(maker.TypeParameter(n, List.<JCExpression>nil()));
                    }
                    tps = lb.toList();
                }
                JCMethodDecl md = generateToBuilderMethod(toBuilderMethodName, builderClassName, tdParent, tps, builderFields, fluent, ast);
                if (md != null)
                    injectMethod(tdParent, md);
        }
    }
    recursiveSetGeneratedBy(builderType.get(), ast, annotationNode.getContext());
}
Also used : JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) Builder(lombok.Builder) ListBuffer(com.sun.tools.javac.util.ListBuffer) ArrayList(java.util.ArrayList) JCTypeApply(com.sun.tools.javac.tree.JCTree.JCTypeApply) JavacSingularizer(lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer) Name(com.sun.tools.javac.util.Name) JCPrimitiveTypeTree(com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree) JavacNode(lombok.javac.JavacNode) JCArrayTypeTree(com.sun.tools.javac.tree.JCTree.JCArrayTypeTree) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) SingularData(lombok.javac.handlers.JavacSingularsRecipes.SingularData)

Example 2 with JCExpression

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

the class HandleBuilder method generateBuildMethod.

private JCMethodDecl generateBuildMethod(boolean isStatic, String buildName, Name builderName, JCExpression returnType, java.util.List<BuilderFieldData> builderFields, JavacNode type, List<JCExpression> thrownExceptions, JCTree source, boolean addCleaning) {
    JavacTreeMaker maker = type.getTreeMaker();
    JCExpression call;
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    if (addCleaning) {
        JCExpression notClean = maker.Unary(CTC_NOT, maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")));
        JCStatement invokeClean = maker.Exec(maker.Apply(List.<JCExpression>nil(), maker.Ident(type.toName("$lombokClean")), List.<JCExpression>nil()));
        JCIf ifUnclean = maker.If(notClean, invokeClean, null);
        statements.append(ifUnclean);
    }
    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.singularData.getSingularizer().appendBuildCode(bfd.singularData, type, source, statements, bfd.name);
        }
    }
    ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
    for (BuilderFieldData bfd : builderFields) {
        args.append(maker.Ident(bfd.name));
    }
    if (addCleaning) {
        statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, true))));
    }
    if (builderName == null) {
        call = maker.NewClass(null, List.<JCExpression>nil(), returnType, args.toList(), null);
        statements.append(maker.Return(call));
    } else {
        ListBuffer<JCExpression> typeParams = new ListBuffer<JCExpression>();
        for (JCTypeParameter tp : ((JCClassDecl) type.get()).typarams) {
            typeParams.append(maker.Ident(tp.name));
        }
        JCExpression callee = maker.Ident(((JCClassDecl) type.up().get()).name);
        if (!isStatic)
            callee = maker.Select(callee, type.up().toName("this"));
        JCExpression fn = maker.Select(callee, builderName);
        call = maker.Apply(typeParams.toList(), fn, args.toList());
        if (returnType instanceof JCPrimitiveTypeTree && CTC_VOID.equals(typeTag(returnType))) {
            statements.append(maker.Exec(call));
        } else {
            statements.append(maker.Return(call));
        }
    }
    JCBlock body = maker.Block(0, statements.toList());
    return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(buildName), returnType, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), thrownExceptions, body, null);
}
Also used : JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCPrimitiveTypeTree(com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCIf(com.sun.tools.javac.tree.JCTree.JCIf) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement)

Example 3 with JCExpression

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

the class HandleBuilder method getSingularData.

/**
	 * Returns the explicitly requested singular annotation on this node (field
	 * or parameter), or null if there's no {@code @Singular} annotation on it.
	 * 
	 * @param node The node (field or method param) to inspect for its name and potential {@code @Singular} annotation.
	 */
private SingularData getSingularData(JavacNode node) {
    for (JavacNode child : node.down()) {
        if (!annotationTypeMatches(Singular.class, child))
            continue;
        Name pluralName = node.getKind() == Kind.FIELD ? removePrefixFromField(node) : ((JCVariableDecl) node.get()).name;
        AnnotationValues<Singular> ann = createAnnotation(Singular.class, child);
        deleteAnnotationIfNeccessary(child, Singular.class);
        String explicitSingular = ann.getInstance().value();
        if (explicitSingular.isEmpty()) {
            if (Boolean.FALSE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_AUTO))) {
                node.addError("The singular must be specified explicitly (e.g. @Singular(\"task\")) because auto singularization is disabled.");
                explicitSingular = pluralName.toString();
            } else {
                explicitSingular = autoSingularize(pluralName.toString());
                if (explicitSingular == null) {
                    node.addError("Can't singularize this name; please specify the singular explicitly (i.e. @Singular(\"sheep\"))");
                    explicitSingular = pluralName.toString();
                }
            }
        }
        Name singularName = node.toName(explicitSingular);
        JCExpression type = null;
        if (node.get() instanceof JCVariableDecl) {
            type = ((JCVariableDecl) node.get()).vartype;
        }
        String name = null;
        List<JCExpression> typeArgs = List.nil();
        if (type instanceof JCTypeApply) {
            typeArgs = ((JCTypeApply) type).arguments;
            type = ((JCTypeApply) type).clazz;
        }
        name = type.toString();
        String targetFqn = JavacSingularsRecipes.get().toQualified(name);
        JavacSingularizer singularizer = JavacSingularsRecipes.get().getSingularizer(targetFqn);
        if (singularizer == null) {
            node.addError("Lombok does not know how to create the singular-form builder methods for type '" + name + "'; they won't be generated.");
            return null;
        }
        return new SingularData(child, singularName, pluralName, typeArgs, targetFqn, singularizer);
    }
    return null;
}
Also used : Singular(lombok.Singular) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JavacNode(lombok.javac.JavacNode) SingularData(lombok.javac.handlers.JavacSingularsRecipes.SingularData) JCTypeApply(com.sun.tools.javac.tree.JCTree.JCTypeApply) JavacSingularizer(lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name)

Example 4 with JCExpression

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

the class HandleCleanup method handle.

@Override
public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");
    if (inNetbeansEditor(annotationNode))
        return;
    deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
    String cleanupName = annotation.getInstance().value();
    if (cleanupName.length() == 0) {
        annotationNode.addError("cleanupName cannot be the empty string.");
        return;
    }
    if (annotationNode.up().getKind() != Kind.LOCAL) {
        annotationNode.addError("@Cleanup is legal only on local variable declarations.");
        return;
    }
    JCVariableDecl decl = (JCVariableDecl) annotationNode.up().get();
    if (decl.init == null) {
        annotationNode.addError("@Cleanup variable declarations need to be initialized.");
        return;
    }
    JavacNode ancestor = annotationNode.up().directUp();
    JCTree blockNode = ancestor.get();
    final List<JCStatement> statements;
    if (blockNode instanceof JCBlock) {
        statements = ((JCBlock) blockNode).stats;
    } else if (blockNode instanceof JCCase) {
        statements = ((JCCase) blockNode).stats;
    } else if (blockNode instanceof JCMethodDecl) {
        statements = ((JCMethodDecl) blockNode).body.stats;
    } else {
        annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
        return;
    }
    boolean seenDeclaration = false;
    ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>();
    ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>();
    for (JCStatement statement : statements) {
        if (!seenDeclaration) {
            if (statement == decl)
                seenDeclaration = true;
            newStatements.append(statement);
        } else {
            tryBlock.append(statement);
        }
    }
    if (!seenDeclaration) {
        annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
        return;
    }
    doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);
    JavacTreeMaker maker = annotationNode.getTreeMaker();
    JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
    List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));
    JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
    JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));
    JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);
    Context context = annotationNode.getContext();
    JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast, context);
    newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.<JCCatch>nil(), finalizer), ast, context));
    if (blockNode instanceof JCBlock) {
        ((JCBlock) blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCCase) {
        ((JCCase) blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCMethodDecl) {
        ((JCMethodDecl) blockNode).body.stats = newStatements.toList();
    } else
        throw new AssertionError("Should not get here");
    ancestor.rebuild();
}
Also used : Context(com.sun.tools.javac.util.Context) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCTree(com.sun.tools.javac.tree.JCTree) JCBinary(com.sun.tools.javac.tree.JCTree.JCBinary) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JavacNode(lombok.javac.JavacNode) JCIf(com.sun.tools.javac.tree.JCTree.JCIf) JCCase(com.sun.tools.javac.tree.JCTree.JCCase)

Example 5 with JCExpression

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

the class HandleConstructor method createStaticConstructor.

public JCMethodDecl createStaticConstructor(String name, AccessLevel level, JavacNode typeNode, List<JavacNode> fields, JCTree source) {
    JavacTreeMaker maker = typeNode.getTreeMaker();
    JCClassDecl type = (JCClassDecl) typeNode.get();
    JCModifiers mods = maker.Modifiers(Flags.STATIC | toJavacModifier(level));
    JCExpression returnType, constructorType;
    ListBuffer<JCTypeParameter> typeParams = new ListBuffer<JCTypeParameter>();
    ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();
    ListBuffer<JCExpression> typeArgs1 = new ListBuffer<JCExpression>();
    ListBuffer<JCExpression> typeArgs2 = new ListBuffer<JCExpression>();
    ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
    if (!type.typarams.isEmpty()) {
        for (JCTypeParameter param : type.typarams) {
            typeArgs1.append(maker.Ident(param.name));
            typeArgs2.append(maker.Ident(param.name));
            typeParams.append(maker.TypeParameter(param.name, param.bounds));
        }
        returnType = maker.TypeApply(maker.Ident(type.name), typeArgs1.toList());
        constructorType = maker.TypeApply(maker.Ident(type.name), typeArgs2.toList());
    } else {
        returnType = maker.Ident(type.name);
        constructorType = maker.Ident(type.name);
    }
    for (JavacNode fieldNode : fields) {
        JCVariableDecl field = (JCVariableDecl) fieldNode.get();
        Name fieldName = removePrefixFromField(fieldNode);
        JCExpression pType = cloneType(maker, field.vartype, source, typeNode.getContext());
        List<JCAnnotation> nonNulls = findAnnotations(fieldNode, NON_NULL_PATTERN);
        List<JCAnnotation> nullables = findAnnotations(fieldNode, NULLABLE_PATTERN);
        long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
        JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, nonNulls.appendList(nullables)), fieldName, pType, null);
        params.append(param);
        args.append(maker.Ident(fieldName));
    }
    JCReturn returnStatement = maker.Return(maker.NewClass(null, List.<JCExpression>nil(), constructorType, args.toList(), null));
    JCBlock body = maker.Block(0, List.<JCStatement>of(returnStatement));
    return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(name), returnType, typeParams.toList(), params.toList(), List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
Also used : JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCReturn(com.sun.tools.javac.tree.JCTree.JCReturn) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) ListBuffer(com.sun.tools.javac.util.ListBuffer) 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) JavacNode(lombok.javac.JavacNode) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation)

Aggregations

JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)311 JCTree (com.sun.tools.javac.tree.JCTree)95 Type (com.redhat.ceylon.model.typechecker.model.Type)85 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)81 Tree (com.redhat.ceylon.compiler.typechecker.tree.Tree)67 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)59 ListBuffer (com.sun.tools.javac.util.ListBuffer)54 JCTypeParameter (com.sun.tools.javac.tree.JCTree.JCTypeParameter)39 Name (com.sun.tools.javac.util.Name)39 SyntheticName (com.redhat.ceylon.compiler.java.codegen.Naming.SyntheticName)37 TypeDeclaration (com.redhat.ceylon.model.typechecker.model.TypeDeclaration)35 TypedDeclaration (com.redhat.ceylon.model.typechecker.model.TypedDeclaration)34 JCBlock (com.sun.tools.javac.tree.JCTree.JCBlock)34 JavacTreeMaker (lombok.javac.JavacTreeMaker)33 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)30 TypeParameter (com.redhat.ceylon.model.typechecker.model.TypeParameter)29 Declaration (com.redhat.ceylon.model.typechecker.model.Declaration)27 Function (com.redhat.ceylon.model.typechecker.model.Function)26 Parameter (com.redhat.ceylon.model.typechecker.model.Parameter)26 JCNewClass (com.sun.tools.javac.tree.JCTree.JCNewClass)26