diff options
Diffstat (limited to 'src/core')
-rw-r--r-- | src/core/lombok/core/TransformationsUtil.java | 107 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java | 62 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleSetter.java | 25 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleWither.java | 271 | ||||
-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 |
8 files changed, 768 insertions, 116 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 ae488612..ed18dd45 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -476,6 +476,31 @@ public class EclipseHandlerUtil { return typeMatches(type, node, ((Annotation)node.get()).type); } + public static TypeReference cloneSelfType(EclipseNode context, ASTNode source) { + int pS = source.sourceStart, pE = source.sourceEnd; + long p = (long)pS << 32 | pE; + EclipseNode type = context; + TypeReference result = null; + while (type != null && type.getKind() != Kind.TYPE) type = type.up(); + if (type != null && type.get() instanceof TypeDeclaration) { + TypeDeclaration typeDecl = (TypeDeclaration) type.get(); + if (typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0) { + TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; + int idx = 0; + for (TypeParameter param : typeDecl.typeParameters) { + TypeReference typeRef = new SingleTypeReference(param.name, (long)param.sourceStart << 32 | param.sourceEnd); + setGeneratedBy(typeRef, source); + refs[idx++] = typeRef; + } + result = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); + } else { + result = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); + } + } + if (result != null) setGeneratedBy(result, source); + return result; + } + public static TypeReference makeType(TypeBinding binding, ASTNode pos, boolean allowCompound) { int dims = binding.dimensions(); binding = binding.leafComponentType(); @@ -946,10 +971,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); } /** @@ -958,10 +980,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); } /** @@ -969,10 +988,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); } /** @@ -981,10 +997,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/eclipse/handlers/HandleSetter.java b/src/core/lombok/eclipse/handlers/HandleSetter.java index 996ac14a..0bce69d6 100644 --- a/src/core/lombok/eclipse/handlers/HandleSetter.java +++ b/src/core/lombok/eclipse/handlers/HandleSetter.java @@ -46,14 +46,11 @@ 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.NameReference; -import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; -import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; @@ -183,11 +180,11 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { } } - MethodDeclaration method = generateSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, source); + MethodDeclaration method = createSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, source); injectMethod(fieldNode.up(), method); } - private MethodDeclaration generateSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, ASTNode source) { + private MethodDeclaration createSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, ASTNode source) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; @@ -195,29 +192,15 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { setGeneratedBy(method, source); method.modifiers = modifier; if (shouldReturnThis) { - EclipseNode type = fieldNode; - while (type != null && type.getKind() != Kind.TYPE) type = type.up(); - if (type != null && type.get() instanceof TypeDeclaration) { - TypeDeclaration typeDecl = (TypeDeclaration) type.get(); - if (typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0) { - TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; - int idx = 0; - for (TypeParameter param : typeDecl.typeParameters) { - TypeReference typeRef = new SingleTypeReference(param.name, (long)param.sourceStart << 32 | param.sourceEnd); - setGeneratedBy(typeRef, source); - refs[idx++] = typeRef; - } - method.returnType = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); - } else method.returnType = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); - } + method.returnType = cloneSelfType(fieldNode, source); } if (method.returnType == null) { method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; + setGeneratedBy(method.returnType, source); shouldReturnThis = false; } - setGeneratedBy(method.returnType, source); if (isFieldDeprecated(fieldNode)) { method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; } diff --git a/src/core/lombok/eclipse/handlers/HandleWither.java b/src/core/lombok/eclipse/handlers/HandleWither.java new file mode 100644 index 00000000..90253ade --- /dev/null +++ b/src/core/lombok/eclipse/handlers/HandleWither.java @@ -0,0 +1,271 @@ +/* + * 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.eclipse.handlers; + +import static lombok.eclipse.Eclipse.*; +import static lombok.eclipse.handlers.EclipseHandlerUtil.*; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import lombok.AccessLevel; +import lombok.core.AST.Kind; +import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; +import lombok.eclipse.EclipseAnnotationHandler; +import lombok.eclipse.EclipseNode; +import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; +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.mangosdk.spi.ProviderFor; + +@ProviderFor(EclipseAnnotationHandler.class) +public class HandleWither extends EclipseAnnotationHandler<Wither> { + public boolean generateWitherForType(EclipseNode typeNode, EclipseNode pos, AccessLevel level, boolean checkForTypeLevelWither) { + if (checkForTypeLevelWither) { + if (typeNode != null) for (EclipseNode 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 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.get(), 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, ASTNode pos, 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; + } + } + } + + createWitherForField(level, fieldNode, fieldNode, pos, false); + } + + @Override public void handle(AnnotationValues<Wither> annotation, Annotation ast, EclipseNode annotationNode) { + EclipseNode node = annotationNode.up(); + AccessLevel level = annotation.getInstance().value(); + if (level == AccessLevel.NONE || node == null) return; + + switch (node.getKind()) { + case FIELD: + createWitherForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true); + break; + case TYPE: + generateWitherForType(node, annotationNode, level, false); + break; + } + } + + private void createWitherForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + for (EclipseNode fieldNode : fieldNodes) { + createWitherForField(level, fieldNode, errorNode, source, whineIfExists); + } + } + + private void createWitherForField(AccessLevel level, + EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + if (fieldNode.getKind() != Kind.FIELD) { + errorNode.addError("@Wither is only supported on a class or a field."); + return; + } + + FieldDeclaration field = (FieldDeclaration) fieldNode.get(); + TypeReference fieldType = copyType(field.type, source); + boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; + String witherName = toWitherName(fieldNode, isBoolean); + + if (witherName == null) { + errorNode.addWarning("Not generating wither for this field: It does not fit your @Accessors prefix list."); + return; + } + + if ((field.modifiers & ClassFileConstants.AccStatic) != 0) { + errorNode.addWarning("Not generating wither for this field: Withers cannot be generated for static fields."); + return; + } + + if ((field.modifiers & ClassFileConstants.AccFinal) != 0 && field.initialization != null) { + errorNode.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] == '$') { + errorNode.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); + errorNode.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, source); + injectMethod(fieldNode.up(), method); + } + + private MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source) { + 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); + method.modifiers = modifier; + method.returnType = cloneSelfType(fieldNode, source); + if (method.returnType == null) return null; + + if (isFieldDeprecated(fieldNode)) { + method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; + } + Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL); + 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; + + List<Expression> args = new ArrayList<Expression>(); + 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.toString().startsWith("$")) 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( + new SingleNameReference(field.name, p), + createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source), + 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; + + Annotation[] nonNulls = findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN); + Annotation[] nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); + List<Statement> statements = new ArrayList<Statement>(5); + if (nonNulls.length > 0) { + Statement nullCheck = generateNullCheck(field, source); + if (nullCheck != null) statements.add(nullCheck); + } + statements.add(returnStatement); + + method.statements = statements.toArray(new Statement[0]); + + Annotation[] copiedAnnotations = copyAnnotations(source, nonNulls, nullables); + if (copiedAnnotations.length != 0) param.annotations = copiedAnnotations; + 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 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 fcafb88e..b0f2a890 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -65,6 +65,7 @@ import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; @@ -316,11 +317,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)); } /** @@ -329,11 +326,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)); } /** @@ -341,11 +334,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)); } /** @@ -354,11 +343,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)); } /** @@ -375,6 +377,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"); |