diff options
Diffstat (limited to 'src')
10 files changed, 282 insertions, 35 deletions
diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index c313cf51..072b6df2 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -2601,25 +2601,25 @@ public class EclipseHandlerUtil { applyAnnotationToMethodDecl(typeNode, mth, lib.getNonNullAnnotation(), lib.isTypeUse()); } - public static void createRelevantNullableAnnotation(EclipseNode typeNode, Argument arg) { + public static void createRelevantNullableAnnotation(EclipseNode typeNode, Argument arg, MethodDeclaration mth) { NullAnnotationLibrary lib = typeNode.getAst().readConfiguration(ConfigurationKeys.ADD_NULL_ANNOTATIONS); if (lib == null) return; - applyAnnotationToVarDecl(typeNode, arg, lib.getNullableAnnotation(), lib.isTypeUse()); + applyAnnotationToVarDecl(typeNode, arg, mth, lib.getNullableAnnotation(), lib.isTypeUse()); } - public static void createRelevantNullableAnnotation(EclipseNode typeNode, Argument arg, List<NullAnnotationLibrary> applied) { + public static void createRelevantNullableAnnotation(EclipseNode typeNode, Argument arg, MethodDeclaration mth, List<NullAnnotationLibrary> applied) { NullAnnotationLibrary lib = typeNode.getAst().readConfiguration(ConfigurationKeys.ADD_NULL_ANNOTATIONS); if (lib == null || applied.contains(lib)) return; - applyAnnotationToVarDecl(typeNode, arg, lib.getNullableAnnotation(), lib.isTypeUse()); + applyAnnotationToVarDecl(typeNode, arg, mth, lib.getNullableAnnotation(), lib.isTypeUse()); } - public static void createRelevantNonNullAnnotation(EclipseNode typeNode, Argument arg) { + public static void createRelevantNonNullAnnotation(EclipseNode typeNode, Argument arg, MethodDeclaration mth) { NullAnnotationLibrary lib = typeNode.getAst().readConfiguration(ConfigurationKeys.ADD_NULL_ANNOTATIONS); if (lib == null) return; - applyAnnotationToVarDecl(typeNode, arg, lib.getNonNullAnnotation(), lib.isTypeUse()); + applyAnnotationToVarDecl(typeNode, arg, mth, lib.getNonNullAnnotation(), lib.isTypeUse()); } private static void applyAnnotationToMethodDecl(EclipseNode typeNode, MethodDeclaration mth, String annType, boolean typeUse) { @@ -2653,9 +2653,10 @@ public class EclipseHandlerUtil { } a[0] = ann; mth.returnType.annotations[len - 1] = a; + mth.bits |= Eclipse.HasTypeAnnotations; } } - private static void applyAnnotationToVarDecl(EclipseNode typeNode, Argument arg, String annType, boolean typeUse) { + private static void applyAnnotationToVarDecl(EclipseNode typeNode, Argument arg, MethodDeclaration mth, String annType, boolean typeUse) { if (annType == null) return; int partCount = 1; @@ -2686,6 +2687,9 @@ public class EclipseHandlerUtil { } a[0] = ann; arg.type.annotations[len - 1] = a; + arg.type.bits |= Eclipse.HasTypeAnnotations; + arg.bits |= Eclipse.HasTypeAnnotations; + mth.bits |= Eclipse.HasTypeAnnotations; } } @@ -2770,15 +2774,7 @@ public class EclipseHandlerUtil { * Returns {@code true} if the provided node supports static methods and types (top level or static class) */ public static boolean isStaticAllowed(EclipseNode typeNode) { - boolean staticAllowed = true; - - while (typeNode.getKind() != Kind.COMPILATION_UNIT) { - if (!staticAllowed) return false; - - staticAllowed = typeNode.isStatic(); - typeNode = typeNode.up(); - } - return true; + return typeNode.isStatic() || typeNode.up() == null || typeNode.up().getKind() == Kind.COMPILATION_UNIT || isRecord(typeNode); } public static AbstractVariableDeclaration[] getRecordComponents(TypeDeclaration typeDeclaration) { diff --git a/src/core/lombok/eclipse/handlers/EclipseSingularsRecipes.java b/src/core/lombok/eclipse/handlers/EclipseSingularsRecipes.java index 998c1274..54f1a551 100755 --- a/src/core/lombok/eclipse/handlers/EclipseSingularsRecipes.java +++ b/src/core/lombok/eclipse/handlers/EclipseSingularsRecipes.java @@ -44,6 +44,7 @@ import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.MessageSend; +import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; @@ -430,7 +431,7 @@ public class EclipseSingularsRecipes { } } - protected void nullBehaviorize(EclipseNode typeNode, SingularData data, List<Statement> statements, Argument arg) { + protected void nullBehaviorize(EclipseNode typeNode, SingularData data, List<Statement> statements, Argument arg, MethodDeclaration md) { boolean ignoreNullCollections = data.isIgnoreNullCollections(); if (ignoreNullCollections) { @@ -439,11 +440,11 @@ public class EclipseSingularsRecipes { b.statements = statements.toArray(new Statement[statements.size()]); statements.clear(); statements.add(new IfStatement(isNotNull, b, 0, 0)); - EclipseHandlerUtil.createRelevantNullableAnnotation(typeNode, arg); + EclipseHandlerUtil.createRelevantNullableAnnotation(typeNode, arg, md); return; } - EclipseHandlerUtil.createRelevantNonNullAnnotation(typeNode, arg); + EclipseHandlerUtil.createRelevantNonNullAnnotation(typeNode, arg, md); Statement nullCheck = EclipseHandlerUtil.generateNullCheck(null, data.getPluralName(), typeNode, "%s cannot be null"); statements.add(0, nullCheck); } diff --git a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java index 940612e7..b0e0e526 100755 --- a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java @@ -642,13 +642,17 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; QualifiedTypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p }); - if (onParamTypeNullable != null) objectRef.annotations = new Annotation[][] {null, null, onParamTypeNullable}; + if (onParamTypeNullable != null) { + objectRef.annotations = new Annotation[][] {null, null, onParamTypeNullable}; + objectRef.bits |= Eclipse.HasTypeAnnotations; + method.bits |= Eclipse.HasTypeAnnotations; + } setGeneratedBy(objectRef, source); method.arguments = new Argument[] {new Argument(new char[] { 'o' }, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; if (!onParam.isEmpty() || onParamNullable != null) method.arguments[0].annotations = copyAnnotations(source, onParam.toArray(new Annotation[0]), onParamNullable); - EclipseHandlerUtil.createRelevantNullableAnnotation(type, method.arguments[0], applied); + EclipseHandlerUtil.createRelevantNullableAnnotation(type, method.arguments[0], method, applied); setGeneratedBy(method.arguments[0], source); List<Statement> statements = new ArrayList<Statement>(); @@ -898,7 +902,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH method.arguments = new Argument[] {new Argument(otherName, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; if (!onParam.isEmpty()) method.arguments[0].annotations = onParam.toArray(new Annotation[0]); - EclipseHandlerUtil.createRelevantNullableAnnotation(type, method.arguments[0]); + EclipseHandlerUtil.createRelevantNullableAnnotation(type, method.arguments[0], method); setGeneratedBy(method.arguments[0], source); SingleNameReference otherRef = new SingleNameReference(otherName, p); diff --git a/src/core/lombok/eclipse/handlers/HandleWithBy.java b/src/core/lombok/eclipse/handlers/HandleWithBy.java index 5ab3cf81..bfba91d4 100644 --- a/src/core/lombok/eclipse/handlers/HandleWithBy.java +++ b/src/core/lombok/eclipse/handlers/HandleWithBy.java @@ -373,7 +373,7 @@ public class HandleWithBy extends EclipseAnnotationHandler<WithBy> { method.statements = statements.toArray(new Statement[0]); } - createRelevantNonNullAnnotation(sourceNode, param); + createRelevantNonNullAnnotation(sourceNode, param, method); createRelevantNonNullAnnotation(fieldNode, method); method.traverse(new SetGeneratedByVisitor(source), parent.scope); diff --git a/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSingularizer.java b/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSingularizer.java index 47822ff3..a43e0331 100755 --- a/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSingularizer.java +++ b/src/core/lombok/eclipse/handlers/singulars/EclipseGuavaSingularizer.java @@ -207,7 +207,7 @@ abstract class EclipseGuavaSingularizer extends EclipseSingularizer { paramType = addTypeArgs(getTypeArgumentsCount(), true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, ClassFileConstants.AccFinal); - nullBehaviorize(builderType, data, statements, param); + nullBehaviorize(builderType, data, statements, param, md); if (returnStatement != null) statements.add(returnStatement); diff --git a/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSetSingularizer.java b/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSetSingularizer.java index fbde3021..810a7878 100755 --- a/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSetSingularizer.java +++ b/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilListSetSingularizer.java @@ -184,7 +184,7 @@ abstract class EclipseJavaUtilListSetSingularizer extends EclipseJavaUtilSingula paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, ClassFileConstants.AccFinal); - nullBehaviorize(builderType, data, statements, param); + nullBehaviorize(builderType, data, statements, param, md); if (returnStatement != null) statements.add(returnStatement); md.statements = statements.toArray(new Statement[0]); diff --git a/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilMapSingularizer.java b/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilMapSingularizer.java index 859cce94..16ed2d44 100755 --- a/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilMapSingularizer.java +++ b/src/core/lombok/eclipse/handlers/singulars/EclipseJavaUtilMapSingularizer.java @@ -316,7 +316,7 @@ public class EclipseJavaUtilMapSingularizer extends EclipseJavaUtilSingularizer paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs()); Argument param = new Argument(data.getPluralName(), 0, paramType, ClassFileConstants.AccFinal); - nullBehaviorize(builderType, data, statements, param); + nullBehaviorize(builderType, data, statements, param, md); if (returnStatement != null) statements.add(returnStatement); diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index 53a518b4..b17e34d8 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -2096,15 +2096,7 @@ public class JavacHandlerUtil { * Returns {@code true} if the provided node supports static methods and types (top level or static class) */ public static boolean isStaticAllowed(JavacNode typeNode) { - boolean staticAllowed = true; - - while (typeNode.getKind() != Kind.COMPILATION_UNIT) { - if (!staticAllowed) return false; - - staticAllowed = typeNode.isStatic(); - typeNode = typeNode.up(); - } - return true; + return typeNode.isStatic() || typeNode.up() == null || typeNode.up().getKind() == Kind.COMPILATION_UNIT || isRecord(typeNode); } public static JavacNode upToTypeNode(JavacNode node) { diff --git a/src/eclipseAgent/lombok/eclipse/agent/MavenEcjBootstrapApp.java b/src/eclipseAgent/lombok/eclipse/agent/MavenEcjBootstrapApp.java new file mode 100644 index 00000000..7f9d4d36 --- /dev/null +++ b/src/eclipseAgent/lombok/eclipse/agent/MavenEcjBootstrapApp.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2022 The Project Lombok Authors. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.eclipse.agent; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.List; + +import com.zwitserloot.cmdreader.CmdReader; +import com.zwitserloot.cmdreader.Description; +import com.zwitserloot.cmdreader.InvalidCommandLineException; +import com.zwitserloot.cmdreader.Shorthand; + +import lombok.core.LombokApp; +import lombok.spi.Provides; + +@Provides +public class MavenEcjBootstrapApp extends LombokApp { + @Override public String getAppName() { + return "createMavenECJBootstrap"; + } + + @Override public String getAppDescription() { + return "Creates .mvn/jvm.config and .mvn/lombok-bootstrap.jar for\n" + + "use with the ECJ compiler."; + } + + private static class CmdArgs { + @Shorthand("w") + @Description("Overwrite existing files. Defaults to false.") + boolean overwrite = false; + + @Shorthand("o") + @Description("The root of a Maven project. Defaults to the current working directory.") + String output; + + @Shorthand({"h", "?"}) + @Description("Shows this help text") + boolean help; + } + + @Override public int runApp(List<String> rawArgs) throws Exception { + CmdReader<CmdArgs> reader = CmdReader.of(CmdArgs.class); + CmdArgs args; + try { + args = reader.make(rawArgs.toArray(new String[0])); + } catch (InvalidCommandLineException e) { + printHelp(reader, e.getMessage(), System.err); + return 1; + } + + if (args.help) { + printHelp(reader, null, System.out); + return 0; + } + + return createBootstrap(args.output, args.overwrite); + } + + private int createBootstrap(String root, boolean overwrite) { + File mvn = new File(root, ".mvn"); + int result = 0; + if (result == 0) result = makeMvn(mvn); + if (result == 0) result = makeJvmConfig(mvn, overwrite); + if (result == 0) result = makeJar(mvn, overwrite); + return result; + } + + private int makeMvn(File mvn) { + int result = 0; + Exception err = null; + try { + if (!mvn.exists() && !mvn.mkdirs()) result = 1; + } catch (Exception e) { + result = 1; + err = e; + } + if (result != 0) { + System.err.println("Could not create " + mvn.getPath()); + if (err != null) err.printStackTrace(System.err); + } + return result; + } + + private int makeJvmConfig(File mvn, boolean overwrite) { + File jvmConfig = new File(mvn, "jvm.config"); + if (jvmConfig.exists() && !overwrite) { + System.err.println(canonical(jvmConfig) + " exists but '-w' not specified."); + return 1; + } + try { + FileWriter writer = new FileWriter(jvmConfig); + writer.write("-javaagent:.mvn/lombok-bootstrap.jar"); + writer.flush(); + writer.close(); + System.out.println("Successfully created: " + canonical(jvmConfig)); + return 0; + } catch (Exception e) { + System.err.println("Could not create: " + canonical(jvmConfig)); + e.printStackTrace(System.err); + return 1; + } + } + + private int makeJar(File mvn, boolean overwrite) { + File jar = new File(mvn, "lombok-bootstrap.jar"); + if (jar.exists() && !overwrite) { + System.err.println(canonical(jar) + " but '-w' not specified."); + return 1; + } + try { + InputStream input = MavenEcjBootstrapApp.class.getResourceAsStream("/lombok/launch/mavenEcjBootstrapAgent.jar"); + FileOutputStream output = new FileOutputStream(jar); + try { + byte[] buffer = new byte[4096]; + int length; + while ((length = input.read(buffer)) > 0) output.write(buffer, 0, length); + output.flush(); + output.close(); + System.out.println("Successfully created: " + canonical(jar)); + return 0; + } finally { + try { + output.close(); + } catch (Exception ignore) {} + } + } catch (Exception e) { + System.err.println("Could not create: " + canonical(jar)); + e.printStackTrace(System.err); + return 1; + } + } + + private static String canonical(File out) { + try { + return out.getCanonicalPath(); + } catch (Exception e) { + return out.getAbsolutePath(); + } + } + + private void printHelp(CmdReader<CmdArgs> reader, String message, PrintStream out) { + if (message != null) { + out.println(message); + out.println("----------------------------"); + } + out.println(reader.generateCommandLineHelp("java -jar lombok.jar createMavenECJBootstrap")); + } +} diff --git a/src/mavenEcjBootstrapAgent/lombok/launch/MavenEcjBootstrapAgent.java b/src/mavenEcjBootstrapAgent/lombok/launch/MavenEcjBootstrapAgent.java new file mode 100644 index 00000000..b36e591f --- /dev/null +++ b/src/mavenEcjBootstrapAgent/lombok/launch/MavenEcjBootstrapAgent.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2022 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.launch; + +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.lang.instrument.Instrumentation; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.ProtectionDomain; +import java.util.jar.JarFile; + +/** + * This Java agent does not transform bytecode, but acts as a watcher that can + * figure out when it is appropriate to load Lombok itself within a Maven + * execution. + * + * It relies on several facts: + * <ul> + * <li>maven-compiler-plugin contains an {@code AbstractCompilerMojo} class that + * compiler instances extend. + * <li>Maven loaders are {@code ClassRealms}, which extend {@code URLClassLoader}. + * <li>Each plugin dependency in the <em>pom.xml </em>is represented as a file URL on the + * ClassRealm that points to the artifact. + * <li>URLs to Maven artifacts contain the group and artifact ids + * ({@code [...]/groupid/artifactid/ver/artifactid-ver.jar}). + * <li>The Lombok Java agent class is {@code lombok.launch.Agent}. + * </ul> + * Given all of the above, the transformer simply waits for {@code AbstractCompilerMojo} + * to be loaded, then uses the loader to find the path to the Lombok jar file, + * and finally loads the Lombok agent using reflection. + */ +public final class MavenEcjBootstrapAgent { + private static final String MAVEN_COMPILER_TRIGGER_CLASS = "org/apache/maven/plugin/compiler/AbstractCompilerMojo"; + private static final String LOMBOK_URL_IDENTIFIER = "/org/projectlombok/lombok/"; + private static final String LOMBOK_AGENT_CLASS = "lombok.launch.Agent"; + private static final byte[] NOT_TRANSFORMED = null; + + private MavenEcjBootstrapAgent() {} + + public static void premain(final String agentArgs, final Instrumentation instrumentation) { + instrumentation.addTransformer(new ClassFileTransformer() { + @Override public byte[] transform(final ClassLoader loader, final String className, final Class<?> cbr, final ProtectionDomain pd, final byte[] cfb) throws IllegalClassFormatException { + if (MAVEN_COMPILER_TRIGGER_CLASS.equals(className)) { + for (final URL url : ((URLClassLoader) loader).getURLs()) { + if (url.getPath().contains(LOMBOK_URL_IDENTIFIER)) { + try { + instrumentation.appendToSystemClassLoaderSearch(new JarFile(url.getPath())); + MavenEcjBootstrapAgent.class.getClassLoader().loadClass(LOMBOK_AGENT_CLASS).getDeclaredMethod("premain", String.class, Instrumentation.class).invoke(null, agentArgs, instrumentation); + instrumentation.removeTransformer(this); + break; + } catch (Exception e) { + // There are no appropriate loggers available at + // this point in time. + e.printStackTrace(System.err); + } + } + } + } + return NOT_TRANSFORMED; + } + }); + } +} |