From 00371a7f35c367fcb10b54b3cfe18e3f63065da2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:47:42 +0200 Subject: [PATCH] Run /test as vanilla does in a world without test instances Model TestCommand's release tree (ResourceSelectorArgument patterns included) and its finder, locate, pos, stop and clear outcomes when no test instance block exists. Compare /help's gamerule alternatives as a set: GameRuleCommand registers them in identity-hash order. Co-Authored-By: Claude Opus 5.5 --- .../examples/command_parse_fixture.rs | 1 + crates/horizon-client/src/command/args.rs | 65 ++++++++++++++ .../horizon-client/src/command/tree_extra.rs | 86 +++++++++++++++++-- .../src/command/vanilla_order.rs | 1 - crates/horizon-client/src/game/commands.rs | 1 + .../horizon-client/src/game/commands/extra.rs | 71 +++++++++++++++ tools/command_exec_corpus.py | 15 +++- tools/generate_command_order.py | 4 + tools/test_command_exec_parity.py | 6 ++ 9 files changed, 243 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index ee6519bfc..39d738b7f 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -61,6 +61,7 @@ fn parser_id(ty: &ArgType) -> String { _ => "minecraft:template_rotation".into(), }, ArgType::HexColor => "minecraft:hex_color".into(), + ArgType::ResourceSelector(_) => "minecraft:resource_selector".into(), ArgType::Uuid => "minecraft:uuid".into(), ArgType::GameProfile => "minecraft:game_profile".into(), ArgType::Style => "minecraft:style".into(), diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index d4d4c76ff..436bf6cf4 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -315,6 +315,45 @@ pub enum ArgType { SlotSource, /// ResourceOrIdArgument over a registry: an id or an inline SNBT value. ResourceOrId(&'static str), + /// ResourceSelectorArgument: a `*`/`?` pattern over a registry's ids. + ResourceSelector(&'static str), +} + +/// FilenameUtils.wildcardMatch (case-sensitive) of `*` and `?` patterns. +pub fn wildcard_match(text: &str, pattern: &str) -> bool { + let t: Vec = text.chars().collect(); + let p: Vec = pattern.chars().collect(); + let (mut ti, mut pi) = (0, 0); + let (mut star, mut mark) = (None, 0); + while ti < t.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { + ti += 1; + pi += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == '*' { + pi += 1; + } + pi == p.len() +} +/// ResourceSelectorArgument: the registry ids a pattern selects. +pub fn select_resources<'a>(ids: &'a [String], pattern: &str) -> Vec<&'a String> { + let pattern = if pattern.contains(':') { + pattern.to_owned() + } else { + format!("minecraft:{pattern}") + }; + ids.iter().filter(|id| wildcard_match(id, &pattern)).collect() } /// SlotRanges.SLOTS: every slot range name and its size, in vanilla order. @@ -1409,6 +1448,29 @@ impl ArgType { } Arg::Str(name.to_owned()) } + ArgType::ResourceSelector(registry) => { + let start = reader.cursor; + while reader.can_read() && { + let c = reader.peek(); + is_id_char(c) || c == '*' || c == '?' + } { + reader.skip(); + } + let raw = reader.string[start..reader.cursor].to_owned(); + let pattern = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + if select_resources(reg.ids(registry), &pattern).is_empty() { + return Err(CommandError::tr_at( + "argument.resource_selector.not_found", + &[&pattern, registry], + reader, + )); + } + Arg::Str(pattern) + } ArgType::HexColor => { let text = reader.read_unquoted_string(); if !matches!(text.len(), 3 | 6) { @@ -1803,6 +1865,9 @@ impl ArgType { } ArgType::StrEnum(values, _) => builder.suggest_matching(values.iter().copied()), ArgType::HexColor => builder.suggest_matching(["F00", "FF0000"]), + ArgType::ResourceSelector(registry) => { + suggest_resources(builder, reg.ids(registry), "") + } ArgType::GameProfile => { let players = reg.players.clone(); super::selector::suggest(builder, reg, &|b| { diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-client/src/command/tree_extra.rs index 636aaf0db..a4f0d15ff 100644 --- a/crates/horizon-client/src/command/tree_extra.rs +++ b/crates/horizon-client/src/command/tree_extra.rs @@ -1,7 +1,6 @@ -//! Commands Horizon parses but does not run (multiplayer, profiling and -//! server-only features): `/dialog`, `/kick`, `/posteffect`, `/fetchprofile`, -//! `/spectate`, `/publish`, `/unpublish`, `/waypoint`, `/debug`, `/jfr` and -//! the `/test` root. +//! Commands of the hosted game rather than the world: `/dialog`, `/kick`, +//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`, +//! `/waypoint`, `/debug`, `/jfr` and `/test`. use super::{ Dispatcher, args::ArgType, @@ -126,7 +125,84 @@ pub fn register(d: &mut Dispatcher, root: usize) { d.executes(l, "jfr"); } - // TestCommand (game tests; only its root is modelled) + // TestCommand (release build: no export subcommands) let test = d.literal(root, "test"); d.requires(test, GAMEMASTERS); + let tests = ArgType::ResourceSelector("minecraft:test_instance"); + let int0 = ArgType::Integer { + min: 0, + max: i32::MAX, + }; + let int = ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }; + // numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only + // the first two. + let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| { + let n = d.argument(node, "numberOfTimes", int0.clone()); + d.executes(n, id); + let u = d.argument(n, "untilFailed", ArgType::Bool); + d.executes(u, id); + if build_info { + let r = d.argument(u, "rotationSteps", int.clone()); + d.executes(r, id); + let t = d.argument(r, "testsPerRow", int.clone()); + d.executes(t, id); + } + }; + let run = d.literal(test, "run"); + let t = d.argument(run, "tests", tests.clone()); + d.executes(t, "test.run"); + retry(d, t, "test.run", true); + let multiple = d.literal(test, "runmultiple"); + let t = d.argument(multiple, "tests", tests.clone()); + d.executes(t, "test.run"); + let a = d.argument(t, "amount", int.clone()); + d.executes(a, "test.run"); + for name in ["runthese", "runclosest", "runthat"] { + let l = d.literal(test, name); + d.executes(l, "test.run.found"); + retry(d, l, "test.run.found", false); + } + let failed = d.literal(test, "runfailed"); + d.executes(failed, "test.run.found"); + let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool); + d.executes(only, "test.run.found"); + retry(d, only, "test.run.found", true); + retry(d, failed, "test.run.found", true); + let verify = d.literal(test, "verify"); + let t = d.argument(verify, "tests", tests.clone()); + d.executes(t, "test.verify"); + let locate = d.literal(test, "locate"); + let t = d.argument(locate, "tests", tests); + d.executes(t, "test.locate"); + for name in [ + "resetclosest", + "resetthese", + "resetthat", + "clearthat", + "clearthese", + ] { + let l = d.literal(test, name); + d.executes(l, "test.clear"); + } + let all = d.literal(test, "clearall"); + d.executes(all, "test.clear"); + let r = d.argument(all, "radius", int.clone()); + d.executes(r, "test.clear"); + let stop = d.literal(test, "stop"); + d.executes(stop, "test.stop"); + let pos = d.literal(test, "pos"); + d.executes(pos, "test.pos"); + let var = d.argument(pos, "var", ArgType::Word); + d.executes(var, "test.pos"); + let create = d.literal(test, "create"); + let id = d.argument(create, "id", ArgType::Id("none")); + d.executes(id, "test.create"); + let w = d.argument(id, "width", int.clone()); + d.executes(w, "test.create"); + let h = d.argument(w, "height", int.clone()); + let depth = d.argument(h, "depth", int); + d.executes(depth, "test.create"); } diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-client/src/command/vanilla_order.rs index c5089ee1a..975cc7bf9 100644 --- a/crates/horizon-client/src/command/vanilla_order.rs +++ b/crates/horizon-client/src/command/vanilla_order.rs @@ -11,7 +11,6 @@ pub const ORDER: &[(&str, &[&str])] = &[ ("execute facing", &["entity", "pos"]), ("datapack", &["enable", "disable", "list", "create"]), ("datapack enable name", &["after", "before", "last", "first"]), - ("gamerule", &["spawn_wandering_traders", "minecraft:spawn_wandering_traders", "players_nether_portal_creative_delay", "minecraft:players_nether_portal_creative_delay", "allow_entering_nether_using_portals", "minecraft:allow_entering_nether_using_portals", "players_sleeping_percentage", "minecraft:players_sleeping_percentage", "universal_anger", "minecraft:universal_anger", "locator_bar", "minecraft:locator_bar", "lava_source_conversion", "minecraft:lava_source_conversion", "ender_pearls_vanish_on_death", "minecraft:ender_pearls_vanish_on_death", "mob_griefing", "minecraft:mob_griefing", "spread_vines", "minecraft:spread_vines", "max_command_forks", "minecraft:max_command_forks", "spawner_blocks_work", "minecraft:spawner_blocks_work", "advance_time", "minecraft:advance_time", "mob_explosion_drop_decay", "minecraft:mob_explosion_drop_decay", "elytra_movement_check", "minecraft:elytra_movement_check", "fall_damage", "minecraft:fall_damage", "log_admin_commands", "minecraft:log_admin_commands", "natural_health_regeneration", "minecraft:natural_health_regeneration", "spawn_monsters", "minecraft:spawn_monsters", "projectiles_can_break_blocks", "minecraft:projectiles_can_break_blocks", "keep_inventory", "minecraft:keep_inventory", "advance_weather", "minecraft:advance_weather", "random_tick_speed", "minecraft:random_tick_speed", "max_block_modifications", "minecraft:max_block_modifications", "global_sound_events", "minecraft:global_sound_events", "spawn_phantoms", "minecraft:spawn_phantoms", "block_explosion_drop_decay", "minecraft:block_explosion_drop_decay", "forgive_dead_players", "minecraft:forgive_dead_players", "reduced_debug_info", "minecraft:reduced_debug_info", "tnt_explosion_drop_decay", "minecraft:tnt_explosion_drop_decay", "player_movement_check", "minecraft:player_movement_check", "max_command_sequence_length", "minecraft:max_command_sequence_length", "spectators_generate_chunks", "minecraft:spectators_generate_chunks", "command_blocks_work", "minecraft:command_blocks_work", "freeze_damage", "minecraft:freeze_damage", "send_command_feedback", "minecraft:send_command_feedback", "show_death_messages", "minecraft:show_death_messages", "limited_crafting", "minecraft:limited_crafting", "max_snow_accumulation_height", "minecraft:max_snow_accumulation_height", "block_drops", "minecraft:block_drops", "tnt_explodes", "minecraft:tnt_explodes", "water_source_conversion", "minecraft:water_source_conversion", "fire_damage", "minecraft:fire_damage", "fire_spread_radius_around_player", "minecraft:fire_spread_radius_around_player", "pvp", "minecraft:pvp", "raids", "minecraft:raids", "mob_drops", "minecraft:mob_drops", "command_block_output", "minecraft:command_block_output", "immediate_respawn", "minecraft:immediate_respawn", "show_advancement_messages", "minecraft:show_advancement_messages", "spawn_patrols", "minecraft:spawn_patrols", "spawn_mobs", "minecraft:spawn_mobs", "entity_drops", "minecraft:entity_drops", "drowning_damage", "minecraft:drowning_damage", "spawn_wardens", "minecraft:spawn_wardens", "players_nether_portal_default_delay", "minecraft:players_nether_portal_default_delay", "respawn_radius", "minecraft:respawn_radius", "max_entity_cramming", "minecraft:max_entity_cramming"]), ("item", &["replace", "fill", "override", "modify"]), ("item replace entity target slots", &["from", "with"]), ("item fill entity target slots", &["from", "with"]), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 30c5f3d60..c2585d49d 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -593,6 +593,7 @@ impl Game<'_> { "debug" => self.cmd_debug(ctx), "jfr" => self.cmd_jfr(ctx), "version" => self.cmd_version(), + id if id.starts_with("test.") => self.cmd_test(id, ctx), "place" => self.cmd_place(ctx), "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index 5605194b7..9bb03532f 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -491,6 +491,77 @@ impl Game<'_> { Ok(n) } + // ---- /test ---------------------------------------------------------- + + /// `TestCommand`. Horizon has no game test instances or test runner: every + /// finder comes back empty, as in a world without test instance blocks. + pub(super) fn cmd_test(&mut self, id: &str, ctx: &Context) -> R { + match id { + // run , runmultiple, verify: GameTestRunner. + "test.run" | "test.verify" | "test.create" => Err(err("command.failed", &[])), + // runthese/runclosest/runthat/runfailed: TestFinder finds nothing. + "test.run.found" => { + if ctx.literals.iter().any(|l| l == "runthat") { + self.source_player()?; + } + self.feedback(Text::translate("commands.test.no_tests", &[])); + Ok(0) + } + // reset*/clear*: TestCommand.reset throws CLEAR_NO_TESTS too. + "test.clear" => { + if ctx.literals.iter().any(|l| l == "resetthat" || l == "clearthat") { + self.source_player()?; + } + Err(err("commands.test.clear.error.no_tests", &[])) + } + "test.stop" => Ok(1), + "test.locate" => { + // CommandSourceStack.sendSystemMessage: no feedback rule. + if !self.command_source.is_some_and(|s| s.silent) { + self.system_message(Text::translate("commands.test.locate.started", &[])); + } + Err(err("commands.test.error.no_test_instances", &[])) + } + _ => { + // TestCommand.showPos: the block the player looks at (10 blocks). + self.source_player()?; + let p = self.test_pick_block(); + Err(err( + "commands.test.error.no_test_containing_pos", + &[&p[0], &p[1], &p[2]], + )) + } + } + } + /// `Entity.pick(10, 1, false)`: the first non-air block on the view ray, + /// else the block at the ray's end. + fn test_pick_block(&self) -> [i32; 3] { + use horizon_core::{ + geometry::{Vec3, traverse_blocks}, + position::BlockPos, + }; + let Some(p) = self.player.as_ref() else { + return [0; 3]; + }; + let eye = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ); + let (yaw, pitch) = (f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians()); + let dir = [-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()]; + let end = Vec3::new(eye.x + dir[0] * 10.0, eye.y + dir[1] * 10.0, eye.z + dir[2] * 10.0); + let hit = traverse_blocks(eye, end, 256, |b: BlockPos| { + let state = self.world.block(b.x, b.y, b.z); + (!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z]) + }); + hit.ok().flatten().unwrap_or([ + end.x.floor() as i32, + end.y.floor() as i32, + end.z.floor() as i32, + ]) + } + // ---- /kick ---------------------------------------------------------- /// `KickCommand.kickPlayers`: only guests of a published world can be diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index e8d9ac45b..2fb23967c 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -838,6 +838,8 @@ def social(): def test_command(): + # Horizon has no game test runner: `/test run|runmultiple|verify` of an + # existing instance and `/test create` are not compared. return [ cmd('/test clearall'), cmd('/test stop'), @@ -847,7 +849,18 @@ def test_command(): cmd('/test resetclosest'), cmd('/test runfailed'), cmd('/test clearthese'), - cmd('/test verify minecraft:always_pass'), + cmd('/test runthese'), + cmd('/test runthat 2 true'), + cmd('/test runfailed true'), + cmd('/test resetthese'), + cmd('/test resetthat'), + cmd('/test clearthat'), + cmd('/test clearall 10'), + cmd('/test pos myPos'), + cmd('/test locate *'), + cmd('/test run minecraft:nothing*'), + cmd('/test locate nothing'), + cmd('/execute as @e[type=!minecraft:player,limit=1] run test pos'), ] diff --git a/tools/generate_command_order.py b/tools/generate_command_order.py index 54fd9f1fa..6eabc909b 100644 --- a/tools/generate_command_order.py +++ b/tools/generate_command_order.py @@ -27,6 +27,10 @@ def main(): def walk(v, r, path): names = list(v.get("children", {})) + # GameRuleCommand registers the rules in a Reference2ObjectOpenHashMap's + # (identity hash) order, which changes from run to run. + if path == ["gamerule"]: + return order = r.get("order", []) shared = [n for n in names if n in order] if shared != [n for n in order if n in names]: diff --git a/tools/test_command_exec_parity.py b/tools/test_command_exec_parity.py index c6994e0bb..2aa0c757a 100644 --- a/tools/test_command_exec_parity.py +++ b/tools/test_command_exec_parity.py @@ -132,8 +132,14 @@ MASKS = [ ] +GAMERULES = re.compile(r'/gamerule \(([^)]*)\)') + + def masked(record): text = json.dumps(record['messages'], ensure_ascii=False) + # GameRuleCommand registers the rules in identity-hash order, different + # in every JVM: compare /help's gamerule alternatives as a set. + text = GAMERULES.sub(lambda m: '/gamerule (' + '|'.join(sorted(m.group(1).split('|'))) + ')', text) for pattern, replacement in MASKS: text = pattern.sub(replacement, text) return text