diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index 1b6905bef..ee6519bfc 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -120,7 +120,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { } children.insert(child.name().to_owned(), v); } - let mut v = json!({"children": children}); + let order: Vec<&str> = n.children.iter().map(|&c| d.nodes[c].name()).collect(); + let mut v = json!({"children": children, "order": order}); if n.command.is_some() { v["executable"] = json!(true); } diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e6931852a..79041beb5 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -18,6 +18,7 @@ pub mod tree_misc; pub mod tree_scoreboard; pub mod tree_world; pub mod vanilla; +mod vanilla_order; use crate::text::Text; pub use args::{Arg, ArgType, Registries}; diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 495f36966..daf4ecf86 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -403,6 +403,7 @@ pub fn build_with(dev: bool) -> Dispatcher { super::tree_misc::register(&mut d, root); super::tree_world::register(&mut d, root); super::tree_extra::register(&mut d, root); + apply_vanilla_order(&mut d); d } @@ -506,6 +507,42 @@ pub fn game_modes() -> [&'static str; 4] { GameMode::ALL.map(GameMode::name) } /// The shared vanilla tree. +/// Reorder node children as vanilla registers them (Brigadier keeps +/// children in registration order; smart usage lists them that way). +fn apply_vanilla_order(d: &mut Dispatcher) { + for (path, order) in super::vanilla_order::ORDER { + let mut node = Some(0usize); + for name in path.split(' ').filter(|n| !n.is_empty()) { + node = node.and_then(|n| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + }); + } + let Some(n) = node else { continue }; + let mut children = d.nodes[n].children.clone(); + let rank = |c: usize| { + order + .iter() + .position(|o| *o == d.nodes[c].name()) + .unwrap_or(order.len()) + }; + children.sort_by_key(|&c| rank(c)); + d.nodes[n].children = children; + } +} +/// The tree the game runs: a release integrated server's, or with +/// `HORIZON_DEV_COMMANDS` set the development one +/// (SharedConstants.DEBUG_DEV_COMMANDS). +pub fn game_dispatcher() -> &'static Dispatcher { + if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { + dispatcher() + } else { + release_dispatcher() + } +} pub fn dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(build) diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-client/src/command/vanilla_order.rs new file mode 100644 index 000000000..c5089ee1a --- /dev/null +++ b/crates/horizon-client/src/command/vanilla_order.rs @@ -0,0 +1,36 @@ +//! The order of node children in vanilla's command tree, for the nodes +//! where Horizon's tree registers them differently (path of node names +//! from the root, children in vanilla's order). Generated by +//! tools/generate_command_order.py; do not edit by hand. + +pub const ORDER: &[(&str, &[&str])] = &[ + ("", &["advancement", "attribute", "execute", "bossbar", "clear", "clone", "compute", "damage", "data", "datapack", "debug", "defaultgamemode", "dialog", "difficulty", "effect", "me", "enchant", "experience", "xp", "fill", "fillbiome", "forceload", "function", "gamemode", "gamerule", "give", "help", "item", "kick", "kill", "list", "locate", "loot", "msg", "tell", "w", "swing", "particle", "place", "playsound", "posteffect", "random", "reload", "recipe", "fetchprofile", "return", "ride", "rotate", "say", "schedule", "scoreboard", "seed", "version", "setblock", "spawnpoint", "setworldspawn", "spectate", "spreadplayers", "stopsound", "stopwatch", "summon", "tag", "team", "teammsg", "tm", "teleport", "tp", "tellraw", "test", "tick", "time", "title", "trigger", "waypoint", "weather", "worldborder", "jfr", "publish", "unpublish"]), + ("execute", &["run", "if", "unless", "as", "at", "store", "positioned", "rotated", "facing", "align", "anchored", "in", "summon", "on"]), + ("execute if", &["block", "biome", "loaded", "dimension", "score", "blocks", "entity", "predicate", "function", "stopwatch", "data", "items", "slots"]), + ("execute unless", &["block", "biome", "loaded", "dimension", "score", "blocks", "entity", "predicate", "function", "stopwatch", "data", "items", "slots"]), + ("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"]), + ("item override entity target slots", &["from", "with"]), + ("loot replace entity entities slot", &["fish", "loot", "kill", "mine", "count"]), + ("loot replace entity entities slot fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot replace entity entities slot mine pos", &["tool", "mainhand", "offhand"]), + ("loot replace entity entities slot count fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot replace entity entities slot count mine pos", &["tool", "mainhand", "offhand"]), + ("loot replace block targetPos slot", &["fish", "loot", "kill", "mine", "count"]), + ("loot replace block targetPos slot fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot replace block targetPos slot mine pos", &["tool", "mainhand", "offhand"]), + ("loot replace block targetPos slot count fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot replace block targetPos slot count mine pos", &["tool", "mainhand", "offhand"]), + ("loot insert targetPos fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot insert targetPos mine pos", &["tool", "mainhand", "offhand"]), + ("loot give players fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot give players mine pos", &["tool", "mainhand", "offhand"]), + ("loot spawn targetPos fish loot_table pos", &["tool", "mainhand", "offhand"]), + ("loot spawn targetPos mine pos", &["tool", "mainhand", "offhand"]), + ("scoreboard players", &["list", "set", "get", "add", "remove", "reset", "enable", "display", "operation"]), +]; diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 792b7ebdc..7add40610 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -410,7 +410,7 @@ impl Game<'_> { return; }; let atlas = &self.res.atlas; - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) { self.ui.chat_screen = Some(screen); return; @@ -528,7 +528,7 @@ impl Game<'_> { screen.draw( batch, &self.res.atlas, - vanilla::dispatcher(), + vanilla::game_dispatcher(), &self.ui.registries, self.cursor, bg, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 018159278..30c5f3d60 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -77,7 +77,7 @@ fn format_double(v: f64) -> String { impl Game<'_> { /// Commands.performCommand for a line without its slash. pub(super) fn run_command(&mut self, command: &str) { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(command, &self.ui.registries); let result = match parse.executable() { Err(e) => { @@ -666,7 +666,7 @@ impl Game<'_> { } } fn cmd_help(&mut self, ctx: &Context) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let level = self.ui.registries.permission; match ctx.get("command") { None => { diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index ec0b94237..2ed16b72f 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -157,7 +157,7 @@ impl Game<'_> { /// Run one command line with `source` (no error reporting): the entry /// for functions and `execute run`. pub(in crate::game) fn execute_line(&mut self, line: &str, source: Source) -> R { - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let parse = d.parse(line, &self.ui.registries); let (ctx, _) = parse.executable()?; let ctx = ctx.clone(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ea15def42..c86774d08 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -556,7 +556,7 @@ impl Game<'_> { }; let skip = usize::from(text.starts_with('/')); let command = &text[skip..]; - let d = vanilla::dispatcher(); + let d = vanilla::game_dispatcher(); let level = std::mem::replace(&mut self.ui.registries.permission, permission); let parse = d.parse(command, &self.ui.registries); let ((start, end), suggestions) = d.suggestions(&parse, command.len(), &self.ui.registries); diff --git a/tools/generate_command_order.py b/tools/generate_command_order.py new file mode 100644 index 000000000..54fd9f1fa --- /dev/null +++ b/tools/generate_command_order.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Generate crates/horizon-client/src/command/vanilla_order.rs: the order of +the children of each node of vanilla's command tree where Horizon's tree +registers them in a different order. Brigadier keeps children in +registration order, and /help (smart usage) lists them that way. + + python3 tools/test_command_parse_parity.py # exports .local/command-parse-parity/tree.json + command_parse_fixture tree rust_tree.json # Horizon's tree with child order + generate_command_order.py VANILLA_TREE RUST_TREE +""" +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("vanilla", type=Path) + parser.add_argument("rust", type=Path) + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/command/vanilla_order.rs") + args = parser.parse_args() + vanilla = json.loads(args.vanilla.read_text()) + rust = json.loads(args.rust.read_text()) + rows = [] + + def walk(v, r, path): + names = list(v.get("children", {})) + 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]: + rows.append((" ".join(path), shared)) + for n in names: + if n in r.get("children", {}): + walk(v["children"][n], r["children"][n], path + [n]) + + walk(vanilla, rust, []) + if not rows or rows[0][0] != "": + raise SystemExit("expected the root's order to differ") + lines = [ + "//! The order of node children in vanilla's command tree, for the nodes", + "//! where Horizon's tree registers them differently (path of node names", + "//! from the root, children in vanilla's order). Generated by", + "//! tools/generate_command_order.py; do not edit by hand.", + "", + "pub const ORDER: &[(&str, &[&str])] = &[", + ] + for path, names in rows: + joined = ", ".join(f'"{n}"' for n in names) + lines.append(f' ("{path}", &[{joined}]),') + lines += ["];", ""] + args.out.write_text("\n".join(lines)) + print(f"wrote {len(rows)} nodes to {args.out}") + + +if __name__ == "__main__": + main()