Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.
Rust differential-testinggame-enginegamedevlinuxminecraftminecraft-javareimplementationrustvoxelvulkanwgpu
Merge main (3310fcafb9) into the mod API
arismokod7b307aed55d
diff --cc crates/horizon-client/src/game/native_hooks.rsindex 3a293979f,970e3c577..c69390aa0--- a/crates/horizon-client/src/game/native_hooks.rs+++ b/crates/horizon-client/src/game/native_hooks.rs@@@ -2586,8 -2615,29 +2586,29 @@@ impl Game<'_>command: &str,ran: &mut bool,) {- let _ = (player, command, ran);+ mod_api::dispatch_perform_command(self, mod_api::mods(), player, command, ran);}+ /// A server player's game mode is about to change (NeoForge's+ /// `PlayerChangeGameModeEvent`): from `from` to `to` (0 survival, 1+ /// creative, 2 adventure, 3 spectator, as `NativeServerPlayer`'s+ /// `game_mode`), `player` being the UUID and `name` the name. Heard for+ /// the `/gamemode` command, the F3+F4 switcher's packet and a hardcore+ /// world's respawn into spectator, once for each change to a different+ /// mode; not for the world's default mode a player joins with. Set+ /// `cancel` and the player keeps their mode (nothing is sent, the+ /// command counts it as no change). For a change the game makes inside+ /// a player's turn their state is swapped in; for the hardcore respawn+ /// it is not. @API:native_player_game_mode_changed@.+ pub(super) fn native_player_game_mode_changed(+ &mut self,+ player: u128,+ name: &str,+ from: i32,+ to: i32,+ cancel: &mut bool,+ ) {+ let _ = (player, name, from, to, cancel);+ }/// `player` (`name`) changed dimension (NeoForge's/// `PlayerChangedDimensionEvent`): `from` and `to` are dimension ids/// (`minecraft:overworld`, `minecraft:the_nether`, `minecraft:the_end`).diff --cc docs/launcher-commands.mdindex 1429c5b24,1429c5b24..e8c2fc5a5--- a/docs/launcher-commands.md+++ b/docs/launcher-commands.md@@@ -89,6 -89,6 +89,7 @@@ Native mods (docs/native-mods.md): comphorizon-launcher native-build [FOLDER]- `FOLDER`: A mod folder (horizon-mixin.toml, or an unpacked .hnmod), or a folder of them (default: the native mods installed and turned on in the instance)++- `--server-output`: Export mode: build a standalone dedicated-server engine into this folder instead of an instance's build. Needs a mod FOLDER; no instance is read or changed, and no launcher config is written- `--instance`: The instance whose installed native mods to build, and which then plays the build (default: the selected one)- `--update`: Move to the newest installed release or Nightly instead of the Horizon the instance plays (a full rebuild)- `--trust-native-code`: You read the mods' source and trust it with full access to this computerdiff --cc launcher/src/native_mods.rsindex 70ba346e5,9fe65227f..d764b600c--- a/launcher/src/native_mods.rs+++ b/launcher/src/native_mods.rs@@@ -850,11 -872,16 +925,16 @@@ pub fn version_forhash.update(part.as_bytes());hash.update([0]);}- // bundles() reads folders in path order; that is also trait dispatch order.+ if target == Target::Server {+ hash.update(target.name().as_bytes());+ hash.update([0]);+ }- let mut sorted: Vec<&Bundle> = bundles.iter().collect();- sorted.sort_by(|a, b| a.id.cmp(&b.id));- for b in sorted {++ // bundles() reads folders in path order, which with their manifests decides trait dispatch++ // order: hashed in that order, a different order is another build.+ for b in bundles {hash.update(b.id.as_bytes());hash.update([0]);- for (name, path) in files(&b.dir)? {+ for (name, path) in bundle_files(b)? {let bytes = fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;hash.update(name.as_bytes());hash.update((bytes.len() as u64).to_le_bytes());@@@ -1118,9 -1139,9 +1201,10 @@@ fn apply(rust: &Toolchain, tool: &Pathfn compile(rust: &Toolchain,stage: &Path,- target: &Path,+ target: Target,+ target_dir: &Path,profile: Profile,+ package: &str,) -> Command {let mut cmd = cargo(rust, stage, "build");// Cargo's progress bar (units done of the total) is read from its output. Incremental@@@ -1303,52 -1311,35 +1390,67 @@@ fn sync(from: &Path, to: &Path) -> ResuOk(())}+/// Copy a bundle without its API package's Cargo build output.+fn copy_bundle(bundle: &Bundle, to: &Path) -> Result<(), String> {+ let root = bundle.dir.canonicalize().map_err(|e| e.to_string())?;+ let skip = api_target(&root, bundle.api.as_deref())?;+ backend::copy_dir_except(&root, to, skip.as_deref()).map_err(|e| e.to_string())+}++/// Stage only manifests horizon-mixins can apply, after trait injections are prepared.+fn stage_mixins(mods: &[Bundle], to: &Path) -> Result<(), String> {+ if to.exists() {+ fs::remove_dir_all(to).map_err(|e| e.to_string())?;+ }+ fs::create_dir_all(to).map_err(|e| e.to_string())?;+ for bundle in mods.iter().filter(|b| b.mixins_content) {+ copy_bundle(bundle, &to.join(&bundle.id))?;+ }+ Ok(())+}++/// The `data/` of the bundles horizon-mixins doesn't apply, staged in `stage` where it stages the+/// others' (`native-data/<mod id>/`), for `native_data!` and the mods' build steps.+fn stage_trait_data(mods: &[Bundle], stage: &Path) -> Result<(), String> {+ for bundle in mods.iter().filter(|b| !b.mixins_content) {+ let data = bundle.dir.join("data");+ if data.is_dir() {+ let to = stage.join("native-data").join(&bundle.id);+ backend::copy_dir(&data, &to).map_err(|e| format!("{}: {e}", to.display()))?;+ }+ }+ Ok(())+}+- /// Builds `folder`'s mods on the Horizon revision they pin (else `base`'s, the installed version- /// whose game files the build reuses: a native build's own revision when it is one, [`base_for`])- /// and points `instance` at the build, the default one included. Returns the build's version; a- /// build already made is used again. Mods pinning different revisions build on the newest one,- /// with the newest horizon-mixins they name, only when the player agreed to try (`anyway`): else- /// the error starts with [`MISMATCH`] and says which.- pub fn build(+ /// What a build of `folder`'s mods came out as: the version it installed and what it did.+ #[derive(Clone, Debug)]+ struct Built {+ version: String,+ /// Which case the build was, said before anything ran.+ plan: Plan,+ /// The profile it compiled with: the chosen one, unless the source has no `[profile.fast]`.+ profile: Profile,+ /// How long the whole build took.+ secs: u64,+ }++ /// The pipeline both targets build with ([`build`], [`build_server`]): `folder`'s mods on the+ /// Horizon revision they pin (else `base`'s, the installed version whose game files the build+ /// reuses: a native build's own revision when it is one, [`base_for`]), compiled as `target`+ /// (the game, or the headless engine) and installed as its own version, `native-<revision>-<key>`+ /// (the key hashes the revision, the mods' files, the tool's commit, the profile and the+ /// target). A build already made is used again. Mods pinning different revisions build on the+ /// newest one, with the newest horizon-mixins they name, only when the player agreed to try+ /// (`anyway`): else the error starts with [`MISMATCH`] and says which. Nothing of the player's+ /// outside the launcher's data is touched: no instance is edited and no version selected here.+ fn pipeline(base: &str,folder: &Path,- instance: &Instance,anyway: bool,profile: Profile,- progress: impl Fn(Step),- ) -> Result<String, String> {+ target: Target,+ progress: &impl Fn(Step),+ ) -> Result<Built, String> {let started = std::time::Instant::now();backend::need_prepared(base)?;fs::create_dir_all(root()).map_err(|e| e.to_string())?;@@@ -1455,15 -1417,27 +1557,26 @@@.map(|m| Ok((m.id.clone(), mod_hash(m)?))).collect::<Result<_, String>>()?,};- let exists = backend::installed().contains(&version);- let plan = classify(exists, last_record(profile).as_ref(), &now);+ let exists = target.directory(&version).join(".installed").is_file();+ let plan = classify(exists, last_record(target, profile).as_ref(), &now);progress(Step::Plan(plan.clone(), profile));+ let mut built = Built {+ version: version.clone(),+ plan: plan.clone(),+ profile,+ secs: 0,+ };if !exists {- rust_toolchain::linker()?;+ match target {+ // The headless build links none of the sound or controller libraries: it needs+ // only a C compiler and the C library's headers ([`rust_toolchain::linker_server`]).+ Target::Client => rust_toolchain::linker()?,+ Target::Server => rust_toolchain::linker_server()?,+ }let rust = rust_toolchain::install(|f| progress(Step::Rust(f)))?;- let tool = tool(&rust, &mixins, progress)?;+ let needs_mixins = mods.iter().any(|m| m.mixins_content);progress(Step::Source(revision.clone()));let source = source(&revision)?;- progress(Step::Mixins);// `root()` is already the form horizon-mixins and MinGW take: resolved (no link, which// it refuses) and, on Windows, ASCII (which they can't read past), both by build_dir.let real = root();@@@ -1518,26 -1453,17 +1631,28 @@@let stage = real.join("stage");sync(&fresh, &stage)?;let _ = fs::remove_dir_all(&fresh);- if crates::any(&stage) {+ if crates::any(&stage) || has_api {progress(Step::Crates);- lock_crates(&rust, &source, &stage)?;+ lock_crates(&rust, &source, &stage, &mods)?;}- let target = real.join("target");+ let target_dir = real.join("target");// A revision without `[profile.fast]` builds with `release`: the build says so.- let profile = profile_of(&stage, profile);+ let compiled = profile_of(&stage, profile);+ built.profile = compiled;let (mut crates, mut total, mut name) = (0, None, String::new());run(- compile(&rust, &stage, target, &target_dir, compiled),+ compile(+ &rust,+ &stage,- &target,- profile,++ target,++ &target_dir,++ compiled,+ if has_api {+ api::PACKAGE+ } else {+ "horizon-client"+ },+ ),"Compiling the game",|line| {for event in parse_cargo(line) {@@@ -1738,14 -1828,23 +2017,23 @@@ mod tests"native-mods.json","native-data",] {- assert!(!carried_over(OsStr::new(own)), "{own}");+ assert!(!carried_over(OsStr::new(own), Target::Client), "{own}");}for kept in ["horizon-ctl", "resources", "LICENSE"] {- assert!(carried_over(OsStr::new(kept)), "{kept}");+ assert!(carried_over(OsStr::new(kept), Target::Client), "{kept}");}+ // A server build keeps neither the game's own binary nor a stale `horizon-engine` the+ // base shipped, which would run unmodded beside the built one.+ let engine = Target::Server.binary();+ assert!(+ !carried_over(OsStr::new(&engine), Target::Server),+ "{engine}"+ );+ assert!(!carried_over(OsStr::new(backend::CLIENT), Target::Server));+ assert!(carried_over(OsStr::new("resources"), Target::Server));}- fn dir(name: &str) -> PathBuf {+ pub(super) fn dir(name: &str) -> PathBuf {let d = std::env::temp_dir().join(format!("horizon-native-{name}-{}", std::process::id()));let _ = fs::remove_dir_all(&d);fs::create_dir_all(&d).unwrap();@@@ -2240,42 -2286,6 +2536,51 @@@assert_ne!(first, key(A));}+ #[test]+ fn api_target_is_neither_copied_nor_hashed() {+ let d = dir("api-target");+ fs::create_dir_all(d.join("engine/target/debug")).unwrap();+ fs::create_dir_all(d.join("other/target")).unwrap();+ fs::create_dir_all(d.join("engine/empty")).unwrap();+ fs::write(+ d.join(MANIFEST),+ "[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n",+ )+ .unwrap();+ fs::write(+ d.join("engine/Cargo.toml"),+ "[package]\nname = 'example'\nversion = '0.1.0'\n",+ )+ .unwrap();+ fs::write(d.join("engine/target/debug/output"), "one").unwrap();+ fs::write(d.join("other/target/keep"), "keep").unwrap();+ let bundle = bundle(&d, None).unwrap();- let key = || version_for(A, B, Profile::Fast, std::slice::from_ref(&bundle)).unwrap();++ let key = || {++ version_for(++ A,++ B,++ Profile::Fast,++ Target::Client,++ std::slice::from_ref(&bundle),++ )++ .unwrap()++ };+ let first = key();+ let hash = mod_hash(&bundle).unwrap();+ let digest = source_digest(&bundle);+ fs::write(d.join("engine/target/debug/output"), "two").unwrap();+ assert_eq!(first, key());+ assert_eq!(hash, mod_hash(&bundle).unwrap());+ assert_eq!(digest, source_digest(&bundle));+ let dest = dir("api-target-copy");+ copy_bundle(&bundle, &dest).unwrap();+ assert!(!dest.join("engine/target").exists());+ assert!(dest.join("engine/empty").is_dir());+ assert!(dest.join("other/target/keep").is_file());+ fs::write(d.join("engine/Cargo.toml"), "changed").unwrap();+ assert_ne!(first, key());+ }+/// The test bundle (`tests/fixtures/native-crate-demo`): its crate's sources and data, and its/// own data folder, are all in the build's key.#[test]@@@ -2308,10 -2319,245 +2614,246 @@@let d = dir("profile-key");write_bundle(&d, "hello", "fn hook() {}");let found = bundles(&d).unwrap();- let fast = version_for(A, B, Profile::Fast, &found).unwrap();- let release = version_for(A, B, Profile::Release, &found).unwrap();+ let fast = version_for(A, B, Profile::Fast, Target::Client, &found).unwrap();+ let release = version_for(A, B, Profile::Release, Target::Client, &found).unwrap();assert_ne!(fast, release);- assert_eq!(fast, version_for(A, B, Profile::Fast, &found).unwrap());+ assert_eq!(+ fast,+ version_for(A, B, Profile::Fast, Target::Client, &found).unwrap()+ );+ }++ /// The server build (docs/server.md): compiled headless off the same source, with its own+ /// key, and the game build's flags unchanged.+ #[test]+ fn a_server_build_compiles_headless_with_its_own_key() {+ let d = dir("server-key");+ write_bundle(&d, "hello", "fn hook() {}");+ let found = bundles(&d).unwrap();+ let key = |target: Target| version_for(A, B, Profile::Fast, target, &found).unwrap();+ assert_ne!(+ key(Target::Client),+ key(Target::Server),+ "the two targets never stand in for each other"+ );+ assert_eq!(key(Target::Server), key(Target::Server));+ assert_ne!(+ key(Target::Server),+ version_for(A, B, Profile::Release, Target::Server, &found).unwrap(),+ "the profile is still in the server key"+ );+ let rust = Toolchain {+ dir: PathBuf::from("/rust/1.99.1-x"),+ };+ let flags = |stage: &Path, target: Target| {+ compile(+ &rust,+ stage,+ target,+ Path::new("/native/target"),+ Profile::Fast,++ "horizon-client",+ )+ .get_args()+ .map(|a| a.to_string_lossy().into_owned())+ .collect::<Vec<String>>()+ };+ let server = flags(&d, Target::Server);+ assert!(server.contains(&"--no-default-features".into()));+ assert!(+ !server.iter().any(|a| a.starts_with("--features")),+ "no feature the source doesn't have"+ );+ let client = flags(&d, Target::Client);+ assert!(!client.contains(&"--no-default-features".into()));+ // A source with the `mods` feature keeps it in both builds.+ fs::create_dir_all(d.join("crates/horizon-client")).unwrap();+ fs::write(+ d.join("crates/horizon-client/Cargo.toml"),+ "[features]\nmods = []\n",+ )+ .unwrap();+ for target in [Target::Client, Target::Server] {+ let args = flags(&d, target);+ assert!(+ args.windows(2)+ .any(|w| w == ["--features", FEATURES].map(String::from)),+ "{:?}: the mods feature stays on",+ target+ );+ }+ }++ /// A record (`native-mods.json`) says what it compiles; one from before targets were+ /// recorded is a client build, so it still reads ([`about`]).+ #[test]+ fn a_builds_record_names_its_target_and_older_ones_still_read() {+ let d = dir("about-target");+ let record = |target: Option<&str>| {+ let json = match target {+ Some(target) => {+ format!(r#"{{"base":"v2026.10.13","horizon":"{A}","target":"{target}"}}"#)+ }+ None => format!(r#"{{"base":"v2026.10.13","horizon":"{A}"}}"#),+ };+ fs::write(d.join("native-mods.json"), json).unwrap();+ about_in(&d).unwrap()+ };+ assert_eq!(+ record(None).target,+ Target::Client,+ "a build from before targets"+ );+ assert_eq!(record(Some("client")).target, Target::Client);+ assert_eq!(record(Some("server")).target, Target::Server);+ assert_eq!(record(Some("anything-else")).target, Target::Client);+ assert_eq!(record(None).horizon, A);+ }++ /// The export ([`build_server`]): a standalone runtime folder with the engine, the mods'+ /// data and the build's record, engine still executable, and nothing of the player's+ /// overwritten.+ #[test]+ fn an_exported_server_folder_keeps_its_files_and_overwrites_nothing() {+ let built = dir("export-built");+ fs::write(built.join(Target::Server.binary()), b"engine").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(+ built.join(Target::Server.binary()),+ std::fs::Permissions::from_mode(0o755),+ )+ .unwrap();+ }+ fs::create_dir_all(built.join("native-data/bake")).unwrap();+ fs::write(built.join("native-data/bake/table.bin"), b"data").unwrap();+ fs::create_dir_all(built.join("resources")).unwrap();+ fs::write(built.join("resources/lang.json"), b"{}").unwrap();+ let out = dir("export-out");+ let output = out.join("server");+ export(&built, &output).unwrap();+ assert_eq!(+ fs::read(output.join(Target::Server.binary())).unwrap(),+ b"engine"+ );+ assert_eq!(+ fs::read(output.join("native-data/bake/table.bin")).unwrap(),+ b"data"+ );+ assert_eq!(fs::read(output.join("resources/lang.json")).unwrap(), b"{}");+ assert_eq!(+ fs::read_dir(&out).unwrap().flatten().count(),+ 1,+ "no staging folder left beside it"+ );+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = fs::metadata(output.join(Target::Server.binary()))+ .unwrap()+ .permissions()+ .mode();+ assert_eq!(mode & 0o111, 0o111, "the engine stays executable");+ }+ // A folder already there is refused, and its contents are left alone.+ let taken = dir("export-taken");+ fs::write(taken.join("keep.txt"), b"mine").unwrap();+ let err = export(&built, &taken).unwrap_err();+ assert!(err.contains("already exists"), "{err}");+ assert_eq!(fs::read(taken.join("keep.txt")).unwrap(), b"mine");+ let failed = out.join("failed");+ assert!(export(&out.join("missing-source"), &failed).is_err());+ assert!(!failed.exists());+ assert_eq!(fs::read_dir(&out).unwrap().flatten().count(), 1);+ }++ #[test]+ fn server_install_is_not_playable_and_export_survives_cache_removal() {+ let base = "native-test-server-base";+ let version = "native-test-server-cache";+ let source = backend::version_dir(base);+ fs::create_dir_all(source.join(".local/horizon-client/26.3")).unwrap();+ fs::write(+ source.join(".local/horizon-client/26.3/facts.json"),+ b"facts",+ )+ .unwrap();+ fs::write(source.join(Target::Server.binary()), b"unmodded").unwrap();+ let binary = dir("server-install").join("built");+ fs::write(&binary, b"modded").unwrap();+ install(+ base,+ version,+ Target::Server,+ &binary,+ &serde_json::json!({"target":"server"}),+ |d| {+ fs::create_dir_all(d.join("native-data")).unwrap();+ fs::write(d.join("native-data/test"), b"baked").unwrap();+ Ok(())+ },+ )+ .unwrap();+ assert!(!backend::installed().contains(&version.to_string()));+ let cached = Target::Server.directory(version);+ let output = dir("server-independent").join("export");+ export(&cached, &output).unwrap();+ fs::remove_dir_all(cached).unwrap();+ assert_eq!(+ fs::read(output.join(Target::Server.binary())).unwrap(),+ b"modded"+ );+ assert_eq!(fs::read(output.join("native-data/test")).unwrap(), b"baked");+ assert_eq!(+ fs::read(output.join(".local/horizon-client/26.3/facts.json")).unwrap(),+ b"facts"+ );+ assert!(output.join("native-mods.json").is_file());+ let _ = fs::remove_dir_all(source);+ }++ /// The export's own gate: an output that already exists is refused before anything is+ /// downloaded or compiled (a base that isn't installed would refuse the build otherwise),+ /// and no instance is edited or version selected.+ #[test]+ fn a_server_build_refuses_an_existing_output_before_building() {+ let output = dir("server-output");+ let folder = dir("server-mods");+ write_bundle(&folder, "hello", "fn hook() {}");+ let instances_before = instances::list();+ let selected_before = backend::Settings::load().selected;+ let err = build_server(+ "v0.0.0-not-installed",+ &folder,+ &output,+ true,+ Profile::Fast,+ |_| {},+ )+ .unwrap_err();+ assert!(err.contains("already exists"), "{err}");+ let managed = root().join("forbidden-export");+ let err = build_server(+ "v0.0.0-not-installed",+ &folder,+ &managed,+ true,+ Profile::Fast,+ |_| {},+ )+ .unwrap_err();+ assert!(+ err.contains("outside the launcher's managed folders"),+ "{err}"+ );+ assert!(!managed.exists());+ assert_eq!(instances::list(), instances_before, "no instance is edited");+ assert_eq!(+ backend::Settings::load().selected,+ selected_before,+ "no version is selected"+ );}#[test]@@@ -2539,9 -2785,9 +3081,10 @@@let cmd = compile(&rust,&stage,+ Target::Client,Path::new("/native/target"),Profile::Fast,+ "horizon-client",);let args: Vec<String> = cmd.get_args()@@@ -2570,9 -2816,9 +3113,10 @@@let cmd = compile(&rust,&stage,+ Target::Client,Path::new("/native/target"),Profile::Fast,+ "horizon-client",);let args: Vec<_> = cmd.get_args().collect();assert_eq!(args[1], "--config");@@@ -2602,9 -2848,9 +3146,10 @@@let cmd = compile(&rust,&d,+ Target::Client,Path::new("/native/target"),Profile::Fast,+ "horizon-client",);let args: Vec<_> = cmd.get_args().collect();assert!(args.windows(2).any(|w| w == ["--profile", "fast"]));diff --cc launcher/src/native_mods/api.rsindex 36dd0631d,000000000..f20f6f523mode 100644,000000..100644--- a/launcher/src/native_mods/api.rs+++ b/launcher/src/native_mods/api.rs@@@ -1,376 -1,0 +1,410 @@@+//! The launcher's generated executable for trait mods.+use super::{Bundle, MANIFEST};+use std::fs;+use std::path::Path;++/// Match horizon-mixins crate IDs before using them as folder names.+pub(super) fn valid_id(id: &str) -> bool {+ !id.is_empty()+ && id.len() <= 100+ && id+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')+}++fn read(path: &Path) -> Result<toml::Table, String> {+ let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;+ text.parse().map_err(|e| format!("{}: {e}", path.display()))+}++fn write(path: &Path, value: &toml::Table) -> Result<(), String> {+ let text = toml::to_string(value).map_err(|e| format!("{}: {e}", path.display()))?;+ fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))+}++/// Remove launcher-only tables from the incoming copy before horizon-mixins reads it.+pub(super) fn strip(bundle: &Bundle) -> Result<(), String> {+ let path = bundle.dir.join(MANIFEST);+ let mut manifest = read(&path)?;+ let api = manifest.remove("api");+ let dependencies = manifest.remove("dependencies");+ if api.is_some() || dependencies.is_some() {+ write(&path, &manifest)?;+ }+ Ok(())+}++/// Read and validate the trait package folder at the manifest boundary.+pub(super) fn folder(dir: &Path, table: &toml::Value) -> Result<String, String> {+ let manifest = dir.join(MANIFEST);+ if !table+ .as_table()+ .is_some_and(|t| t.len() == 1 && t.contains_key("path"))+ {+ return Err(format!("{}: [api] accepts only path", manifest.display()));+ }+ let folder = table+ .get("path")+ .and_then(toml::Value::as_str)+ .ok_or_else(|| format!("{}: [api] needs a path", manifest.display()))?;+ let relative = Path::new(folder);+ // An absolute path would bypass the incoming copy when joined later.+ if relative.is_absolute() {+ return Err(format!(+ "{}: invalid [api] path {folder:?}",+ manifest.display()+ ));+ }+ let source = dir.join(relative);+ let root = dir+ .canonicalize()+ .map_err(|e| format!("{}: {e}", dir.display()))?;+ let resolved = source+ .canonicalize()+ .map_err(|e| format!("{}: {e}", source.display()))?;+ if !resolved.starts_with(&root) || !resolved.join("Cargo.toml").is_file() {+ return Err(format!(+ "{}: [api] path must be a folder in the bundle with Cargo.toml",+ manifest.display()+ ));+ }+ Ok(folder.to_owned())+}++pub(super) const PACKAGE: &str = "horizon-native-game";+/// Where the generated executable's package is staged, in the workspace.+const GAME: &str = "crates/native-game";++fn path_dep(path: &str) -> toml::Value {+ toml::Value::Table(toml::Table::from_iter([("path".into(), path.into())]))+}++fn main_rs(count: usize) -> String {+ let entries = (0..count)+ .map(|i| format!(" mod_{i}::hooks(),\n"))+ .collect::<String>();+ // Mirrors crates/horizon-client/src/main.rs, with trait mods passed to main_with.+ format!(+ r#"//! Generated by the launcher.+#![forbid(unsafe_code)]++#[global_allocator]+static ALLOCATOR: horizon_threads::Allocator = horizon_threads::Allocator;++static MOD_API_LEVEL: [u8; horizon_mods::api_level::MARK.len()] = horizon_mods::api_level::MARK;++fn main() {{+ std::hint::black_box(&MOD_API_LEVEL);+ let mods: horizon_client::mod_api::Mods = vec![+{entries} ].into();+ horizon_client::entry::main_with(mods);+}}+"#+ )+}++/// API objects in the same order as the generated executable's mod list.+pub(super) fn with_api(mods: &[Bundle]) -> impl Iterator<Item = &Bundle> {+ mods.iter().filter(|m| m.api.is_some())+}++/// Add API packages and the generated executable to the fresh staged workspace.+pub(super) fn stage(+ stage: &Path,+ bundles: &[Bundle],+ declared: &[Vec<super::dependencies::Dependency>],+ resolution: &super::dependencies::Resolution,+) -> Result<bool, String> {+ let mods: Vec<_> = resolution+ .order+ .iter()+ .map(|&i| (i, &bundles[i]))+ .filter(|(_, b)| b.api.is_some())+ .collect();+ let mut packages = std::collections::HashMap::new();+ for (_, bundle) in &mods {+ let path = bundle+ .dir+ .join(bundle.api.as_ref().expect("filtered"))+ .join("Cargo.toml");+ let manifest = read(&path)?;+ let name = manifest+ .get("package")+ .and_then(|p| p.get("name"))+ .and_then(toml::Value::as_str)+ .ok_or_else(|| format!("{}: missing package name", path.display()))?;+ packages.insert(bundle.id.as_str(), name.to_owned());+ }+ if mods.is_empty() {+ return Ok(false);+ }+ let mut deps = toml::Table::new();+ for name in ["horizon-client", "horizon-threads", "horizon-mods"] {+ deps.insert(name.into(), path_dep(&format!("../{name}")));+ }++ // horizon-client's defaults (sound, controllers) are this package's, so a server build's++ // `--no-default-features` turns them off here too.++ if let Some(client) = deps++ .get_mut("horizon-client")++ .and_then(toml::Value::as_table_mut)++ {++ client.insert("default-features".into(), false.into());++ }+ let mut members = Vec::new();+ for (i, (index, bundle)) in mods.iter().enumerate() {+ let relative = format!("native-api/{}", bundle.id);+ let dest = stage.join(&relative);+ let source = bundle.dir.join(bundle.api.as_ref().expect("filtered"));+ super::sync(&source, &dest)?;+ let path = dest.join("Cargo.toml");+ let mut manifest = read(&path)?;+ let package = manifest+ .get("package")+ .and_then(|p| p.get("name"))+ .and_then(toml::Value::as_str)+ .ok_or_else(|| format!("{}: missing package name", path.display()))?+ .to_owned();+ let dependencies = manifest+ .get_mut("dependencies")+ .and_then(toml::Value::as_table_mut)+ .ok_or_else(|| format!("{}: missing horizon-client dependency", path.display()))?;+ let dependency = dependencies+ .iter_mut()+ .find(|(key, value)| {+ *key == "horizon-client"+ || value.get("package").and_then(toml::Value::as_str) == Some("horizon-client")+ })+ .ok_or_else(|| format!("{}: missing horizon-client dependency", path.display()))?+ .1;+ let mut rewritten = path_dep("../../crates/horizon-client");+ if let (Some(old), Some(new)) = (dependency.as_table(), rewritten.as_table_mut()) {+ // A renamed dependency also needs its package name.+ for key in ["package", "features", "default-features"] {+ if let Some(value) = old.get(key) {+ new.insert(key.into(), value.clone());+ }+ }+ }++ // The game's features are the generated package's to choose (a server build turns its++ // defaults off), so no mod turns them back on.++ if let Some(new) = rewritten.as_table_mut() {++ new.insert("default-features".into(), false.into());++ }+ *dependency = rewritten;+ let targets: Vec<_> = declared[*index]+ .iter()+ .map(|dependency| super::dependencies::Package {+ dependency,+ package: packages.get(dependency.id.as_str()).map(String::as_str),+ })+ .collect();+ let enabled = super::dependencies::rewrite(&bundle.id, &mut manifest, &targets)+ .map_err(|e| e.to_string())?;+ write(&path, &manifest)?;+ let mut dep = toml::Table::new();+ dep.insert("path".into(), format!("../../{relative}").into());+ dep.insert("package".into(), package.into());+ if !enabled.is_empty() {+ dep.insert(+ "features".into(),+ toml::Value::Array(enabled.into_iter().map(toml::Value::String).collect()),+ );+ }+ deps.insert(format!("mod_{i}"), toml::Value::Table(dep));+ members.push(relative);+ }+ // Beside horizon-client, so its build script (the Windows stack size and icon, for the+ // `horizon-client` binary this package owns now) finds `packaging/` where it looks.+ let game = stage.join(GAME);+ fs::create_dir_all(game.join("src")).map_err(|e| e.to_string())?;+ let mut manifest = toml::Table::new();+ manifest.insert(+ "package".into(),+ toml::Value::Table(toml::Table::from_iter([+ ("name".into(), PACKAGE.into()),+ ("version".into(), "0.1.0".into()),+ ("edition".into(), "2024".into()),+ ("publish".into(), false.into()),+ ("build".into(), "../horizon-client/build.rs".into()),+ ])),+ );+ let windows = toml::Table::from_iter([(+ "build-dependencies".into(),+ toml::Value::Table(toml::Table::from_iter([(+ "winresource".into(),+ "0.1".into(),+ )])),+ )]);+ manifest.insert(+ "target".into(),+ toml::Value::Table(toml::Table::from_iter([(+ "cfg(windows)".into(),+ toml::Value::Table(windows),+ )])),+ );+ manifest.insert(+ "bin".into(),+ toml::Value::Array(vec![toml::Value::Table(toml::Table::from_iter([+ ("name".into(), "horizon-client".into()),+ ("path".into(), "src/main.rs".into()),+ ]))]),+ );+ manifest.insert("dependencies".into(), toml::Value::Table(deps));++ manifest.insert(++ "features".into(),++ toml::Value::Table(toml::Table::from_iter([(++ "default".into(),++ toml::Value::Array(vec!["horizon-client/default".into()]),++ )])),++ );+ write(&game.join("Cargo.toml"), &manifest)?;+ fs::write(game.join("src/main.rs"), main_rs(mods.len())).map_err(|e| e.to_string())?;+ let root = stage.join("Cargo.toml");+ let mut workspace = read(&root)?;+ let list = workspace+ .get_mut("workspace")+ .and_then(|w| w.get_mut("members"))+ .and_then(toml::Value::as_array_mut)+ .ok_or("workspace has no members")?;+ members.push(GAME.into());+ list.extend(members.into_iter().map(toml::Value::String));+ write(&root, &workspace)?;+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixture(manifest: &str) -> std::path::PathBuf {+ let name = std::thread::current().name().unwrap().replace(':', "-");+ let dir = super::super::tests::dir(&name);+ fs::create_dir_all(dir.join("engine/src")).unwrap();+ fs::write(dir.join(MANIFEST), manifest).unwrap();+ fs::write(dir.join("engine/Cargo.toml"), "[package]\nname = 'example-mod'\nversion = '0.1.0'\nedition = '2024'\n[dependencies]\nhorizon-client = '0.1'\n").unwrap();+ fs::write(dir.join("engine/src/lib.rs"), "").unwrap();+ dir+ }++ #[test]+ fn validates_the_api_folder() {+ for (path, valid) in [+ ("engine", true),+ ("missing", false),+ ("../engine", false),+ ("/engine", false),+ ] {+ let dir = fixture(&format!(+ "[mod]\nid = 'example'\nversion = '1'\n[api]\npath = {path:?}\n"+ ));+ assert_eq!(super::super::bundle(&dir, None).is_ok(), valid, "{path}");+ fs::remove_dir_all(dir).unwrap();+ }+ }++ #[test]+ fn rejects_an_entry_override() {+ let dir = fixture(+ "[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\nentry = 'other'\n",+ );+ assert!(super::super::bundle(&dir, None)+ .unwrap_err()+ .contains("accepts only path"));+ fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn removes_only_the_api_table_for_mixins() {+ let dir = fixture(+ "[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n[dependencies]\nbase = '^1'\n[[injection]]\nid = 'test'\n",+ );+ let bundle = super::super::bundle(&dir, None).unwrap();+ assert!(bundle.mixins_content);+ strip(&bundle).unwrap();+ let value = read(&dir.join(MANIFEST)).unwrap();+ assert!(!value.contains_key("api"));+ assert!(!value.contains_key("dependencies"));+ assert!(value.contains_key("injection"));+ fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn generated_main_keeps_mod_order() {+ for count in 0..=2 {+ let text = main_rs(count);+ assert!(text.contains("entry::main_with(mods)"));+ assert_eq!(text.matches("::hooks()").count(), count);+ if count == 2 {+ assert!(+ text.find("mod_0::hooks()").unwrap() < text.find("mod_1::hooks()").unwrap()+ );+ }+ }+ }++ #[test]+ fn stages_api_without_a_dependency_cycle() {+ let dir = fixture("[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n");+ let bundle = super::super::bundle(&dir, None).unwrap();+ let stage_dir = dir.join("workspace");+ fs::create_dir_all(&stage_dir).unwrap();+ fs::write(stage_dir.join("Cargo.toml"), "[workspace]\nmembers = []\n").unwrap();+ let resolution = super::super::dependencies::Resolution { order: vec![0] };+ assert!(stage(&stage_dir, &[bundle], &[vec![]], &resolution).unwrap());+ let root = read(&stage_dir.join("Cargo.toml")).unwrap();+ let members = root["workspace"]["members"].as_array().unwrap();+ assert!(members+ .iter()+ .any(|v| v.as_str() == Some("native-api/example")));+ assert!(members.iter().any(|v| v.as_str() == Some(GAME)));+ let engine = read(&stage_dir.join("native-api/example/Cargo.toml")).unwrap();+ assert_eq!(+ engine["dependencies"]["horizon-client"]["path"].as_str(),+ Some("../../crates/horizon-client")+ );+ let game = read(&stage_dir.join(GAME).join("Cargo.toml")).unwrap();+ assert_eq!(+ game["dependencies"]["mod_0"]["package"].as_str(),+ Some("example-mod")+ );+ assert_eq!(+ game["dependencies"]["mod_0"]["path"].as_str(),+ Some("../../native-api/example")+ );+ assert_eq!(+ game["package"]["build"].as_str(),+ Some("../horizon-client/build.rs")+ );+ assert!(stage_dir+ .join(GAME)+ .join(+ game["dependencies"]["horizon-client"]["path"]+ .as_str()+ .unwrap()+ )+ .ends_with("crates/native-game/../horizon-client"));++ // The game's default features are the generated package's alone, so a server build's++ // `--no-default-features` reaches horizon-client.++ assert_eq!(++ engine["dependencies"]["horizon-client"]["default-features"].as_bool(),++ Some(false)++ );++ assert_eq!(++ game["dependencies"]["horizon-client"]["default-features"].as_bool(),++ Some(false)++ );++ assert_eq!(++ game["features"]["default"][0].as_str(),++ Some("horizon-client/default")++ );+ fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn api_only_skips_mixins() {+ let dir = fixture("[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n");+ let bundle = super::super::bundle(&dir, None).unwrap();+ assert!(!bundle.mixins_content);+ fs::remove_dir_all(dir).unwrap();+ }+}diff --cc launcher/src/native_mods/inject.rsindex dcb9ef3c1,000000000..9362ad1ebmode 100644,000000..100644--- a/launcher/src/native_mods/inject.rs+++ b/launcher/src/native_mods/inject.rs@@@ -1,438 -1,0 +1,440 @@@+//! Trait-backed HEAD injections, generated in the incoming copy and staged game.+use super::{api, Bundle, MANIFEST};+use quote::quote;+use std::{+ collections::{HashMap, HashSet},+ fs,+ path::Path,+};++/// A trait declaration to add to the staged game after horizon-mixins has run.+pub(super) struct Injection {+ name: syn::Ident,+ parameters: Vec<(syn::Ident, syn::Type)>,+ cancellable: bool,+}++/// Replace trait injections with ordinary mixin helpers, leaving ordinary injections unchanged.+pub(super) fn prepare(mods: &[Bundle], source: &Path) -> Result<Vec<Injection>, String> {+ let mut result = Vec::new();+ let mut names = HashSet::new();+ let owners: HashMap<_, _> = api::with_api(mods)+ .enumerate()+ .map(|(i, b)| (b.id.as_str(), i))+ .collect();+ // These are the copied bundles under mods.incoming, never the player's originals.+ for bundle in mods {+ api::strip(bundle)?;+ let path = bundle.dir.join(MANIFEST);+ let text = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ let mut manifest: toml::Table = text+ .parse()+ .map_err(|e| format!("{}: {e}", path.display()))?;+ let entries = manifest+ .get_mut("injection")+ .and_then(toml::Value::as_array_mut);+ if let Some(entries) = entries {+ for (index, entry) in entries.iter_mut().enumerate() {+ let table = entry.as_table_mut().ok_or("injection must be a table")?;+ let Some(method) = table.remove("trait_method") else {+ continue;+ };+ if bundle.api.is_none() {+ return Err(format!("{}: trait_method requires [api]", path.display()));+ }+ let target = if let Some(hook) = table.get("hook").and_then(toml::Value::as_str) {+ let catalog = source.join("native-hooks.json");+ let text = fs::read_to_string(&catalog)+ .map_err(|e| format!("{}: {e}", catalog.display()))?;+ let catalog: serde_json::Value =+ serde_json::from_str(&text).map_err(|e| e.to_string())?;+ catalog["hooks"]+ .as_array()+ .and_then(|hooks| hooks.iter().find(|h| h["name"].as_str() == Some(hook)))+ .and_then(|h| h["target"].as_str())+ .ok_or_else(|| format!("unknown catalog hook {hook}"))?+ .to_owned()+ } else {+ table+ .get("target")+ .and_then(toml::Value::as_str)+ .ok_or("trait_method needs a target or catalog hook")?+ .to_owned()+ };+ let target_crate = target.split("::").next().unwrap_or_default();+ if target_crate != "horizon_client" {+ return Err(format!("trait injection target {target:?} is in crate {target_crate:?}; only horizon-client targets are supported"));+ }+ if table.get("kind").and_then(toml::Value::as_str) != Some("HEAD") {+ return Err(format!(+ "{}: trait_method supports only HEAD injections",+ path.display()+ ));+ }+ if table.contains_key("helper") {+ return Err(format!(+ "{}: trait_method cannot also specify helper",+ path.display()+ ));+ }+ let method = method+ .as_str()+ .ok_or("trait_method must be a Rust identifier")?;+ let _: syn::Ident =+ syn::parse_str(method).map_err(|_| "trait_method must be a Rust identifier")?;+ let name = format!("inject_{}_{}", bundle.id.replace('-', "_"), method);+ let ident: syn::Ident =+ syn::parse_str(&name).map_err(|_| "invalid generated trait method")?;+ if !names.insert(name.clone()) {+ return Err(format!("duplicate generated trait method {name}"));+ }+ let cancellable = match table.get("cancellable") {+ None => false,+ Some(v) => v.as_bool().ok_or("cancellable must be a boolean")?,+ };+ let mut parameters = Vec::new();+ let mut seen = HashSet::new();+ if let Some(bindings) = table.get("bindings") {+ for binding in bindings.as_array().ok_or("bindings must be an array")? {+ let binding = binding.as_table().ok_or("binding must be a table")?;+ let name = binding+ .get("name")+ .and_then(toml::Value::as_str)+ .ok_or("binding needs a name")?;+ let ident: syn::Ident =+ syn::parse_str(name).map_err(|_| "invalid binding name")?;+ if !seen.insert(name.to_owned()) {+ return Err(format!("duplicate binding {name}"));+ }+ let ty = binding+ .get("ty")+ .and_then(toml::Value::as_str)+ .ok_or("binding needs a type")?;+ let ty: syn::Type =+ syn::parse_str(ty).map_err(|e| format!("invalid binding type: {e}"))?;+ parameters.push((ident, ty));+ }+ }+ let injection = Injection {+ name: ident,+ parameters,+ cancellable,+ };+ let helper_path = format!("horizon-trait-injection-{index}.rs");+ let helper_file = bundle.dir.join(&helper_path);+ if helper_file.exists() {+ return Err(format!(+ "{} is reserved for generated helpers",+ helper_file.display()+ ));+ }+ fs::write(&helper_file, injection.helper(owners[bundle.id.as_str()]))+ .map_err(|e| e.to_string())?;+ table.insert("helper".into(), helper_path.into());+ result.push(injection);+ }+ }+ fs::write(+ &path,+ toml::to_string(&manifest).map_err(|e| e.to_string())?,+ )+ .map_err(|e| e.to_string())?;+ }+ Ok(result)+}++impl Injection {+ fn helper(&self, owner: usize) -> String {+ let name = &self.name;+ let params = self.parameters.iter().map(|(n, t)| quote!(#n: #t));+ let args = self.parameters.iter().map(|(n, t)| {+ if matches!(t, syn::Type::Reference(r) if r.mutability.is_some()) {+ quote!(&mut *#n)+ } else {+ quote!(#n)+ }+ });+ let call = quote!(owner.#name(#(#args),*));+ // Before the mods are installed (an injection into code `main_with` runs first), or+ // with fewer mods than the build had, the injection does nothing.+ let (output, result, absent) = if self.cancellable {+ (+ quote!(-> core::ops::ControlFlow<()>),+ quote! {+ if #call == crate::mod_api::Flow::Cancel {+ return core::ops::ControlFlow::Break(());+ }+ core::ops::ControlFlow::Continue(())+ },+ quote!(core::ops::ControlFlow::Continue(())),+ )+ } else {+ (quote!(), quote!(#call;), quote!())+ };+ quote! {+ fn horizon_trait_dispatch(#(#params),*) #output {+ let Some(owner) = crate::mod_api::mods().get(#owner) else {+ return #absent;+ };+ #result+ }+ }+ .to_string()+ }++ fn declaration(&self) -> String {+ let name = &self.name;+ let types = self.parameters.iter().map(|(_, ty)| ty);+ let (output, default) = if self.cancellable {+ (quote!(-> Flow), quote!(Flow::Continue))+ } else {+ (quote!(), quote!())+ };+ quote!(fn #name(&self, #(_: #types),*) #output { #default }).to_string()+ }+}++/// Add declarations to the existing generated trait, not its dispatch implementations.+pub(super) fn stage(stage: &Path, injections: &[Injection]) -> Result<(), String> {+ if injections.is_empty() {+ return Ok(());+ }+ let path = stage.join("crates/horizon-client/src/mod_api/generated.rs");+ let source = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ let file = syn::parse_file(&source).map_err(|e| format!("{}: {e}", path.display()))?;+ let hooks = file+ .items+ .iter()+ .find_map(|i| match i {+ syn::Item::Trait(t) if t.ident == "Hooks" => Some(t),+ _ => None,+ })+ .ok_or("generated Hooks trait missing")?;+ for injection in injections {+ if hooks+ .items+ .iter()+ .any(|i| matches!(i, syn::TraitItem::Fn(f) if f.sig.ident == injection.name))+ {+ return Err(format!("trait method {} already exists", injection.name));+ }+ }+ let marker = "pub trait Hooks: Send + Sync {\n";+ if source.matches(marker).count() != 1 {+ return Err("generated Hooks marker missing or ambiguous".into());+ }+ let declarations = injections+ .iter()+ .map(Injection::declaration)+ .collect::<String>();+ fs::write(+ path,+ source.replacen(marker, &format!("{marker}{declarations}"), 1),+ )+ .map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixture(name: &str, injection: &str) -> (std::path::PathBuf, Bundle) {+ let root =+ std::env::temp_dir().join(format!("horizon-inject-{}-{name}", std::process::id()));+ let _ = fs::remove_dir_all(&root);+ fs::create_dir_all(root.join("engine/src")).unwrap();+ fs::write(+ root.join("engine/Cargo.toml"),+ "[package]\nname = 'mod-example'\nversion = '1.0.0'\n",+ )+ .unwrap();+ fs::write(root.join("engine/src/lib.rs"), "").unwrap();+ fs::write(+ root.join(MANIFEST),+ format!("[mod]\nid = 'example'\nversion = '1'\n[api]\npath = 'engine'\n{injection}"),+ )+ .unwrap();+ let bundle = super::super::bundle(&root, None).unwrap();+ (root, bundle)+ }++ #[test]+ fn owner_dispatch_and_cancel_are_generated_from_bindings() {+ let (root, bundle) = fixture("cancel", "[[injection]]\nid = 'hook'\ntarget = 'horizon_client::game::tick'\nkind = 'HEAD'\ntrait_method = 'tick'\ncancellable = true\nbindings = [{ name = 'amount', ty = '&mut i32', value = '&mut *amount' }]\n");+ let injections = prepare(&[bundle], &root).unwrap();+ let helper = fs::read_to_string(root.join("horizon-trait-injection-0.rs")).unwrap();+ let manifest = fs::read_to_string(root.join(MANIFEST)).unwrap();+ assert!(!manifest.contains("trait_method"));+ assert!(!manifest.contains("[api]"));+ let stage_dir = root.join("stage/crates/horizon-client/src/mod_api");+ fs::create_dir_all(&stage_dir).unwrap();+ fs::write(+ stage_dir.join("generated.rs"),+ "pub trait Hooks: Send + Sync {\n}\n",+ )+ .unwrap();+ stage(&root.join("stage"), &injections).unwrap();+ let output = fs::read_to_string(stage_dir.join("generated.rs")).unwrap();+ assert!(syn::parse_file(&output).is_ok());+ let program = format!(+ r#"+ mod mod_api {{+ use std::sync::OnceLock;+ #[derive(PartialEq)] pub enum Flow {{ Continue, Cancel }}+ {output}+ struct Owner;+ impl Hooks for Owner {{+ fn inject_example_tick(&self, amount: &mut i32) -> Flow {{+ *amount = 42;+ Flow::Cancel+ }}+ }}+ struct Other;+ impl Hooks for Other {{+ fn inject_example_tick(&self, _: &mut i32) -> Flow {{ panic!("wrong owner") }}+ }}+ pub fn mods() -> &'static [Box<dyn Hooks>] {{+ static MODS: OnceLock<Vec<Box<dyn Hooks>>> = OnceLock::new();+ MODS.get_or_init(|| vec![Box::new(Owner), Box::new(Other)])+ }}+ }}+ {helper}+ fn main() {{+ let mut value = 1;+ assert!(matches!(horizon_trait_dispatch(&mut value), core::ops::ControlFlow::Break(())));+ assert_eq!(value, 42);+ }}+ "#+ );+ let source = root.join("proof.rs");+ let binary = root.join(format!("proof-bin{}", std::env::consts::EXE_SUFFIX));+ fs::write(&source, program).unwrap();+ let compiler = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());+ let compiled = std::process::Command::new(compiler)+ .args(["--edition", "2024"])+ .arg(&source)+ .arg("-o")+ .arg(&binary)+ .output()+ .unwrap();+ assert!(+ compiled.status.success(),+ "{}",+ String::from_utf8_lossy(&compiled.stderr)+ );+ assert!(std::process::Command::new(binary)+ .status()+ .unwrap()+ .success());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn trait_edits_do_not_invalidate_mixin_cache() {+ let (root, bundle) = fixture("cache", "[[injection]]\nid = 'hook'\ntarget = 'horizon_client::game::tick'\nkind = 'HEAD'\ntrait_method = 'tick'\n");+ let key = || {+ super::super::inject_cache::key(+ "revision",+ "mixins",+ super::super::Profile::Fast,+ std::slice::from_ref(&bundle),+ )+ .unwrap()+ };+ let before = key();+ fs::write(root.join("engine/src/lib.rs"), "// one line edit").unwrap();+ assert_eq!(before, key());+ fs::write(root.join("other.rs"), "// mixin input").unwrap();+ assert_ne!(before, key());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn mixin_inputs_inside_api_are_not_excluded_from_cache() {+ let (root, bundle) = fixture("api-helper", "[[injection]]\nid = 'hook'\ntarget = 'horizon_client::game::tick'\nkind = 'HEAD'\nhelper = 'engine/src/lib.rs'\n");+ let key = || {+ super::super::inject_cache::key(+ "revision",+ "mixins",+ super::super::Profile::Fast,+ std::slice::from_ref(&bundle),+ )+ .unwrap()+ };+ let before = key();+ fs::write(root.join("engine/src/lib.rs"), "fn changed() {}\n").unwrap();+ assert_ne!(before, key());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn mixin_crate_containing_api_is_not_excluded_from_cache() {+ let (root, bundle) = fixture("api-parent", "[[crate]]\nid = 'whole_bundle'\npath = '.'\n");+ let key = || {+ super::super::inject_cache::key(+ "revision",+ "mixins",+ super::super::Profile::Fast,+ std::slice::from_ref(&bundle),+ )+ .unwrap()+ };+ let before = key();+ fs::write(root.join("engine/src/lib.rs"), "// changed\n").unwrap();+ assert_ne!(before, key());+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn installed_build_key_tracks_dispatch_order() {+ let (root, first) = fixture("order", "");+ let mut second = first.clone();+ second.id = "second".into();+ let a = super::super::version_for(+ "0123456789012345678901234567890123456789",+ "mixins",+ super::super::Profile::Fast,++ super::super::Target::Client,+ &[first.clone(), second.clone()],+ )+ .unwrap();+ let b = super::super::version_for(+ "0123456789012345678901234567890123456789",+ "mixins",+ super::super::Profile::Fast,++ super::super::Target::Client,+ &[second, first],+ )+ .unwrap();+ assert_ne!(a, b);+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn trait_injections_reject_targets_in_other_crates() {+ let (root, bundle) = fixture("other-crate", "[[injection]]\nid = 'hook'\ntarget = 'horizon_world::loot::load'\nkind = 'HEAD'\ntrait_method = 'load'\n");+ let error = prepare(&[bundle], &root).err().unwrap();+ assert!(error.contains("horizon_world::loot::load") && error.contains("horizon_world"));+ fs::remove_dir_all(root).unwrap();++ let (root, bundle) = fixture("other-catalog", "[[injection]]\nid = 'hook'\nhook = 'loot_table_load'\nkind = 'HEAD'\ntrait_method = 'load'\n");+ fs::write(+ root.join("native-hooks.json"),+ r#"{"hooks":[{"name":"loot_table_load","target":"horizon_world::loot::load"}]}"#,+ )+ .unwrap();+ let error = prepare(&[bundle], &root).err().unwrap();+ assert!(error.contains("horizon_world::loot::load") && error.contains("horizon_world"));+ fs::remove_dir_all(root).unwrap();+ }++ #[test]+ fn unsupported_injection_is_rejected() {+ let (root, bundle) = fixture("return", "[[injection]]\nid = 'hook'\ntarget = 'horizon_client::game::tick'\nkind = 'RETURN'\ntrait_method = 'tick'\n");+ assert!(prepare(&[bundle], &root)+ .err()+ .unwrap()+ .contains("only HEAD"));+ fs::remove_dir_all(root).unwrap();+ }+}