From 849aa4fddadb40439a30967131d2847b90fb139f Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Sun, 9 Sep 2018 19:47:51 +0200 Subject: SuperBuilder toBuilder; test cases --- src/core/lombok/experimental/SuperBuilder.java | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/core/lombok/experimental/SuperBuilder.java b/src/core/lombok/experimental/SuperBuilder.java index 26127a5f..be6ea304 100644 --- a/src/core/lombok/experimental/SuperBuilder.java +++ b/src/core/lombok/experimental/SuperBuilder.java @@ -1,16 +1,16 @@ /* * Copyright (C) 2018 The Project Lombok Authors. - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,7 +43,7 @@ import lombok.Singular; * The builder also has a build() method which returns a completed instance of the original type. *

* Complete documentation is found at the project lombok features page for @SuperBuilder. - * + * * @see Singular */ @Target(TYPE) @@ -51,16 +51,15 @@ import lombok.Singular; public @interface SuperBuilder { /** @return Name of the method that creates a new builder instance. Default: {@code builder}. */ String builderMethodName() default "builder"; - + /** @return Name of the method in the builder class that creates an instance of your {@code @Builder}-annotated class. */ String buildMethodName() default "build"; - - // toBuilder also requires a two-stage system where each class gets its own toBuilder but calls on a second method (and also calls parentclass's method) - // to fill the builder, as this class does not know what fields to pass on to the builder. Let's consider this, but only for milestone 2. - /* - * If true, generate an instance method to obtain a builder that is initialized with the values of this instance. - * + + /** + * If true, generate an instance method to obtain a builder that is initialized with the values of this instance. + * In this case, all superclasses must also have toBuilder=true. + * * @return Whether to generate a {@code toBuilder()} method. */ -// boolean toBuilder() default false; + boolean toBuilder() default false; } -- cgit From b42ce5325afbe6202d5d5815a9c74dd64a0ce3de Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Tue, 11 Sep 2018 10:32:50 +0200 Subject: SuperBuilder: generate toBuilder method (javac) --- src/core/lombok/javac/handlers/HandleBuilder.java | 2 +- .../lombok/javac/handlers/HandleSuperBuilder.java | 67 +++++++++++++++++----- 2 files changed, 53 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/core/lombok/javac/handlers/HandleBuilder.java b/src/core/lombok/javac/handlers/HandleBuilder.java index 63697691..91cd4abb 100644 --- a/src/core/lombok/javac/handlers/HandleBuilder.java +++ b/src/core/lombok/javac/handlers/HandleBuilder.java @@ -84,7 +84,7 @@ public class HandleBuilder extends JavacAnnotationHandler { return ((Boolean) expr).booleanValue(); } - private static class BuilderFieldData { + public static class BuilderFieldData { JCExpression type; Name rawName; Name name; diff --git a/src/core/lombok/javac/handlers/HandleSuperBuilder.java b/src/core/lombok/javac/handlers/HandleSuperBuilder.java index b8f572d5..62dc93c1 100644 --- a/src/core/lombok/javac/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/javac/handlers/HandleSuperBuilder.java @@ -68,6 +68,7 @@ import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.HandleBuilder.BuilderFieldData; import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import lombok.javac.handlers.JavacSingularsRecipes.ExpressionMaker; import lombok.javac.handlers.JavacSingularsRecipes.StatementMaker; @@ -78,21 +79,9 @@ import lombok.javac.handlers.JavacSingularsRecipes.SingularData; @HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes. public class HandleSuperBuilder extends JavacAnnotationHandler { private static final String SELF_METHOD = "self"; - - private static class BuilderFieldData { - JCExpression type; - Name rawName; - Name name; - Name nameOfDefaultProvider; - Name nameOfSetFlag; - SingularData singularData; - ObtainVia obtainVia; - JavacNode obtainViaNode; - JavacNode originalFieldNode; - - java.util.List createdFields = new ArrayList(); - } - + private static final String TO_BUILDER_METHOD_NAME = "toBuilder"; + private static final String FILL_VALUES_METHOD_NAME = "$fillValuesFrom"; + @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.SUPERBUILDER_FLAG_USAGE, "@SuperBuilder"); @@ -109,6 +98,8 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { if (!checkName("builderMethodName", builderMethodName, annotationNode)) return; if (!checkName("buildMethodName", buildMethodName, annotationNode)) return; + boolean toBuilder = superbuilderAnnotation.toBuilder(); + JavacNode tdParent = annotationNode.up(); java.util.List builderFields = new ArrayList(); @@ -307,6 +298,19 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { if (builderMethod != null) injectMethod(tdParent, builderMethod); } } + + if (toBuilder) { + switch (methodExists(TO_BUILDER_METHOD_NAME, tdParent, 0)) { + case EXISTS_BY_USER: + annotationNode.addWarning("Not generating toBuilder() as it already exists."); + return; + case NOT_EXISTS: + JCMethodDecl md = generateToBuilderMethod(builderClassName, builderImplClassName, annotationNode, tdParent, typeParams); + if (md != null) { + injectMethod(tdParent, md); + } + } + } } /** @@ -495,6 +499,39 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { return maker.MethodDef(maker.Modifiers(modifiers), type.toName(builderMethodName), returnType, copyTypeParams(source, typeParams), List.nil(), List.nil(), body, null); } + /** + * Generates a toBuilder() method that looks like this: + *

+	 * public ParentBuilder<?, ?> toBuilder() {
+	 *     return new FoobarBuilderImpl().$fillValuesFrom(this);
+	 * }
+	 * 
+ */ + private JCMethodDecl generateToBuilderMethod(String builderClassName, String builderImplClassName, JavacNode source, JavacNode type, List typeParams) { + JavacTreeMaker maker = type.getTreeMaker(); + + ListBuffer typeArgs = new ListBuffer(); + for (JCTypeParameter typeParam : typeParams) typeArgs.append(maker.Ident(typeParam.name)); + + JCExpression newClass = maker.NewClass(null, List.nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderImplClassName), typeParams), List.nil(), null); + JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), List.nil()); + JCStatement statement = maker.Return(invokeFillMethod); + + JCBlock body = maker.Block(0, List.of(statement)); + int modifiers = Flags.PUBLIC; + + // Add any type params of the annotated class to the return type. + ListBuffer typeParameterNames = new ListBuffer(); + typeParameterNames.addAll(typeParameterNames(maker, typeParams)); + // Now add the . + JCWildcard wildcard = maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); + typeParameterNames.add(wildcard); + typeParameterNames.add(wildcard); + JCTypeApply returnType = maker.TypeApply(maker.Ident(type.toName(builderClassName)), typeParameterNames.toList()); + + return maker.MethodDef(maker.Modifiers(modifiers), type.toName(TO_BUILDER_METHOD_NAME), returnType, copyTypeParams(source, typeParams), List.nil(), List.nil(), body, null); + } + private JCMethodDecl generateAbstractSelfMethod(JavacNode type, boolean override, String builderGenericName) { JavacTreeMaker maker = type.getTreeMaker(); List annotations = List.nil(); -- cgit From abb0d2374e0ca6cda55c5ea63f51235111701081 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Tue, 11 Sep 2018 14:52:15 +0200 Subject: SuperBuilder: generate fillValuesFrom method (javac) --- .../lombok/javac/handlers/HandleSuperBuilder.java | 95 +++++++++++++++++++++- 1 file changed, 92 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/core/lombok/javac/handlers/HandleSuperBuilder.java b/src/core/lombok/javac/handlers/HandleSuperBuilder.java index 62dc93c1..01ac2794 100644 --- a/src/core/lombok/javac/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/javac/handlers/HandleSuperBuilder.java @@ -37,11 +37,13 @@ import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; +import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; @@ -234,6 +236,9 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { injectFieldAndMarkGenerated(builderType, uncleanField); } + // Generate $fillValuesFrom() method in the abstract builder. + injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName, classGenericName, builderFields)); + // Generate abstract self() and build() methods in the abstract builder. injectMethod(builderType, generateAbstractSelfMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName)); injectMethod(builderType, generateAbstractBuildMethod(tdParent, buildMethodName, superclassBuilderClassExpression != null, classGenericName)); @@ -500,7 +505,7 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { } /** - * Generates a toBuilder() method that looks like this: + * Generates a toBuilder() method in the annotated class that looks like this: *
 	 * public ParentBuilder<?, ?> toBuilder() {
 	 *     return new FoobarBuilderImpl().$fillValuesFrom(this);
@@ -514,7 +519,9 @@ public class HandleSuperBuilder extends JavacAnnotationHandler {
 		for (JCTypeParameter typeParam : typeParams) typeArgs.append(maker.Ident(typeParam.name));
 		
 		JCExpression newClass = maker.NewClass(null, List.nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderImplClassName), typeParams), List.nil(), null);
-		JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), List.nil());
+		List methodArgs = List.of(maker.Ident(type.toName("this")));
+		JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), methodArgs);
+//		JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), List.nil());
 		JCStatement statement = maker.Return(invokeFillMethod);
 		
 		JCBlock body = maker.Block(0, List.of(statement));
@@ -531,6 +538,88 @@ public class HandleSuperBuilder extends JavacAnnotationHandler {
 		
 		return maker.MethodDef(maker.Modifiers(modifiers), type.toName(TO_BUILDER_METHOD_NAME), returnType, copyTypeParams(source, typeParams), List.nil(), List.nil(), body, null);
 	}
+
+	/**
+	 * Generates a $fillValuesFrom() method in the abstract builder class that looks
+	 * like this:
+	 * 
+	 * protected B $fillValuesFrom(final C instance) {
+	 *     super.$fillValuesFrom(instance);
+	 *     this.field(instance.field);
+	 *     return self();
+	 * }
+	 * 
+ */ + private JCMethodDecl generateFillValuesMethod(JavacNode type, boolean inherited, String builderGenericName, String classGenericName, java.util.List builderFields) { + JavacTreeMaker maker = type.getTreeMaker(); + List annotations = List.nil(); + if (inherited) { + JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(type, "Override"), List.nil()); + annotations = List.of(overrideAnnotation); + } + JCModifiers modifiers = maker.Modifiers(Flags.PROTECTED, annotations); + Name name = type.toName(FILL_VALUES_METHOD_NAME); + JCExpression returnType = maker.Ident(type.toName(builderGenericName)); + + final String instanceVariableName = "instance"; + JCExpression classGenericNameExpr = maker.Ident(type.toName(classGenericName)); + JCVariableDecl param = maker.VarDef(maker.Modifiers(Flags.LocalVarFlags), type.toName(instanceVariableName), classGenericNameExpr, null); + + ListBuffer body = new ListBuffer(); + + if (inherited) { + // Call super. + JCMethodInvocation callToSuper = maker.Apply(List.nil(), + maker.Select(maker.Ident(type.toName("super")), name), + List.of(maker.Ident(type.toName(instanceVariableName)))); + body.append(maker.Exec(callToSuper)); + } + + // Call the builder's setter methods to fill the values from the instance. + for (BuilderFieldData bfd : builderFields) { + JCExpressionStatement exec = createSetterCallWithInstanceValue(bfd, instanceVariableName, type, maker); + body.append(exec); + } + + JCReturn returnStatement = maker.Return(maker.Apply(List.nil(), maker.Ident(type.toName(SELF_METHOD)), List.nil())); + body.append(returnStatement); + JCBlock bodyBlock = maker.Block(0, body.toList()); + + return maker.MethodDef(modifiers, name, returnType, List.nil(), List.of(param), List.nil(), bodyBlock, null); + } + + private JCExpressionStatement createSetterCallWithInstanceValue(BuilderFieldData bfd, final String instanceVariableName, JavacNode type, JavacTreeMaker maker) { + JCExpression[] tgt = new JCExpression[bfd.singularData == null ? 1 : 2]; + if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { + for (int i = 0; i < tgt.length; i++) { + tgt[i] = maker.Select(maker.Ident(type.toName(instanceVariableName)), bfd.obtainVia == null ? bfd.rawName : type.toName(bfd.obtainVia.field())); + } + } else { + if (bfd.obtainVia.isStatic()) { + for (int i = 0; i < tgt.length; i++) { + JCExpression c = maker.Select(maker.Ident(type.toName(type.getName())), type.toName(bfd.obtainVia.method())); + tgt[i] = maker.Apply(List.nil(), c, List.of(maker.Ident(type.toName(instanceVariableName)))); + } + } else { + for (int i = 0; i < tgt.length; i++) { + JCExpression c = maker.Select(maker.Ident(type.toName(instanceVariableName)), type.toName(bfd.obtainVia.method())); + tgt[i] = maker.Apply(List.nil(), c, List.nil()); + } + } + } + + JCExpression arg; + if (bfd.singularData == null) { + arg = tgt[0]; + } else { + JCExpression eqNull = maker.Binary(CTC_EQUAL, tgt[0], maker.Literal(CTC_BOT, null)); + JCExpression emptyList = maker.Apply(List.nil(), chainDots(type, "java", "util", "Collections", "emptyList"), List.nil()); + arg = maker.Conditional(eqNull, emptyList, tgt[1]); + } + JCMethodInvocation apply = maker.Apply(List.nil(), maker.Select(maker.Ident(type.toName("this")), bfd.name), List.of(arg)); + JCExpressionStatement exec = maker.Exec(apply); + return exec; + } private JCMethodDecl generateAbstractSelfMethod(JavacNode type, boolean override, String builderGenericName) { JavacTreeMaker maker = type.getTreeMaker(); @@ -542,7 +631,7 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { JCModifiers modifiers = maker.Modifiers(Flags.PROTECTED | Flags.ABSTRACT, annotations); Name name = type.toName(SELF_METHOD); JCExpression returnType = maker.Ident(type.toName(builderGenericName)); - + return maker.MethodDef(modifiers, name, returnType, List.nil(), List.nil(), List.nil(), null, null); } -- cgit From 1f3688fdba92508e091eab39b6131dbca2a8ef83 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Tue, 11 Sep 2018 16:36:25 +0200 Subject: SuperBuilder: generate fillValuesFrom method (ecj) --- .../lombok/eclipse/handlers/HandleBuilder.java | 2 +- .../eclipse/handlers/HandleSuperBuilder.java | 127 ++++++++++++++++++--- .../lombok/javac/handlers/HandleSuperBuilder.java | 6 +- 3 files changed, 113 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/core/lombok/eclipse/handlers/HandleBuilder.java b/src/core/lombok/eclipse/handlers/HandleBuilder.java index 9a069c58..5d417bde 100644 --- a/src/core/lombok/eclipse/handlers/HandleBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleBuilder.java @@ -105,7 +105,7 @@ public class HandleBuilder extends EclipseAnnotationHandler { return ((Boolean) expr).booleanValue(); } - private static class BuilderFieldData { + public static class BuilderFieldData { TypeReference type; char[] rawName; char[] name; diff --git a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java index 3c07ac55..6c1b2cac 100644 --- a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java @@ -39,7 +39,9 @@ import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; +import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; @@ -48,6 +50,8 @@ import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.NullLiteral; +import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; @@ -56,6 +60,7 @@ import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; @@ -87,6 +92,7 @@ import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer; import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData; import lombok.eclipse.handlers.EclipseSingularsRecipes.StatementMaker; import lombok.eclipse.handlers.EclipseSingularsRecipes.TypeReferenceMaker; +import lombok.eclipse.handlers.HandleBuilder.BuilderFieldData; import lombok.experimental.NonFinal; import lombok.experimental.SuperBuilder; @@ -98,40 +104,31 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { private static final char[] DEFAULT_PREFIX = "$default$".toCharArray(); private static final char[] SET_PREFIX = "$set".toCharArray(); private static final char[] SELF_METHOD_NAME = "self".toCharArray(); + private static final char[] TO_BUILDER_METHOD_NAME = "toBuilder".toCharArray(); + private static final char[] FILL_VALUES_METHOD_NAME = "$fillValuesFrom".toCharArray(); + private static final char[] EMPTY_LIST = "emptyList".toCharArray(); private static final AbstractMethodDeclaration[] EMPTY_METHODS = {}; - private static class BuilderFieldData { - TypeReference type; - char[] rawName; - char[] name; - char[] nameOfDefaultProvider; - char[] nameOfSetFlag; - SingularData singularData; - ObtainVia obtainVia; - EclipseNode obtainViaNode; - EclipseNode originalFieldNode; - - List createdFields = new ArrayList(); - } - @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.SUPERBUILDER_FLAG_USAGE, "@SuperBuilder"); long p = (long) ast.sourceStart << 32 | ast.sourceEnd; - SuperBuilder builderInstance = annotation.getInstance(); + SuperBuilder superbuilderAnnotation = annotation.getInstance(); - String builderMethodName = builderInstance.builderMethodName(); - String buildMethodName = builderInstance.buildMethodName(); + String builderMethodName = superbuilderAnnotation.builderMethodName(); + String buildMethodName = superbuilderAnnotation.buildMethodName(); if (builderMethodName == null) builderMethodName = "builder"; if (buildMethodName == null) buildMethodName = "build"; if (!checkName("builderMethodName", builderMethodName, annotationNode)) return; if (!checkName("buildMethodName", buildMethodName, annotationNode)) return; - + + boolean toBuilder = superbuilderAnnotation.toBuilder(); + EclipseNode tdParent = annotationNode.up(); java.util.List builderFields = new ArrayList(); @@ -293,7 +290,12 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { cleanDecl.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); injectFieldAndMarkGenerated(builderType, cleanDecl); } - + + if (toBuilder) { + // Generate $fillValuesFrom() method in the abstract builder. + injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClass != null, builderGenericName, classGenericName, typeParams, builderFields, ast)); + } + // Generate abstract self() and build() methods in the abstract builder. injectMethod(builderType, generateAbstractSelfMethod(tdParent, superclassBuilderClass != null, builderGenericName)); injectMethod(builderType, generateAbstractBuildMethod(tdParent, buildMethodName, superclassBuilderClass != null, classGenericName, ast)); @@ -532,6 +534,93 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { return out; } + /** + * Generates a $fillValuesFrom() method in the abstract builder class that looks + * like this: + *
+	 * protected B $fillValuesFrom(final C instance) {
+	 *     super.$fillValuesFrom(instance);
+	 *     this.field(instance.field);
+	 *     return self();
+	 * }
+	 * 
+ */ + private MethodDeclaration generateFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderGenericName, String classGenericName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { + MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) tdParent.top().get()).compilationResult); + out.selector = FILL_VALUES_METHOD_NAME; + out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + out.modifiers = ClassFileConstants.AccProtected; + if (inherited) out.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, tdParent.get())}; + out.returnType = new SingleTypeReference(builderGenericName.toCharArray(), 0); + + final String instanceVariableName = "instance"; + TypeReference builderType = createTypeReferenceWithTypeParameters(classGenericName, typeParams); + out.arguments = new Argument[] {new Argument(instanceVariableName.toCharArray(), 0, builderType, Modifier.FINAL)}; + + List body = new ArrayList(); + + if (inherited) { + // Call super. + MessageSend callToSuper = new MessageSend(); + callToSuper.receiver = new SuperReference(0, 0); + callToSuper.selector = FILL_VALUES_METHOD_NAME; + callToSuper.arguments = new Expression[] {new SingleNameReference(instanceVariableName.toCharArray(), 0)}; + body.add(callToSuper); + } + + // Call the builder's setter methods to fill the values from the instance. + for (BuilderFieldData bfd : builderFields) { + MessageSend exec = createSetterCallWithInstanceValue(bfd, instanceVariableName, tdParent, source); + body.add(exec); + } + + MessageSend returnCall = new MessageSend(); + returnCall.receiver = ThisReference.implicitThis(); + returnCall.selector = SELF_METHOD_NAME; + body.add(new ReturnStatement(returnCall, 0, 0)); + + out.statements = body.isEmpty() ? null : body.toArray(new Statement[body.size()]); + + return out; + } + + private MessageSend createSetterCallWithInstanceValue(BuilderFieldData bfd, final String instanceVariableName, EclipseNode type, ASTNode source) { + char[] setterName = bfd.name; + MessageSend ms = new MessageSend(); + Expression[] tgt = new Expression[bfd.singularData == null ? 1 : 2]; + + if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { + char[] fieldName = bfd.obtainVia == null ? bfd.rawName : bfd.obtainVia.field().toCharArray(); + for (int i = 0; i < tgt.length; i++) { + FieldReference fr = new FieldReference(fieldName, 0); + fr.receiver = new SingleNameReference(instanceVariableName.toCharArray(), 0); + tgt[i] = fr; + } + } else { + String obtainName = bfd.obtainVia.method(); + boolean obtainIsStatic = bfd.obtainVia.isStatic(); + for (int i = 0; i < tgt.length; i++) { + MessageSend obtainExpr = new MessageSend(); + obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new ThisReference(0, 0); + obtainExpr.selector = obtainName.toCharArray(); + if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new ThisReference(0, 0)}; + tgt[i] = obtainExpr; + } + } + if (bfd.singularData == null) { + ms.arguments = tgt; + } else { + Expression ifNull = new EqualExpression(tgt[0], new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); + MessageSend emptyList = new MessageSend(); + emptyList.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Collections".toCharArray()); + emptyList.selector = EMPTY_LIST; + ms.arguments = new Expression[] {new ConditionalExpression(ifNull, emptyList, tgt[1])}; + } + ms.receiver = ThisReference.implicitThis(); + ms.selector = setterName; + return ms; + } + private MethodDeclaration generateAbstractSelfMethod(EclipseNode tdParent, boolean override, String builderGenericName) { MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) tdParent.top().get()).compilationResult); out.selector = SELF_METHOD_NAME; diff --git a/src/core/lombok/javac/handlers/HandleSuperBuilder.java b/src/core/lombok/javac/handlers/HandleSuperBuilder.java index 01ac2794..c8727f93 100644 --- a/src/core/lombok/javac/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/javac/handlers/HandleSuperBuilder.java @@ -236,8 +236,10 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { injectFieldAndMarkGenerated(builderType, uncleanField); } - // Generate $fillValuesFrom() method in the abstract builder. - injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName, classGenericName, builderFields)); + if (toBuilder) { + // Generate $fillValuesFrom() method in the abstract builder. + injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName, classGenericName, builderFields)); + } // Generate abstract self() and build() methods in the abstract builder. injectMethod(builderType, generateAbstractSelfMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName)); -- cgit From da59d2d6375afcfcf6cb43288adba61cb99a49e8 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Tue, 11 Sep 2018 16:59:29 +0200 Subject: SuperBuilder: generate toBuilder method (ecj) --- .../eclipse/handlers/HandleSuperBuilder.java | 47 +++++++++++++++++++++- .../lombok/javac/handlers/HandleSuperBuilder.java | 1 - 2 files changed, 46 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java index 6c1b2cac..1bbc514e 100644 --- a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java @@ -104,7 +104,8 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { private static final char[] DEFAULT_PREFIX = "$default$".toCharArray(); private static final char[] SET_PREFIX = "$set".toCharArray(); private static final char[] SELF_METHOD_NAME = "self".toCharArray(); - private static final char[] TO_BUILDER_METHOD_NAME = "toBuilder".toCharArray(); + private static final String TO_BUILDER_METHOD_NAME_STRING = "toBuilder"; + private static final char[] TO_BUILDER_METHOD_NAME = TO_BUILDER_METHOD_NAME_STRING.toCharArray(); private static final char[] FILL_VALUES_METHOD_NAME = "$fillValuesFrom".toCharArray(); private static final char[] EMPTY_LIST = "emptyList".toCharArray(); @@ -345,6 +346,15 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { MethodDeclaration md = generateBuilderMethod(builderMethodName, builderClassName, builderImplClassName, tdParent, typeParams, ast); if (md != null) injectMethod(tdParent, md); } + + if (toBuilder) switch (methodExists(TO_BUILDER_METHOD_NAME_STRING, tdParent, 0)) { + case EXISTS_BY_USER: + annotationNode.addWarning("Not generating toBuilder() as it already exists."); + break; + case NOT_EXISTS: + MethodDeclaration md = generateToBuilderMethod(builderClassName, builderImplClassName, tdParent, typeParams, ast); + if (md != null) injectMethod(tdParent, md); + } } private EclipseNode generateBuilderAbstractClass(EclipseNode tdParent, String builderClass, @@ -534,6 +544,41 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { return out; } + /** + * Generates a toBuilder() method in the annotated class that looks like this: + *
+	 * public ParentBuilder<?, ?> toBuilder() {
+	 *     return new FoobarBuilderImpl().$fillValuesFrom(this);
+	 * }
+	 * 
+ */ + private MethodDeclaration generateToBuilderMethod(String builderClassName, String builderImplClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) { + int pS = source.sourceStart, pE = source.sourceEnd; + long p = (long) pS << 32 | pE; + + MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); + out.selector = TO_BUILDER_METHOD_NAME; + out.modifiers = ClassFileConstants.AccPublic; + out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + + // Add type params if there are any. + if (typeParams != null && typeParams.length > 0) out.typeParameters = copyTypeParams(typeParams, source); + + TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND) }; + out.returnType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p); + + AllocationExpression newClass = new AllocationExpression(); + newClass.type = namePlusTypeParamsToTypeReference(builderImplClassName.toCharArray(), typeParams, p); + MessageSend invokeFillMethod = new MessageSend(); + invokeFillMethod.receiver = newClass; + invokeFillMethod.selector = FILL_VALUES_METHOD_NAME; + invokeFillMethod.arguments = new Expression[] {new ThisReference(0, 0)}; + out.statements = new Statement[] {new ReturnStatement(invokeFillMethod, pS, pE)}; + + out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope); + return out; + } + /** * Generates a $fillValuesFrom() method in the abstract builder class that looks * like this: diff --git a/src/core/lombok/javac/handlers/HandleSuperBuilder.java b/src/core/lombok/javac/handlers/HandleSuperBuilder.java index c8727f93..bdcd043a 100644 --- a/src/core/lombok/javac/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/javac/handlers/HandleSuperBuilder.java @@ -523,7 +523,6 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { JCExpression newClass = maker.NewClass(null, List.nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderImplClassName), typeParams), List.nil(), null); List methodArgs = List.of(maker.Ident(type.toName("this"))); JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), methodArgs); -// JCMethodInvocation invokeFillMethod = maker.Apply(List.nil(), maker.Select(newClass, type.toName(FILL_VALUES_METHOD_NAME)), List.nil()); JCStatement statement = maker.Return(invokeFillMethod); JCBlock body = maker.Block(0, List.of(statement)); -- cgit From a2b884c71194c780d37ccbd84561abd6a0f63741 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Tue, 11 Sep 2018 20:37:16 +0200 Subject: SuperBuilder: fixed ObtainVia --- src/core/lombok/eclipse/handlers/HandleSuperBuilder.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java index 1bbc514e..bb78e82a 100644 --- a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java @@ -646,9 +646,9 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { boolean obtainIsStatic = bfd.obtainVia.isStatic(); for (int i = 0; i < tgt.length; i++) { MessageSend obtainExpr = new MessageSend(); - obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new ThisReference(0, 0); + obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new SingleNameReference(instanceVariableName.toCharArray(), 0); obtainExpr.selector = obtainName.toCharArray(); - if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new ThisReference(0, 0)}; + if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new SingleNameReference(instanceVariableName.toCharArray(), 0)}; tgt[i] = obtainExpr; } } -- cgit From f5fff49f73ceabb776f470a9ed346ace0ce12be6 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Fri, 14 Sep 2018 22:53:02 +0200 Subject: SuperBuilder toBuilder: generate static toBuilder helper method (ecj) --- .../eclipse/handlers/HandleSuperBuilder.java | 168 +++++++++++++-------- 1 file changed, 109 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java index bb78e82a..a68ede3c 100644 --- a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java @@ -107,7 +107,11 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { private static final String TO_BUILDER_METHOD_NAME_STRING = "toBuilder"; private static final char[] TO_BUILDER_METHOD_NAME = TO_BUILDER_METHOD_NAME_STRING.toCharArray(); private static final char[] FILL_VALUES_METHOD_NAME = "$fillValuesFrom".toCharArray(); + private static final char[] FILL_VALUES_STATIC_METHOD_NAME = "$fillValuesFromInstanceIntoBuilder".toCharArray(); private static final char[] EMPTY_LIST = "emptyList".toCharArray(); + private static final char[] INSTANCE_VARIABLE_NAME = "instance".toCharArray(); + private static final String BUILDER_VARIABLE_NAME_STRING = "b"; + private static final char[] BUILDER_VARIABLE_NAME = BUILDER_VARIABLE_NAME_STRING.toCharArray(); private static final AbstractMethodDeclaration[] EMPTY_METHODS = {}; @@ -294,7 +298,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { if (toBuilder) { // Generate $fillValuesFrom() method in the abstract builder. - injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClass != null, builderGenericName, classGenericName, typeParams, builderFields, ast)); + injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClass != null, builderGenericName, classGenericName, builderImplClassName, typeParams, builderFields, ast)); } // Generate abstract self() and build() methods in the abstract builder. @@ -323,8 +327,9 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { if (addCleaning) injectMethod(builderType, generateCleanMethod(builderFields, builderType, ast)); - if ((td.modifiers & ClassFileConstants.AccAbstract) != 0) { + if ((td.modifiers & ClassFileConstants.AccAbstract) != 0 && !toBuilder) { // Only non-abstract classes get the Builder implementation. + // However, if we want to generate a toBuilder, we need a helper function in the builder implementation class. return; } @@ -336,7 +341,24 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { annotationNode.addError("@SuperBuilder does not support customized builders. Use @Builder instead."); return; } - + + if (toBuilder) { + // Generate $fillValuesFromInstanceIntoBuilder() method in the builder implementation class. + injectMethod(builderImplType, generateStaticFillValuesMethod(tdParent, superclassBuilderClass != null, builderClassName, classGenericName, typeParams, builderFields, ast)); + + switch (methodExists(TO_BUILDER_METHOD_NAME_STRING, tdParent, 0)) { + case EXISTS_BY_USER: + annotationNode.addWarning("Not generating toBuilder() as it already exists."); + break; + case NOT_EXISTS: + injectMethod(tdParent, generateToBuilderMethod(builderClassName, builderImplClassName, tdParent, typeParams, ast)); + } + if ((td.modifiers & ClassFileConstants.AccAbstract) != 0) { + // The rest of the builder implementation class is not necessary for abstract classes. + return; + } + } + // Create the self() and build() methods in the BuilderImpl. injectMethod(builderImplType, generateSelfMethod(builderImplType, typeParams, p)); injectMethod(builderImplType, generateBuildMethod(tdParent, buildMethodName, returnType, ast)); @@ -346,15 +368,6 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { MethodDeclaration md = generateBuilderMethod(builderMethodName, builderClassName, builderImplClassName, tdParent, typeParams, ast); if (md != null) injectMethod(tdParent, md); } - - if (toBuilder) switch (methodExists(TO_BUILDER_METHOD_NAME_STRING, tdParent, 0)) { - case EXISTS_BY_USER: - annotationNode.addWarning("Not generating toBuilder() as it already exists."); - break; - case NOT_EXISTS: - MethodDeclaration md = generateToBuilderMethod(builderClassName, builderImplClassName, tdParent, typeParams, ast); - if (md != null) injectMethod(tdParent, md); - } } private EclipseNode generateBuilderAbstractClass(EclipseNode tdParent, String builderClass, @@ -449,7 +462,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { constructor.selector = typeDeclaration.name; if (callBuilderBasedSuperConstructor) { constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super); - constructor.constructorCall.arguments = new Expression[] {new SingleNameReference("b".toCharArray(), p)}; + constructor.constructorCall.arguments = new Expression[] {new SingleNameReference(BUILDER_VARIABLE_NAME, p)}; } else { constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); } @@ -463,7 +476,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND)}; TypeReference builderType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p); - constructor.arguments = new Argument[] {new Argument("b".toCharArray(), p, builderType, Modifier.FINAL)}; + constructor.arguments = new Argument[] {new Argument(BUILDER_VARIABLE_NAME, p, builderType, Modifier.FINAL)}; List statements = new ArrayList(); @@ -476,10 +489,10 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { Expression assignmentExpr; if (fieldNode.singularData != null && fieldNode.singularData.getSingularizer() != null) { - fieldNode.singularData.getSingularizer().appendBuildCode(fieldNode.singularData, typeNode, statements, fieldNode.name, "b"); + fieldNode.singularData.getSingularizer().appendBuildCode(fieldNode.singularData, typeNode, statements, fieldNode.name, BUILDER_VARIABLE_NAME_STRING); assignmentExpr = new SingleNameReference(fieldNode.name, p); } else { - char[][] variableInBuilder = new char[][] {"b".toCharArray(), fieldName}; + char[][] variableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldName}; long[] positions = new long[] {p, p}; assignmentExpr = new QualifiedNameReference(variableInBuilder, positions, s, e); } @@ -487,7 +500,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { // In case of @Builder.Default, set the value to the default if it was NOT set in the builder. if (fieldNode.nameOfSetFlag != null) { - char[][] setVariableInBuilder = new char[][] {"b".toCharArray(), fieldNode.nameOfSetFlag}; + char[][] setVariableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldNode.nameOfSetFlag}; long[] positions = new long[] {p, p}; QualifiedNameReference setVariableInBuilderRef = new QualifiedNameReference(setVariableInBuilder, positions, s, e); @@ -585,12 +598,12 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { *
 	 * protected B $fillValuesFrom(final C instance) {
 	 *     super.$fillValuesFrom(instance);
-	 *     this.field(instance.field);
+	 *     FoobarBuilderImpl.$fillValuesFromInstanceIntoBuilder(instance, this);
 	 *     return self();
 	 * }
 	 * 
*/ - private MethodDeclaration generateFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderGenericName, String classGenericName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { + private MethodDeclaration generateFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderGenericName, String classGenericName, String builderImplClassName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) tdParent.top().get()).compilationResult); out.selector = FILL_VALUES_METHOD_NAME; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; @@ -598,9 +611,8 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { if (inherited) out.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, tdParent.get())}; out.returnType = new SingleTypeReference(builderGenericName.toCharArray(), 0); - final String instanceVariableName = "instance"; TypeReference builderType = createTypeReferenceWithTypeParameters(classGenericName, typeParams); - out.arguments = new Argument[] {new Argument(instanceVariableName.toCharArray(), 0, builderType, Modifier.FINAL)}; + out.arguments = new Argument[] {new Argument(INSTANCE_VARIABLE_NAME, 0, builderType, Modifier.FINAL)}; List body = new ArrayList(); @@ -609,16 +621,18 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { MessageSend callToSuper = new MessageSend(); callToSuper.receiver = new SuperReference(0, 0); callToSuper.selector = FILL_VALUES_METHOD_NAME; - callToSuper.arguments = new Expression[] {new SingleNameReference(instanceVariableName.toCharArray(), 0)}; + callToSuper.arguments = new Expression[] {new SingleNameReference(INSTANCE_VARIABLE_NAME, 0)}; body.add(callToSuper); } - // Call the builder's setter methods to fill the values from the instance. - for (BuilderFieldData bfd : builderFields) { - MessageSend exec = createSetterCallWithInstanceValue(bfd, instanceVariableName, tdParent, source); - body.add(exec); - } + // Call the builder implemention's helper method that actually fills the values from the instance. + MessageSend callStaticFillValuesMethod = new MessageSend(); + callStaticFillValuesMethod.receiver = new SingleNameReference(builderImplClassName.toCharArray(), 0); + callStaticFillValuesMethod.selector = FILL_VALUES_STATIC_METHOD_NAME; + callStaticFillValuesMethod.arguments = new Expression[] {new SingleNameReference(INSTANCE_VARIABLE_NAME, 0), new ThisReference(0, 0)}; + body.add(callStaticFillValuesMethod); + // Return self(). MessageSend returnCall = new MessageSend(); returnCall.receiver = ThisReference.implicitThis(); returnCall.selector = SELF_METHOD_NAME; @@ -629,40 +643,76 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { return out; } - private MessageSend createSetterCallWithInstanceValue(BuilderFieldData bfd, final String instanceVariableName, EclipseNode type, ASTNode source) { - char[] setterName = bfd.name; - MessageSend ms = new MessageSend(); - Expression[] tgt = new Expression[bfd.singularData == null ? 1 : 2]; - - if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { - char[] fieldName = bfd.obtainVia == null ? bfd.rawName : bfd.obtainVia.field().toCharArray(); - for (int i = 0; i < tgt.length; i++) { - FieldReference fr = new FieldReference(fieldName, 0); - fr.receiver = new SingleNameReference(instanceVariableName.toCharArray(), 0); - tgt[i] = fr; - } - } else { - String obtainName = bfd.obtainVia.method(); - boolean obtainIsStatic = bfd.obtainVia.isStatic(); - for (int i = 0; i < tgt.length; i++) { - MessageSend obtainExpr = new MessageSend(); - obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new SingleNameReference(instanceVariableName.toCharArray(), 0); - obtainExpr.selector = obtainName.toCharArray(); - if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new SingleNameReference(instanceVariableName.toCharArray(), 0)}; - tgt[i] = obtainExpr; - } + /** + * Generates a $fillValuesFromInstanceIntoBuilder() method in + * the builder implementation class that copies all fields from the instance + * to the builder. It looks like this: + * + *
+	 * protected B $fillValuesFromInstanceIntoBuilder(Foobar instance, FoobarBuilder<?, ?> b) {
+	 * 	b.field(instance.field);
+	 * }
+	 * 
+ */ + private MethodDeclaration generateStaticFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderClassName, String classGenericName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { + MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) tdParent.top().get()).compilationResult); + out.selector = FILL_VALUES_STATIC_METHOD_NAME; + out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + out.modifiers = ClassFileConstants.AccPrivate | ClassFileConstants.AccStatic; + out.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); + + TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND)}; + TypeReference builderType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, 0); + Argument builderArgument = new Argument(BUILDER_VARIABLE_NAME, 0, builderType, Modifier.FINAL); + out.arguments = new Argument[] {new Argument(INSTANCE_VARIABLE_NAME, 0, new SingleTypeReference(tdParent.getName().toCharArray(), 0), Modifier.FINAL), builderArgument}; + + List body = new ArrayList(); + + // Call the builder's setter methods to fill the values from the instance. + for (BuilderFieldData bfd : builderFields) { + MessageSend exec = createSetterCallWithInstanceValue(bfd, tdParent, source); + body.add(exec); + } + + out.statements = body.isEmpty() ? null : body.toArray(new Statement[body.size()]); + + return out; + } + + private MessageSend createSetterCallWithInstanceValue(BuilderFieldData bfd, EclipseNode type, ASTNode source) { + char[] setterName = bfd.name; + MessageSend ms = new MessageSend(); + Expression[] tgt = new Expression[bfd.singularData == null ? 1 : 2]; + + if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) { + char[] fieldName = bfd.obtainVia == null ? bfd.rawName : bfd.obtainVia.field().toCharArray(); + for (int i = 0; i < tgt.length; i++) { + FieldReference fr = new FieldReference(fieldName, 0); + fr.receiver = new SingleNameReference(INSTANCE_VARIABLE_NAME, 0); + tgt[i] = fr; } - if (bfd.singularData == null) { - ms.arguments = tgt; - } else { - Expression ifNull = new EqualExpression(tgt[0], new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); - MessageSend emptyList = new MessageSend(); - emptyList.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Collections".toCharArray()); - emptyList.selector = EMPTY_LIST; - ms.arguments = new Expression[] {new ConditionalExpression(ifNull, emptyList, tgt[1])}; + } else { + String obtainName = bfd.obtainVia.method(); + boolean obtainIsStatic = bfd.obtainVia.isStatic(); + for (int i = 0; i < tgt.length; i++) { + MessageSend obtainExpr = new MessageSend(); + obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new SingleNameReference(INSTANCE_VARIABLE_NAME, 0); + obtainExpr.selector = obtainName.toCharArray(); + if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new SingleNameReference(INSTANCE_VARIABLE_NAME, 0)}; + tgt[i] = obtainExpr; } - ms.receiver = ThisReference.implicitThis(); - ms.selector = setterName; + } + if (bfd.singularData == null) { + ms.arguments = tgt; + } else { + Expression ifNull = new EqualExpression(tgt[0], new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL); + MessageSend emptyList = new MessageSend(); + emptyList.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Collections".toCharArray()); + emptyList.selector = EMPTY_LIST; + ms.arguments = new Expression[] {new ConditionalExpression(ifNull, emptyList, tgt[1])}; + } + ms.receiver = new SingleNameReference(BUILDER_VARIABLE_NAME, 0); + ms.selector = setterName; return ms; } -- cgit From 7a287670f4bb6b22db920b980ce5dde4fcef5af5 Mon Sep 17 00:00:00 2001 From: Jan Rieke Date: Sun, 16 Sep 2018 15:51:19 +0200 Subject: SuperBuilder toBuilder: generate static toBuilder helper method (javac) --- .../eclipse/handlers/HandleSuperBuilder.java | 4 +- .../lombok/javac/handlers/HandleSuperBuilder.java | 114 ++++++++++++++++----- 2 files changed, 88 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java index a68ede3c..fe53c7ed 100644 --- a/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java @@ -344,7 +344,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { if (toBuilder) { // Generate $fillValuesFromInstanceIntoBuilder() method in the builder implementation class. - injectMethod(builderImplType, generateStaticFillValuesMethod(tdParent, superclassBuilderClass != null, builderClassName, classGenericName, typeParams, builderFields, ast)); + injectMethod(builderImplType, generateStaticFillValuesMethod(tdParent, superclassBuilderClass != null, builderClassName, typeParams, builderFields, ast)); switch (methodExists(TO_BUILDER_METHOD_NAME_STRING, tdParent, 0)) { case EXISTS_BY_USER: @@ -654,7 +654,7 @@ public class HandleSuperBuilder extends EclipseAnnotationHandler { * } *
*/ - private MethodDeclaration generateStaticFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderClassName, String classGenericName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { + private MethodDeclaration generateStaticFillValuesMethod(EclipseNode tdParent, boolean inherited, String builderClassName, TypeParameter[] typeParams, java.util.List builderFields, ASTNode source) { MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) tdParent.top().get()).compilationResult); out.selector = FILL_VALUES_STATIC_METHOD_NAME; out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; diff --git a/src/core/lombok/javac/handlers/HandleSuperBuilder.java b/src/core/lombok/javac/handlers/HandleSuperBuilder.java index bdcd043a..84adc72e 100644 --- a/src/core/lombok/javac/handlers/HandleSuperBuilder.java +++ b/src/core/lombok/javac/handlers/HandleSuperBuilder.java @@ -63,6 +63,7 @@ import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; import lombok.core.handlers.HandlerUtil; +import lombok.core.handlers.HandlerUtil.FieldAccess; import lombok.core.handlers.InclusionExclusionUtils.Included; import lombok.experimental.NonFinal; import lombok.experimental.SuperBuilder; @@ -73,9 +74,9 @@ import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.HandleBuilder.BuilderFieldData; import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import lombok.javac.handlers.JavacSingularsRecipes.ExpressionMaker; -import lombok.javac.handlers.JavacSingularsRecipes.StatementMaker; import lombok.javac.handlers.JavacSingularsRecipes.JavacSingularizer; import lombok.javac.handlers.JavacSingularsRecipes.SingularData; +import lombok.javac.handlers.JavacSingularsRecipes.StatementMaker; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes. @@ -83,6 +84,9 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { private static final String SELF_METHOD = "self"; private static final String TO_BUILDER_METHOD_NAME = "toBuilder"; private static final String FILL_VALUES_METHOD_NAME = "$fillValuesFrom"; + private static final String STATIC_FILL_VALUES_METHOD_NAME = "$fillValuesFromInstanceIntoBuilder"; + private static final String INSTANCE_VARIABLE_NAME = "instance"; + private static final String BUILDER_VARIABLE_NAME = "b"; @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { @@ -238,7 +242,7 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { if (toBuilder) { // Generate $fillValuesFrom() method in the abstract builder. - injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName, classGenericName, builderFields)); + injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderGenericName, classGenericName, builderImplClassName, builderFields)); } // Generate abstract self() and build() methods in the abstract builder. @@ -267,8 +271,10 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { recursiveSetGeneratedBy(builderType.get(), ast, annotationNode.getContext()); - if ((td.mods.flags & Flags.ABSTRACT) == 0) { + boolean isAbstract = (td.mods.flags & Flags.ABSTRACT) != 0; + if (!isAbstract || toBuilder) { // Only non-abstract classes get the Builder implementation. + // However, if we want to generate a toBuilder, we need a helper function in the builder implementation class. // Create the builder implementation class. JavacNode builderImplType = findInnerClass(tdParent, builderImplClassName); @@ -278,14 +284,21 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { annotationNode.addError("@SuperBuilder does not support customized builders. Use @Builder instead."); return; } + + if (toBuilder) { + // Generate $fillValuesFromInstanceIntoBuilder() method in the builder implementation class. + injectMethod(builderImplType, generateStaticFillValuesMethod(tdParent, superclassBuilderClassExpression != null, builderClassName, classGenericName, typeParams, builderFields, ast)); + } - // Create a simple constructor for the BuilderImpl class. - JCMethodDecl cd = HandleConstructor.createConstructor(AccessLevel.PRIVATE, List.nil(), builderImplType, List.nil(), false, annotationNode); - if (cd != null) injectMethod(builderImplType, cd); - - // Create the self() and build() methods in the BuilderImpl. - injectMethod(builderImplType, generateSelfMethod(builderImplType, typeParams)); - injectMethod(builderImplType, generateBuildMethod(buildMethodName, returnType, builderImplType, thrownExceptions)); + if (!isAbstract) { + // Create a simple constructor for the BuilderImpl class. + JCMethodDecl cd = HandleConstructor.createConstructor(AccessLevel.PRIVATE, List.nil(), builderImplType, List.nil(), false, annotationNode); + if (cd != null) injectMethod(builderImplType, cd); + + // Create the self() and build() methods in the BuilderImpl. + injectMethod(builderImplType, generateSelfMethod(builderImplType, typeParams)); + injectMethod(builderImplType, generateBuildMethod(buildMethodName, returnType, builderImplType, thrownExceptions)); + } recursiveSetGeneratedBy(builderImplType.get(), ast, annotationNode.getContext()); } @@ -294,8 +307,8 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { generateBuilderBasedConstructor(tdParent, typeParams, builderFields, annotationNode, builderClassName, superclassBuilderClassExpression != null); - if ((td.mods.flags & Flags.ABSTRACT) == 0) { - // Only non-abstract classes get the Builder implementation and the builder() method. + if (!isAbstract) { + // Only non-abstract classes get the builder() method. // Add the builder() method to the annotated class. // Allow users to specify their own builder() methods, e.g., to provide default values. @@ -419,7 +432,7 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { ListBuffer statements = new ListBuffer(); - Name builderVariableName = typeNode.toName("b"); + Name builderVariableName = typeNode.toName(BUILDER_VARIABLE_NAME); for (BuilderFieldData bfd : builderFields) { JCExpression rhs; if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) { @@ -546,12 +559,12 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { *
 	 * protected B $fillValuesFrom(final C instance) {
 	 *     super.$fillValuesFrom(instance);
-	 *     this.field(instance.field);
+	 *     FoobarBuilderImpl.$fillValuesFromInstanceIntoBuilder(instance, this);
 	 *     return self();
 	 * }
 	 * 
*/ - private JCMethodDecl generateFillValuesMethod(JavacNode type, boolean inherited, String builderGenericName, String classGenericName, java.util.List builderFields) { + private JCMethodDecl generateFillValuesMethod(JavacNode type, boolean inherited, String builderGenericName, String classGenericName, String builderImplClassName, java.util.List builderFields) { JavacTreeMaker maker = type.getTreeMaker(); List annotations = List.nil(); if (inherited) { @@ -562,9 +575,8 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { Name name = type.toName(FILL_VALUES_METHOD_NAME); JCExpression returnType = maker.Ident(type.toName(builderGenericName)); - final String instanceVariableName = "instance"; JCExpression classGenericNameExpr = maker.Ident(type.toName(classGenericName)); - JCVariableDecl param = maker.VarDef(maker.Modifiers(Flags.LocalVarFlags), type.toName(instanceVariableName), classGenericNameExpr, null); + JCVariableDecl param = maker.VarDef(maker.Modifiers(Flags.LocalVarFlags), type.toName(INSTANCE_VARIABLE_NAME), classGenericNameExpr, null); ListBuffer body = new ListBuffer(); @@ -572,15 +584,15 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { // Call super. JCMethodInvocation callToSuper = maker.Apply(List.nil(), maker.Select(maker.Ident(type.toName("super")), name), - List.of(maker.Ident(type.toName(instanceVariableName)))); + List.of(maker.Ident(type.toName(INSTANCE_VARIABLE_NAME)))); body.append(maker.Exec(callToSuper)); } - // Call the builder's setter methods to fill the values from the instance. - for (BuilderFieldData bfd : builderFields) { - JCExpressionStatement exec = createSetterCallWithInstanceValue(bfd, instanceVariableName, type, maker); - body.append(exec); - } + // Call the builder implemention's helper method that actually fills the values from the instance. + JCMethodInvocation callStaticFillValuesMethod = maker.Apply(List.nil(), + maker.Select(maker.Ident(type.toName(builderImplClassName)), type.toName(STATIC_FILL_VALUES_METHOD_NAME)), + List.of(maker.Ident(type.toName(INSTANCE_VARIABLE_NAME)), maker.Ident(type.toName("this")))); + body.append(maker.Exec(callStaticFillValuesMethod)); JCReturn returnStatement = maker.Return(maker.Apply(List.nil(), maker.Ident(type.toName(SELF_METHOD)), List.nil())); body.append(returnStatement); @@ -589,21 +601,67 @@ public class HandleSuperBuilder extends JavacAnnotationHandler { retu