Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lombok support for java-11 #4769

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add lombok support for java-11
  • Loading branch information
amishra-u committed Dec 11, 2024
commit 481ef951805b40dd6ea58c992f8a3ec418d8a72a
1 change: 1 addition & 0 deletions rewrite-java-11/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ val javaTck = configurations.create("javaTck") {
dependencies {
api(project(":rewrite-core"))
api(project(":rewrite-java"))
runtimeOnly(project(":rewrite-java-lombok"))

compileOnly("org.slf4j:slf4j-api:1.7.+")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
Expand All @@ -44,19 +45,26 @@
import org.openrewrite.tree.ParsingEventListener;
import org.openrewrite.tree.ParsingExecutionContextView;

import javax.annotation.processing.Processor;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardLocation;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;

/**
Expand All @@ -77,6 +85,7 @@ public class ReloadableJava11Parser implements JavaParser {
private final JavaCompiler compiler;
private final ResettableLog compilerLog;
private final Collection<NamedStyles> styles;
private final List<Processor> annotationProcessors;

private ReloadableJava11Parser(boolean logCompilationWarningsAndErrors,
@Nullable Collection<Path> classpath,
Expand Down Expand Up @@ -106,6 +115,65 @@ private ReloadableJava11Parser(boolean logCompilationWarningsAndErrors,
Options.instance(context).put("-g", "-g");
Options.instance(context).put("-proc", "none");

LOMBOK:
if (System.getenv().getOrDefault("REWRITE_LOMBOK", System.getProperty("rewrite.lombok")) != null &&
classpath != null && classpath.stream().anyMatch(it -> it.toString().contains("lombok"))) {
Processor lombokProcessor = null;
try {
// https://projectlombok.org/contributing/lombok-execution-path
List<String> overrideClasspath = new ArrayList<>();
for (Path part : classpath) {
if (part.toString().contains("lombok")) {
overrideClasspath.add(part.toString());
}
}
// make sure the rewrite-java-lombok dependency comes first
boolean found = false;
for (int i = 0; i < overrideClasspath.size(); i++) {
if (overrideClasspath.get(i).contains("rewrite-java-lombok")) {
overrideClasspath.add(0, overrideClasspath.remove(i));
found = true;
}
}
if (!found) {
// try to find `rewrite-java-lombok` using class loader
URL resource = getClass().getClassLoader().getResource("org/openrewrite/java/lombok/OpenRewriteConfigurationKeysLoader.class");
if (resource != null && resource.getProtocol().equals("jar") && resource.getPath().startsWith("file:")) {
String path = Paths.get(URI.create(resource.getPath().substring(0, resource.getPath().indexOf("!")))).toString();
overrideClasspath.add(0, path);
} else {
break LOMBOK;
}
}
System.setProperty("shadow.override.lombok", String.join(File.pathSeparator, overrideClasspath));

Class<?> shadowLoaderClass = Class.forName("lombok.launch.ShadowClassLoader", true, getClass().getClassLoader());
Constructor<?> shadowLoaderConstructor = shadowLoaderClass.getDeclaredConstructor(
Class.forName("java.lang.ClassLoader"),
Class.forName("java.lang.String"),
Class.forName("java.lang.String"),
Class.forName("java.util.List"),
Class.forName("java.util.List"));
shadowLoaderConstructor.setAccessible(true);

ClassLoader lombokShadowLoader = (ClassLoader) shadowLoaderConstructor.newInstance(
getClass().getClassLoader(),
"lombok",
null,
emptyList(),
singletonList("lombok.patcher.Symbols")
);
lombokProcessor = (Processor) lombokShadowLoader.loadClass("lombok.core.AnnotationProcessor").getDeclaredConstructor().newInstance();
Options.instance(context).put(Option.PROCESSOR, "lombok.launch.AnnotationProcessorHider$AnnotationProcessor");
} catch (ReflectiveOperationException ignore) {
// Lombok was not found or could not be initialized
} finally {
annotationProcessors = lombokProcessor != null ? singletonList(lombokProcessor) : emptyList();
}
} else {
annotationProcessors = emptyList();
}

// MUST be created ahead of compiler construction
new TimedTodo(context);

Expand Down Expand Up @@ -191,37 +259,44 @@ LinkedHashMap<Input, JCTree.JCCompilationUnit> parseInputsToCompilerAst(Iterable
}

LinkedHashMap<Input, JCTree.JCCompilationUnit> cus = new LinkedHashMap<>();
acceptedInputs(sourceFiles).forEach(input1 -> {
List<ReloadableJava11ParserInputFileObject> inputFileObjects = acceptedInputs(sourceFiles)
.map(input -> new ReloadableJava11ParserInputFileObject(input, ctx))
.collect(Collectors.toList());
if (!annotationProcessors.isEmpty()) {
compiler.initProcessAnnotations(annotationProcessors, inputFileObjects, emptyList());
}
try {
//noinspection unchecked
com.sun.tools.javac.util.List<JCTree.JCCompilationUnit> jcCompilationUnits = compiler.parseFiles((List<JavaFileObject>) (List<?>) inputFileObjects);
for (int i = 0; i < inputFileObjects.size(); i++) {
cus.put(inputFileObjects.get(i).getInput(), jcCompilationUnits.get(i));
}
try {
JCTree.JCCompilationUnit jcCompilationUnit = compiler.parse(new ReloadableJava11ParserInputFileObject(input1, ctx));
cus.put(input1, jcCompilationUnit);
} catch (IllegalStateException e) {
if ("endPosTable already set".equals(e.getMessage())) {
throw new IllegalStateException(
"Call reset() on JavaParser before parsing another set of source files that " +
"have some of the same fully qualified names. Source file [" +
input1.getPath() + "]\n[\n" + StringUtils.readFully(input1.getSource(ctx), getCharset(ctx)) + "\n]", e);
initModules(cus.values());
enterAll(cus.values());

// For some reason this is necessary in JDK 9+, where the internal block counter that
// annotationsBlocked() tests against remains >0 after attribution.
Annotate annotate = Annotate.instance(context);
while (annotate.annotationsBlocked()) {
annotate.unblockAnnotations(); // also flushes once unblocked
}
if (!annotationProcessors.isEmpty()) {
compiler.processAnnotations(jcCompilationUnits, emptyList());
}
throw e;
compiler.attribute(compiler.todo);
} catch (Throwable t) {
// when symbol entering fails on problems like missing types, attribution can often times proceed
// unhindered, but it sometimes cannot (so attribution is always a BEST EFFORT in the presence of errors)
ctx.getOnError().accept(new JavaParsingException("Failed symbol entering or attribution", t));
}
});

try {
initModules(cus.values());
enterAll(cus.values());

// For some reason this is necessary in JDK 9+, where the internal block counter that
// annotationsBlocked() tests against remains >0 after attribution.
Annotate annotate = Annotate.instance(context);
while (annotate.annotationsBlocked()) {
annotate.unblockAnnotations(); // also flushes once unblocked
} catch (IllegalStateException e) {
if ("endPosTable already set".equals(e.getMessage())) {
throw new IllegalStateException(
"Call reset() on JavaParser before parsing another set of source files that " +
"have some of the same fully qualified names.", e);
}

compiler.attribute(compiler.todo);
} catch (Throwable t) {
// when symbol entering fails on problems like missing types, attribution can often times proceed
// unhindered, but it sometimes cannot (so attribution is always a BEST EFFORT in the presence of errors)
ctx.getOnError().accept(new JavaParsingException("Failed symbol entering or attribution", t));
throw e;
}
return cus;
}
Expand Down
Loading
Loading