diff options
author | Reinier Zwitserloot <reinier@zwitserloot.com> | 2013-02-11 22:34:48 +0100 |
---|---|---|
committer | Reinier Zwitserloot <reinier@zwitserloot.com> | 2013-02-11 22:34:48 +0100 |
commit | aafd83079a3000d3deb6e40a182849da2509fbfb (patch) | |
tree | cf87951eee9bb098bb96ecc3c02c6f1ab34c405d /src/core | |
parent | ef8769d3180b2c6de91a64f69dfa23a2e6e449b9 (diff) | |
download | lombok-aafd83079a3000d3deb6e40a182849da2509fbfb.tar.gz lombok-aafd83079a3000d3deb6e40a182849da2509fbfb.tar.bz2 lombok-aafd83079a3000d3deb6e40a182849da2509fbfb.zip |
BIG commit:
* re-introduction of onMethod/onConstructor/onParam
* tests checking error/warnings rewritten to be more heuristic, in order to accomodate difference in messaging between java6 and java 7
* Ability to eliminate java's own output of erroneous error messages (heh); i.e. those messages that are invalidated by lombok's actions. This mechanism is used for onMethod/onConstructor/onParam
* First steps to unifying a billion setGeneratedBy calls into a single visitor traversal for eclipse' HandleGetter/Setter/Constructor/Wither
* To simplify 'zooming in' the tests on just a few files, added an 'accept' mechanism.
* Updated copyright headers of website to 2013.
Diffstat (limited to 'src/core')
21 files changed, 661 insertions, 233 deletions
diff --git a/src/core/lombok/AllArgsConstructor.java b/src/core/lombok/AllArgsConstructor.java index 2147bdae..068b7a68 100644 --- a/src/core/lombok/AllArgsConstructor.java +++ b/src/core/lombok/AllArgsConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2012 The Project Lombok Authors. + * Copyright (C) 2010-2013 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 @@ -49,6 +49,11 @@ public @interface AllArgsConstructor { String staticName() default ""; /** + * Any annotations listed here are put on the generated constructor. The syntax for this feature is: {@code @AllArgsConstructor(onConstructor=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onConstructor() default {}; + + /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; @@ -63,4 +68,13 @@ public @interface AllArgsConstructor { */ @Deprecated boolean suppressConstructorProperties() default false; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} } diff --git a/src/core/lombok/Getter.java b/src/core/lombok/Getter.java index fa12ce1b..57f5e40a 100644 --- a/src/core/lombok/Getter.java +++ b/src/core/lombok/Getter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -57,5 +57,19 @@ public @interface Getter { */ lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC; + /** + * Any annotations listed here are put on the generated method. The syntax for this feature is: {@code @Getter(onMethod=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onMethod() default @AnyAnnotation; + boolean lazy() default false; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} } diff --git a/src/core/lombok/NoArgsConstructor.java b/src/core/lombok/NoArgsConstructor.java index ba53e39f..bbf2d9e6 100644 --- a/src/core/lombok/NoArgsConstructor.java +++ b/src/core/lombok/NoArgsConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2012 The Project Lombok Authors. + * Copyright (C) 2010-2013 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -51,7 +51,21 @@ public @interface NoArgsConstructor { String staticName() default ""; /** + * Any annotations listed here are put on the generated constructor. The syntax for this feature is: {@code @NoArgsConstructor(onConstructor=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onConstructor() default {}; + + /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} } diff --git a/src/core/lombok/RequiredArgsConstructor.java b/src/core/lombok/RequiredArgsConstructor.java index afe9773e..31c4b81d 100644 --- a/src/core/lombok/RequiredArgsConstructor.java +++ b/src/core/lombok/RequiredArgsConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2012 The Project Lombok Authors. + * Copyright (C) 2010-2013 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 @@ -49,6 +49,11 @@ public @interface RequiredArgsConstructor { String staticName() default ""; /** + * Any annotations listed here are put on the generated constructor. The syntax for this feature is: {@code @RequiredArgsConstructor(onConstructor=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onConstructor() default {}; + + /** * Sets the access level of the constructor. By default, generated constructors are {@code public}. */ AccessLevel access() default lombok.AccessLevel.PUBLIC; @@ -63,4 +68,13 @@ public @interface RequiredArgsConstructor { */ @Deprecated boolean suppressConstructorProperties() default false; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} } diff --git a/src/core/lombok/Setter.java b/src/core/lombok/Setter.java index 59ed9346..22622520 100644 --- a/src/core/lombok/Setter.java +++ b/src/core/lombok/Setter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -57,4 +57,23 @@ public @interface Setter { * If you want your setter to be non-public, you can specify an alternate access level here. */ lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC; + + /** + * Any annotations listed here are put on the generated method. The syntax for this feature is: {@code @Setter(onMethod=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onMethod() default {}; + + /** + * Any annotations listed here are put on the generated method's parameter. The syntax for this feature is: {@code @Setter(onParam=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onParam() default {}; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} }
\ No newline at end of file diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index 96795fe1..78780522 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -473,7 +473,7 @@ public class EclipseHandlerUtil { } } if (allNull) return null; - return result.toArray(EMPTY_ANNOTATION_ARRAY); + return result.toArray(new Annotation[0]); } public static boolean hasAnnotation(Class<? extends java.lang.annotation.Annotation> type, EclipseNode node) { @@ -1492,40 +1492,102 @@ public class EclipseHandlerUtil { intLiteralFactoryMethod = intLiteralFactoryMethod_; } - private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; - static Annotation[] getAndRemoveAnnotationParameter(Annotation annotation, String annotationName) { - - List<Annotation> result = new ArrayList<Annotation>(); - if (annotation instanceof NormalAnnotation) { - NormalAnnotation normalAnnotation = (NormalAnnotation)annotation; - MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; - List<MemberValuePair> pairs = new ArrayList<MemberValuePair>(); - if (memberValuePairs != null) for (MemberValuePair memberValuePair : memberValuePairs) { - if (annotationName.equals(new String(memberValuePair.name))) { - Expression value = memberValuePair.value; - if (value instanceof ArrayInitializer) { - ArrayInitializer array = (ArrayInitializer) value; - for(Expression expression : array.expressions) { - if (expression instanceof Annotation) { - result.add((Annotation)expression); - } - } - } - else if (value instanceof Annotation) { - result.add((Annotation)value); - } - continue; + private static boolean isAllUnderscores(char[] in) { + if (in == null || in.length == 0) return false; + for (char c : in) if (c != '_') return false; + return true; + } + + static List<Annotation> unboxAndRemoveAnnotationParameter(Annotation annotation, String annotationName, String errorName, EclipseNode errorNode) { + if ("value".equals(annotationName)) { + // We can't unbox this, because SingleMemberAnnotation REQUIRES a value, and this method + // is supposed to remove the value. That means we need to replace the SMA with either + // MarkerAnnotation or NormalAnnotation and that is beyond the scope of this method as we + // don't need that at the time of writing this method; we only unbox onMethod, onParameter + // and onConstructor. Let's exit early and very obviously: + throw new UnsupportedOperationException("Lombok cannot unbox 'value' from SingleMemberAnnotation at this time."); + } + if (!NormalAnnotation.class.equals(annotation.getClass())) { + // Prevent MarkerAnnotation, SingleMemberAnnotation, and + // CompletionOnAnnotationMemberValuePair from triggering this handler. + return Collections.emptyList(); + } + + NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; + MemberValuePair[] pairs = normalAnnotation.memberValuePairs; + + if (pairs == null) return Collections.emptyList(); + + char[] nameAsCharArray = annotationName.toCharArray(); + + for (int i = 0; i < pairs.length; i++) { + if (pairs[i].name == null || !Arrays.equals(nameAsCharArray, pairs[i].name)) continue; + Expression value = pairs[i].value; + MemberValuePair[] newPairs = new MemberValuePair[pairs.length - 1]; + if (i > 0) System.arraycopy(pairs, 0, newPairs, 0, i); + if (i < pairs.length - 1) System.arraycopy(pairs, i + 1, newPairs, i, pairs.length - i - 1); + normalAnnotation.memberValuePairs = newPairs; + // We have now removed the annotation parameter and stored '@_({... annotations ...})', + // which we must now unbox. + if (!(value instanceof Annotation)) { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + return Collections.emptyList(); + } + + Annotation atUnderscore = (Annotation) value; + if (!(atUnderscore.type instanceof SingleTypeReference) || + !isAllUnderscores(((SingleTypeReference) atUnderscore.type).token)) { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + return Collections.emptyList(); + } + + if (atUnderscore instanceof MarkerAnnotation) { + // It's @getter(onMethod=@_). This is weird, but fine. + return Collections.emptyList(); + } + + Expression content = null; + + if (atUnderscore instanceof NormalAnnotation) { + MemberValuePair[] mvps = ((NormalAnnotation) atUnderscore).memberValuePairs; + if (mvps == null || mvps.length == 0) { + // It's @getter(onMethod=@_()). This is weird, but fine. + return Collections.emptyList(); + } + if (mvps.length == 1 && Arrays.equals("value".toCharArray(), mvps[0].name)) { + content = mvps[0].value; } - pairs.add(memberValuePair); } - if (!result.isEmpty()) { - normalAnnotation.memberValuePairs = pairs.isEmpty() ? null : pairs.toArray(new MemberValuePair[0]); - return result.toArray(EMPTY_ANNOTATION_ARRAY); + if (atUnderscore instanceof SingleMemberAnnotation) { + content = ((SingleMemberAnnotation) atUnderscore).memberValue; + } + + if (content == null) { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + return Collections.emptyList(); + } + + if (content instanceof Annotation) { + return Collections.singletonList((Annotation) content); + } else if (content instanceof ArrayInitializer) { + Expression[] expressions = ((ArrayInitializer) content).expressions; + List<Annotation> result = new ArrayList<Annotation>(); + if (expressions != null) for (Expression ex : expressions) { + if (ex instanceof Annotation) result.add((Annotation) ex); + else { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + return Collections.emptyList(); + } + } + return result; + } else { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + return Collections.emptyList(); } } - return EMPTY_ANNOTATION_ARRAY; + return Collections.emptyList(); } static NameReference createNameReference(String name, Annotation source) { diff --git a/src/core/lombok/eclipse/handlers/HandleConstructor.java b/src/core/lombok/eclipse/handlers/HandleConstructor.java index 5d4656b6..8ccad77f 100644 --- a/src/core/lombok/eclipse/handlers/HandleConstructor.java +++ b/src/core/lombok/eclipse/handlers/HandleConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 The Project Lombok Authors. + * Copyright (C) 2010-2013 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 @@ -79,7 +79,10 @@ public class HandleConstructor { String staticName = ann.staticName(); if (level == AccessLevel.NONE) return; List<EclipseNode> fields = new ArrayList<EclipseNode>(); - new HandleConstructor().generateConstructor(typeNode, level, fields, staticName, false, false, ast); + + List<Annotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@NoArgsConstructor(onConstructor=", annotationNode); + + new HandleConstructor().generateConstructor(typeNode, level, fields, staticName, false, false, onConstructor, ast); } } @@ -94,7 +97,10 @@ public class HandleConstructor { @SuppressWarnings("deprecation") boolean suppressConstructorProperties = ann.suppressConstructorProperties(); if (level == AccessLevel.NONE) return; - new HandleConstructor().generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, false, suppressConstructorProperties, ast); + + List<Annotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@RequiredArgsConstructor(onConstructor=", annotationNode); + + new HandleConstructor().generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, false, suppressConstructorProperties, onConstructor, ast); } } @@ -137,7 +143,10 @@ public class HandleConstructor { @SuppressWarnings("deprecation") boolean suppressConstructorProperties = ann.suppressConstructorProperties(); if (level == AccessLevel.NONE) return; - new HandleConstructor().generateConstructor(typeNode, level, findAllFields(typeNode), staticName, false, suppressConstructorProperties, ast); + + List<Annotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@AllArgsConstructor(onConstructor=", annotationNode); + + new HandleConstructor().generateConstructor(typeNode, level, findAllFields(typeNode), staticName, false, suppressConstructorProperties, onConstructor, ast); } } @@ -155,15 +164,15 @@ public class HandleConstructor { return true; } - public void generateRequiredArgsConstructor(EclipseNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, ASTNode source) { - generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, skipIfConstructorExists, false, source); + public void generateRequiredArgsConstructor(EclipseNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, List<Annotation> onConstructor, ASTNode source) { + generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, skipIfConstructorExists, false, onConstructor, source); } - public void generateAllArgsConstructor(EclipseNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, ASTNode source) { - generateConstructor(typeNode, level, findAllFields(typeNode), staticName, skipIfConstructorExists, false, source); + public void generateAllArgsConstructor(EclipseNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, List<Annotation> onConstructor, ASTNode source) { + generateConstructor(typeNode, level, findAllFields(typeNode), staticName, skipIfConstructorExists, false, onConstructor, source); } - public void generateConstructor(EclipseNode typeNode, AccessLevel level, List<EclipseNode> fields, String staticName, boolean skipIfConstructorExists, boolean suppressConstructorProperties, ASTNode source) { + public void generateConstructor(EclipseNode typeNode, AccessLevel level, List<EclipseNode> fields, String staticName, boolean skipIfConstructorExists, boolean suppressConstructorProperties, List<Annotation> onConstructor, ASTNode source) { boolean staticConstrRequired = staticName != null && !staticName.equals(""); if (skipIfConstructorExists && constructorExists(typeNode) != MemberExistsResult.NOT_EXISTS) return; @@ -187,7 +196,7 @@ public class HandleConstructor { } } - ConstructorDeclaration constr = createConstructor(staticConstrRequired ? AccessLevel.PRIVATE : level, typeNode, fields, suppressConstructorProperties, source); + ConstructorDeclaration constr = createConstructor(staticConstrRequired ? AccessLevel.PRIVATE : level, typeNode, fields, suppressConstructorProperties, source, onConstructor); injectMethod(typeNode, constr); if (staticConstrRequired) { MethodDeclaration staticConstr = createStaticConstructor(level, staticName, typeNode, fields, source); @@ -196,8 +205,8 @@ public class HandleConstructor { } private static final char[][] JAVA_BEANS_CONSTRUCTORPROPERTIES = new char[][] { "java".toCharArray(), "beans".toCharArray(), "ConstructorProperties".toCharArray() }; - private static Annotation[] createConstructorProperties(ASTNode source, Annotation[] originalAnnotationArray, Collection<EclipseNode> fields) { - if (fields.isEmpty()) return originalAnnotationArray; + private static Annotation[] createConstructorProperties(ASTNode source, Collection<EclipseNode> fields) { + if (fields.isEmpty()) return null; int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; @@ -223,14 +232,14 @@ public class HandleConstructor { ann.memberValue = fieldNames; setGeneratedBy(ann, source); setGeneratedBy(ann.memberValue, source); - if (originalAnnotationArray == null) return new Annotation[] { ann }; - Annotation[] newAnnotationArray = Arrays.copyOf(originalAnnotationArray, originalAnnotationArray.length + 1); - newAnnotationArray[originalAnnotationArray.length] = ann; - return newAnnotationArray; + return new Annotation[] { ann }; } - private ConstructorDeclaration createConstructor(AccessLevel level, - EclipseNode type, Collection<EclipseNode> fields, boolean suppressConstructorProperties, ASTNode source) { + private ConstructorDeclaration createConstructor( + AccessLevel level, EclipseNode type, Collection<EclipseNode> fields, + boolean suppressConstructorProperties, ASTNode source, List<Annotation> onConstructor) { + + TypeDeclaration typeDeclaration = ((TypeDeclaration)type.get()); long p = (long)source.sourceStart << 32 | source.sourceEnd; boolean isEnum = (((TypeDeclaration)type.get()).modifiers & ClassFileConstants.AccEnum) != 0; @@ -239,12 +248,10 @@ public class HandleConstructor { ConstructorDeclaration constructor = new ConstructorDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - setGeneratedBy(constructor, source); constructor.modifiers = toEclipseModifier(level); - constructor.selector = ((TypeDeclaration)type.get()).name; + constructor.selector = typeDeclaration.name; constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); - setGeneratedBy(constructor.constructorCall, source); constructor.constructorCall.sourceStart = source.sourceStart; constructor.constructorCall.sourceEnd = source.sourceEnd; constructor.thrownExceptions = null; @@ -261,19 +268,14 @@ public class HandleConstructor { for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); FieldReference thisX = new FieldReference(field.name, p); - setGeneratedBy(thisX, source); thisX.receiver = new ThisReference((int)(p >> 32), (int)p); - setGeneratedBy(thisX.receiver, source); SingleNameReference assignmentNameRef = new SingleNameReference(field.name, p); - setGeneratedBy(assignmentNameRef, source); Assignment assignment = new Assignment(thisX, assignmentNameRef, (int)p); assignment.sourceStart = (int)(p >> 32); assignment.sourceEnd = assignment.statementEnd = (int)(p >> 32); - setGeneratedBy(assignment, source); assigns.add(assignment); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL); - setGeneratedBy(parameter, source); Annotation[] nonNulls = findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN); Annotation[] nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); if (nonNulls.length != 0) { @@ -289,10 +291,19 @@ public class HandleConstructor { constructor.statements = nullChecks.isEmpty() ? null : nullChecks.toArray(new Statement[nullChecks.size()]); constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]); - if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(type)) { - constructor.annotations = createConstructorProperties(source, constructor.annotations, fields); + /* Generate annotations that must be put on the generated method, and attach them. */ { + Annotation[] constructorProperties = null; + if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(type)) { + constructorProperties = createConstructorProperties(source, fields); + } + + Annotation[] copiedAnnotations = copyAnnotations(source, + onConstructor.toArray(new Annotation[0]), + constructorProperties); + if (copiedAnnotations.length != 0) constructor.annotations = copiedAnnotations; } + constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope); return constructor; } @@ -309,7 +320,6 @@ public class HandleConstructor { MethodDeclaration constructor = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - setGeneratedBy(constructor, source); constructor.modifiers = toEclipseModifier(level) | Modifier.STATIC; TypeDeclaration typeDecl = (TypeDeclaration) type.get(); @@ -323,7 +333,6 @@ public class HandleConstructor { } constructor.returnType = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); } else constructor.returnType = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); - setGeneratedBy(constructor.returnType, source); constructor.annotations = null; constructor.selector = name.toCharArray(); constructor.thrownExceptions = null; @@ -336,18 +345,15 @@ public class HandleConstructor { List<Expression> assigns = new ArrayList<Expression>(); AllocationExpression statement = new AllocationExpression(); statement.sourceStart = pS; statement.sourceEnd = pE; - setGeneratedBy(statement, source); statement.type = copyType(constructor.returnType, source); for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos); - setGeneratedBy(nameRef, source); assigns.add(nameRef); Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL); - setGeneratedBy(parameter, source); Annotation[] copiedAnnotations = copyAnnotations(source, findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN), findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN)); if (copiedAnnotations.length != 0) parameter.annotations = copiedAnnotations; @@ -357,7 +363,8 @@ public class HandleConstructor { statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]); constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]); constructor.statements = new Statement[] { new ReturnStatement(statement, (int)(p >> 32), (int)p) }; - setGeneratedBy(constructor.statements[0], source); + + constructor.traverse(new SetGeneratedByVisitor(source), typeDecl.scope); return constructor; } } diff --git a/src/core/lombok/eclipse/handlers/HandleData.java b/src/core/lombok/eclipse/handlers/HandleData.java index ba29b30b..3a43bd3f 100644 --- a/src/core/lombok/eclipse/handlers/HandleData.java +++ b/src/core/lombok/eclipse/handlers/HandleData.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -21,6 +21,8 @@ */ package lombok.eclipse.handlers; +import java.util.Collections; + import lombok.AccessLevel; import lombok.Data; import lombok.core.AnnotationValues; @@ -62,6 +64,6 @@ public class HandleData extends EclipseAnnotationHandler<Data> { new HandleSetter().generateSetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); - new HandleConstructor().generateRequiredArgsConstructor(typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), true, ast); + new HandleConstructor().generateRequiredArgsConstructor(typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), true, Collections.<Annotation>emptyList(), ast); } } diff --git a/src/core/lombok/eclipse/handlers/HandleGetter.java b/src/core/lombok/eclipse/handlers/HandleGetter.java index df05fc7e..7f788c5d 100644 --- a/src/core/lombok/eclipse/handlers/HandleGetter.java +++ b/src/core/lombok/eclipse/handlers/HandleGetter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -125,7 +125,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { return; } - createGetterForField(level, fieldNode, fieldNode, pos, false, lazy); + createGetterForField(level, fieldNode, fieldNode, pos, false, lazy, Collections.<Annotation>emptyList()); } public void handle(AnnotationValues<Getter> annotation, Annotation ast, EclipseNode annotationNode) { @@ -142,25 +142,30 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { if (node == null) return; + List<Annotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod=", annotationNode); + switch (node.getKind()) { case FIELD: - createGetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true, lazy); + createGetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true, lazy, onMethod); break; case TYPE: + if (!onMethod.isEmpty()) { + annotationNode.addError("'onMethod' is not supported for @Getter on a type."); + } if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type."); generateGetterForType(node, annotationNode, level, false); break; } } - private void createGetterForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy) { + private void createGetterForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy, List<Annotation> onMethod) { for (EclipseNode fieldNode : fieldNodes) { - createGetterForField(level, fieldNode, errorNode, source, whineIfExists, lazy); + createGetterForField(level, fieldNode, errorNode, source, whineIfExists, lazy, onMethod); } } private void createGetterForField(AccessLevel level, - EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy) { + EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy, List<Annotation> onMethod) { if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Getter is only supported on a class or a field."); return; @@ -207,17 +212,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { } } - MethodDeclaration method = generateGetter((TypeDeclaration) fieldNode.up().get(), fieldNode, getterName, modifier, source, lazy); - - Annotation[] deprecated = null; - if (isFieldDeprecated(fieldNode)) { - deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; - } - - Annotation[] copiedAnnotations = copyAnnotations(source, findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN), findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN), findDelegatesAndMarkAsHandled(fieldNode), deprecated); - if (copiedAnnotations.length != 0) { - method.annotations = copiedAnnotations; - } + MethodDeclaration method = createGetter((TypeDeclaration) fieldNode.up().get(), fieldNode, getterName, modifier, source, lazy, onMethod); injectMethod(fieldNode.up(), method); } @@ -234,7 +229,8 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { return delegates.toArray(EMPTY_ANNOTATIONS_ARRAY); } - private MethodDeclaration generateGetter(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source, boolean lazy) { + private MethodDeclaration createGetter(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source, boolean lazy, List<Annotation> onMethod) { + FieldDeclaration field = (FieldDeclaration) fieldNode.get(); // Remember the type; lazy will change it; TypeReference returnType = copyType(((FieldDeclaration) fieldNode.get()).type, source); @@ -247,7 +243,6 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { } MethodDeclaration method = new MethodDeclaration(parent.compilationResult); - setGeneratedBy(method, source); method.modifiers = modifier; method.returnType = returnType; method.annotations = null; @@ -263,6 +258,23 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { EclipseHandlerUtil.registerCreatedLazyGetter((FieldDeclaration) fieldNode.get(), method.selector, returnType); + /* Generate annotations that must be put on the generated method, and attach them. */ { + Annotation[] deprecated = null; + if (isFieldDeprecated(fieldNode)) { + deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; + } + + Annotation[] copiedAnnotations = copyAnnotations(source, + onMethod.toArray(new Annotation[0]), + findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN), + findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN), + findDelegatesAndMarkAsHandled(fieldNode), + deprecated); + + if (copiedAnnotations.length != 0) method.annotations = copiedAnnotations; + } + + method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } @@ -270,7 +282,6 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Statement returnStatement = new ReturnStatement(fieldRef, field.sourceStart, field.sourceEnd); - setGeneratedBy(returnStatement, source); return new Statement[] {returnStatement}; } @@ -319,7 +330,6 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { char[][] newType = TYPE_MAP.get(new String(((SingleTypeReference)field.type).token)); if (newType != null) { componentType = new QualifiedTypeReference(newType, poss(source, 3)); - setGeneratedBy(componentType, source); } } @@ -327,21 +337,17 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { /* java.util.concurrent.atomic.AtomicReference<ValueType> value = this.fieldName.get(); */ { LocalDeclaration valueDecl = new LocalDeclaration(valueName, pS, pE); - setGeneratedBy(valueDecl, source); TypeReference[][] typeParams = AR_PARAMS.clone(); typeParams[4] = new TypeReference[] {copyType(componentType, source)}; valueDecl.type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); valueDecl.type.sourceStart = pS; valueDecl.type.sourceEnd = valueDecl.type.statementEnd = pE; - setGeneratedBy(valueDecl.type, source); MessageSend getter = new MessageSend(); - setGeneratedBy(getter, source); getter.sourceStart = pS; getter.statementEnd = getter.sourceEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); valueDecl.initialization = getter; - setGeneratedBy(valueDecl.initialization, source); statements[0] = valueDecl; } @@ -360,102 +366,75 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { EqualExpression cond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); - setGeneratedBy(cond.left, source); - setGeneratedBy(cond.right, source); - setGeneratedBy(cond, source); Block then = new Block(0); - setGeneratedBy(then, source); Expression lock = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Block inner = new Block(0); - setGeneratedBy(inner, source); inner.statements = new Statement[2]; /* value = this.fieldName.get(); */ { MessageSend getter = new MessageSend(); - setGeneratedBy(getter, source); getter.sourceStart = pS; getter.sourceEnd = getter.statementEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Assignment assign = new Assignment(new SingleNameReference(valueName, p), getter, pE); assign.sourceStart = pS; assign.statementEnd = assign.sourceEnd = pE; - setGeneratedBy(assign, source); - setGeneratedBy(assign.lhs, source); inner.statements[0] = assign; } /* if (value == null) */ { EqualExpression innerCond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); - setGeneratedBy(innerCond.left, source); - setGeneratedBy(innerCond.right, source); - setGeneratedBy(innerCond, source); Block innerThen = new Block(0); - setGeneratedBy(innerThen, source); innerThen.statements = new Statement[3]; /* final ValueType actualValue = new ValueType(); */ { LocalDeclaration actualValueDecl = new LocalDeclaration(actualValueName, pS, pE); - setGeneratedBy(actualValueDecl, source); actualValueDecl.type = copyType(field.type, source); actualValueDecl.type.sourceStart = pS; actualValueDecl.type.sourceEnd = actualValueDecl.type.statementEnd = pE; - setGeneratedBy(actualValueDecl.type, source); actualValueDecl.initialization = field.initialization; actualValueDecl.modifiers = ClassFileConstants.AccFinal; innerThen.statements[0] = actualValueDecl; } /* value = new java.util.concurrent.atomic.AtomicReference<ValueType>(actualValue); */ { AllocationExpression create = new AllocationExpression(); - setGeneratedBy(create, source); create.sourceStart = pS; create.sourceEnd = create.statementEnd = pE; TypeReference[][] typeParams = AR_PARAMS.clone(); typeParams[4] = new TypeReference[] {copyType(componentType, source)}; create.type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); create.type.sourceStart = pS; create.type.sourceEnd = create.type.statementEnd = pE; - setGeneratedBy(create.type, source); create.arguments = new Expression[] {new SingleNameReference(actualValueName, p)}; - setGeneratedBy(create.arguments[0], source); Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), create, pE); innerAssign.sourceStart = pS; innerAssign.statementEnd = innerAssign.sourceEnd = pE; - setGeneratedBy(innerAssign, source); - setGeneratedBy(innerAssign.lhs, source); innerThen.statements[1] = innerAssign; } /* this.fieldName.set(value); */ { MessageSend setter = new MessageSend(); - setGeneratedBy(setter, source); setter.sourceStart = pS; setter.sourceEnd = setter.statementEnd = pE; setter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); setter.selector = new char[] { 's', 'e', 't' }; setter.arguments = new Expression[] { new SingleNameReference(valueName, p)}; - setGeneratedBy(setter.arguments[0], source); innerThen.statements[2] = setter; } IfStatement innerIf = new IfStatement(innerCond, innerThen, pS, pE); - setGeneratedBy(innerIf, source); inner.statements[1] = innerIf; } SynchronizedStatement sync = new SynchronizedStatement(lock, inner, pS, pE); - setGeneratedBy(sync, source); then.statements = new Statement[] {sync}; IfStatement ifStatement = new IfStatement(cond, then, pS, pE); - setGeneratedBy(ifStatement, source); statements[1] = ifStatement; } /* return value.get(); */ { MessageSend getter = new MessageSend(); - setGeneratedBy(getter, source); getter.sourceStart = pS; getter.sourceEnd = getter.statementEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = new SingleNameReference(valueName, p); - setGeneratedBy(getter.receiver, source); statements[2] = new ReturnStatement(getter, pS, pE); - setGeneratedBy(statements[2], source); } @@ -471,7 +450,6 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { TypeReference type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); // Some magic here type.sourceStart = -1; type.sourceEnd = -2; - setGeneratedBy(type, source); field.type = type; AllocationExpression init = new AllocationExpression(); diff --git a/src/core/lombok/eclipse/handlers/HandleSetter.java b/src/core/lombok/eclipse/handlers/HandleSetter.java index 8037ed23..9b46b704 100644 --- a/src/core/lombok/eclipse/handlers/HandleSetter.java +++ b/src/core/lombok/eclipse/handlers/HandleSetter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2011 The Project Lombok Authors. + * Copyright (C) 2009-2013 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,6 +27,7 @@ import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import lombok.AccessLevel; @@ -111,7 +112,9 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { return; } - createSetterForField(level, fieldNode, fieldNode, pos, false); + List<Annotation> empty = Collections.emptyList(); + + createSetterForField(level, fieldNode, fieldNode, pos, false, empty, empty); } public void handle(AnnotationValues<Setter> annotation, Annotation ast, EclipseNode annotationNode) { @@ -119,24 +122,36 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; + List<Annotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode); + List<Annotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode); + switch (node.getKind()) { case FIELD: - createSetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true); + createSetterForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true, onMethod, onParam); break; case TYPE: + if (!onMethod.isEmpty()) { + annotationNode.addError("'onMethod' is not supported for @Setter on a type."); + } + if (!onParam.isEmpty()) { + annotationNode.addError("'onParam' is not supported for @Setter on a type."); + } generateSetterForType(node, annotationNode, level, false); break; } } - private void createSetterForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + private void createSetterForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists, List<Annotation> onMethod, List<Annotation> onParam) { for (EclipseNode fieldNode : fieldNodes) { - createSetterForField(level, fieldNode, errorNode, source, whineIfExists); + createSetterForField(level, fieldNode, errorNode, source, whineIfExists, onMethod, onParam); } } - private void createSetterForField(AccessLevel level, - EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + private void createSetterForField( + AccessLevel level, EclipseNode fieldNode, EclipseNode errorNode, + ASTNode source, boolean whineIfExists, List<Annotation> onMethod, + List<Annotation> onParam) { + if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Setter is only supported on a class or a field."); return; @@ -147,6 +162,7 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { boolean isBoolean = nameEquals(fieldType.getTypeName(), "boolean") && fieldType.dimensions() == 0; 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; @@ -172,16 +188,15 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { } } - MethodDeclaration method = createSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, source); + MethodDeclaration method = createSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, source, onMethod, onParam); injectMethod(fieldNode.up(), method); } - private MethodDeclaration createSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, ASTNode source) { + private MethodDeclaration createSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, ASTNode source, List<Annotation> onMethod, List<Annotation> onParam) { 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; if (shouldReturnThis) { method.returnType = cloneSelfType(fieldNode, source); @@ -190,15 +205,18 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { if (method.returnType == null) { method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; - setGeneratedBy(method.returnType, source); shouldReturnThis = false; } + Annotation[] deprecated = null; if (isFieldDeprecated(fieldNode)) { - method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; + deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; + } + Annotation[] copiedAnnotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated); + if (copiedAnnotations.length != 0) { + method.annotations = copiedAnnotations; } Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL); param.sourceStart = pS; param.sourceEnd = pE; - setGeneratedBy(param, source); method.arguments = new Argument[] { param }; method.selector = name.toCharArray(); method.binding = null; @@ -207,10 +225,8 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); NameReference fieldNameRef = new SingleNameReference(field.name, p); - setGeneratedBy(fieldNameRef, source); Assignment assignment = new Assignment(fieldRef, fieldNameRef, (int)p); assignment.sourceStart = pS; assignment.sourceEnd = assignment.statementEnd = pE; - setGeneratedBy(assignment, source); method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; @@ -227,15 +243,15 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { 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; + Annotation[] copiedAnnotationsParam = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0])); + if (copiedAnnotationsParam.length != 0) param.annotations = copiedAnnotationsParam; + + method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } } diff --git a/src/core/lombok/eclipse/handlers/HandleValue.java b/src/core/lombok/eclipse/handlers/HandleValue.java index 4c293dc0..b74fbede 100644 --- a/src/core/lombok/eclipse/handlers/HandleValue.java +++ b/src/core/lombok/eclipse/handlers/HandleValue.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Project Lombok Authors. + * Copyright (C) 2012-2013 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 @@ -22,6 +22,9 @@ package lombok.eclipse.handlers; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; + +import java.util.Collections; + import lombok.AccessLevel; import lombok.core.AnnotationValues; import lombok.core.HandlerPriority; @@ -76,6 +79,6 @@ public class HandleValue extends EclipseAnnotationHandler<Value> { new HandleWither().generateWitherForType(typeNode, annotationNode, AccessLevel.PUBLIC, true); new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode); new HandleToString().generateToStringForType(typeNode, annotationNode); - new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), true, ast); + new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, ann.staticConstructor(), true, Collections.<Annotation>emptyList(), ast); } } diff --git a/src/core/lombok/eclipse/handlers/HandleWither.java b/src/core/lombok/eclipse/handlers/HandleWither.java index 1441a5f2..9d74cbd1 100644 --- a/src/core/lombok/eclipse/handlers/HandleWither.java +++ b/src/core/lombok/eclipse/handlers/HandleWither.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Project Lombok Authors. + * Copyright (C) 2012-2013 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,6 +27,7 @@ import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import lombok.AccessLevel; @@ -114,7 +115,8 @@ public class HandleWither extends EclipseAnnotationHandler<Wither> { } } - createWitherForField(level, fieldNode, fieldNode, pos, false); + List<Annotation> empty = Collections.emptyList(); + createWitherForField(level, fieldNode, fieldNode, pos, false, empty, empty); } @Override public void handle(AnnotationValues<Wither> annotation, Annotation ast, EclipseNode annotationNode) { @@ -122,24 +124,35 @@ public class HandleWither extends EclipseAnnotationHandler<Wither> { AccessLevel level = annotation.getInstance().value(); if (level == AccessLevel.NONE || node == null) return; + List<Annotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode); + List<Annotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode); + switch (node.getKind()) { case FIELD: - createWitherForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true); + createWitherForFields(level, annotationNode.upFromAnnotationToFields(), annotationNode, annotationNode.get(), true, onMethod, onParam); break; case TYPE: + if (!onMethod.isEmpty()) { + annotationNode.addError("'onMethod' is not supported for @Wither on a type."); + } + if (!onParam.isEmpty()) { + annotationNode.addError("'onParam' is not supported for @Wither on a type."); + } generateWitherForType(node, annotationNode, level, false); break; } } - private void createWitherForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + private void createWitherForFields(AccessLevel level, Collection<EclipseNode> fieldNodes, EclipseNode errorNode, ASTNode source, boolean whineIfExists, List<Annotation> onMethod, List<Annotation> onParam) { for (EclipseNode fieldNode : fieldNodes) { - createWitherForField(level, fieldNode, errorNode, source, whineIfExists); + createWitherForField(level, fieldNode, errorNode, source, whineIfExists, onMethod, onParam); } } - private void createWitherForField(AccessLevel level, - EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + private void createWitherForField( + AccessLevel level, EclipseNode fieldNode, EclipseNode errorNode, + ASTNode source, boolean whineIfExists, List<Annotation> onMethod, + List<Annotation> onParam) { if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Wither is only supported on a class or a field."); return; @@ -190,11 +203,11 @@ public class HandleWither extends EclipseAnnotationHandler<Wither> { int modifier = toEclipseModifier(level); - MethodDeclaration method = createWither((TypeDeclaration) fieldNode.up().get(), fieldNode, witherName, modifier, source); + MethodDeclaration method = createWither((TypeDeclaration) fieldNode.up().get(), fieldNode, witherName, modifier, source, onMethod, onParam); injectMethod(fieldNode.up(), method); } - private MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source) { + private MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source, List<Annotation> onMethod, List<Annotation> onParam) { if (name == null) return null; FieldDeclaration field = (FieldDeclaration) fieldNode.get(); int pS = source.sourceStart, pE = source.sourceEnd; @@ -204,8 +217,13 @@ public class HandleWither extends EclipseAnnotationHandler<Wither> { method.returnType = cloneSelfType(fieldNode, source); if (method.returnType == null) return null; + Annotation[] deprecated = null; if (isFieldDeprecated(fieldNode)) { - method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) }; + deprecated = new Annotation[] { generateDeprecatedAnnotation(source) }; + } + Annotation[] copiedAnnotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated); + if (copiedAnnotations.length != 0) { + method.annotations = copiedAnnotations; } Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL); param.sourceStart = pS; param.sourceEnd = pE; @@ -259,8 +277,9 @@ public class HandleWither extends EclipseAnnotationHandler<Wither> { method.statements = statements.toArray(new Statement[0]); - Annotation[] copiedAnnotations = copyAnnotations(source, nonNulls, nullables); - if (copiedAnnotations.length != 0) param.annotations = copiedAnnotations; + Annotation[] copiedAnnotationsParam = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0])); + if (copiedAnnotationsParam.length != 0) param.annotations = copiedAnnotationsParam; + method.traverse(new SetGeneratedByVisitor(source), parent.scope); return method; } diff --git a/src/core/lombok/experimental/Wither.java b/src/core/lombok/experimental/Wither.java index 58be660a..f667cb1f 100644 --- a/src/core/lombok/experimental/Wither.java +++ b/src/core/lombok/experimental/Wither.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Project Lombok Authors. + * Copyright (C) 2012-2013 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 @@ -58,4 +58,23 @@ public @interface Wither { * If you want your wither to be non-public, you can specify an alternate access level here. */ AccessLevel value() default AccessLevel.PUBLIC; + + /** + * Any annotations listed here are put on the generated method. The syntax for this feature is: {@code @Setter(onMethod=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onMethod() default {}; + + /** + * Any annotations listed here are put on the generated method's parameter. The syntax for this feature is: {@code @Setter(onParam=@_({@AnnotationsGoHere}))} + */ + AnyAnnotation[] onParam() default {}; + + /** + * Placeholder annotation to enable the placement of annotations on the generated code. + * @deprecated Don't use this annotation, ever - Read the documentation. + */ + @Deprecated + @Retention(RetentionPolicy.SOURCE) + @Target({}) + @interface AnyAnnotation {} } diff --git a/src/core/lombok/javac/CapturingDiagnosticListener.java b/src/core/lombok/javac/CapturingDiagnosticListener.java new file mode 100644 index 00000000..45b4047a --- /dev/null +++ b/src/core/lombok/javac/CapturingDiagnosticListener.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2012-2013 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; + +import java.io.File; +import java.util.Collection; +import java.util.Iterator; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.tools.Diagnostic; +import javax.tools.Diagnostic.Kind; +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileObject; + +/** + * This class stores any reported errors as {@code CompilerMessage} objects and supports removing some of these. + * Currently this class is only used for testing purposes. + */ +public class CapturingDiagnosticListener implements DiagnosticListener<JavaFileObject> { + private final File file; + private final Collection<CompilerMessage> messages; + + public CapturingDiagnosticListener(File file, Collection<CompilerMessage> messages) { + this.file = file; + this.messages = messages; + } + + @Override public void report(Diagnostic<? extends JavaFileObject> d) { + String msg = d.getMessage(Locale.ENGLISH); + Matcher m = Pattern.compile( + "^" + Pattern.quote(file.getAbsolutePath()) + + "\\s*:\\s*\\d+\\s*:\\s*(?:warning:\\s*)?(.*)$", Pattern.DOTALL).matcher(msg); + if (m.matches()) msg = m.group(1); + messages.add(new CompilerMessage(d.getLineNumber(), d.getColumnNumber(), d.getStartPosition(), d.getKind() == Kind.ERROR, msg)); + } + + public void suppress(int start, int end) { + Iterator<CompilerMessage> it = messages.iterator(); + while (it.hasNext()) { + long pos = it.next().getPosition(); + if (pos >= start && pos < end) it.remove(); + } + } + + public static final class CompilerMessage { + /** Line Number (starting at 1) */ + private final long line; + + /** Preferably column, but if that is hard to calculate (e.g. in ecj), then position is acceptable. */ + private final long columnOrPosition; + private final long position; + private final boolean isError; + private final String message; + + public CompilerMessage(long line, long columnOrPosition, long position, boolean isError, String message) { + this.line = line; + this.columnOrPosition = columnOrPosition; + this.position = position; + this.isError = isError; + this.message = message; + } + + public long getLine() { + return line; + } + + public long getPosition() { + return position; + } + + public long getColumnOrPosition() { + return columnOrPosition; + } + + public boolean isError() { + return isError; + } + + public String getMessage() { + return message; + } + + @Override public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (isError ? 1231 : 1237); + result = prime * result + (int) (line ^ (line >>> 32)); + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + (int) (columnOrPosition ^ (columnOrPosition >>> 32)); + return result; + } + + @Override public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + CompilerMessage other = (CompilerMessage) obj; + if (isError != other.isError) return false; + if (line != other.line) return false; + if (message == null) { + if (other.message != null) return false; + } else if (!message.equals(other.message)) return false; + if (columnOrPosition != other.columnOrPosition) return false; + return true; + } + + @Override public String toString() { + return String.format("%d:%d %s %s", line, columnOrPosition, isError ? "ERROR" : "WARNING", message); + } + } +} diff --git a/src/core/lombok/javac/JavacAST.java b/src/core/lombok/javac/JavacAST.java index c2c55f1d..71c17538 100644 --- a/src/core/lombok/javac/JavacAST.java +++ b/src/core/lombok/javac/JavacAST.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2010 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -28,6 +28,7 @@ import java.util.List; import javax.annotation.processing.Messager; import javax.tools.Diagnostic; +import javax.tools.DiagnosticListener; import javax.tools.JavaFileObject; import lombok.core.AST; @@ -50,6 +51,8 @@ import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.JCDiagnostic; +import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; @@ -287,8 +290,28 @@ public class JavacAST extends AST<JavacAST, JavacNode, JCTree> { if (node != null) nodes.add(node); } + private static final Field JAVAC7_DEFERRED_DIAGNOSTICS; + + static { + Field f = null; + try { + f = Log.class.getField("deferredDiagnostics"); + if (!ListBuffer.class.isAssignableFrom(f.getType())) throw new NoSuchFieldException("deferredDiagnostics does not have the expected type."); + } catch (NoSuchFieldException e) {} + JAVAC7_DEFERRED_DIAGNOSTICS = f; + } + + /** + * Attempts to remove any compiler errors generated by java whose reporting position is located anywhere between the start and end of the supplied node. + */ + void removeDeferredErrors(JavacNode node) { + DiagnosticPosition pos = node.get().pos(); + JCCompilationUnit top = (JCCompilationUnit) top().get(); + removeFromDeferredDiagnostics(pos.getStartPosition(), pos.getEndPosition(top.endPositions)); + } + /** Supply either a position or a node (in that case, position of the node is used) */ - void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos) { + void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos, boolean attemptToRemoveErrorsInRange) { JavaFileObject oldSource = null; JavaFileObject newSource = null; JCTree astObject = node == null ? null : node.get(); @@ -298,6 +321,9 @@ public class JavacAST extends AST<JavacAST, JavacNode, JCTree> { oldSource = log.useSource(newSource); if (pos == null) pos = astObject.pos(); } + if (pos != null && attemptToRemoveErrorsInRange) { + removeFromDeferredDiagnostics(pos.getStartPosition(), pos.getEndPosition(top.endPositions)); + } try { switch (kind) { case ERROR: @@ -319,6 +345,35 @@ public class JavacAST extends AST<JavacAST, JavacNode, JCTree> { if (oldSource != null) log.useSource(oldSource); } } + + private void removeFromDeferredDiagnostics(int startPos, int endPos) { + DiagnosticListener<?> listener = getContext().get(DiagnosticListener.class); + if (listener instanceof CapturingDiagnosticListener) { + ((CapturingDiagnosticListener) listener).suppress(startPos, endPos); + } + try { + if (JAVAC7_DEFERRED_DIAGNOSTICS != null) { + ListBuffer<?> deferredDiagnostics = (ListBuffer<?>) JAVAC7_DEFERRED_DIAGNOSTICS.get(log); + ListBuffer<Object> newDeferredDiagnostics = ListBuffer.lb(); + for (Object diag : deferredDiagnostics) { + if (!(diag instanceof JCDiagnostic)) { + newDeferredDiagnostics.add(diag); + continue; + } + long here = ((JCDiagnostic) diag).getStartPosition(); + if (here >= startPos && here < endPos) { + // We eliminate it + } else { + newDeferredDiagnostics.add(diag); + } + } + JAVAC7_DEFERRED_DIAGNOSTICS.set(log, newDeferredDiagnostics); + } + } catch (Exception e) { + // We do not expect failure here; if failure does occur, the best course of action is to silently continue; the result will be that the error output of + // javac will contain rather a lot of messages, but this is a lot better than just crashing during compilation! + } + } /** {@inheritDoc} */ @Override protected void setElementInASTCollection(Field field, Object refField, List<Collection<?>> chain, Collection<?> collection, int idx, JCTree newN) throws IllegalAccessException { diff --git a/src/core/lombok/javac/JavacNode.java b/src/core/lombok/javac/JavacNode.java index b478781b..16c06430 100644 --- a/src/core/lombok/javac/JavacNode.java +++ b/src/core/lombok/javac/JavacNode.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2010 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -209,31 +209,35 @@ public class JavacNode extends lombok.core.LombokNode<JavacAST, JavacNode, JCTre return ast.toName(name); } + public void removeDeferredErrors() { + ast.removeDeferredErrors(this); + } + /** * Generates an compiler error focused on the AST node represented by this node object. */ @Override public void addError(String message) { - ast.printMessage(Diagnostic.Kind.ERROR, message, this, null); + ast.printMessage(Diagnostic.Kind.ERROR, message, this, null, true); } /** * Generates an compiler error focused on the AST node represented by this node object. */ public void addError(String message, DiagnosticPosition pos) { - ast.printMessage(Diagnostic.Kind.ERROR, message, null, pos); + ast.printMessage(Diagnostic.Kind.ERROR, message, null, pos, true); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ @Override public void addWarning(String message) { - ast.printMessage(Diagnostic.Kind.WARNING, message, this, null); + ast.printMessage(Diagnostic.Kind.WARNING, message, this, null, false); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ public void addWarning(String message, DiagnosticPosition pos) { - ast.printMessage(Diagnostic.Kind.WARNING, message, null, pos); + ast.printMessage(Diagnostic.Kind.WARNING, message, null, pos, false); } } diff --git a/src/core/lombok/javac/handlers/HandleConstructor.java b/src/core/lombok/javac/handlers/HandleConstructor.java index b6c31f83..bb883ca4 100644 --- a/src/core/lombok/javac/handlers/HandleConstructor.java +++ b/src/core/lombok/javac/handlers/HandleConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010-2011 The Project Lombok Authors. + * Copyright (C) 2010-2013 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 @@ -60,12 +60,13 @@ public class HandleConstructor { deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, NoArgsConstructor.class.getSimpleName())) return; + List<JCAnnotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@NoArgsConstructor(onConstructor=", annotationNode); NoArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); String staticName = ann.staticName(); if (level == AccessLevel.NONE) return; List<JavacNode> fields = List.nil(); - new HandleConstructor().generateConstructor(typeNode, level, fields, staticName, false, false, annotationNode); + new HandleConstructor().generateConstructor(typeNode, level, onConstructor, fields, staticName, false, false, annotationNode); } } @@ -76,13 +77,14 @@ public class HandleConstructor { deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, RequiredArgsConstructor.class.getSimpleName())) return; + List<JCAnnotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@RequiredArgsConstructor(onConstructor=", annotationNode); RequiredArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); String staticName = ann.staticName(); @SuppressWarnings("deprecation") boolean suppressConstructorProperties = ann.suppressConstructorProperties(); if (level == AccessLevel.NONE) return; - new HandleConstructor().generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, false, suppressConstructorProperties, annotationNode); + new HandleConstructor().generateConstructor(typeNode, level, onConstructor, findRequiredFields(typeNode), staticName, false, suppressConstructorProperties, annotationNode); } } @@ -110,13 +112,14 @@ public class HandleConstructor { deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); JavacNode typeNode = annotationNode.up(); if (!checkLegality(typeNode, annotationNode, AllArgsConstructor.class.getSimpleName())) return; + List<JCAnnotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@AllArgsConstructor(onConstructor=", annotationNode); AllArgsConstructor ann = annotation.getInstance(); AccessLevel level = ann.access(); String staticName = ann.staticName(); @SuppressWarnings("deprecation") boolean suppressConstructorProperties = ann.suppressConstructorProperties(); if (level == AccessLevel.NONE) return; - new HandleConstructor().generateConstructor(typeNode, level, findAllFields(typeNode), staticName, false, suppressConstructorProperties, annotationNode); + new HandleConstructor().generateConstructor(typeNode, level, onConstructor, findAllFields(typeNode), staticName, false, suppressConstructorProperties, annotationNode); } } @@ -152,14 +155,14 @@ public class HandleConstructor { } public void generateRequiredArgsConstructor(JavacNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, JavacNode source) { - generateConstructor(typeNode, level, findRequiredFields(typeNode), staticName, skipIfConstructorExists, false, source); + generateConstructor(typeNode, level, List.<JCAnnotation>nil(), findRequiredFields(typeNode), staticName, skipIfConstructorExists, false, source); } public void generateAllArgsConstructor(JavacNode typeNode, AccessLevel level, String staticName, boolean skipIfConstructorExists, JavacNode source) { - generateConstructor(typeNode, level, findAllFields(typeNode), staticName, skipIfConstructorExists, false, source); + generateConstructor(typeNode, level, List.<JCAnnotation>nil(), findAllFields(typeNode), staticName, skipIfConstructorExists, false, source); } - public void generateConstructor(JavacNode typeNode, AccessLevel level, List<JavacNode> fields, String staticName, boolean skipIfConstructorExists, boolean suppressConstructorProperties, JavacNode source) { + public void generateConstructor(JavacNode typeNode, AccessLevel level, List<JCAnnotation> onConstructor, List<JavacNode> fields, String staticName, boolean skipIfConstructorExists, boolean suppressConstructorProperties, JavacNode source) { boolean staticConstrRequired = staticName != null && !staticName.equals(""); if (skipIfConstructorExists && constructorExists(typeNode) != MemberExistsResult.NOT_EXISTS) return; @@ -183,7 +186,7 @@ public class HandleConstructor { } } - JCMethodDecl constr = createConstructor(staticConstrRequired ? AccessLevel.PRIVATE : level, typeNode, fields, suppressConstructorProperties, source.get()); + JCMethodDecl constr = createConstructor(staticConstrRequired ? AccessLevel.PRIVATE : level, onConstructor, typeNode, fields, suppressConstructorProperties, source.get()); injectMethod(typeNode, constr); if (staticConstrRequired) { JCMethodDecl staticConstr = createStaticConstructor(staticName, level, typeNode, fields, source.get()); @@ -204,7 +207,7 @@ public class HandleConstructor { mods.annotations = mods.annotations.append(annotation); } - private JCMethodDecl createConstructor(AccessLevel level, JavacNode typeNode, List<JavacNode> fields, boolean suppressConstructorProperties, JCTree source) { + private JCMethodDecl createConstructor(AccessLevel level, List<JCAnnotation> onConstructor, JavacNode typeNode, List<JavacNode> fields, boolean suppressConstructorProperties, JCTree source) { TreeMaker maker = typeNode.getTreeMaker(); boolean isEnum = (((JCClassDecl) typeNode.get()).mods.flags & Flags.ENUM) != 0; @@ -234,6 +237,8 @@ public class HandleConstructor { if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(typeNode)) { addConstructorProperties(mods, typeNode, fields); } + if (onConstructor != null) mods.annotations = mods.annotations.appendList(copyAnnotations(onConstructor)); + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("<init>"), null, List.<JCTypeParameter>nil(), params.toList(), List.<JCExpression>nil(), maker.Block(0L, nullChecks.appendList(assigns).toList()), null), source); } diff --git a/src/core/lombok/javac/handlers/HandleGetter.java b/src/core/lombok/javac/handlers/HandleGetter.java index 65947c72..bc68d5ad 100644 --- a/src/core/lombok/javac/handlers/HandleGetter.java +++ b/src/core/lombok/javac/handlers/HandleGetter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -21,8 +21,8 @@ */ package lombok.javac.handlers; -import static lombok.javac.handlers.JavacHandlerUtil.*; import static lombok.javac.Javac.*; +import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; import java.util.Collections; @@ -32,9 +32,9 @@ import java.util.Map; import lombok.AccessLevel; import lombok.Delegate; import lombok.Getter; +import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; -import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; @@ -43,7 +43,6 @@ import org.mangosdk.spi.ProviderFor; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; @@ -60,10 +59,11 @@ import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCTypeApply; 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; -import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** * Handles the {@code lombok.Getter} annotation for javac. @@ -123,8 +123,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { //The annotation will make it happen, so we can skip it. return; } - - createGetterForField(level, fieldNode, fieldNode, false, lazy); + createGetterForField(level, fieldNode, fieldNode, false, lazy, List.<JCAnnotation>nil()); } @Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacNode annotationNode) { @@ -144,25 +143,30 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { if (node == null) return; + List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod=", annotationNode); + switch (node.getKind()) { case FIELD: - createGetterForFields(level, fields, annotationNode, true, lazy); + createGetterForFields(level, fields, annotationNode, true, lazy, onMethod); break; case TYPE: + if (!onMethod.isEmpty()) { + annotationNode.addError("'onMethod' is not supported for @Getter on a type."); + } if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type."); generateGetterForType(node, annotationNode, level, false); break; } } - private void createGetterForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists, boolean lazy) { + private void createGetterForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists, boolean lazy, List<JCAnnotation> onMethod) { for (JavacNode fieldNode : fieldNodes) { - createGetterForField(level, fieldNode, errorNode, whineIfExists, lazy); + createGetterForField(level, fieldNode, errorNode, whineIfExists, lazy, onMethod); } } private void createGetterForField(AccessLevel level, - JavacNode fieldNode, JavacNode source, boolean whineIfExists, boolean lazy) { + JavacNode fieldNode, JavacNode source, boolean whineIfExists, boolean lazy, List<JCAnnotation> onMethod) { if (fieldNode.getKind() != Kind.FIELD) { source.addError("@Getter is only supported on a class or a field."); return; @@ -208,10 +212,10 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC); - injectMethod(fieldNode.up(), createGetter(access, fieldNode, fieldNode.getTreeMaker(), lazy, source.get())); + injectMethod(fieldNode.up(), createGetter(access, fieldNode, fieldNode.getTreeMaker(), source.get(), lazy, onMethod)); } - private JCMethodDecl createGetter(long access, JavacNode field, TreeMaker treeMaker, boolean lazy, JCTree source) { + private JCMethodDecl createGetter(long access, JavacNode field, TreeMaker treeMaker, JCTree source, boolean lazy, List<JCAnnotation> onMethod) { JCVariableDecl fieldNode = (JCVariableDecl) field.get(); // Remember the type; lazy will change it @@ -240,7 +244,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { List<JCAnnotation> delegates = findDelegatesAndRemoveFromField(field); - List<JCAnnotation> annsOnMethod = nonNulls.appendList(nullables); + List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod).appendList(nonNulls).appendList(nullables); if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil())); } diff --git a/src/core/lombok/javac/handlers/HandleSetter.java b/src/core/lombok/javac/handlers/HandleSetter.java index e2c75e2e..c1e03c35 100644 --- a/src/core/lombok/javac/handlers/HandleSetter.java +++ b/src/core/lombok/javac/handlers/HandleSetter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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,7 +118,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { return; } - createSetterForField(level, fieldNode, fieldNode, false); + createSetterForField(level, fieldNode, fieldNode, false, List.<JCAnnotation>nil(), List.<JCAnnotation>nil()); } @Override public void handle(AnnotationValues<Setter> annotation, JCAnnotation ast, JavacNode annotationNode) { @@ -130,26 +130,28 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { if (level == AccessLevel.NONE || node == null) return; + List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode); + List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode); + switch (node.getKind()) { case FIELD: - createSetterForFields(level, fields, annotationNode, true); + createSetterForFields(level, fields, annotationNode, true, onMethod, onParam); break; case TYPE: + if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Setter on a type."); + if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Setter on a type."); generateSetterForType(node, annotationNode, level, false); break; } } - private void createSetterForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists) { - + private void createSetterForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { for (JavacNode fieldNode : fieldNodes) { - createSetterForField(level, fieldNode, errorNode, whineIfExists); + createSetterForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); } } - private void createSetterForField(AccessLevel level, - JavacNode fieldNode, JavacNode source, boolean whineIfExists) { - + private void createSetterForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean whineIfExists, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { if (fieldNode.getKind() != Kind.FIELD) { fieldNode.addError("@Setter is only supported on a class or a field."); return; @@ -188,11 +190,11 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC); - JCMethodDecl createdSetter = createSetter(access, fieldNode, fieldNode.getTreeMaker(), source.get()); + JCMethodDecl createdSetter = createSetter(access, fieldNode, fieldNode.getTreeMaker(), source.get(), onMethod, onParam); injectMethod(fieldNode.up(), createdSetter); } - private JCMethodDecl createSetter(long access, JavacNode field, TreeMaker treeMaker, JCTree source) { + private JCMethodDecl createSetter(long access, JavacNode field, TreeMaker treeMaker, JCTree source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { String setterName = toSetterName(field); boolean returnThis = shouldReturnThis(field); if (setterName == null) return null; @@ -207,7 +209,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { List<JCAnnotation> nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); Name methodName = field.toName(setterName); - List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); + List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables); JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); @@ -241,10 +243,11 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { List<JCExpression> throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; - List<JCAnnotation> annsOnMethod = List.nil(); + List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod); if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil())); } + return recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source); } diff --git a/src/core/lombok/javac/handlers/HandleWither.java b/src/core/lombok/javac/handlers/HandleWither.java index 64011f91..ba5aa72d 100644 --- a/src/core/lombok/javac/handlers/HandleWither.java +++ b/src/core/lombok/javac/handlers/HandleWither.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Project Lombok Authors. + * Copyright (C) 2012-2013 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 @@ -109,16 +109,12 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { * @param pos The node responsible for generating the wither (the {@code @Value} or {@code @Wither} annotation). */ public void generateWitherForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level) { - for (JavacNode child : fieldNode.down()) { - if (child.getKind() == Kind.ANNOTATION) { - if (annotationTypeMatches(Wither.class, child)) { - //The annotation will make it happen, so we can skip it. - return; - } - } + if (hasAnnotation(Wither.class, fieldNode)) { + //The annotation will make it happen, so we can skip it. + return; } - createWitherForField(level, fieldNode, fieldNode, false); + createWitherForField(level, fieldNode, fieldNode, false, List.<JCAnnotation>nil(), List.<JCAnnotation>nil()); } @Override public void handle(AnnotationValues<Wither> annotation, JCAnnotation ast, JavacNode annotationNode) { @@ -130,25 +126,28 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { if (level == AccessLevel.NONE || node == null) return; + List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode); + List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode); + switch (node.getKind()) { case FIELD: - createWitherForFields(level, fields, annotationNode, true); + createWitherForFields(level, fields, annotationNode, true, onMethod, onParam); break; case TYPE: + if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Wither on a type."); + if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Wither on a type."); generateWitherForType(node, annotationNode, level, false); break; } } - private void createWitherForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists) { + private void createWitherForFields(AccessLevel level, Collection<JavacNode> fieldNodes, JavacNode errorNode, boolean whineIfExists, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { for (JavacNode fieldNode : fieldNodes) { - createWitherForField(level, fieldNode, errorNode, whineIfExists); + createWitherForField(level, fieldNode, errorNode, whineIfExists, onMethod, onParam); } } - private void createWitherForField(AccessLevel level, - JavacNode fieldNode, JavacNode source, boolean whineIfExists) { - + private void createWitherForField(AccessLevel level, JavacNode fieldNode, JavacNode source, boolean whineIfExists, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { if (fieldNode.getKind() != Kind.FIELD) { fieldNode.addError("@Wither is only supported on a class or a field."); return; @@ -197,11 +196,11 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { long access = toJavacModifier(level); - JCMethodDecl createdWither = createWither(access, fieldNode, fieldNode.getTreeMaker(), source.get()); + JCMethodDecl createdWither = createWither(access, fieldNode, fieldNode.getTreeMaker(), source.get(), onMethod, onParam); injectMethod(fieldNode.up(), createdWither); } - private JCMethodDecl createWither(long access, JavacNode field, TreeMaker treeMaker, JCTree source) { + private JCMethodDecl createWither(long access, JavacNode field, TreeMaker treeMaker, JCTree source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) { String witherName = toWitherName(field); if (witherName == null) return null; @@ -212,7 +211,7 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { List<JCAnnotation> nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); Name methodName = field.toName(witherName); - List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); + List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables); JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); @@ -260,7 +259,8 @@ public class HandleWither extends JavacAnnotationHandler<Wither> { List<JCExpression> throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; - List<JCAnnotation> annsOnMethod = List.nil(); + List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod); + if (isFieldDeprecated(field)) { annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil())); } diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index ad3e4a17..c2de5b05 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009-2012 The Project Lombok Authors. + * Copyright (C) 2009-2013 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 @@ -63,8 +63,8 @@ import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCStatement; -import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCTypeApply; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; @@ -920,33 +920,77 @@ public class JavacHandlerUtil { return problematic.toList(); } - static List<JCExpression> getAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName) { + static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode errorNode) { ListBuffer<JCExpression> params = ListBuffer.lb(); - List<JCExpression> result = List.nil(); + ListBuffer<JCAnnotation> result = ListBuffer.lb(); + errorNode.removeDeferredErrors(); + + outer: for (JCExpression param : ast.args) { + String nameOfParam = "value"; + JCExpression valueOfParam = null; if (param instanceof JCAssign) { JCAssign assign = (JCAssign) param; if (assign.lhs instanceof JCIdent) { JCIdent ident = (JCIdent) assign.lhs; - if (parameterName.equals(ident.name.toString())) { - if (assign.rhs instanceof JCNewArray) { - result = ((JCNewArray) assign.rhs).elems; + nameOfParam = ident.name.toString(); + } + valueOfParam = assign.rhs; + } + + if (!parameterName.equals(nameOfParam)) { + params.append(param); + continue outer; + } + + if (valueOfParam instanceof JCAnnotation) { + String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString(); + dummyAnnotationName = dummyAnnotationName.replace("_", ""); + if (dummyAnnotationName.length() > 0) { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + continue outer; + } + for (JCExpression expr : ((JCAnnotation) valueOfParam).args) { + if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) { + JCIdent id = (JCIdent) ((JCAssign) expr).lhs; + if ("value".equals(id.name.toString())) { + expr = ((JCAssign) expr).rhs; } else { - result = result.append(assign.rhs); + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + continue outer; } - continue; + } + + if (expr instanceof JCAnnotation) { + result.append((JCAnnotation) expr); + } else if (expr instanceof JCNewArray) { + for (JCExpression expr2 : ((JCNewArray) expr).elems) { + if (expr2 instanceof JCAnnotation) { + result.append((JCAnnotation) expr2); + } else { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + continue outer; + } + } + } else { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + continue outer; } } + } else { + if (valueOfParam instanceof JCNewArray && ((JCNewArray) valueOfParam).elems.isEmpty()) { + // Then we just remove it and move on (it's onMethod={} for example). + } else { + errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))"); + } } - - params.append(param); } ast.args = params.toList(); - return result; + return result.toList(); } - static List<JCAnnotation> copyAnnotations(List<JCExpression> in) { + static List<JCAnnotation> copyAnnotations(List<? extends JCExpression> in) { ListBuffer<JCAnnotation> out = ListBuffer.lb(); for (JCExpression expr : in) { if (!(expr instanceof JCAnnotation)) continue; |