From 6304811ac92dca759fd0fb9f5bc4151f2de43424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=40=E9=B9=BF?= <95417360+T-fenlin@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:24:42 +0800 Subject: [PATCH] fix(java): run a single Java file on the project JDK, including JDK 6 (#7925) A single Java file ran on the java found on PATH, so a JDK 6/8 project could not start it: those launchers have no source mode. The file now runs on the project or module JDK; when that JDK has no source launcher, or the file belongs to an Eclipse module, it is compiled with the JDK's javac (source folders, jars, encoding and referenced workspace projects from .classpath) and started with java -cp. JDK 6 is detected from rt.jar's manifest. The class name comes from the package declaration, and the source path from where the package path starts, so Maven-style layouts resolve correctly. JDWP and VM options stay before -cp, program arguments after the class. Co-authored-by: T-fenlin <95417360+T-fenlin@users.noreply.github.com> --- crates/ide-host/src/ops/run.rs | 5 + crates/ide-host/src/ops/run/java_file.rs | 609 ++++++++++++++++++++++ crates/ide-sdk/src/java.rs | 44 +- crates/ide-workspace/src/roots/eclipse.rs | 25 +- src/features/run/producers.test.ts | 21 + src/features/run/producers.ts | 25 +- src/features/run/runtimes.ts | 7 +- 7 files changed, 727 insertions(+), 9 deletions(-) create mode 100644 crates/ide-host/src/ops/run/java_file.rs diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 76e301e952..70062e48a7 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -527,6 +527,10 @@ async fn start_inner( ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags); } let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new(""))); + // A single Java source file runs on the project's JDK: JDK 6/8 compile it with javac + // first (their launchers have no JEP 330 source mode), and its Eclipse module's class + // path is honoured. The rewritten command starts below like any other. + java_file::prepare(&project.root, root, &settings, &mut config, &on_output, cancel).await?; add_java_agents(&mut config, &on_output, Some(&run_dir)); if config.command == ide_sdk::godot::COMMAND { return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND)); @@ -930,6 +934,7 @@ pub async fn run_attach(host: &Host, window: &str, id: RunId, on_output: Channel pub mod commands; pub(crate) mod container; +mod java_file; pub use commands::*; #[cfg(test)] diff --git a/crates/ide-host/src/ops/run/java_file.rs b/crates/ide-host/src/ops/run/java_file.rs new file mode 100644 index 0000000000..443ede3941 --- /dev/null +++ b/crates/ide-host/src/ops/run/java_file.rs @@ -0,0 +1,609 @@ +//! One Java source file run from the gutter (`kind == "java-file"`). +//! +//! JDK 11+ starts the file with the source launcher (`java Hi.java`, JEP 330). Older JDKs +//! have no source launcher, so the file is compiled with that JDK's `javac` and started +//! with `java -cp`. A nearby Eclipse project's `.classpath` supplies the source folders, +//! library jars and encoding, together with the workspace projects it references (legacy +//! code shares classes between projects); the compiled classes go to a cache directory, +//! never into the project. +use super::Emit; +use ide_core::settings::Settings; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use ide_run::{OutputChunk, RunConfig}; +use ide_sdk::java::Jdk; +use ide_workspace::roots::eclipse; +use std::hash::{Hash, Hasher}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::Duration; + +/// A large project can take a while to compile; the run is cancelled with the request. +const COMPILE_TIMEOUT: Duration = Duration::from_secs(120); + +/// What the Eclipse project around the file declares in its `.classpath`. +#[derive(Debug)] +struct JavaFileModule { + /// Directory of the Eclipse project (holds `.classpath`). + dir: PathBuf, + sources: Vec, + libraries: Vec, + /// Eclipse's per-project source encoding (`GBK`, `UTF-8`, …), when it declares one. + encoding: Option, +} + +impl JavaFileModule { + /// The innermost Eclipse project above `file` (within `boundary`). + fn of(file: &Path, boundary: &Path) -> Option { + let mut ancestors = file.parent()?.ancestors().take_while(|dir| dir.starts_with(boundary)); + let (dir, cp) = ancestors.find_map(|dir| eclipse::classpath(dir).map(|cp| (dir, cp)))?; + Self::at(dir, &cp, boundary) + } + + /// The module `dir` itself declares, if it has a `.classpath`, and its Eclipse project + /// references: legacy workspaces share the model between projects (`/htlib`, `/htmzbase`). + fn at(dir: &Path, cp: &eclipse::EclipseClasspath, boundary: &Path) -> Option { + let mut module = Self { + dir: dir.to_path_buf(), + sources: Vec::new(), + libraries: Vec::new(), + encoding: eclipse_encoding(dir), + }; + let mut seen = Vec::new(); + collect_eclipse(dir, cp, boundary, false, &mut seen, &mut module); + Some(module) + } +} + +/// Eclipse's build path: the project's source folders and jars, and those of every Eclipse +/// project it references (their output folder, jars and sources, transitively). The module's +/// own output folder is left out: the file is compiled into a fresh directory, not against +/// classes of an older build. +fn collect_eclipse( + dir: &Path, + cp: &eclipse::EclipseClasspath, + boundary: &Path, + referenced: bool, + seen: &mut Vec, + module: &mut JavaFileModule, +) { + if seen.iter().any(|seen| seen == dir) { + return; + } + seen.push(dir.to_path_buf()); + let resolve = |path: &str| ide_core::project_roots::resolve(dir, Path::new(path)); + for (source, _) in &cp.sources { + push_unique(&mut module.sources, resolve(source), Path::is_dir); + } + if referenced && let Some(output) = &cp.output { + push_unique(&mut module.libraries, resolve(output), Path::exists); + } + for library in &cp.libraries { + // `/OtherProject/lib.jar` names a jar of another project of the workspace. + let path = match library.strip_prefix('/').and_then(|rest| rest.split_once('/')) { + Some((project, rest)) => eclipse::referenced_project(dir, project, boundary).map(|dir| dir.join(rest)), + None => Some(resolve(library)), + }; + if let Some(path) = path { + push_unique(&mut module.libraries, path, Path::exists); + } + } + for project in &cp.projects { + let Some(other) = eclipse::referenced_project(dir, project, boundary) else { continue }; + if let Some(cp) = eclipse::classpath(&other) { + collect_eclipse(&other, &cp, boundary, true, seen, module); + } + } +} + +fn push_unique(paths: &mut Vec, path: PathBuf, usable: impl Fn(&Path) -> bool) { + if usable(&path) && !paths.contains(&path) { + paths.push(path); + } +} + +/// The JDK the file runs on: the module's, the project's, else one that can compile the +/// project's language level (JDK 6 is a full JDK and works here). +fn java_jdk(root: &Path, module: Option<&Path>, settings: &Settings) -> Option { + let module = module.unwrap_or(root); + ide_sdk::apply::module_jdk(root, module, settings).or_else(|| { + let level = ide_sdk::apply::effective_java_language_level(root, module, settings) + .and_then(ide_build::compile::language_release); + let installed = ide_sdk::java::installed_jdks(); + ide_sdk::java::pick_jdk(&installed, level).cloned() + }) +} + +fn jdk_bin(home: &Path, name: &str) -> PathBuf { + let name = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }; + home.join("bin").join(name) +} + +/// Whether a launcher argument names a Java source file; no lowercased copy is allocated. +fn is_java_source(arg: &str) -> bool { + arg.as_bytes().get(arg.len().saturating_sub(5)..).is_some_and(|tail| tail.eq_ignore_ascii_case(b".java")) +} + +fn file_name(path: &Path) -> String { + path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default() +} + +/// Eclipse's source encoding for the project at `dir` +/// (`.settings/org.eclipse.core.resources.prefs`, `encoding/=…`). +fn eclipse_encoding(dir: &Path) -> Option { + let prefs = std::fs::read_to_string(dir.join(".settings/org.eclipse.core.resources.prefs")).ok()?; + let key = std::fs::read_to_string(dir.join(".project")) + .ok() + .and_then(|project| project_name(&project)) + .map(|name| format!("encoding/{name}")); + prefs.lines().find_map(|line| { + let (line_key, value) = line.split_once('=')?; + let line_key = line_key.trim(); + let wanted = key.as_deref().map_or_else(|| line_key.starts_with("encoding/"), |key| line_key == key); + wanted.then(|| value.trim().to_owned()).filter(|value| !value.is_empty()) + }) +} + +/// The `` of an Eclipse `.project` file. +fn project_name(project: &str) -> Option { + let start = project.find("")? + "".len(); + let end = project[start..].find("")? + start; + Some(project[start..end].trim().to_owned()) +} + +fn join_paths(paths: &[PathBuf]) -> String { + std::env::join_paths(paths).map(|paths| paths.to_string_lossy().into_owned()).unwrap_or_default() +} + +/// The class javac writes for the file: its package declaration and the file stem. +fn class_name(file: &Path, package: Option<&str>) -> String { + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + match package { + Some(package) => format!("{package}.{stem}"), + None => stem, + } +} + +/// The source root the package declaration implies (`…/src/main/java` for +/// `…/src/main/java/com/example/Hi.java` in `com.example`), else the file's folder. +fn package_root(file: &Path, package: Option<&str>) -> Option { + let mut dir = file.parent()?; + for part in package.unwrap_or_default().split('.').filter(|part| !part.is_empty()).rev() { + if dir.file_name().is_none_or(|name| name != part) { + return file.parent().map(Path::to_path_buf); + } + dir = dir.parent()?; + } + Some(dir.to_path_buf()) +} + +/// The package declaration sits at the top; no need to read a large source file whole. +const PACKAGE_SCAN_BYTES: u64 = 64 * 1024; + +/// The `package a.b.c;` declaration, read as ASCII so a legacy (GBK) file still works. +fn package_name(file: &Path) -> Option { + let mut head = Vec::new(); + std::fs::File::open(file).ok()?.take(PACKAGE_SCAN_BYTES).read_to_end(&mut head).ok()?; + String::from_utf8_lossy(&head).lines().find_map(|line| { + let rest = line.trim().strip_prefix("package ")?; + Some(rest.split(';').next()?.trim().to_owned()).filter(|name| !name.is_empty()) + }) +} + +/// A stable directory per source file, so a rebuild reuses classes of unchanged files. +fn compile_dir(file: &Path) -> PathBuf { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + file.hash(&mut hasher); + let stem: String = file + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + .unwrap_or_default() + .chars() + .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }) + .collect(); + std::env::temp_dir().join("openidea-run").join(format!("java-{stem}-{:x}", hasher.finish())) +} + +/// Replaces `config` with `java -cp ` after compiling the file with the +/// JDK's own `javac`; leaves it alone when the JDK supports the source launcher and the +/// file needs no project class path. +pub(super) async fn prepare( + project_root: &Path, + root: &Path, + settings: &ide_core::settings::Settings, + config: &mut RunConfig, + on_output: &Emit, + cancel: &CancellationToken, +) -> IdeResult<()> { + if config.kind != "java-file" { + return Ok(()); + } + // Debugging prefixes the launcher's arguments with the JDWP agent and the configuration's + // VM options (`java -agentlib:jdwp=… Hi.java`); they stay in front of the rewritten + // command, and anything after the file is a program argument. The other launcher form, + // `javac … && java -cp …`, has no source file among its arguments and is left alone. + let at = ide_run::java_cmdline::vm_options_end(&config.args); + if !config.args.get(at).is_some_and(|arg| is_java_source(arg)) { + return Ok(()); + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + // The process starts in the project root plus `cwd` (see `start_inner`); the argument + // is relative to that, not to a workspace member's settings root. + let cwd = project_root.join(config.cwd.as_deref().unwrap_or(Path::new(""))); + let file = { + let path = PathBuf::from(&config.args[at]); + if path.is_absolute() { path } else { ide_core::project_roots::resolve(&cwd, &path) } + }; + if !file.is_file() { + // The launcher reports the missing file with its own message. + return Ok(()); + } + // Reading `.classpath` files and the first scan for installed JDKs touch the disk. + let (module, jdk) = { + let (file, project_root, root, settings) = + (file.clone(), project_root.to_path_buf(), root.to_path_buf(), settings.clone()); + tokio::task::spawn_blocking(move || { + let module = JavaFileModule::of(&file, &project_root); + let jdk = java_jdk(&root, module.as_ref().map(|m| m.dir.as_path()), &settings); + (module, jdk) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + }; + let Some(jdk) = jdk else { + // No JDK resolved: keep the bare `java` of the configuration. + return Ok(()); + }; + let java = ide_sdk::java::java_executable(&jdk.home); + let has_module_classpath = module.as_ref().is_some_and(|m| !m.sources.is_empty() || !m.libraries.is_empty()); + if jdk.major >= 11 && !has_module_classpath { + // A standalone file: the source launcher is enough, on the project's own JDK. + config.command = java.to_string_lossy().into_owned(); + return Ok(()); + } + let javac = jdk_bin(&jdk.home, "javac"); + if !javac.is_file() { + return Err(IdeError::unavailable(format!( + "Running '{}' on JDK {} needs javac, and {} does not exist. Set a full JDK as the project SDK.", + file_name(&file), + jdk.major, + javac.display() + ))); + } + let sources = module.as_ref().map(|m| m.sources.as_slice()).unwrap_or_default(); + let libraries = module.as_ref().map(|m| m.libraries.as_slice()).unwrap_or_default(); + let out = compile_dir(&file); + std::fs::create_dir_all(&out).map_err(|e| IdeError::internal(format!("Cannot create {} ({e})", out.display())))?; + let mut args: Vec = vec!["-g".into(), "-d".into(), out.to_string_lossy().into_owned()]; + if !libraries.is_empty() { + args.extend(["-cp".into(), join_paths(libraries)]); + } + // Sources outside the file's own file are compiled on demand (`-implicit`), so a + // reference to another class of the project ends up in the same output directory. + let package = package_name(&file); + let source_path = if sources.is_empty() { + package_root(&file, package.as_deref()).into_iter().collect() + } else { + sources.to_vec() + }; + if !source_path.is_empty() { + args.extend(["-sourcepath".into(), join_paths(&source_path)]); + } + if let Some(encoding) = module.as_ref().and_then(|m| m.encoding.as_deref()) { + args.extend(["-encoding".into(), encoding.to_owned()]); + } + args.push(file.to_string_lossy().into_owned()); + + let class = class_name(&file, package.as_deref()); + let cwd = file.parent().map(Path::to_path_buf).unwrap_or(cwd); + let javac_args = args; + let javac_program = javac.clone(); + let compiled = tokio::time::timeout( + COMPILE_TIMEOUT, + tokio::task::spawn_blocking(move || { + let mut command = Command::new(&javac_program); + command.args(&javac_args).current_dir(&cwd).stdin(Stdio::null()); + // A release build is a GUI process: without CREATE_NO_WINDOW, Windows opens a + // console window for javac (a dev build shares its launcher's console instead). + ide_core::process::prepare(&mut command).output() + }), + ) + .await + .map_err(|_| IdeError::unavailable("Compiling the Java file timed out"))? + .map_err(|e| IdeError::internal(e.to_string()))?; + let output = match compiled { + Ok(output) => output, + Err(e) => { + return Err(IdeError::unavailable(format!("Cannot run {} ({e})", javac.display()))); + } + }; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let stdout = ide_core::output_encoding::decode_tool_output(&output.stdout); + let stderr = ide_core::output_encoding::decode_tool_output(&output.stderr); + // The first diagnostic is the failure message; take it before `stderr` is emitted. + let failure = (!output.status.success()) + .then(|| stderr.lines().find(|line| !line.trim().is_empty()).unwrap_or("javac failed").trim().to_owned()); + if !stdout.trim().is_empty() { + on_output(OutputChunk::System { text: with_newline(stdout) }); + } + if !stderr.trim().is_empty() { + on_output(OutputChunk::Stderr { text: with_newline(stderr) }); + } + if let Some(detail) = failure { + return Err(IdeError::invalid(format!( + "Compiling '{}' with JDK {} failed: {detail}", + file_name(&file), + jdk.major + ))); + } + let class_file = out.join(format!("{}.class", class.replace('.', "/"))); + if !class_file.is_file() { + return Err(IdeError::invalid(format!( + "javac did not write {}; check the package and the public class name of the file", + class_file.display() + ))); + } + let mut class_paths = vec![out]; + class_paths.extend(libraries.iter().cloned()); + let mut rewritten = config.args[..at].to_vec(); + rewritten.extend(["-cp".into(), join_paths(&class_paths), class]); + rewritten.extend(config.args[at + 1..].iter().cloned()); + config.command = java.to_string_lossy().into_owned(); + config.args = rewritten; + Ok(()) +} + +fn with_newline(mut text: String) -> String { + if !text.ends_with('\n') { + text.push('\n'); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use ide_core::settings::Settings; + use std::sync::Arc; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn file_config(_file: &Path, args: Vec) -> RunConfig { + RunConfig { + id: "java-file:test".into(), + name: "Hi".into(), + kind: "java-file".into(), + command: "java".into(), + args, + cwd: None, + env: Default::default(), + detected: true, + is_test: false, + debug_adapter: Some("java-debug".into()), + allow_parallel: false, + extras: Default::default(), + } + } + + fn no_output() -> Emit { + Arc::new(|_chunk: OutputChunk| {}) + } + + #[test] + fn class_names_follow_the_source_root_and_the_package_declaration() { + let dir = tempfile::tempdir().unwrap(); + let src = dir.path().join("src"); + let file = src.join("com/example/Hi.java"); + write(&file, "package com.example;\nclass Hi {}\n"); + let package = package_name(&file); + assert_eq!(class_name(&file, package.as_deref()), "com.example.Hi"); + assert_eq!(package_root(&file, package.as_deref()), Some(src)); + // A Maven layout: the root is where the package path starts, not the `src` folder. + let maven = dir.path().join("app/src/main/java/a/b/Hi.java"); + write(&maven, "package a.b;\npublic class Hi {}\n"); + let package = package_name(&maven); + assert_eq!(class_name(&maven, package.as_deref()), "a.b.Hi"); + assert_eq!(package_root(&maven, package.as_deref()), Some(dir.path().join("app/src/main/java"))); + // A folder that does not match the package: javac still finds the file itself. + let loose = dir.path().join("other/Hi.java"); + write(&loose, "package a.b;\npublic class Hi {}\n"); + let package = package_name(&loose); + assert_eq!(class_name(&loose, package.as_deref()), "a.b.Hi"); + assert_eq!(package_root(&loose, package.as_deref()), Some(dir.path().join("other"))); + assert_eq!(package_root(&loose, None), Some(dir.path().join("other"))); + } + + #[test] + fn eclipse_modules_supply_sources_libraries_and_the_source_encoding() { + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("proj"); + write( + &project.join(".classpath"), + r#" + + + + +"#, + ); + write(&project.join(".project"), "demo"); + write( + &project.join(".settings/org.eclipse.core.resources.prefs"), + "eclipse.preferences.version=1\nencoding/demo=GBK\n", + ); + std::fs::create_dir_all(project.join("src")).unwrap(); + write(&project.join("lib/dep.jar"), ""); + let file = project.join("src/p/Hi.java"); + write(&file, "package p;\nclass Hi {}\n"); + let module = JavaFileModule::of(&file, dir.path()).unwrap(); + assert_eq!(module.dir, project); + assert_eq!(module.sources, [project.join("src")]); + assert_eq!(module.libraries, [project.join("lib/dep.jar")]); + assert_eq!(module.encoding.as_deref(), Some("GBK")); + } + + #[test] + fn eclipse_project_references_supply_their_sources_output_and_jars() { + // svcLocalInpInfo → /htlib: the referenced project's bin, its jars and its sources. + let dir = tempfile::tempdir().unwrap(); + let workspace = dir.path(); + let app = workspace.join("app"); + let lib = workspace.join("htlib"); + write(&app.join(".project"), "app"); + write( + &app.join(".classpath"), + r#" + + + + + +"#, + ); + std::fs::create_dir_all(app.join("src")).unwrap(); + std::fs::create_dir_all(app.join("bin")).unwrap(); + write(&app.join("lib/own.jar"), ""); + write(&lib.join(".project"), "htlib"); + write( + &lib.join(".classpath"), + r#" + + + + +"#, + ); + std::fs::create_dir_all(lib.join("src")).unwrap(); + std::fs::create_dir_all(lib.join("bin")).unwrap(); + write(&lib.join("htxs-system.jar"), ""); + write(&lib.join("lib/jdom.jar"), ""); + let file = app.join("src/p/Hi.java"); + write(&file, "package p;\nclass Hi {}\n"); + let module = JavaFileModule::of(&file, workspace).unwrap(); + assert_eq!(module.dir, app); + assert_eq!(module.sources, [app.join("src"), lib.join("src")]); + // The app's own `bin` is not trusted; the referenced project's is Eclipse's model. + assert_eq!( + module.libraries, + [app.join("lib/own.jar"), lib.join("htxs-system.jar"), lib.join("bin"), lib.join("lib/jdom.jar")] + ); + } + + #[test] + fn a_jdk_6_project_sdk_is_used_for_the_file() { + // A JDK 6 install has no `release` file: `jdk_at` reads `rt.jar`'s manifest. + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("jdk6"); + write(&home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }), ""); + std::fs::create_dir_all(home.join("jre/lib")).unwrap(); + let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("jre/lib/rt.jar")).unwrap()); + zip.start_file("META-INF/MANIFEST.MF", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"Manifest-Version: 1.0\r\nSpecification-Version: 1.6\r\n\r\n").unwrap(); + zip.finish().unwrap(); + let mut settings = Settings::default(); + settings.languages.java.jdk = home.to_string_lossy().into_owned(); + let jdk = java_jdk(dir.path(), None, &settings).expect("the configured JDK 6"); + assert_eq!(jdk.major, 6); + } + + /// A file of an Eclipse module with a JDK that has no source launcher is compiled with + /// `javac` and started from a class path. Skipped when no JDK is configured. + #[tokio::test] + async fn a_project_file_is_compiled_and_started_from_a_class_path() { + let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return }; + if !jdk_bin(&home, "javac").is_file() || !jdk_bin(&home, "java").is_file() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("proj"); + write(&project.join(".classpath"), ""); + write(&project.join(".project"), "demo"); + let file = project.join("src/p/Hi.java"); + write( + &file, + "package p; public class Hi { public static void main(String[] args) { System.out.println(\"hi\"); } }", + ); + let mut settings = Settings::default(); + settings.languages.java.jdk = home.to_string_lossy().into_owned(); + let mut config = file_config(&file, vec![file.to_string_lossy().into_owned()]); + let output = Arc::new(std::sync::Mutex::new(String::new())); + let sink: Emit = { + let output = output.clone(); + Arc::new(move |chunk: OutputChunk| { + if let OutputChunk::Stderr { text } = chunk { + output.lock().unwrap().push_str(&text); + } + }) + }; + prepare(&project, &project, &settings, &mut config, &sink, &CancellationToken::new()).await.unwrap(); + assert_eq!(config.args.first().map(String::as_str), Some("-cp")); + assert_eq!(config.args.last().map(String::as_str), Some("p.Hi")); + let run = Command::new(&config.command).args(&config.args).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(String::from_utf8_lossy(&run.stdout).trim(), "hi"); + } + + /// Debugging a file puts the JDWP agent (and the configuration's VM options) before the + /// file; the compile-and-run rewrite keeps them in front of `-cp` and the program + /// arguments after the class. Skipped when no JDK is configured. + #[tokio::test] + async fn a_debug_launch_keeps_the_jdwp_agent_and_the_program_arguments() { + let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return }; + if !jdk_bin(&home, "javac").is_file() || !jdk_bin(&home, "java").is_file() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("proj"); + write(&project.join(".classpath"), ""); + write(&project.join(".project"), "demo"); + let file = project.join("src/p/Hi.java"); + write( + &file, + "package p; public class Hi { public static void main(String[] args) { System.out.println(args[0]); } }", + ); + let mut settings = Settings::default(); + settings.languages.java.jdk = home.to_string_lossy().into_owned(); + let agent = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:0"; + let args = + vec![agent.to_owned(), "-Xmx1g".to_owned(), file.to_string_lossy().into_owned(), "argument".to_owned()]; + let mut config = file_config(&file, args); + prepare(&project, &project, &settings, &mut config, &no_output(), &CancellationToken::new()).await.unwrap(); + assert_eq!(config.args[..2], [agent, "-Xmx1g"]); + assert_eq!(config.args[2], "-cp"); + assert_eq!(config.args[4], "p.Hi"); + assert_eq!(config.args.last().map(String::as_str), Some("argument")); + let run = Command::new(&config.command).args(&config.args).output().unwrap(); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + // Some JDKs print the JDWP listener line on stdout; the program's output follows it. + let stdout = String::from_utf8_lossy(&run.stdout); + assert!(stdout.trim_end().ends_with("argument"), "{stdout}"); + } + + /// The other launcher form compiles first itself (`javac … && java -cp …`) and names no + /// source file among its arguments: it is left alone. + #[tokio::test] + async fn a_compiled_launcher_line_is_left_alone() { + let settings = Settings::default(); + let mut config = file_config(Path::new("Hi.java"), Vec::new()); + config.command = "javac -d out Hi.java && java -cp out Hi".into(); + prepare(Path::new("."), Path::new("."), &settings, &mut config, &no_output(), &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(config.command, "javac -d out Hi.java && java -cp out Hi"); + assert!(config.args.is_empty()); + // A VM option's value that happens to end in `.java` is not the source file either. + let mut option = file_config(Path::new("Hi.java"), vec!["-Dscript=run.java".into()]); + prepare(Path::new("."), Path::new("."), &settings, &mut option, &no_output(), &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(option.args, ["-Dscript=run.java"]); + } +} diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index ca3a00a6ff..bb4588977a 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -26,21 +26,40 @@ pub(crate) fn server_jdk_incomplete_message(jdk: &Jdk, min_java: u32) -> String /// `JAVA_VERSION="21.0.3"` (or `"1.8.0_372"`) from a JDK's `release` file. pub fn parse_release(release: &str) -> Option { let line = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?; - let v = line.trim().trim_matches('"'); + parse_version(line) +} + +/// The feature version of `21.0.3` or `1.8.0_372` (quotes and spaces allowed). +fn parse_version(version: &str) -> Option { + let v = version.trim().trim_matches('"'); let mut parts = v.split(['.', '_', '-', '+']); let first: u32 = parts.next()?.parse().ok()?; if first == 1 { parts.next()?.parse().ok() } else { Some(first) } } -/// The JDK at `home` (or a macOS bundle), if it has a `release` file and `bin/java`. +/// The JDK at `home` (or a macOS bundle), if it has a `release` file (JDK 7+) or a +/// version in `rt.jar`'s manifest (JDK 6) and `bin/java`. pub fn jdk_at(home: &Path) -> Option { let bundle_home = home.join("Contents/Home"); let home = if bundle_home.is_dir() { bundle_home.as_path() } else { home }; - let release = std::fs::read_to_string(home.join("release")).ok()?; if !home.join("bin").join(crate::exe("java")).is_file() { return None; } - Some(Jdk { major: parse_release(&release)?, home: crate::launch_path(home).unwrap_or_else(|_| home.to_path_buf()) }) + let major = std::fs::read_to_string(home.join("release")) + .ok() + .and_then(|release| parse_release(&release)) + .or_else(|| rt_jar_version(home))?; + Some(Jdk { major, home: crate::launch_path(home).unwrap_or_else(|_| home.to_path_buf()) }) +} + +/// JDK 6 predates the `release` file; `rt.jar`'s manifest has `Specification-Version: 1.6`. +fn rt_jar_version(home: &Path) -> Option { + let rt = [home.join("jre/lib/rt.jar"), home.join("lib/rt.jar")].into_iter().find(|p| p.is_file())?; + let mut zip = zip::ZipArchive::new(std::fs::File::open(rt).ok()?).ok()?; + let mut manifest = zip.by_name("META-INF/MANIFEST.MF").ok()?; + let mut text = String::new(); + std::io::Read::read_to_string(&mut manifest, &mut text).ok()?; + text.lines().find_map(|line| line.trim().strip_prefix("Specification-Version:").and_then(parse_version)) } struct JavaProbe { @@ -763,6 +782,23 @@ mod tests { assert_eq!(java_runtime(&jdks, 21), None); } + #[test] + fn jdk_6_is_detected_from_the_rt_jar_manifest() { + use std::io::Write; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("jdk6"); + std::fs::create_dir_all(home.join("bin")).unwrap(); + std::fs::create_dir_all(home.join("jre/lib")).unwrap(); + std::fs::write(home.join("bin").join(crate::exe("java")), "").unwrap(); + let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("jre/lib/rt.jar")).unwrap()); + zip.start_file("META-INF/MANIFEST.MF", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"Manifest-Version: 1.0\r\nSpecification-Version: 1.6\r\n\r\n").unwrap(); + zip.finish().unwrap(); + let jdk = jdk_at(&home).expect("JDK 6 has no release file"); + assert_eq!(jdk.major, 6); + assert_eq!(jdk.home, dunce::canonicalize(&home).unwrap()); + } + fn test_jdk(root: &Path, major: u32, name: &str) -> Jdk { let home = root.join(name.trim_start_matches('/')); std::fs::create_dir_all(home.join("bin")).unwrap(); diff --git a/crates/ide-workspace/src/roots/eclipse.rs b/crates/ide-workspace/src/roots/eclipse.rs index 3806fb9f70..752859594c 100644 --- a/crates/ide-workspace/src/roots/eclipse.rs +++ b/crates/ide-workspace/src/roots/eclipse.rs @@ -1,7 +1,7 @@ //! Eclipse projects without Maven or Gradle: `.classpath` names the source folders (tests //! by their `test` attribute), the output folder and the library jars; a Dynamic Web //! Project's `.settings/org.eclipse.wst.common.component` names the web content folder. -use std::path::Path; +use std::path::{Path, PathBuf}; /// What `.classpath` declares, with project-relative `/`-separated paths. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -11,6 +11,8 @@ pub struct EclipseClasspath { pub output: Option, /// Library jars or class folders (`kind="lib"`), project-relative or absolute. pub libraries: Vec, + /// Eclipse workspace project references (`kind="src" path="/Other"`), by project name. + pub projects: Vec, } /// The value of `name="…"` in a tag's text. @@ -77,8 +79,14 @@ pub fn parse_classpath(text: &str) -> EclipseClasspath { let (Some(kind), Some(path)) = (attribute(tag, "kind"), attribute(tag, "path")) else { continue }; let path = clean(&path); match kind.as_str() { - // `/OtherProject` is a project reference, not a folder of this one. - "src" if !path.starts_with('/') && !path.is_empty() => { + // `/OtherProject` is a reference to another project of the Eclipse workspace. + "src" if path.starts_with('/') => { + let name = path.trim_start_matches('/'); + if !name.is_empty() { + out.projects.push(name.to_owned()); + } + } + "src" if !path.is_empty() => { let test = elements(body, "attribute").iter().any(|(a, _)| { attribute(a, "name").as_deref() == Some("test") && attribute(a, "value").as_deref() == Some("true") }); @@ -92,6 +100,16 @@ pub fn parse_classpath(text: &str) -> EclipseClasspath { out } +/// The folder of the Eclipse workspace project `name`, referenced as `/name` from `dir`: an +/// Eclipse workspace keeps its projects as sibling folders, so look in `dir`'s ancestors up +/// to `boundary`. +pub fn referenced_project(dir: &Path, name: &str, boundary: &Path) -> Option { + dir.ancestors().take_while(|ancestor| ancestor.starts_with(boundary)).find_map(|ancestor| { + let project = ancestor.join(name); + (project.join(".project").is_file()).then_some(project) + }) +} + /// The project's `.classpath`, unless a Maven or Gradle build owns its model. pub fn classpath(dir: &Path) -> Option { if ["pom.xml", "build.gradle", "build.gradle.kts"].iter().any(|f| dir.join(f).is_file()) { @@ -146,6 +164,7 @@ mod tests { assert_eq!(cp.sources, [("src".to_owned(), false), ("test".to_owned(), true)]); assert_eq!(cp.output.as_deref(), Some("build/classes")); assert_eq!(cp.libraries, ["WebContent/WEB-INF/lib/commons-lang.jar", "lib/mail.jar"]); + assert_eq!(cp.projects, ["OtherProject"]); } #[test] diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 1b20c56c2a..207a59d718 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -12,6 +12,7 @@ import { produceDirectory, produceFile, produceFuzz, + projectJavaLauncher, shebang, shellWord, fileTargets, @@ -627,6 +628,26 @@ describe("single-file producers (scratches)", () => { expect(p.config!.args.at(-1)).toBe("demo.Hi"); }); + it("Java: a single file runs and compiles on the Project JDK, not the java on the PATH", () => { + const src = "public class Hi {\n public static void main(String[] args) {}\n}"; + // No `java` on the PATH: the Project JDK alone is enough. + const jdk: ToolEnv = { ...env({}, { windows: true }), java: "C:/jdk6/bin/java.exe" }; + expect(run(scratch("Hi.java", src), jdk)).toMatchObject({ command: "C:/jdk6/bin/java.exe", args: ["Hi.java"] }); + // The `javac` of the same JDK compiles a main class the source launcher would not pick. + const two = "class Parent {}\npublic class Test {\n public static void main(String[] args) {}\n}\n"; + const compiled = produceContext(scratch("Test.java", two), jdk)!.config!; + expect(compiled.command).toContain("C:/jdk6/bin/javac.exe -g"); + expect(compiled.command).toMatch(/C:\/jdk6\/bin\/java\.exe -cp \S+ Test$/); + // A JDK setting is a home, its `bin`, or the launcher; relative to the project root. + expect(projectJavaLauncher("D:\\ProgramData\\java\\jdk-6u45", ROOT, true)).toBe( + "D:/ProgramData/java/jdk-6u45/bin/java.exe", + ); + expect(projectJavaLauncher("/opt/jdk-17/bin", null, false)).toBe("/opt/jdk-17/bin/java"); + expect(projectJavaLauncher("/opt/jdk-17/bin/java", null, false)).toBe("/opt/jdk-17/bin/java"); + expect(projectJavaLauncher("tools/jdk", ROOT, false)).toBe("/work/app/tools/jdk/bin/java"); + expect(projectJavaLauncher(" ", ROOT, false)).toBeNull(); + }); + it("Java: a main class after another top-level class compiles with javac, then runs with java -cp", () => { const src = "class Parent {\n void show() {}\n}\n\npublic class Test {\n" + diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index ca3b595b11..4d1ff0339b 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -72,6 +72,8 @@ export interface ToolEnv { python?: string | null; /** The PHP interpreter chosen in settings (else the `php` on `PATH`). */ php?: string | null; + /** The project JDK's `java` launcher (Java single files run and compile on it). */ + java?: string | null; /** Run JavaScript / TypeScript with Deno / Bun: the project has `deno.json(c)` / `bun.lock(b)`, or `preferred`. */ deno?: boolean; bun?: boolean; @@ -411,6 +413,25 @@ function pick(env: ToolEnv, names: readonly string[]): { name: string; command: return null; } +/** + * The `java` launcher a Project JDK setting (`languages.java.jdk`) names: the setting is a JDK + * home, its `bin`, or the launcher itself. Relative values are relative to the project root. + * Null when no JDK is set. + */ +export function projectJavaLauncher( + jdk: string | null | undefined, + root: string | null, + windows: boolean, +): string | null { + const value = jdk?.trim(); + if (!value) return null; + const path = value.replace(/\\/g, "/").replace(/\/+$/, ""); + const relative = !/^([A-Za-z]:\/|\/|\/\/)/.test(path); + const base = relative && root ? `${root.replace(/\\/g, "/").replace(/\/+$/, "")}/${path}` : path; + if (/\/java(\.exe)?$/i.test(base)) return base; + return `${/\/bin$/i.test(base) ? base : `${base}/bin`}/java${windows ? ".exe" : ""}`; +} + /** `major.minor` of a version string, or null. */ function semver(v: string | null | undefined): [number, number] | null { const m = /^(\d+)\.(\d+)/.exec(v ?? ""); @@ -739,7 +760,9 @@ const hasZigTests = (content?: string) => content !== undefined && /^\s*test\s+( */ function javaFile(input: ContextInput, env: ToolEnv, s: FileSite, mainClass?: string): Produced { const tools = toolsFor("java"); - const java = pick(env, tools); + // The project JDK (Settings › Java) runs the file, as it does for the project's own + // launch configurations; the `java` found on the PATH is only the fallback. + const java = env.java ? { name: "java", command: env.java } : pick(env, tools); if (!java) return { name: s.file, scope: "file", missing: missing("java", s.file, tools) }; const source: Produced = { name: s.file, diff --git a/src/features/run/runtimes.ts b/src/features/run/runtimes.ts index 49851bfc31..731b4af4e5 100644 --- a/src/features/run/runtimes.ts +++ b/src/features/run/runtimes.ts @@ -9,7 +9,7 @@ import { useProject } from "@/platform/project"; import { withRunTarget } from "@/platform/runTargetSelection"; import { call, commands, isTauri } from "@/platform/ipc"; import { isWindows } from "./jvmTypes"; -import type { LocatedTool, ToolEnv } from "./producers"; +import { projectJavaLauncher, type LocatedTool, type ToolEnv } from "./producers"; const TTL = 60_000; @@ -162,6 +162,11 @@ export async function toolEnv( compileDir: compileDir ?? "/tmp/openidea-run", macosSysroot, windows: isWindows(), + // A single Java file runs on the Project JDK, like the project's own launch + // configurations; the `java` on the PATH only stands in when none is set. + java: names.includes("java") + ? projectJavaLauncher(useProject.getState().settings?.languages?.java?.jdk, root, isWindows()) + : null, python: py, php: phpInterpreter, ...markers,