дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
fix(java): compile annotation-generated sources incrementally (#8373)
The incremental Java build treated every generated source as the output of an aggregating processor, so any change recompiled the whole source set, and a deleted source left its generated sources and their classes behind. The build state now records the source javac names as each generated source's origin (JDK 18+): a change compiles that origin, which regenerates its generated sources and replaces their classes, dependents of a generated class compile its origin, and deleting the origin removes them. Files a processor writes without an origin (generated sources, classes, or resources such as META-INF/services that aggregating processors rewrite from the compiled sources alone) still make the next change compile the set from scratch. Covered by real-javac tests with an isolating and an aggregating processor. Co-authored-by: Lrxc <[email protected]>
Цей коміт міститься в:
1 джерело
7228d77a4f
коміт
71c5403e30
3 files changed
+279
-17
No files matched your search
@@ -86,9 +86,13 @@ pub(super) struct SetState {
|
||||
pub dirty: BTreeSet<PathBuf>,
|
||||
pub changes: Vec<ApiChange>,
|
||||
/// Sources annotation processors wrote, and other files they wrote without an originating
|
||||
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
|
||||
/// compiles the set from scratch.
|
||||
/// source (`META-INF/services`…): processors that aggregate. A generated source without a
|
||||
/// recorded origin, or a class file without a source, compiles the set from scratch.
|
||||
pub generated: Vec<PathBuf>,
|
||||
/// Generated source → the source javac names as its originating file (JDK 18+): the
|
||||
/// compilation that source changes regenerates the generated source with it.
|
||||
#[serde(default)]
|
||||
pub generated_origins: BTreeMap<PathBuf, PathBuf>,
|
||||
pub unowned: Vec<PathBuf>,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
@@ -140,7 +140,16 @@ impl JavaBuildService {
|
||||
changed.insert(src.clone());
|
||||
}
|
||||
Some(src) if removed.contains(src) => {}
|
||||
_ => {
|
||||
Some(src) => match previous.generated_origins.get(src) {
|
||||
Some(origin) if source_stamps.contains_key(origin) => {
|
||||
changed.insert(origin.clone());
|
||||
}
|
||||
_ => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
},
|
||||
None => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
@@ -151,10 +160,13 @@ impl JavaBuildService {
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
// Aggregating processors: any file they wrote without an origin (a generated source, a
|
||||
// class, or a resource such as `META-INF/services` or configuration metadata, which they
|
||||
// rewrite from the sources of the compilation alone) can't be followed class by class.
|
||||
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
|
||||
let from_scratch =
|
||||
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
|
||||
let unattributed = previous.generated.iter().any(|g| !previous.generated_origins.contains_key(g))
|
||||
|| !previous.unowned.is_empty();
|
||||
let from_scratch = from_scratch || (unattributed && has_changes);
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
@@ -163,15 +175,38 @@ impl JavaBuildService {
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
generated: previous.generated.clone(),
|
||||
generated_origins: previous.generated_origins.clone(),
|
||||
unowned: previous.unowned.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// A removed source takes the generated sources it produced with it.
|
||||
let mut removed_sources = removed.clone();
|
||||
for (generated, origin) in &state.generated_origins {
|
||||
if removed.contains(origin) {
|
||||
removed_sources.insert(generated.clone());
|
||||
}
|
||||
}
|
||||
if !removed_sources.is_empty() {
|
||||
let removed_generated: Vec<PathBuf> = state
|
||||
.generated_origins
|
||||
.iter()
|
||||
.filter(|(_, origin)| removed.contains(*origin))
|
||||
.map(|(generated, _)| generated.clone())
|
||||
.collect();
|
||||
for file in &removed_generated {
|
||||
let _ = std::fs::remove_file(file);
|
||||
state.generated_origins.remove(file);
|
||||
}
|
||||
state.generated.retain(|g| !removed_generated.contains(g));
|
||||
}
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed_sources.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let gone_empty = gone.is_empty();
|
||||
@@ -187,12 +222,24 @@ impl JavaBuildService {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
state.generated.clear();
|
||||
state.generated_origins.clear();
|
||||
state.unowned.clear();
|
||||
state.classes.retain(|_, r| r.source.as_ref().is_some_and(|s| source_stamps.contains_key(s)));
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
let dependents = incremental::dependent_sources(&state.classes, &affected);
|
||||
changed
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(
|
||||
dependents
|
||||
.into_iter()
|
||||
.filter_map(|source| compile_source(source, &state.generated_origins, &source_stamps)),
|
||||
)
|
||||
.collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&set.generated_dir)?;
|
||||
@@ -213,16 +260,28 @@ impl JavaBuildService {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
// A generated source's classes go with the source that regenerates it.
|
||||
let generated_of_batch: Vec<PathBuf> = state
|
||||
.generated_origins
|
||||
.iter()
|
||||
.filter(|(_, origin)| batch.contains(*origin))
|
||||
.map(|(generated, _)| generated.clone())
|
||||
.collect();
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s) || generated_of_batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
for generated in &generated_of_batch {
|
||||
let _ = std::fs::remove_file(generated);
|
||||
state.generated_origins.remove(generated);
|
||||
}
|
||||
state.generated.retain(|g| !generated_of_batch.contains(g));
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
@@ -239,11 +298,12 @@ impl JavaBuildService {
|
||||
server = Some(self.servers.server(set.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let mut generated_now: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result =
|
||||
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
|
||||
match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::Generated { path, source } => generated_now.push((path.clone(), source.clone())),
|
||||
Reply::OutputText { text } => {
|
||||
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
|
||||
}
|
||||
@@ -282,11 +342,36 @@ impl JavaBuildService {
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
let own_real = |source: &Path| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(source) {
|
||||
return Some(source.to_path_buf());
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
canonical.get(&dunce::canonicalize(source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
// Generated sources javac names an originating source for (JDK 18+) are tracked as
|
||||
// their own source, so a change to their API reaches the sources that use them; the
|
||||
// origin source regenerates them when it compiles.
|
||||
let mut origins = std::mem::take(&mut state.generated_origins);
|
||||
for (generated, source) in &generated_now {
|
||||
state.generated.push(generated.clone());
|
||||
if let Some(source) = source {
|
||||
origins.insert(generated.clone(), source.clone());
|
||||
}
|
||||
}
|
||||
for (generated, _) in &generated_now {
|
||||
if let Some(origin) = resolve_generated(generated, &origins, &own_real) {
|
||||
origins.insert(generated.clone(), origin);
|
||||
} else {
|
||||
origins.remove(generated);
|
||||
}
|
||||
}
|
||||
state.generated_origins = origins;
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if let Some(real) = own_real(&source) {
|
||||
return Some(real);
|
||||
}
|
||||
// A generated source whose origin javac named.
|
||||
state.generated_origins.get(&source).map(|_| source.clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
@@ -315,9 +400,27 @@ impl JavaBuildService {
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
let dependents = incremental::dependent_sources(&state.classes, &affected);
|
||||
to_compile.extend(
|
||||
dependents
|
||||
.into_iter()
|
||||
.filter_map(|source| compile_source(source, &state.generated_origins, &source_stamps)),
|
||||
);
|
||||
let shadowed = incremental::shadowed_sources(&state.classes, &round.added);
|
||||
to_compile.extend(
|
||||
shadowed
|
||||
.into_iter()
|
||||
.filter_map(|source| compile_source(source, &state.generated_origins, &source_stamps)),
|
||||
);
|
||||
}
|
||||
state.generated.sort();
|
||||
state.generated.dedup();
|
||||
state.unowned.sort();
|
||||
state.unowned.dedup();
|
||||
// A class javac now attributes to a generated source is tracked in `classes`, not as an
|
||||
// unowned output, even when an earlier build recorded it as one.
|
||||
let class_files: BTreeSet<PathBuf> = state.classes.values().map(|r| r.file.clone()).collect();
|
||||
state.unowned.retain(|path| !class_files.contains(path));
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
@@ -700,6 +803,40 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
args
|
||||
}
|
||||
|
||||
/// The source javac must compile for `source`: itself when it is a source of the set, or the
|
||||
/// source javac named as the origin of a generated source, following chained processors.
|
||||
fn compile_source(
|
||||
source: PathBuf,
|
||||
origins: &BTreeMap<PathBuf, PathBuf>,
|
||||
sources: &BTreeMap<PathBuf, FileStamp>,
|
||||
) -> Option<PathBuf> {
|
||||
let mut source = source;
|
||||
for _ in 0..8 {
|
||||
if sources.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
source = origins.get(&source)?.clone();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The real source `generated` traces back to through `origins`; `None` when javac named no
|
||||
/// origin for it (a processor that aggregates, or a JDK that reports no originating file).
|
||||
fn resolve_generated(
|
||||
generated: &Path,
|
||||
origins: &BTreeMap<PathBuf, PathBuf>,
|
||||
own_real: &dyn Fn(&Path) -> Option<PathBuf>,
|
||||
) -> Option<PathBuf> {
|
||||
let mut at = generated.to_path_buf();
|
||||
for _ in 0..8 {
|
||||
if let Some(real) = own_real(&at) {
|
||||
return Some(real);
|
||||
}
|
||||
at = origins.get(&at)?.clone();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `.mvn/jvm.config` of the reactor: the options Maven's JVM (and so its in-process javac) runs with.
|
||||
fn jvm_config(top: Reactor, top_dir: &Path) -> Vec<String> {
|
||||
if matches!(top, Reactor::Gradle(_)) {
|
||||
|
||||
@@ -1146,3 +1146,124 @@ fn recompiles_a_single_file_through_either_the_plain_or_linked_spelling() {
|
||||
|
||||
assert!(second.is_empty(), "{second:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_sources_compile_their_originating_source() {
|
||||
let root = PathBuf::from("/p");
|
||||
let mut sources = BTreeMap::new();
|
||||
sources.insert(root.join("A.java"), (1, 2));
|
||||
let mut origins = BTreeMap::new();
|
||||
origins.insert(root.join("gen/AImpl.java"), root.join("A.java"));
|
||||
assert_eq!(compile_source(root.join("gen/AImpl.java"), &origins, &sources), Some(root.join("A.java")));
|
||||
// A processor's output may be another processor's input.
|
||||
origins.insert(root.join("gen/B.java"), root.join("gen/AImpl.java"));
|
||||
assert_eq!(compile_source(root.join("gen/B.java"), &origins, &sources), Some(root.join("A.java")));
|
||||
assert_eq!(compile_source(root.join("gen/C.java"), &origins, &sources), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_source_without_a_known_origin_is_unattributed() {
|
||||
let root = PathBuf::from("/p");
|
||||
let mut origins = BTreeMap::new();
|
||||
origins.insert(root.join("gen/AImpl.java"), root.join("A.java"));
|
||||
let known = |path: &Path| (path == root.join("A.java").as_path()).then(|| path.to_path_buf());
|
||||
assert_eq!(resolve_generated(&root.join("gen/AImpl.java"), &origins, &known), Some(root.join("A.java")));
|
||||
assert_eq!(resolve_generated(&root.join("gen/Orphan.java"), &origins, &known), None);
|
||||
}
|
||||
|
||||
/// Compiles annotation processor `proc.P` from `source` into a directory for `-processorpath`.
|
||||
fn processor_dir(root: &Path, source: &str) -> PathBuf {
|
||||
let home = PathBuf::from(std::env::var_os("JAVA_HOME").unwrap());
|
||||
let src = root.join("processor/proc/P.java");
|
||||
write(root, "processor/proc/P.java", source);
|
||||
let out = root.join("processor-classes");
|
||||
let status = std::process::Command::new(home.join("bin/javac")).arg("-d").arg(&out).arg(&src).status().unwrap();
|
||||
assert!(status.success());
|
||||
out
|
||||
}
|
||||
|
||||
/// `app`'s POM running `proc.P` from `dir` over its sources.
|
||||
fn app_pom_with_processor(dir: &Path) -> String {
|
||||
APP_POM.replace(
|
||||
"</build>",
|
||||
&format!(
|
||||
concat!(
|
||||
"<plugins><plugin><artifactId>maven-compiler-plugin</artifactId><configuration><compilerArgs>",
|
||||
"<arg>-processorpath</arg><arg>{}</arg><arg>-processor</arg><arg>proc.P</arg>",
|
||||
"</compilerArgs></configuration></plugin></plugins></build>",
|
||||
),
|
||||
dir.display()
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const PROCESSOR_IMPORTS: &str = "package proc;\nimport java.io.Writer;\nimport java.util.*;\nimport javax.annotation.processing.*;\nimport javax.lang.model.SourceVersion;\nimport javax.lang.model.element.*;\nimport javax.tools.StandardLocation;\n";
|
||||
|
||||
#[test]
|
||||
fn an_aggregating_processors_resource_keeps_every_source_after_an_incremental_change() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
if tools().is_none() {
|
||||
return;
|
||||
}
|
||||
// Like AutoService: one resource listing every annotated class of the compilation.
|
||||
let dir = processor_dir(
|
||||
tmp.path(),
|
||||
&format!(
|
||||
"{PROCESSOR_IMPORTS}@SupportedAnnotationTypes(\"p.Svc\")\npublic class P extends AbstractProcessor {{\n private final Set<String> names = new TreeSet<>();\n @Override public SourceVersion getSupportedSourceVersion() {{ return SourceVersion.latestSupported(); }}\n @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {{\n for (TypeElement a : annotations) for (Element e : env.getElementsAnnotatedWith(a)) names.add(((TypeElement) e).getQualifiedName().toString());\n if (env.processingOver()) {{\n try (Writer w = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, \"\", \"META-INF/services/p.Api\").openWriter()) {{\n for (String n : names) w.write(n + \"\\n\");\n }} catch (Exception ex) {{ throw new RuntimeException(ex); }}\n }}\n return false;\n }}\n}}\n"
|
||||
),
|
||||
);
|
||||
let pom = app_pom_with_processor(&dir);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("app/src/main/java/p/Svc.java", "package p;\npublic @interface Svc {}\n"),
|
||||
("app/src/main/java/p/A.java", "package p;\n@Svc public class A {}\n"),
|
||||
("app/src/main/java/p/B.java", "package p;\n@Svc public class B {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let services = f.out("t.app/classes/META-INF/services/p.Api");
|
||||
f.steps_of_launch();
|
||||
assert_eq!(fs::read_to_string(&services).unwrap(), "p.A\np.B\n");
|
||||
f.write("app/src/main/java/p/A.java", "package p;\n@Svc public class A { int changed; }\n");
|
||||
f.steps_of_launch();
|
||||
assert_eq!(fs::read_to_string(&services).unwrap(), "p.A\np.B\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_source_follows_the_source_it_was_generated_from() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
if tools().is_none() {
|
||||
return;
|
||||
}
|
||||
// Like MapStruct: one generated source per annotated class, naming it as the originating element.
|
||||
let dir = processor_dir(
|
||||
tmp.path(),
|
||||
&format!(
|
||||
"{PROCESSOR_IMPORTS}@SupportedAnnotationTypes(\"p.Svc\")\npublic class P extends AbstractProcessor {{\n @Override public SourceVersion getSupportedSourceVersion() {{ return SourceVersion.latestSupported(); }}\n @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {{\n for (TypeElement a : annotations) for (Element e : env.getElementsAnnotatedWith(a)) {{\n String name = e.getSimpleName() + \"Impl\";\n try (Writer w = processingEnv.getFiler().createSourceFile(\"p.\" + name, e).openWriter()) {{\n w.write(\"package p;\\npublic class \" + name + \" {{ \" + e.getSimpleName() + \" of; }}\\n\");\n }} catch (Exception ex) {{ throw new RuntimeException(ex); }}\n }}\n return false;\n }}\n}}\n"
|
||||
),
|
||||
);
|
||||
let pom = app_pom_with_processor(&dir);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("app/src/main/java/p/Svc.java", "package p;\npublic @interface Svc {}\n"),
|
||||
("app/src/main/java/p/A.java", "package p;\n@Svc public class A {}\n"),
|
||||
("app/src/main/java/p/B.java", "package p;\n@Svc public class B {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
f.steps_of_launch();
|
||||
let a_impl = f.out("t.app/classes/p/AImpl.class");
|
||||
assert!(a_impl.is_file() && f.out("t.app/classes/p/BImpl.class").is_file());
|
||||
|
||||
// A change to A compiles A alone, and regenerates AImpl with it.
|
||||
f.write("app/src/main/java/p/A.java", "package p;\n@Svc public class A { void changed() {} }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 3 files)"]);
|
||||
assert!(a_impl.is_file());
|
||||
|
||||
// Deleting A takes AImpl's source and class with it.
|
||||
fs::remove_file(f.root.join("app/src/main/java/p/A.java")).unwrap();
|
||||
f.steps_of_launch();
|
||||
assert!(!a_impl.exists());
|
||||
assert!(!f.out("t.app/classes/p/A.class").exists());
|
||||
assert!(f.out("t.app/classes/p/BImpl.class").is_file());
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача