diff options
author | Reinier Zwitserloot <reinier@zwitserloot.com> | 2018-07-03 04:17:47 +0200 |
---|---|---|
committer | Reinier Zwitserloot <reinier@zwitserloot.com> | 2018-07-03 05:42:34 +0200 |
commit | 3987f54b8321ae666cb1c774aef5986df05bf4ad (patch) | |
tree | da0c53aa062e8e0168d22564995ba6de61577ceb /src/core/lombok | |
parent | 577ce94facde1092ab2eec9de12270183e8048bc (diff) | |
download | lombok-3987f54b8321ae666cb1c774aef5986df05bf4ad.tar.gz lombok-3987f54b8321ae666cb1c774aef5986df05bf4ad.tar.bz2 lombok-3987f54b8321ae666cb1c774aef5986df05bf4ad.zip |
[issue #1347] When lombok generates constructors, it should call the `@Builder.Default` static method instead of initializing to null/0/false. This does that, for javac.
Diffstat (limited to 'src/core/lombok')
6 files changed, 199 insertions, 41 deletions
diff --git a/src/core/lombok/core/AlreadyHandledAnnotations.java b/src/core/lombok/core/AlreadyHandledAnnotations.java new file mode 100644 index 00000000..4cf13888 --- /dev/null +++ b/src/core/lombok/core/AlreadyHandledAnnotations.java @@ -0,0 +1,33 @@ +/* + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */package lombok.core; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Used to indicate a handler is to be invoked for its marked annotation even if that annotation is already handled. Useful for cleanup handlers + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface AlreadyHandledAnnotations {} diff --git a/src/core/lombok/javac/HandlerLibrary.java b/src/core/lombok/javac/HandlerLibrary.java index 3c61696b..9e7b8fe5 100644 --- a/src/core/lombok/javac/HandlerLibrary.java +++ b/src/core/lombok/javac/HandlerLibrary.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2014 The Project Lombok Authors. + * Copyright (C) 2009-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 @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; @@ -36,6 +37,7 @@ import java.util.TreeSet; import javax.annotation.processing.Messager; import javax.tools.Diagnostic; +import lombok.core.AlreadyHandledAnnotations; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; import lombok.core.HandlerPriority; import lombok.core.SpiLoadUtil; @@ -57,7 +59,7 @@ import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; */ public class HandlerLibrary { private final TypeLibrary typeLibrary = new TypeLibrary(); - private final Map<String, AnnotationHandlerContainer<?>> annotationHandlers = new HashMap<String, AnnotationHandlerContainer<?>>(); + private final Map<String, List<AnnotationHandlerContainer<?>>> annotationHandlers = new HashMap<String, List<AnnotationHandlerContainer<?>>>(); private final Collection<VisitorContainer> visitorHandlers = new ArrayList<VisitorContainer>(); private final Messager messager; @@ -78,7 +80,7 @@ public class HandlerLibrary { VisitorContainer(JavacASTVisitor visitor) { this.visitor = visitor; HandlerPriority hp = visitor.getClass().getAnnotation(HandlerPriority.class); - this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); + this.priority = hp == null ? 0L : (((long) hp.value()) << 32) + hp.subValue(); this.resolutionResetNeeded = visitor.getClass().isAnnotationPresent(ResolutionResetNeeded.class); } @@ -96,6 +98,7 @@ public class HandlerLibrary { private final Class<T> annotationClass; private final long priority; private final boolean resolutionResetNeeded; + private final boolean evenIfAlreadyHandled; AnnotationHandlerContainer(JavacAnnotationHandler<T> handler, Class<T> annotationClass) { this.handler = handler; @@ -103,6 +106,7 @@ public class HandlerLibrary { HandlerPriority hp = handler.getClass().getAnnotation(HandlerPriority.class); this.priority = hp == null ? 0L : (((long)hp.value()) << 32) + hp.subValue(); this.resolutionResetNeeded = handler.getClass().isAnnotationPresent(ResolutionResetNeeded.class); + this.evenIfAlreadyHandled = handler.getClass().isAnnotationPresent(AlreadyHandledAnnotations.class); } public void handle(final JavacNode node) { @@ -116,6 +120,10 @@ public class HandlerLibrary { public boolean isResolutionResetNeeded() { return resolutionResetNeeded; } + + public boolean isEvenIfAlreadyHandled() { + return evenIfAlreadyHandled; + } } private SortedSet<Long> priorities; @@ -132,9 +140,11 @@ public class HandlerLibrary { private void calculatePriorities() { SortedSet<Long> set = new TreeSet<Long>(); SortedSet<Long> resetNeeded = new TreeSet<Long>(); - for (AnnotationHandlerContainer<?> container : annotationHandlers.values()) { - set.add(container.getPriority()); - if (container.isResolutionResetNeeded()) resetNeeded.add(container.getPriority()); + for (List<AnnotationHandlerContainer<?>> containers : annotationHandlers.values()) { + for (AnnotationHandlerContainer<?> container : containers) { + set.add(container.getPriority()); + if (container.isResolutionResetNeeded()) resetNeeded.add(container.getPriority()); + } } for (VisitorContainer container : visitorHandlers) { set.add(container.getPriority()); @@ -173,9 +183,9 @@ public class HandlerLibrary { Class<? extends Annotation> annotationClass = handler.getAnnotationHandledByThisHandler(); AnnotationHandlerContainer<?> container = new AnnotationHandlerContainer(handler, annotationClass); String annotationClassName = container.annotationClass.getName().replace("$", "."); - if (lib.annotationHandlers.put(annotationClassName, container) != null) { - lib.javacWarning("Duplicate handlers for annotation type: " + annotationClassName); - } + List<AnnotationHandlerContainer<?>> list = lib.annotationHandlers.get(annotationClassName); + if (list == null) lib.annotationHandlers.put(annotationClassName, list = new ArrayList<AnnotationHandlerContainer<?>>(1)); + list.add(container); lib.typeLibrary.addType(container.annotationClass.getName()); } } @@ -236,19 +246,25 @@ public class HandlerLibrary { String rawType = annotation.annotationType.toString(); String fqn = resolver.typeRefToFullyQualifiedName(node, typeLibrary, rawType); if (fqn == null) return; - AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); - if (container == null) return; + List<AnnotationHandlerContainer<?>> containers = annotationHandlers.get(fqn); + if (containers == null) return; - try { - if (container.getPriority() == priority) { - if (checkAndSetHandled(annotation)) container.handle(node); + for (AnnotationHandlerContainer<?> container : containers) { + try { + if (container.getPriority() == priority) { + if (checkAndSetHandled(annotation)) { + container.handle(node); + } else { + if (container.isEvenIfAlreadyHandled()) container.handle(node); + } + } + } catch (AnnotationValueDecodeFail fail) { + fail.owner.setError(fail.getMessage(), fail.idx); + } catch (Throwable t) { + String sourceName = "(unknown).java"; + if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); + javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); } - } catch (AnnotationValueDecodeFail fail) { - fail.owner.setError(fail.getMessage(), fail.idx); - } catch (Throwable t) { - String sourceName = "(unknown).java"; - if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); - javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); } } diff --git a/src/core/lombok/javac/handlers/HandleBuilder.java b/src/core/lombok/javac/handlers/HandleBuilder.java index d56d6ac2..fa887974 100644 --- a/src/core/lombok/javac/handlers/HandleBuilder.java +++ b/src/core/lombok/javac/handlers/HandleBuilder.java @@ -144,7 +144,7 @@ public class HandleBuilder extends JavacAnnotationHandler<Builder> { boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation("lombok.experimental.Value", parent)); for (JavacNode fieldNode : HandleConstructor.findAllFields(tdParent, true)) { JCVariableDecl fd = (JCVariableDecl) fieldNode.get(); - JavacNode isDefault = findAnnotation(Builder.Default.class, fieldNode, true); + JavacNode isDefault = findAnnotation(Builder.Default.class, fieldNode, false); boolean isFinal = (fd.mods.flags & Flags.FINAL) != 0 || (valuePresent && !hasAnnotation(NonFinal.class, fieldNode)); BuilderFieldData bfd = new BuilderFieldData(); bfd.rawName = fd.name; diff --git a/src/core/lombok/javac/handlers/HandleBuilderDefault.java b/src/core/lombok/javac/handlers/HandleBuilderDefault.java index af45a620..df5eebc9 100644 --- a/src/core/lombok/javac/handlers/HandleBuilderDefault.java +++ b/src/core/lombok/javac/handlers/HandleBuilderDefault.java @@ -26,6 +26,8 @@ import static lombok.javac.handlers.JavacHandlerUtil.*; import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.JCTree.JCIdent; import lombok.Builder; import lombok.core.AST.Kind; @@ -47,5 +49,14 @@ public class HandleBuilderDefault extends JavacAnnotationHandler<Builder.Default annotationNode.addWarning("@Builder.Default requires @Builder or @SuperBuilder on the class for it to mean anything."); deleteAnnotationIfNeccessary(annotationNode, Builder.Default.class); } + + /** HandleBuilder is going to wipe out the import, at which point '@Builder.Default' is no longer clear. */ + if (ast.annotationType instanceof JCFieldAccess) { + JCFieldAccess jfa = (JCFieldAccess) ast.annotationType; + if (jfa.selected instanceof JCIdent && ((JCIdent) jfa.selected).name.contentEquals("Builder") && jfa.name.contentEquals("Default")) { + JCFieldAccess newJfaSel = annotationNode.getTreeMaker().Select(annotationNode.getTreeMaker().Ident(annotationNode.toName("lombok")), ((JCIdent) jfa.selected).name); + jfa.selected = newJfaSel; + } + } } } diff --git a/src/core/lombok/javac/handlers/HandleBuilderDefaultRemove.java b/src/core/lombok/javac/handlers/HandleBuilderDefaultRemove.java new file mode 100644 index 00000000..fc0738c3 --- /dev/null +++ b/src/core/lombok/javac/handlers/HandleBuilderDefaultRemove.java @@ -0,0 +1,45 @@ +/* + * 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 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.javac.handlers; + +import static lombok.javac.handlers.JavacHandlerUtil.*; + +import org.mangosdk.spi.ProviderFor; + +import com.sun.tools.javac.tree.JCTree.JCAnnotation; + +import lombok.Builder; +import lombok.Builder.Default; +import lombok.core.AlreadyHandledAnnotations; +import lombok.core.AnnotationValues; +import lombok.core.HandlerPriority; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; + +@ProviderFor(JavacAnnotationHandler.class) +@HandlerPriority(65536) +@AlreadyHandledAnnotations +public class HandleBuilderDefaultRemove extends JavacAnnotationHandler<Builder.Default> { + @Override public void handle(AnnotationValues<Default> annotation, JCAnnotation ast, JavacNode annotationNode) { + deleteAnnotationIfNeccessary(annotationNode, Builder.Default.class); + } +} diff --git a/src/core/lombok/javac/handlers/HandleConstructor.java b/src/core/lombok/javac/handlers/HandleConstructor.java index 32eb43b2..76caaffe 100644 --- a/src/core/lombok/javac/handlers/HandleConstructor.java +++ b/src/core/lombok/javac/handlers/HandleConstructor.java @@ -80,8 +80,7 @@ public class HandleConstructor { if (level == AccessLevel.NONE) return; String staticName = ann.staticName(); boolean force = ann.force(); - List<JavacNode> fields = force ? findFinalFields(typeNode) : List.<JavacNode>nil(); - handleConstructor.generateConstructor(typeNode, level, onConstructor, fields, force, staticName, SkipIfConstructorExists.NO, annotationNode); + handleConstructor.generateConstructor(typeNode, level, onConstructor, List.<JavacNode>nil(), force, staticName, SkipIfConstructorExists.NO, annotationNode); } } @@ -201,9 +200,8 @@ public class HandleConstructor { Boolean v = typeNode.getAst().readConfiguration(ConfigurationKeys.NO_ARGS_CONSTRUCTOR_EXTRA_PRIVATE); if (v == null || !v) return; - - List<JavacNode> fields = findFinalFields(typeNode); - generate(typeNode, AccessLevel.PRIVATE, List.<JCAnnotation>nil(), fields, true, null, SkipIfConstructorExists.NO, source, true); + + generate(typeNode, AccessLevel.PRIVATE, List.<JCAnnotation>nil(), List.<JavacNode>nil(), true, null, SkipIfConstructorExists.NO, source, true); } public void generateRequiredArgsConstructor(JavacNode typeNode, AccessLevel level, String staticName, SkipIfConstructorExists skipIfConstructorExists, JavacNode source) { @@ -304,7 +302,7 @@ public class HandleConstructor { mods.annotations = mods.annotations.append(annotation); } - @SuppressWarnings("deprecation") public static JCMethodDecl createConstructor(AccessLevel level, List<JCAnnotation> onConstructor, JavacNode typeNode, List<JavacNode> fields, boolean allToDefault, JavacNode source) { + @SuppressWarnings("deprecation") public static JCMethodDecl createConstructor(AccessLevel level, List<JCAnnotation> onConstructor, JavacNode typeNode, List<JavacNode> fieldsToParam, boolean forceDefaults, JavacNode source) { JavacTreeMaker maker = typeNode.getTreeMaker(); boolean isEnum = (((JCClassDecl) typeNode.get()).mods.flags & Flags.ENUM) != 0; @@ -312,7 +310,10 @@ public class HandleConstructor { boolean addConstructorProperties; - if (fields.isEmpty()) { + List<JavacNode> fieldsToDefault = fieldsNeedingBuilderDefaults(typeNode, fieldsToParam); + List<JavacNode> fieldsToExplicit = forceDefaults ? fieldsNeedingExplicitDefaults(typeNode, fieldsToParam) : List.<JavacNode>nil(); + + if (fieldsToParam.isEmpty()) { addConstructorProperties = false; } else { Boolean v = typeNode.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_ADD_CONSTRUCTOR_PROPERTIES); @@ -324,29 +325,45 @@ public class HandleConstructor { ListBuffer<JCStatement> assigns = new ListBuffer<JCStatement>(); ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>(); - for (JavacNode fieldNode : fields) { + for (JavacNode fieldNode : fieldsToParam) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); Name fieldName = removePrefixFromField(fieldNode); Name rawName = field.name; List<JCAnnotation> nonNulls = findAnnotations(fieldNode, NON_NULL_PATTERN); - if (!allToDefault) { - 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, field.vartype, null); - params.append(param); - if (!nonNulls.isEmpty()) { - JCStatement nullCheck = generateNullCheck(maker, fieldNode, param, source); - if (nullCheck != null) nullChecks.append(nullCheck); - } + 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, field.vartype, null); + params.append(param); + if (!nonNulls.isEmpty()) { + JCStatement nullCheck = generateNullCheck(maker, fieldNode, param, source); + if (nullCheck != null) nullChecks.append(nullCheck); } JCFieldAccess thisX = maker.Select(maker.Ident(fieldNode.toName("this")), rawName); - JCExpression assign = maker.Assign(thisX, allToDefault ? getDefaultExpr(maker, field.vartype) : maker.Ident(fieldName)); + JCExpression assign = maker.Assign(thisX, maker.Ident(fieldName)); + assigns.append(maker.Exec(assign)); + } + + for (JavacNode fieldNode : fieldsToExplicit) { + JCVariableDecl field = (JCVariableDecl) fieldNode.get(); + Name rawName = field.name; + JCFieldAccess thisX = maker.Select(maker.Ident(fieldNode.toName("this")), rawName); + JCExpression assign = maker.Assign(thisX, getDefaultExpr(maker, field.vartype)); + assigns.append(maker.Exec(assign)); + } + + for (JavacNode fieldNode : fieldsToDefault) { + JCVariableDecl field = (JCVariableDecl) fieldNode.get(); + Name rawName = field.name; + Name fieldName = removePrefixFromField(fieldNode); + Name nameOfDefaultProvider = typeNode.toName("$default$" + fieldName); + JCFieldAccess thisX = maker.Select(maker.Ident(fieldNode.toName("this")), rawName); + JCExpression assign = maker.Assign(thisX, maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(((JCClassDecl) typeNode.get()).name), nameOfDefaultProvider), List.<JCExpression>nil())); assigns.append(maker.Exec(assign)); } JCModifiers mods = maker.Modifiers(toJavacModifier(level), List.<JCAnnotation>nil()); - if (!allToDefault && addConstructorProperties && !isLocalType(typeNode) && LombokOptionsFactory.getDelombokOptions(typeNode.getContext()).getFormatPreferences().generateConstructorProperties()) { - addConstructorProperties(mods, typeNode, fields); + if (addConstructorProperties && !isLocalType(typeNode) && LombokOptionsFactory.getDelombokOptions(typeNode.getContext()).getFormatPreferences().generateConstructorProperties()) { + addConstructorProperties(mods, typeNode, fieldsToParam); } if (onConstructor != null) mods.annotations = mods.annotations.appendList(copyAnnotations(onConstructor)); @@ -355,6 +372,42 @@ public class HandleConstructor { maker.Block(0L, nullChecks.appendList(assigns).toList()), null), source.get(), typeNode.getContext()); } + /** + * For each field which is not final and has no initializer that gets 'removed' by {@code @Builder.Default} there is no need to + * write an explicit 'this.x = foo' in the constructor, so strip them away here. + */ + private static List<JavacNode> fieldsNeedingBuilderDefaults(JavacNode typeNode, List<JavacNode> fieldsToParam) { + ListBuffer<JavacNode> out = new ListBuffer<JavacNode>(); + top: + for (JavacNode node : typeNode.down()) { + if (node.getKind() != Kind.FIELD) continue top; + JCVariableDecl varDecl = (JCVariableDecl) node.get(); + if ((varDecl.mods.flags & Flags.STATIC) != 0) continue top; + for (JavacNode ftp : fieldsToParam) if (node == ftp) continue top; + if (JavacHandlerUtil.hasAnnotation(Builder.Default.class, node)) out.append(node); + } + return out.toList(); + } + + /** + * Return each field which is final and has no initializer, and which is not already a parameter. + */ + private static List<JavacNode> fieldsNeedingExplicitDefaults(JavacNode typeNode, List<JavacNode> fieldsToParam) { + ListBuffer<JavacNode> out = new ListBuffer<JavacNode>(); + top: + for (JavacNode node : typeNode.down()) { + if (node.getKind() != Kind.FIELD) continue top; + JCVariableDecl varDecl = (JCVariableDecl) node.get(); + if (varDecl.init != null) continue top; + if ((varDecl.mods.flags & Flags.FINAL) == 0) continue top; + if ((varDecl.mods.flags & Flags.STATIC) != 0) continue top; + for (JavacNode ftp : fieldsToParam) if (node == ftp) continue top; + if (JavacHandlerUtil.hasAnnotation(Builder.Default.class, node)) continue top; + out.append(node); + } + return out.toList(); + } + private static JCExpression getDefaultExpr(JavacTreeMaker maker, JCExpression type) { if (type instanceof JCPrimitiveTypeTree) { switch (((JCPrimitiveTypeTree) type).getPrimitiveTypeKind()) { |