Skip to content

Commit

Permalink
[fixes #1324] toBuilder with @Singular marked collections that are nu…
Browse files Browse the repository at this point in the history
…ll no longer throws NPE.
  • Loading branch information
rzwitserloot committed Oct 15, 2018
1 parent 06455de commit 94eadb5
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 148 deletions.
1 change: 1 addition & 0 deletions doc/changelog.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Lombok Changelog
* PLATFORM: Support for Eclipse Photon. [Issue #1831](https://github.com/rzwitserloot/lombok/issues/1831)
* FEATURE: The `@FieldNameConstants` feature has been completely redesigned. [Issue #1774](https://github.com/rzwitserloot/lombok/issues/1774) [FieldNameConstants documentation](https://projectlombok.org/features/experimental/FieldNameConstants)
* FEATURE: Lombok's `@NonNull` annotation can now be used on types (annotation on types has been introduced in JDK 8). `@Builder`'s `@Singular` annotation now properly deals with annotations on the generics type on the collection: `@Singular List<@NonNull String> names;` now does the right thing.
* FEATURE: You can now mix `@SuperBuilder` and `toBuilder`, and `toBuilder` no longer throws `NullPointerException` if an `@Singular`-marked collection field is `null`. [Issue #1324](https://github.com/rzwitserloot/lombok/issues/1324)
* BREAKING CHANGE: Lombok will now always copy specific annotations around (from field to getter, from field to builder 'setter', etcetera): A specific curated list of known annotations where that is the right thing to do (generally, `@NonNull` style annotations from various libraries), as well as any annotations you explicitly list in the `lombok.copyableAnnotations` config key in your `lombok.config` file. Also, lombok is more consistent about copying these annotations. (Previous behaviour: Lombok used to copy any annotation whose simple name was `NonNull`, `Nullable`, or `CheckForNull`). [Issue #1570](https://github.com/rzwitserloot/lombok/issues/1570) and [Issue #1634](https://github.com/rzwitserloot/lombok/issues/1634)
* BUGFIX: When using lombok to compile modularized (`module-info.java`-style) code, if the module name has dots in it, it wouldn't work. [Issue #1808](https://github.com/rzwitserloot/lombok/issues/1808)
* BUGFIX: Errors about lombok not reading a module providing `org.mapstruct.ap.spi` when trying to use lombok in jigsaw-mode on JDK 11. [Issue #1806](https://github.com/rzwitserloot/lombok/issues/1806)
Expand Down
44 changes: 28 additions & 16 deletions src/core/lombok/eclipse/handlers/HandleBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import static lombok.core.handlers.HandlerUtil.*;
import static lombok.eclipse.handlers.EclipseHandlerUtil.*;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand All @@ -46,6 +47,7 @@
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.IfStatement;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
Expand Down Expand Up @@ -502,15 +504,12 @@ private static final char[] prefixWith(char[] prefix, char[] name) {
}
}

private static final char[] EMPTY_LIST = "emptyList".toCharArray();
private static final char[] BUILDER_TEMP_VAR = {'b', 'u', 'i', 'l', 'd', 'e', 'r'};
private MethodDeclaration generateToBuilderMethod(String methodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, List<BuilderFieldData> builderFields, boolean fluent, ASTNode source) {
// return new ThingieBuilder<A, B>().setA(this.a).setB(this.b);

int pS = source.sourceStart, pE = source.sourceEnd;
long p = (long) pS << 32 | pE;

MethodDeclaration out = new MethodDeclaration(
((CompilationUnitDeclaration) type.top().get()).compilationResult);
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.selector = methodName.toCharArray();
out.modifiers = ClassFileConstants.AccPublic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
Expand All @@ -519,6 +518,7 @@ private MethodDeclaration generateToBuilderMethod(String methodName, String buil
invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);

Expression receiver = invoke;
List<Statement> statements = null;
for (BuilderFieldData bfd : builderFields) {
char[] setterName = fluent ? bfd.name : HandlerUtil.buildAccessorName("set", new String(bfd.name)).toCharArray();
MessageSend ms = new MessageSend();
Expand All @@ -542,22 +542,34 @@ private MethodDeclaration generateToBuilderMethod(String methodName, String buil
tgt[i] = obtainExpr;
}
}

ms.selector = setterName;
if (bfd.singularData == null) {
ms.arguments = tgt;
ms.receiver = receiver;
receiver = ms;
} 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;
emptyList.typeArguments = copyTypes(bfd.singularData.getTypeArgs().toArray(new TypeReference[0]));
ms.arguments = new Expression[] {new ConditionalExpression(ifNull, emptyList, tgt[1])};
ms.arguments = new Expression[] {tgt[1]};
ms.receiver = new SingleNameReference(BUILDER_TEMP_VAR, p);
EqualExpression isNotNull = new EqualExpression(tgt[0], new NullLiteral(pS, pE), OperatorIds.NOT_EQUAL);
if (statements == null) statements = new ArrayList<Statement>();
statements.add(new IfStatement(isNotNull, ms, pS, pE));
}
ms.receiver = receiver;
ms.selector = setterName;
receiver = ms;
}

out.statements = new Statement[] {new ReturnStatement(receiver, pS, pE)};
if (statements != null) {
out.statements = new Statement[statements.size() + 2];
for (int i = 0; i < statements.size(); i++) out.statements[i + 1] = statements.get(i);
LocalDeclaration b = new LocalDeclaration(BUILDER_TEMP_VAR, pS, pE);
out.statements[0] = b;
b.modifiers |= Modifier.FINAL;
b.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
b.type.sourceStart = pS; b.type.sourceEnd = pE;
b.initialization = receiver;
out.statements[out.statements.length - 1] = new ReturnStatement(new SingleNameReference(BUILDER_TEMP_VAR, p), pS, pE);
} else {
out.statements = new Statement[] {new ReturnStatement(receiver, pS, pE)};
}

out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
return out;
Expand Down Expand Up @@ -617,7 +629,7 @@ public MethodDeclaration generateBuildMethod(EclipseNode tdParent, boolean isSta
inv.typeArguments = typeParameterNames(((TypeDeclaration) type.get()).typeParameters);

args.add(new ConditionalExpression(
new SingleNameReference(bfd.nameOfSetFlag, 0L),
new SingleNameReference(bfd.nameOfSetFlag, 0L),
new SingleNameReference(bfd.name, 0L),
inv));
} else {
Expand Down
23 changes: 14 additions & 9 deletions src/core/lombok/javac/handlers/HandleBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ private static void unpack(StringBuilder sb, JCExpression expr) {
sb.append("__ERR__");
}

private static final String BUILDER_TEMP_VAR = "builder";
private JCMethodDecl generateToBuilderMethod(String toBuilderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams, java.util.List<BuilderFieldData> builderFields, boolean fluent, JCAnnotation ast) {
// return new ThingieBuilder<A, B>().setA(this.a).setB(this.b);
JavacTreeMaker maker = type.getTreeMaker();
Expand All @@ -495,6 +496,7 @@ private JCMethodDecl generateToBuilderMethod(String toBuilderMethodName, String

JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
JCExpression invoke = call;
ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
for (BuilderFieldData bfd : builderFields) {
Name setterName = fluent ? bfd.name : type.toName(HandlerUtil.buildAccessorName("set", bfd.name.toString()));
JCExpression[] tgt = new JCExpression[bfd.singularData == null ? 1 : 2];
Expand All @@ -519,18 +521,21 @@ private JCMethodDecl generateToBuilderMethod(String toBuilderMethodName, String
JCExpression arg;
if (bfd.singularData == null) {
arg = tgt[0];
invoke = maker.Apply(List.<JCExpression>nil(), maker.Select(invoke, setterName), List.of(arg));
} else {
JCExpression eqNull = maker.Binary(CTC_EQUAL, tgt[0], maker.Literal(CTC_BOT, null));
List<JCExpression> tas = cloneTypes(maker, bfd.singularData.getTypeArgs(), ast, type.getContext());
JCExpression emptyList = maker.Apply(tas, chainDots(type, "java", "util", "Collections", "emptyList"), List.<JCExpression>nil());
arg = maker.Conditional(eqNull, emptyList, tgt[1]);
JCExpression isNotNull = maker.Binary(CTC_NOT_EQUAL, tgt[0], maker.Literal(CTC_BOT, null));
JCExpression invokeBuilder = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(type.toName(BUILDER_TEMP_VAR)), setterName), List.<JCExpression>of(tgt[1]));
statements.append(maker.If(isNotNull, maker.Exec(invokeBuilder), null));
}

invoke = maker.Apply(List.<JCExpression>nil(), maker.Select(invoke, setterName), List.of(arg));
}
JCStatement statement = maker.Return(invoke);

JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
if (!statements.isEmpty()) {
JCExpression tempVarType = namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams);
statements.prepend(maker.VarDef(maker.Modifiers(Flags.FINAL), type.toName(BUILDER_TEMP_VAR), tempVarType, invoke));
statements.append(maker.Return(maker.Ident(type.toName(BUILDER_TEMP_VAR))));
} else {
statements.append(maker.Return(invoke));
}
JCBlock body = maker.Block(0, statements.toList());
return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(toBuilderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ public static BuilderSingularToBuilderWithNullBuilder builder() {
}
@java.lang.SuppressWarnings("all")
public BuilderSingularToBuilderWithNullBuilder toBuilder() {
return new BuilderSingularToBuilderWithNullBuilder().elems(this.elems == null ? java.util.Collections.<String>emptyList() : this.elems);
final BuilderSingularToBuilderWithNullBuilder builder = new BuilderSingularToBuilderWithNullBuilder();
if (this.elems != null) builder.elems(this.elems);
return builder;
}
}
77 changes: 19 additions & 58 deletions test/transform/resource/after-delombok/BuilderWithToBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,27 @@ public static <T> BuilderWithToBuilderBuilder<T> builder() {
}
@java.lang.SuppressWarnings("all")
public BuilderWithToBuilderBuilder<T> toBuilder() {
return new BuilderWithToBuilderBuilder<T>().one(this.mOne).two(this.mTwo).foo(BuilderWithToBuilder.rrr(this)).bars(this.bars == null ? java.util.Collections.<T>emptyList() : this.bars);
final BuilderWithToBuilderBuilder<T> builder = new BuilderWithToBuilderBuilder<T>().one(this.mOne).two(this.mTwo).foo(BuilderWithToBuilder.rrr(this));
if (this.bars != null) builder.bars(this.bars);
return builder;
}
}
class ConstructorWithToBuilder<T> {
private String mOne;
private String mTwo;
private T foo;
@lombok.Singular
private List<T> bars;
public ConstructorWithToBuilder(String mOne, T bar) {
private com.google.common.collect.ImmutableList<T> bars;
public ConstructorWithToBuilder(String mOne, T baz, com.google.common.collect.ImmutableList<T> bars) {
}
@java.lang.SuppressWarnings("all")
public static class ConstructorWithToBuilderBuilder<T> {
@java.lang.SuppressWarnings("all")
private String mOne;
@java.lang.SuppressWarnings("all")
private T bar;
private T baz;
@java.lang.SuppressWarnings("all")
private com.google.common.collect.ImmutableList<T> bars;
@java.lang.SuppressWarnings("all")
ConstructorWithToBuilderBuilder() {
}
Expand All @@ -112,18 +116,23 @@ public ConstructorWithToBuilderBuilder<T> mOne(final String mOne) {
return this;
}
@java.lang.SuppressWarnings("all")
public ConstructorWithToBuilderBuilder<T> bar(final T bar) {
this.bar = bar;
public ConstructorWithToBuilderBuilder<T> baz(final T baz) {
this.baz = baz;
return this;
}
@java.lang.SuppressWarnings("all")
public ConstructorWithToBuilderBuilder<T> bars(final com.google.common.collect.ImmutableList<T> bars) {
this.bars = bars;
return this;
}
@java.lang.SuppressWarnings("all")
public ConstructorWithToBuilder<T> build() {
return new ConstructorWithToBuilder<T>(mOne, bar);
return new ConstructorWithToBuilder<T>(mOne, baz, bars);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public java.lang.String toString() {
return "ConstructorWithToBuilder.ConstructorWithToBuilderBuilder(mOne=" + this.mOne + ", bar=" + this.bar + ")";
return "ConstructorWithToBuilder.ConstructorWithToBuilderBuilder(mOne=" + this.mOne + ", baz=" + this.baz + ", bars=" + this.bars + ")";
}
}
@java.lang.SuppressWarnings("all")
Expand All @@ -132,54 +141,6 @@ public static <T> ConstructorWithToBuilderBuilder<T> builder() {
}
@java.lang.SuppressWarnings("all")
public ConstructorWithToBuilderBuilder<T> toBuilder() {
return new ConstructorWithToBuilderBuilder<T>().mOne(this.mOne).bar(this.foo);
return new ConstructorWithToBuilderBuilder<T>().mOne(this.mOne).baz(this.foo).bars(this.bars);
}
}
class StaticWithToBuilder<T, K> {
private String mOne;
private String mTwo;
private T foo;
private K bar;
@lombok.Singular
private List<T> bars;
public static <Z> StaticWithToBuilder<Z, String> test(String mOne, Z bar) {
return new StaticWithToBuilder<Z, String>();
}
@java.lang.SuppressWarnings("all")
public static class StaticWithToBuilderBuilder<Z> {
@java.lang.SuppressWarnings("all")
private String mOne;
@java.lang.SuppressWarnings("all")
private Z bar;
@java.lang.SuppressWarnings("all")
StaticWithToBuilderBuilder() {
}
@java.lang.SuppressWarnings("all")
public StaticWithToBuilderBuilder<Z> mOne(final String mOne) {
this.mOne = mOne;
return this;
}
@java.lang.SuppressWarnings("all")
public StaticWithToBuilderBuilder<Z> bar(final Z bar) {
this.bar = bar;
return this;
}
@java.lang.SuppressWarnings("all")
public StaticWithToBuilder<Z, String> build() {
return StaticWithToBuilder.<Z>test(mOne, bar);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public java.lang.String toString() {
return "StaticWithToBuilder.StaticWithToBuilderBuilder(mOne=" + this.mOne + ", bar=" + this.bar + ")";
}
}
@java.lang.SuppressWarnings("all")
public static <Z> StaticWithToBuilderBuilder<Z> builder() {
return new StaticWithToBuilderBuilder<Z>();
}
@java.lang.SuppressWarnings("all")
public StaticWithToBuilderBuilder<T> toBuilder() {
return new StaticWithToBuilderBuilder<T>().mOne(this.mOne).bar(this.foo);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ public static void test() {
return new BuilderSingularToBuilderWithNullBuilder();
}
public @java.lang.SuppressWarnings("all") BuilderSingularToBuilderWithNullBuilder toBuilder() {
return new BuilderSingularToBuilderWithNullBuilder().elems(((this.elems == null) ? java.util.Collections.<String>emptyList() : this.elems));
final BuilderSingularToBuilderWithNullBuilder builder = new BuilderSingularToBuilderWithNullBuilder();
if ((this.elems != null))
builder.elems(this.elems);
return builder;
}
}
}
Loading

0 comments on commit 94eadb5

Please sign in to comment.