diff options
Diffstat (limited to 'src/core')
-rw-r--r-- | src/core/lombok/core/AnnotationValues.java | 20 | ||||
-rw-r--r-- | src/core/lombok/core/TransformationsUtil.java | 263 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java | 112 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java | 6 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleGetter.java | 12 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleSetter.java | 67 | ||||
-rw-r--r-- | src/core/lombok/eclipse/handlers/HandleToString.java | 2 | ||||
-rw-r--r-- | src/core/lombok/experimental/Accessors.java | 56 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleAccessors.java | 42 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java | 6 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleGetter.java | 13 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleSetter.java | 69 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/HandleToString.java | 2 | ||||
-rw-r--r-- | src/core/lombok/javac/handlers/JavacHandlerUtil.java | 126 |
14 files changed, 736 insertions, 60 deletions
diff --git a/src/core/lombok/core/AnnotationValues.java b/src/core/lombok/core/AnnotationValues.java index 64111dae..df056dd4 100644 --- a/src/core/lombok/core/AnnotationValues.java +++ b/src/core/lombok/core/AnnotationValues.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009 The Project Lombok Authors. + * Copyright (C) 2009-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 @@ -118,6 +118,18 @@ public class AnnotationValues<A extends Annotation> { this.ast = ast; } + public static <A extends Annotation> AnnotationValues<A> of(Class<A> type) { + return new AnnotationValues<A>(type, Collections.<String, AnnotationValue>emptyMap(), null); + } + + /** + * Creates a new annotation wrapper with all default values, and using the provided ast as lookup anchor for + * class literals. + */ + public static <A extends Annotation> AnnotationValues<A> of(Class<A> type, LombokNode<?, ?, ?> ast) { + return new AnnotationValues<A>(type, Collections.<String, AnnotationValue>emptyMap(), ast); + } + /** * Thrown on the fly if an actual annotation instance procured via the {@link #getInstance()} method is queried * for a method for which this AnnotationValues instance either doesn't have a guess or can't manage to fit @@ -423,7 +435,7 @@ public class AnnotationValues<A extends Annotation> { } /* 2. Walk through non-star imports and search for a match. */ { - for (String im : ast.getImportStatements()) { + for (String im : ast == null ? Collections.<String>emptyList() : ast.getImportStatements()) { if (im.endsWith(".*")) continue; int idx = im.lastIndexOf('.'); String simple = idx == -1 ? im : im.substring(idx+1); @@ -434,7 +446,7 @@ public class AnnotationValues<A extends Annotation> { } /* 3. Walk through star imports and, if they start with "java.", use Class.forName based resolution. */ { - List<String> imports = new ArrayList<String>(ast.getImportStatements()); + List<String> imports = ast == null ? Collections.<String>emptyList() : new ArrayList<String>(ast.getImportStatements()); imports.add("java.lang.*"); for (String im : imports) { if (!im.endsWith(".*") || !im.startsWith("java.")) continue; @@ -465,7 +477,7 @@ public class AnnotationValues<A extends Annotation> { private static String inLocalPackage(LombokNode<?, ?, ?> node, String typeName) { StringBuilder result = new StringBuilder(); - if (node.getPackageDeclaration() != null) result.append(node.getPackageDeclaration()); + if (node != null && node.getPackageDeclaration() != null) result.append(node.getPackageDeclaration()); if (result.length() > 0) result.append('.'); result.append(typeName); return result.toString(); diff --git a/src/core/lombok/core/TransformationsUtil.java b/src/core/lombok/core/TransformationsUtil.java new file mode 100644 index 00000000..60d9bab0 --- /dev/null +++ b/src/core/lombok/core/TransformationsUtil.java @@ -0,0 +1,263 @@ +/* + * Copyright (C) 2009-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.core; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +import lombok.experimental.Accessors; + +/** + * Container for static utility methods useful for some of the standard lombok transformations, regardless of + * target platform (e.g. useful for both javac and Eclipse lombok implementations). + */ +public class TransformationsUtil { + private TransformationsUtil() { + //Prevent instantiation + } + + /** + * Given the name of a field, return the 'base name' of that field. For example, {@code fFoobar} becomes {@code foobar} if {@code f} is in the prefix list. + * For prefixes that end in a letter character, the next character must be a non-lowercase character (i.e. {@code hashCode} is not {@code ashCode} even if + * {@code h} is in the prefix list, but {@code hAshcode} would become {@code ashCode}). The first prefix that matches is used. If the prefix list is empty, + * or the empty string is in the prefix list and no prefix before it matches, the fieldName will be returned verbatim. + * + * If no prefix matches and the empty string is not in the prefix list and the prefix list is not empty, {@code null} is returned. + * + * @param fieldName The full name of a field. + * @param prefixes A list of prefixes, usually provided by the {@code Accessors} settings annotation, listing field prefixes. + * @return The base name of the field. + */ + private static CharSequence removePrefix(CharSequence fieldName, String[] prefixes) { + if (prefixes == null || prefixes.length == 0) return fieldName; + + outer: + for (String prefix : prefixes) { + if (prefix.length() == 0) return fieldName; + if (fieldName.length() <= prefix.length()) continue outer; + for (int i = 0; i < prefix.length(); i++) { + if (fieldName.charAt(i) != prefix.charAt(i)) continue outer; + } + char followupChar = fieldName.charAt(prefix.length()); + // if prefix is a letter then follow up letter needs to not be lowercase, i.e. 'foo' is not a match + // as field named 'oo' with prefix 'f', but 'fOo' would be. + if (Character.isLetter(prefix.charAt(prefix.length() - 1)) && + Character.isLowerCase(followupChar)) continue outer; + return "" + Character.toLowerCase(followupChar) + fieldName.subSequence(prefix.length() + 1, fieldName.length()); + } + + return null; + } + + /** Matches any of the 8 primitive names, such as {@code boolean}. */ + public static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile( + "^(boolean|byte|short|int|long|float|double|char)$"); + + /* NB: 'notnull' is not part of the pattern because there are lots of @NotNull annotations out there that are crappily named and actually mean + something else, such as 'this field must not be null _when saved to the db_ but its perfectly okay to start out as such, and a no-args + constructor and the implied starts-out-as-null state that goes with it is in fact mandatory' which happens with javax.validation.constraints.NotNull. + Various problems with spring have also been reported. See issue #287, issue #271, and issue #43. */ + + /** Matches the simple part of any annotation that lombok considers as indicative of NonNull status. */ + public static final Pattern NON_NULL_PATTERN = Pattern.compile("^(?:nonnull)$", Pattern.CASE_INSENSITIVE); + + /** Matches the simple part of any annotation that lombok considers as indicative of Nullable status. */ + public static final Pattern NULLABLE_PATTERN = Pattern.compile("^(?:nullable|checkfornull)$", Pattern.CASE_INSENSITIVE); + + /** + * Generates a getter 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 {@null}.</li> + * <li>If {@code Accessors} has {@code fluent=true}, then return the basename.</li> + * <li>Pick a prefix. 'get' normally, but 'is' if {@code isBoolean} is true.</li> + * <li>Only if {@code isBoolean} is true: Check if the field starts with {@code is} followed by a non-lowercase character. If so, return the field name verbatim.</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 the prefix 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 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()); + } + + /** + * Generates a setter 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 {@null}.</li> + * <li>If {@code Accessors} has {@code fluent=true}, then return the basename.</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 set} 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 "set"} 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 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) { + 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 (isBoolean && fName.startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fName.charAt(2))) { + // The field is for example named 'isRunning'. + return "set" + fName.substring(2); + } + + return buildName("set", fName); + } + + /** + * Returns all names of methods that would represent the getter for a field with the provided name. + * + * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> + * {@code [isRunning, getRunning, isIsRunning, getIsRunning]} + * + * @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> toAllGetterNames(AnnotationValues<Accessors> accessors, CharSequence fieldName, boolean isBoolean) { + if (!isBoolean) return Collections.singletonList(toGetterName(accessors, fieldName, false)); + + 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); + } + + /** + * Returns all names of methods that would represent the setter for a field with the provided name. + * + * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> + * {@code [setRunning, setIsRunning]} + * + * @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) { + if (!isBoolean) return Collections.singletonList(toSetterName(accessors, fieldName, false)); + + 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("set", baseName)); + } + } + + return new ArrayList<String>(names); + } + + private static List<String> toBaseNames(CharSequence fieldName, boolean isBoolean, boolean fluent) { + List<String> baseNames = new ArrayList<String>(); + baseNames.add(fieldName.toString()); + + // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. + String fName = fieldName.toString(); + if (fName.startsWith("is") && fName.length() > 2 && !Character.isLowerCase(fName.charAt(2))) { + String baseName = fName.substring(2); + if (fluent) { + baseNames.add("" + Character.toLowerCase(baseName.charAt(0)) + baseName.substring(1)); + } else { + baseNames.add(baseName); + } + } + + return baseNames; + } + + /** + * @param prefix Something like {@code get} or {@code set} or {@code is}. + * @param suffix Something like {@code running}. + * @return prefix + smartly title-cased suffix. For example, {@code setRunning}. + */ + private static String buildName(String prefix, String suffix) { + if (suffix.length() == 0) return prefix; + if (prefix.length() == 0) return suffix; + + char first = suffix.charAt(0); + if (Character.isLowerCase(first)) { + boolean useUpperCase = suffix.length() > 2 && + (Character.isTitleCase(suffix.charAt(1)) || Character.isUpperCase(suffix.charAt(1))); + suffix = String.format("%s%s", + useUpperCase ? Character.toUpperCase(first) : Character.toTitleCase(first), + suffix.subSequence(1, suffix.length())); + } + return String.format("%s%s", prefix, suffix); + } +} diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index 67a2d07c..a056c396 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -41,11 +41,12 @@ import lombok.Data; import lombok.Getter; import lombok.Lombok; import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.core.AnnotationValues.AnnotationValue; import lombok.eclipse.EclipseAST; import lombok.eclipse.EclipseNode; -import lombok.core.TransformationsUtil; +import lombok.experimental.Accessors; import lombok.core.TypeResolver; import org.eclipse.core.runtime.ILog; @@ -777,7 +778,7 @@ public class EclipseHandlerUtil { TypeReference fieldType = ((FieldDeclaration)field.get()).type; boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; EclipseNode typeNode = field.up(); - for (String potentialGetterName : TransformationsUtil.toAllGetterNames(field.getName(), isBoolean)) { + for (String potentialGetterName : toAllGetterNames(field, isBoolean)) { for (EclipseNode potentialGetter : typeNode.down()) { if (potentialGetter.getKind() != Kind.METHOD) continue; if (!(potentialGetter.get() instanceof MethodDeclaration)) continue; @@ -820,7 +821,8 @@ public class EclipseHandlerUtil { } if (hasGetterAnnotation) { - String getterName = TransformationsUtil.toGetterName(field.getName(), isBoolean); + String getterName = toGetterName(field, isBoolean); + if (getterName == null) return null; return new GetterMethod(getterName.toCharArray(), fieldType); } @@ -930,6 +932,64 @@ public class EclipseHandlerUtil { } /** + * Translates the given field into all possible getter names. + * 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 the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). + * + * 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); + } + + /** + * Translates the given field into all possible setter names. + * 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 the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). + * + * 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); + } + + /** + * When generating a setter, the setter either returns void (beanspec) or Self (fluent). + * This method scans for the {@code Accessors} annotation to figure that out. + */ + public static boolean shouldReturnThis(EclipseNode field) { + if ((((FieldDeclaration) field.get()).modifiers & ClassFileConstants.AccStatic) != 0) return false; + AnnotationValues<Accessors> accessors = EclipseHandlerUtil.getAccessorsForField(field); + boolean forced = (accessors.getActualExpression("chain") != null); + Accessors instance = accessors.getInstance(); + return instance.chain() || (instance.fluent() && !forced); + } + + /** * Checks if the field should be included in operations that work on 'all' fields: * If the field is static, or starts with a '$', or is actually an enum constant, 'false' is returned, indicating you should skip it. */ @@ -949,6 +1009,26 @@ public class EclipseHandlerUtil { return true; } + public static AnnotationValues<Accessors> getAccessorsForField(EclipseNode field) { + for (EclipseNode node : field.down()) { + if (annotationTypeMatches(Accessors.class, node)) { + return createAnnotation(Accessors.class, node); + } + } + + EclipseNode current = field.up(); + while (current != null) { + for (EclipseNode node : current.down()) { + if (annotationTypeMatches(Accessors.class, node)) { + return createAnnotation(Accessors.class, node); + } + } + current = current.up(); + } + + return AnnotationValues.of(Accessors.class, field); + } + /** * Checks if there is a field with the provided name. * @@ -977,8 +1057,8 @@ public class EclipseHandlerUtil { /** * Wrapper for {@link #methodExists(String, EclipseNode, boolean)} with {@code caseSensitive} = {@code true}. */ - public static MemberExistsResult methodExists(String methodName, EclipseNode node) { - return methodExists(methodName, node, true); + public static MemberExistsResult methodExists(String methodName, EclipseNode node, int params) { + return methodExists(methodName, node, true, params); } /** @@ -988,8 +1068,9 @@ public class EclipseHandlerUtil { * @param methodName the method name to check for. * @param node Any node that represents the Type (TypeDeclaration) to look in, or any child node thereof. * @param caseSensitive If the search should be case sensitive. + * @param params The number of parameters the method should have; varargs count as 0-*. Set to -1 to find any method with the appropriate name regardless of parameter count. */ - public static MemberExistsResult methodExists(String methodName, EclipseNode node, boolean caseSensitive) { + public static MemberExistsResult methodExists(String methodName, EclipseNode node, boolean caseSensitive, int params) { while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } @@ -1001,7 +1082,24 @@ public class EclipseHandlerUtil { char[] mName = def.selector; if (mName == null) continue; boolean nameEquals = caseSensitive ? methodName.equals(new String(mName)) : methodName.equalsIgnoreCase(new String(mName)); - if (nameEquals) return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + if (nameEquals) { + if (params > -1) { + int minArgs = 0; + int maxArgs = 0; + if (def.arguments != null && def.arguments.length > 0) { + minArgs = def.arguments.length; + if ((def.arguments[def.arguments.length - 1].type.bits & ASTNode.IsVarArgs) != 0) { + minArgs--; + maxArgs = Integer.MAX_VALUE; + } else { + maxArgs = minArgs; + } + } + + if (params < minArgs || params > maxArgs) continue; + } + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + } } } } diff --git a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java index ef01835c..82a8f00e 100644 --- a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java @@ -204,9 +204,9 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH boolean isFinal = (typeDecl.modifiers & ClassFileConstants.AccFinal) != 0; boolean needsCanEqual = !isDirectDescendantOfObject || !isFinal; java.util.List<MemberExistsResult> existsResults = new ArrayList<MemberExistsResult>(); - existsResults.add(methodExists("equals", typeNode)); - existsResults.add(methodExists("hashCode", typeNode)); - existsResults.add(methodExists("canEqual", typeNode)); + existsResults.add(methodExists("equals", typeNode, 1)); + existsResults.add(methodExists("hashCode", typeNode, 0)); + existsResults.add(methodExists("canEqual", typeNode, 1)); switch (Collections.max(existsResults)) { case EXISTS_BY_LOMBOK: return; diff --git a/src/core/lombok/eclipse/handlers/HandleGetter.java b/src/core/lombok/eclipse/handlers/HandleGetter.java index 3bdba74e..d53bf89b 100644 --- a/src/core/lombok/eclipse/handlers/HandleGetter.java +++ b/src/core/lombok/eclipse/handlers/HandleGetter.java @@ -187,14 +187,18 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { } TypeReference fieldType = copyType(field.type, source); - String fieldName = new String(field.name); boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; - String getterName = TransformationsUtil.toGetterName(fieldName, isBoolean); + String getterName = toGetterName(fieldNode, isBoolean); + + if (getterName == null) { + errorNode.addWarning("Not generating getter for this field: It does not fit your @Accessors prefix list."); + return; + } int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); - for (String altName : TransformationsUtil.toAllGetterNames(fieldName, isBoolean)) { - switch (methodExists(altName, fieldNode, false)) { + for (String altName : toAllGetterNames(fieldNode, isBoolean)) { + switch (methodExists(altName, fieldNode, false, 0)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: diff --git a/src/core/lombok/eclipse/handlers/HandleSetter.java b/src/core/lombok/eclipse/handlers/HandleSetter.java index 8599fca7..996ac14a 100644 --- a/src/core/lombok/eclipse/handlers/HandleSetter.java +++ b/src/core/lombok/eclipse/handlers/HandleSetter.java @@ -25,15 +25,18 @@ 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.Setter; +import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; -import lombok.core.AST.Kind; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; +import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -43,9 +46,14 @@ 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; @@ -148,12 +156,17 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); TypeReference fieldType = copyType(field.type, source); boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; - String setterName = TransformationsUtil.toSetterName(new String(field.name), isBoolean); + String setterName = toSetterName(fieldNode, isBoolean); + boolean shouldReturnThis = shouldReturnThis(fieldNode); + if (setterName == null) { + errorNode.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list."); + return; + } int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); - for (String altName : TransformationsUtil.toAllSetterNames(new String(field.name), isBoolean)) { - switch (methodExists(altName, fieldNode, false)) { + for (String altName : toAllSetterNames(fieldNode, isBoolean)) { + switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: @@ -170,19 +183,40 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { } } - MethodDeclaration method = generateSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, modifier, source); + MethodDeclaration method = generateSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, source); injectMethod(fieldNode.up(), method); } - private MethodDeclaration generateSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source) { + private MethodDeclaration generateSetter(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; MethodDeclaration method = new MethodDeclaration(parent.compilationResult); setGeneratedBy(method, source); method.modifiers = modifier; - method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); - method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; + 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); + } + } + + if (method.returnType == null) { + method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); + method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; + shouldReturnThis = false; + } setGeneratedBy(method.returnType, source); if (isFieldDeprecated(fieldNode)) { method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; @@ -207,13 +241,24 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { 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) { - method.statements = new Statement[] { assignment }; + statements.add(assignment); } else { Statement nullCheck = generateNullCheck(field, source); - if (nullCheck != null) method.statements = new Statement[] { nullCheck, assignment }; - else method.statements = new Statement[] { assignment }; + if (nullCheck != null) statements.add(nullCheck); + statements.add(assignment); } + + if (shouldReturnThis) { + ThisReference thisRef = new ThisReference(pS, pE); + setGeneratedBy(thisRef, source); + ReturnStatement returnThis = new ReturnStatement(thisRef, pS, pE); + setGeneratedBy(returnThis, source); + statements.add(returnThis); + } + method.statements = statements.toArray(new Statement[0]); + Annotation[] copiedAnnotations = copyAnnotations(source, nonNulls, nullables); if (copiedAnnotations.length != 0) param.annotations = copiedAnnotations; return method; diff --git a/src/core/lombok/eclipse/handlers/HandleToString.java b/src/core/lombok/eclipse/handlers/HandleToString.java index 07d88f5f..26f0e9be 100644 --- a/src/core/lombok/eclipse/handlers/HandleToString.java +++ b/src/core/lombok/eclipse/handlers/HandleToString.java @@ -159,7 +159,7 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { } } - switch (methodExists("toString", typeNode)) { + switch (methodExists("toString", typeNode, 0)) { case NOT_EXISTS: MethodDeclaration toString = createToString(typeNode, nodesForToString, includeFieldNames, callSuper, errorNode.get(), fieldAccess); injectMethod(typeNode, toString); diff --git a/src/core/lombok/experimental/Accessors.java b/src/core/lombok/experimental/Accessors.java new file mode 100644 index 00000000..5b454273 --- /dev/null +++ b/src/core/lombok/experimental/Accessors.java @@ -0,0 +1,56 @@ +/* + * 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; + +/** + * A container for settings for the generation of getters and setters. + * Using this annotation does nothing by itself; an annotation that makes lombok generate getters and setters, + * such as {@link lombok.Setter} or {@link lombok.Data} is also required. + */ +@Target({ElementType.TYPE, ElementType.FIELD}) +@Retention(RetentionPolicy.SOURCE) +public @interface Accessors { + /** + * If true, accessors will be named after the field and not include a <code>get</code> or <code>set</code> + * prefix. If true and <code>chain</code> is omitted, <code>chain</code> defaults to <code>true</code>. + * <strong>default: false</strong> + */ + boolean fluent() default false; + + /** + * If true, setters return <code>this</code> instead of <code>void</code>. + * <strong>default: false</strong>, unless <code>fluent=true</code>, then <strong>default: true</code> + */ + boolean chain() default false; + + /** + * If present, only fields with any of the stated prefixes are given the getter/setter treatment. + * Note that a prefix only counts if the next character is NOT a lowercase character. If multiple fields + * all turn into the same name when the prefix is stripped, an error will be generated. + */ + String[] prefix() default {}; +} diff --git a/src/core/lombok/javac/handlers/HandleAccessors.java b/src/core/lombok/javac/handlers/HandleAccessors.java new file mode 100644 index 00000000..f642d64d --- /dev/null +++ b/src/core/lombok/javac/handlers/HandleAccessors.java @@ -0,0 +1,42 @@ +/* + * 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.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; + +import org.mangosdk.spi.ProviderFor; + +import com.sun.tools.javac.tree.JCTree.JCAnnotation; + +import lombok.core.AnnotationValues; +import lombok.experimental.Accessors; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; + +@ProviderFor(JavacAnnotationHandler.class) +public class HandleAccessors extends JavacAnnotationHandler<Accessors> { + @Override public void handle(AnnotationValues<Accessors> annotation, JCAnnotation ast, JavacNode annotationNode) { + // Accessors itself is handled by HandleGetter/Setter; this is just to ensure that the annotation is removed + // from the AST when delomboking. + deleteAnnotationIfNeccessary(annotationNode, Accessors.class); + } +} diff --git a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java index 0a9d4cc2..00601b56 100644 --- a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java @@ -177,9 +177,9 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas boolean isFinal = (((JCClassDecl)typeNode.get()).mods.flags & Flags.FINAL) != 0; boolean needsCanEqual = !isFinal || !isDirectDescendantOfObject; java.util.List<MemberExistsResult> existsResults = new ArrayList<MemberExistsResult>(); - existsResults.add(methodExists("equals", typeNode)); - existsResults.add(methodExists("hashCode", typeNode)); - existsResults.add(methodExists("canEqual", typeNode)); + existsResults.add(methodExists("equals", typeNode, 1)); + existsResults.add(methodExists("hashCode", typeNode, 0)); + existsResults.add(methodExists("canEqual", typeNode, 1)); switch (Collections.max(existsResults)) { case EXISTS_BY_LOMBOK: return; diff --git a/src/core/lombok/javac/handlers/HandleGetter.java b/src/core/lombok/javac/handlers/HandleGetter.java index b3421f86..dd0a99ad 100644 --- a/src/core/lombok/javac/handlers/HandleGetter.java +++ b/src/core/lombok/javac/handlers/HandleGetter.java @@ -188,10 +188,15 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { } } - String methodName = toGetterName(fieldDecl); + String methodName = toGetterName(fieldNode); - for (String altName : toAllGetterNames(fieldDecl)) { - switch (methodExists(altName, fieldNode, false)) { + if (methodName == null) { + source.addWarning("Not generating getter for this field: It does not fit your @Accessors prefix list."); + return; + } + + for (String altName : toAllGetterNames(fieldNode)) { + switch (methodExists(altName, fieldNode, false, 0)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: @@ -229,7 +234,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { } JCBlock methodBody = treeMaker.Block(0, statements); - Name methodName = field.toName(toGetterName(fieldNode)); + Name methodName = field.toName(toGetterName(field)); List<JCTypeParameter> methodGenericParams = List.nil(); List<JCVariableDecl> parameters = List.nil(); diff --git a/src/core/lombok/javac/handlers/HandleSetter.java b/src/core/lombok/javac/handlers/HandleSetter.java index 0298311e..02591736 100644 --- a/src/core/lombok/javac/handlers/HandleSetter.java +++ b/src/core/lombok/javac/handlers/HandleSetter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 The Project Lombok Authors. + * Copyright (C) 2009-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 @@ -50,12 +50,14 @@ import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +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; /** @@ -162,10 +164,15 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { } JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); - String methodName = toSetterName(fieldDecl); + String methodName = toSetterName(fieldNode); - for (String altName : toAllSetterNames(fieldDecl)) { - switch (methodExists(altName, fieldNode, false)) { + if (methodName == null) { + source.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list."); + return; + } + + for (String altName : toAllSetterNames(fieldNode)) { + switch (methodExists(altName, fieldNode, false, 1)) { case EXISTS_BY_LOMBOK: return; case EXISTS_BY_USER: @@ -184,35 +191,67 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC); - injectMethod(fieldNode.up(), createSetter(access, fieldNode, fieldNode.getTreeMaker(), source.get())); + JCMethodDecl createdSetter = createSetter(access, fieldNode, fieldNode.getTreeMaker(), source.get()); + injectMethod(fieldNode.up(), createdSetter); } private JCMethodDecl createSetter(long access, JavacNode field, TreeMaker treeMaker, JCTree source) { + String setterName = toSetterName(field); + boolean returnThis = shouldReturnThis(field); + if (setterName == null) return null; + JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD); JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name)); - List<JCStatement> statements; + 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(setterName); + List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); + + JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); + if (nonNulls.isEmpty()) { - statements = List.<JCStatement>of(treeMaker.Exec(assign)); + statements.append(treeMaker.Exec(assign)); } else { JCStatement nullCheck = generateNullCheck(treeMaker, field); - if (nullCheck != null) statements = List.<JCStatement>of(nullCheck, treeMaker.Exec(assign)); - else statements = List.<JCStatement>of(treeMaker.Exec(assign)); + if (nullCheck != null) statements.append(nullCheck); + statements.append(treeMaker.Exec(assign)); } - JCBlock methodBody = treeMaker.Block(0, statements); - Name methodName = field.toName(toSetterName(fieldDecl)); - List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); + 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); + } + } + } - JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); - //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. - JCExpression methodType = treeMaker.Type(new JCNoType(getCtcInt(TypeTags.class, "VOID"))); + if (methodType == null) { + //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. + methodType = treeMaker.Type(new JCNoType(getCtcInt(TypeTags.class, "VOID"))); + returnThis = false; + } + + if (returnThis) { + JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this"))); + statements.append(returnStatement); + } + JCBlock methodBody = treeMaker.Block(0, statements.toList()); List<JCTypeParameter> methodGenericParams = List.nil(); List<JCVariableDecl> parameters = List.of(param); List<JCExpression> throwsClauses = List.nil(); diff --git a/src/core/lombok/javac/handlers/HandleToString.java b/src/core/lombok/javac/handlers/HandleToString.java index a5fb099b..016a7972 100644 --- a/src/core/lombok/javac/handlers/HandleToString.java +++ b/src/core/lombok/javac/handlers/HandleToString.java @@ -151,7 +151,7 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { } } - switch (methodExists("toString", typeNode)) { + switch (methodExists("toString", typeNode, 0)) { case NOT_EXISTS: JCMethodDecl method = createToString(typeNode, nodesForToString.toList(), includeFieldNames, callSuper, fieldAccess, source.get()); injectMethod(typeNode, method); diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index a6b33308..fc7666ec 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -39,7 +39,9 @@ import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.AnnotationValues.AnnotationValue; +import lombok.core.TransformationsUtil; import lombok.core.TypeResolver; +import lombok.experimental.Accessors; import lombok.javac.Javac; import lombok.javac.JavacNode; @@ -290,6 +292,95 @@ public class JavacHandlerUtil { } /** + * Translates the given field into all possible getter names. + * 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 the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). + * + * 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); + } + + /** + * Translates the given field into all possible setter names. + * 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 the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). + * + * 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); + } + + /** + * When generating a setter, the setter either returns void (beanspec) or Self (fluent). + * This method scans for the {@code Accessors} annotation to figure that out. + */ + public static boolean shouldReturnThis(JavacNode field) { + if ((((JCVariableDecl) field.get()).mods.flags & Flags.STATIC) != 0) return false; + + AnnotationValues<Accessors> accessors = JavacHandlerUtil.getAccessorsForField(field); + + boolean forced = (accessors.getActualExpression("chain") != null); + Accessors instance = accessors.getInstance(); + return instance.chain() || (instance.fluent() && !forced); + } + + private static boolean isBoolean(JavacNode field) { + JCExpression varType = ((JCVariableDecl) field.get()).vartype; + return varType != null && varType.toString().equals("boolean"); + } + + public static AnnotationValues<Accessors> getAccessorsForField(JavacNode field) { + for (JavacNode node : field.down()) { + if (annotationTypeMatches(Accessors.class, node)) { + return createAnnotation(Accessors.class, node); + } + } + + JavacNode current = field.up(); + while (current != null) { + for (JavacNode node : current.down()) { + if (annotationTypeMatches(Accessors.class, node)) { + return createAnnotation(Accessors.class, node); + } + } + current = current.up(); + } + + return AnnotationValues.of(Accessors.class, field); + } + + /** * Checks if there is a field with the provided name. * * @param fieldName the field name to check for. @@ -313,8 +404,8 @@ public class JavacHandlerUtil { return MemberExistsResult.NOT_EXISTS; } - public static MemberExistsResult methodExists(String methodName, JavacNode node) { - return methodExists(methodName, node, true); + public static MemberExistsResult methodExists(String methodName, JavacNode node, int params) { + return methodExists(methodName, node, true, params); } /** @@ -324,8 +415,9 @@ public class JavacHandlerUtil { * @param methodName the method name to check for. * @param node Any node that represents the Type (JCClassDecl) to look in, or any child node thereof. * @param caseSensitive If the search should be case sensitive. + * @param params The number of parameters the method should have; varargs count as 0-*. Set to -1 to find any method with the appropriate name regardless of parameter count. */ - public static MemberExistsResult methodExists(String methodName, JavacNode node, boolean caseSensitive) { + public static MemberExistsResult methodExists(String methodName, JavacNode node, boolean caseSensitive, int params) { while (node != null && !(node.get() instanceof JCClassDecl)) { node = node.up(); } @@ -333,9 +425,28 @@ public class JavacHandlerUtil { if (node != null && node.get() instanceof JCClassDecl) { for (JCTree def : ((JCClassDecl)node.get()).defs) { if (def instanceof JCMethodDecl) { - String name = ((JCMethodDecl)def).name.toString(); + JCMethodDecl md = (JCMethodDecl) def; + String name = md.name.toString(); boolean matches = caseSensitive ? name.equals(methodName) : name.equalsIgnoreCase(methodName); - if (matches) return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + if (matches) { + if (params > -1) { + List<JCVariableDecl> ps = md.params; + int minArgs = 0; + int maxArgs = 0; + if (ps != null && ps.length() > 0) { + minArgs = ps.length(); + if ((ps.last().mods.flags & Flags.VARARGS) != 0) { + maxArgs = Integer.MAX_VALUE; + minArgs--; + } else { + maxArgs = minArgs; + } + } + + if (params < minArgs || params > maxArgs) continue; + } + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + } } } } @@ -400,7 +511,7 @@ public class JavacHandlerUtil { private static GetterMethod findGetter(JavacNode field) { JCVariableDecl decl = (JCVariableDecl)field.get(); JavacNode typeNode = field.up(); - for (String potentialGetterName : toAllGetterNames(decl)) { + for (String potentialGetterName : toAllGetterNames(field)) { for (JavacNode potentialGetter : typeNode.down()) { if (potentialGetter.getKind() != Kind.METHOD) continue; JCMethodDecl method = (JCMethodDecl) potentialGetter.get(); @@ -442,7 +553,8 @@ public class JavacHandlerUtil { } if (hasGetterAnnotation) { - String getterName = toGetterName(decl); + String getterName = toGetterName(field); + if (getterName == null) return null; return new GetterMethod(field.toName(getterName), decl.vartype); } |