diff options
author | Reinier Zwitserloot <reinier@zwitserloot.com> | 2012-07-12 02:58:26 +0200 |
---|---|---|
committer | Reinier Zwitserloot <reinier@zwitserloot.com> | 2012-07-12 02:58:26 +0200 |
commit | 3cf9ffed29cfe56734570b1c3c57d924ac7416df (patch) | |
tree | d7a9a68e89ccf4af2bf52ad4b90f0c2dc0d6de9b /src/core/lombok | |
parent | 1865bd7309b9d1dc743f83ccdbd7204fb0939ecd (diff) | |
download | lombok-3cf9ffed29cfe56734570b1c3c57d924ac7416df.tar.gz lombok-3cf9ffed29cfe56734570b1c3c57d924ac7416df.tar.bz2 lombok-3cf9ffed29cfe56734570b1c3c57d924ac7416df.zip |
Wither support + tests (javac only; ecj tests are currently set to ignore).
Diffstat (limited to 'src/core/lombok')
-rw-r--r-- | src/core/lombok/core/TransformationsUtil.java | 107 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java | 37 | ||||
-rw-r--r-- | src/core/lombok/experimental/Wither.java | 60 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleSetter.java | 23 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleWither.java | 274 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/JavacHandlerUtil.java | 62 |
6 files changed, 468 insertions, 95 deletions
diff --git a/src/core/lombok/core/TransformationsUtil.java b/src/core/lombok/core/TransformationsUtil.java index 69b6b734..921c27d6 100644 --- a/src/core/lombok/core/TransformationsUtil.java +++ b/src/core/lombok/core/TransformationsUtil.java @@ -104,20 +104,7 @@ public class TransformationsUtil { * @return The getter 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 toGetterName(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { - if (fieldName.length() == 0) return null; - - Accessors ac = accessors.getInstance(); - fieldName = removePrefix(fieldName, ac.prefix()); - if (fieldName == null) return null; - - if (ac.fluent()) return fieldName.toString(); - - if (isBoolean && fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - // The field is for example named 'isRunning'. - return fieldName.toString(); - } - - return buildName(isBoolean ? "is" : "get", fieldName.toString()); + return toAccessorName(accessors, fieldName, isBoolean, "is", "get", true); } /** @@ -141,20 +128,50 @@ public class TransformationsUtil { * @return The setter 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 toSetterName(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { + return toAccessorName(accessors, fieldName, isBoolean, "set", "set", true); + } + + /** + * Generates a wither name from a given field name. + * + * Strategy: + * <ul> + * <li>Reduce the field's name to its base name by stripping off any prefix (from {@code Accessors}). If the field name does not fit + * the prefix list, this method immediately returns {@code null}.</li> + * <li>Only if {@code isBoolean} is true: Check if the field starts with {@code is} followed by a non-lowercase character. + * If so, replace {@code is} with {@code with} and return that.</li> + * <li>Check if the first character of the field is lowercase. If so, check if the second character + * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character.</li> + * <li>Return {@code "with"} plus the possibly title/uppercased first character, and the rest of the field name.</li> + * </ul> + * + * @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. + */ + public static String toWitherName(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { + return toAccessorName(accessors, fieldName, isBoolean, "with", "with", false); + } + + private static String toAccessorName(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean, + String booleanPrefix, String normalPrefix, boolean adhereToFluent) { + if (fieldName.length() == 0) return null; + Accessors ac = accessors.getInstance(); fieldName = removePrefix(fieldName, ac.prefix()); if (fieldName == null) return null; String fName = fieldName.toString(); - if (ac.fluent()) return fName; + if (adhereToFluent && ac.fluent()) return fName; - if (isBoolean && fName.startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fName.charAt(2))) { + if (isBoolean && fName.startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { // The field is for example named 'isRunning'. - return "set" + fName.substring(2); + return booleanPrefix + fName.substring(2); } - return buildName("set", fName); + return buildName(isBoolean ? booleanPrefix : normalPrefix, fName); } /** @@ -168,28 +185,7 @@ public class TransformationsUtil { * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. */ public static List<String> toAllGetterNames(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { - if (!isBoolean) { - String getterName = toGetterName(accessors, fieldName, false); - return (getterName == null) ? Collections.<String>emptyList() : Collections.singletonList(getterName); - } - - Accessors acc = accessors.getInstance(); - fieldName = removePrefix(fieldName, acc.prefix()); - if (fieldName == null) return Collections.emptyList(); - - List<String> baseNames = toBaseNames(fieldName, isBoolean, acc.fluent()); - - Set<String> names = new HashSet<String>(); - for (String baseName : baseNames) { - if (acc.fluent()) { - names.add(baseName); - } else { - names.add(buildName("is", baseName)); - names.add(buildName("get", baseName)); - } - } - - return new ArrayList<String>(names); + return toAllAccessorNames(accessors, fieldName, isBoolean, "is", "get", true); } /** @@ -198,13 +194,34 @@ public class TransformationsUtil { * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> * {@code [setRunning, setIsRunning]} * + * @param accessors Accessors configuration. * @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<String> toAllSetterNames(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { + return toAllAccessorNames(accessors, fieldName, isBoolean, "set", "set", true); + } + + /** + * Returns all names of methods that would represent the wither for a field with the provided name. + * + * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> + * {@code [withRunning, withIsRunning]} + * + * @param accessors Accessors configuration. + * @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<String> toAllWitherNames(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { + return toAllAccessorNames(accessors, fieldName, isBoolean, "with", "with", false); + } + + private static List<String> toAllAccessorNames(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean, + String booleanPrefix, String normalPrefix, boolean adhereToFluent) { + if (!isBoolean) { - String setterName = toSetterName(accessors, fieldName, false); - return (setterName == null) ? Collections.<String>emptyList() : Collections.singletonList(setterName); + String accessorName = toAccessorName(accessors, fieldName, false, booleanPrefix, normalPrefix, adhereToFluent); + return (accessorName == null) ? Collections.<String>emptyList() : Collections.singletonList(accessorName); } Accessors acc = accessors.getInstance(); @@ -215,14 +232,16 @@ public class TransformationsUtil { Set<String> names = new HashSet<String>(); for (String baseName : baseNames) { - if (acc.fluent()) { + if (adhereToFluent && acc.fluent()) { names.add(baseName); } else { - names.add(buildName("set", baseName)); + names.add(buildName(normalPrefix, baseName)); + if (!normalPrefix.equals(booleanPrefix)) names.add(buildName(booleanPrefix, baseName)); } } return new ArrayList<String>(names); + } private static List<String> toBaseNames(CharSequence fieldName, boolean isBoolean, boolean fluent) { diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index 7120a602..f9bb18b1 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -945,10 +945,7 @@ public class EclipseHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static List<String> toAllGetterNames(EclipseNode field, boolean isBoolean) { - String fieldName = field.getName(); - AnnotationValues<Accessors> accessors = getAccessorsForField(field); - - return TransformationsUtil.toAllGetterNames(accessors, fieldName, isBoolean); + return TransformationsUtil.toAllGetterNames(getAccessorsForField(field), field.getName(), isBoolean); } /** @@ -957,10 +954,7 @@ public class EclipseHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toGetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toGetterName(EclipseNode field, boolean isBoolean) { - String fieldName = field.getName(); - AnnotationValues<Accessors> accessors = EclipseHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toGetterName(accessors, fieldName, isBoolean); + return TransformationsUtil.toGetterName(getAccessorsForField(field), field.getName(), isBoolean); } /** @@ -968,10 +962,7 @@ public class EclipseHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List<String> toAllSetterNames(EclipseNode field, boolean isBoolean) { - String fieldName = field.getName(); - AnnotationValues<Accessors> accessors = EclipseHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toAllSetterNames(accessors, fieldName, isBoolean); + return TransformationsUtil.toAllSetterNames(getAccessorsForField(field), field.getName(), isBoolean); } /** @@ -980,10 +971,24 @@ public class EclipseHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toSetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toSetterName(EclipseNode field, boolean isBoolean) { - String fieldName = field.getName(); - AnnotationValues<Accessors> accessors = EclipseHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toSetterName(accessors, fieldName, isBoolean); + return TransformationsUtil.toSetterName(getAccessorsForField(field), field.getName(), isBoolean); + } + + /** + * Translates the given field into all possible wither names. + * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. + */ + public static java.util.List<String> toAllWitherNames(EclipseNode field, boolean isBoolean) { + return TransformationsUtil.toAllWitherNames(getAccessorsForField(field), field.getName(), isBoolean); + } + + /** + * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). + * + * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. + */ + public static String toWitherName(EclipseNode field, boolean isBoolean) { + return TransformationsUtil.toWitherName(getAccessorsForField(field), field.getName(), isBoolean); } /** diff --git a/src/core/lombok/experimental/Wither.java b/src/core/lombok/experimental/Wither.java new file mode 100644 index 00000000..ec2f5496 --- /dev/null +++ b/src/core/lombok/experimental/Wither.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2012 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.experimental; + +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 'wither' - a withX method which produces a clone of this object (except for 1 field which gets a new value). + * <p> + * Example: + * <pre> + * private @Wither final int foo; + * </pre> + * + * will generate: + * + * <pre> + * public SELF_TYPE withFoo(int foo) { + * return this.foo == foo ? this : new SELF_TYPE(otherField1, otherField2, foo); + * } + * </pre> + * + * If any method named {@code withFoo} (case insensitive) exists, regardless of return type or parameters, + * no method is generated, and instead a compiler warning is emitted. + * <p> + * 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. + */ +@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.SOURCE) +public @interface Wither { + /** + * If you want your wither to be non-public, you can specify an alternate access level here. + */ + AccessLevel value() default AccessLevel.PUBLIC; +} diff --git a/src/core/lombok/javac/handlers/HandleSetter.java b/src/core/lombok/javac/handlers/HandleSetter.java index 02591736..a782e605 100644 --- a/src/core/lombok/javac/handlers/HandleSetter.java +++ b/src/core/lombok/javac/handlers/HandleSetter.java @@ -21,8 +21,8 @@ */ package lombok.javac.handlers; +import static lombok.javac.Javac.getCtcInt; import static lombok.javac.handlers.JavacHandlerUtil.*; -import static lombok.javac.Javac.*; import java.util.Collection; @@ -37,6 +37,7 @@ import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; +import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; @@ -171,6 +172,11 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { return; } + if ((fieldDecl.mods.flags & Flags.FINAL) != 0) { + source.addWarning("Not generating setter for this field: Setters cannot be generated for final fields."); + return; + } + for (String altName : toAllSetterNames(fieldNode)) { switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: @@ -224,20 +230,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { JCExpression methodType = null; if (returnThis) { - JavacNode typeNode = field; - while (typeNode != null && typeNode.getKind() != Kind.TYPE) typeNode = typeNode.up(); - if (typeNode != null && typeNode.get() instanceof JCClassDecl) { - JCClassDecl type = (JCClassDecl) typeNode.get(); - ListBuffer<JCExpression> typeArgs = ListBuffer.lb(); - if (!type.typarams.isEmpty()) { - for (JCTypeParameter tp : type.typarams) { - typeArgs.append(treeMaker.Ident(tp.name)); - } - methodType = treeMaker.TypeApply(treeMaker.Ident(type.name), typeArgs.toList()); - } else { - methodType = treeMaker.Ident(type.name); - } - } + methodType = cloneSelfType(field); } if (methodType == null) { diff --git a/src/core/lombok/javac/handlers/HandleWither.java b/src/core/lombok/javac/handlers/HandleWither.java new file mode 100644 index 00000000..61bf7bd0 --- /dev/null +++ b/src/core/lombok/javac/handlers/HandleWither.java @@ -0,0 +1,274 @@ +/* + * Copyright (C) 2012 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.Javac.getCtcInt; +import static lombok.javac.handlers.JavacHandlerUtil.*; + +import java.util.Collection; + +import lombok.AccessLevel; +import lombok.core.AST.Kind; +import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; +import lombok.experimental.Wither; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; + +import org.mangosdk.spi.ProviderFor; + +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +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.tree.TreeMaker; +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<Wither> { + public void generateWitherForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelWither) { + if (checkForTypeLevelWither) { + if (typeNode != null) for (JavacNode child : typeNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (annotationTypeMatches(Wither.class, child)) { + //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) { + for (JavacNode 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; + } + } + } + + createWitherForField(level, fieldNode, fieldNode, false); + } + + @Override public void handle(AnnotationValues<Wither> annotation, JCAnnotation ast, JavacNode annotationNode) { + Collection<JavacNode> 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; + + switch (node.getKind()) { + case FIELD: + createWitherForFields(level, fields, annotationNode, true); + break; + case TYPE: + generateWitherForType(node, annotationNode, level, false); + break; + } + } + + private void createWitherForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists) { + for (JavacNode fieldNode : fieldNodes) { + createWitherForField(level, fieldNode, errorNode, whineIfExists); + } + } + + private void createWitherForField(AccessLevel level, + JavacNode fieldNode, JavacNode source, boolean whineIfExists) { + + 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) { + source.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); + return; + } + + if ((fieldDecl.mods.flags & Flags.STATIC) != 0) { + source.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) { + source.addWarning("Not generating wither for this field: Withers cannot be generated for final, initialized fields."); + return; + } + + if (fieldDecl.name.toString().startsWith("$")) { + source.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 (whineIfExists) { + String altNameExpl = ""; + if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); + source.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.get()); + injectMethod(fieldNode.up(), createdWither); + } + + private JCMethodDecl createWither(long access, JavacNode field, TreeMaker treeMaker, JCTree source) { + String witherName = toWitherName(field); + if (witherName == null) return null; + + JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); + + ListBuffer<JCStatement> statements = ListBuffer.lb(); + List<JCAnnotation> nonNulls = findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN); + List<JCAnnotation> nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); + + Name methodName = field.toName(witherName); + List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); + + JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); + + JCExpression selfType = cloneSelfType(field); + if (selfType == null) return null; + + TreeMaker maker = field.getTreeMaker(); + + ListBuffer<JCExpression> args = ListBuffer.lb(); + 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.<JCExpression>nil(), selfType, args.toList(), null); + JCExpression identityCheck = maker.Binary(getCtcInt(JCTree.class, "EQ"), 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 (nonNulls.isEmpty()) { + statements.append(returnStatement); + } else { + JCStatement nullCheck = generateNullCheck(treeMaker, field); + if (nullCheck != null) statements.append(nullCheck); + statements.append(returnStatement); + } + + JCExpression returnType = cloneSelfType(field); + + JCBlock methodBody = treeMaker.Block(0, statements.toList()); + List<JCTypeParameter> methodGenericParams = List.nil(); + List<JCVariableDecl> parameters = List.of(param); + List<JCExpression> throwsClauses = List.nil(); + JCExpression annotationMethodDefaultValue = null; + + List<JCAnnotation> annsOnMethod = List.nil(); + if (isFieldDeprecated(field)) { + annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil())); + } + return recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, returnType, + methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source); + } +} diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index 437ba6cb..f2cdee6d 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -61,6 +61,7 @@ import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; 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.tree.TreeMaker; import com.sun.tools.javac.tree.TreeScanner; @@ -307,11 +308,7 @@ public class JavacHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List<String> toAllGetterNames(JavacNode field) { - String fieldName = field.getName(); - boolean isBoolean = isBoolean(field); - AnnotationValues<Accessors> accessors = JavacHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toAllGetterNames(accessors, fieldName, isBoolean); + return TransformationsUtil.toAllGetterNames(getAccessorsForField(field), field.getName(), isBoolean(field)); } /** @@ -320,11 +317,7 @@ public class JavacHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toGetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toGetterName(JavacNode field) { - String fieldName = field.getName(); - boolean isBoolean = isBoolean(field); - AnnotationValues<Accessors> accessors = JavacHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toGetterName(accessors, fieldName, isBoolean); + return TransformationsUtil.toGetterName(getAccessorsForField(field), field.getName(), isBoolean(field)); } /** @@ -332,11 +325,7 @@ public class JavacHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static java.util.List<String> toAllSetterNames(JavacNode field) { - String fieldName = field.getName(); - boolean isBoolean = isBoolean(field); - AnnotationValues<Accessors> accessors = JavacHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toAllSetterNames(accessors, fieldName, isBoolean); + return TransformationsUtil.toAllSetterNames(getAccessorsForField(field), field.getName(), isBoolean(field)); } /** @@ -345,11 +334,24 @@ public class JavacHandlerUtil { * Convenient wrapper around {@link TransformationsUtil#toSetterName(lombok.core.AnnotationValues, CharSequence, boolean)}. */ public static String toSetterName(JavacNode field) { - String fieldName = field.getName(); - boolean isBoolean = isBoolean(field); - AnnotationValues<Accessors> accessors = JavacHandlerUtil.getAccessorsForField(field); - - return TransformationsUtil.toSetterName(accessors, fieldName, isBoolean); + return TransformationsUtil.toSetterName(getAccessorsForField(field), field.getName(), isBoolean(field)); + } + + /** + * Translates the given field into all possible wither names. + * Convenient wrapper around {@link TransformationsUtil#toAllWitherNames(lombok.core.AnnotationValues, CharSequence, boolean)}. + */ + public static java.util.List<String> toAllWitherNames(JavacNode field) { + return TransformationsUtil.toAllWitherNames(getAccessorsForField(field), field.getName(), isBoolean(field)); + } + + /** + * @return the likely wither name for the stated field. (e.g. private boolean foo; to withFoo). + * + * Convenient wrapper around {@link TransformationsUtil#toWitherName(lombok.core.AnnotationValues, CharSequence, boolean)}. + */ + public static String toWitherName(JavacNode field) { + return TransformationsUtil.toWitherName(getAccessorsForField(field), field.getName(), isBoolean(field)); } /** @@ -366,6 +368,26 @@ public class JavacHandlerUtil { return instance.chain() || (instance.fluent() && !forced); } + public static JCExpression cloneSelfType(JavacNode field) { + JavacNode typeNode = field; + TreeMaker maker = field.getTreeMaker(); + while (typeNode != null && typeNode.getKind() != Kind.TYPE) typeNode = typeNode.up(); + if (typeNode != null && typeNode.get() instanceof JCClassDecl) { + JCClassDecl type = (JCClassDecl) typeNode.get(); + ListBuffer<JCExpression> typeArgs = ListBuffer.lb(); + if (!type.typarams.isEmpty()) { + for (JCTypeParameter tp : type.typarams) { + typeArgs.append(maker.Ident(tp.name)); + } + return maker.TypeApply(maker.Ident(type.name), typeArgs.toList()); + } else { + return maker.Ident(type.name); + } + } else { + return null; + } + } + private static boolean isBoolean(JavacNode field) { JCExpression varType = ((JCVariableDecl) field.get()).vartype; return varType != null && varType.toString().equals("boolean"); |