Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class Config:
else:
DYLIB_PREFIX = "lib"
DYLIB_SUFFIX = ".so"

RUST_BACKEND_DYLIB = ROOT_DIR / "target/release" / f"{DYLIB_PREFIX}rustc_codegen_jvm{DYLIB_SUFFIX}"
RUST_BACKEND_TOOLCHAIN = ROOT_DIR / "target/release/.rustc_codegen_jvm-toolchain"
JAVA_LINKER_EXE = JAVA_LINKER_DIR / "target/release/java-linker"
Expand All @@ -84,8 +84,8 @@ def run_command(cmd: List[str], cwd: Path = None, check: bool = True):
print(f"{Colors.YELLOW}▶️ Running: {' '.join(cmd)}{cwd_str}{Colors.RESET}")
try:
proc = subprocess.run(
cmd,
cwd=cwd,
cmd,
cwd=cwd,
check=check,
stdout=sys.stdout, # Stream output directly
stderr=sys.stderr
Expand Down Expand Up @@ -143,17 +143,17 @@ def contains_non_runtime_classes(jar_path: Path) -> bool:
def clean():
"""Cleans all generated files and build artifacts."""
print(f"{Colors.CYAN}🧹 Cleaning all components...{Colors.RESET}")

# Root cargo clean
run_command(["cargo", "clean"], cwd=Config.ROOT_DIR)

# Subproject cargo clean
run_command(["cargo", "clean"], cwd=Config.JAVA_LINKER_DIR)
run_command(["cargo", "clean"], cwd=Config.CARGO_JVM_DIR)

# Remove specific files and directories
for path in [
Config.CONFIG_TOML,
Config.CONFIG_TOML,
Config.JVM_TARGET_JSON,
Config.RUNTIME_DIR / "build"
]:
Expand Down Expand Up @@ -192,8 +192,8 @@ def build_runtime():
Config.RUNTIME_CLASSES_DIR.mkdir(parents=True, exist_ok=True)
Config.RUNTIME_JAR.parent.mkdir(parents=True, exist_ok=True)

source_paths = [str(path) for path in Config.RUNTIME_SOURCES]
javac_base = ["javac", "-Xlint:-options", "-d", str(Config.RUNTIME_CLASSES_DIR)]
source_paths = [str(path).removeprefix("//?/") for path in Config.RUNTIME_SOURCES]
javac_base = ["javac", "-Xlint:-options", "-d", str(Config.RUNTIME_CLASSES_DIR).removeprefix("//?/")]
proc = run_command(["javac", "--release", "8"] + javac_base[1:] + source_paths, check=False)
if proc.returncode != 0:
print(
Expand All @@ -204,9 +204,9 @@ def build_runtime():
run_command([
"jar",
"cf",
str(Config.RUNTIME_JAR),
str(Config.RUNTIME_JAR).removeprefix("//?/"),
"-C",
str(Config.RUNTIME_CLASSES_DIR),
str(Config.RUNTIME_CLASSES_DIR).removeprefix("//?/"),
".",
])

Expand Down Expand Up @@ -234,7 +234,7 @@ def build_rust_backend():
):
print(f"{Colors.GREEN}✅ Rust codegen backend is up to date.{Colors.RESET}")
return

print(f"{Colors.CYAN}📦 Building Rust codegen backend...{Colors.RESET}")
# Setting RUSTFLAGS as an environment variable is more robust.
env = os.environ.copy()
Expand All @@ -248,7 +248,7 @@ def build_java_linker():
if not is_stale(Config.JAVA_LINKER_EXE, Config.LINKER_RUST_SOURCES):
print(f"{Colors.GREEN}✅ Java linker is up to date.{Colors.RESET}")
return

print(f"{Colors.CYAN}📦 Building Java linker...{Colors.RESET}")
env = os.environ.copy()
env["RUSTFLAGS"] = "-Awarnings"
Expand All @@ -264,35 +264,35 @@ def build_cargo_jvm():
print(f"{Colors.CYAN}📦 Building cargo-jvm...{Colors.RESET}")
subprocess.run(["cargo", "build", "--release"], cwd=Config.CARGO_JVM_DIR, check=True)
print(f"{Colors.GREEN} cargo-jvm built successfully.{Colors.RESET}")

def generate_config_files():
"""Generates config.toml and jvm-unknown-jvm.json from templates."""
print(f"{Colors.CYAN}🛠️ Generating configuration files from templates...{Colors.RESET}")

# Logic from GenerateFiles.py is now integrated here
replacements = {
"../../../": Config.ROOT_DIR.as_posix() + "/",
"../../../": Config.ROOT_DIR.as_posix().removeprefix("//?/") + "/",
"@RUST_BACKEND_DYLIB@": Config.RUST_BACKEND_DYLIB.name,
}

for template_path in Config.ROOT_DIR.glob("*.template"):
content = template_path.read_text()
for old, new in replacements.items():
content = content.replace(old, new)

target_path = template_path.with_suffix("") # Removes .template
target_path.write_text(content)
shutil.copymode(template_path, target_path)
print(f" Generated {target_path.name}")
print(f"{Colors.GREEN} Configuration files generated.{Colors.RESET}")

def all_tasks():
"""Runs all necessary build tasks in the correct order."""
if not Config.IS_CI:
install_rust_components()

generate_config_files()

# The order defines the dependency chain.
build_runtime()
build_rust_backend()
Expand Down Expand Up @@ -327,9 +327,9 @@ def help_message():
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Build script for rustc_codegen_jvm.")
parser.add_argument(
"target",
nargs="?",
default="all",
"target",
nargs="?",
default="all",
choices=TARGETS.keys(),
help=f"The build target to run. One of: {', '.join(TARGETS.keys())}"
)
Expand Down
48 changes: 38 additions & 10 deletions cargo-jvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,9 @@ fn package_library(backend: &Backend, rlibs: &BTreeSet<PathBuf>, output: &Path)
if rlibs.is_empty() {
return Err(user_error("Cargo did not report any library archives"));
}
let has_panic_unwind = rlibs.iter().any(|path| rlib_crate_name(path) == Some("panic_unwind"));
let has_panic_unwind = rlibs
.iter()
.any(|path| rlib_crate_name(path) == Some("panic_unwind"));
let selected_rlibs = rlibs.iter().filter(|path| {
// `-Zbuild-std=std,panic_unwind` may still report panic_abort as a
// compiler artifact. A native linker selects one panic runtime; a JAR
Expand All @@ -853,7 +855,21 @@ fn package_library(backend: &Backend, rlibs: &BTreeSet<PathBuf>, output: &Path)

fn rlib_crate_name(path: &Path) -> Option<&str> {
let name = path.file_stem()?.to_str()?.strip_prefix("lib")?;
Some(name.split_once('-').map_or(name, |(crate_name, _)| crate_name))
Some(
name.split_once('-')
.map_or(name, |(crate_name, _)| crate_name),
)
}

fn strip_unc_prefix(path: &Path) -> PathBuf {
let s = path.to_string_lossy();
if let Some(stripped) = s.strip_prefix(r"\\?\") {
PathBuf::from(stripped)
} else if let Some(stripped) = s.strip_prefix("//?/") {
PathBuf::from(stripped)
} else {
path.to_path_buf()
}
}

fn cargo_command(
Expand All @@ -867,14 +883,14 @@ fn cargo_command(
command
.arg(subcommand)
.arg("--target")
.arg(&backend.target_spec)
.arg(strip_unc_prefix(&backend.target_spec))
.arg("-Zjson-target-spec")
.arg("-Zbuild-std=std,panic_unwind")
.arg("-Zbuild-std-features=panic-unwind")
.arg("--config")
.arg(&backend.cargo_config)
.arg(strip_unc_prefix(&backend.cargo_config))
.env("RUSTUP_TOOLCHAIN", &backend.toolchain.channel)
.env("__CARGO_TESTS_ONLY_SRC_ROOT", overlay);
.env("__CARGO_TESTS_ONLY_SRC_ROOT", strip_unc_prefix(&overlay));
if capture {
command.arg("--message-format=json-render-diagnostics");
}
Expand Down Expand Up @@ -1234,7 +1250,10 @@ fn print_doctor(backend: &Backend) -> DynResult<()> {
print!(" (dirty)");
}
println!();
println!("rustc_codegen_jvm: {}", backend.root.display());
println!(
"rustc_codegen_jvm: {}",
strip_unc_prefix(&backend.root).display()
);
println!("pinned Rust toolchain: {}", backend.toolchain.channel);
match git_output(&backend.root, &["log", "-1", "--format=%H%x09%s"]) {
Ok(commit) => println!("rustc_codegen_jvm HEAD: {}", commit.trim()),
Expand Down Expand Up @@ -1280,9 +1299,15 @@ fn print_doctor(backend: &Backend) -> DynResult<()> {
};
println!("{name}: {}", String::from_utf8_lossy(version).trim());
}
println!("target: {}", backend.target_spec.display());
println!("linker: {}", backend.linker.display());
println!("runtime: {}", backend.runtime_jar.display());
println!(
"target: {}",
strip_unc_prefix(&backend.target_spec).display()
);
println!("linker: {}", strip_unc_prefix(&backend.linker).display());
println!(
"runtime: {}",
strip_unc_prefix(&backend.runtime_jar).display()
);
Ok(())
}

Expand Down Expand Up @@ -1601,7 +1626,10 @@ mod tests {
rlib_crate_name(Path::new("/tmp/libpanic_unwind-35f4b19ff65eda2b.rlib")),
Some("panic_unwind")
);
assert_eq!(rlib_crate_name(Path::new("/tmp/libdemo.rlib")), Some("demo"));
assert_eq!(
rlib_crate_name(Path::new("/tmp/libdemo.rlib")),
Some("demo")
);
assert_eq!(rlib_crate_name(Path::new("/tmp/demo.jar")), None);
}

Expand Down
6 changes: 3 additions & 3 deletions stdlib_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ def prepare_stdlib_source(sysroot: Path, commit: str) -> tuple[Path, str]:
try:
shutil.copytree(installed, temporary_library)
shutil.copytree(STDLIB_OVERLAY_ROOT, temporary_library, dirs_exist_ok=True)
patch_directory = temporary_library.relative_to(ROOT)
patch_directory = temporary_library.relative_to(ROOT).as_posix()
for patch in sorted(STDLIB_PATCH_ROOT.glob("*.patch")):
applied = run(
[
"git",
"apply",
"--whitespace=nowarn",
f"--directory={patch_directory}",
str(patch.resolve()),
patch.relative_to(ROOT).as_posix(),
]
)
if applied.returncode != 0:
Expand All @@ -120,7 +120,7 @@ def prepare_stdlib_source(sysroot: Path, commit: str) -> tuple[Path, str]:
def main() -> None:
sysroot, _, commit = rustc_info()
source, _ = prepare_stdlib_source(sysroot, commit)
print(source)
print(source.as_posix().removeprefix("//?/"))


if __name__ == "__main__":
Expand Down