From 63ea3db6b7ab41ff945cad1ec8af7f78b5679f66 Mon Sep 17 00:00:00 2001 From: ttzn Date: Sat, 26 Dec 2020 13:13:24 +0100 Subject: @StandardException feature working draft * annotation with javac and Eclipse handlers * single test file --- .../javac/handlers/HandleStandardException.java | 216 +++++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 src/core/lombok/javac/handlers/HandleStandardException.java (limited to 'src/core/lombok/javac/handlers/HandleStandardException.java') diff --git a/src/core/lombok/javac/handlers/HandleStandardException.java b/src/core/lombok/javac/handlers/HandleStandardException.java new file mode 100644 index 00000000..6a382788 --- /dev/null +++ b/src/core/lombok/javac/handlers/HandleStandardException.java @@ -0,0 +1,216 @@ +/* + * Copyright (C) 2010-2019 The Project Lombok Authors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.javac.handlers; + +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import com.sun.tools.javac.util.Name; +import lombok.AccessLevel; +import lombok.ConfigurationKeys; +import lombok.StandardException; +import lombok.core.AST.Kind; +import lombok.core.AnnotationValues; +import lombok.delombok.LombokOptionsFactory; +import lombok.javac.Javac; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.JavacHandlerUtil.*; +import org.mangosdk.spi.ProviderFor; + +import static lombok.core.handlers.HandlerUtil.handleFlagUsage; +import static lombok.javac.Javac.CTC_VOID; +import static lombok.javac.handlers.JavacHandlerUtil.*; + +@ProviderFor(JavacAnnotationHandler.class) +public class HandleStandardException extends JavacAnnotationHandler { + private static final String NAME = StandardException.class.getSimpleName(); + + @Override + public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { + handleFlagUsage(annotationNode, ConfigurationKeys.STANDARD_EXCEPTION_FLAG_USAGE, "@StandardException"); + deleteAnnotationIfNeccessary(annotationNode, StandardException.class); + JavacNode typeNode = annotationNode.up(); + if (!checkLegality(typeNode, annotationNode)) return; + + SuperParameter messageField = new SuperParameter("message", typeNode.getSymbolTable().stringType); + SuperParameter causeField = new SuperParameter("cause", typeNode.getSymbolTable().throwableType); + + boolean skip = true; + generateConstructor(typeNode, AccessLevel.PUBLIC, List.nil(), skip, annotationNode); + generateConstructor(typeNode, AccessLevel.PUBLIC, List.of(messageField), skip, annotationNode); + generateConstructor(typeNode, AccessLevel.PUBLIC, List.of(causeField), skip, annotationNode); + generateConstructor(typeNode, AccessLevel.PUBLIC, List.of(messageField, causeField), skip, annotationNode); + } + + private static boolean checkLegality(JavacNode typeNode, JavacNode errorNode) { + JCClassDecl typeDecl = null; + if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get(); + long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags; + boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0; + + if (typeDecl == null || notAClass) { + errorNode.addError(NAME + " is only supported on a class or an enum."); + return false; + } + + return true; + } + + public void generateConstructor(JavacNode typeNode, AccessLevel level, List fields, + boolean skipIfConstructorExists, JavacNode source) { + generate(typeNode, level, fields, skipIfConstructorExists, source); + } + + private void generate(JavacNode typeNode, AccessLevel level, List fields, boolean skipIfConstructorExists, + JavacNode source) { + ListBuffer argTypes = new ListBuffer(); + for (SuperParameter field : fields) { + Type mirror = field.type; + if (mirror == null) { + argTypes = null; + break; + } + argTypes.append(mirror); + } + List argTypes_ = argTypes == null ? null : argTypes.toList(); + + if (!(skipIfConstructorExists && constructorExists(typeNode, fields) != MemberExistsResult.NOT_EXISTS)) { + JCMethodDecl constr = createConstructor(level, typeNode, fields, source); + injectMethod(typeNode, constr, argTypes_, Javac.createVoidType(typeNode.getSymbolTable(), CTC_VOID)); + } + } + + public static MemberExistsResult constructorExists(JavacNode node, List parameters) { + node = upToTypeNode(node); + + if (node != null && node.get() instanceof JCClassDecl) { + for (JCTree def : ((JCClassDecl) node.get()).defs) { + if (def instanceof JCMethodDecl) { + JCMethodDecl md = (JCMethodDecl) def; + if (md.name.contentEquals("") && (md.mods.flags & Flags.GENERATEDCONSTR) == 0) { + if (!paramsMatch(md.params, parameters)) continue; + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + } + } + } + } + + return MemberExistsResult.NOT_EXISTS; + } + + private static boolean paramsMatch(List params, List superParams) { + if (params == null) { + return superParams.size() == 0; + } else if (params.size() != superParams.size()) { + return false; + } else { + for (int i = 0; i < superParams.size(); i++) { + SuperParameter field = superParams.get(i); + JCVariableDecl param = params.get(i); + if (!param.getType().type.equals(field.type)) + return false; + } + } + + return true; + } + + public static void addConstructorProperties(JCModifiers mods, JavacNode node, List fields) { + if (fields.isEmpty()) return; + JavacTreeMaker maker = node.getTreeMaker(); + JCExpression constructorPropertiesType = chainDots(node, "java", "beans", "ConstructorProperties"); + ListBuffer fieldNames = new ListBuffer(); + for (SuperParameter field : fields) { + Name fieldName = node.toName(field.name); + fieldNames.append(maker.Literal(fieldName.toString())); + } + JCExpression fieldNamesArray = maker.NewArray(null, List.nil(), fieldNames.toList()); + JCAnnotation annotation = maker.Annotation(constructorPropertiesType, List.of(fieldNamesArray)); + mods.annotations = mods.annotations.append(annotation); + } + + @SuppressWarnings("deprecation") public static JCMethodDecl createConstructor(AccessLevel level, JavacNode typeNode, + List fieldsToParam, JavacNode source) { + JavacTreeMaker maker = typeNode.getTreeMaker(); + + boolean isEnum = (((JCClassDecl) typeNode.get()).mods.flags & Flags.ENUM) != 0; + if (isEnum) level = AccessLevel.PRIVATE; + + boolean addConstructorProperties; + + if (fieldsToParam.isEmpty()) { + addConstructorProperties = false; + } else { + Boolean v = typeNode.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_ADD_CONSTRUCTOR_PROPERTIES); + addConstructorProperties = v != null ? v.booleanValue() : + Boolean.FALSE.equals(typeNode.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES)); + } + + ListBuffer params = new ListBuffer(); + ListBuffer superArgs = new ListBuffer(); + + for (SuperParameter fieldNode : fieldsToParam) { + Name fieldName = source.toName(fieldNode.name); + long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext()); + JCExpression pType = maker.getUnderlyingTreeMaker().Ident(fieldNode.type.tsym); + JCVariableDecl param = maker.VarDef(maker.Modifiers(flags), fieldName, pType, null); + params.append(param); + superArgs.append(maker.Ident(fieldName)); + } + + ListBuffer statements = new ListBuffer(); + JCMethodInvocation callToSuper = maker.Apply(List.nil(), + maker.Ident(typeNode.toName("super")), + superArgs.toList()); + statements.add(maker.Exec(callToSuper)); + + JCModifiers mods = maker.Modifiers(toJavacModifier(level), List.nil()); + if (addConstructorProperties && !isLocalType(typeNode) && LombokOptionsFactory.getDelombokOptions(typeNode.getContext()).getFormatPreferences().generateConstructorProperties()) { + addConstructorProperties(mods, typeNode, fieldsToParam); + } + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(""), + null, List.nil(), params.toList(), List.nil(), + maker.Block(0L, statements.toList()), null), source.get(), typeNode.getContext()); + } + + public static boolean isLocalType(JavacNode type) { + Kind kind = type.up().getKind(); + if (kind == Kind.COMPILATION_UNIT) return false; + if (kind == Kind.TYPE) return isLocalType(type.up()); + return true; + } + + private static class SuperParameter { + private final String name; + private final Type type; + + private SuperParameter(String name, Type type) { + this.name = name; + this.type = type; + } + } +} -- cgit From af16ba23cd46fa3d3b096daa8d725df2b4d78976 Mon Sep 17 00:00:00 2001 From: ttzn Date: Wed, 24 Mar 2021 23:52:08 +0100 Subject: @StandardException feature working draft * move feature under experimental * replace ProviderFor with Provides * add doc material (to be completed) * add author --- AUTHORS | 1 + src/core/lombok/StandardException.java | 34 -------------------- .../eclipse/handlers/HandleStandardException.java | 8 ++--- .../lombok/experimental/StandardException.java | 34 ++++++++++++++++++++ .../javac/handlers/HandleStandardException.java | 9 +++--- .../resource/before/StandardExceptions.java | 6 ++-- .../features/experimental/StandardException.html | 36 ++++++++++++++++++++++ website/templates/features/experimental/index.html | 4 +++ .../StandardExceptionExample_post.jpage | 16 ++++++++++ .../StandardExceptionExample_pre.jpage | 5 +++ 10 files changed, 107 insertions(+), 46 deletions(-) delete mode 100644 src/core/lombok/StandardException.java create mode 100644 src/core/lombok/experimental/StandardException.java create mode 100644 website/templates/features/experimental/StandardException.html create mode 100644 website/usageExamples/StandardExceptionExample_post.jpage create mode 100644 website/usageExamples/StandardExceptionExample_pre.jpage (limited to 'src/core/lombok/javac/handlers/HandleStandardException.java') diff --git a/AUTHORS b/AUTHORS index f152f0c7..547246d9 100755 --- a/AUTHORS +++ b/AUTHORS @@ -2,6 +2,7 @@ Lombok contributors in alphabetical order: Adam Juraszek Aleksandr Zhelezniak +Amine Touzani Andre Brait Bulgakov Alexander Caleb Brinkman diff --git a/src/core/lombok/StandardException.java b/src/core/lombok/StandardException.java deleted file mode 100644 index 0456a649..00000000 --- a/src/core/lombok/StandardException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2010-2017 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; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.SOURCE) -public @interface StandardException { -} diff --git a/src/core/lombok/eclipse/handlers/HandleStandardException.java b/src/core/lombok/eclipse/handlers/HandleStandardException.java index 9996f4fa..e7f25edb 100755 --- a/src/core/lombok/eclipse/handlers/HandleStandardException.java +++ b/src/core/lombok/eclipse/handlers/HandleStandardException.java @@ -23,16 +23,16 @@ package lombok.eclipse.handlers; import lombok.AccessLevel; import lombok.ConfigurationKeys; -import lombok.StandardException; +import lombok.experimental.StandardException; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.EclipseHandlerUtil.*; +import lombok.spi.Provides; import org.eclipse.jdt.internal.compiler.ast.*; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; -import org.mangosdk.spi.ProviderFor; import java.lang.reflect.Modifier; import java.util.*; @@ -42,7 +42,7 @@ import static lombok.eclipse.Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; import static lombok.eclipse.Eclipse.pos; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; -@ProviderFor(EclipseAnnotationHandler.class) +@Provides public class HandleStandardException extends EclipseAnnotationHandler { private static final String NAME = StandardException.class.getSimpleName(); @@ -175,12 +175,10 @@ public class HandleStandardException extends EclipseAnnotationHandler parameters, EclipseNode sourceNode) { - ASTNode source = sourceNode.get(); TypeDeclaration typeDeclaration = ((TypeDeclaration) type.get()); boolean isEnum = (((TypeDeclaration) type.get()).modifiers & ClassFileConstants.AccEnum) != 0; - if (isEnum) level = AccessLevel.PRIVATE; boolean addConstructorProperties; diff --git a/src/core/lombok/experimental/StandardException.java b/src/core/lombok/experimental/StandardException.java new file mode 100644 index 00000000..9f8a4e65 --- /dev/null +++ b/src/core/lombok/experimental/StandardException.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2010-2017 The Project Lombok Authors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.experimental; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.SOURCE) +public @interface StandardException { +} diff --git a/src/core/lombok/javac/handlers/HandleStandardException.java b/src/core/lombok/javac/handlers/HandleStandardException.java index 6a382788..598f1aa7 100644 --- a/src/core/lombok/javac/handlers/HandleStandardException.java +++ b/src/core/lombok/javac/handlers/HandleStandardException.java @@ -30,7 +30,7 @@ import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import lombok.AccessLevel; import lombok.ConfigurationKeys; -import lombok.StandardException; +import lombok.experimental.StandardException; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.delombok.LombokOptionsFactory; @@ -39,13 +39,13 @@ import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.JavacHandlerUtil.*; -import org.mangosdk.spi.ProviderFor; +import lombok.spi.Provides; import static lombok.core.handlers.HandlerUtil.handleFlagUsage; import static lombok.javac.Javac.CTC_VOID; import static lombok.javac.handlers.JavacHandlerUtil.*; -@ProviderFor(JavacAnnotationHandler.class) +@Provides public class HandleStandardException extends JavacAnnotationHandler { private static final String NAME = StandardException.class.getSimpleName(); @@ -161,7 +161,6 @@ public class HandleStandardException extends JavacAnnotationHandler"), null, List.nil(), params.toList(), List.nil(), - maker.Block(0L, statements.toList()), null), source.get(), typeNode.getContext()); + maker.Block(0L, statements.toList()), null), source); } public static boolean isLocalType(JavacNode type) { diff --git a/test/transform/resource/before/StandardExceptions.java b/test/transform/resource/before/StandardExceptions.java index 7e4a3b93..939e1b6b 100644 --- a/test/transform/resource/before/StandardExceptions.java +++ b/test/transform/resource/before/StandardExceptions.java @@ -1,6 +1,8 @@ -@lombok.StandardException class EmptyException extends Exception { +import lombok.experimental.StandardException; + +@StandardException class EmptyException extends Exception { } -@lombok.StandardException class NoArgsException extends Exception { +@StandardException class NoArgsException extends Exception { public NoArgsException() { } } diff --git a/website/templates/features/experimental/StandardException.html b/website/templates/features/experimental/StandardException.html new file mode 100644 index 00000000..25324c4b --- /dev/null +++ b/website/templates/features/experimental/StandardException.html @@ -0,0 +1,36 @@ +<#import "../_features.html" as f> + +<@f.scaffold title="@StandardException" + logline="TODO"> + <@f.history> +

+ @StandardException was introduced as an experimental feature in lombok v1.18.21. +

+ + + <@f.overview> +

+ This annotation is intended to be used on subclasses of java.util.Throwable. For each of the four constructors in Throwable, it will generate a corresponding constructor in the target class, that simply forwards its argument to its super-counterpart. +

+ If any of those constructors is manually overriden, it is simply skipped. This allows applying special treatment such as annotations. +

+ + + <@f.snippets name="StandardException" /> + + <@f.confKeys> +
+ lombok.standardException.addConstructorProperties = [true | false] (default: false) +
+ lombok.standardException.flagUsage = [warning | error] (default: not set) +
+ Lombok will flag any usage of @StandardException as a warning or error if configured. +
+ + + <@f.smallPrint> +

+ Although such situation is unlikely to occur, this annotation can technically be applied to any class for which all four expected constructors are defined in a superclass. +

+ + diff --git a/website/templates/features/experimental/index.html b/website/templates/features/experimental/index.html index 32590815..34dd3bb4 100644 --- a/website/templates/features/experimental/index.html +++ b/website/templates/features/experimental/index.html @@ -75,6 +75,10 @@ <@main.feature title="@Jacksonized" href="Jacksonized"> Bob, meet Jackson. Lets make sure you become fast friends. + + <@main.feature title="@StandardException" href="StandardException"> + TODO + <@f.confKeys> diff --git a/website/usageExamples/StandardExceptionExample_post.jpage b/website/usageExamples/StandardExceptionExample_post.jpage new file mode 100644 index 00000000..148603a9 --- /dev/null +++ b/website/usageExamples/StandardExceptionExample_post.jpage @@ -0,0 +1,16 @@ +public class ExampleException extends Exception { + public ExampleException() { + } + + public ExampleException(String message) { + super(message); + } + + public ExampleException(Throwable cause) { + super(cause); + } + + public ExampleException(String message, Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/website/usageExamples/StandardExceptionExample_pre.jpage b/website/usageExamples/StandardExceptionExample_pre.jpage new file mode 100644 index 00000000..8d85286c --- /dev/null +++ b/website/usageExamples/StandardExceptionExample_pre.jpage @@ -0,0 +1,5 @@ +import lombok.experimental.StandardException; + +@StandardException +public class ExampleException extends Exception { +} \ No newline at end of file -- cgit