From c11edbf032ce27e448faa00d37245665942095af Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Mon, 26 Aug 2019 21:41:10 +0200 Subject: [With] renaming lombok.experimental.Wither to lombok.experimental.With --- src/core/lombok/ConfigurationKeys.java | 12 +- src/core/lombok/With.java | 94 +++++++ src/core/lombok/core/LombokInternalAliasing.java | 3 +- src/core/lombok/core/handlers/HandlerUtil.java | 14 +- .../eclipse/handlers/EclipseHandlerUtil.java | 16 +- src/core/lombok/eclipse/handlers/HandleWith.java | 293 ++++++++++++++++++++ src/core/lombok/eclipse/handlers/HandleWither.java | 293 -------------------- src/core/lombok/experimental/Wither.java | 4 +- src/core/lombok/javac/handlers/HandleWith.java | 294 +++++++++++++++++++++ src/core/lombok/javac/handlers/HandleWither.java | 294 --------------------- .../lombok/javac/handlers/JavacHandlerUtil.java | 32 ++- 11 files changed, 726 insertions(+), 623 deletions(-) create mode 100644 src/core/lombok/With.java create mode 100644 src/core/lombok/eclipse/handlers/HandleWith.java delete mode 100644 src/core/lombok/eclipse/handlers/HandleWither.java create mode 100644 src/core/lombok/javac/handlers/HandleWith.java delete mode 100644 src/core/lombok/javac/handlers/HandleWither.java (limited to 'src/core') diff --git a/src/core/lombok/ConfigurationKeys.java b/src/core/lombok/ConfigurationKeys.java index d46889d6..0baf1f3b 100644 --- a/src/core/lombok/ConfigurationKeys.java +++ b/src/core/lombok/ConfigurationKeys.java @@ -593,14 +593,14 @@ public class ConfigurationKeys { */ public static final ConfigurationKey FIELD_NAME_CONSTANTS_UPPERCASE = new ConfigurationKey("lombok.fieldNameConstants.uppercase", "The default name of the constants inside the inner type generated by @FieldNameConstants follow the variable name precisely. If this config key is true, lombok will uppercase them as best it can. (default: false).") {}; - // ----- Wither ----- + // ----- With ----- /** - * lombok configuration: {@code lombok.wither.flagUsage} = {@code WARNING} | {@code ERROR}. + * lombok configuration: {@code lombok.with.flagUsage} = {@code WARNING} | {@code ERROR}. * - * If set, any usage of {@code @Wither} results in a warning / error. + * If set, any usage of {@code @With} results in a warning / error. */ - public static final ConfigurationKey WITHER_FLAG_USAGE = new ConfigurationKey("lombok.wither.flagUsage", "Emit a warning or error if @Wither is used.") {}; + public static final ConfigurationKey WITH_FLAG_USAGE = new ConfigurationKey("lombok.with.flagUsage", "Emit a warning or error if @With is used.") {}; // ----- SuperBuilder ----- @@ -625,9 +625,9 @@ public class ConfigurationKeys { /** * lombok configuration: {@code lombok.copyableAnnotations} += <TypeName: fully-qualified annotation class name>. * - * Copy these annotations to getters, setters, withers, builder-setters, etc. + * Copy these annotations to getters, setters, with methods, builder-setters, etc. */ - public static final ConfigurationKey> COPYABLE_ANNOTATIONS = new ConfigurationKey>("lombok.copyableAnnotations", "Copy these annotations to getters, setters, withers, builder-setters, etc.") {}; + public static final ConfigurationKey> COPYABLE_ANNOTATIONS = new ConfigurationKey>("lombok.copyableAnnotations", "Copy these annotations to getters, setters, with methods, builder-setters, etc.") {}; /** * lombok configuration: {@code checkerframework} = {@code true} | {@code false} | <String: MajorVer.MinorVer> (Default: false). diff --git a/src/core/lombok/With.java b/src/core/lombok/With.java new file mode 100644 index 00000000..141d1fa6 --- /dev/null +++ b/src/core/lombok/With.java @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2012-2019 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; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import lombok.AccessLevel; + +/** + * Put on any field to make lombok build a 'with' - a withX method which produces a clone of this object (except for 1 field which gets a new value). + *

+ * Complete documentation is found at the project lombok features page for @With. + *

+ * Example: + *

+ *     private @With final int foo;
+ * 
+ * + * will generate: + * + *
+ *     public SELF_TYPE withFoo(int foo) {
+ *         return this.foo == foo ? this : new SELF_TYPE(otherField1, otherField2, foo);
+ *     }
+ * 
+ *

+ * This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have + * a {@code With} annotation have the annotation. + */ +@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.SOURCE) +public @interface With { + /** + * If you want your with method to be non-public, you can specify an alternate access level here. + * + * @return The method will be generated with this access modifier. + */ + AccessLevel value() default AccessLevel.PUBLIC; + + /** + * Any annotations listed here are put on the generated method. + * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
+ * up to JDK7:
+ * {@code @With(onMethod=@__({@AnnotationsGoHere}))}
+ * from JDK8:
+ * {@code @With(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. + * + * @return List of annotations to apply to the generated method. + */ + AnyAnnotation[] onMethod() default {}; + + /** + * Any annotations listed here are put on the generated method's parameter. + * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).
+ * up to JDK7:
+ * {@code @With(onParam=@__({@AnnotationsGoHere}))}
+ * from JDK8:
+ * {@code @With(onParam_={@AnnotationsGohere})} // note the underscore after {@code onParam}. + * + * @return List of annotations to apply to the generated parameter in the method. + */ + AnyAnnotation[] onParam() default {}; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} +} diff --git a/src/core/lombok/core/LombokInternalAliasing.java b/src/core/lombok/core/LombokInternalAliasing.java index c1089580..0b92d3b9 100644 --- a/src/core/lombok/core/LombokInternalAliasing.java +++ b/src/core/lombok/core/LombokInternalAliasing.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013-2018 The Project Lombok Authors. + * Copyright (C) 2013-2019 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 @@ -51,6 +51,7 @@ public class LombokInternalAliasing { m2.put("lombok.experimental.Builder", "lombok.Builder"); m2.put("lombok.experimental.var", "lombok.var"); m2.put("lombok.Delegate", "lombok.experimental.Delegate"); + m2.put("lombok.experimental.Wither", "lombok.With"); ALIASES = Collections.unmodifiableMap(m2); } } diff --git a/src/core/lombok/core/handlers/HandlerUtil.java b/src/core/lombok/core/handlers/HandlerUtil.java index 21a3a216..be32e101 100644 --- a/src/core/lombok/core/handlers/HandlerUtil.java +++ b/src/core/lombok/core/handlers/HandlerUtil.java @@ -38,6 +38,7 @@ import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.Value; +import lombok.With; import lombok.core.AST; import lombok.core.AnnotationValues; import lombok.core.JavaIdentifiers; @@ -47,7 +48,6 @@ import lombok.core.configuration.ConfigurationKey; import lombok.core.configuration.FlagUsageType; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; -import lombok.experimental.Wither; /** * Container for static utility methods useful for some of the standard lombok handlers, regardless of @@ -406,7 +406,7 @@ public class HandlerUtil { @SuppressWarnings({"all", "unchecked", "deprecation"}) public static final List INVALID_ON_BUILDERS = Collections.unmodifiableList( Arrays.asList( - Getter.class.getName(), Setter.class.getName(), Wither.class.getName(), + Getter.class.getName(), Setter.class.getName(), With.class.getName(), "lombok.experimental.Wither", ToString.class.getName(), EqualsAndHashCode.class.getName(), RequiredArgsConstructor.class.getName(), AllArgsConstructor.class.getName(), NoArgsConstructor.class.getName(), Data.class.getName(), Value.class.getName(), "lombok.experimental.Value", FieldDefaults.class.getName())); @@ -502,7 +502,7 @@ public class HandlerUtil { } /** - * Generates a wither name from a given field name. + * Generates a with name from a given field name. * * Strategy: *

    @@ -518,9 +518,9 @@ public class HandlerUtil { * @param accessors Accessors configuration. * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type {@code java.lang.Boolean}, you should provide {@code false}. - * @return The wither name for this field, or {@code null} if this field does not fit expected patterns and therefore cannot be turned into a getter name. + * @return The with name for this field, or {@code null} if this field does not fit expected patterns and therefore cannot be turned into a getter name. */ - public static String toWitherName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { + public static String toWithName(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAccessorName(ast, accessors, fieldName, isBoolean, "with", "with", false); } @@ -582,7 +582,7 @@ public class HandlerUtil { } /** - * Returns all names of methods that would represent the wither for a field with the provided name. + * Returns all names of methods that would represent the with for a field with the provided name. * * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:
    * {@code [withRunning, withIsRunning]} @@ -591,7 +591,7 @@ public class HandlerUtil { * @param fieldName the name of the field. * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. */ - public static List toAllWitherNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { + public static List toAllWithNames(AST ast, AnnotationValues accessors, CharSequence fieldName, boolean isBoolean) { return toAllAccessorNames(ast, accessors, fieldName, isBoolean, "with", "with", false); } diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index 6a6d4cca..0955dba6 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -1417,20 +1417,20 @@ public class EclipseHandlerUtil { } /** - * Translates the given field into all possible wither names. - * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. + * Translates the given field into all possible with names. + * Convenient wrapper around {@link TransformationsUtil#toAllWithNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ - public static java.util.List toAllWitherNames(EclipseNode field, boolean isBoolean) { - return HandlerUtil.toAllWitherNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); + public static java.util.List toAllWithNames(EclipseNode field, boolean isBoolean) { + return HandlerUtil.toAllWithNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** - * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). + * @return the likely with name for the stated field. (e.g. private boolean foo; to withFoo). * - * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. + * Convenient wrapper around {@link TransformationsUtil#toWithName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ - public static String toWitherName(EclipseNode field, boolean isBoolean) { - return HandlerUtil.toWitherName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); + public static String toWithName(EclipseNode field, boolean isBoolean) { + return HandlerUtil.toWithName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean); } /** diff --git a/src/core/lombok/eclipse/handlers/HandleWith.java b/src/core/lombok/eclipse/handlers/HandleWith.java new file mode 100644 index 00000000..8c8c3712 --- /dev/null +++ b/src/core/lombok/eclipse/handlers/HandleWith.java @@ -0,0 +1,293 @@ +/* + * Copyright (C) 2012-2019 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.eclipse.handlers; + +import static lombok.core.handlers.HandlerUtil.*; +import static lombok.eclipse.Eclipse.*; +import static lombok.eclipse.handlers.EclipseHandlerUtil.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import lombok.AccessLevel; +import lombok.ConfigurationKeys; +import lombok.With; +import lombok.core.AST.Kind; +import lombok.core.configuration.CheckerFrameworkVersion; +import lombok.core.AnnotationValues; +import lombok.eclipse.EclipseAnnotationHandler; +import lombok.eclipse.EclipseNode; + +import org.eclipse.jdt.internal.compiler.ast.ASTNode; +import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.Argument; +import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; +import org.eclipse.jdt.internal.compiler.ast.EqualExpression; +import org.eclipse.jdt.internal.compiler.ast.Expression; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.OperatorIds; +import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; +import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.ThisReference; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.ast.TypeReference; +import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; +import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; +import org.mangosdk.spi.ProviderFor; + +@ProviderFor(EclipseAnnotationHandler.class) +public class HandleWith extends EclipseAnnotationHandler { + public boolean generateWithForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelWith) { + if (checkForTypeLevelWith) { + if (hasAnnotation(With.class, typeNode)) { + //The annotation will make it happen, so we can skip it. + return true; + } + } + + TypeDeclaration typeDecl = null; + if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); + int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; + boolean notAClass = (modifiers & + (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; + + if (typeDecl == null || notAClass) { + pos.addError("@With is only supported on a class or a field."); + return false; + } + + for (EclipseNode field : typeNode.down()) { + if (field.getKind() != Kind.FIELD) continue; + FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); + if (!filterField(fieldDecl)) continue; + + //Skip final fields. + if ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0 && fieldDecl.initialization != null) continue; + + generateWithForField(field, pos, level); + } + return true; + } + + + /** + * Generates a with on the stated field. + * + * Used by {@link HandleValue}. + * + * The difference between this call and the handle method is as follows: + * + * If there is a {@code lombok.With} annotation on the field, it is used and the + * same rules apply (e.g. warning if the method already exists, stated access level applies). + * If not, the with method is still generated if it isn't already there, though there will not + * be a warning if its already there. The default access level is used. + */ + public void generateWithForField(EclipseNode fieldNode, EclipseNode sourceNode, AccessLevel level) { + for (EclipseNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (annotationTypeMatches(With.class, child)) { + //The annotation will make it happen, so we can skip it. + return; + } + } + } + + List empty = Collections.emptyList(); + createWithForField(level, fieldNode, sourceNode, false, empty, empty); + } + + @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { + handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITH_FLAG_USAGE, "@With"); + + EclipseNode node = annotationNode.up(); + AccessLevel level = annotation.getInstance().value(); + if (level == AccessLevel.NONE || node == null) return; + + List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@With(onMethod", annotationNode); + List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@With(onParam", annotationNode); + + switch (node.getKind()) { + case FIELD: + createWithForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, true, onMethod, onParam); + break; + case TYPE: + if (!onMethod.isEmpty()) { + annotationNode.addError("'onMethod' is not supported for @With on a type."); + } + if (!onParam.isEmpty()) { + annotationNode.addError("'onParam' is not supported for @With on a type."); + } + generateWithForType(node, annotationNode, level, false); + break; + } + } + + public void createWithForFields(AccessLevel level, Collection fieldNodes, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { + for (EclipseNode fieldNode : fieldNodes) { + createWithForField(level, fieldNode, sourceNode, whineIfExists, onMethod, onParam); + } + } + + public void createWithForField( + AccessLevel level, EclipseNode fieldNode, EclipseNode sourceNode, + boolean whineIfExists, List onMethod, + List onParam) { + + ASTNode source = sourceNode.get(); + if (fieldNode.getKind() != Kind.FIELD) { + sourceNode.addError("@With is only supported on a class or a field."); + return; + } + + EclipseNode typeNode = fieldNode.up(); + boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((TypeDeclaration) typeNode.get()).modifiers & ClassFileConstants.AccAbstract) != 0; + + FieldDeclaration field = (FieldDeclaration) fieldNode.get(); + TypeReference fieldType = copyType(field.type, source); + boolean isBoolean = isBoolean(fieldType); + String withName = toWithName(fieldNode, isBoolean); + + if (withName == null) { + fieldNode.addWarning("Not generating a with method for this field: It does not fit your @Accessors prefix list."); + return; + } + + if ((field.modifiers & ClassFileConstants.AccStatic) != 0) { + fieldNode.addWarning("Not generating " + withName + " for this field: With methods cannot be generated for static fields."); + return; + } + + if ((field.modifiers & ClassFileConstants.AccFinal) != 0 && field.initialization != null) { + fieldNode.addWarning("Not generating " + withName + " for this field: With methods cannot be generated for final, initialized fields."); + return; + } + + if (field.name != null && field.name.length > 0 && field.name[0] == '$') { + fieldNode.addWarning("Not generating " + withName + " for this field: With methods cannot be generated for fields starting with $."); + return; + } + + for (String altName : toAllWithNames(fieldNode, isBoolean)) { + switch (methodExists(altName, fieldNode, false, 1)) { + case EXISTS_BY_LOMBOK: + return; + case EXISTS_BY_USER: + if (whineIfExists) { + String altNameExpl = ""; + if (!altName.equals(withName)) altNameExpl = String.format(" (%s)", altName); + fieldNode.addWarning( + String.format("Not generating %s(): A method with that name already exists%s", withName, altNameExpl)); + } + return; + default: + case NOT_EXISTS: + //continue scanning the other alt names. + } + } + + int modifier = toEclipseModifier(level); + + MethodDeclaration method = createWith((TypeDeclaration) fieldNode.up().get(), fieldNode, withName, modifier, sourceNode, onMethod, onParam, makeAbstract); + injectMethod(fieldNode.up(), method); + } + + public MethodDeclaration createWith(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, EclipseNode sourceNode, List onMethod, List onParam, boolean makeAbstract ) { + ASTNode source = sourceNode.get(); + if (name == null) return null; + FieldDeclaration field = (FieldDeclaration) fieldNode.get(); + int pS = source.sourceStart, pE = source.sourceEnd; + long p = (long) pS << 32 | pE; + MethodDeclaration method = new MethodDeclaration(parent.compilationResult); + if (makeAbstract) modifier = modifier | ClassFileConstants.AccAbstract | ExtraCompilerModifiers.AccSemicolonBody; + method.modifiers = modifier; + method.returnType = cloneSelfType(fieldNode, source); + if (method.returnType == null) return null; + + Annotation[] deprecated = null, checkerFramework = null; + if (isFieldDeprecated(fieldNode)) deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; + if (getCheckerFrameworkVersion(fieldNode).generateSideEffectFree()) checkerFramework = new Annotation[] { generateNamedAnnotation(source, CheckerFrameworkVersion.NAME__SIDE_EFFECT_FREE) }; + + method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), checkerFramework, deprecated); + Argument param = new Argument(field.name, p, copyType(field.type, source), ClassFileConstants.AccFinal); + param.sourceStart = pS; param.sourceEnd = pE; + method.arguments = new Argument[] { param }; + method.selector = name.toCharArray(); + method.binding = null; + method.thrownExceptions = null; + method.typeParameters = null; + method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + + Annotation[] copyableAnnotations = findCopyableAnnotations(fieldNode); + + if (!makeAbstract) { + List args = new ArrayList(); + for (EclipseNode child : fieldNode.up().down()) { + if (child.getKind() != Kind.FIELD) continue; + FieldDeclaration childDecl = (FieldDeclaration) child.get(); + // Skip fields that start with $ + if (childDecl.name != null && childDecl.name.length > 0 && childDecl.name[0] == '$') continue; + long fieldFlags = childDecl.modifiers; + // Skip static fields. + if ((fieldFlags & ClassFileConstants.AccStatic) != 0) continue; + // Skip initialized final fields. + if (((fieldFlags & ClassFileConstants.AccFinal) != 0) && childDecl.initialization != null) continue; + if (child.get() == fieldNode.get()) { + args.add(new SingleNameReference(field.name, p)); + } else { + args.add(createFieldAccessor(child, FieldAccess.ALWAYS_FIELD, source)); + } + } + + AllocationExpression constructorCall = new AllocationExpression(); + constructorCall.arguments = args.toArray(new Expression[0]); + constructorCall.type = cloneSelfType(fieldNode, source); + + Expression identityCheck = new EqualExpression( + createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source), + new SingleNameReference(field.name, p), + OperatorIds.EQUAL_EQUAL); + ThisReference thisRef = new ThisReference(pS, pE); + Expression conditional = new ConditionalExpression(identityCheck, thisRef, constructorCall); + Statement returnStatement = new ReturnStatement(conditional, pS, pE); + method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; + method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; + + List statements = new ArrayList(5); + if (hasNonNullAnnotations(fieldNode)) { + Statement nullCheck = generateNullCheck(field, sourceNode); + if (nullCheck != null) statements.add(nullCheck); + } + statements.add(returnStatement); + + method.statements = statements.toArray(new Statement[0]); + } + param.annotations = copyAnnotations(source, copyableAnnotations, onParam.toArray(new Annotation[0])); + + method.traverse(new SetGeneratedByVisitor(source), parent.scope); + return method; + } +} diff --git a/src/core/lombok/eclipse/handlers/HandleWither.java b/src/core/lombok/eclipse/handlers/HandleWither.java deleted file mode 100644 index 8be08cfe..00000000 --- a/src/core/lombok/eclipse/handlers/HandleWither.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (C) 2012-2019 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.eclipse.handlers; - -import static lombok.core.handlers.HandlerUtil.*; -import static lombok.eclipse.Eclipse.*; -import static lombok.eclipse.handlers.EclipseHandlerUtil.*; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import lombok.AccessLevel; -import lombok.ConfigurationKeys; -import lombok.core.AST.Kind; -import lombok.core.configuration.CheckerFrameworkVersion; -import lombok.core.AnnotationValues; -import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseNode; -import lombok.experimental.Wither; - -import org.eclipse.jdt.internal.compiler.ast.ASTNode; -import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; -import org.eclipse.jdt.internal.compiler.ast.Annotation; -import org.eclipse.jdt.internal.compiler.ast.Argument; -import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; -import org.eclipse.jdt.internal.compiler.ast.EqualExpression; -import org.eclipse.jdt.internal.compiler.ast.Expression; -import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; -import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; -import org.eclipse.jdt.internal.compiler.ast.OperatorIds; -import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; -import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.jdt.internal.compiler.ast.Statement; -import org.eclipse.jdt.internal.compiler.ast.ThisReference; -import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; -import org.eclipse.jdt.internal.compiler.ast.TypeReference; -import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; -import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; -import org.mangosdk.spi.ProviderFor; - -@ProviderFor(EclipseAnnotationHandler.class) -public class HandleWither extends EclipseAnnotationHandler { - public boolean generateWitherForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelWither) { - if (checkForTypeLevelWither) { - if (hasAnnotation(Wither.class, typeNode)) { - //The annotation will make it happen, so we can skip it. - return true; - } - } - - TypeDeclaration typeDecl = null; - if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); - int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; - boolean notAClass = (modifiers & - (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; - - if (typeDecl == null || notAClass) { - pos.addError("@Wither is only supported on a class or a field."); - return false; - } - - for (EclipseNode field : typeNode.down()) { - if (field.getKind() != Kind.FIELD) continue; - FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); - if (!filterField(fieldDecl)) continue; - - //Skip final fields. - if ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0 && fieldDecl.initialization != null) continue; - - generateWitherForField(field, pos, level); - } - return true; - } - - - /** - * Generates a wither on the stated field. - * - * Used by {@link HandleValue}. - * - * The difference between this call and the handle method is as follows: - * - * If there is a {@code lombok.experimental.Wither} annotation on the field, it is used and the - * same rules apply (e.g. warning if the method already exists, stated access level applies). - * If not, the wither is still generated if it isn't already there, though there will not - * be a warning if its already there. The default access level is used. - */ - public void generateWitherForField(EclipseNode fieldNode, EclipseNode sourceNode, AccessLevel level) { - for (EclipseNode child : fieldNode.down()) { - if (child.getKind() == Kind.ANNOTATION) { - if (annotationTypeMatches(Wither.class, child)) { - //The annotation will make it happen, so we can skip it. - return; - } - } - } - - List empty = Collections.emptyList(); - createWitherForField(level, fieldNode, sourceNode, false, empty, empty); - } - - @Override public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { - handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither"); - - EclipseNode node = annotationNode.up(); - AccessLevel level = annotation.getInstance().value(); - if (level == AccessLevel.NONE || node == null) return; - - List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod", annotationNode); - List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam", annotationNode); - - switch (node.getKind()) { - case FIELD: - createWitherForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, true, onMethod, onParam); - break; - case TYPE: - if (!onMethod.isEmpty()) { - annotationNode.addError("'onMethod' is not supported for @Wither on a type."); - } - if (!onParam.isEmpty()) { - annotationNode.addError("'onParam' is not supported for @Wither on a type."); - } - generateWitherForType(node, annotationNode, level, false); - break; - } - } - - public void createWitherForFields(AccessLevel level, Collection fieldNodes, EclipseNode sourceNode, boolean whineIfExists, List onMethod, List onParam) { - for (EclipseNode fieldNode : fieldNodes) { - createWitherForField(level, fieldNode, sourceNode, whineIfExists, onMethod, onParam); - } - } - - public void createWitherForField( - AccessLevel level, EclipseNode fieldNode, EclipseNode sourceNode, - boolean whineIfExists, List onMethod, - List onParam) { - - ASTNode source = sourceNode.get(); - if (fieldNode.getKind() != Kind.FIELD) { - sourceNode.addError("@Wither is only supported on a class or a field."); - return; - } - - EclipseNode typeNode = fieldNode.up(); - boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((TypeDeclaration) typeNode.get()).modifiers & ClassFileConstants.AccAbstract) != 0; - - FieldDeclaration field = (FieldDeclaration) fieldNode.get(); - TypeReference fieldType = copyType(field.type, source); - boolean isBoolean = isBoolean(fieldType); - String witherName = toWitherName(fieldNode, isBoolean); - - if (witherName == null) { - fieldNode.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); - return; - } - - if ((field.modifiers & ClassFileConstants.AccStatic) != 0) { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for static fields."); - return; - } - - if ((field.modifiers & ClassFileConstants.AccFinal) != 0 && field.initialization != null) { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for final, initialized fields."); - return; - } - - if (field.name != null && field.name.length > 0 && field.name[0] == '$') { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for fields starting with $."); - return; - } - - for (String altName : toAllWitherNames(fieldNode, isBoolean)) { - switch (methodExists(altName, fieldNode, false, 1)) { - case EXISTS_BY_LOMBOK: - return; - case EXISTS_BY_USER: - if (whineIfExists) { - String altNameExpl = ""; - if (!altName.equals(witherName)) altNameExpl = String.format(" (%s)", altName); - fieldNode.addWarning( - String.format("Not generating %s(): A method with that name already exists%s", witherName, altNameExpl)); - } - return; - default: - case NOT_EXISTS: - //continue scanning the other alt names. - } - } - - int modifier = toEclipseModifier(level); - - MethodDeclaration method = createWither((TypeDeclaration) fieldNode.up().get(), fieldNode, witherName, modifier, sourceNode, onMethod, onParam, makeAbstract); - injectMethod(fieldNode.up(), method); - } - - public MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, EclipseNode sourceNode, List onMethod, List onParam, boolean makeAbstract ) { - ASTNode source = sourceNode.get(); - if (name == null) return null; - FieldDeclaration field = (FieldDeclaration) fieldNode.get(); - int pS = source.sourceStart, pE = source.sourceEnd; - long p = (long) pS << 32 | pE; - MethodDeclaration method = new MethodDeclaration(parent.compilationResult); - if (makeAbstract) modifier = modifier | ClassFileConstants.AccAbstract | ExtraCompilerModifiers.AccSemicolonBody; - method.modifiers = modifier; - method.returnType = cloneSelfType(fieldNode, source); - if (method.returnType == null) return null; - - Annotation[] deprecated = null, checkerFramework = null; - if (isFieldDeprecated(fieldNode)) deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; - if (getCheckerFrameworkVersion(fieldNode).generateSideEffectFree()) checkerFramework = new Annotation[] { generateNamedAnnotation(source, CheckerFrameworkVersion.NAME__SIDE_EFFECT_FREE) }; - - method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), checkerFramework, deprecated); - Argument param = new Argument(field.name, p, copyType(field.type, source), ClassFileConstants.AccFinal); - param.sourceStart = pS; param.sourceEnd = pE; - method.arguments = new Argument[] { param }; - method.selector = name.toCharArray(); - method.binding = null; - method.thrownExceptions = null; - method.typeParameters = null; - method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; - - Annotation[] copyableAnnotations = findCopyableAnnotations(fieldNode); - - if (!makeAbstract) { - List args = new ArrayList(); - for (EclipseNode child : fieldNode.up().down()) { - if (child.getKind() != Kind.FIELD) continue; - FieldDeclaration childDecl = (FieldDeclaration) child.get(); - // Skip fields that start with $ - if (childDecl.name != null && childDecl.name.length > 0 && childDecl.name[0] == '$') continue; - long fieldFlags = childDecl.modifiers; - // Skip static fields. - if ((fieldFlags & ClassFileConstants.AccStatic) != 0) continue; - // Skip initialized final fields. - if (((fieldFlags & ClassFileConstants.AccFinal) != 0) && childDecl.initialization != null) continue; - if (child.get() == fieldNode.get()) { - args.add(new SingleNameReference(field.name, p)); - } else { - args.add(createFieldAccessor(child, FieldAccess.ALWAYS_FIELD, source)); - } - } - - AllocationExpression constructorCall = new AllocationExpression(); - constructorCall.arguments = args.toArray(new Expression[0]); - constructorCall.type = cloneSelfType(fieldNode, source); - - Expression identityCheck = new EqualExpression( - createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source), - new SingleNameReference(field.name, p), - OperatorIds.EQUAL_EQUAL); - ThisReference thisRef = new ThisReference(pS, pE); - Expression conditional = new ConditionalExpression(identityCheck, thisRef, constructorCall); - Statement returnStatement = new ReturnStatement(conditional, pS, pE); - method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; - method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; - - List statements = new ArrayList(5); - if (hasNonNullAnnotations(fieldNode)) { - Statement nullCheck = generateNullCheck(field, sourceNode); - if (nullCheck != null) statements.add(nullCheck); - } - statements.add(returnStatement); - - method.statements = statements.toArray(new Statement[0]); - } - param.annotations = copyAnnotations(source, copyableAnnotations, onParam.toArray(new Annotation[0])); - - method.traverse(new SetGeneratedByVisitor(source), parent.scope); - return method; - } -} diff --git a/src/core/lombok/experimental/Wither.java b/src/core/lombok/experimental/Wither.java index 3df546d0..cf20c1eb 100644 --- a/src/core/lombok/experimental/Wither.java +++ b/src/core/lombok/experimental/Wither.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2017 The Project Lombok Authors. + * Copyright (C) 2012-2019 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 @@ -50,6 +50,8 @@ import lombok.AccessLevel; *

    * This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code Wither} annotation have the annotation. + * + * @deprecated {@link lombok.With} has been promoted to the main package, so use that one instead. */ @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) diff --git a/src/core/lombok/javac/handlers/HandleWith.java b/src/core/lombok/javac/handlers/HandleWith.java new file mode 100644 index 00000000..fd14e06a --- /dev/null +++ b/src/core/lombok/javac/handlers/HandleWith.java @@ -0,0 +1,294 @@ +/* + * Copyright (C) 2012-2019 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.core.handlers.HandlerUtil.*; +import static lombok.javac.Javac.*; +import static lombok.javac.handlers.JavacHandlerUtil.*; + +import java.util.Collection; + +import lombok.AccessLevel; +import lombok.ConfigurationKeys; +import lombok.With; +import lombok.core.AST.Kind; +import lombok.core.AnnotationValues; +import lombok.core.configuration.CheckerFrameworkVersion; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.JavacHandlerUtil.CopyJavadoc; + +import org.mangosdk.spi.ProviderFor; + +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.Symbol.ClassSymbol; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCConditional; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCNewClass; +import com.sun.tools.javac.tree.JCTree.JCReturn; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import com.sun.tools.javac.util.Name; + +/** + * Handles the {@code lombok.With} annotation for javac. + */ +@ProviderFor(JavacAnnotationHandler.class) +public class HandleWith extends JavacAnnotationHandler { + public void generateWithForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelWith) { + if (checkForTypeLevelWith) { + if (hasAnnotation(With.class, typeNode)) { + //The annotation will make it happen, so we can skip it. + return; + } + } + + JCClassDecl typeDecl = null; + if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); + long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; + boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; + + if (typeDecl == null || notAClass) { + errorNode.addError("@With is only supported on a class or a field."); + return; + } + + for (JavacNode field : typeNode.down()) { + if (field.getKind() != Kind.FIELD) continue; + JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); + //Skip fields that start with $ + if (fieldDecl.name.toString().startsWith("$")) continue; + //Skip static fields. + if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; + //Skip final initialized fields. + if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) continue; + + generateWithForField(field, errorNode.get(), level); + } + } + + /** + * Generates a with on the stated field. + * + * Used by {@link HandleValue}. + * + * The difference between this call and the handle method is as follows: + * + * If there is a {@code lombok.experimental.With} annotation on the field, it is used and the + * same rules apply (e.g. warning if the method already exists, stated access level applies). + * If not, the with is still generated if it isn't already there, though there will not + * be a warning if its already there. The default access level is used. + * + * @param fieldNode The node representing the field you want a with for. + * @param pos The node responsible for generating the with (the {@code @Value} or {@code @With} annotation). + */ + public void generateWithForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level) { + if (hasAnnotation(With.class, fieldNode)) { + //The annotation will make it happen, so we can skip it. + return; + } + + createWithForField(level, fieldNode, fieldNode, false, List.nil(), List.nil()); + } + + @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { + handleFlagUsage(annotationNode, ConfigurationKeys.WITH_FLAG_USAGE, "@With"); + + Collection fields = annotationNode.upFromAnnotationToFields(); + deleteAnnotationIfNeccessary(annotationNode, With.class, "lombok.experimental.Wither"); + deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); + JavacNode node = annotationNode.up(); + AccessLevel level = annotation.getInstance().value(); + + if (level == AccessLevel.NONE || node == null) return; + + List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@With(onMethod", annotationNode); + List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@With(onParam", annotationNode); + + switch (node.getKind()) { + case FIELD: + createWithForFields(level, fields, annotationNode, true, onMethod, onParam); + break; + case TYPE: + if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @With on a type."); + if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @With on a type."); + generateWithForType(node, annotationNode, level, false); + break; + } + } + + public void createWithForFields(AccessLevel level, Collection fieldNodes, JavacNode errorNode, boolean whineIfExists, List onMethod, List onParam) { + for (JavacNode fieldNode : fieldNodes) { + createWithForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); + } + } + + public void createWithForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean strictMode, List onMethod, List onParam) { + JavacNode typeNode = fieldNode.up(); + boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((JCClassDecl) typeNode.get()).mods.flags & Flags.ABSTRACT) != 0; + + if (fieldNode.getKind() != Kind.FIELD) { + fieldNode.addError("@With is only supported on a class or a field."); + return; + } + + JCVariableDecl fieldDecl = (JCVariableDecl) fieldNode.get(); + String methodName = toWithName(fieldNode); + + if (methodName == null) { + fieldNode.addWarning("Not generating a withX method for this field: It does not fit your @Accessors prefix list."); + return; + } + + if ((fieldDecl.mods.flags & Flags.STATIC) != 0) { + if (strictMode) { + fieldNode.addWarning("Not generating " + methodName + " for this field: With methods cannot be generated for static fields."); + } + return; + } + + if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) { + if (strictMode) { + fieldNode.addWarning("Not generating " + methodName + " for this field: With methods cannot be generated for final, initialized fields."); + } + return; + } + + if (fieldDecl.name.toString().startsWith("$")) { + if (strictMode) { + fieldNode.addWarning("Not generating " + methodName + " for this field: With methods cannot be generated for fields starting with $."); + } + return; + } + + for (String altName : toAllWithNames(fieldNode)) { + switch (methodExists(altName, fieldNode, false, 1)) { + case EXISTS_BY_LOMBOK: + return; + case EXISTS_BY_USER: + if (strictMode) { + String altNameExpl = ""; + if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); + fieldNode.addWarning( + String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); + } + return; + default: + case NOT_EXISTS: + //continue scanning the other alt names. + } + } + + long access = toJavacModifier(level); + + JCMethodDecl createdWith = createWith(access, fieldNode, fieldNode.getTreeMaker(), source, onMethod, onParam, makeAbstract); + ClassSymbol sym = ((JCClassDecl) fieldNode.up().get()).sym; + Type returnType = sym == null ? null : sym.type; + + injectMethod(typeNode, createdWith, List.of(getMirrorForFieldType(fieldNode)), returnType); + } + + public JCMethodDecl createWith(long access, JavacNode field, JavacTreeMaker maker, JavacNode source, List onMethod, List onParam, boolean makeAbstract) { + String withName = toWithName(field); + if (withName == null) return null; + + JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); + + List copyableAnnotations = findCopyableAnnotations(field); + + Name methodName = field.toName(withName); + + JCExpression returnType = cloneSelfType(field); + + JCBlock methodBody = null; + long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext()); + List annsOnParam = copyAnnotations(onParam).appendList(copyableAnnotations); + + JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); + + if (!makeAbstract) { + ListBuffer statements = new ListBuffer(); + + JCExpression selfType = cloneSelfType(field); + if (selfType == null) return null; + + ListBuffer args = new ListBuffer(); + for (JavacNode child : field.up().down()) { + if (child.getKind() != Kind.FIELD) continue; + JCVariableDecl childDecl = (JCVariableDecl) child.get(); + // Skip fields that start with $ + if (childDecl.name.toString().startsWith("$")) continue; + long fieldFlags = childDecl.mods.flags; + // Skip static fields. + if ((fieldFlags & Flags.STATIC) != 0) continue; + // Skip initialized final fields. + if (((fieldFlags & Flags.FINAL) != 0) && childDecl.init != null) continue; + if (child.get() == field.get()) { + args.append(maker.Ident(fieldDecl.name)); + } else { + args.append(createFieldAccessor(maker, child, FieldAccess.ALWAYS_FIELD)); + } + } + + JCNewClass newClass = maker.NewClass(null, List.nil(), selfType, args.toList(), null); + JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); + JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass); + JCReturn returnStatement = maker.Return(conditional); + + if (!hasNonNullAnnotations(field)) { + statements.append(returnStatement); + } else { + JCStatement nullCheck = generateNullCheck(maker, field, source); + if (nullCheck != null) statements.append(nullCheck); + statements.append(returnStatement); + } + + methodBody = maker.Block(0, statements.toList()); + } + List methodGenericParams = List.nil(); + List parameters = List.of(param); + List throwsClauses = List.nil(); + JCExpression annotationMethodDefaultValue = null; + + List annsOnMethod = copyAnnotations(onMethod); + CheckerFrameworkVersion checkerFramework = getCheckerFrameworkVersion(source); + if (checkerFramework.generateSideEffectFree()) annsOnMethod = annsOnMethod.prepend(maker.Annotation(genTypeRef(source, CheckerFrameworkVersion.NAME__SIDE_EFFECT_FREE), List.nil())); + + if (isFieldDeprecated(field)) annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.nil())); + + if (makeAbstract) access = access | Flags.ABSTRACT; + JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType, + methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext()); + copyJavadoc(field, decl, CopyJavadoc.WITH); + return decl; + } +} diff --git a/src/core/lombok/javac/handlers/HandleWither.java b/src/core/lombok/javac/handlers/HandleWither.java deleted file mode 100644 index 9c95cb78..00000000 --- a/src/core/lombok/javac/handlers/HandleWither.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2012-2019 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.core.handlers.HandlerUtil.*; -import static lombok.javac.Javac.*; -import static lombok.javac.handlers.JavacHandlerUtil.*; - -import java.util.Collection; - -import lombok.AccessLevel; -import lombok.ConfigurationKeys; -import lombok.core.AST.Kind; -import lombok.core.AnnotationValues; -import lombok.core.configuration.CheckerFrameworkVersion; -import lombok.experimental.Wither; -import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacNode; -import lombok.javac.JavacTreeMaker; -import lombok.javac.handlers.JavacHandlerUtil.CopyJavadoc; - -import org.mangosdk.spi.ProviderFor; - -import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.code.Symbol.ClassSymbol; -import com.sun.tools.javac.tree.JCTree.JCAnnotation; -import com.sun.tools.javac.tree.JCTree.JCBlock; -import com.sun.tools.javac.tree.JCTree.JCClassDecl; -import com.sun.tools.javac.tree.JCTree.JCConditional; -import com.sun.tools.javac.tree.JCTree.JCExpression; -import com.sun.tools.javac.tree.JCTree.JCMethodDecl; -import com.sun.tools.javac.tree.JCTree.JCNewClass; -import com.sun.tools.javac.tree.JCTree.JCReturn; -import com.sun.tools.javac.tree.JCTree.JCStatement; -import com.sun.tools.javac.tree.JCTree.JCTypeParameter; -import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; -import com.sun.tools.javac.util.List; -import com.sun.tools.javac.util.ListBuffer; -import com.sun.tools.javac.util.Name; - -/** - * Handles the {@code lombok.experimental.Wither} annotation for javac. - */ -@ProviderFor(JavacAnnotationHandler.class) -public class HandleWither extends JavacAnnotationHandler { - public void generateWitherForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelWither) { - if (checkForTypeLevelWither) { - if (hasAnnotation(Wither.class, typeNode)) { - //The annotation will make it happen, so we can skip it. - return; - } - } - - JCClassDecl typeDecl = null; - if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); - long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; - boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; - - if (typeDecl == null || notAClass) { - errorNode.addError("@Wither is only supported on a class or a field."); - return; - } - - for (JavacNode field : typeNode.down()) { - if (field.getKind() != Kind.FIELD) continue; - JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); - //Skip fields that start with $ - if (fieldDecl.name.toString().startsWith("$")) continue; - //Skip static fields. - if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; - //Skip final initialized fields. - if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) continue; - - generateWitherForField(field, errorNode.get(), level); - } - } - - /** - * Generates a wither on the stated field. - * - * Used by {@link HandleValue}. - * - * The difference between this call and the handle method is as follows: - * - * If there is a {@code lombok.experimental.Wither} annotation on the field, it is used and the - * same rules apply (e.g. warning if the method already exists, stated access level applies). - * If not, the wither is still generated if it isn't already there, though there will not - * be a warning if its already there. The default access level is used. - * - * @param fieldNode The node representing the field you want a wither for. - * @param pos The node responsible for generating the wither (the {@code @Value} or {@code @Wither} annotation). - */ - public void generateWitherForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level) { - if (hasAnnotation(Wither.class, fieldNode)) { - //The annotation will make it happen, so we can skip it. - return; - } - - createWitherForField(level, fieldNode, fieldNode, false, List.nil(), List.nil()); - } - - @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { - handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither"); - - Collection fields = annotationNode.upFromAnnotationToFields(); - deleteAnnotationIfNeccessary(annotationNode, Wither.class); - deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); - JavacNode node = annotationNode.up(); - AccessLevel level = annotation.getInstance().value(); - - if (level == AccessLevel.NONE || node == null) return; - - List onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod", annotationNode); - List onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam", annotationNode); - - switch (node.getKind()) { - case FIELD: - createWitherForFields(level, fields, annotationNode, true, onMethod, onParam); - break; - case TYPE: - if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Wither on a type."); - if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Wither on a type."); - generateWitherForType(node, annotationNode, level, false); - break; - } - } - - public void createWitherForFields(AccessLevel level, Collection fieldNodes, JavacNode errorNode, boolean whineIfExists, List onMethod, List onParam) { - for (JavacNode fieldNode : fieldNodes) { - createWitherForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); - } - } - - public void createWitherForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean strictMode, List onMethod, List onParam) { - JavacNode typeNode = fieldNode.up(); - boolean makeAbstract = typeNode != null && typeNode.getKind() == Kind.TYPE && (((JCClassDecl) typeNode.get()).mods.flags & Flags.ABSTRACT) != 0; - - if (fieldNode.getKind() != Kind.FIELD) { - fieldNode.addError("@Wither is only supported on a class or a field."); - return; - } - - JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); - String methodName = toWitherName(fieldNode); - - if (methodName == null) { - fieldNode.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); - return; - } - - if ((fieldDecl.mods.flags & Flags.STATIC) != 0) { - if (strictMode) { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for static fields."); - } - return; - } - - if ((fieldDecl.mods.flags & Flags.FINAL) != 0 && fieldDecl.init != null) { - if (strictMode) { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for final, initialized fields."); - } - return; - } - - if (fieldDecl.name.toString().startsWith("$")) { - if (strictMode) { - fieldNode.addWarning("Not generating wither for this field: Withers cannot be generated for fields starting with $."); - } - return; - } - - for (String altName : toAllWitherNames(fieldNode)) { - switch (methodExists(altName, fieldNode, false, 1)) { - case EXISTS_BY_LOMBOK: - return; - case EXISTS_BY_USER: - if (strictMode) { - String altNameExpl = ""; - if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); - fieldNode.addWarning( - String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); - } - return; - default: - case NOT_EXISTS: - //continue scanning the other alt names. - } - } - - long access = toJavacModifier(level); - - JCMethodDecl createdWither = createWither(access, fieldNode, fieldNode.getTreeMaker(), source, onMethod, onParam, makeAbstract); - ClassSymbol sym = ((JCClassDecl) fieldNode.up().get()).sym; - Type returnType = sym == null ? null : sym.type; - - injectMethod(typeNode, createdWither, List.of(getMirrorForFieldType(fieldNode)), returnType); - } - - public JCMethodDecl createWither(long access, JavacNode field, JavacTreeMaker maker, JavacNode source, List onMethod, List onParam, boolean makeAbstract) { - String witherName = toWitherName(field); - if (witherName == null) return null; - - JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); - - List copyableAnnotations = findCopyableAnnotations(field); - - Name methodName = field.toName(witherName); - - JCExpression returnType = cloneSelfType(field); - - JCBlock methodBody = null; - long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext()); - List annsOnParam = copyAnnotations(onParam).appendList(copyableAnnotations); - - JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); - - if (!makeAbstract) { - ListBuffer statements = new ListBuffer(); - - JCExpression selfType = cloneSelfType(field); - if (selfType == null) return null; - - ListBuffer args = new ListBuffer(); - for (JavacNode child : field.up().down()) { - if (child.getKind() != Kind.FIELD) continue; - JCVariableDecl childDecl = (JCVariableDecl) child.get(); - // Skip fields that start with $ - if (childDecl.name.toString().startsWith("$")) continue; - long fieldFlags = childDecl.mods.flags; - // Skip static fields. - if ((fieldFlags & Flags.STATIC) != 0) continue; - // Skip initialized final fields. - if (((fieldFlags & Flags.FINAL) != 0) && childDecl.init != null) continue; - if (child.get() == field.get()) { - args.append(maker.Ident(fieldDecl.name)); - } else { - args.append(createFieldAccessor(maker, child, FieldAccess.ALWAYS_FIELD)); - } - } - - JCNewClass newClass = maker.NewClass(null, List.nil(), selfType, args.toList(), null); - JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name)); - JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass); - JCReturn returnStatement = maker.Return(conditional); - - if (!hasNonNullAnnotations(field)) { - statements.append(returnStatement); - } else { - JCStatement nullCheck = generateNullCheck(maker, field, source); - if (nullCheck != null) statements.append(nullCheck); - statements.append(returnStatement); - } - - methodBody = maker.Block(0, statements.toList()); - } - List methodGenericParams = List.nil(); - List parameters = List.of(param); - List throwsClauses = List.nil(); - JCExpression annotationMethodDefaultValue = null; - - List annsOnMethod = copyAnnotations(onMethod); - CheckerFrameworkVersion checkerFramework = getCheckerFrameworkVersion(source); - if (checkerFramework.generateSideEffectFree()) annsOnMethod = annsOnMethod.prepend(maker.Annotation(genTypeRef(source, CheckerFrameworkVersion.NAME__SIDE_EFFECT_FREE), List.nil())); - - if (isFieldDeprecated(field)) annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.nil())); - - if (makeAbstract) access = access | Flags.ABSTRACT; - JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType, - methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext()); - copyJavadoc(field, decl, CopyJavadoc.WITHER); - return decl; - } -} diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index f23a894a..d12a980f 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -590,20 +590,20 @@ public class JavacHandlerUtil { } /** - * Translates the given field into all possible wither names. - * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. + * Translates the given field into all possible with names. + * Convenient wrapper around {@link TransformationsUtil#toAllWithNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ - public static java.util.List toAllWitherNames(JavacNode field) { - return HandlerUtil.toAllWitherNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); + public static java.util.List toAllWithNames(JavacNode field) { + return HandlerUtil.toAllWithNames(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** - * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). + * @return the likely with name for the stated field. (e.g. private boolean foo; to withFoo). * - * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. + * Convenient wrapper around {@link TransformationsUtil#toWithName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ - public static String toWitherName(JavacNode field) { - return HandlerUtil.toWitherName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); + public static String toWithName(JavacNode field) { + return HandlerUtil.toWithName(field.getAst(), getAccessorsForField(field), field.getName(), isBoolean(field)); } /** @@ -1883,7 +1883,7 @@ public class JavacHandlerUtil { return (JCExpression) in; } - private static final Pattern SECTION_FINDER = Pattern.compile("^\\s*\\**\\s*[-*][-*]+\\s*([GS]ETTER|WITHER)\\s*[-*][-*]+\\s*\\**\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); + private static final Pattern SECTION_FINDER = Pattern.compile("^\\s*\\**\\s*[-*][-*]+\\s*([GS]ETTER|WITH(?:ER)?)\\s*[-*][-*]+\\s*\\**\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); public static String stripLinesWithTagFromJavadoc(String javadoc, String regexpFragment) { Pattern p = Pattern.compile("^\\s*\\**\\s*" + regexpFragment + "\\s*\\**\\s*$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); @@ -1898,12 +1898,18 @@ public class JavacHandlerUtil { return javadoc.substring(0, m.start()); } - public static String getJavadocSection(String javadoc, String sectionName) { + public static String getJavadocSection(String javadoc, String sectionNameSpec) { + String[] sectionNames = sectionNameSpec.split("\\|"); Matcher m = SECTION_FINDER.matcher(javadoc); int sectionStart = -1; int sectionEnd = -1; while (m.find()) { - if (m.group(1).equalsIgnoreCase(sectionName)) { + boolean found = false; + for (String sectionName : sectionNames) if (m.group(1).equalsIgnoreCase(sectionName)) { + found = true; + break; + } + if (found) { sectionStart = m.end() + 1; } else if (sectionStart != -1) { sectionEnd = m.start(); @@ -1953,9 +1959,9 @@ public class JavacHandlerUtil { return applySetter(cu, node, "SETTER"); } }, - WITHER { + WITH { @Override public String apply(final JCCompilationUnit cu, final JavacNode node) { - return applySetter(cu, node, "WITHER"); + return applySetter(cu, node, "WITH|WITHER"); } }; -- cgit