From 536f85b9dfd6abe1498219f923394465c098ae53 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 20:01:26 +0800 Subject: [PATCH] feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu. ## What changes - **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path): - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`. - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`. The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone. - **Outputs.** Every project writes to `/java-build//out/./classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs. - **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle. - **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded). - A build compiles the changed sources. - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow. - Downstream sets follow an API change log. - A changed constant recompiles the set and everything compiled against it. - Sources a failed compile left behind stay dirty. - Sets whose annotation processors aggregate compile from scratch. - **Build menu.** - Build Project and Build Module compile with the service. - Recompile compiles the file with the service and publishes javac's diagnostics. - **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801. - **When it applies.** - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on. - Gradle modules when Settings › Gradle › *Build and run using* is the IDE. - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles. - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below). - **Fallback.** These go to the build tool's own build: - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds; - a failed prepare run. The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`. ## Tests - `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing): - first build, no-op build, only changed files recompile; - API changes reach dependents, including through subclasses and across modules; - constant changes recompile dependents; - resource changes run only the resources step; - deleted sources, compile errors with positions, the test source set; - Recompile and Build Project; - Gradle projects; - fallback for Gradle projects with other compilers; - plus class-file parsing, the API change log, javac options and Ant patterns. - `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors. - `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`. - `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on. --- crates/ide-build/src/compile/fingerprint.rs | 9 +- crates/ide-build/src/compile/mod.rs | 24 +- crates/ide-build/src/jbuild/classfile.rs | 482 +++++++ .../src/jbuild/gradle-build.init.gradle | 145 +++ crates/ide-build/src/jbuild/incremental.rs | 216 ++++ crates/ide-build/src/jbuild/javac.rs | 263 ++++ crates/ide-build/src/jbuild/mod.rs | 1122 +++++++++++++++++ crates/ide-build/src/jbuild/model.rs | 342 +++++ crates/ide-build/src/jbuild/tests.rs | 544 ++++++++ crates/ide-build/src/lib.rs | 1 + crates/ide-build/src/maven.rs | 30 +- crates/ide-host/src/lib.rs | 3 + crates/ide-host/src/mcp/run/configs.rs | 1 + crates/ide-host/src/ops/build.rs | 101 +- crates/ide-host/src/ops/java.rs | 243 +++- crates/ide-host/tests/java_build.rs | 215 ++++ crates/ide-host/tests/workspaces.rs | 20 +- crates/ide-lsp/tests/real_servers.rs | 104 ++ crates/ide-sdk/src/java.rs | 17 + java/java-build/README.md | 40 + java/java-build/build-dependencies.sha256 | 52 + java/java-build/build.py | 38 + .../ai/openidea/javac/maven/BuildModel.java | 501 ++++++++ java/java-build/openidea-java-build.jar | Bin 0 -> 60696 bytes .../src/ai/openidea/javac/Server.java | 459 +++++++ src/bindings.ts | 4 +- src/features/debugger/__tests__/java.test.ts | 4 +- .../debugger/__tests__/javaCancel.test.ts | 2 +- src/features/debugger/java.ts | 10 +- src/features/run/applicationUpdate.test.ts | 4 +- src/features/run/applicationUpdate.ts | 2 + src/features/run/javaModule.test.ts | 72 +- src/features/run/resolveCancellation.test.ts | 2 +- src/features/run/tomcat.test.tsx | 9 +- src/platform/javaLaunch.ts | 9 +- 35 files changed, 5040 insertions(+), 50 deletions(-) create mode 100644 crates/ide-build/src/jbuild/classfile.rs create mode 100644 crates/ide-build/src/jbuild/gradle-build.init.gradle create mode 100644 crates/ide-build/src/jbuild/incremental.rs create mode 100644 crates/ide-build/src/jbuild/javac.rs create mode 100644 crates/ide-build/src/jbuild/mod.rs create mode 100644 crates/ide-build/src/jbuild/model.rs create mode 100644 crates/ide-build/src/jbuild/tests.rs create mode 100644 crates/ide-host/tests/java_build.rs create mode 100644 java/java-build/README.md create mode 100644 java/java-build/build-dependencies.sha256 create mode 100644 java/java-build/build.py create mode 100644 java/java-build/maven/ai/openidea/javac/maven/BuildModel.java create mode 100644 java/java-build/openidea-java-build.jar create mode 100644 java/java-build/src/ai/openidea/javac/Server.java diff --git a/crates/ide-build/src/compile/fingerprint.rs b/crates/ide-build/src/compile/fingerprint.rs index d5ebe4f0f..f8330eea7 100644 --- a/crates/ide-build/src/compile/fingerprint.rs +++ b/crates/ide-build/src/compile/fingerprint.rs @@ -6,7 +6,7 @@ use std::io::Read; use std::time::SystemTime; /// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only. -type Stamp = (u64, SystemTime, Option); +pub(crate) type Stamp = (u64, SystemTime, Option); #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct LaunchFingerprint { @@ -182,7 +182,7 @@ fn collect( } /// Scans every input, storing project inputs relative to the project. -pub(super) fn scan_all( +pub(crate) fn scan_all( root: &Path, inputs: Vec, cancel: &CancellationToken, @@ -282,6 +282,11 @@ pub(super) fn module_fingerprint( } impl LaunchFingerprint { + /// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]). + pub(crate) fn new(parameters: String, files: BTreeMap>) -> Self { + LaunchFingerprint { version: 2, parameters, files } + } + /// Folders (relative to the project) of the Maven projects whose POM is an input. pub(super) fn project_dirs(&self) -> impl Iterator { self.files diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index b565973c3..891f37253 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -3,7 +3,7 @@ //! background with cancellation and parses the compiler output into messages //! for the Build tool window, the Problems view and the editor. -mod fingerprint; +pub(crate) mod fingerprint; mod launch_resources; mod modules; mod parse; @@ -845,6 +845,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) projects } +/// A step running Maven, its output parsed as Maven's. +pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep { + BuildStep::new(program, args, cwd, Format::Maven) +} + +pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep { + BuildStep::new(program, args, cwd, Format::Gradle) +} + +/// The linked reactor root building the project at `module` (project-relative). +pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> { + maven_reactor(m, module) +} + +/// The projects of the reactor `top`. +pub(crate) fn reactor_projects_of<'a>( + m: &'a maven::MavenModel, + top: &'a maven::MavenProject, +) -> Vec<&'a maven::MavenProject> { + reactor_projects(m, top) +} + fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> { m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module)) } diff --git a/crates/ide-build/src/jbuild/classfile.rs b/crates/ide-build/src/jbuild/classfile.rs new file mode 100644 index 000000000..ff74b75ba --- /dev/null +++ b/crates/ide-build/src/jbuild/classfile.rs @@ -0,0 +1,482 @@ +//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the +//! classes its constant pool refers to, and fingerprints of its API and of its compile-time +//! constants. Bounds-checked: a malformed file is `None`, never a panic. +use std::collections::BTreeSet; + +/// A class file, as the dependency graph and the API diff see it. +#[derive(Clone, Debug, PartialEq)] +pub struct ClassFile { + /// Internal name (`com/acme/Order$Line`). + pub name: String, + pub super_name: Option, + pub interfaces: Vec, + /// Classes named in the constant pool: references, descriptors, signatures, annotation types. + pub refs: BTreeSet, + /// What other classes compile against: non-private, non-synthetic members and their + /// signatures, supertypes, nested classes, permitted subclasses, record components. + pub api: u64, + /// The compile-time constants (`static final` fields with a `ConstantValue`), which javac + /// copies into the classes that use them: a change can't be traced through references. + pub constants: u64, +} + +const ACC_PRIVATE: u16 = 0x0002; +const ACC_SYNTHETIC: u16 = 0x1000; + +struct Bytes<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Bytes<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let slice = self.data.get(self.pos..end)?; + self.pos = end; + Some(slice) + } + fn u1(&mut self) -> Option { + Some(self.take(1)?[0]) + } + fn u2(&mut self) -> Option { + let b = self.take(2)?; + Some(u16::from_be_bytes([b[0], b[1]])) + } + fn u4(&mut self) -> Option { + let b = self.take(4)?; + Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + } +} + +#[derive(Clone, Debug)] +enum Entry { + Empty, + Utf8(String), + Class(u16), + String(u16), + /// Integer, float, long, double: the raw bytes. + Number(Vec), + NameAndType(u16), + MethodType(u16), + Other, +} + +struct Pool(Vec); + +impl Pool { + fn utf8(&self, index: u16) -> Option<&str> { + match self.0.get(index as usize)? { + Entry::Utf8(s) => Some(s), + _ => None, + } + } + fn class(&self, index: u16) -> Option<&str> { + match self.0.get(index as usize)? { + Entry::Class(name) => self.utf8(*name), + _ => None, + } + } + /// A `ConstantValue`'s value, as bytes. + fn constant(&self, index: u16) -> Option> { + match self.0.get(index as usize)? { + Entry::Number(bytes) => Some(bytes.clone()), + Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()), + _ => None, + } + } +} + +/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable. +#[derive(Clone, Copy)] +struct Fnv(u64); + +impl Fnv { + fn new() -> Self { + Fnv(0xcbf2_9ce4_8422_2325) + } + fn bytes(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3); + } + // A separator, so `ab`+`c` and `a`+`bc` differ. + self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3); + } + fn str(&mut self, s: &str) { + self.bytes(s.as_bytes()); + } + fn u16(&mut self, v: u16) { + self.bytes(&v.to_be_bytes()); + } +} + +/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order;`). +fn descriptor_refs(text: &str, out: &mut BTreeSet) { + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'L' + && (i == 0 + || matches!( + bytes[i - 1], + b'(' | b')' + | b'[' + | b';' + | b'<' + | b'>' + | b'+' + | b'-' + | b':' + | b'*' + | b'I' + | b'J' + | b'Z' + | b'B' + | b'C' + | b'S' + | b'F' + | b'D' + | b'V' + | b'^' + )) + { + let start = i + 1; + let mut end = start; + while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') { + end += 1; + } + if end < bytes.len() && end > start { + let name = &text[start..end]; + if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) { + out.insert(name.to_owned()); + } + } + i = end; + } else { + i += 1; + } + } +} + +fn class_ref(name: &str, out: &mut BTreeSet) { + if name.starts_with('[') { + descriptor_refs(name, out); + } else { + out.insert(name.to_owned()); + } +} + +struct Member { + access: u16, + name: String, + descriptor: String, + /// Fingerprint of the attributes that are part of the API. + extra: u64, + constant: Option>, +} + +fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> { + let count = r.u2()?; + for _ in 0..count { + let name = pool.utf8(r.u2()?)?.to_owned(); + let len = r.u4()? as usize; + let body = r.take(len)?; + on(&name, body); + } + Some(()) +} + +fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet) -> Option> { + let count = r.u2()?; + let mut out = Vec::with_capacity(count as usize); + for _ in 0..count { + let access = r.u2()?; + let name = pool.utf8(r.u2()?)?.to_owned(); + let descriptor = pool.utf8(r.u2()?)?.to_owned(); + descriptor_refs(&descriptor, refs); + let mut extra = Fnv::new(); + let mut constant = None; + attributes(r, pool, |attr, body| { + let mut b = Bytes { data: body, pos: 0 }; + match attr { + "Signature" => { + if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) { + descriptor_refs(sig, refs); + extra.str("S"); + extra.str(sig); + } + } + "ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)), + "Exceptions" => { + let mut names: Vec<&str> = Vec::new(); + if let Some(n) = b.u2() { + for _ in 0..n { + if let Some(c) = b.u2().and_then(|i| pool.class(i)) { + names.push(c); + } + } + } + names.sort_unstable(); + extra.str("E"); + for n in names { + extra.str(n); + } + } + // An annotation element's default value is compiled into its uses. + "AnnotationDefault" => { + extra.str("D"); + element_value(&mut b, pool, refs, &mut extra); + } + _ => {} + } + })?; + out.push(Member { access, name, descriptor, extra: extra.0, constant }); + } + Some(out) +} + +/// Parses a class file; `None` when it isn't a well-formed one. +pub fn parse(data: &[u8]) -> Option { + let mut r = Bytes { data, pos: 0 }; + if r.u4()? != 0xCAFE_BABE { + return None; + } + r.u2()?; + r.u2()?; + let count = r.u2()?; + let mut entries = vec![Entry::Empty]; + let mut i = 1; + while i < count { + let tag = r.u1()?; + let entry = match tag { + 1 => { + let len = r.u2()? as usize; + Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned()) + } + 3 | 4 => Entry::Number(r.take(4)?.to_vec()), + 5 | 6 => Entry::Number(r.take(8)?.to_vec()), + 7 => Entry::Class(r.u2()?), + 8 => Entry::String(r.u2()?), + 9..=11 => { + r.take(4)?; + Entry::Other + } + 12 => { + r.u2()?; + Entry::NameAndType(r.u2()?) + } + 15 => { + r.take(3)?; + Entry::Other + } + 16 => Entry::MethodType(r.u2()?), + 17 | 18 => { + r.take(4)?; + Entry::Other + } + 19 | 20 => { + r.take(2)?; + Entry::Other + } + _ => return None, + }; + let wide = matches!(tag, 5 | 6); + entries.push(entry); + i += 1; + if wide { + entries.push(Entry::Empty); + i += 1; + } + } + let pool = Pool(entries); + let mut refs = BTreeSet::new(); + for entry in &pool.0 { + match entry { + Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs), + Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => { + descriptor_refs(pool.utf8(*descriptor)?, &mut refs) + } + _ => {} + } + } + let access = r.u2()?; + let name = pool.class(r.u2()?)?.to_owned(); + let super_index = r.u2()?; + let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) }; + let mut interfaces = Vec::new(); + for _ in 0..r.u2()? { + interfaces.push(pool.class(r.u2()?)?.to_owned()); + } + let fields = members(&mut r, &pool, &mut refs)?; + let methods = members(&mut r, &pool, &mut refs)?; + + let mut api = Fnv::new(); + // ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class. + api.u16(access & !(0x0020 | ACC_SYNTHETIC)); + api.str(&name); + api.str(super_name.as_deref().unwrap_or("")); + let mut sorted = interfaces.clone(); + sorted.sort(); + for i in &sorted { + api.str(i); + } + let mut class_attrs: Vec<(String, u64)> = Vec::new(); + attributes(&mut r, &pool, |attr, body| { + let mut b = Bytes { data: body, pos: 0 }; + let mut h = Fnv::new(); + match attr { + "Signature" => { + if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) { + descriptor_refs(sig, &mut refs); + h.str(sig); + } + } + "PermittedSubclasses" => { + let mut names = Vec::new(); + for _ in 0..b.u2().unwrap_or(0) { + if let Some(c) = b.u2().and_then(|i| pool.class(i)) { + names.push(c.to_owned()); + } + } + names.sort(); + names.iter().for_each(|n| h.str(n)); + } + "Record" => { + for _ in 0..b.u2().unwrap_or(0) { + let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i))) + else { + break; + }; + h.str(n); + h.str(d); + let mut component = |attr: &str, body: &[u8]| { + if attr == "Signature" + && let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i)) + { + h.str(sig); + } + }; + if attributes(&mut b, &pool, &mut component).is_none() { + break; + } + } + } + // Nested classes this class declares, and their access. + "InnerClasses" => { + let mut nested = Vec::new(); + for _ in 0..b.u2().unwrap_or(0) { + let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else { + break; + }; + let inner = pool.class(inner).unwrap_or(""); + if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 { + nested.push(format!("{inner}:{flags}")); + } + } + nested.sort(); + nested.iter().for_each(|n| h.str(n)); + } + "RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => { + // Annotation types are dependencies; their values aren't API. + annotation_types(body, &pool, &mut refs); + return; + } + _ => return, + } + class_attrs.push((attr.to_owned(), h.0)); + })?; + class_attrs.sort(); + for (attr, h) in &class_attrs { + api.str(attr); + api.bytes(&h.to_be_bytes()); + } + let mut constants = Fnv::new(); + let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new(); + for (kind, list) in [(0u8, &fields), (1u8, &methods)] { + for m in list.iter() { + if kind == 0 + && let Some(value) = &m.constant + { + // Private constants are inlined too, but only in their own class. + if m.access & ACC_PRIVATE == 0 { + constants.str(&m.name); + constants.str(&m.descriptor); + constants.bytes(value); + } + } + if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "" { + continue; + } + api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra)); + } + } + api_members.sort(); + for (kind, name, descriptor, access, extra) in api_members { + api.bytes(&[kind]); + api.str(name); + api.str(descriptor); + api.u16(access); + api.bytes(&extra.to_be_bytes()); + } + refs.remove(&name); + refs.retain(|r| !r.starts_with("java/")); + Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 }) +} + +/// Adds the types of the annotations in a `Runtime*Annotations` attribute. +fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet) { + let mut b = Bytes { data: body, pos: 0 }; + let Some(count) = b.u2() else { return }; + let mut ignored = Fnv::new(); + for _ in 0..count { + if annotation(&mut b, pool, refs, &mut ignored).is_none() { + return; + } + } +} + +fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet, h: &mut Fnv) -> Option<()> { + let ty = pool.utf8(b.u2()?)?; + descriptor_refs(ty, refs); + h.str(ty); + for _ in 0..b.u2()? { + h.str(pool.utf8(b.u2()?)?); + element_value(b, pool, refs, h)?; + } + Some(()) +} + +/// An annotation element value: its class names go to `refs`, its value (resolved, not the +/// constant pool indices) to `h`. +fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet, h: &mut Fnv) -> Option<()> { + let tag = b.u1()?; + h.bytes(&[tag]); + match tag { + b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?), + b's' => h.str(pool.utf8(b.u2()?)?), + b'e' => { + let ty = pool.utf8(b.u2()?)?; + descriptor_refs(ty, refs); + h.str(ty); + h.str(pool.utf8(b.u2()?)?); + } + b'c' => { + let ty = pool.utf8(b.u2()?)?; + descriptor_refs(ty, refs); + h.str(ty); + } + b'@' => annotation(b, pool, refs, h)?, + b'[' => { + for _ in 0..b.u2()? { + element_value(b, pool, refs, h)?; + } + } + _ => return None, + } + Some(()) +} + +/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow. +pub fn simple_name(name: &str) -> &str { + let tail = name.rsplit('/').next().unwrap_or(name); + tail.rsplit('$').next().unwrap_or(tail) +} diff --git a/crates/ide-build/src/jbuild/gradle-build.init.gradle b/crates/ide-build/src/jbuild/gradle-build.init.gradle new file mode 100644 index 000000000..142603160 --- /dev/null +++ b/crates/ide-build/src/jbuild/gradle-build.init.gradle @@ -0,0 +1,145 @@ +// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=, +// every Java source set writes its classes and resources to /[.]/classes|test-classes, +// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task +// `openideaBuildModel` (-Popenidea.build.model=) runs what generates sources, processes the +// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it: +// the same model the Maven extension writes (java/java-build, BuildModel). +import groovy.json.JsonOutput +import org.gradle.api.tasks.compile.AbstractCompile +import org.gradle.api.tasks.compile.JavaCompile +import org.gradle.jvm.tasks.Jar + +def property = { String name -> gradle.startParameter.projectProperties[name] } +def outRoot = property('openidea.build.output') +if (outRoot == null || gradle.parent != null) return + +// The project's name in the build: unique, unlike `name`. +def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') } +def outputOf = { Project p, String set -> + def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p) + new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes')) +} +def javaSets = { Project p -> + def sets = p.extensions.findByName('sourceSets') + sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null } +} + +gradle.projectsEvaluated { + def root = gradle.rootProject + root.allprojects.each { p -> + javaSets(p).each { ss -> + def out = outputOf(p, ss.name) + ss.java.destinationDirectory.set(out) + ss.output.resourcesDir = out + p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out } + } + } + root.tasks.register('openideaBuildModel') { + // What compiling needs from the same project (generated sources), and the resources. + dependsOn { + root.allprojects.collectMany { p -> + javaSets(p).collectMany { ss -> + def compile = p.tasks.getByName(ss.compileJavaTaskName) + def generators = compile.taskDependencies.getDependencies(compile).findAll { + it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar) + } + generators + [p.tasks.getByName(ss.processResourcesTaskName)] + } + } + } + doLast { + // Project artifacts resolve to the projects' outputs. + def artifacts = [:] + root.allprojects.each { p -> + def main = javaSets(p).find { it.name == 'main' } + if (main == null) return + def jar = p.tasks.findByName('jar') + if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main') + } + def files = { collection -> + def out = [] + try { + collection?.files?.each { f -> + def mapped = artifacts[f.canonicalPath] ?: f + if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath + } + } catch (e) { + out << "!${e.message}".toString() + } + out + } + def included = gradle.includedBuilds.collect { it.name } + def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p -> + def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()] + def others = p.tasks.withType(AbstractCompile).findAll { + !(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/ + }.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() } + def setModel = { String name -> + def ss = javaSets(p).find { it.name == name } + if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []] + JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName) + def o = compile.options + def classpath = files(compile.classpath) + def runtime = files(ss.runtimeClasspath) + (classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() } + def processorPath = files(o.annotationProcessorPath) + def processorProblems = processorPath.findAll { it.startsWith('!') } + def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } } + def home = null + try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {} + [ + sourceRoots: ss.java.srcDirs.collect { it.canonicalPath }, + output: outputOf(p, name).canonicalPath, + classpath: classpath.findAll { !it.startsWith('!') }, + runtimeClasspath: runtime.findAll { !it.startsWith('!') }, + resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] }, + compiler: [ + compilerId: 'javac', + source: compile.sourceCompatibility, + target: compile.targetCompatibility, + release: o.release.orNull?.toString(), + encoding: o.encoding, + debug: o.debug, + debuglevel: o.debugOptions.debugLevel, + showWarnings: o.warnings, + showDeprecation: o.deprecation, + fork: home != null, + executable: home == null ? null : new File(home, 'bin/javac').path, + generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath, + includes: ss.java.includes as List, + excludes: ss.java.excludes as List, + compilerArgs: o.allCompilerArgs.collect { it.toString() }, + processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null, + processorPathError: !processorProblems.isEmpty() + ? processorProblems[0].substring(1) + : (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'), + ], + ] + } + def mainModel = setModel('main') + def testModel = setModel('test') + // Gradle compiles tests against the main classes: they're the main output here. + [ + dir: p.projectDir.canonicalPath, + groupId: (p.group ?: '').toString(), + artifactId: nameOf(p), + version: p.version.toString(), + packaging: 'jar', + main: mainModel, + test: testModel, + otherCompilers: others, + testGenerators: [], + problems: problems, + gradlePath: p.path, + ] + } + def modelFile = property('openidea.build.model') + if (modelFile != null) { + def file = new File(modelFile) + def temporary = new File(file.parentFile, file.name + '.tmp') + temporary.text = JsonOutput.toJson([version: 1, projects: projects]) + temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }() + } + } + } +} diff --git a/crates/ide-build/src/jbuild/incremental.rs b/crates/ide-build/src/jbuild/incremental.rs new file mode 100644 index 000000000..7aaf64a5c --- /dev/null +++ b/crates/ide-build/src/jbuild/incremental.rs @@ -0,0 +1,216 @@ +//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it +//! compiled, the source it came from, its supertypes, the classes its constant pool names and +//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed +//! sources, then the sources of classes that refer to a class whose API changed (or to a +//! subclass of one), round after round until no API changes. Sets compiled against this one +//! read its log of API changes; a changed compile-time constant, which javac copies into the +//! classes that use it, recompiles the whole set and every set compiled against it. +use super::*; +use std::collections::BTreeSet; + +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +pub(super) struct ClassRecord { + /// The source javac compiled it from; `None` for classes an annotation processor wrote + /// without naming an originating source. + pub source: Option, + pub file: PathBuf, + pub super_name: Option, + #[serde(default)] + pub interfaces: Vec, + #[serde(default)] + pub refs: Vec, + pub api: u64, + pub constants: u64, +} + +impl ClassRecord { + pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option) -> (String, Self) { + let record = ClassRecord { + source, + file, + super_name: class.super_name, + interfaces: class.interfaces, + refs: class.refs.into_iter().collect(), + api: class.api, + constants: class.constants, + }; + (class.name, record) + } + + fn has_constants(&self) -> bool { + self.constants != NO_CONSTANTS + } +} + +/// The constant fingerprint of a class without compile-time constants. +pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325; + +/// The classes whose API one compilation of a set changed. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +pub(super) struct ApiChange { + /// The set's generation before and after the compilation. + pub since: u64, + pub generation: u64, + pub classes: Vec, + /// Everything counts as changed: a constant changed, or there was nothing to compare with. + pub all: bool, +} + +/// How many compilations' API changes a set keeps for the sets compiled against it; one that +/// fell further behind compiles from scratch. +const CHANGE_LOG: usize = 64; + +/// The inputs of a source set that, when changed, compile it from scratch. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +pub(super) struct SetStamp { + pub options: Vec, + /// Classpath entries outside the reactor's outputs, with their stamps (folders have none). + pub libraries: Vec<(PathBuf, Option)>, + /// The reactor outputs on the classpath, in order. + pub reactor: Vec, + pub processor_path: Vec<(PathBuf, Option)>, + pub java_home: PathBuf, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +pub(super) struct SetState { + pub stamp: SetStamp, + /// The sources as of the last compilation. + pub sources: BTreeMap, + /// Changes whenever the set's classes do. + pub generation: u64, + /// The generation of each reactor output it was compiled against. + pub upstream: BTreeMap, + pub classes: BTreeMap, + /// Sources a failed compilation left uncompiled. + pub dirty: BTreeSet, + pub changes: Vec, + /// 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. + pub generated: Vec, + pub unowned: Vec, + pub success: bool, +} + +impl SetState { + /// The classes whose API changed since generation `since`; `None` when unknown (the log + /// doesn't reach back that far) or when everything counts as changed. + pub fn changes_since(&self, since: u64) -> Option> { + let mut changed = BTreeSet::new(); + let mut at = since; + while at != self.generation { + let change = self.changes.iter().find(|c| c.since == at)?; + if change.all { + return None; + } + changed.extend(change.classes.iter().cloned()); + at = change.generation; + } + Some(changed) + } + + pub fn log(&mut self, generation: u64, classes: BTreeSet, all: bool) { + self.changes.push(ApiChange { + since: self.generation, + generation, + classes: classes.into_iter().collect(), + all, + }); + if self.changes.len() > CHANGE_LOG { + self.changes.drain(..self.changes.len() - CHANGE_LOG); + } + self.generation = generation; + } +} + +pub(super) fn load_state(path: &Path) -> Option { + serde_json::from_slice(&std::fs::read(path).ok()?).ok() +} + +/// `seeds` and the classes of `classes` that extend or implement one of them, transitively: +/// a class that inherits a changed member changes for the classes that use it. +pub(super) fn with_subclasses(classes: &BTreeMap, seeds: &BTreeSet) -> BTreeSet { + let mut out = seeds.clone(); + loop { + let before = out.len(); + for (name, record) in classes { + if !out.contains(name) + && (record.super_name.as_ref().is_some_and(|s| out.contains(s)) + || record.interfaces.iter().any(|i| out.contains(i))) + { + out.insert(name.clone()); + } + } + if out.len() == before { + return out; + } + } +} + +/// The sources of the classes that refer to one of `affected`. +pub(super) fn dependent_sources( + classes: &BTreeMap, + affected: &BTreeSet, +) -> BTreeSet { + if affected.is_empty() { + return BTreeSet::new(); + } + classes + .iter() + .filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x))) + .filter_map(|(_, r)| r.source.clone()) + .collect() +} + +/// The sources of the classes that refer to a class with the same simple name as one of +/// `added`: a new class can take a simple name over from an on-demand import. +pub(super) fn shadowed_sources(classes: &BTreeMap, added: &BTreeSet) -> BTreeSet { + let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect(); + if names.is_empty() { + return BTreeSet::new(); + } + classes + .iter() + .filter(|(name, r)| { + !added.contains(*name) + && r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x))) + }) + .filter_map(|(_, r)| r.source.clone()) + .collect() +} + +/// What one round's classes changed, compared with the classes the round replaced. +#[derive(Debug, Default)] +pub(super) struct RoundDiff { + pub api: BTreeSet, + pub added: BTreeSet, + pub constants: bool, +} + +pub(super) fn diff(old: &BTreeMap, new: &BTreeMap) -> RoundDiff { + let mut out = RoundDiff::default(); + for (name, record) in new { + match old.get(name) { + Some(before) => { + if before.api != record.api { + out.api.insert(name.clone()); + } + if before.constants != record.constants { + out.constants = true; + } + } + None => { + out.api.insert(name.clone()); + out.added.insert(name.clone()); + } + } + } + for (name, before) in old { + if !new.contains_key(name) { + out.api.insert(name.clone()); + out.constants |= before.has_constants(); + } + } + out +} diff --git a/crates/ide-build/src/jbuild/javac.rs b/crates/ide-build/src/jbuild/javac.rs new file mode 100644 index 000000000..df6d27cc1 --- /dev/null +++ b/crates/ide-build/src/jbuild/javac.rs @@ -0,0 +1,263 @@ +//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK +//! and JVM options, kept warm between builds, compiling one request at a time in process. +use super::*; +use std::io::{BufRead, BufReader, Write}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// A message of the server about one request. +#[derive(Clone, Debug, Deserialize, PartialEq)] +#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")] +pub enum Reply { + Diagnostic { + severity: String, + path: Option, + /// 1-based. + line: Option, + /// 0-based UTF-16. + column: Option, + end_line: Option, + end_column: Option, + code: Option, + message: String, + }, + /// A class (or resource) file javac wrote, and the source it came from. + Output { + path: PathBuf, + source: Option, + }, + /// A source file an annotation processor wrote. + Generated { + path: PathBuf, + source: Option, + }, + OutputText { + text: String, + }, + Done { + success: bool, + cancelled: bool, + }, +} + +#[derive(Debug, Serialize)] +struct Request<'a> { + id: u64, + op: &'static str, + options: &'a [String], + sources: &'a [PathBuf], + encoding: Option<&'a str>, +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +pub struct ServerKey { + pub java_home: PathBuf, + /// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors). + pub jvm_args: Vec, +} + +type Pending = Arc>>>; + +pub struct JavacServer { + child: Mutex, + stdin: Mutex, + pending: Pending, + alive: Arc, + next: AtomicU64, + pub version: String, +} + +impl JavacServer { + fn start(jar: &Path, key: &ServerKey) -> IdeResult { + let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }); + let mut cmd = Command::new(&java); + cmd.args(&key.jvm_args) + .args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"]) + .arg(jar) + .arg("ai.openidea.javac.Server") + .env("JAVA_HOME", &key.java_home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + ide_core::process::prepare(&mut cmd); + ide_core::process::own_group(&mut cmd); + let mut child = + cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?; + let stdin = child.stdin.take().expect("piped"); + let stdout = child.stdout.take().expect("piped"); + let pending: Pending = Arc::default(); + let alive = Arc::new(AtomicBool::new(true)); + let (ready_tx, ready_rx) = mpsc::channel::>(); + { + let (pending, alive) = (pending.clone(), alive.clone()); + std::thread::Builder::new() + .name("javac-server".into()) + .spawn(move || { + let mut ready = Some(ready_tx); + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + let Ok(value) = serde_json::from_str::(&line) else { continue }; + match value.get("kind").and_then(|k| k.as_str()) { + Some("ready") => { + let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned(); + if let Some(ready) = ready.take() { + let _ = ready.send(Ok(version)); + } + continue; + } + Some("fatal") => { + let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned(); + if let Some(ready) = ready.take() { + let _ = ready.send(Err(message)); + } + continue; + } + _ => {} + } + let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue }; + let Ok(reply) = serde_json::from_value::(value) else { continue }; + let done = matches!(reply, Reply::Done { .. }); + let mut pending = pending.lock().unwrap(); + if let Some(tx) = pending.get(&id) { + let _ = tx.send(reply); + } + if done { + pending.remove(&id); + } + } + alive.store(false, Ordering::SeqCst); + // Requests still waiting learn that the server is gone. + for (_, tx) in pending.lock().unwrap().drain() { + let _ = tx.send(Reply::Diagnostic { + severity: "error".into(), + path: None, + line: None, + column: None, + end_line: None, + end_column: None, + code: None, + message: "The javac process exited".into(), + }); + let _ = tx.send(Reply::Done { success: false, cancelled: false }); + } + if let Some(ready) = ready.take() { + let _ = ready.send(Err("The javac process exited while starting".into())); + } + }) + .map_err(|e| IdeError::internal(e.to_string()))?; + } + let version = match ready_rx.recv_timeout(Duration::from_secs(60)) { + Ok(Ok(version)) => version, + Ok(Err(message)) => { + ide_core::process::kill_tree(&mut child); + return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display()))); + } + Err(_) => { + ide_core::process::kill_tree(&mut child); + return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display()))); + } + }; + Ok(JavacServer { + child: Mutex::new(child), + stdin: Mutex::new(stdin), + pending, + alive, + next: AtomicU64::new(1), + version, + }) + } + + fn alive(&self) -> bool { + self.alive.load(Ordering::SeqCst) + } + + fn send(&self, value: &impl Serialize) -> IdeResult<()> { + let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?; + line.push(b'\n'); + let mut stdin = self.stdin.lock().unwrap(); + stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}"))) + } + + /// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the + /// compilation ends. Cancelling stops javac at its next phase. + pub fn compile( + &self, + options: &[String], + sources: &[PathBuf], + encoding: Option<&str>, + cancel: &CancellationToken, + mut on_reply: impl FnMut(&Reply), + ) -> IdeResult { + let id = self.next.fetch_add(1, Ordering::SeqCst); + let (tx, rx) = mpsc::channel(); + self.pending.lock().unwrap().insert(id, tx); + if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) { + self.pending.lock().unwrap().remove(&id); + return Err(e); + } + let mut cancelled = false; + loop { + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(reply) => { + if let Reply::Done { success, cancelled: stopped } = reply { + if stopped || cancelled { + return Err(IdeError::cancelled()); + } + return Ok(success); + } + on_reply(&reply); + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if cancel.is_cancelled() && !cancelled { + cancelled = true; + let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id })); + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + return Err(IdeError::internal("The javac process exited")); + } + } + } + } +} + +impl Drop for JavacServer { + fn drop(&mut self) { + let _ = self.send(&serde_json::json!({ "op": "exit" })); + let mut child = self.child.lock().unwrap(); + for _ in 0..20 { + if child.try_wait().ok().flatten().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(50)); + } + ide_core::process::kill_tree(&mut child); + } +} + +/// The resident javac servers of one IDE process. +#[derive(Default)] +pub struct JavacPool { + servers: Mutex>>, +} + +impl JavacPool { + /// The running server for `key`, started on first use (or after it died). + pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult> { + let mut servers = self.servers.lock().unwrap(); + if let Some(server) = servers.get(key).filter(|s| s.alive()) { + return Ok(server.clone()); + } + let server = Arc::new(JavacServer::start(jar, key)?); + servers.insert(key.clone(), server.clone()); + Ok(server) + } + + /// Stops every server (the project closed). + pub fn shutdown(&self) { + self.servers.lock().unwrap().clear(); + } +} diff --git a/crates/ide-build/src/jbuild/mod.rs b/crates/ide-build/src/jbuild/mod.rs new file mode 100644 index 000000000..d961e1218 --- /dev/null +++ b/crates/ide-build/src/jbuild/mod.rs @@ -0,0 +1,1122 @@ +//! The IDE's own Java build of Maven and Gradle modules (#4078): javac compiles the modules a +//! launch or build needs, in a resident process, with the configuration the build tool itself +//! gives the compiler. +//! +//! - **Model.** A prepare run generates sources, processes resources and records each +//! project's source roots, classpaths, compiler configuration and annotation processor path: +//! `mvn process-resources resources:testResources` with the `java/java-build` extension, or +//! Gradle's `openideaBuildModel` task from `gradle-build.init.gradle`. It runs only when what +//! the model is built from changes ([`model::prepare_fingerprint`], +//! [`model::gradle_prepare_fingerprint`]): build scripts, settings, the launcher, generator +//! inputs, or a missing generated root. +//! - **Outputs.** The prepare run redirects every project's output into the IDE's cache, so +//! neither the language server nor a terminal build writes the classes a launch runs, and +//! projects of the build resolve to those folders, never to jars. +//! - **Compile.** Projects compile in dependency order with javac (`jbuild::javac`), class by +//! class ([`incremental`]): the changed sources, then those an API change reaches. +//! - **Fallback.** Projects the build compiles with more than javac (Kotlin, Groovy, AspectJ, +//! enhancers, another compiler id), multi-release jars and Java modules are left to the build +//! tool's own build. +mod classfile; +mod incremental; +mod javac; +mod model; + +pub use classfile::ClassFile; +pub use javac::{JavacPool, Reply, ServerKey}; + +use incremental::{ClassRecord, SetStamp, SetState}; +pub use model::{CompilerConfig, ProjectModel, ReactorModel, ResourceRoot, SourceSet}; + +use crate::compile::fingerprint; +use crate::compile::{ + BuildEvent, BuildKind, BuildMessage, BuildPlan, BuildStep, BuildSystem, LaunchFingerprint, gradle_build_step, + maven_build_step, maven_reactor_dir, reactor_projects_of, +}; +use crate::process; +use crate::{BuildModel, maven}; +use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, Severity}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn subdir(root: &Path, rel: &str) -> PathBuf { + root.join(rel).components().collect() +} + +/// The resident part of the build: javac servers and one lock per reactor. +#[derive(Default)] +pub struct JavaBuildService { + pub servers: JavacPool, + locks: Mutex>>>, +} + +impl JavaBuildService { + fn lock(&self, dir: &Path) -> Arc> { + self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone() + } +} + +/// One build of the IDE's Java build service. +pub struct JavaBuild<'a> { + pub root: &'a Path, + pub model: &'a BuildModel, + pub cache: &'a Path, + /// `java/java-build`'s jar: the javac server and the Maven extension. + pub jar: &'a Path, + /// Changes when the jar does, so models recorded by an older extension are prepared again. + pub jar_version: &'a str, + pub local_repo: Option, + pub service: &'a JavaBuildService, + /// The JDK home that compiles for a release, when Maven's environment names none. + pub jdk: &'a (dyn Fn(Option) -> Option + Sync), +} + +/// A build the service compiles: a Maven reactor (its top project) or a Gradle build. +#[derive(Clone, Copy)] +enum Reactor<'a> { + Maven(&'a maven::MavenProject), + Gradle(&'a crate::GradleModel), +} + +impl Reactor<'_> { + /// Project-relative folder of the reactor. + fn rel_dir(&self) -> &str { + match self { + Reactor::Maven(top) => &top.dir, + Reactor::Gradle(g) => &g.dir, + } + } + + /// Where its state and outputs live under the cache (`java-build/`). + fn key(&self) -> String { + match self { + Reactor::Maven(top) => top.dir.clone(), + Reactor::Gradle(g) if g.dir.is_empty() => "_gradle".into(), + Reactor::Gradle(g) => format!("{}/_gradle", g.dir), + } + } + + fn env(&self) -> &BTreeMap { + match self { + Reactor::Maven(top) => &top.env, + Reactor::Gradle(g) => &g.env, + } + } + + fn system(&self) -> BuildSystem { + match self { + Reactor::Maven(_) => BuildSystem::Maven, + Reactor::Gradle(_) => BuildSystem::Gradle, + } + } + + fn name(&self) -> &'static str { + match self { + Reactor::Maven(_) => "Maven", + Reactor::Gradle(_) => "Gradle", + } + } +} + +/// One source set to compile, and where its reactor's build keeps its state. +#[derive(Clone, Copy)] +struct SetBuild<'a> { + top: Reactor<'a>, + dir: &'a Path, + project: &'a ProjectModel, + test: bool, + outputs: &'a HashMap, + /// Sources to compile even unchanged (Recompile). + force: &'a BTreeSet, +} + +/// What a launch runs after its build. +#[derive(Debug, Default)] +pub struct LaunchOutputs { + /// The class folders of the launch's projects, then its runtime classpath. + pub class_paths: Vec, + /// Why the build failed; the class folders keep the last successful classes. + pub failure: Option, + pub messages: Vec, +} + +#[derive(Debug)] +pub enum Built { + Done(LaunchOutputs), + /// The service doesn't build this module (and why); the caller builds it with Maven. + Unsupported(String), +} + +/// `(length, mtime in ns)` of a file. +type FileStamp = (u64, u128); + +/// `(length, mtime in ns)` of a file; `None` for a folder or a missing file. +fn file_stamp(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?; + let mtime = meta.modified().ok()?.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + Some((meta.len(), mtime)) +} + +fn now_generation() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64) +} + +/// Matches Ant-style patterns (`**/*.java`, `com/acme/**`) against a `/`-separated path. +fn ant_match(pattern: &str, path: &str) -> bool { + fn segments(p: &[&str], s: &[&str]) -> bool { + match p.first() { + None => s.is_empty(), + Some(&"**") => (0..=s.len()).any(|i| segments(&p[1..], &s[i..])), + Some(seg) => !s.is_empty() && glob(seg, s[0]) && segments(&p[1..], &s[1..]), + } + } + fn glob(p: &str, s: &str) -> bool { + let (p, s): (Vec, Vec) = (p.chars().collect(), s.chars().collect()); + let (mut pi, mut si, mut star, mut mark) = (0, 0, None, 0); + while si < s.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == s[si]) { + pi += 1; + si += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = si; + pi += 1; + } else if let Some(st) = star { + pi = st + 1; + mark += 1; + si = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == '*' { + pi += 1; + } + pi == p.len() + } + let pattern = pattern.replace('\\', "/"); + let pattern = if pattern.ends_with('/') { format!("{pattern}**") } else { pattern }; + let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); + let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + segments(&p, &s) +} + +/// The `.java` files of a source set, filtered by the compiler's includes and excludes. +fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult> { + let config = set.compiler.as_ref(); + let includes = config.map(|c| c.includes.as_slice()).unwrap_or_default(); + let excludes = config.map(|c| c.excludes.as_slice()).unwrap_or_default(); + let mut out = Vec::new(); + let mut seen = HashSet::new(); + for root in &set.source_roots { + if model::is_processor_output(set, root) || !root.is_dir() { + continue; + } + let mut pending = vec![root.clone()]; + while let Some(dir) = pending.pop() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(kind) = entry.file_type() else { continue }; + if kind.is_dir() { + pending.push(path); + } else if path.extension().is_some_and(|e| e == "java") { + let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel)); + if included && !excludes.iter().any(|p| ant_match(p, &rel)) && seen.insert(path.clone()) { + out.push(path); + } + } + } + } + } + out.sort(); + Ok(out) +} + +/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them. +fn debug_args(c: &CompilerConfig) -> Vec { + if c.debug == Some(false) { + return vec!["-g:none".into()]; + } + match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) { + Some(level) => vec![format!("-g:{level}")], + None => vec!["-g".into()], + } +} + +/// The JDK feature version of `release` / `source` (`1.8` → 8). +fn feature(version: &str) -> Option { + let v = version.trim(); + v.strip_prefix("1.").unwrap_or(v).split('.').next()?.parse().ok() +} + +/// javac options for a source set, as maven-compiler-plugin builds them, except for the +/// annotation processors' output, which goes to `generated` in the IDE's outputs. +fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_major: Option) -> Vec { + let c = set.compiler.clone().unwrap_or_default(); + let mut args: Vec = vec!["-d".into(), set.output.to_string_lossy().into_owned()]; + let separator = if cfg!(windows) { ";" } else { ":" }; + args.push("-classpath".into()); + args.push( + std::iter::once(set.output.to_string_lossy().into_owned()) + .chain(classpath.iter().filter(|p| **p != set.output).map(|p| p.to_string_lossy().into_owned())) + .collect::>() + .join(separator), + ); + // Sources outside the compiled set (another root's classes) are found as classes only. + args.extend(["-sourcepath".into(), String::new()]); + args.extend(["-s".into(), generated.to_string_lossy().into_owned()]); + if let Some(path) = c.processor_path.as_ref().filter(|p| !p.is_empty()) { + args.push("-processorpath".into()); + args.push(path.iter().map(|p| p.to_string_lossy()).collect::>().join(separator)); + } + if let Some(processors) = c.annotation_processors.as_ref().filter(|p| !p.is_empty()) { + args.push("-processor".into()); + args.push(processors.join(",")); + } + if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) { + args.push(format!("-proc:{proc}")); + } + args.extend(debug_args(&c)); + if c.parameters == Some(true) { + args.push("-parameters".into()); + } + if c.enable_preview == Some(true) { + args.push("--enable-preview".into()); + } + if c.show_warnings == Some(false) { + args.push("-nowarn".into()); + } + if c.show_deprecation == Some(true) { + args.push("-deprecation".into()); + } + if let Some(encoding) = c.encoding.as_deref().filter(|e| !e.is_empty()) { + args.extend(["-encoding".into(), encoding.to_owned()]); + } + let modern = jdk_major.is_none_or(|m| m >= 9); + match c.release.as_deref().filter(|r| !r.trim().is_empty()) { + Some(release) if modern => args.extend(["--release".into(), release.trim().to_owned()]), + _ => { + if let Some(source) = c.source.as_deref().filter(|s| !s.is_empty()) { + args.extend(["-source".into(), source.to_owned()]); + } + if let Some(target) = c.target.as_deref().filter(|s| !s.is_empty()) { + args.extend(["-target".into(), target.to_owned()]); + } + } + } + for (key, value) in &c.compiler_arguments { + args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") }); + if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) { + args.push(value.clone()); + } + } + if let Some(argument) = &c.compiler_argument { + args.extend(argument.split_whitespace().map(str::to_owned)); + } + args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned()); + args +} + +/// `.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 { + if matches!(top, Reactor::Gradle(_)) { + return Vec::new(); + } + let Ok(text) = std::fs::read_to_string(top_dir.join(".mvn/jvm.config")) else { return Vec::new() }; + text.lines() + .filter(|l| !l.trim_start().starts_with('#')) + .flat_map(str::split_whitespace) + .map(|a| a.replace("${MAVEN_PROJECTBASEDIR}", &top_dir.to_string_lossy())) + .collect() +} + +fn jdk_major(home: &Path) -> Option { + let release = std::fs::read_to_string(home.join("release")).ok()?; + let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?; + feature(value.trim().trim_matches(['"', '\''])) +} + +fn message_text(m: &BuildMessage) -> String { + let severity = match m.severity { + Severity::Error => "error", + Severity::Warning => "warning", + _ => "note", + }; + match (&m.path, m.range) { + (Some(p), Some(r)) => { + format!("{}:{}:{}: {severity}: {}\n", p.display(), r.start.line + 1, r.start.col + 1, m.text) + } + (Some(p), None) => format!("{}: {severity}: {}\n", p.display(), m.text), + _ => format!("{severity}: {}\n", m.text), + } +} + +fn diagnostic(reply: &Reply) -> Option { + let Reply::Diagnostic { severity, path, line, column, end_line, end_column, code, message } = reply else { + return None; + }; + let severity = match severity.as_str() { + "error" => Severity::Error, + "warning" => Severity::Warning, + _ => Severity::Info, + }; + let range = line.map(|line| { + let start = Pos::new(line.saturating_sub(1), column.unwrap_or(0)); + let end = match (end_line, end_column) { + (Some(l), Some(c)) if *l >= line => Pos::new(l - 1, *c), + _ => start, + }; + Range::new(start, end) + }); + Some(BuildMessage { + severity, + text: message.clone(), + path: path.clone().map(Into::into), + range, + code: code.clone(), + }) +} + +/// What a build compiles. +#[derive(Clone, Copy, Debug)] +pub enum Target<'p> { + /// What the launch of the module at this folder runs: its main (or test) classes and the + /// reactor projects they depend on. + Launch { module: &'p Path, test: bool }, + /// Build Module: the main and test classes of the module holding this file or folder, and + /// the reactor projects they depend on. + Module(&'p Path), + /// Build Project: every module of every linked reactor. + Project, + /// Recompile: this source, even unchanged, and what its changes reach. + File(&'p Path), +} + +impl JavaBuild<'_> { + /// Builds what the launch of `module` runs (its main or test classes and the reactor + /// projects they depend on) and returns the classpath to run it with. + pub fn build_launch( + &self, + module: &Path, + test: bool, + kind: BuildKind, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + ) -> IdeResult { + self.build(Target::Launch { module, test }, kind, cancel, on_event) + } + + /// The Maven reactor or Gradle build of the module holding `path`, and the module's folder. + fn reactor_and_module(&self, path: &Path) -> Option<(Reactor<'_>, PathBuf)> { + let rel = |dir: &Path| dir.strip_prefix(self.root).unwrap_or(dir).to_string_lossy().replace('\\', "/"); + // The deepest project folder holding it, of either build tool. + let maven = self.model.maven.iter().flat_map(|m| m.projects.iter().map(|p| subdir(self.root, &p.dir))); + let gradle = self.model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| subdir(self.root, &p.dir))); + let dir = maven.chain(gradle).filter(|dir| path.starts_with(dir)).max_by_key(|dir| dir.components().count())?; + if let Some(m) = &self.model.maven + && let Some(top) = maven_reactor_dir(m, &rel(&dir)) + { + return Some((Reactor::Maven(top), dir)); + } + let g = self.model.gradle_for_module(self.root, &dir)?; + Some((Reactor::Gradle(g), dir)) + } + + fn reactor_of(&self, module: &Path) -> Option> { + self.reactor_and_module(module).map(|(top, _)| top) + } + + /// The classpath a launch of `module` runs with when it doesn't build (Before launch: no + /// build): the outputs of the last build, `None` when the module was never built here. + pub fn recorded_launch(&self, module: &Path, test: bool) -> Option> { + let top = self.reactor_of(module)?; + let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?; + let project = record.model.projects.iter().find(|p| p.dir == module)?; + let paths = class_paths(project, test); + paths.first().is_some_and(|p| p.is_dir()).then_some(paths) + } + + /// Builds `target`. A launch gets the classpath to run with; the others an empty one. + pub fn build( + &self, + target: Target, + kind: BuildKind, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + ) -> IdeResult { + let rel = |path: &Path| path.strip_prefix(self.root).unwrap_or(path).to_string_lossy().replace('\\', "/"); + let (tops, title) = match target { + Target::Project => { + let maven = self.model.maven.iter().flat_map(|m| m.projects.iter().filter(|p| !p.aggregated)); + let tops: Vec = + maven.map(Reactor::Maven).chain(self.model.gradle.iter().map(Reactor::Gradle)).collect(); + let name = self.root.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + (tops, format!("Build '{name}'")) + } + Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => { + let Some((top, dir)) = self.reactor_and_module(module) else { + return Ok(Built::Unsupported("the file belongs to no Maven or Gradle module".into())); + }; + let name = match target { + Target::File(file) => file.file_name(), + _ => dir.file_name(), + } + .map_or_else(|| rel(&dir), |n| n.to_string_lossy().into_owned()); + (vec![top], format!("Build '{name}'")) + } + }; + if tops.is_empty() { + return Ok(Built::Unsupported("no Maven or Gradle build".into())); + } + on_event(BuildEvent::Started { system: BuildSystem::Javac, title }); + // Nested Maven and Gradle runs report into the same build. + let nested = |event: BuildEvent| { + if !matches!(event, BuildEvent::Started { .. }) { + on_event(event); + } + }; + let mut messages = Vec::new(); + let mut class_path = Vec::new(); + for top in tops { + let dir = model::reactor_dir(self.cache, &top.key()); + let lock = self.service.lock(&dir); + let _guard = lock.lock().unwrap(); + let Some(reactor_model) = self.prepared(top, &dir, kind, cancel, &nested)? else { + // The build tool's own build reports why (a build script error, a version the + // extension doesn't load in). + return Ok(Built::Unsupported(format!("{} could not prepare the build", top.name()))); + }; + let project_at = |path: &Path| { + reactor_model + .projects + .iter() + .filter(|p| path.starts_with(&p.dir)) + .max_by_key(|p| p.dir.components().count()) + }; + let mut force = BTreeSet::new(); + let projects: Vec<(&ProjectModel, bool)> = match target { + Target::Launch { module, test } => { + let Some(project) = reactor_model.projects.iter().find(|p| p.dir == module) else { + return Ok(Built::Unsupported(format!( + "the build has no Java project at {}", + module.display() + ))); + }; + class_path = class_paths(project, test); + launch_projects(&reactor_model, project, test) + } + Target::Module(path) => { + let Some(project) = project_at(path) else { + return Ok(Built::Unsupported(format!("no Java project holds {}", path.display()))); + }; + launch_projects(&reactor_model, project, true) + } + Target::File(file) => { + let Some(project) = project_at(file) else { + return Ok(Built::Unsupported(format!("no Java project holds {}", file.display()))); + }; + let test = project.test.source_roots.iter().any(|r| file.starts_with(r)); + force.insert(file.to_path_buf()); + launch_projects(&reactor_model, project, test) + } + Target::Project => { + let mut all: Vec<(&ProjectModel, bool)> = Vec::new(); + for project in &reactor_model.projects { + for set in launch_projects(&reactor_model, project, true) { + if !all.iter().any(|(p, t)| p.dir == set.0.dir && *t == set.1) { + all.push(set); + } + } + } + all + } + }; + for (project, test) in &projects { + if let Some(reason) = project.unsupported(*test) { + return Ok(Built::Unsupported(reason)); + } + // A launch of a Java module runs it from the module path, which the language server reports. + if project.main.source_roots.iter().any(|r| r.join("module-info.java").is_file()) { + return Ok(Built::Unsupported(format!("{} is a Java module", project.artifact_id))); + } + } + if kind == BuildKind::Rebuild { + for (project, test) in &projects { + self.clean(&dir, project, *test)?; + } + } + if let Some(mut failure) = self.resources(top, &dir, &projects, cancel, &nested)? { + failure.class_paths = class_path; + return Ok(Built::Done(failure)); + } + let outputs: HashMap = reactor_model + .projects + .iter() + .flat_map(|p| [(p.main.output.clone(), (p.key(), false)), (p.test.output.clone(), (p.key(), true))]) + .collect(); + let total = projects.len(); + for (i, (project, tests)) in projects.iter().enumerate() { + on_event(BuildEvent::Progress { + message: format!("Compiling {}", project.artifact_id), + fraction: Some(i as f32 / total.max(1) as f32), + }); + let set = SetBuild { top, dir: &dir, project, test: *tests, outputs: &outputs, force: &force }; + if self.compile_set(&set, cancel, on_event, &mut messages)? { + let errors: Vec = messages + .iter() + .filter(|m| m.severity == Severity::Error) + .take(5) + .map(|m| message_text(m).trim_end().to_owned()) + .collect(); + let failure = format!("Build failed:\n{}", errors.join("\n")); + return Ok(Built::Done(LaunchOutputs { + class_paths: class_path, + failure: Some(failure), + messages, + })); + } + } + } + Ok(Built::Done(LaunchOutputs { class_paths: class_path, failure: None, messages })) + } + + /// The reactor's model, from the record when it is current, else from a prepare run. + /// `None` when the prepare run failed. + fn prepared( + &self, + top: Reactor, + dir: &Path, + kind: BuildKind, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + ) -> IdeResult> { + let out = model::output_root(self.cache, &top.key()); + let model_file = dir.join("model.json"); + let (step, fingerprint) = match top { + Reactor::Maven(top) => { + let m = self.model.maven.as_ref().expect("a Maven reactor"); + let reactor = reactor_projects_of(m, top); + let goals = ["process-resources".to_owned(), "resources:testResources".to_owned()]; + let step = model::maven_step(self.root, top, self.jar, &out, Some(&model_file), &goals); + let fingerprint = model::prepare_fingerprint( + self.root, + &reactor, + &step, + self.local_repo.clone(), + self.jar_version, + cancel, + )?; + (step, fingerprint) + } + Reactor::Gradle(g) => { + let init = model::gradle_init_script(dir)?; + let tasks = ["openideaBuildModel".to_owned()]; + let step = model::gradle_step(self.root, g, &init, &out, Some(&model_file), &tasks); + let fingerprint = model::gradle_prepare_fingerprint(self.root, g, &step, self.jar_version, cancel)?; + (step, Some(fingerprint)) + } + }; + if kind != BuildKind::Rebuild + && let (Some(current), Some(record)) = (&fingerprint, model::load_record(dir)) + && record.fingerprint == *current + && model::generated_roots_exist(&record.model) + { + return Ok(Some(record.model)); + } + on_event(BuildEvent::Progress { + message: format!("Generating sources and reading the {} build", top.name()), + fraction: None, + }); + let _ = std::fs::remove_file(&model_file); + let plan = BuildPlan { system: top.system(), title: String::new(), steps: vec![step] }; + let result = crate::compile::run(self.root, &plan, cancel, on_event)?; + if !result.success { + return Ok(None); + } + let reactor_model = model::read_model(&model_file)?; + if let Some(fingerprint) = fingerprint { + model::save_record(dir, &model::PrepareRecord { fingerprint, model: reactor_model.clone() })?; + } + // The prepare run processed every project's resources. + for project in &reactor_model.projects { + for test in [false, true] { + let stamp = resource_stamp(project.set(test), cancel)?; + model::write_json(&state_path(dir, project, test, "resources"), &stamp)?; + } + } + Ok(Some(reactor_model)) + } + + /// Processes the resources that changed since they were last processed, with the build + /// tool (filtering, includes, target paths), into the IDE's outputs. `Some` on failure. + fn resources( + &self, + top: Reactor, + dir: &Path, + projects: &[(&ProjectModel, bool)], + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + ) -> IdeResult> { + let mut changed: Vec<(&ProjectModel, bool, BTreeMap)> = Vec::new(); + for (project, test) in projects { + let stamp = resource_stamp(project.set(*test), cancel)?; + let recorded: Option> = + std::fs::read(state_path(dir, project, *test, "resources")) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + if recorded.as_ref() != Some(&stamp) { + changed.push((project, *test, stamp)); + } + } + if changed.is_empty() { + return Ok(None); + } + on_event(BuildEvent::Progress { message: "Processing resources".into(), fraction: None }); + let out = model::output_root(self.cache, &top.key()); + let step = match top { + Reactor::Maven(top) => { + let top_dir = subdir(self.root, &top.dir); + let mut selection: Vec = changed + .iter() + .map(|(p, _, _)| { + let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/"); + if rel.is_empty() { ".".to_owned() } else { rel } + }) + .collect(); + selection.sort(); + selection.dedup(); + let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")]; + extra.push("resources:resources".into()); + if changed.iter().any(|(_, test, _)| *test) { + extra.push("resources:testResources".into()); + } + model::maven_step(self.root, top, self.jar, &out, None, &extra) + } + Reactor::Gradle(g) => { + let mut tasks = vec!["-q".to_owned()]; + for (project, test, _) in &changed { + let path = project.gradle_path.as_deref().unwrap_or(":"); + let prefix = if path == ":" { String::new() } else { format!("{path}:") }; + tasks.push(format!("{prefix}{}", if *test { "processTestResources" } else { "processResources" })); + } + let init = model::gradle_init_script(dir)?; + model::gradle_step(self.root, g, &init, &out, None, &tasks) + } + }; + let plan = BuildPlan { system: top.system(), title: String::new(), steps: vec![step] }; + let result = crate::compile::run(self.root, &plan, cancel, on_event)?; + if !result.success { + return Ok(Some(LaunchOutputs { + class_paths: Vec::new(), + failure: Some(format!("{} could not process the resources", top.name())), + messages: result.messages, + })); + } + for (project, test, stamp) in changed { + model::write_json(&state_path(dir, project, test, "resources"), &stamp)?; + } + Ok(None) + } + + /// Removes the classes of a source set and its record: the next build compiles it from scratch. + fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> { + let set = project.set(test); + remove_classes(&set.output); + let _ = std::fs::remove_dir_all(generated_dir(dir, project, test)); + let _ = std::fs::remove_file(state_path(dir, project, test, "compile")); + Ok(()) + } + + /// Compiles what changed in one source set (see [`incremental`]). Returns whether it failed. + fn compile_set( + &self, + build: &SetBuild, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + messages: &mut Vec, + ) -> IdeResult { + let SetBuild { top, dir, project, test, outputs, force } = *build; + let set = project.set(test); + if set.compiler.as_ref().is_some_and(|c| c.skip == Some(true)) || set.compiler.is_none() { + return Ok(false); + } + let sources = java_sources(set, cancel)?; + let source_stamps: BTreeMap = + sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect(); + let state_file = state_path(dir, project, test, "compile"); + let previous = incremental::load_state(&state_file); + let config = set.compiler.clone().unwrap_or_default(); + let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature); + let java_home = self.java_home(top, &config, release)?; + let generated = generated_dir(dir, project, test); + let classpath: Vec = if test { + std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect() + } else { + set.classpath.clone() + }; + let options = javac_options(set, &classpath, &generated, jdk_major(&java_home)); + let reactor: Vec = + classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect(); + let stamp = SetStamp { + options: options.clone(), + libraries: classpath + .iter() + .filter(|e| **e != set.output && !outputs.contains_key(*e)) + .map(|e| (e.clone(), file_stamp(e))) + .collect(), + reactor: reactor.clone(), + processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(), + java_home: java_home.clone(), + }; + + // What the reactor outputs it compiles against changed since it last compiled. + let mut upstream = BTreeMap::new(); + let mut upstream_changed = BTreeSet::new(); + let mut upstream_all = false; + for entry in &reactor { + let (key, entry_test) = &outputs[entry]; + let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile")); + let generation = state.as_ref().map_or(0, |s| s.generation); + upstream.insert(entry.clone(), generation); + let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied(); + if recorded == Some(generation) { + continue; + } + match (recorded, state.and_then(|s| s.changes_since(recorded?))) { + (Some(_), Some(changed)) => upstream_changed.extend(changed), + _ => upstream_all = true, + } + } + + let had_state = previous.is_some(); + let previous = previous.unwrap_or_default(); + let changed: BTreeSet = source_stamps + .iter() + .filter(|(path, stamp)| { + previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path) + }) + .map(|(path, _)| path.clone()) + .collect(); + let removed: BTreeSet = + previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect(); + let from_scratch = !had_state + || previous.stamp != stamp + || upstream_all + || !set.output.is_dir() + || (!previous.success && previous.dirty.is_empty()); + if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() { + return Ok(false); + } + // Processors that aggregate (or name no originating source) can't be followed class by class. + let from_scratch = from_scratch + || (!previous.generated.is_empty() || !previous.unowned.is_empty()) + && !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty()); + + let mut state = SetState { + stamp, + sources: source_stamps.clone(), + generation: previous.generation, + upstream, + classes: previous.classes, + changes: previous.changes, + ..Default::default() + }; + let mut api_changed = BTreeSet::new(); + let mut constants_changed = false; + // Classes of removed sources go first, and count as changed. + let gone: Vec = state + .classes + .iter() + .filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s))) + .map(|(n, _)| n.clone()) + .collect(); + for name in gone { + let record = state.classes.remove(&name).expect("listed"); + let _ = std::fs::remove_file(&record.file); + constants_changed |= record.constants != incremental::NO_CONSTANTS; + api_changed.insert(name); + } + let mut to_compile: BTreeSet = if from_scratch || constants_changed { + remove_classes(&set.output); + for file in previous.generated.iter().chain(&previous.unowned) { + let _ = std::fs::remove_file(file); + } + let _ = std::fs::remove_dir_all(&generated); + state.classes.retain(|_, r| r.source.is_some()); + 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() + }; + std::fs::create_dir_all(&set.output)?; + std::fs::create_dir_all(&generated)?; + + let set_name = if test { "tests" } else { "main" }; + let total = source_stamps.len(); + let mut compiled: BTreeSet = BTreeSet::new(); + let mut server = None; + loop { + let batch: BTreeSet = to_compile + .iter() + .filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s)) + .cloned() + .collect(); + if batch.is_empty() { + break; + } + // The classes the batch replaces: their files go first, so nothing stale is left. + let replaced: BTreeMap = state + .classes + .iter() + .filter(|(_, r)| r.source.as_ref().is_some_and(|s| 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); + } + let files: Vec = batch.iter().cloned().collect(); + let noun = if total == 1 { "file" } else { "files" }; + let count = if files.len() == total { + format!("{total} {noun}") + } else { + format!("{} of {total} {noun}", files.len()) + }; + on_event(BuildEvent::Step { + command: format!("javac {} ({set_name}, {count})", project.artifact_id), + cwd: project.dir.clone().into(), + }); + if server.is_none() { + let key = ServerKey { + java_home: java_home.clone(), + jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())), + }; + server = Some(self.service.servers.server(self.jar, &key)?); + } + let mut written: Vec<(PathBuf, Option)> = Vec::new(); + let result = server.as_ref().expect("started").compile( + &options, + &files, + config.encoding.as_deref(), + cancel, + |reply| match reply { + Reply::Output { path, source } => written.push((path.clone(), source.clone())), + Reply::Generated { path, .. } => state.generated.push(path.clone()), + Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }), + Reply::Diagnostic { .. } => { + if let Some(m) = diagnostic(reply) { + on_event(BuildEvent::Output { + text: message_text(&m), + stderr: m.severity == Severity::Error, + }); + on_event(BuildEvent::Message { message: m.clone() }); + messages.push(m); + } + } + Reply::Done { .. } => {} + }, + ); + if !matches!(result, Ok(true)) { + for (path, _) in &written { + let _ = std::fs::remove_file(path); + } + // The next build starts from the state this one started from, with whatever this + // one had to compile still to compile. Its earlier rounds' classes are not the + // baseline: compared with them, the API and constant changes those rounds found + // would never reach this set's dependents or the sets compiled against it. + let mut retry = incremental::load_state(&state_file).unwrap_or_default(); + retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned()); + retry.success = false; + let _ = model::write_json(&state_file, &retry); + return result.map(|_| true); + } + // javac names sources as they were passed; other spellings are matched canonically, + // and classes of sources outside the set (processors' output) are unowned. + let canonical: HashMap = + batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect(); + let own = |source: PathBuf| -> Option { + if source_stamps.contains_key(&source) { + return Some(source); + } + canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone()) + }; + let mut fresh = BTreeMap::new(); + for (path, source) in written { + let source = source.and_then(own); + let class = (path.extension().is_some_and(|e| e == "class")) + .then(|| std::fs::read(&path).ok()) + .flatten() + .and_then(|bytes| classfile::parse(&bytes)); + match (class, source) { + (Some(class), Some(source)) => { + let (name, record) = ClassRecord::new(class, path, Some(source)); + fresh.insert(name, record); + } + _ => state.unowned.push(path), + } + } + let round = incremental::diff(&replaced, &fresh); + constants_changed |= round.constants; + api_changed.extend(round.api.iter().cloned()); + state.classes.extend(fresh); + compiled.extend(batch); + if constants_changed { + // Constants are copied into the classes that use them: compile the rest too. + to_compile.extend(source_stamps.keys().cloned()); + continue; + } + 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)); + } + state.success = true; + if !compiled.is_empty() || !api_changed.is_empty() { + let changed = + incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect()); + state.log(now_generation(), changed, !had_state || constants_changed); + } + model::write_json(&state_file, &state)?; + Ok(false) + } + + /// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's + /// `JAVA_HOME`, else one for the release. + fn java_home(&self, top: Reactor, config: &CompilerConfig, release: Option) -> IdeResult { + if config.fork == Some(true) + && let Some(home) = config.executable.as_deref().map(Path::new).and_then(|e| e.parent()?.parent()) + && home.join("bin").is_dir() + { + return Ok(home.to_path_buf()); + } + if let Some(home) = top.env().get("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir()) { + return Ok(home); + } + (self.jdk)(release).ok_or_else(|| { + IdeError::unavailable(match release { + Some(release) => format!("No JDK {release} or newer is installed to compile the module"), + None => "No JDK is installed to compile the module".to_owned(), + }) + }) + } +} + +/// The source sets a launch of `target` needs, dependencies first: its main classes (and +/// its test classes for a test launch) and the reactor projects on their classpath. +fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test: bool) -> Vec<(&'a ProjectModel, bool)> { + let by_output: HashMap<&Path, &ProjectModel> = + model.projects.iter().map(|p| (p.main.output.as_path(), p)).collect(); + let by_test_output: HashMap<&Path, &ProjectModel> = + model.projects.iter().map(|p| (p.test.output.as_path(), p)).collect(); + fn visit<'a>( + project: &'a ProjectModel, + test: bool, + by_output: &HashMap<&Path, &'a ProjectModel>, + by_test_output: &HashMap<&Path, &'a ProjectModel>, + seen: &mut HashSet<(PathBuf, bool)>, + out: &mut Vec<(&'a ProjectModel, bool)>, + ) { + if !seen.insert((project.dir.clone(), test)) { + return; + } + if test { + visit(project, false, by_output, by_test_output, seen, out); + } + for entry in &project.set(test).classpath { + if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) { + visit(upstream, false, by_output, by_test_output, seen, out); + } else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) { + visit(upstream, true, by_output, by_test_output, seen, out); + } + } + out.push((project, test)); + } + let mut out = Vec::new(); + visit(target, test, &by_output, &by_test_output, &mut HashSet::new(), &mut out); + out +} + +/// The launch classpath: the target's class folders, then its runtime classpath. +fn class_paths(target: &ProjectModel, test: bool) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |p: &PathBuf| { + if !out.contains(p) { + out.push(p.clone()); + } + }; + if test { + push(&target.test.output); + } + push(&target.main.output); + for entry in &target.set(test).runtime_classpath { + push(entry); + } + out +} + +fn state_path(dir: &Path, project: &ProjectModel, test: bool, what: &str) -> PathBuf { + state_path_of(dir, &project.key(), test, what) +} + +fn state_path_of(dir: &Path, key: &str, test: bool, what: &str) -> PathBuf { + dir.join("state").join(key.replace(':', ".")).join(format!("{}-{what}.json", if test { "test" } else { "main" })) +} + +fn generated_dir(dir: &Path, project: &ProjectModel, test: bool) -> PathBuf { + dir.join("generated").join(project.key().replace(':', ".")).join(if test { + "test-annotations" + } else { + "annotations" + }) +} + +/// Deletes the `.class` files under `dir`, keeping the resources next to them. +fn remove_classes(dir: &Path) { + let mut pending = vec![dir.to_path_buf()]; + while let Some(dir) = pending.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + if entry.file_type().is_ok_and(|t| t.is_dir()) { + pending.push(path); + } else if path.extension().is_some_and(|e| e == "class") { + let _ = std::fs::remove_file(path); + } + } + } +} + +/// `(length, mtime)` of every file in a source set's resource folders. +fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult> { + let mut out = BTreeMap::new(); + for root in &set.resources { + let mut pending = vec![root.directory.clone()]; + while let Some(dir) = pending.pop() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + if entry.file_type().is_ok_and(|t| t.is_dir()) { + pending.push(path); + } else if let Some(stamp) = file_stamp(&path) { + out.insert(path, stamp); + } + } + } + } + Ok(out) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ide-build/src/jbuild/model.rs b/crates/ide-build/src/jbuild/model.rs new file mode 100644 index 000000000..dfafe407f --- /dev/null +++ b/crates/ide-build/src/jbuild/model.rs @@ -0,0 +1,342 @@ +//! The build model of a Maven reactor or Gradle build as the build tool itself configures it, +//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due. +use super::*; +use std::fs; + +/// `model.json` of the prepare run (see `BuildModel.java`). +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReactorModel { + pub version: u32, + pub projects: Vec, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProjectModel { + /// Absolute project directory. + pub dir: PathBuf, + pub group_id: String, + pub artifact_id: String, + pub version: String, + pub packaging: String, + pub main: SourceSet, + pub test: SourceSet, + /// Executions in the compile phases that aren't javac (`group:artifact:goal@id`). + #[serde(default)] + pub other_compilers: Vec, + /// Test source generators the prepare run doesn't reach. + #[serde(default)] + pub test_generators: Vec, + #[serde(default)] + pub problems: Vec, + /// The Gradle project path (`:`, `:app`); `None` for Maven. + #[serde(default)] + pub gradle_path: Option, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceSet { + pub source_roots: Vec, + pub output: PathBuf, + pub classpath: Vec, + pub runtime_classpath: Vec, + #[serde(default)] + pub resources: Vec, + pub compiler: Option, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ResourceRoot { + pub directory: PathBuf, + #[serde(default)] + pub filtering: bool, + pub target_path: Option, + #[serde(default)] + pub includes: Vec, + #[serde(default)] + pub excludes: Vec, +} + +/// maven-compiler-plugin's configuration of one source set, as its mojo was configured. +#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CompilerConfig { + pub compiler_id: Option, + pub source: Option, + pub target: Option, + pub release: Option, + pub encoding: Option, + pub parameters: Option, + pub debug: Option, + pub debuglevel: Option, + pub proc: Option, + pub enable_preview: Option, + pub fork: Option, + pub executable: Option, + pub skip: Option, + pub show_warnings: Option, + pub show_deprecation: Option, + pub generated_sources_directory: Option, + #[serde(default)] + pub includes: Vec, + #[serde(default)] + pub excludes: Vec, + pub annotation_processors: Option>, + #[serde(default)] + pub compiler_args: Vec, + pub compiler_argument: Option, + #[serde(default)] + pub compiler_arguments: BTreeMap>, + pub multi_release_output: Option, + pub processor_path: Option>, + pub processor_path_error: Option, +} + +impl ProjectModel { + pub fn key(&self) -> String { + format!("{}:{}", self.group_id, self.artifact_id) + } + + pub fn set(&self, test: bool) -> &SourceSet { + if test { &self.test } else { &self.main } + } + + /// Why the IDE can't compile this project with javac itself, if it can't. + pub fn unsupported(&self, test: bool) -> Option { + // What the build tool couldn't resolve or read: the model would be incomplete. + if let Some(problem) = self.problems.first() { + return Some(format!("{}: {problem}", self.artifact_id)); + } + if !self.other_compilers.is_empty() { + return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", "))); + } + if test && !self.test_generators.is_empty() { + return Some(format!( + "{} generates test sources with {}", + self.artifact_id, + self.test_generators.join(", ") + )); + } + for set in [&self.main, &self.test] { + let Some(c) = &set.compiler else { continue }; + if c.compiler_id.as_deref().is_some_and(|id| id != "javac") { + return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap())); + } + if c.multi_release_output == Some(true) { + return Some(format!("{} is a multi-release jar", self.artifact_id)); + } + if let Some(error) = &c.processor_path_error { + return Some(format!("{}: {error}", self.artifact_id)); + } + } + None + } +} + +/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs. +pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf { + let base = cache.join("java-build"); + if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) } +} + +/// The outputs of every project, `/./classes`, as the extension +/// redirects them (`-Dopenidea.build.output=`). +pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf { + reactor_dir(cache, top_dir).join("out") +} + +/// What the recorded model was prepared from. +#[derive(Debug, Deserialize, Serialize)] +pub(super) struct PrepareRecord { + pub fingerprint: LaunchFingerprint, + pub model: ReactorModel, +} + +const MODEL_VERSION: u32 = 1; + +/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher, +/// and generator inputs (any `src//` that isn't Java sources or resources: +/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves. +pub(super) fn prepare_fingerprint( + root: &Path, + reactor: &[&maven::MavenProject], + step: &BuildStep, + local_repo: Option, + jar_version: &str, + cancel: &CancellationToken, +) -> IdeResult> { + let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) }; + for project in reactor { + let src = subdir(root, &project.dir).join("src"); + for set in fs::read_dir(&src).into_iter().flatten().flatten() { + for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() { + let name = dir.file_name(); + if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) { + inputs.push(dir.path()); + } + } + } + } + for dir in step.cwd.ancestors() { + inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]); + if dir == root { + break; + } + } + inputs.push(process::program_path(&step.program, &step.env, &step.cwd)); + if let Some(home) = dirs::home_dir() { + inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]); + } + if let Some(home) = step.env.get("JAVA_HOME") { + inputs.push(Path::new(home).join("release")); + } + inputs.sort(); + inputs.dedup(); + let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env)) + .map_err(|e| IdeError::internal(e.to_string()))?; + Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))) +} + +pub(super) fn load_record(dir: &Path) -> Option { + let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?; + (record.model.version == MODEL_VERSION).then_some(record) +} + +pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> { + write_json(&dir.join("prepare.json"), record) +} + +pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> { + let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?; + fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?; + file.persist(path).map_err(|e| IdeError::from(e.error))?; + Ok(()) +} + +/// Whether the generated source roots the model lists still exist: `mvn clean` removes them. +pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool { + model.projects.iter().all(|p| { + [&p.main, &p.test].iter().all(|set| { + set.source_roots.iter().all(|root| { + root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root) + }) + }) + }) +} + +/// The annotation processors' output folder, which javac writes into and never reads as a root. +pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool { + set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root) +} + +/// A Maven step at the reactor root running `goals` with the IDE's extension loaded. +pub(super) fn maven_step( + root: &Path, + top: &maven::MavenProject, + jar: &Path, + output_root: &Path, + model_file: Option<&Path>, + extra: &[String], +) -> BuildStep { + let mut step = maven_build_step( + &top.command, + &["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG], + &subdir(root, &top.dir), + ); + step.args.extend(top.options.iter().cloned()); + step.args.push(format!("-Dmaven.ext.class.path={}", jar.display())); + step.args.push(format!("-Dopenidea.build.output={}", output_root.display())); + if let Some(file) = model_file { + step.args.push(format!("-Dopenidea.build.model={}", file.display())); + } + step.args.extend(extra.iter().cloned()); + step.env = top.env.clone(); + step +} + +/// The init script that gives a Gradle build the IDE's outputs and writes its model. +const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle"); + +/// Writes the init script into the build's state folder, and returns its path. +pub(super) fn gradle_init_script(dir: &Path) -> IdeResult { + fs::create_dir_all(dir)?; + let path = dir.join("openidea-build.init.gradle"); + if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) { + fs::write(&path, GRADLE_INIT_SCRIPT)?; + } + Ok(path) +} + +/// A Gradle step at the build's root running `tasks` with the IDE's init script. +pub(super) fn gradle_step( + root: &Path, + g: &crate::GradleModel, + init: &Path, + output_root: &Path, + model_file: Option<&Path>, + tasks: &[String], +) -> BuildStep { + let mut step = gradle_build_step( + &g.command, + // The init script configures the evaluated projects, which a configuration cache skips. + &["--console=plain", "--no-configuration-cache"], + &subdir(root, &g.dir), + ); + step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]); + step.args.push(format!("-Popenidea.build.output={}", output_root.display())); + if let Some(file) = model_file { + step.args.push(format!("-Popenidea.build.model={}", file.display())); + } + step.args.extend(tasks.iter().cloned()); + step.env = g.env.clone(); + step +} + +/// Files a Gradle build's model depends on: settings and build scripts (with what they apply), +/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs. +pub(super) fn gradle_prepare_fingerprint( + root: &Path, + g: &crate::GradleModel, + step: &BuildStep, + jar_version: &str, + cancel: &CancellationToken, +) -> IdeResult { + let mut inputs = crate::gradle::build_files(root, g); + let dir = subdir(root, &g.dir); + inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]); + for project in &g.projects { + let src = subdir(root, &project.dir).join("src"); + for set in fs::read_dir(&src).into_iter().flatten().flatten() { + for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() { + let name = generator.file_name(); + if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) { + inputs.push(generator.path()); + } + } + } + } + inputs.push(process::program_path(&step.program, &step.env, &step.cwd)); + if let Some(home) = dirs::home_dir() { + inputs.push(home.join(".gradle/gradle.properties")); + inputs.push(home.join(".gradle/init.d")); + } + if let Some(home) = step.env.get("JAVA_HOME") { + inputs.push(Path::new(home).join("release")); + } + inputs.sort(); + inputs.dedup(); + let parameters = + serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env)) + .map_err(|e| IdeError::internal(e.to_string()))?; + Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)) +} + +pub(super) fn read_model(path: &Path) -> IdeResult { + let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?; + serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}"))) +} diff --git a/crates/ide-build/src/jbuild/tests.rs b/crates/ide-build/src/jbuild/tests.rs new file mode 100644 index 000000000..a11427d04 --- /dev/null +++ b/crates/ide-build/src/jbuild/tests.rs @@ -0,0 +1,544 @@ +use super::*; +use crate::BuildModel; +use std::fs; +use std::sync::Mutex as StdMutex; + +const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar"); + +fn write(root: &Path, rel: &str, text: &str) { + let path = root.join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped). +fn tools() -> Option<(PathBuf, PathBuf)> { + let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?; + let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?; + Some((home, mvn)) +} + +const ROOT_POM: &str = r#"4.0.0troot1pom +libapp +11UTF-8 +maven-compiler-plugin3.13.0 +true"#; +const LIB_POM: &str = r#"4.0.0troot1lib"#; +const APP_POM: &str = r#"4.0.0troot1app +tlib1 +src/main/resourcestrue"#; + +/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK. +struct Fixture { + _tmp: tempfile::TempDir, + root: PathBuf, + cache: PathBuf, + model: BuildModel, + /// Where the build keeps its state under the cache (`Reactor::key`). + key: &'static str, + service: JavaBuildService, + events: StdMutex>, +} + +impl Fixture { + fn new(files: &[(&str, &str)]) -> Option { + let Some((home, mvn)) = tools() else { + eprintln!("skipped: needs JAVA_HOME and mvn"); + return None; + }; + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + for (rel, text) in + [("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files) + { + write(&root, rel, text); + } + let cache = root.join(".cache"); + let mut model = crate::load(&root, &cache, None); + for p in &mut model.maven.as_mut().unwrap().projects { + p.command = mvn.to_string_lossy().into_owned(); + p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned()); + } + Some(Fixture { + _tmp: tmp, + root, + cache, + model, + key: "", + service: JavaBuildService::default(), + events: StdMutex::default(), + }) + } + + /// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the + /// search path). + fn gradle(files: &[(&str, &str)]) -> Option { + let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir()); + let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())); + let (Some(home), Some(gradle)) = (home, gradle) else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return None; + }; + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let build = [ + ("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"), + ( + "build.gradle", + "subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n", + ), + ("lib/build.gradle", ""), + ( + "app/build.gradle", + "dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n", + ), + ]; + for (rel, text) in build.iter().chain(files) { + write(&root, rel, text); + } + let cache = root.join(".cache"); + let mut model = crate::load(&root, &cache, None); + assert_eq!(model.gradle.len(), 1, "{model:?}"); + let g = &mut model.gradle[0]; + g.command = gradle.to_string_lossy().into_owned(); + g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned()); + Some(Fixture { + _tmp: tmp, + root, + cache, + model, + key: "_gradle", + service: JavaBuildService::default(), + events: StdMutex::default(), + }) + } + + fn write(&self, rel: &str, text: &str) { + write(&self.root, rel, text); + } + + fn out(&self, rel: &str) -> PathBuf { + model::output_root(&self.cache, self.key).join(rel) + } + + /// Builds the launch of `app` (its tests when `test`). + fn launch(&self, test: bool) -> LaunchOutputs { + self.build(Target::Launch { module: &self.root.join("app"), test }) + } + + fn build(&self, target: Target) -> LaunchOutputs { + let jdk = |_: Option| None; + let build = JavaBuild { + root: &self.root, + model: &self.model, + cache: &self.cache, + jar: Path::new(JAR), + jar_version: "test", + local_repo: None, + service: &self.service, + jdk: &jdk, + }; + let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e); + match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) { + Ok(Built::Done(outputs)) => outputs, + Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"), + Err(e) => panic!("{e:?}"), + } + } + + /// The steps of the launch builds since the last call. + fn steps(&self) -> Vec { + self.events + .lock() + .unwrap() + .drain(..) + .filter_map(|e| match e { + BuildEvent::Step { command, .. } => Some(command), + _ => None, + }) + .collect() + } + + /// Builds and returns the steps it took, which must succeed. + fn steps_of_launch(&self) -> Vec { + self.steps(); + let built = self.launch(false); + assert_eq!(built.failure, None, "{:?}", built.messages); + self.steps() + } +} + +#[test] +fn builds_maven_modules_with_javac_and_only_what_changed() { + let Some(f) = Fixture::new(&[ + ( + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib\"; } }\n", + ), + ( + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n", + ), + ("app/src/main/resources/app.properties", "version=${project.version}\n"), + ("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"), + ]) else { + return; + }; + + // First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs. + let first = f.launch(false); + assert_eq!(first.failure, None, "{:?}", first.messages); + assert_eq!(first.class_paths[0], f.out("t.app/classes")); + assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths); + assert!(f.out("t.app/classes/a/A.class").is_file()); + assert!(f.out("t.lib/classes/l/L.class").is_file()); + assert!(!f.root.join("app/target/classes/a/A.class").exists()); + assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n"); + let steps = f.steps(); + assert!(steps[0].contains("process-resources"), "{steps:?}"); + assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]); + + // Nothing changed: no Maven, no javac. + assert_eq!(f.steps_of_launch(), Vec::::new()); + + // A change inside a method compiles that class only, without Maven. + f.write( + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n", + ); + assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]); + + // A resource change is processed by Maven (it filters), and compiles nothing. + f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n"); + let steps = f.steps_of_launch(); + assert_eq!(steps.len(), 1, "{steps:?}"); + assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}"); + assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n"); + + // A deleted source leaves no class behind. + f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n"); + assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]); + assert!(f.out("t.app/classes/a/Gone.class").is_file()); + fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap(); + assert_eq!(f.steps_of_launch(), Vec::::new()); + assert!(!f.out("t.app/classes/a/Gone.class").exists()); + + // Compile errors fail the build with positioned messages. + f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n"); + let failed = f.launch(false); + let failure = failed.failure.expect("fails"); + assert!(failure.contains("incompatible types"), "{failure}"); + let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap(); + assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path())); + assert_eq!(error.range.unwrap().start, Pos::new(1, 25)); + // It compiles again next time, even unchanged. + f.steps(); + assert!(f.launch(false).failure.is_some()); + assert_eq!(f.steps(), ["javac app (main, 1 file)"]); + + // A test launch compiles the module's tests after its main classes. + f.write( + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n", + ); + let tests = f.launch(true); + assert_eq!(tests.failure, None, "{:?}", tests.messages); + assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]); + assert!(f.out("t.app/test-classes/a/ATest.class").is_file()); + + // Recompile compiles the file even unchanged. + f.steps(); + let file = f.root.join("app/src/main/java/a/A.java"); + assert_eq!(f.build(Target::File(&file)).failure, None); + assert_eq!(f.steps(), ["javac app (main, 1 file)"]); + // Build Project builds every module's main and test classes. + f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n"); + assert_eq!(f.build(Target::Project).failure, None); + assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]); + assert!(f.out("t.lib/test-classes/l/LTest.class").is_file()); +} + +#[test] +fn recompiles_the_classes_an_api_change_reaches() { + let Some(f) = Fixture::new(&[ + ("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"), + ("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"), + ("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"), + ("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"), + ("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"), + ("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"), + ("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"), + ("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"), + ]) else { + return; + }; + assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]); + + // A body change: that class only, and nothing downstream. + f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n"); + assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]); + + // An API change reaches the classes that use the class or a subclass of it. + f.write( + "lib/src/main/java/l/Base.java", + "package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n", + ); + assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]); + + // Across modules: only the classes that use it. + f.write( + "lib/src/main/java/l/Other.java", + "package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n", + ); + assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]); + + // A compile-time constant is copied into its uses: everything compiled against it compiles again. + f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n"); + assert_eq!( + f.steps_of_launch(), + ["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"] + ); + + // A removed method fails the classes that still call it. + f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n"); + let failed = f.launch(false); + assert!(failed.failure.expect("fails").contains("User.java")); +} + +#[test] +fn an_api_change_from_a_failed_build_still_reaches_other_modules() { + let Some(f) = Fixture::new(&[ + ("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"), + ("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"), + ("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"), + ]) else { + return; + }; + assert_eq!(f.launch(false).failure, None); + + // L compiles, then U, which still calls the removed method, fails lib before app compiles. + f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n"); + assert!(f.launch(false).failure.expect("lib fails").contains("U.java")); + + // Once lib compiles, app learns that L changed, and A fails too instead of keeping a class + // that calls a method L no longer has. + f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n"); + let failed = f.launch(false); + assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages); + + // So does a changed constant: C compiles, then the whole set, where U fails. + f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n"); + let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n"); + f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }")); + f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n"); + assert_eq!(f.launch(false).failure, None); + f.write("lib/src/main/java/l/C.java", &c(2, "")); + assert!(f.launch(false).failure.expect("lib fails").contains("U.java")); + f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n"); + f.steps(); + assert_eq!(f.launch(false).failure, None); + let steps = f.steps(); + assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}"); +} + +#[test] +fn reads_what_a_class_file_declares() { + let Some((home, _)) = tools() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let compile = |text: &str| { + write(tmp.path(), "p/C.java", text); + let status = std::process::Command::new(home.join("bin/javac")) + .args(["-d", "out", "p/C.java"]) + .current_dir(tmp.path()) + .status() + .unwrap(); + assert!(status.success()); + classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap() + }; + let a = compile( + "package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n" + .replace("x.Y", "Object") + .as_str(), + ); + assert_eq!(a.name, "p/C"); + assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread")); + assert_eq!(a.interfaces, ["java/lang/Runnable"]); + assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs); + assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs); + // Private members and method bodies aren't API; constants have their own fingerprint. + let b = compile( + "package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n", + ); + assert_eq!((a.api, a.constants), (b.api, b.constants)); + let c = compile( + "package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n", + ); + assert_eq!(a.api, c.api); + assert_ne!(a.constants, c.constants); + let d = compile( + "package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n", + ); + assert_ne!(a.api, d.api); +} + +#[test] +fn follows_api_changes_through_the_log() { + let mut state = SetState { generation: 1, ..Default::default() }; + state.log(2, ["a/A".to_owned()].into(), false); + state.log(3, ["a/B".to_owned()].into(), false); + assert_eq!(state.changes_since(3), Some(BTreeSet::new())); + assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into())); + assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into())); + // Unknown generations, and a log entry where everything changed, mean everything. + assert_eq!(state.changes_since(0), None); + state.log(4, BTreeSet::new(), true); + assert_eq!(state.changes_since(3), None); +} + +#[test] +fn ant_patterns_match_like_maven() { + assert!(ant_match("**/*.java", "a/b/C.java")); + assert!(ant_match("**/*.java", "C.java")); + assert!(ant_match("com/acme/**", "com/acme/x/Y.java")); + assert!(!ant_match("com/acme/**", "com/other/Y.java")); + assert!(ant_match("**/generated/", "x/generated/Y.java")); + assert!(ant_match("**/*Test?.java", "a/FooTest1.java")); + assert!(!ant_match("*.java", "a/B.java")); +} + +#[test] +fn javac_options_follow_the_compiler_configuration() { + let set = SourceSet { + output: PathBuf::from("/o"), + compiler: Some(CompilerConfig { + release: Some("17".into()), + source: Some("1.8".into()), + encoding: Some("UTF-8".into()), + parameters: Some(true), + debuglevel: Some("lines,vars".into()), + proc: Some("none".into()), + processor_path: Some(vec![PathBuf::from("/p.jar")]), + annotation_processors: Some(vec!["a.P".into()]), + compiler_args: vec!["-Xlint:unchecked".into()], + compiler_arguments: [("Akey=v".to_owned(), None)].into(), + show_warnings: Some(false), + ..Default::default() + }), + ..Default::default() + }; + let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21)); + let joined = args.join(" "); + let separator = if cfg!(windows) { ";" } else { ":" }; + assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}"); + for expected in [ + "-processorpath /p.jar", + "-processor a.P", + "-proc:none", + "-g:lines,vars", + "-parameters", + "-nowarn", + "-encoding UTF-8", + "--release 17", + "-Akey=v", + ] { + assert!(joined.contains(expected), "{expected} in {joined}"); + } + assert!(joined.ends_with("-Xlint:unchecked"), "{joined}"); + // JDK 8 has no --release: source and target instead. + let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" "); + assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}"); +} + +#[test] +fn builds_gradle_projects_with_javac_and_only_what_changed() { + let Some(f) = Fixture::gradle(&[ + ( + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib\"; } }\n", + ), + ( + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n", + ), + ("app/src/main/resources/app.properties", "version=${version}\n"), + ("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"), + ]) else { + return; + }; + let steps = f.steps_of_launch(); + assert_eq!(steps.len(), 3, "{steps:?}"); + assert!(steps[0].contains("openideaBuildModel"), "{steps:?}"); + assert!(steps[1].starts_with("javac lib (main"), "{steps:?}"); + assert!(steps[2].starts_with("javac app (main"), "{steps:?}"); + assert!(f.out("t.lib/classes/l/L.class").is_file()); + assert!(f.out("t.app/classes/a/A.class").is_file()); + assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n"); + // Gradle's own outputs stay untouched. + assert!(!f.root.join("app/build/classes").exists()); + + let built = f.launch(false); + assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths); + assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths); + assert_eq!(f.steps(), Vec::::new(), "nothing changed"); + + f.write( + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n", + ); + let steps = f.steps_of_launch(); + assert_eq!(steps.len(), 1, "{steps:?}"); + assert!(steps[0].starts_with("javac app (main"), "{steps:?}"); + + f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n"); + let steps = f.steps_of_launch(); + assert_eq!(steps.len(), 1, "{steps:?}"); + assert!(steps[0].contains(":app:processResources"), "{steps:?}"); + assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n"); + + // Tests compile against the main classes. + f.steps(); + let built = f.launch(true); + assert_eq!(built.failure, None, "{:?}", built.messages); + assert!(f.out("t.app/test-classes/a/ATest.class").is_file()); + + // A changed build script prepares again. + f.write("lib/build.gradle", "// changed\n"); + let steps = f.steps_of_launch(); + assert!(steps[0].contains("openideaBuildModel"), "{steps:?}"); + + // An error is a javac diagnostic on the source. + f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n"); + let built = f.launch(false); + assert!(built.failure.is_some()); + let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error"); + assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path())); +} + +#[test] +fn leaves_gradle_projects_with_other_compilers_to_gradle() { + let Some(f) = Fixture::gradle(&[ + ("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"), + ("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), + ]) else { + return; + }; + let jdk = |_: Option| None; + let build = JavaBuild { + root: &f.root, + model: &f.model, + cache: &f.cache, + jar: Path::new(JAR), + jar_version: "test", + local_repo: None, + service: &f.service, + jdk: &jdk, + }; + let target = Target::Launch { module: &f.root.join("app"), test: false }; + match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) { + Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"), + Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"), + Err(e) => panic!("{e:?}"), + } +} diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 94e8d7b5b..9b08b4367 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -9,6 +9,7 @@ pub mod application_update; pub mod compile; pub mod gradle; mod gradle_deps; +pub mod jbuild; pub mod kotlin_bridge; pub mod maven; pub mod pom_edit; diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 4e1f809c1..242007673 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -753,7 +753,26 @@ pub(crate) fn launch_inputs( projects: &[&MavenProject], local_repo: Option, ) -> Option> { - fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec) -> Option<()> { + project_inputs(root, projects, local_repo, true) +} + +/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate +/// on: what Maven's model of them is built from, without their sources. +pub(crate) fn model_inputs( + root: &Path, + projects: &[&MavenProject], + local_repo: Option, +) -> Option> { + project_inputs(root, projects, local_repo, false) +} + +fn project_inputs( + root: &Path, + projects: &[&MavenProject], + local_repo: Option, + sources: bool, +) -> Option> { + fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec) -> Option<()> { let input = matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir") || (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs") @@ -762,6 +781,7 @@ pub(crate) fn launch_inputs( || (parent == "filters" && el.name == "filter"); // Profile activation may depend on the presence of an otherwise unrelated file. let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing"); + let input = input && sources; if input || activation { // A source root under Maven's build directory is generated by the build itself. // Skip it without resolving the property: `` may be custom, and @@ -787,7 +807,7 @@ pub(crate) fn launch_inputs( } } for child in &el.children { - roots(child, &el.name, dir, out)?; + roots(child, &el.name, dir, sources, out)?; } Some(()) } @@ -796,7 +816,9 @@ pub(crate) fn launch_inputs( for project in projects { let dir = root.join(&project.dir); // Include all conventional language/resource roots, including nonstandard files under src. - out.push(dir.join("src")); + if sources { + out.push(dir.join("src")); + } let pom = root.join(&project.pom); resolver.context(&pom, 0); let mut path = pom; @@ -808,7 +830,7 @@ pub(crate) fn launch_inputs( } out.push(path.clone()); let text = xml::read_text(&path)?; - roots(&xml::parse(&text)?, "", &dir, &mut out)?; + roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?; let raw = resolver.pom(&path)?; let Some(parent) = raw.parent else { break }; path = resolver.parent_path(path.parent()?, &parent)?; diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 767db8de4..8c2122bdd 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -118,6 +118,8 @@ pub struct Host { pub(crate) heap_windows: Mutex>, pub(crate) heap_requests: ops::heap::HeapRequests, pub(crate) rebase_editors: Arc, + /// The IDE's Java build: resident javac processes shared by every window's launches. + pub(crate) java_build: Arc, /// SSH connections of Settings › SSH Configurations. pub ssh: Arc, /// SFTP deployment, remote file editing and runs on run targets. @@ -227,6 +229,7 @@ impl Host { heap_windows: Mutex::default(), heap_requests: Default::default(), rebase_editors: Default::default(), + java_build: Default::default(), languages, syntax, config_dir, diff --git a/crates/ide-host/src/mcp/run/configs.rs b/crates/ide-host/src/mcp/run/configs.rs index 3240c6572..022f90f3d 100644 --- a/crates/ide-host/src/mcp/run/configs.rs +++ b/crates/ide-host/src/mcp/run/configs.rs @@ -513,6 +513,7 @@ async fn resolve_jvm_application( call.window(), std::path::PathBuf::from(&module), test == Some(true), + false, policy, &cancel, None, diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 32378c4c2..b2f61c623 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -9,6 +9,7 @@ use crate::{Host, Project}; use ide_command::command; use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult}; +use ide_build::jbuild::Target; use ide_build::maven::completion::{PomCompletion, PomCompletionOption}; use ide_build::maven::sources; use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions}; @@ -975,11 +976,38 @@ pub async fn build_run( let config_dir = host.config_dir.clone(); let token = host.begin_project_request(window, request); let launch_project = project.clone(); + let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone()); let result = blocking(move || { + let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none(); + // A Maven or Gradle project builds with the IDE's Java build (#4078), unless its + // settings ask for the build tool, or it can't. + if single { + let model = with_profiles(load(&root, &cache, &settings), &cache); + let served = match file.as_deref() { + Some(module) => super::java::served_by_service(&root, &model, &settings, module), + None => super::java::project_served_by_service(&model, &settings), + }; + if served { + let service = super::java::ServiceBuild { + service: &service, + data_dir: &data_dir, + root: &root, + cache: &cache, + settings: &settings, + model: &model, + }; + let target = match file.as_deref() { + Some(file) => Target::Module(file), + None => Target::Project, + }; + if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? { + return Ok(result); + } + } + } // Fast path (#2476): an unchanged single-project Maven build skips // Maven entirely. Previous diagnostics stay: nothing changed, so they // are still accurate. - let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none(); if single && kind == BuildKind::Build { let model = with_profiles(load(&root, &cache, &settings), &cache); if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) { @@ -1102,13 +1130,59 @@ pub async fn build_run( let outcome = result?; // Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the // folders the build wrote are attached. An up-to-date build skips Maven and - // still needs this: the classes can already be on disk. - if outcome.system == ide_build::compile::BuildSystem::Maven { + // still needs this: the classes can already be on disk. The IDE's Java build + // generates them with Maven too. + if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) { project.lsp.sync_maven_generated_sources(&project.root).await; } Ok(outcome) } +/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds. +/// Diagnostics of `clear` are cleared once the service builds; its messages are published. +#[allow(clippy::too_many_arguments)] +fn service_build_result( + service: &super::java::ServiceBuild, + target: Target, + kind: BuildKind, + clear: &[std::path::PathBuf], + sink: &ide_core::SharedSink, + token: &CancellationToken, + on_event: &Channel, +) -> IdeResult> { + let started = std::time::Instant::now(); + let title = std::sync::Mutex::new(String::new()); + let forward = |event: BuildEvent| { + if let BuildEvent::Started { title: t, .. } = &event { + *title.lock().unwrap() = t.clone(); + } + let _ = on_event.send(event); + }; + let built = service.build(target, kind, token, &forward)?; + let Some(outputs) = built else { return Ok(None) }; + for path in clear { + sink.emit(IdeEvent::Diagnostics { + path: path.clone().into(), + source: compile::DIAGNOSTICS_SOURCE.into(), + items: Vec::new(), + }); + } + for (path, items) in compile::diagnostics(&outputs.messages) { + sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items }); + } + let count = + |severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32; + Ok(Some(BuildResult { + system: compile::BuildSystem::Javac, + title: title.into_inner().unwrap(), + success: outputs.failure.is_none(), + errors: count(ide_core::Severity::Error), + warnings: count(ide_core::Severity::Warning), + duration_ms: started.elapsed().as_secs_f64() * 1000.0, + messages: outputs.messages, + })) +} + fn plan_compile_file( root: &Path, cache: &Path, @@ -1167,7 +1241,26 @@ pub async fn build_compile_file( }; let sink = project.sink.clone(); let token = host.begin_project_request(window, request); + let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone()); let result = blocking(move || { + { + let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache); + if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) { + let service = super::java::ServiceBuild { + service: &service, + data_dir: &data_dir, + root: &scope.root, + cache: &scope.cache, + settings: &scope.settings, + model: &model, + }; + let target = Target::File(&file); + let kind = BuildKind::Build; + if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? { + return Ok(result); + } + } + } for path in clear { sink.emit(IdeEvent::Diagnostics { path: path.into(), @@ -1190,7 +1283,7 @@ pub async fn build_compile_file( .await; host.end_request(request); let outcome = result?; - if outcome.system == ide_build::compile::BuildSystem::Maven { + if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) { project.lsp.sync_maven_generated_sources(&scope_root).await; } Ok(outcome) diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 9818c9d14..47e2dce4d 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace}; use cache::LaunchEvents; use ide_build::BuildModel; use ide_build::compile::{self, BuildEvent}; +use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target}; use ide_core::error::ErrorKind; use ide_core::settings::Settings; use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; @@ -22,12 +23,16 @@ use std::path::{Path, PathBuf}; /// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first. /// The build streams its console, messages and progress on `on_event` while it runs; a launch /// whose build another launch's build joins receives that build's events. +/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language +/// server serves: java-debug's HotSwap reloads the classes the language server compiles. +#[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn java_resolve_launch( host: &Host, window: &str, module: PathBuf, test: bool, + debug: bool, policy: BuildPolicy, request: RequestId, on_event: Channel, @@ -39,16 +44,18 @@ pub async fn java_resolve_launch( let events: LaunchEvents = std::sync::Arc::new(move |event| { let _ = on_event.send(event); }); - let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await; + let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await; host.end_request(request); result } +#[allow(clippy::too_many_arguments)] pub(crate) async fn resolve_launch( host: &Host, window: &str, module: PathBuf, test: bool, + debug: bool, policy: BuildPolicy, cancel: &CancellationToken, events: Option, @@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch( } let scope = std::sync::Arc::new(scope); let launches = project.java_launches.for_cache(&scope.cache); - let waiting = launches.waiting.add(module.clone(), test, policy, events.clone()); let prefer_maven = scope.settings.languages.java.maven.delegate_build; // A launch builds incrementally unless the configuration asks for Rebuild or NoBuild. let build = policy != BuildPolicy::NoBuild; let full = policy == BuildPolicy::Rebuild; let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; - let (model, external, mut delegated, is_maven) = { + let (model, external, mut delegated, is_maven, non_java, served) = { let scope = scope.clone(); let launches = launches.clone(); let module = module.clone(); @@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch( let model = load_launch_model(&scope); let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test); let is_maven = is_maven_module(root, &model, &module); + let served = served_by_service(root, &model, &scope.settings, &module); let delegated = build && delegates_to_external_build( is_maven, @@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch( prefer_maven, ); let external = non_java || delegated; - (model, external, delegated, is_maven) + (std::sync::Arc::new(model), external, delegated, is_maven, non_java, served) }) .await .map_err(|e| IdeError::internal(e.to_string()))? }; + // A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless + // the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's + // classes differ from javac's: lambda names). jdtls keeps building for its diagnostics + // either way. + if served && !non_java && !debug { + let built = { + let (service, data_dir, scope, model, module, cancel, events) = ( + host.java_build.clone(), + host.local_data_dir.clone(), + scope.clone(), + model.clone(), + module.clone(), + cancel.clone(), + events.clone(), + ); + tokio::task::spawn_blocking(move || { + let on_event = |event: BuildEvent| { + if let Some(events) = &events { + events(event); + } + }; + let kind = build.then_some(build_kind); + build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))?? + }; + if let Some(outputs) = built { + progress("Resolving the classpath"); + let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?; + let data_dir = host.local_data_dir.clone(); + let cancel = cancel.clone(); + return tokio::task::spawn_blocking(move || { + // javac's verdict replaces JDT's, as a Maven build's does. + if build { + apply_external_build_result(&mut info, outputs.failure, true); + } + info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect(); + apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test); + finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + tracing::info!( + total_ms = started.elapsed().as_millis(), + "Java launch resolved with the IDE's Java build" + ); + Ok(info) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))?; + } + } + let waiting = launches.waiting.add(module.clone(), test, policy, events.clone()); let mut external_build = if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None }; if build && !delegated { @@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch( drop_processor_recreate_errors(&mut info); } } - let model = std::sync::Arc::new(model); let members = if delegated { build_members(&project, &scope, &model, &module, test, &waiting, cancel).await? } else { @@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch( .map_err(|e| IdeError::internal(e.to_string()))? } +/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident +/// process with the configuration Maven gives the compiler, into outputs in the project cache +/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs +/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs. +/// Without `kind` (no build before launch), the outputs of its last build, if any. +#[allow(clippy::too_many_arguments)] +fn build_with_service( + service: &JavaBuildService, + data_dir: &Path, + scope: &workspace::Scope, + model: &BuildModel, + module: &Path, + test: bool, + kind: Option, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), +) -> IdeResult> { + let service = + ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model }; + match kind { + Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event), + // No build: the outputs of the last one, when there was one. + None => Ok(service + .with(module, |build| build.recorded_launch(module, test)) + .flatten() + .map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })), + } +} + +/// A build of the IDE's Java build service in one project (or workspace member). +pub(crate) struct ServiceBuild<'a> { + pub service: &'a JavaBuildService, + pub data_dir: &'a Path, + pub root: &'a Path, + pub cache: &'a Path, + pub settings: &'a Settings, + pub model: &'a BuildModel, +} + +impl ServiceBuild<'_> { + /// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar + /// can't be installed. + fn with(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option { + let jar = ide_sdk::java::java_build_jar(self.data_dir)?; + let (root, settings) = (self.root, self.settings); + let jdk = |release: Option| { + ide_sdk::apply::module_jdk(root, module, settings) + .or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned()) + .map(|jdk| jdk.home) + }; + let version = ide_sdk::java::java_build_version(); + let build = JavaBuild { + root, + model: self.model, + cache: self.cache, + jar: &jar, + jar_version: &version, + local_repo: ide_sdk::apply::maven_local_repository(root, settings), + service: self.service, + jdk: &jdk, + }; + Some(f(&build)) + } + + /// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed). + pub fn build( + &self, + target: Target, + kind: compile::BuildKind, + cancel: &CancellationToken, + on_event: &(dyn Fn(BuildEvent) + Sync), + ) -> IdeResult> { + let module = match target { + Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module, + Target::Project => self.root, + }; + let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else { + return Ok(None); + }; + match built { + Ok(Built::Done(outputs)) => Ok(Some(outputs)), + Ok(Built::Unsupported(reason)) => { + tracing::info!(module = %module.display(), reason, "Building with the build tool"); + Ok(None) + } + Err(e) if e.kind == ErrorKind::Cancelled => Err(e), + Err(e) => { + tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message); + on_event(BuildEvent::Output { + text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message), + stderr: true, + }); + Ok(None) + } + } + } +} + fn load_launch_model(scope: &workspace::Scope) -> BuildModel { with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache) } @@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool { model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module)) } +/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless +/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module +/// when Settings › Gradle › Build and run using asks for the IDE. +pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool { + let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true))); + let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false))); + // The deepest module holding it; Maven's when both build the folder. + let module = maven + .chain(gradle) + .filter(|(dir, _)| path.starts_with(dir)) + .max_by_key(|(dir, maven)| (dir.components().count(), *maven)); + match module { + Some((_, true)) => !settings.languages.java.maven.delegate_build, + Some((_, false)) => gradle_served(settings), + None => false, + } +} + +/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and +/// builds them all. +pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool { + let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build); + let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings)); + match (maven, gradle) { + (None, None) => false, + (maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true), + } +} + +fn gradle_served(settings: &Settings) -> bool { + settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide +} + /// A launch of a module jdtls doesn't serve (another Java language server, or none): the /// build tool compiles it, and the classpath comes from that server, else from Maven. #[allow(clippy::too_many_arguments)] @@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls( let started = std::time::Instant::now(); let scope = std::sync::Arc::new(scope); let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; - let (model, built) = { + let (model, built, by_service) = { let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone()); + let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone()); tokio::task::spawn_blocking(move || { let model = load_launch_model(&scope); let on_event = |event: BuildEvent| { @@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls( events(event); } }; - let built = if policy == BuildPolicy::NoBuild { - None - } else { - Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event)) - }; - (model, built) + if policy == BuildPolicy::NoBuild { + return (model, None, false); + } + if served_by_service(&scope.root, &model, &scope.settings, &module) + && !compile::launch_has_non_java_sources(&scope.root, &model, &module, test) + { + match build_with_service( + &service, + &data_dir, + &scope, + &model, + &module, + test, + Some(kind), + &cancel, + &on_event, + ) { + Ok(Some(outputs)) => { + let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure }; + return (model, Some(Ok(built)), true); + } + Ok(None) => {} + Err(e) => return (model, Some(Err(e)), false), + } + } + let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event); + (model, Some(built), false) }) .await .map_err(|e| IdeError::internal(e.to_string()))? @@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls( tokio::task::spawn_blocking(move || { let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings); match from_server { + // The IDE's Java build gave the whole classpath; the server adds its JDK. + Some(server) if by_service => { + info.project_root = server.classpath.project_root; + info.java_home = server.jdk_home.map(Into::into); + } + None if by_service => {} Some(server) => { info.project_root = server.classpath.project_root; info.module_paths = server.classpath.module_paths; diff --git a/crates/ide-host/tests/java_build.rs b/crates/ide-host/tests/java_build.rs new file mode 100644 index 000000000..15d1f688e --- /dev/null +++ b/crates/ide-host/tests/java_build.rs @@ -0,0 +1,215 @@ +mod common; + +use ide_build::compile::BuildEvent; +use ide_core::RequestId; +use ide_host::{Host, ops}; +use ide_run::BuildPolicy; +use ide_workspace::{SettingsStore, settings::SettingsScope}; +use std::fs; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +fn write(root: &Path, rel: &str, text: &str) { + let path = root.join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache) +/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn maven_launch_compiles_with_the_ides_java_build() { + let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir()); + if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() { + eprintln!("skipped: needs JAVA_HOME and mvn"); + return; + } + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + write( + &root, + "pom.xml", + r#"4.0.0troot1pom +libapp +11UTF-8"#, + ); + write( + &root, + "lib/pom.xml", + r#"4.0.0troot1lib"#, + ); + write( + &root, + "app/pom.xml", + r#"4.0.0troot1app +tlib1"#, + ); + write( + &root, + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib\"; } }\n", + ); + write( + &root, + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n", + ); + // No language server: the build tool compiles the launch. + let global = SettingsStore::load(&base.join("config"), None); + for server in ["jdtls", "java-analyzer", "kmp-lsp"] { + global + .set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false)) + .unwrap(); + } + let host = Host::new(common::host_config(&base)); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + + let events = Arc::new(Mutex::new(Vec::new())); + let sink = events.clone(); + let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event)); + let info = ops::java::java_resolve_launch( + &host, + "main", + root.join("app"), + false, + false, + BuildPolicy::Make, + RequestId::next(), + channel, + ) + .await + .unwrap(); + let steps: Vec = events + .lock() + .unwrap() + .iter() + .filter_map(|e| match e { + BuildEvent::Step { command, .. } => Some(command.clone()), + _ => None, + }) + .collect(); + assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}"); + assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}"); + let first = Path::new(&info.class_paths[0]); + assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths); + assert!(first.join("a/A.class").is_file()); + assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths); + assert!(!root.join("app/target/classes").exists()); + + // Build › Build Project compiles with it too, and reports javac's errors. + write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n"); + let built = ops::build::build_run( + &host, + "main", + ide_build::compile::BuildKind::Build, + None, + None, + RequestId::next(), + Vec::new(), + ops::Channel::new(|_: BuildEvent| {}), + ) + .await + .unwrap(); + assert_eq!(built.system, ide_build::compile::BuildSystem::Javac); + assert!(!built.success); + assert_eq!(built.errors, 1, "{:?}", built.messages); + assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages); + assert!(!root.join("lib/target/classes").exists()); + host.shutdown().await; +} + +/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile +/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`). +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gradle_launch_compiles_with_the_ides_java_build() { + let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir()); + let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else { + eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"); + write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n"); + write(&root, "lib/build.gradle", ""); + write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n"); + write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display())); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap(); + write( + &root, + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static String name() { return \"lib\"; } }\n", + ); + write( + &root, + "app/src/main/java/a/A.java", + "package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n", + ); + let global = SettingsStore::load(&base.join("config"), None); + for server in ["jdtls", "java-analyzer", "kmp-lsp"] { + global + .set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false)) + .unwrap(); + } + global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap(); + let host = Host::new(common::host_config(&base)); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + + let events = Arc::new(Mutex::new(Vec::new())); + let sink = events.clone(); + let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event)); + let info = ops::java::java_resolve_launch( + &host, + "main", + root.join("app"), + false, + false, + BuildPolicy::Make, + RequestId::next(), + channel, + ) + .await + .unwrap(); + let steps: Vec = events + .lock() + .unwrap() + .iter() + .filter_map(|e| match e { + BuildEvent::Step { command, .. } => Some(command.clone()), + _ => None, + }) + .collect(); + assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}"); + let first = Path::new(&info.class_paths[0]); + assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths); + assert!(first.join("a/A.class").is_file()); + assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths); + assert!(!root.join("app/build/classes").exists()); + + write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n"); + let built = ops::build::build_run( + &host, + "main", + ide_build::compile::BuildKind::Build, + None, + None, + RequestId::next(), + Vec::new(), + ops::Channel::new(|_: BuildEvent| {}), + ) + .await + .unwrap(); + assert_eq!(built.system, ide_build::compile::BuildSystem::Javac); + assert_eq!(built.errors, 1, "{:?}", built.messages); + assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages); + host.shutdown().await; +} diff --git a/crates/ide-host/tests/workspaces.rs b/crates/ide-host/tests/workspaces.rs index 4cd7e0c09..8ea4ff350 100644 --- a/crates/ide-host/tests/workspaces.rs +++ b/crates/ide-host/tests/workspaces.rs @@ -88,10 +88,18 @@ done let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let sink = events.clone(); let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event)); - let info = - ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel) - .await - .unwrap(); + let info = ops::java::java_resolve_launch( + &host, + "main", + module, + test, + false, + BuildPolicy::Make, + RequestId::next(), + channel, + ) + .await + .unwrap(); // The build streams its command and progress while it runs. use ide_build::compile::BuildEvent; let events = events.lock().unwrap(); @@ -110,7 +118,9 @@ done assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out)); assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar)); let calls = fs::read_to_string(root.join("calls")).unwrap(); - assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}"); + // This Maven records no build model for the IDE's Java build, so Maven builds the module. + assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}"); + assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}"); assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}"); assert!(calls.contains(":build-classpath"), "{calls}"); } diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index 27bcbd64f..c876db2e5 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() { assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}"); mgr.shutdown_all().await; } + +/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs: +/// its build is what reports an API change in one Maven module in the files of the modules +/// that use it, open or not. With `java.autobuild.enabled: false` (and +/// `validateAllOpenBuffersOnChanges`), neither updates. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"] +async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() { + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap().join("project"); + let write = |rel: &str, text: &str| { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path + }; + let parent = r#"troot1"#; + write( + "pom.xml", + r#"4.0.0troot1pomlibapp11"#, + ); + write( + "lib/pom.xml", + &format!("4.0.0{parent}lib"), + ); + write( + "app/pom.xml", + &format!( + "4.0.0{parent}apptlib1" + ), + ); + let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n"; + let app_source = "package a;\npublic class A { String s = l.L.name(); }\n"; + let lib = write("lib/src/main/java/l/L.java", lib_source); + let app = write("app/src/main/java/a/A.java", app_source); + let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n"); + let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap(); + java.language_servers.retain(|s| s.name == "jdtls"); + let server = &mut java.language_servers[0]; + if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") { + server.command = bin; + } + server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]); + let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java])); + let (lib_doc, app_doc) = (DocId::next(), DocId::next()); + mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source); + mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source); + let errors = |path: &Path| { + events.lock().iter().rev().find_map(|e| match e { + IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some( + items + .iter() + .filter(|d| d.severity == ide_core::Severity::Error) + .map(|d| d.message.clone()) + .collect::>(), + ), + _ => None, + }) + }; + // The import resolves `lib` from source: the open editor of `app` has no errors. + retry("app imported", Duration::from_secs(300), || { + let status = last_status(&events, "jdtls"); + if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status { + panic!("jdtls failed: {message:?}"); + } + let clean = errors(&app).is_some_and(|e| e.is_empty()); + let mgr = mgr.clone(); + let app = app.clone(); + async move { + let cp = + tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default())) + .await + .ok()? + .ok()?; + (clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(()) + } + }) + .await; + // Rename the method in the editor of `lib`, and save. + let renamed = lib_source.replace("name()", "title()"); + let line = lib_source.lines().nth(1).unwrap(); + mgr.did_change( + lib_doc, + 2, + &[AppliedChange { + range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)), + text: renamed.lines().nth(1).unwrap().to_owned(), + }], + &|| renamed.clone(), + ); + std::fs::write(&lib, &renamed).unwrap(); + mgr.did_save(lib_doc, &renamed); + retry("the open editor of app reports the removed method", Duration::from_secs(120), || { + let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()"))); + async move { found.then_some(()) } + }) + .await; + retry("the closed file of app reports it too", Duration::from_secs(60), || { + let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()"))); + async move { found.then_some(()) } + }) + .await; + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); +} diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 71804aeea..ed1463b22 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1654,6 +1654,23 @@ pub fn junit_runner_jar(data_dir: &Path) -> Option { ) } +/// The IDE's Java build (`java/java-build`): the resident javac server and the Maven +/// extension that records the build model. +const JAVA_BUILD: &[u8] = include_bytes!("../../../java/java-build/openidea-java-build.jar"); + +/// Extracts the Java build jar into the application's data directory. +pub fn java_build_jar(data_dir: &Path) -> Option { + install_bundle(data_dir, "java-build", "1.0.0", JAVA_BUILD) +} + +/// Changes whenever the embedded Java build jar does (FNV-1a of its bytes), so build models +/// recorded by an older extension are prepared again. +pub fn java_build_version() -> String { + let hash = + JAVA_BUILD.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)); + format!("{hash:016x}") +} + /// The JUnit Platform launcher a test classpath needs to start the runner. #[derive(Debug, PartialEq)] pub enum JunitLauncher { diff --git a/java/java-build/README.md b/java/java-build/README.md new file mode 100644 index 000000000..478413296 --- /dev/null +++ b/java/java-build/README.md @@ -0,0 +1,40 @@ +# Java build + +The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar holds two parts: + +- `ai.openidea.javac.Server` (`src/`): a resident javac. OpenIDEA starts one per JDK (and + `.mvn/jvm.config`) as `java -cp openidea-java-build.jar ai.openidea.javac.Server` and keeps it + running between builds. It reads one JSON request per line on stdin and answers on stdout: + + | Request | Meaning | + | ------------------------------------------------------------------------ | ----------------------------------------------- | + | `{"id":1,"op":"compile","options":[…],"sources":[…],"encoding":"UTF-8"}` | Compile with javac (`ToolProvider`), in process | + | `{"op":"cancel","id":1}` | Stop that compilation at javac's next phase | + | `{"op":"exit"}` | Finish the queued requests, then exit | + + Replies carry the request's `id`: `diagnostic` (1-based line, 0-based UTF-16 column), + `output` (a class file and the source it came from), `generated` (a source an annotation + processor wrote), `output-text`, then `done`. `ready` and `fatal` concern the server. + +- `ai.openidea.javac.maven.BuildModel` (`maven/`): a Maven core extension, loaded with + `-Dmaven.ext.class.path`. With `-Dopenidea.build.output=` it redirects every project's + output to `/./classes|test-classes`, and resolves reactor + projects to those folders. With `-Dopenidea.build.model=` it writes, after the build, + each project's source roots, classpaths, resources and the configuration maven-compiler-plugin's + mojos get (including the resolved `annotationProcessorPaths`), as JSON. + +OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs, +settings or generator inputs change, then compiles the launch's modules with the server. + +Gradle builds get the same model from an init script instead +(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with +`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run +using is set to the IDE. + +The jar is committed and embedded by `ide-sdk` (`java_build_jar`). It is built with `--release 8` +against Maven 3.9.11, whose files `build-dependencies.sha256` pins. Rebuild it after changing +the source: + +```sh +JAVA_HOME= python3 build.py +``` diff --git a/java/java-build/build-dependencies.sha256 b/java/java-build/build-dependencies.sha256 new file mode 100644 index 000000000..dc593d461 --- /dev/null +++ b/java/java-build/build-dependencies.sha256 @@ -0,0 +1,52 @@ +0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08 maven/aopalliance-1.0.jar +876eab6a83daecad5ca67eb9fcabb063c97b5aeb8cf1fca7a989ecde17522051 maven/asm-9.8.jar +d3d530d0f28fd0fbbffe2b0b338f70e8cb96f1605579e2e3abd4db29cac24e69 maven/commons-cli-1.9.0.jar +ba005f304cef92a3dede24a38ad5ac9b8afccf0d8f75839d6c1338634cf7f6e4 maven/commons-codec-1.18.0.jar +6661d5335090a5fc61dd869d2095bc6c1e2156e3aa47a6e4ababdf64c99a7889 maven/error_prone_annotations-2.38.0.jar +cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb maven/failureaccess-1.0.3.jar +94855942d4992f112946d3de1c334e709237b8126d8130bf07807c018a4a2120 maven/gson-2.13.1.jar +f3d7f57f67fd622f4d468dfdd692b3a5e3909246c28017ac3263405f0fe617ed maven/guava-33.4.8-jre.jar +142ad4475e19524d2fe3ac995b3f7cbc962fc726f2edb9dbdccc61feab9b2bf9 maven/guice-5.1.0-classes.jar +c8bc7e1c51a6d4ce72f40d2ebbabf1c4b68bfe76e732104b04381b493478e9d6 maven/httpclient-4.5.14.jar +6c9b3dd142a09dc468e23ad39aad6f75a0f2b85125104469f026e52a474e464f maven/httpcore-4.4.16.jar +0b7b8b003a90ea491579b62f5118828e45112914c65589b00faa49d6ec785839 maven/jansi-2.4.2.jar +e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b maven/javax.annotation-api-1.3.2.jar +91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff maven/javax.inject-1.jar +ab57ca8fd223772c17365d121f59e94ecbf0ae59d08c03a3cb5b81071c019195 maven/jcl-over-slf4j-1.7.36.jar +1fad6e6be7557781e4d33729d49ae1cdc8fdda6fe477bb0cc68ce351eafdfbab maven/jspecify-1.0.0.jar +0bfd1c121f907642344311d81e4dfd93eba6c24dc712cc0aeae273eb22833022 maven/maven-artifact-3.9.11.jar +5b1de1560ec19c4c69a655f986455888f3a0bcc3c160cac1f1edb87de3825f77 maven/maven-builder-support-3.9.11.jar +b0e2865fc808fd9fb3bee95bf37c0609eeb20c59bf1e6b958b37b365ee11f52e maven/maven-compat-3.9.11.jar +93d3c0523dda6c86c6620d9e692e7df39d0e2e4e4cd860061a8c0d274c2ad185 maven/maven-core-3.9.11.jar +7e15e05035331d0a7e0fe56d7354b2b30e15c0a8c60863cbf28df25190e197db maven/maven-embedder-3.9.11.jar +163aa596f976264384efeb50b4cb8a806086fd64a9b755ad1f69195fed3998ad maven/maven-model-3.9.11.jar +c4c72accdcd848332c1a37995610a6a369d49fdaabc43e85f0022a5b77de3ba7 maven/maven-model-builder-3.9.11.jar +8e985a56412564cf687040efed8bcd3a63eac2202a824bb01e1d5ece2b87458f maven/maven-plugin-api-3.9.11.jar +f8655f5f0060e0032944f2a23688d186e140d2184749bcfa1927f83cd6a8b1a2 maven/maven-repository-metadata-3.9.11.jar +c0ce14849298720dcf3b09fe9e263b3c576d2d6cd43c61f8aa9d6117e04e5e47 maven/maven-resolver-api-1.9.24.jar +18b7d557c41379db8b157ba95263c676f52c293f5416b67bd1db083e99b30383 maven/maven-resolver-connector-basic-1.9.24.jar +3cd88edda00c46242cdbe57aefb47703519d176d9e8a500333de15faf41b0e1d maven/maven-resolver-impl-1.9.24.jar +a222b0a5ca4c145e8e0f45207a23bcce18bdbe1f1c980e4e9fb332591ee8c91a maven/maven-resolver-named-locks-1.9.24.jar +b5d6e52ae1ecf1cb62ede2234234ba3093149524066488e84415187ce478c582 maven/maven-resolver-provider-3.9.11.jar +e3153906e93333c106ee18babb72ba7984ccb15e9116ea08f88c71b8d9387e01 maven/maven-resolver-spi-1.9.24.jar +b09268d41e1dfcae15a829d45a512ca29d62b727421d3bd6383ac6252e5e960f maven/maven-resolver-transport-file-1.9.24.jar +a0de339a8dd3473d9abaa1cf974507f38783e26af31d36a90c1e59cc8714ded0 maven/maven-resolver-transport-http-1.9.24.jar +78ed57fa2123a2d84fad7a0b15ca73b89df47c10294d02d6f8121c4d0e5050cb maven/maven-resolver-transport-wagon-1.9.24.jar +aeb7e776a8c47b1c317a2581f299e2525b044cb8abde31164e970bbbefab12b1 maven/maven-resolver-util-1.9.24.jar +026718d47d19e360d978857bc63d3dc065884fc2c801563d8a2a77b5ab74ccf8 maven/maven-settings-3.9.11.jar +33c96e4ca5a15b7c93180f6b2f8deb15f511dfc15dda0d2b671c968b22108972 maven/maven-settings-builder-3.9.11.jar +b613357e1bad4dfc1dead801691c9460f9585fe7c6b466bc25186212d7d18487 maven/maven-shared-utils-3.4.2.jar +76d9fa894fa61d1492877ca599cb5ab28ca4573d5f389d6c12a8233b995335f9 maven/maven-slf4j-provider-3.9.11.jar +1cbd7a965a5e2a9ea823bab311962a4e5aa5c240705bdbad5a52b40ffdfa1004 maven/org.eclipse.sisu.inject-0.9.0.M4.jar +b90579bc652eac7331436e0a25533fce14130b9c6e015f2dd3a3d4bb07e942b7 maven/org.eclipse.sisu.plexus-0.9.0.M4.jar +9a7f1b5c5a9effd61eadfd8731452a2f76a8e79111fac391ef75ea801bea203a maven/plexus-cipher-2.0.jar +50edb93c73786e62822b4fe1336e22880fdf147191373cf5c911370e16748fcf maven/plexus-component-annotations-2.2.0.jar +ab2a8715570438a2e4164d85ad3e8d489eabc38ea5093c2eb8ab7f58403535b5 maven/plexus-interpolation-1.28.jar +873139960c4c780176dda580b003a2c4bf82188bdce5bb99234e224ef7acfceb maven/plexus-sec-dispatcher-2.0.jar +27ef130e32c236090e408fb5498d94cb9ea26d14070fb1c8985d607b62d098d1 maven/plexus-utils-3.6.0.jar +d3ef575e3e4979678dc01bf1dcce51021493b4d11fb7f1be8ad982877c16a1c0 maven/slf4j-api-1.7.36.jar +afc9216fa97b78dad227b4a8d4d67b9897bf113a57f80598d62993841113e103 maven/wagon-file-3.5.3.jar +d2b6e48c9fcbe579e1858c622d14464011ff265fa6e28e794004a6882154a509 maven/wagon-http-3.5.3.jar +8e7da766f55164fde8779aaaa125832506c2848cab4876b5305138873e28037f maven/wagon-http-shared-3.5.3.jar +5e72000338945ed3e96f8e4f578d1d0672e1af7e19c0e9014197ae5b31af3ef4 maven/wagon-provider-api-3.5.3.jar +1ad3292cd563381e3fd632f3fded1988f9e9b2be7a9f3db63ff4c4cedba13fa5 maven/plexus-classworlds-2.9.0.jar diff --git a/java/java-build/build.py b/java/java-build/build.py new file mode 100644 index 000000000..82fef92f1 --- /dev/null +++ b/java/java-build/build.py @@ -0,0 +1,38 @@ +"""Build the committed jar: python3 build.py /path/to/apache-maven-3.9.11 [--record-dependencies]. + +One jar, two parts, Java 8 bytecode: +- `src`: the resident javac server (`ai.openidea.javac.Server`), JDK classes only. +- `maven`: the prepare run's Maven extension (`ai.openidea.javac.maven.BuildModel`), compiled + against Maven 3.9.11's API jars, pinned by build-dependencies.sha256. +Archive order and timestamps are deterministic. Use a JDK that still compiles `--release 8`.""" +import hashlib +import os +import pathlib +import subprocess +import sys +import tempfile +import zipfile + +root = pathlib.Path(__file__).resolve().parent +maven = pathlib.Path(sys.argv[1]).resolve() +jars = sorted((maven / 'lib').glob('*.jar')) + sorted((maven / 'boot').glob('*.jar')) +actual = ''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()} maven/{p.name}\n' for p in jars) +if '--record-dependencies' in sys.argv: + (root / 'build-dependencies.sha256').write_text(actual) +if (root / 'build-dependencies.sha256').read_text() != actual: + sys.exit('Build dependencies differ from build-dependencies.sha256') +java_home = os.environ.get('JAVA_HOME') +javac = str(pathlib.Path(java_home) / 'bin' / 'javac') if java_home else 'javac' +with tempfile.TemporaryDirectory() as output: + for source, classpath in [('src', []), ('maven', jars)]: + subprocess.run([javac, '--release', '8', '-Xlint:-options', '-proc:none', '-encoding', 'UTF-8', '-g', + '-classpath', os.pathsep.join(map(str, classpath)), '-d', output, + *map(str, sorted((root / source).rglob('*.java')))], check=True) + files = {p.relative_to(output).as_posix(): p.read_bytes() for p in pathlib.Path(output).rglob('*.class')} + files['META-INF/sisu/javax.inject.Named'] = b'ai.openidea.javac.maven.BuildModel\n' + files['META-INF/MANIFEST.MF'] = b'Manifest-Version: 1.0\nMain-Class: ai.openidea.javac.Server\n\n' + staged = root / 'openidea-java-build.jar.pending' + with zipfile.ZipFile(staged, 'w', zipfile.ZIP_DEFLATED) as jar: + for name, data in sorted(files.items()): + jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data) + staged.replace(root / 'openidea-java-build.jar') diff --git a/java/java-build/maven/ai/openidea/javac/maven/BuildModel.java b/java/java-build/maven/ai/openidea/javac/maven/BuildModel.java new file mode 100644 index 000000000..91861951d --- /dev/null +++ b/java/java-build/maven/ai/openidea/javac/maven/BuildModel.java @@ -0,0 +1,501 @@ +package ai.openidea.javac.maven; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.maven.AbstractMavenLifecycleParticipant; +import org.apache.maven.MavenExecutionException; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.lifecycle.LifecycleExecutor; +import org.apache.maven.lifecycle.MavenExecutionPlan; +import org.apache.maven.model.Dependency; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.BuildPluginManager; +import org.apache.maven.plugin.MavenPluginManager; +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.project.DefaultDependencyResolutionRequest; +import org.apache.maven.project.DependencyResolutionResult; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.ProjectDependenciesResolver; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.collection.CollectRequest; +import org.eclipse.aether.graph.DependencyNode; +import org.eclipse.aether.graph.Exclusion; +import org.eclipse.aether.repository.WorkspaceReader; +import org.eclipse.aether.repository.WorkspaceRepository; +import org.eclipse.aether.resolution.ArtifactResult; +import org.eclipse.aether.resolution.DependencyRequest; +import org.eclipse.aether.resolution.DependencyResult; + +/** + * Records how each project of the session compiles, for the IDE's own Java build. Loaded only + * by the IDE's prepare run ({@code -Dmaven.ext.class.path= -Dopenidea.build.model= + * process-resources resources:testResources}): generated sources exist and resources are + * processed, and nothing is compiled. Test source generators run after {@code compile} in + * Maven's lifecycle, so they don't run; the source roots build-helper adds are read from its + * configuration, and any other generator is listed so the IDE leaves those tests to Maven. + * + *

Per project and source set (main, test): the source roots (including the ones generated + * sources added), the output directory, the compile classpath with reactor projects as their + * output directories (never their jars), the runtime classpath, the compiler plugin's resolved + * configuration (release, encoding, arguments, annotation processor path) and the resources. + * Executions bound to the compile phases that are not javac (Kotlin, AspectJ, bytecode + * enhancers) are listed, so the IDE leaves such projects to Maven. + */ +@Named("openidea-build-model") +@Singleton +public final class BuildModel extends AbstractMavenLifecycleParticipant { + private static final String COMPILER = "org.apache.maven.plugins:maven-compiler-plugin"; + /** Test phases before test-compile, which the prepare run doesn't reach. */ + private static final Set TEST_GENERATE_PHASES = new HashSet<>(Arrays.asList( + "generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources")); + /** Phases whose executions change what the compile phases produce. */ + private static final Set COMPILE_PHASES = + new HashSet<>(Arrays.asList("compile", "process-classes", "test-compile", "process-test-classes")); + /** Executions in those phases that don't change the classes the IDE compiles. */ + private static final Set HARMLESS = new HashSet<>(Arrays.asList( + "org.jacoco:jacoco-maven-plugin", "org.apache.maven.plugins:maven-enforcer-plugin", + "org.codehaus.mojo:animal-sniffer-maven-plugin", "org.apache.maven.plugins:maven-checkstyle-plugin", + "com.github.spotbugs:spotbugs-maven-plugin", "org.apache.maven.plugins:maven-pmd-plugin", + "com.diffplug.spotless:spotless-maven-plugin", "org.apache.maven.plugins:maven-dependency-plugin", + "org.apache.maven.plugins:maven-resources-plugin", "org.codehaus.mojo:build-helper-maven-plugin", + "pl.project13.maven:git-commit-id-plugin", "io.github.git-commit-id:git-commit-id-maven-plugin")); + + private final LifecycleExecutor lifecycle; + private final MavenPluginManager plugins; + private final BuildPluginManager buildPlugins; + private final ProjectDependenciesResolver dependencies; + private final RepositorySystem repositories; + + @Inject + public BuildModel(LifecycleExecutor lifecycle, MavenPluginManager plugins, BuildPluginManager buildPlugins, + ProjectDependenciesResolver dependencies, RepositorySystem repositories) { + this.lifecycle = lifecycle; + this.plugins = plugins; + this.buildPlugins = buildPlugins; + this.dependencies = dependencies; + this.repositories = repositories; + } + + /** + * With {@code -Dopenidea.build.output=

}, every project's classes and resources go to + * {@code /./classes} (and {@code test-classes}): the IDE's outputs, + * apart from what a terminal build or the language server writes to {@code target}. + */ + @Override public void afterProjectsRead(MavenSession session) { + String output = session.getUserProperties().getProperty("openidea.build.output"); + if (output == null) return; + for (MavenProject project : session.getProjects()) { + File dir = new File(output, project.getGroupId() + "." + project.getArtifactId()); + project.getBuild().setOutputDirectory(new File(dir, "classes").getAbsolutePath()); + project.getBuild().setTestOutputDirectory(new File(dir, "test-classes").getAbsolutePath()); + } + } + + @Override public void afterSessionEnd(MavenSession session) throws MavenExecutionException { + String destination = session.getUserProperties().getProperty("openidea.build.model"); + if (destination == null) return; + StringBuilder json = new StringBuilder("{\"version\":1,\"projects\":["); + boolean first = true; + MavenProject current = session.getCurrentProject(); + try { + for (MavenProject project : session.getProjects()) { + if (!first) json.append(','); + first = false; + project(json, session, project); + } + } finally { + session.setCurrentProject(current); + } + json.append("]}"); + File target = new File(destination); + try { + File parent = target.getAbsoluteFile().getParentFile(); + parent.mkdirs(); + File temp = File.createTempFile("build-model", ".json", parent); + try (Writer out = new OutputStreamWriter(Files.newOutputStream(temp.toPath()), StandardCharsets.UTF_8)) { + out.write(json.toString()); + } + Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + throw new MavenExecutionException("Cannot write the IDE build model: " + e.getMessage(), e); + } + } + + private void project(StringBuilder json, MavenSession session, MavenProject project) { + session.setCurrentProject(project); + json.append("{\"dir\":").append(q(project.getBasedir().getAbsolutePath())) + .append(",\"groupId\":").append(q(project.getGroupId())) + .append(",\"artifactId\":").append(q(project.getArtifactId())) + .append(",\"version\":").append(q(project.getVersion())) + .append(",\"packaging\":").append(q(project.getPackaging())); + List problems = new ArrayList<>(); + Map compilers = new HashMap<>(); + List configured = new ArrayList<>(); + List others = new ArrayList<>(); + List testGenerators = new ArrayList<>(); + List testRoots = new ArrayList<>(project.getTestCompileSourceRoots()); + try { + MavenExecutionPlan plan = lifecycle.calculateExecutionPlan(session, true, "test-compile"); + for (MojoExecution execution : plan.getMojoExecutions()) { + String plugin = execution.getGroupId() + ":" + execution.getArtifactId(); + String phase = execution.getLifecyclePhase(); + if (COMPILER.equals(plugin) && ("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) { + if (compilers.containsKey(execution.getGoal())) { + others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId()); + continue; + } + try { + buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor()); + Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution); + compilers.put(execution.getGoal(), mojo); + configured.add(execution); + } catch (Exception e) { + problems.add("Cannot read the " + execution.getGoal() + " configuration: " + e); + } + } else if (phase != null && COMPILE_PHASES.contains(phase) && !HARMLESS.contains(plugin)) { + others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId()); + } else if (phase != null && TEST_GENERATE_PHASES.contains(phase)) { + String goal = plugin + ":" + execution.getGoal(); + if (goal.equals("org.apache.maven.plugins:maven-resources-plugin:testResources")) continue; + if (goal.equals("org.codehaus.mojo:build-helper-maven-plugin:add-test-source")) { + try { + buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor()); + Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution); + Object sources = get(mojo, "sources"); + if (sources instanceof File[]) + for (File f : (File[]) sources) testRoots.add(f.getAbsolutePath()); + plugins.releaseMojo(mojo, execution); + continue; + } catch (Exception e) { + problems.add("Cannot read build-helper's test sources: " + e); + } + } + testGenerators.add(goal + "@" + execution.getExecutionId()); + } + } + } catch (Exception e) { + problems.add("Cannot plan the build: " + e); + } + Set reactor = new HashSet<>(); + for (MavenProject p : session.getProjects()) reactor.add(p.getGroupId() + ":" + p.getArtifactId()); + RepositorySystemSession repo = reactorSession(session); + List compile = new ArrayList<>(); + List runtime = new ArrayList<>(); + List test = new ArrayList<>(); + try { + DependencyResolutionResult result = + dependencies.resolve(new DefaultDependencyResolutionRequest(project, repo)); + classpaths(result.getDependencyGraph(), compile, runtime, test); + for (Exception e : result.getCollectionErrors()) problems.add(e.getMessage()); + } catch (Exception e) { + problems.add("Cannot resolve the dependencies: " + rootMessage(e)); + org.apache.maven.project.DependencyResolutionException failure = cause(e); + if (failure != null && failure.getResult() != null && failure.getResult().getDependencyGraph() != null) + classpaths(failure.getResult().getDependencyGraph(), compile, runtime, test); + } + json.append(",\"main\":"); + sourceSet(json, session, project, compilers.get("compile"), null, compile, runtime, problems); + json.append(",\"test\":"); + List testClasspath = new ArrayList<>(); + testClasspath.add(project.getBuild().getOutputDirectory()); + testClasspath.addAll(test); + sourceSet(json, session, project, compilers.get("testCompile"), testRoots, testClasspath, testClasspath, problems); + json.append(",\"otherCompilers\":").append(strings(others)); + json.append(",\"testGenerators\":").append(strings(testGenerators)); + json.append(",\"problems\":").append(strings(problems)).append('}'); + for (int i = 0; i < configured.size(); i++) { + Mojo mojo = compilers.get(configured.get(i).getGoal()); + if (mojo != null) plugins.releaseMojo(mojo, configured.get(i)); + } + } + + /** `testRoots`: the test source roots, `null` for the main source set. */ + private void sourceSet(StringBuilder json, MavenSession session, MavenProject project, Mojo compiler, + List testRoots, List classpath, List runtime, List problems) { + boolean test = testRoots != null; + List roots = test ? testRoots : project.getCompileSourceRoots(); + String output = test ? project.getBuild().getTestOutputDirectory() : project.getBuild().getOutputDirectory(); + json.append("{\"sourceRoots\":").append(strings(roots)) + .append(",\"output\":").append(q(output)) + .append(",\"classpath\":").append(strings(classpath)) + .append(",\"runtimeClasspath\":").append(strings(runtime)) + .append(",\"resources\":"); + List resources = test ? project.getTestResources() : project.getResources(); + json.append('['); + for (int i = 0; i < resources.size(); i++) { + Resource r = resources.get(i); + if (i > 0) json.append(','); + json.append("{\"directory\":").append(q(new File(project.getBasedir(), r.getDirectory()).isAbsolute() + ? r.getDirectory() : new File(project.getBasedir(), r.getDirectory()).getAbsolutePath())) + .append(",\"filtering\":").append(r.isFiltering()) + .append(",\"targetPath\":").append(q(r.getTargetPath())) + .append(",\"includes\":").append(strings(r.getIncludes())) + .append(",\"excludes\":").append(strings(r.getExcludes())).append('}'); + } + json.append(']'); + json.append(",\"compiler\":"); + if (compiler == null) { + json.append("null}"); + return; + } + json.append('{'); + String goal = test ? "testCompile" : "compile"; + field(json, "compilerId", get(compiler, "compilerId")); + field(json, "source", get(compiler, test ? "testSource" : "source", "source")); + field(json, "target", get(compiler, test ? "testTarget" : "target", "target")); + field(json, "release", get(compiler, test ? "testRelease" : "release", "release")); + field(json, "encoding", get(compiler, "encoding")); + field(json, "parameters", get(compiler, "parameters")); + field(json, "debug", get(compiler, "debug")); + field(json, "debuglevel", get(compiler, "debuglevel")); + field(json, "proc", get(compiler, "proc")); + field(json, "enablePreview", get(compiler, "enablePreview")); + field(json, "fork", get(compiler, "fork")); + field(json, "executable", get(compiler, "executable")); + field(json, "skip", get(compiler, test ? "skip" : "skipMain")); + field(json, "showWarnings", get(compiler, "showWarnings")); + field(json, "showDeprecation", get(compiler, "showDeprecation")); + field(json, "generatedSourcesDirectory", + get(compiler, test ? "generatedTestSourcesDirectory" : "generatedSourcesDirectory")); + field(json, "includes", get(compiler, test ? "testIncludes" : "includes")); + field(json, "excludes", get(compiler, test ? "testExcludes" : "excludes")); + field(json, "annotationProcessors", get(compiler, "annotationProcessors")); + field(json, "compilerArgs", get(compiler, "compilerArgs")); + field(json, "compilerArgument", get(compiler, "compilerArgument")); + field(json, "compilerArguments", get(compiler, "compilerArguments")); + field(json, "multiReleaseOutput", get(compiler, "multiReleaseOutput")); + Object paths = get(compiler, "annotationProcessorPaths"); + if (paths instanceof Collection && !((Collection) paths).isEmpty()) { + try { + Object useDepMgmt = get(compiler, "annotationProcessorPathsUseDepMgmt"); + field(json, "processorPath", processorPath(session, project, (Collection) paths, + Boolean.TRUE.equals(useDepMgmt))); + } catch (Exception e) { + problems.add("Cannot resolve the annotation processor path of " + goal + ": " + rootMessage(e)); + field(json, "processorPathError", rootMessage(e)); + } + } + if (json.charAt(json.length() - 1) == ',') json.setLength(json.length() - 1); + json.append("}}"); + } + + /** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */ + private static void classpaths(DependencyNode root, List compile, List runtime, List test) { + List nodes = new ArrayList<>(); + collect(root, nodes, new HashSet<>()); + for (DependencyNode node : nodes) { + if (node.getDependency() == null || node.getArtifact() == null) continue; + File file = node.getArtifact().getFile(); + if (file == null) continue; + String scope = node.getDependency().getScope(); + String path = file.getAbsolutePath(); + if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path); + if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path); + test.add(path); + } + } + + /** Pre-order, as Maven lists `project.getArtifacts()` for classpaths. */ + private static void collect(DependencyNode node, List out, Set seen) { + for (DependencyNode child : node.getChildren()) { + Artifact a = child.getArtifact(); + String key = a == null ? String.valueOf(System.identityHashCode(child)) + : a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() + ":" + a.getClassifier(); + if (seen.add(key)) out.add(child); + } + for (DependencyNode child : node.getChildren()) collect(child, out, seen); + } + + /** + * A repository session that resolves reactor projects to their output directories, as the + * IDE compiles against them: before (and without) any packaging, and even before they exist. + */ + private static RepositorySystemSession reactorSession(MavenSession session) { + final Map byKey = new HashMap<>(); + for (MavenProject p : session.getProjects()) + byKey.put(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(), p); + final WorkspaceReader fallback = session.getRepositorySession().getWorkspaceReader(); + final WorkspaceRepository repository = new WorkspaceRepository("openidea-reactor"); + WorkspaceReader reader = new WorkspaceReader() { + @Override public WorkspaceRepository getRepository() { + return repository; + } + + @Override public File findArtifact(Artifact artifact) { + MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion()); + if (p == null) return fallback == null ? null : fallback.findArtifact(artifact); + if ("pom".equals(artifact.getExtension())) return p.getFile(); + boolean tests = "tests".equals(artifact.getClassifier()) || "test-jar".equals(artifact.getProperty("type", "")); + File dir = new File(tests ? p.getBuild().getTestOutputDirectory() : p.getBuild().getOutputDirectory()); + dir.mkdirs(); + return dir; + } + + @Override public List findVersions(Artifact artifact) { + MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion()); + if (p != null) return java.util.Collections.singletonList(p.getVersion()); + return fallback == null ? java.util.Collections.emptyList() : fallback.findVersions(artifact); + } + }; + DefaultRepositorySystemSession copy = new DefaultRepositorySystemSession(session.getRepositorySession()); + copy.setWorkspaceReader(reader); + return copy; + } + + /** maven-compiler-plugin's `annotationProcessorPaths`, resolved with their dependencies as the plugin does. */ + private List processorPath(MavenSession session, MavenProject project, Collection coordinates, + boolean useDepMgmt) throws Exception { + Map managed = new HashMap<>(); + if (project.getDependencyManagement() != null) + for (Dependency d : project.getDependencyManagement().getDependencies()) + managed.put(d.getGroupId() + ":" + d.getArtifactId(), d.getVersion()); + CollectRequest request = new CollectRequest(); + request.setRepositories(project.getRemoteProjectRepositories()); + for (Object c : coordinates) { + String group = (String) get(c, "groupId"); + String artifact = (String) get(c, "artifactId"); + String version = (String) get(c, "version"); + if (version == null) version = managed.get(group + ":" + artifact); + if (version == null) throw new IllegalStateException("No version for " + group + ":" + artifact); + String classifier = (String) get(c, "classifier"); + String type = (String) get(c, "type"); + List exclusions = new ArrayList<>(); + Object declared = get(c, "exclusions"); + if (declared instanceof Collection) + for (Object e : (Collection) declared) + exclusions.add(new Exclusion((String) get(e, "groupId"), (String) get(e, "artifactId"), "*", "*")); + DefaultArtifact a = new DefaultArtifact(group, artifact, classifier == null ? "" : classifier, + type == null || "jar".equals(type) ? "jar" : type, version); + request.addDependency(new org.eclipse.aether.graph.Dependency(a, "runtime", false, exclusions)); + } + if (useDepMgmt && project.getDependencyManagement() != null) { + for (Dependency d : project.getDependencyManagement().getDependencies()) { + request.addManagedDependency(new org.eclipse.aether.graph.Dependency(new DefaultArtifact(d.getGroupId(), + d.getArtifactId(), d.getClassifier() == null ? "" : d.getClassifier(), + d.getType() == null ? "jar" : d.getType(), d.getVersion()), d.getScope())); + } + } + DependencyResult result = + repositories.resolveDependencies(reactorSession(session), new DependencyRequest(request, null)); + Set out = new LinkedHashSet<>(); + for (ArtifactResult r : result.getArtifactResults()) + if (r.getArtifact() != null && r.getArtifact().getFile() != null) out.add(r.getArtifact().getFile().getAbsolutePath()); + return new ArrayList<>(out); + } + + private static org.apache.maven.project.DependencyResolutionException cause(Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) + if (t instanceof org.apache.maven.project.DependencyResolutionException) + return (org.apache.maven.project.DependencyResolutionException) t; + return null; + } + + private static String rootMessage(Throwable e) { + Throwable t = e; + while (t.getCause() != null && t.getCause() != t) t = t.getCause(); + return t.getMessage() == null ? t.toString() : t.getMessage(); + } + + /** The first of `names` that a field of the mojo (or its superclasses) has, read reflectively. */ + private static Object get(Object target, String... names) { + for (String name : names) { + for (Class c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + try { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + Object value = f.get(target); + if (value != null || names.length == 1) return value; + break; + } catch (NoSuchFieldException e) { + // Try the superclass. + } catch (IllegalAccessException | RuntimeException e) { + return null; + } + } + } + return null; + } + + private static void field(StringBuilder json, String name, Object value) { + if (value == null) return; + json.append(q(name)).append(':').append(value(value)).append(','); + } + + private static String value(Object value) { + if (value == null) return "null"; + if (value instanceof Boolean || value instanceof Number) return value.toString(); + if (value instanceof File) return q(((File) value).getAbsolutePath()); + if (value instanceof Collection) { + StringBuilder b = new StringBuilder("["); + for (Object o : (Collection) value) { + if (b.length() > 1) b.append(','); + b.append(value(o)); + } + return b.append(']').toString(); + } + if (value instanceof Object[]) return value(Arrays.asList((Object[]) value)); + if (value instanceof Map) { + StringBuilder b = new StringBuilder("{"); + for (Map.Entry e : new LinkedHashMap<>((Map) value).entrySet()) { + if (b.length() > 1) b.append(','); + b.append(q(String.valueOf(e.getKey()))).append(':').append(q(e.getValue() == null ? null : String.valueOf(e.getValue()))); + } + return b.append('}').toString(); + } + return q(value.toString()); + } + + private static String strings(Collection values) { + StringBuilder b = new StringBuilder("["); + if (values != null) { + for (String s : values) { + if (b.length() > 1) b.append(','); + b.append(q(s)); + } + } + return b.append(']').toString(); + } + + static String q(String s) { + if (s == null) return "null"; + StringBuilder b = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"': b.append("\\\""); break; + case '\\': b.append("\\\\"); break; + case '\n': b.append("\\n"); break; + case '\r': b.append("\\r"); break; + case '\t': b.append("\\t"); break; + default: + if (c < 0x20) b.append(String.format("\\u%04x", (int) c)); + else b.append(c); + } + } + return b.append('"').toString(); + } +} diff --git a/java/java-build/openidea-java-build.jar b/java/java-build/openidea-java-build.jar new file mode 100644 index 0000000000000000000000000000000000000000..be916598d4aec5946e688f137f4154e875a34937 GIT binary patch literal 60696 zcmd?S34B!5`8WQYb7yjICO0G`1RT~7_N*d`8W4f77-TbHF^Eb?1{g^)aV9}fajROZ zwpwddD6Unb)>=ggiMZRMt<~;}wYJv!Yin2SW>u8`_c`a@J9j3N5Zk{0-{++G=NJ15fAQMtUaHPYO-+}6fzk+#bD zoza%&WwGW+OIig79((=KT!V;zTtQ>B%59h`zNtz#Y~u9FCT{w-K7RZuWIL8BLnO&C zDPU8OvILD%jj8I0#aa?o3!;si+hU21Xw$?~qixNCvbHt0bVd?_ilytx3btGOn?zrLk>u)$&+`5YvF(?;1en$v~?R~F1$wW6-!Z0D^>V+G|WOI)#$$5fCtyQwAG z7VVg$DqbTfP=i4fl(#h67Fpiex-k-8)wr<*DFsVoO^q#U8skxZb`o>zI~tp|0zA%h zs6N&iZ;C96@)tRJWEK9Q#D#55EwMzjZS%57$Cg;LNz()!)gSZ)*|lwLk+?$VNW!FY zLBlf-E85IBkY9{}9Rt)6`A6~4@*Psf0qX>f$J3Q$;Ew3{9uiMI5qgx&z5IV}Hw_J} z=t3dtaReTN$;Xj+%u;!emU(}Wc@kbo6fgzX08Pc;Qv3>#CaH`n=7!O3{L8me=jwMqh+Gjw!TjTo`h(rX zn#Q)KNJ~qkIc-Xfwnz%fZgO9TP3S%L<@~ss=^!Aw$_dOYQhA1} zzaxO7oEO6lGBJvdN=2pDD_>pw2b9J?CjI>aWJw~{mWD-dr4i-~RK-IU5VJLD1b57U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bTBoNSW-Zk$_TH7eGgt*%{UMIv^q>_ z|3P)>d{&_|9d1GvW4~x@5JO?BJjp48!lR@`F=1|XH7PqmI|W|EnaI0ngm}qxyU>ks@&(kK=1{ww3&XuoyQ;yW0DL2e zqRMTQ9crUWYy8BCAPlc%0ym&8gk4}w$R*g4e8yit&T6EmFmbNN<)`lL7Cd#xA$pmQFvteW0U>b%2Kt^7EmUoFjl1!ooB6|d1xVK}f+yiQxi8`KB`f;|GBQgC2ty7(hx$$hS`0%gzY-5USQ?rqEc2L?5y?1<5d~%{vH)@65Lql8 zw(@<;P8NzB5BLt63ceepdJ-68T@Lf;iNLTxz!<-q0)BFAttZg;L4$n&`s&Z%$3LX0 zVjoqC{cu0`QF5LaW30}`vgK977O5j~&!Cxhgp%W8-%WAQF>HjpDL2)7?qG(qJxs+I z{FOouQd|hcz%rJ-?vmi%Vj$5jyys3ln4Fgcxv;4&MmMsT?emLs^r1}7p24JfA_ zTaZ)ONco7kQ}0sYs48ettFUBN+t+E~0@jqSmO!^Z3Y*sQJVt$XJG1EZ6U^TOn7^Nb z|Ne}^;&WPnb7ij+f2Ui;LApzPNgKphn799+nE0ArM7o#7zs&fv{3%SEfIz2V{0rzQ zqeHHfGEjlaG{kjZeZEUjPRfy#lM89D% zqR;4V1L|H@v8r`-QBOc^sEcA3x*t8Qi>r-0#E*|lDDq6gO-KlnNKW@)GF=^~%gJ;~ ze8?o+YD(N@Qa(}_1>$?OF6s}c$LgXv$ownZ5cdRbh#Le$&7Ro@&pZS6NyenKiz)GEzMY{u;*B z&gxsjCE5F;rz0(2g}B^bgSZjFWC=@tvSitK{)XhXarPVUapqHnzNIC0?%R=t<;Pc{ zTNLgMz;gY$hpnr>1>d)iI@7v^?OWPgN9xyjFopPH_p-k*IC;v2rW*Y2-D)MKihwA4BHBD?)bApProtocol: one JSON object per line. Requests on stdin: + * {@code {"id":1,"op":"compile","options":[...],"sources":[...],"encoding":"UTF-8"}}, + * {@code {"op":"cancel","id":1}}, {@code {"op":"exit"}}. Replies on stdout, all carrying the + * request {@code id}: {@code diagnostic} (severity, path, 1-based line, UTF-16 column and end, + * code, message), {@code output} (a class or resource file written, with the source it came + * from), {@code generated} (a source an annotation processor wrote), {@code output-text} + * (javac's own printed text), then one {@code done} (success, cancelled). + */ +public final class Server { + private static final Object OUT_LOCK = new Object(); + private static PrintWriter out; + + public static void main(String[] args) throws IOException { + out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), false); + // Anything else printing to stdout would break the protocol. + System.setOut(System.err); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + if (compiler == null) { + send("{\"kind\":\"fatal\",\"message\":" + Json.quote("This Java runtime has no compiler (a JRE, not a JDK)") + "}"); + System.exit(2); + } + send("{\"kind\":\"ready\",\"version\":" + Json.quote(System.getProperty("java.version")) + "}"); + BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + final AtomicReference running = new AtomicReference<>(); + final java.util.concurrent.BlockingQueue queue = new java.util.concurrent.LinkedBlockingQueue<>(); + Thread worker = new Thread(() -> { + while (true) { + Request request; + try { + request = queue.take(); + } catch (InterruptedException e) { + return; + } + if (request.exit) return; + running.set(request); + try { + compile(compiler, request); + } catch (Throwable t) { + StringWriter trace = new StringWriter(); + t.printStackTrace(new PrintWriter(trace)); + send("{\"id\":" + request.id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":" + + Json.quote("javac crashed: " + trace) + "}"); + send("{\"id\":" + request.id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":false}"); + } finally { + running.set(null); + } + } + }, "javac"); + worker.start(); + String line; + while ((line = in.readLine()) != null) { + if (line.trim().isEmpty()) continue; + Map message; + try { + message = Json.parseObject(line); + } catch (RuntimeException e) { + send("{\"kind\":\"fatal\",\"message\":" + Json.quote("Bad request: " + e.getMessage()) + "}"); + continue; + } + String op = (String) message.get("op"); + if ("cancel".equals(op)) { + Request current = running.get(); + long id = ((Number) message.get("id")).longValue(); + if (current != null && current.id == id) current.cancelled = true; + for (Request queued : queue) if (queued.id == id) queued.cancelled = true; + } else if ("exit".equals(op)) { + break; + } else if ("compile".equals(op)) { + queue.add(Request.of(message)); + } + } + Request exit = new Request(); + exit.exit = true; + // Requests already sent finish first; the host cancels the ones it no longer wants. + queue.add(exit); + try { + worker.join(); + } catch (InterruptedException ignored) { + } + System.exit(0); + } + + static void send(String json) { + synchronized (OUT_LOCK) { + out.print(json); + out.print('\n'); + out.flush(); + } + } + + static final class Request { + long id; + List options = new ArrayList<>(); + List sources = new ArrayList<>(); + String encoding; + volatile boolean cancelled; + boolean exit; + + @SuppressWarnings("unchecked") + static Request of(Map message) { + Request r = new Request(); + r.id = ((Number) message.get("id")).longValue(); + Object options = message.get("options"); + if (options != null) for (Object o : (List) options) r.options.add((String) o); + Object sources = message.get("sources"); + if (sources != null) for (Object o : (List) sources) r.sources.add((String) o); + r.encoding = (String) message.get("encoding"); + return r; + } + } + + /** Thrown from the task listener to stop a cancelled compilation. */ + static final class Cancelled extends RuntimeException { + private static final long serialVersionUID = 1L; + + Cancelled() { + super("cancelled", null, false, false); + } + } + + private static void compile(JavaCompiler compiler, final Request request) throws IOException { + final long id = request.id; + if (request.cancelled) { + send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":true}"); + return; + } + Charset charset = request.encoding == null ? StandardCharsets.UTF_8 : Charset.forName(request.encoding); + final int[] errors = {0}; + DiagnosticListener diagnostics = d -> { + if (d.getKind() == Diagnostic.Kind.ERROR) errors[0]++; + send(diagnostic(id, d)); + }; + StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, Locale.ROOT, charset); + JavaFileManager manager = new Recording(standard, id); + List files = new ArrayList<>(); + for (String source : request.sources) files.add(new File(source)); + Iterable units = standard.getJavaFileObjectsFromFiles(files); + StringWriter printed = new StringWriter(); + boolean success = false; + boolean cancelled = false; + try { + JavaCompiler.CompilationTask task = + compiler.getTask(printed, manager, diagnostics, request.options, null, units); + stopWhenCancelled(task, request); + success = Boolean.TRUE.equals(task.call()) && errors[0] == 0; + } catch (RuntimeException e) { + if (isCancelled(e)) { + cancelled = true; + } else if (e instanceof IllegalArgumentException) { + // An option javac doesn't know (a newer --release than this JDK has). + send("{\"id\":" + id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":" + + Json.quote(e.getMessage()) + "}"); + } else { + throw e; + } + } finally { + try { + manager.close(); + } catch (IOException ignored) { + } + } + String text = printed.toString(); + if (!text.isEmpty()) send("{\"id\":" + id + ",\"kind\":\"output-text\",\"text\":" + Json.quote(text) + "}"); + send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":" + success + ",\"cancelled\":" + cancelled + "}"); + } + + /** + * Stops the compilation at its next phase once {@code request} is cancelled, through + * {@code com.sun.source.util.TaskListener} (reflectively: Java 8's {@code --release} API has no + * {@code jdk.compiler}). + */ + private static void stopWhenCancelled(JavaCompiler.CompilationTask task, final Request request) { + try { + Class listener = Class.forName("com.sun.source.util.TaskListener", false, task.getClass().getClassLoader()); + Object proxy = java.lang.reflect.Proxy.newProxyInstance(listener.getClassLoader(), new Class[] {listener}, + (self, method, args) -> { + if (method.getDeclaringClass() == Object.class) { + switch (method.getName()) { + case "hashCode": return System.identityHashCode(self); + case "equals": return self == args[0]; + default: return "cancellation listener"; + } + } + if (request.cancelled) throw new Cancelled(); + return null; + }); + task.getClass().getMethod("addTaskListener", listener).invoke(task, proxy); + } catch (ReflectiveOperationException | RuntimeException e) { + // Not javac's task: cancellation then waits for the compilation to end. + } + } + + private static boolean isCancelled(Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof Cancelled) return true; + return false; + } + + private static String diagnostic(long id, Diagnostic d) { + StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":\"diagnostic\",\"severity\":"); + String severity; + switch (d.getKind()) { + case ERROR: severity = "error"; break; + case WARNING: + case MANDATORY_WARNING: severity = "warning"; break; + default: severity = "info"; + } + json.append(Json.quote(severity)); + JavaFileObject source = d.getSource(); + if (source != null) { + json.append(",\"path\":").append(Json.quote(path(source.toUri()))); + long start = d.getStartPosition(); + long end = d.getEndPosition(); + int[] startCol = start >= 0 ? lineColumn(source, start) : null; + int[] endCol = end >= 0 ? lineColumn(source, end) : null; + if (startCol != null) json.append(",\"line\":").append(startCol[0]).append(",\"column\":").append(startCol[1]); + else if (d.getLineNumber() > 0) json.append(",\"line\":").append(d.getLineNumber()); + if (endCol != null) json.append(",\"endLine\":").append(endCol[0]).append(",\"endColumn\":").append(endCol[1]); + } + if (d.getCode() != null) json.append(",\"code\":").append(Json.quote(d.getCode())); + json.append(",\"message\":").append(Json.quote(d.getMessage(Locale.ROOT))); + return json.append('}').toString(); + } + + /** 1-based line and 0-based UTF-16 column of a char offset (Java chars are UTF-16 units). */ + private static int[] lineColumn(JavaFileObject source, long offset) { + CharSequence text; + try { + text = source.getCharContent(true); + } catch (IOException | RuntimeException e) { + return null; + } + if (offset > text.length()) return null; + int line = 1; + int lineStart = 0; + for (int i = 0; i < offset; i++) { + char c = text.charAt(i); + if (c == '\n' || (c == '\r' && (i + 1 >= text.length() || text.charAt(i + 1) != '\n'))) { + line++; + lineStart = i + 1; + } + } + return new int[] {line, (int) offset - lineStart}; + } + + static String path(URI uri) { + if ("file".equals(uri.getScheme())) return new File(uri).getPath(); + return uri.toString(); + } + + /** Reports every file the compiler writes and the source it came from. */ + static final class Recording extends ForwardingJavaFileManager { + private final long id; + + Recording(JavaFileManager manager, long id) { + super(manager); + this.id = id; + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, + FileObject sibling) throws IOException { + JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling); + report(location, file, sibling, kind == JavaFileObject.Kind.SOURCE); + return file; + } + + @Override + public FileObject getFileForOutput(Location location, String packageName, String relativeName, + FileObject sibling) throws IOException { + FileObject file = super.getFileForOutput(location, packageName, relativeName, sibling); + report(location, file, sibling, location == StandardLocation.SOURCE_OUTPUT); + return file; + } + + private void report(Location location, FileObject file, FileObject sibling, boolean generatedSource) { + StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":") + .append(Json.quote(generatedSource ? "generated" : "output")) + .append(",\"path\":").append(Json.quote(path(file.toUri()))); + if (sibling != null && sibling.toUri().getScheme() != null) + json.append(",\"source\":").append(Json.quote(path(sibling.toUri()))); + json.append(",\"location\":").append(Json.quote(location.getName())); + send(json.append('}').toString()); + } + } + + /** Just enough JSON for the protocol: objects, arrays, strings, numbers, booleans, null. */ + static final class Json { + private final String text; + private int at; + + private Json(String text) { + this.text = text; + } + + @SuppressWarnings("unchecked") + static Map parseObject(String text) { + Json json = new Json(text); + Object value = json.value(); + json.space(); + if (!(value instanceof Map) || json.at != text.length()) throw new IllegalArgumentException("not one JSON object"); + return (Map) value; + } + + static String quote(String s) { + if (s == null) return "null"; + StringBuilder b = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"': b.append("\\\""); break; + case '\\': b.append("\\\\"); break; + case '\n': b.append("\\n"); break; + case '\r': b.append("\\r"); break; + case '\t': b.append("\\t"); break; + default: + if (c < 0x20) b.append(String.format("\\u%04x", (int) c)); + else b.append(c); + } + } + return b.append('"').toString(); + } + + private void space() { + while (at < text.length() && Character.isWhitespace(text.charAt(at))) at++; + } + + private char peek() { + space(); + if (at >= text.length()) throw new IllegalArgumentException("unexpected end"); + return text.charAt(at); + } + + private void expect(char c) { + if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at " + at); + at++; + } + + private Object value() { + char c = peek(); + if (c == '{') { + at++; + Map map = new java.util.LinkedHashMap<>(); + if (peek() == '}') { + at++; + return map; + } + while (true) { + String key = string(); + expect(':'); + map.put(key, value()); + if (peek() == ',') { + at++; + continue; + } + expect('}'); + return map; + } + } + if (c == '[') { + at++; + List list = new ArrayList<>(); + if (peek() == ']') { + at++; + return list; + } + while (true) { + list.add(value()); + if (peek() == ',') { + at++; + continue; + } + expect(']'); + return list; + } + } + if (c == '"') return string(); + if (text.startsWith("true", at)) { + at += 4; + return Boolean.TRUE; + } + if (text.startsWith("false", at)) { + at += 5; + return Boolean.FALSE; + } + if (text.startsWith("null", at)) { + at += 4; + return null; + } + int start = at; + while (at < text.length() && "+-0123456789.eE".indexOf(text.charAt(at)) >= 0) at++; + if (start == at) throw new IllegalArgumentException("unexpected '" + c + "' at " + at); + String number = text.substring(start, at); + return number.contains(".") || number.contains("e") || number.contains("E") + ? (Object) Double.parseDouble(number) : (Object) Long.parseLong(number); + } + + private String string() { + expect('"'); + StringBuilder b = new StringBuilder(); + while (true) { + if (at >= text.length()) throw new IllegalArgumentException("unterminated string"); + char c = text.charAt(at++); + if (c == '"') return b.toString(); + if (c != '\\') { + b.append(c); + continue; + } + char e = text.charAt(at++); + switch (e) { + case 'n': b.append('\n'); break; + case 'r': b.append('\r'); break; + case 't': b.append('\t'); break; + case 'b': b.append('\b'); break; + case 'f': b.append('\f'); break; + case 'u': + b.append((char) Integer.parseInt(text.substring(at, at + 4), 16)); + at += 4; + break; + default: b.append(e); + } + } + } + } + + private Server() { + } +} diff --git a/src/bindings.ts b/src/bindings.ts index 1933a4a54..b4d7ec1b0 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -858,8 +858,10 @@ export const commands = { * A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first. * The build streams its console, messages and progress on `on_event` while it runs; a launch * whose build another launch's build joins receives that build's events. + * A Maven module is built by the IDE's Java build, except for a `debug` launch the language + * server serves: java-debug's HotSwap reloads the classes the language server compiles. */ - javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel) => typedError(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request, onEvent })), + javaResolveLaunch: (module: string, test: boolean, debug: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel) => typedError(__TAURI_INVOKE("java_resolve_launch", { module, test, debug, policy, request, onEvent })), /** * Downloads the latest `vendor` JDK of Java `version` into `location` (default: * [`jdk_download_location`]), streaming progress through `on_event`; cancellable diff --git a/src/features/debugger/__tests__/java.test.ts b/src/features/debugger/__tests__/java.test.ts index b4b46fc24..e8854cfae 100644 --- a/src/features/debugger/__tests__/java.test.ts +++ b/src/features/debugger/__tests__/java.test.ts @@ -99,7 +99,7 @@ describe("Java debugging (java-debug through jdtls)", () => { expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false); const l = await javaLaunchConfig(app, "/p"); expect(invoked).toEqual([ - ["javaResolveLaunch", ["api", false, "automatic", expect.any(Number), expect.anything()]], + ["javaResolveLaunch", ["api", false, true, "automatic", expect.any(Number), expect.anything()]], ["javaDebugAdapter", ["api"]], ["javaDebugServer", ["api"]], ]); @@ -240,7 +240,7 @@ it.each(["sibling", "/outside/modules"])("debugs from %s with the main class mod const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p"); expect(invoked).toContainEqual([ "javaResolveLaunch", - ["api", false, "automatic", expect.any(Number), expect.anything()], + ["api", false, true, "automatic", expect.any(Number), expect.anything()], ]); expect(invoked).toContainEqual(["javaDebugServer", ["api"]]); expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`); diff --git a/src/features/debugger/__tests__/javaCancel.test.ts b/src/features/debugger/__tests__/javaCancel.test.ts index 7e646620a..0b51a4869 100644 --- a/src/features/debugger/__tests__/javaCancel.test.ts +++ b/src/features/debugger/__tests__/javaCancel.test.ts @@ -70,7 +70,7 @@ async function startAndStop() { ).toContain("Building and resolving the classpath of Main…"); expect(useDebugRunSessions.getState().sessions[0]?.configId).toBe(config.id); await executeAction("debug.stop"); - expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![3]); + expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![4]); expect(useDebug.getState().sessions[session.id]?.status).toBe("terminated"); expect(useDebugRunSessions.getState().sessions).toEqual([]); return { starting }; diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index d4439644c..cc8c6b303 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -145,16 +145,16 @@ export async function javaLaunchConfig( const parsed = parseJavaArgs(rc.args); if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`); preparation?.signal.throwIfAborted(); - const { module, info, resolved } = await prepareJavaLaunch( - rc, - preparation ?? { + const { module, info, resolved } = await prepareJavaLaunch(rc, { + ...(preparation ?? { request: nextRequestId(), signal: new AbortController().signal, saveAll: async () => { await maybeEditorService()?.saveAll(); }, - }, - ); + }), + debug: true, + }); const cwd = resolved.cwd ? join(root, resolved.cwd) : root; if (info.errorCount > 0 && !preparation?.report) notifications().notify({ diff --git a/src/features/run/applicationUpdate.test.ts b/src/features/run/applicationUpdate.test.ts index 433c60745..21a767ecc 100644 --- a/src/features/run/applicationUpdate.test.ts +++ b/src/features/run/applicationUpdate.test.ts @@ -147,7 +147,7 @@ const boot = { describe("Spring Boot application updates", () => { it("processes resources and publishes them to the resolved runtime output", async () => { await updateTomcat(boot, "resources"); - expect(mocks.resolve).toHaveBeenCalledWith("app", false, "noBuild", 1, expect.anything()); + expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "noBuild", 1, expect.anything()); expect(mocks.runBuild).toHaveBeenCalledWith({ id: "build" }); expect(mocks.publish).toHaveBeenCalledWith(boot.config, ["/p/app/bin/main"], "a.Main"); expect(mocks.update).not.toHaveBeenCalled(); @@ -155,7 +155,7 @@ describe("Spring Boot application updates", () => { }); it("compiles and invokes the existing scoped HotSwap action in debug", async () => { await updateTomcat(boot, "classes"); - expect(mocks.resolve).toHaveBeenCalledWith("app", false, "make", 1, expect.anything()); + expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "make", 1, expect.anything()); expect(mocks.action).toHaveBeenCalledWith("debug.reloadChangedClasses", { configId: "boot" }); }); it("explains compiled classes require restart without a debugger", async () => { diff --git a/src/features/run/applicationUpdate.ts b/src/features/run/applicationUpdate.ts index 22f6904c5..a3ed26157 100644 --- a/src/features/run/applicationUpdate.ts +++ b/src/features/run/applicationUpdate.ts @@ -54,6 +54,8 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging: mode === "classes" ? "make" : "noBuild", request, followLaunchBuild(request, tx`Build before launch: ${config.name}`), + // HotSwap reloads what the Java language server compiles. + debugging, ); if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled") throw updateBuildError(info); diff --git a/src/features/run/javaModule.test.ts b/src/features/run/javaModule.test.ts index 12edd5a55..73ea1d177 100644 --- a/src/features/run/javaModule.test.ts +++ b/src/features/run/javaModule.test.ts @@ -84,7 +84,14 @@ afterEach(() => { it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => { const session = await startRun({ ...config, module: "app", cwd }); expect(session?.status).toBe("running"); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); expect(ipc.runStart).toHaveBeenCalledWith( expect.objectContaining({ cwd, args: ["-cp", "/p/app/target/classes", "a.Main"] }), expect.anything(), @@ -108,13 +115,27 @@ const launchInfo = (build: "succeeded" | "failed" | "withErrors") => ({ it.each(["noBuild", "rebuild"] as const)("passes the %s build policy to the resolver", async (buildPolicy) => { await startRun({ ...config, module: "app", buildPolicy }); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, buildPolicy, expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + buildPolicy, + expect.any(Number), + expect.anything(), + ); }); it("always applies the launch policy after a Before launch Build Project", async () => { useProject.setState({ project: { root: "/p" } as never }); await startRun({ ...config, module: "app" }); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); useProject.setState({ project: null }); }); @@ -145,7 +166,14 @@ it.each([undefined, "automatic", "make", "rebuild"] as const)( it("finds the source module for an old saved configuration without a module", async () => { await startRun({ ...config, cwd: "/outside/modules" }); expect(ipc.findFiles).toHaveBeenCalledWith("Main.java", 1000); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); expect(ipc.runStart).toHaveBeenCalledWith( expect.objectContaining({ cwd: "/outside/modules" }), expect.anything(), @@ -166,7 +194,14 @@ it.each([null, "/elsewhere"])("recovers an attached module from its indexed path }); const session = await startRun({ ...config, cwd }); expect(session?.status).toBe("running"); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + module, + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); expect(ipc.runStart).toHaveBeenCalledWith( expect.objectContaining({ cwd: cwd ?? module, module }), expect.anything(), @@ -184,7 +219,14 @@ it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath reso expect.anything(), expect.any(Number), ); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); expect(boot.args).toBe(args); expect(args).not.toContain("-Dspring.output.ansi.enabled=always"); }); @@ -193,14 +235,28 @@ it.each(["never", "detect", "always"])("preserves an explicit Spring Boot consol const args = [`-Dspring.output.ansi.enabled=${value}`, "-cp", "lib/*", "a.Main"]; await startRun({ ...config, kind: "spring-boot", args }); expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number)); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); }); it("keeps plain Java runs with an explicit classpath free of Spring Boot options", async () => { const args = ["-cp", "lib/*", "a.Main"]; await startRun({ ...config, args }); expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number)); - expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything()); + expect(ipc.javaResolveLaunch).toHaveBeenCalledWith( + "app", + false, + false, + "automatic", + expect.any(Number), + expect.anything(), + ); }); it("adds the Spring Boot console option once when resolving the module classpath", async () => { diff --git a/src/features/run/resolveCancellation.test.ts b/src/features/run/resolveCancellation.test.ts index 95c7d5a8d..05020bc84 100644 --- a/src/features/run/resolveCancellation.test.ts +++ b/src/features/run/resolveCancellation.test.ts @@ -69,7 +69,7 @@ describe("Stop during Java launch resolution", () => { await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce()); const session = useRun.getState().sessions[0]!; expect(session.status).toBe("starting"); - const request = ipc.javaResolveLaunch.mock.calls[0]![3]; + const request = ipc.javaResolveLaunch.mock.calls[0]![4]; expect(request).toEqual(expect.any(Number)); await stopSession(session.id); expect(ipc.cancelRequest).toHaveBeenCalledExactlyOnceWith(request); diff --git a/src/features/run/tomcat.test.tsx b/src/features/run/tomcat.test.tsx index 654fdd851..20712ec25 100644 --- a/src/features/run/tomcat.test.tsx +++ b/src/features/run/tomcat.test.tsx @@ -292,7 +292,14 @@ describe("updating a running Tomcat deployment", () => { it("compiles the selected WAR module and copies its outputs instead of rebuilding the WAR", async () => { const c = config({ deployment: "artifact", artifact: "maven:web/pom.xml" }); expect(await syncTomcatOutputs(c, false)).toBe(true); - expect(commands.javaResolveLaunch).toHaveBeenCalledWith("web", false, "make", expect.anything(), expect.anything()); + expect(commands.javaResolveLaunch).toHaveBeenCalledWith( + "web", + false, + false, + "make", + expect.anything(), + expect.anything(), + ); expect(commands.runTomcatSync).toHaveBeenCalledWith(c, "web", ["/p/web/target/classes", "/m2/lib.jar"], false); }); diff --git a/src/platform/javaLaunch.ts b/src/platform/javaLaunch.ts index 1be4a26e7..1cff1916c 100644 --- a/src/platform/javaLaunch.ts +++ b/src/platform/javaLaunch.ts @@ -252,6 +252,11 @@ export interface JavaPreparation { saveAll?: () => Promise; /** Follows the build while it runs (status bar, Build tool window); see `followLaunchBuild`. */ build?: JavaBuildFollower; + /** + * A debug launch: a module the Java language server serves is compiled by it, whose classes + * java-debug's HotSwap reloads, instead of the IDE's Java build. + */ + debug?: boolean; } /** Receives the events of a launch's build as it runs, then its outcome. */ @@ -267,11 +272,12 @@ export async function resolveJavaLaunch( policy: BuildPolicy, request: RequestId, build?: JavaBuildFollower, + debug = false, ): Promise { const channel = new Channel(); channel.onmessage = (e) => build?.onEvent(e); try { - const info = await call(commands.javaResolveLaunch(module, test, policy, request, channel)); + const info = await call(commands.javaResolveLaunch(module, test, debug, policy, request, channel)); build?.finish(info.build === "failed" ? "failed" : info.build === "cancelled" ? "cancelled" : "success"); return info; } catch (e) { @@ -305,6 +311,7 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep policy, preparation.request, preparation.build, + preparation.debug, ).catch((error: unknown) => { if (error instanceof IpcError && error.data?.type === "javaBuildProblems") { const problems = error.data.problems.join("; ");