diff options
34 files changed, 1253 insertions, 313 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); } diff --git a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java index 056f5bf4..095928ad 100644 --- a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java +++ b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java @@ -759,6 +759,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { printDocComment(tree); printExpr(tree.mods); printTypeParameters(tree.typarams); + if (tree.typarams != null && tree.typarams.length() > 0) print(" "); if (tree.name == tree.name.table.fromChars("<init>".toCharArray(), 0, 6)) { print(enclClassName != null ? enclClassName : tree.name); } else { diff --git a/src/utils/lombok/core/TransformationsUtil.java b/src/utils/lombok/core/TransformationsUtil.java deleted file mode 100644 index 56ae0fb0..00000000 --- a/src/utils/lombok/core/TransformationsUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2009 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; - -/** - * 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 - } - - /** - * Generates a getter name from a given field name. - * - * Strategy: - * - * First, pick a prefix. 'get' normally, but 'is' if {@code isBoolean} is true. - * - * Then, 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. - * - * return the prefix plus the possibly title/uppercased first character, and the rest of the field name. - * - * Note that for boolean fields, if the field starts with 'is', and the character after that is - * <b>not</b> a lowercase character, the field name is returned without changing any character's case and without - * any prefix. - * - * @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 String toGetterName(CharSequence fieldName, boolean isBoolean) { - final String prefix = isBoolean ? "is" : "get"; - - if (fieldName.length() == 0) return prefix; - - 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(prefix, fieldName.toString()); - } - - 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. */ - public static final Pattern NON_NULL_PATTERN = Pattern.compile("^(?:nonnull)$", Pattern.CASE_INSENSITIVE); - public static final Pattern NULLABLE_PATTERN = Pattern.compile("^(?:nullable|checkfornull)$", Pattern.CASE_INSENSITIVE); - - /** - * Generates a setter name from a given field name. - * - * Strategy: - * - * 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. - * - * return "set" plus the possibly title/uppercased first character, and the rest of the field name. - * - * Note that if the field is boolean and starts with 'is' followed by a non-lowercase letter, the 'is' is stripped and replaced with 'set'. - * - * @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 String toSetterName(CharSequence fieldName, boolean isBoolean) { - if (fieldName.length() == 0) return "set"; - - if (isBoolean && fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - // The field is for example named 'isRunning'. - return "set" + fieldName.toString().substring(2); - } - - return buildName("set", fieldName.toString()); - } - - private static String buildName(String prefix, String suffix) { - if (suffix.length() == 0) return prefix; - - 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); - } - - /** - * 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 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(CharSequence fieldName, boolean isBoolean) { - if (!isBoolean) return Collections.singletonList(toGetterName(fieldName, false)); - - List<String> baseNames = new ArrayList<String>(); - baseNames.add(fieldName.toString()); - - // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. - if (fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - baseNames.add(fieldName.toString().substring(2)); - } - - Set<String> names = new HashSet<String>(); - for (String baseName : baseNames) { - if (baseName.length() > 0 && Character.isLowerCase(baseName.charAt(0))) { - baseName = Character.toTitleCase(baseName.charAt(0)) + baseName.substring(1); - } - - names.add("is" + baseName); - names.add("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(CharSequence fieldName, boolean isBoolean) { - if (!isBoolean) return Collections.singletonList(toSetterName(fieldName, false)); - - List<String> baseNames = new ArrayList<String>(); - baseNames.add(fieldName.toString()); - - // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. - if (fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - baseNames.add(fieldName.toString().substring(2)); - } - - Set<String> names = new HashSet<String>(); - for (String baseName : baseNames) { - if (baseName.length() > 0 && Character.isLowerCase(baseName.charAt(0))) { - baseName = Character.toTitleCase(baseName.charAt(0)) + baseName.substring(1); - } - - names.add("set" + baseName); - } - - return new ArrayList<String>(names); - } -} diff --git a/src/utils/lombok/javac/Javac.java b/src/utils/lombok/javac/Javac.java index fb24df93..d97746f1 100644 --- a/src/utils/lombok/javac/Javac.java +++ b/src/utils/lombok/javac/Javac.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 @@ -27,7 +27,6 @@ import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCLiteral; -import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * Container for static utility methods relevant to lombok's operation on javac. @@ -38,56 +37,6 @@ public class Javac { } /** - * Translates the given field into all possible getter names. - * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(CharSequence, boolean)}. - */ - public static java.util.List<String> toAllGetterNames(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toAllGetterNames(fieldName, isBoolean); - } - - /** - * @return the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). - * - * Convenient wrapper around {@link TransformationsUtil#toGetterName(CharSequence, boolean)}. - */ - public static String toGetterName(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toGetterName(fieldName, isBoolean); - } - - /** - * Translates the given field into all possible setter names. - * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(CharSequence, boolean)}. - */ - public static java.util.List<String> toAllSetterNames(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toAllSetterNames(fieldName, isBoolean); - } - - /** - * @return the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). - * - * Convenient wrapper around {@link TransformationsUtil#toSetterName(CharSequence, boolean)}. - */ - public static String toSetterName(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toSetterName(fieldName, isBoolean); - } - - /** * Checks if the given expression (that really ought to refer to a type expression) represents a primitive type. */ public static boolean isPrimitive(JCExpression ref) { diff --git a/test/transform/resource/after-delombok/Accessors.java b/test/transform/resource/after-delombok/Accessors.java new file mode 100644 index 00000000..b21f2de9 --- /dev/null +++ b/test/transform/resource/after-delombok/Accessors.java @@ -0,0 +1,133 @@ +class AccessorsFluent { + private String fieldName = ""; + + @java.lang.SuppressWarnings("all") + public String fieldName() { + return this.fieldName; + } + + @java.lang.SuppressWarnings("all") + public AccessorsFluent fieldName(final String fieldName) { + this.fieldName = fieldName; + return this; + } +} + +class AccessorsFluentOnClass { + private String fieldName = ""; + private String otherFieldWithOverride = ""; + + @java.lang.SuppressWarnings("all") + public String fieldName() { + return this.fieldName; + } + + @java.lang.SuppressWarnings("all") + public String getOtherFieldWithOverride() { + return this.otherFieldWithOverride; + } + + @java.lang.SuppressWarnings("all") + public AccessorsFluentOnClass fieldName(final String fieldName) { + this.fieldName = fieldName; + return this; + } +} + +class AccessorsChain { + private boolean isRunning; + + @java.lang.SuppressWarnings("all") + public AccessorsChain setRunning(final boolean isRunning) { + this.isRunning = isRunning; + return this; + } +} + +class AccessorsPrefix { + + private String fieldName; + private String fActualField; + + @java.lang.SuppressWarnings("all") + public void setActualField(final String fActualField) { + this.fActualField = fActualField; + } +} + +class AccessorsPrefix2 { + + private String fieldName; + private String fActualField; + + @java.lang.SuppressWarnings("all") + public void setFieldName(final String fieldName) { + this.fieldName = fieldName; + } + + @java.lang.SuppressWarnings("all") + public void setActualField(final String fActualField) { + this.fActualField = fActualField; + } +} + +class AccessorsPrefix3 { + private String fName; + + private String getName() { + return fName; + } + + @java.lang.Override + @java.lang.SuppressWarnings("all") + public java.lang.String toString() { + return "AccessorsPrefix3(fName=" + this.getName() + ")"; + } + + @java.lang.Override + @java.lang.SuppressWarnings("all") + public boolean equals(final java.lang.Object o) { + if (o == this) return true; + if (!(o instanceof AccessorsPrefix3)) return false; + final AccessorsPrefix3 other = (AccessorsPrefix3)o; + if (!other.canEqual((java.lang.Object)this)) return false; + if (this.getName() == null ? other.getName() != null : !this.getName().equals((java.lang.Object)other.getName())) return false; + return true; + } + + @java.lang.SuppressWarnings("all") + public boolean canEqual(final java.lang.Object other) { + return other instanceof AccessorsPrefix3; + } + + @java.lang.Override + @java.lang.SuppressWarnings("all") + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = result * PRIME + (this.getName() == null ? 0 : this.getName().hashCode()); + return result; + } +} +class AccessorsFluentGenerics<T extends Number> { + private String name; + @java.lang.SuppressWarnings("all") + public AccessorsFluentGenerics<T> name(final String name) { + this.name = name; + return this; + } +} +class AccessorsFluentNoChaining { + private String name; + @java.lang.SuppressWarnings("all") + public void name(final String name) { + this.name = name; + } +} +class AccessorsFluentStatic<T extends Number> { + private static String name; + @java.lang.SuppressWarnings("all") + public static void name(final String name) { + AccessorsFluentStatic.name = name; + } +}
\ No newline at end of file diff --git a/test/transform/resource/after-delombok/Constructors.java b/test/transform/resource/after-delombok/Constructors.java index baea640f..db48b6b8 100644 --- a/test/transform/resource/after-delombok/Constructors.java +++ b/test/transform/resource/after-delombok/Constructors.java @@ -44,4 +44,18 @@ class NoArgsConstructor1 { @java.lang.SuppressWarnings("all") public NoArgsConstructor1() { } +} +class RequiredArgsConstructorStaticNameGenerics<T extends Number> { + final T x; + String name; + + @java.lang.SuppressWarnings("all") + private RequiredArgsConstructorStaticNameGenerics(final T x) { + this.x = x; + } + + @java.lang.SuppressWarnings("all") + public static <T extends Number> RequiredArgsConstructorStaticNameGenerics<T> of(final T x) { + return new RequiredArgsConstructorStaticNameGenerics<T>(x); + } }
\ No newline at end of file diff --git a/test/transform/resource/after-delombok/SetterAlreadyExists.java b/test/transform/resource/after-delombok/SetterAlreadyExists.java index abc6d48f..5bfc1f83 100644 --- a/test/transform/resource/after-delombok/SetterAlreadyExists.java +++ b/test/transform/resource/after-delombok/SetterAlreadyExists.java @@ -22,24 +22,32 @@ class Setter5 { String foo; void setFoo() { } + @java.lang.SuppressWarnings("all") + public void setFoo(final String foo) { + this.foo = foo; + } } class Setter6 { String foo; void setFoo(String foo, int x) { } + @java.lang.SuppressWarnings("all") + public void setFoo(final String foo) { + this.foo = foo; + } } class Setter7 { String foo; - static void setFoo() { + void setFoo(String foo, Object... x) { } } class Setter8 { boolean isFoo; - void setIsFoo() { + void setIsFoo(boolean foo) { } } class Setter9 { boolean isFoo; - void setFoo() { + void setFoo(boolean foo) { } }
\ No newline at end of file diff --git a/test/transform/resource/after-delombok/ValWeirdTypes.java b/test/transform/resource/after-delombok/ValWeirdTypes.java index 9eb211b3..2c2905ed 100644 --- a/test/transform/resource/after-delombok/ValWeirdTypes.java +++ b/test/transform/resource/after-delombok/ValWeirdTypes.java @@ -23,7 +23,7 @@ public class ValWeirdTypes<Z> { } }; } - public <T extends Number>void testTypeParams(List<T> param) { + public <T extends Number> void testTypeParams(List<T> param) { final T t = param.get(0); final Z z = fieldList.get(0); final java.util.List<T> k = param; diff --git a/test/transform/resource/after-ecj/Accessors.java b/test/transform/resource/after-ecj/Accessors.java new file mode 100644 index 00000000..4ee0ebcd --- /dev/null +++ b/test/transform/resource/after-ecj/Accessors.java @@ -0,0 +1,126 @@ +class AccessorsFluent { + private @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent = true) String fieldName = ""; + public @java.lang.SuppressWarnings("all") String fieldName() { + return this.fieldName; + } + public @java.lang.SuppressWarnings("all") AccessorsFluent fieldName(final String fieldName) { + this.fieldName = fieldName; + return this; + } + AccessorsFluent() { + super(); + } +} +@lombok.experimental.Accessors(fluent = true) @lombok.Getter class AccessorsFluentOnClass { + private @lombok.Setter String fieldName = ""; + private @lombok.experimental.Accessors String otherFieldWithOverride = ""; + public @java.lang.SuppressWarnings("all") AccessorsFluentOnClass fieldName(final String fieldName) { + this.fieldName = fieldName; + return this; + } + public @java.lang.SuppressWarnings("all") String fieldName() { + return this.fieldName; + } + public @java.lang.SuppressWarnings("all") String getOtherFieldWithOverride() { + return this.otherFieldWithOverride; + } + AccessorsFluentOnClass() { + super(); + } +} +class AccessorsChain { + private @lombok.Setter @lombok.experimental.Accessors(chain = true) boolean isRunning; + public @java.lang.SuppressWarnings("all") AccessorsChain setRunning(final boolean isRunning) { + this.isRunning = isRunning; + return this; + } + AccessorsChain() { + super(); + } +} +@lombok.experimental.Accessors(prefix = "f") class AccessorsPrefix { + private @lombok.Setter String fieldName; + private @lombok.Setter String fActualField; + public @java.lang.SuppressWarnings("all") void setActualField(final String fActualField) { + this.fActualField = fActualField; + } + AccessorsPrefix() { + super(); + } +} +@lombok.experimental.Accessors(prefix = {"f", ""}) class AccessorsPrefix2 { + private @lombok.Setter String fieldName; + private @lombok.Setter String fActualField; + public @java.lang.SuppressWarnings("all") void setFieldName(final String fieldName) { + this.fieldName = fieldName; + } + public @java.lang.SuppressWarnings("all") void setActualField(final String fActualField) { + this.fActualField = fActualField; + } + AccessorsPrefix2() { + super(); + } +} +@lombok.experimental.Accessors(prefix = "f") @lombok.ToString @lombok.EqualsAndHashCode class AccessorsPrefix3 { + private String fName; + public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { + return (("AccessorsPrefix3(fName=" + this.getName()) + ")"); + } + public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { + if ((o == this)) + return true; + if ((! (o instanceof AccessorsPrefix3))) + return false; + final @java.lang.SuppressWarnings("all") AccessorsPrefix3 other = (AccessorsPrefix3) o; + if ((! other.canEqual((java.lang.Object) this))) + return false; + if (((this.getName() == null) ? (other.getName() != null) : (! this.getName().equals((java.lang.Object) other.getName())))) + return false; + return true; + } + public @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { + return (other instanceof AccessorsPrefix3); + } + public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { + final int PRIME = 31; + int result = 1; + result = ((result * PRIME) + ((this.getName() == null) ? 0 : this.getName().hashCode())); + return result; + } + AccessorsPrefix3() { + super(); + } + private String getName() { + return fName; + } +} +class AccessorsFluentGenerics<T extends Number> { + private @lombok.Setter @lombok.experimental.Accessors(fluent = true) String name; + public @java.lang.SuppressWarnings("all") AccessorsFluentGenerics<T> name(final String name) { + this.name = name; + return this; + } + AccessorsFluentGenerics() { + super(); + } +} +class AccessorsFluentNoChaining { + private @lombok.Setter @lombok.experimental.Accessors(fluent = true,chain = false) String name; + public @java.lang.SuppressWarnings("all") void name(final String name) { + this.name = name; + } + AccessorsFluentNoChaining() { + super(); + } +} +class AccessorsFluentStatic<T extends Number> { + private static @lombok.Setter @lombok.experimental.Accessors(fluent = true) String name; + <clinit>() { + } + public static @java.lang.SuppressWarnings("all") void name(final String name) { + AccessorsFluentStatic.name = name; + } + AccessorsFluentStatic() { + super(); + } +} diff --git a/test/transform/resource/after-ecj/Constructors.java b/test/transform/resource/after-ecj/Constructors.java index 3b3a14da..e6dd8a21 100644 --- a/test/transform/resource/after-ecj/Constructors.java +++ b/test/transform/resource/after-ecj/Constructors.java @@ -40,4 +40,15 @@ public @java.lang.SuppressWarnings("all") NoArgsConstructor1() { super(); } +} +@lombok.RequiredArgsConstructor(staticName = "of") class RequiredArgsConstructorStaticNameGenerics<T extends Number> { + final T x; + String name; + private @java.lang.SuppressWarnings("all") RequiredArgsConstructorStaticNameGenerics(final T x) { + super(); + this.x = x; + } + public static @java.lang.SuppressWarnings("all") <T extends Number>RequiredArgsConstructorStaticNameGenerics<T> of(final T x) { + return new RequiredArgsConstructorStaticNameGenerics<T>(x); + } }
\ No newline at end of file diff --git a/test/transform/resource/after-ecj/SetterAlreadyExists.java b/test/transform/resource/after-ecj/SetterAlreadyExists.java index 69983ac5..4c8a212d 100644 --- a/test/transform/resource/after-ecj/SetterAlreadyExists.java +++ b/test/transform/resource/after-ecj/SetterAlreadyExists.java @@ -32,6 +32,9 @@ class Setter4 { } class Setter5 { @lombok.Setter String foo; + public @java.lang.SuppressWarnings("all") void setFoo(final String foo) { + this.foo = foo; + } Setter5() { super(); } @@ -40,6 +43,9 @@ class Setter5 { } class Setter6 { @lombok.Setter String foo; + public @java.lang.SuppressWarnings("all") void setFoo(final String foo) { + this.foo = foo; + } Setter6() { super(); } @@ -51,7 +57,7 @@ class Setter7 { Setter7() { super(); } - static void setFoo() { + void setFoo(String foo, Object... x) { } } class Setter8 { @@ -59,7 +65,7 @@ class Setter8 { Setter8() { super(); } - void setIsFoo() { + void setIsFoo(boolean foo) { } } class Setter9 { @@ -67,6 +73,6 @@ class Setter9 { Setter9() { super(); } - void setFoo() { + void setFoo(boolean foo) { } }
\ No newline at end of file diff --git a/test/transform/resource/before/Accessors.java b/test/transform/resource/before/Accessors.java new file mode 100644 index 00000000..3ef8a02f --- /dev/null +++ b/test/transform/resource/before/Accessors.java @@ -0,0 +1,50 @@ +class AccessorsFluent { + @lombok.Getter @lombok.Setter @lombok.experimental.Accessors(fluent=true) + private String fieldName = ""; +} + +@lombok.experimental.Accessors(fluent=true) +@lombok.Getter +class AccessorsFluentOnClass { + @lombok.Setter private String fieldName = ""; + @lombok.experimental.Accessors private String otherFieldWithOverride = ""; +} + +class AccessorsChain { + @lombok.Setter @lombok.experimental.Accessors(chain=true) private boolean isRunning; +} + +@lombok.experimental.Accessors(prefix="f") +class AccessorsPrefix { + @lombok.Setter private String fieldName; + @lombok.Setter private String fActualField; +} + +@lombok.experimental.Accessors(prefix={"f", ""}) +class AccessorsPrefix2 { + @lombok.Setter private String fieldName; + @lombok.Setter private String fActualField; +} + +@lombok.experimental.Accessors(prefix="f") +@lombok.ToString +@lombok.EqualsAndHashCode +class AccessorsPrefix3 { + private String fName; + + private String getName() { + return fName; + } +} + +class AccessorsFluentGenerics<T extends Number> { + @lombok.Setter @lombok.experimental.Accessors(fluent=true) private String name; +} + +class AccessorsFluentNoChaining { + @lombok.Setter @lombok.experimental.Accessors(fluent=true,chain=false) private String name; +} + +class AccessorsFluentStatic<T extends Number> { + @lombok.Setter @lombok.experimental.Accessors(fluent=true) private static String name; +}
\ No newline at end of file diff --git a/test/transform/resource/before/Constructors.java b/test/transform/resource/before/Constructors.java index 6ac228d6..272fa850 100644 --- a/test/transform/resource/before/Constructors.java +++ b/test/transform/resource/before/Constructors.java @@ -17,4 +17,8 @@ @lombok.NoArgsConstructor class NoArgsConstructor1 { int x; String name; -}
\ No newline at end of file +} +@lombok.RequiredArgsConstructor(staticName="of") class RequiredArgsConstructorStaticNameGenerics<T extends Number> { + final T x; + String name; +} diff --git a/test/transform/resource/before/SetterAlreadyExists.java b/test/transform/resource/before/SetterAlreadyExists.java index 9ac56d8a..8d995b39 100644 --- a/test/transform/resource/before/SetterAlreadyExists.java +++ b/test/transform/resource/before/SetterAlreadyExists.java @@ -30,16 +30,16 @@ class Setter6 { } class Setter7 { @lombok.Setter String foo; - static void setFoo() { + void setFoo(String foo, Object... x) { } } class Setter8 { @lombok.Setter boolean isFoo; - void setIsFoo() { + void setIsFoo(boolean foo) { } } class Setter9 { @lombok.Setter boolean isFoo; - void setFoo() { + void setFoo(boolean foo) { } }
\ No newline at end of file diff --git a/test/transform/resource/messages-delombok/Accessors.java.messages b/test/transform/resource/messages-delombok/Accessors.java.messages new file mode 100644 index 00000000..4c7a0daa --- /dev/null +++ b/test/transform/resource/messages-delombok/Accessors.java.messages @@ -0,0 +1 @@ +19:9 WARNING Not generating setter for this field: It does not fit your @Accessors prefix list.
\ No newline at end of file diff --git a/test/transform/resource/messages-delombok/SetterAlreadyExists.java.messages b/test/transform/resource/messages-delombok/SetterAlreadyExists.java.messages index e1c0ee7d..7a4279c4 100644 --- a/test/transform/resource/messages-delombok/SetterAlreadyExists.java.messages +++ b/test/transform/resource/messages-delombok/SetterAlreadyExists.java.messages @@ -2,8 +2,6 @@ 7:9 WARNING Not generating setFoo(): A method with that name already exists 12:9 WARNING Not generating setFoo(): A method with that name already exists 17:9 WARNING Not generating setFoo(): A method with that name already exists -22:9 WARNING Not generating setFoo(): A method with that name already exists -27:9 WARNING Not generating setFoo(): A method with that name already exists 32:9 WARNING Not generating setFoo(): A method with that name already exists 37:9 WARNING Not generating setFoo(): A method with that name already exists (setIsFoo) 42:9 WARNING Not generating setFoo(): A method with that name already exists diff --git a/test/transform/resource/messages-ecj/Accessors.java.messages b/test/transform/resource/messages-ecj/Accessors.java.messages new file mode 100644 index 00000000..88594029 --- /dev/null +++ b/test/transform/resource/messages-ecj/Accessors.java.messages @@ -0,0 +1 @@ +19 warning Not generating setter for this field: It does not fit your @Accessors prefix list. diff --git a/test/transform/resource/messages-ecj/SetterAlreadyExists.java.messages b/test/transform/resource/messages-ecj/SetterAlreadyExists.java.messages index e82f4e6d..bc97510c 100644 --- a/test/transform/resource/messages-ecj/SetterAlreadyExists.java.messages +++ b/test/transform/resource/messages-ecj/SetterAlreadyExists.java.messages @@ -2,8 +2,6 @@ 7 warning Not generating setFoo(): A method with that name already exists 12 warning Not generating setFoo(): A method with that name already exists 17 warning Not generating setFoo(): A method with that name already exists -22 warning Not generating setFoo(): A method with that name already exists -27 warning Not generating setFoo(): A method with that name already exists 32 warning Not generating setFoo(): A method with that name already exists 37 warning Not generating setFoo(): A method with that name already exists (setIsFoo) 42 warning Not generating setFoo(): A method with that name already exists diff --git a/website/features/experimental/Accessors.html b/website/features/experimental/Accessors.html new file mode 100644 index 00000000..bbcd80bb --- /dev/null +++ b/website/features/experimental/Accessors.html @@ -0,0 +1,103 @@ +<!DOCTYPE html> +<html><head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <link rel="stylesheet" type="text/css" href="../../logi/reset.css" /> + <link rel="stylesheet" type="text/css" href="../features.css" /> + <link rel="shortcut icon" href="../../favicon.ico" type="image/x-icon" /> + <meta name="description" content="Spice up your java" /> + <title>EXPERIMENTAL - @Accessors</title> +</head><body><div id="pepper"> + <div class="minimumHeight"></div> + <div class="meat"> + <div class="header"><a href="../../index.html">Project Lombok</a></div> + <h1>@Accessors</h1> + <div class="byline">A more fluent API for getters and setters.</div> + <div class="since"> + <h3>Since</h3> + <p> + @Accessors was introduced as experimental feature in lombok v0.10.10. + </p> + </div> + <div class="experimental"> + <h3>Experimental</h3> + <p> + Experimental because: + <ul> + <li>We may want to roll these features into a more complete property support concept.</li> + <li>New feature - community feedback requested.</li> + </ul> + Current status: <em>positive</em> - Currently we feel this feature may move out of experimental status with no or minor changes soon. + </div> + <div class="overview"> + <h3>Overview</h3> + <p> + The <code>@Accessors</code> annotation is used to configure how lombok generates and looks for getters and setters. + </p><p> + By default, lombok follows the <em>bean specification</em> for getters and setters: The getter for a field named <code>pepper</code> + is <code>getPepper</code> for example. However, some might like to break with the <em>bean specification</em> in order to end up with + nicer looking APIs. <code>@Accessors</code> lets you do this. + </p><p> + Some programmers like to use a prefix for their fields, i.e. they write <code>fPepper</code> instead of <code>pepper</code>. + We <em>strongly</em> discourage doing this, as you can't unit test the validity of your prefixes, and refactor scripts may turn fields + into local variables or method names. Furthermore, your tools (such as your editor) can take care of rendering the identifier in a + certain way if you want this information to be instantly visible. Nevertheless, you can list the prefixes that your project uses via + <code>@Accessors</code> as well. + </p><p> + <code>@Accessors</code> therefore has 3 options:<ul> + <li><code>fluent</code> - A boolean. If <em>true</em>, the getter for <code>pepper</code> is just <code>pepper()</code>, and the + setter is <code>pepper(T newValue)</code>. Furthermore, unless specified, <code>chain</code> defaults to <em>true</em>.<br /> + Default: <em>false</em>.</li> + <li><code>chain</code> - A boolean. If <em>true</em>, generated setters return <code>this</code> instead of <code>void</code>.<br /> + Default: <em>false</em>, unless <code>fluent=true</code>, then Default: <em>true</em>.</li> + <li><code>prefix</code> - A list of strings. If present, fields must be prefixed with any of these prefixes. Each field name is + compared to each prefix in the list in turn, and if a match is found, the prefix is stripped out to create the base name for + the field. It is legal to include an empty string in the list, which will always match. For characters which are letters, the + character following the prefix must not be a lowercase letter, i.e. <code>pepper</code> is not a match even to prefix <code>p</code>, + but <code>pEpper</code> would be (and would mean the base name of this field is <code>epper</code>).</li> + </p><p> + The <code>@Accessors</code> annotation is legal on types and fields; the annotation that applies is the one on the field if present, + otherwise the one on the class. When a <code>@Accessors</code> annotation on a field is present, any <code>@Accessors</code> annotation + also present on that field's type is ignored. + </p> + </div> + <div class="snippets"> + <div class="pre"> + <h3>With Lombok</h3> + <div class="snippet">@HTML_PRE@</div> + </div> + <div class="sep"></div> + <div class="post"> + <h3>Vanilla Java</h3> + <div class="snippet">@HTML_POST@</div> + </div> + </div> + <div style="clear: left;"></div> + <div class="overview"> + <h3>Small print</h3><div class="smallprint"> + <p> + The nearest <code>@Accessors</code> annotation is also used for the various methods in lombok that look for getters, such as + <code>@EqualsAndHashCode</code>. + </p><p> + If a prefix list is provided and a field does not start with one of them, that field is skipped entirely by lombok, and + a warning will be generated. + </p> + </div> + </div> + <div class="footer"> + <a href="index.html">Back to experimental features</a> | <span class="disabled">Previous feature</span> | <span class="disabled">Next feature</span><br /> + <a href="../../credits.html" class="creditsLink">credits</a> | <span class="copyright">Copyright © 2009-2012 The Project Lombok Authors, licensed under the <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</span> + </div> + <div style="clear: both;"></div> + </div> +</div> +<script type="text/javascript"> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); +</script> +<script type="text/javascript"> + try { + var pageTracker = _gat._getTracker("UA-9884254-1"); + pageTracker._trackPageview(); + } catch(err) {} +</script> +</body></html> diff --git a/website/features/experimental/index.html b/website/features/experimental/index.html new file mode 100644 index 00000000..e4e90c41 --- /dev/null +++ b/website/features/experimental/index.html @@ -0,0 +1,45 @@ +<!DOCTYPE html> +<html><head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <link rel="stylesheet" type="text/css" href="../../logi/reset.css" /> + <link rel="stylesheet" type="text/css" href="../features.css" /> + <link rel="shortcut icon" href="../../favicon.ico" type="image/x-icon" /> + <meta name="description" content="Spice up your java" /> + <title>Lombok feature overview</title> +</head><body><div id="pepper"> + <div class="minimumHeight"></div> + <div class="meat"> + <div class="header"><a href="../../index.html">Project Lombok</a></div> + <h1>Lombok experimental features</h1> + <div class="index overview"> + Experimental features are available in your normal lombok installation, but are not as robustly supported as lombok's main features. + In particular, experimental features:<ul> + <li>Are not tested as well as the core features.</li> + <li>Do not get bugs fixed as quickly as core features.</li> + <li>May have APIs that will change, possibly drastically if we find a different, better way to solve the same problem.</li> + <li>May disappear entirely if the feature is too difficult to support or does bust enough boilerplate.</li> + </ul> + Features that receive positive community feedback and which seem to produce clean, flexible code will eventually become accepted + as a core feature and move out of the experimental package. + <dl> + <dt><a href="Accessors.html"><code>@Accessors</code></a></dt> + <dd>A more fluent API for getters and setters.</dd> + </dl> + </div> + <div class="footer"> + <a href="../../credits.html" class="creditsLink">credits</a> | <span class="copyright">Copyright © 2009-2012 The Project Lombok Authors, licensed under the <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</span> + </div> + <div style="clear: both;"></div> + </div> +</div> +<script type="text/javascript"> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); +</script> +<script type="text/javascript"> + try { + var pageTracker = _gat._getTracker("UA-9884254-1"); + pageTracker._trackPageview(); + } catch(err) {} +</script> +</body></html> diff --git a/website/features/index.html b/website/features/index.html index 1a4531f4..00669bb5 100644 --- a/website/features/index.html +++ b/website/features/index.html @@ -38,6 +38,8 @@ <dd>Finally! Hassle-free final local variables.</dd> <dt><a href="Delegate.html"><code>@Delegate</code></a></dt> <dd>Don't lose your composition.</dd> + <dt><a href="experimental/index.html">experimental features</a></dt> + <dd>Here be dragons: Extra features which aren't quite ready for prime time yet.</dd> </dl> </div> <div class="pointer"> |