Add vanilla font metrics with unifont fallback, languages, styled text and a Brigadier command core

Font: bitmap glyph ascent/oversampling, unihex glyphs rasterized on demand
into a reserved atlas region, bold/italic/underline/strikethrough and
StringSplitter wrapping. Languages layer lang/<code>.json over en_us.
The command module ports Brigadier parsing, suggestions and smart usage
with the vanilla argument types and the 26.3 command tree; game rules
use the 26.3 registry names and saved-data file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:16:20 +02:00
parent 1b38d82aac
commit 67f51123e8
15 changed files with 3730 additions and 104 deletions
File diff suppressed because it is too large Load Diff
+639
View File
@@ -0,0 +1,639 @@
//! A port of Brigadier (the command library vanilla uses): a string reader,
//! literal/argument node trees with redirects, parsing that tries every
//! relevant child and keeps the best result, completion suggestions, smart
//! usage text and the vanilla error messages. Argument types live in
//! [`args`]; the vanilla command tree in [`vanilla`].
pub mod args;
pub mod vanilla;
use crate::text::Text;
pub use args::{Arg, ArgType, Registries};
/// A command error (CommandSyntaxException): the message and, for parse
/// errors, the input and cursor it occurred at.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandError {
pub message: Text,
pub input: Option<String>,
pub cursor: usize,
/// BuiltInExceptions.literalIncorrect (summarised specially by the chat UI).
pub literal_incorrect: bool,
}
impl CommandError {
pub fn new(message: Text) -> Self {
Self { message, input: None, cursor: 0, literal_incorrect: false }
}
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
Self::new(Text::tr(key, args))
}
pub fn at(message: Text, reader: &Reader) -> Self {
Self { message, input: Some(reader.string.to_owned()), cursor: reader.cursor, literal_incorrect: false }
}
pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self {
Self::at(Text::tr(key, args), reader)
}
/// CommandSyntaxException.getContext: up to ten characters before the
/// cursor followed by "<--[HERE]".
pub fn context(&self) -> Option<String> {
let input = self.input.as_ref()?;
let cursor = self.cursor.min(input.len());
let start = input.floor_char_boundary(cursor.saturating_sub(10));
let mut out = String::new();
if cursor > 10 {
out.push_str("...");
}
out.push_str(&input[start..cursor]);
out.push_str("<--[HERE]");
Some(out)
}
/// The message as shown by command suggestions ("... at position N: ...").
pub fn with_context(&self) -> Text {
match self.context() {
Some(context) => Text::translate("command.context.parse_error", &[self.message.clone(), Text::literal(self.cursor.to_string()), Text::literal(context)]),
None => self.message.clone(),
}
}
}
pub type CmdResult<T> = Result<T, CommandError>;
/// Brigadier StringReader over a command line (byte cursor on char boundaries).
#[derive(Clone, Debug)]
pub struct Reader<'a> {
pub string: &'a str,
pub cursor: usize,
}
impl<'a> Reader<'a> {
pub fn new(string: &'a str) -> Self {
Self { string, cursor: 0 }
}
pub fn can_read(&self) -> bool {
self.cursor < self.string.len()
}
pub fn can_read_n(&self, n: usize) -> bool {
self.string[self.cursor..].chars().take(n).count() == n
}
pub fn peek(&self) -> char {
self.string[self.cursor..].chars().next().unwrap_or('\0')
}
pub fn peek_at(&self, offset: usize) -> char {
self.string[self.cursor..].chars().nth(offset).unwrap_or('\0')
}
pub fn skip(&mut self) {
self.cursor += self.peek().len_utf8();
}
pub fn read(&mut self) -> char {
let c = self.peek();
self.skip();
c
}
pub fn remaining(&self) -> &'a str {
&self.string[self.cursor..]
}
pub fn skip_whitespace(&mut self) {
while self.can_read() && self.peek().is_whitespace() {
self.skip();
}
}
pub fn is_allowed_number(c: char) -> bool {
c.is_ascii_digit() || c == '.' || c == '-'
}
pub fn is_allowed_in_unquoted(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
}
fn read_number_text(&mut self) -> &'a str {
let start = self.cursor;
while self.can_read() && Self::is_allowed_number(self.peek()) {
self.skip();
}
&self.string[start..self.cursor]
}
fn number<T: std::str::FromStr>(&mut self, kind: &str) -> CmdResult<T> {
let start = self.cursor;
let text = self.read_number_text();
if text.is_empty() {
return Err(CommandError::tr_at(&format!("parsing.{kind}.expected"), &[], self));
}
// Java's parsers reject a trailing '.'-less exponent etc. the same way.
match text.parse::<T>() {
Ok(v) if !(kind == "int" || kind == "long") || !text.contains('.') => Ok(v),
_ => {
self.cursor = start;
Err(CommandError::tr_at(&format!("parsing.{kind}.invalid"), &[&text], self))
}
}
}
pub fn read_int(&mut self) -> CmdResult<i32> {
self.number("int")
}
pub fn read_long(&mut self) -> CmdResult<i64> {
self.number("long")
}
pub fn read_double(&mut self) -> CmdResult<f64> {
self.number("double")
}
pub fn read_float(&mut self) -> CmdResult<f32> {
self.number("float")
}
pub fn read_unquoted_string(&mut self) -> &'a str {
let start = self.cursor;
while self.can_read() && Self::is_allowed_in_unquoted(self.peek()) {
self.skip();
}
&self.string[start..self.cursor]
}
pub fn read_string_until(&mut self, terminator: char) -> CmdResult<String> {
let mut out = String::new();
let mut escaped = false;
while self.can_read() {
let c = self.read();
if escaped {
if c == terminator || c == '\\' {
out.push(c);
escaped = false;
} else {
self.cursor -= c.len_utf8();
return Err(CommandError::tr_at("parsing.quote.escape", &[&c], self));
}
} else if c == '\\' {
escaped = true;
} else if c == terminator {
return Ok(out);
} else {
out.push(c);
}
}
Err(CommandError::tr_at("parsing.quote.expected.end", &[], self))
}
pub fn read_quoted_string(&mut self) -> CmdResult<String> {
if !self.can_read() {
return Ok(String::new());
}
let next = self.peek();
if next != '"' && next != '\'' {
return Err(CommandError::tr_at("parsing.quote.expected.start", &[], self));
}
self.skip();
self.read_string_until(next)
}
pub fn read_string(&mut self) -> CmdResult<String> {
if !self.can_read() {
return Ok(String::new());
}
let next = self.peek();
if next == '"' || next == '\'' {
self.skip();
return self.read_string_until(next);
}
Ok(self.read_unquoted_string().to_owned())
}
pub fn read_boolean(&mut self) -> CmdResult<bool> {
let start = self.cursor;
let value = self.read_string()?;
if value.is_empty() {
return Err(CommandError::tr_at("parsing.bool.expected", &[], self));
}
match value.as_str() {
"true" => Ok(true),
"false" => Ok(false),
_ => {
self.cursor = start;
Err(CommandError::tr_at("parsing.bool.invalid", &[&value], self))
}
}
}
pub fn expect(&mut self, c: char) -> CmdResult<()> {
if !self.can_read() || self.peek() != c {
return Err(CommandError::tr_at("parsing.expected", &[&c], self));
}
self.skip();
Ok(())
}
}
pub type Range = (usize, usize);
#[derive(Clone, Debug)]
pub enum NodeKind {
Root,
Literal(String),
Argument { name: String, ty: ArgType },
}
#[derive(Clone, Debug)]
pub struct Node {
pub kind: NodeKind,
pub children: Vec<usize>,
/// The command id run when parsing ends here.
pub command: Option<&'static str>,
pub redirect: Option<usize>,
/// Required permission level (0 everyone, 2 game masters, 4 owners).
pub permission: u8,
}
impl Node {
pub fn name(&self) -> &str {
match &self.kind {
NodeKind::Root => "",
NodeKind::Literal(l) => l,
NodeKind::Argument { name, .. } => name,
}
}
/// CommandNode.getUsageText.
pub fn usage_text(&self) -> String {
match &self.kind {
NodeKind::Root => String::new(),
NodeKind::Literal(l) => l.clone(),
NodeKind::Argument { name, .. } => format!("<{name}>"),
}
}
}
#[derive(Clone, Debug)]
pub struct ParsedArg {
pub name: String,
pub value: Arg,
pub range: Range,
}
/// CommandContextBuilder: the nodes and arguments parsed so far.
#[derive(Clone, Debug)]
pub struct Context {
pub root: usize,
pub nodes: Vec<(usize, Range)>,
pub args: Vec<ParsedArg>,
pub command: Option<&'static str>,
pub range: Range,
pub child: Option<Box<Context>>,
/// Literal words parsed so far (mode keywords such as `masked`).
pub literals: Vec<String>,
}
impl Context {
fn new(root: usize, start: usize) -> Self {
Self { root, nodes: Vec::new(), args: Vec::new(), command: None, range: (start, start), child: None, literals: Vec::new() }
}
/// Whether the literal `word` was parsed (in this context).
pub fn has(&self, word: &str) -> bool {
self.literals.iter().any(|l| l == word)
}
fn with_node(&mut self, node: usize, range: Range) {
self.nodes.push((node, range));
self.range = (self.range.0.min(range.0), self.range.1.max(range.1));
}
pub fn last_child(&self) -> &Context {
let mut c = self;
while let Some(child) = &c.child {
c = child;
}
c
}
pub fn get(&self, name: &str) -> Option<&Arg> {
self.args.iter().rev().find(|a| a.name == name).map(|a| &a.value)
}
/// CommandContextBuilder.findSuggestionContext: the node whose children
/// complete the text at `cursor`, and where that text starts.
pub fn suggestion_context(&self, cursor: usize) -> (usize, usize, &Context) {
if self.range.1 < cursor {
if let Some(child) = &self.child {
return child.suggestion_context(cursor);
}
if let Some((node, range)) = self.nodes.last() {
return (*node, range.1 + 1, self);
}
return (self.root, self.range.0, self);
}
let mut prev = self.root;
for (node, range) in &self.nodes {
if range.0 <= cursor && cursor <= range.1 {
return (prev, range.0, self);
}
prev = *node;
}
(prev, self.range.0, self)
}
}
#[derive(Clone, Debug)]
pub struct ParseResults {
pub context: Context,
pub input: String,
pub cursor: usize,
pub errors: Vec<(usize, CommandError)>,
}
impl ParseResults {
pub fn can_read(&self) -> bool {
self.cursor < self.input.len()
}
/// Commands.getParseException.
pub fn error(&self) -> Option<CommandError> {
if !self.can_read() {
return None;
}
if self.errors.len() == 1 {
return Some(self.errors[0].1.clone());
}
let reader = Reader { string: &self.input, cursor: self.cursor };
Some(if self.context.range.0 == self.context.range.1 {
CommandError::tr_at("command.unknown.command", &[], &reader)
} else {
CommandError::tr_at("command.unknown.argument", &[], &reader)
})
}
/// The executable context and command id, or the vanilla error.
pub fn executable(&self) -> CmdResult<(&Context, &'static str)> {
if let Some(e) = self.error() {
return Err(e);
}
let last = self.context.last_child();
match last.command {
Some(id) => Ok((last, id)),
None => Err(CommandError::tr_at("command.unknown.command", &[], &Reader { string: &self.input, cursor: self.cursor })),
}
}
}
/// A completion: replace `range` of the input with `text`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Suggestion {
pub range: Range,
pub text: String,
pub tooltip: Option<String>,
}
impl Suggestion {
/// Suggestion.apply.
pub fn apply(&self, input: &str) -> String {
let (s, e) = (self.range.0.min(input.len()), self.range.1.min(input.len()));
format!("{}{}{}", &input[..s], self.text, &input[e..])
}
}
/// SuggestionsBuilder: suggestions for the text from `start` to the cursor.
pub struct SuggestionsBuilder<'a> {
pub input: &'a str,
pub start: usize,
pub out: Vec<Suggestion>,
}
impl<'a> SuggestionsBuilder<'a> {
pub fn new(input: &'a str, start: usize) -> Self {
Self { input, start: start.min(input.len()), out: Vec::new() }
}
pub fn remaining(&self) -> &'a str {
&self.input[self.start..]
}
pub fn remaining_lower(&self) -> String {
self.remaining().to_lowercase()
}
pub fn suggest(&mut self, text: impl Into<String>) {
let text = text.into();
if text != self.remaining() {
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: None });
}
}
pub fn suggest_tooltip(&mut self, text: impl Into<String>, tooltip: impl Into<String>) {
let text = text.into();
if text != self.remaining() {
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: Some(tooltip.into()) });
}
}
pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> {
SuggestionsBuilder::new(self.input, start)
}
/// SharedSuggestionProvider.suggest: candidates starting with the remaining text.
pub fn suggest_matching<'b>(&mut self, candidates: impl IntoIterator<Item = &'b str>) {
let lower = self.remaining_lower();
for c in candidates {
if c.to_lowercase().starts_with(&lower) {
self.suggest(c);
}
}
}
}
/// Suggestions.create: merged, expanded to a common range and sorted case-insensitively.
pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Suggestion>) {
if list.is_empty() {
return ((0, 0), Vec::new());
}
let start = list.iter().map(|s| s.range.0).min().unwrap_or(0);
let end = list.iter().map(|s| s.range.1).max().unwrap_or(0);
let mut out: Vec<Suggestion> = Vec::new();
for s in list {
// Suggestion.expand: pad the text with the input around it.
let text = format!("{}{}{}", &input[start..s.range.0], s.text, &input[s.range.1..end]);
let expanded = Suggestion { range: (start, end), text, tooltip: s.tooltip };
if !out.iter().any(|o| o.text == expanded.text) {
out.push(expanded);
}
}
out.sort_by(|a, b| a.text.to_lowercase().cmp(&b.text.to_lowercase()));
((start, end), out)
}
/// The command tree (CommandDispatcher). Node 0 is the root.
#[derive(Clone, Debug)]
pub struct Dispatcher {
pub nodes: Vec<Node>,
}
impl Default for Dispatcher {
fn default() -> Self {
Self::new()
}
}
impl Dispatcher {
pub fn new() -> Self {
Self { nodes: vec![Node { kind: NodeKind::Root, children: Vec::new(), command: None, redirect: None, permission: 0 }] }
}
fn add(&mut self, parent: usize, kind: NodeKind) -> usize {
let name = match &kind {
NodeKind::Literal(l) => l.clone(),
NodeKind::Argument { name, .. } => name.clone(),
NodeKind::Root => String::new(),
};
// CommandNode.addChild merges same-named children.
if let Some(&existing) = self.nodes[parent].children.iter().find(|&&c| self.nodes[c].name() == name) {
return existing;
}
let permission = self.nodes[parent].permission;
self.nodes.push(Node { kind, children: Vec::new(), command: None, redirect: None, permission });
let id = self.nodes.len() - 1;
self.nodes[parent].children.push(id);
id
}
pub fn literal(&mut self, parent: usize, name: &str) -> usize {
self.add(parent, NodeKind::Literal(name.to_owned()))
}
pub fn argument(&mut self, parent: usize, name: &str, ty: ArgType) -> usize {
self.add(parent, NodeKind::Argument { name: name.to_owned(), ty })
}
pub fn executes(&mut self, node: usize, command: &'static str) -> usize {
self.nodes[node].command = Some(command);
node
}
pub fn redirect(&mut self, node: usize, target: usize) -> usize {
self.nodes[node].redirect = Some(target);
node
}
pub fn requires(&mut self, node: usize, level: u8) -> usize {
self.nodes[node].permission = level;
node
}
/// A root literal by name.
pub fn find(&self, name: &str) -> Option<usize> {
self.nodes[0].children.iter().copied().find(|&c| self.nodes[c].name() == name)
}
fn relevant(&self, node: usize, reader: &Reader) -> Vec<usize> {
let children = &self.nodes[node].children;
let literals: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))).collect();
let arguments: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })).collect();
if literals.is_empty() {
return arguments;
}
let rest = reader.remaining();
let word = rest.split(' ').next().unwrap_or("");
match literals.iter().find(|&&l| self.nodes[l].name() == word) {
Some(&l) => vec![l],
None => arguments,
}
}
fn parse_node(&self, node: usize, reader: &mut Reader, context: &mut Context, reg: &Registries) -> CmdResult<()> {
let start = reader.cursor;
match &self.nodes[node].kind {
NodeKind::Root => Ok(()),
NodeKind::Literal(literal) => {
if reader.remaining().starts_with(literal.as_str()) {
let end = start + literal.len();
reader.cursor = end;
if !reader.can_read() || reader.peek() == ' ' {
context.with_node(node, (start, end));
context.literals.push(literal.clone());
return Ok(());
}
reader.cursor = start;
}
let mut e = CommandError::tr_at("argument.literal.incorrect", &[literal], reader);
e.literal_incorrect = true;
Err(e)
}
NodeKind::Argument { name, ty } => {
let value = ty.parse(reader, reg)?;
let range = (start, reader.cursor);
context.args.push(ParsedArg { name: name.clone(), value, range });
context.with_node(node, range);
Ok(())
}
}
}
fn parse_nodes(&self, node: usize, input: &str, cursor: usize, so_far: &Context, reg: &Registries, level: u8) -> ParseResults {
let mut errors = Vec::new();
let mut potentials: Vec<ParseResults> = Vec::new();
let original = Reader { string: input, cursor };
for child in self.relevant(node, &original) {
if self.nodes[child].permission > level {
continue;
}
let mut context = so_far.clone();
let mut reader = original.clone();
let parsed = self.parse_node(child, &mut reader, &mut context, reg).and_then(|()| {
if reader.can_read() && reader.peek() != ' ' {
Err(CommandError::tr_at("command.expected.separator", &[], &reader))
} else {
Ok(())
}
});
if let Err(e) = parsed {
errors.push((child, e));
continue;
}
context.command = self.nodes[child].command;
let redirect = self.nodes[child].redirect;
if reader.can_read_n(if redirect.is_none() { 2 } else { 1 }) {
reader.skip();
if let Some(target) = redirect {
let child_context = Context::new(target, reader.cursor);
let parse = self.parse_nodes(target, input, reader.cursor, &child_context, reg, level);
context.child = Some(Box::new(parse.context));
return ParseResults { context, input: input.to_owned(), cursor: parse.cursor, errors: parse.errors };
}
potentials.push(self.parse_nodes(child, input, reader.cursor, &context, reg, level));
} else {
potentials.push(ParseResults { context, input: input.to_owned(), cursor: reader.cursor, errors: Vec::new() });
}
}
if !potentials.is_empty() {
// Prefer fully read input, then results without errors (stable sort).
potentials.sort_by_key(|p| (p.can_read(), !p.errors.is_empty()));
return potentials.swap_remove(0);
}
ParseResults { context: so_far.clone(), input: input.to_owned(), cursor, errors }
}
/// CommandDispatcher.parse from the start of `input` (no leading slash).
pub fn parse(&self, input: &str, reg: &Registries) -> ParseResults {
self.parse_at(input, 0, reg)
}
/// Parse starting at byte `start` (after a leading '/').
pub fn parse_at(&self, input: &str, start: usize, reg: &Registries) -> ParseResults {
let context = Context::new(0, start);
self.parse_nodes(0, input, start, &context, reg, reg.permission)
}
/// CommandDispatcher.getCompletionSuggestions at `cursor`.
pub fn suggestions(&self, parse: &ParseResults, cursor: usize, reg: &Registries) -> (Range, Vec<Suggestion>) {
let (parent, start, context) = parse.context.suggestion_context(cursor);
let start = start.min(cursor);
let truncated = &parse.input[..cursor.min(parse.input.len())];
let mut all = Vec::new();
for &child in &self.nodes[parent].children {
if self.nodes[child].permission > reg.permission {
continue;
}
let mut builder = SuggestionsBuilder::new(truncated, start);
match &self.nodes[child].kind {
NodeKind::Literal(l) => {
if l.to_lowercase().starts_with(&builder.remaining_lower()) {
builder.suggest(l.clone());
}
}
NodeKind::Argument { ty, name } => ty.suggest(&mut builder, reg, context, name),
NodeKind::Root => {}
}
all.extend(builder.out);
}
merge_suggestions(truncated, all)
}
fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option<String> {
let n = &self.nodes[node];
if n.permission > level {
return None;
}
let this = if optional { format!("[{}]", n.usage_text()) } else { n.usage_text() };
let child_optional = n.command.is_some();
let (open, close) = if child_optional { ("[", "]") } else { ("(", ")") };
if !deep {
if let Some(r) = n.redirect {
let target = if r == 0 { "...".to_owned() } else { format!("-> {}", self.nodes[r].usage_text()) };
return Some(format!("{this} {target}"));
}
let children: Vec<usize> = n.children.iter().copied().filter(|&c| self.nodes[c].permission <= level).collect();
if children.len() == 1 {
if let Some(usage) = self.smart_usage_of(children[0], child_optional, child_optional, level) {
return Some(format!("{this} {usage}"));
}
} else if children.len() > 1 {
let mut child_usage: Vec<String> = Vec::new();
for &c in &children {
if let Some(u) = self.smart_usage_of(c, child_optional, true, level)
&& !child_usage.contains(&u)
{
child_usage.push(u);
}
}
if child_usage.len() == 1 {
let usage = &child_usage[0];
return Some(format!("{this} {}", if child_optional { format!("[{usage}]") } else { usage.clone() }));
}
if child_usage.len() > 1 {
let alternatives: Vec<String> = children.iter().map(|&c| self.nodes[c].usage_text()).collect();
return Some(format!("{this} {open}{}{close}", alternatives.join("|")));
}
}
}
Some(this)
}
/// CommandDispatcher.getSmartUsage: one line per child of `node`.
pub fn smart_usage(&self, node: usize, level: u8) -> Vec<(usize, String)> {
let optional = self.nodes[node].command.is_some();
self.nodes[node].children.iter().filter_map(|&c| self.smart_usage_of(c, optional, false, level).map(|u| (c, u))).collect()
}
}
#[cfg(test)]
mod tests;
+139
View File
@@ -0,0 +1,139 @@
use super::{args::*, vanilla, *};
fn reg() -> Registries {
let mut r = Registries { permission: 4, ..Registries::default() };
r.items = vec!["minecraft:diamond".into(), "minecraft:diamond_sword".into(), "minecraft:stone".into()];
r.blocks.insert("minecraft:stone".into(), vec![]);
r.blocks.insert(
"minecraft:oak_stairs".into(),
vec![("facing".into(), vec!["north".into(), "south".into()]), ("half".into(), vec!["top".into(), "bottom".into()])],
);
r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()];
r.entity_types = vec!["minecraft:pig".into(), "minecraft:player".into(), "minecraft:zombie".into()];
r.players = vec!["Player".into()];
r.dimensions = vec!["minecraft:overworld".into()];
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
r
}
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
let reg = reg();
let parse = vanilla::dispatcher().parse(input, &reg);
let (ctx, id) = parse.executable()?;
Ok((id.to_owned(), ctx.args.iter().map(|a| a.name.clone()).collect()))
}
fn suggestions(input: &str) -> Vec<String> {
let reg = reg();
let d = vanilla::dispatcher();
let parse = d.parse(input, &reg);
d.suggestions(&parse, input.len(), &reg).1.into_iter().map(|s| s.text).collect()
}
#[test]
fn reader_matches_brigadier() {
let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true");
assert_eq!(r.read_int().unwrap(), 12);
r.skip();
assert_eq!(r.read_double().unwrap(), -3.5);
r.skip();
assert_eq!(r.read_unquoted_string(), "abc");
r.skip();
assert_eq!(r.read_string().unwrap(), "q\"x");
r.skip();
assert!(r.read_boolean().unwrap());
let e = Reader::new("1.5").read_int().unwrap_err();
assert_eq!(e.message.plain(), "parsing.int.invalid");
assert_eq!(e.context().unwrap(), "<--[HERE]");
}
#[test]
fn parses_vanilla_commands() {
assert_eq!(run("gamemode creative").unwrap().0, "gamemode");
assert_eq!(run("gamemode creative @s").unwrap().1, ["gamemode", "target"]);
assert_eq!(run("give @s minecraft:diamond 64").unwrap().1, ["targets", "item", "count"]);
assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location");
assert_eq!(run("tp Player").unwrap().0, "teleport.destination");
assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location");
assert_eq!(run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, "teleport.targets.location");
assert_eq!(run("time set 1000").unwrap().0, "time.set");
assert_eq!(run("time set 1d").unwrap().0, "time.set");
assert_eq!(run("time set day").unwrap().0, "time.set.marker");
assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime");
assert_eq!(run("weather rain 10s").unwrap().0, "weather");
assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience");
assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule");
assert_eq!(run("gamerule minecraft:random_tick_speed 10").unwrap().0, "gamerule");
assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill");
assert_eq!(run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone").unwrap().0, "fill");
assert_eq!(run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, "clone");
assert_eq!(run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, "setblock");
assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon");
assert_eq!(run("difficulty hard").unwrap().0, "difficulty");
assert_eq!(run("say hello @p").unwrap().0, "say");
let reg = reg();
let parse = vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", &reg);
let (ctx, _) = parse.executable().unwrap();
assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move"));
}
#[test]
fn vanilla_error_messages() {
let e = run("foo").unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
assert_eq!(e.cursor, 0);
let e = run("gamemode").unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
let e = run("gamemode creatve").unwrap_err();
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
assert_eq!(e.cursor, 9);
let e = run("give @s minecraft:dirt").unwrap_err();
assert_eq!(e.message.plain(), "argument.item.id.invalid");
let e = run("give @s diamond 0").unwrap_err();
assert_eq!(e.message.plain(), "argument.integer.low");
let e = run("gamemode creative @e").unwrap_err();
assert_eq!(e.message.plain(), "argument.player.entities");
let e = run("setblock 1 2").unwrap_err();
assert_eq!(e.message.plain(), "argument.pos3d.incomplete");
let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err();
assert_eq!(e.message.plain(), "argument.block.property.invalid");
}
#[test]
fn suggestions_like_vanilla() {
let root = suggestions("");
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
assert_eq!(suggestions("game"), ["gamemode", "gamerule"]);
assert_eq!(suggestions("gamemode "), ["adventure", "creative", "spectator", "survival"]);
assert_eq!(suggestions("gamemode c"), ["creative"]);
assert_eq!(suggestions("give @s dia"), ["minecraft:diamond", "minecraft:diamond_sword"]);
// Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr).
assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]);
assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]);
assert_eq!(suggestions("kill @e"), ["["]);
assert_eq!(suggestions("kill @e[ty"), ["type="]);
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]);
assert_eq!(suggestions("tp "), ["@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"]);
assert_eq!(suggestions("time set 5"), ["d", "s", "t"]);
assert!(suggestions("time set ").contains(&"minecraft:day".to_owned()));
}
#[test]
fn smart_usage_matches_brigadier() {
let d = vanilla::dispatcher();
let usage = |name: &str| d.smart_usage(0, 4).into_iter().find(|(n, _)| d.nodes[*n].name() == name).unwrap().1;
assert_eq!(usage("gamemode"), "gamemode <gamemode> [<target>]");
assert_eq!(usage("give"), "give <targets> <item> [<count>]");
assert_eq!(usage("kill"), "kill [<targets>]");
assert_eq!(usage("weather"), "weather (clear|rain|thunder)");
assert_eq!(usage("tp"), "tp -> teleport");
assert_eq!(usage("difficulty"), "difficulty [peaceful|easy|normal|hard]");
}
#[test]
fn local_coordinates_follow_view() {
// Facing south (yaw 0) moves +Z.
let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6);
// ^1 (left) while facing south is +X.
let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}");
let w = Coordinates::World([Coord { relative: true, value: 1.0 }, Coord { relative: false, value: 5.0 }, Coord { relative: true, value: 0.0 }]);
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
}
@@ -0,0 +1,340 @@
//! The vanilla command tree (Commands.java registrations) for the commands
//! Horizon implements. Leaves carry command ids that the game executes;
//! mode keywords are read back from the parsed literals.
use super::{
Dispatcher,
args::{ArgType, GameMode, Resource, integer},
};
use crate::gamerules::{RULES, Value};
/// Permission levels (Commands.LEVEL_*).
pub const ALL: u8 = 0;
pub const GAMEMASTERS: u8 = 2;
const PLAYERS: ArgType = ArgType::Entity { single: false, players: true };
const PLAYER: ArgType = ArgType::Entity { single: true, players: true };
const ENTITIES: ArgType = ArgType::Entity { single: false, players: false };
const ENTITY: ArgType = ArgType::Entity { single: true, players: false };
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
pub fn build() -> Dispatcher {
let mut d = Dispatcher::new();
let root = 0;
// help [<command>]
let help = d.literal(root, "help");
d.executes(help, "help");
let c = d.argument(help, "command", ArgType::Greedy);
d.executes(c, "help");
// gamemode <gamemode> [<target>]
let gm = d.literal(root, "gamemode");
d.requires(gm, GAMEMASTERS);
let mode = d.argument(gm, "gamemode", ArgType::GameMode);
d.executes(mode, "gamemode");
let t = d.argument(mode, "target", PLAYERS);
d.executes(t, "gamemode");
let dgm = d.literal(root, "defaultgamemode");
d.requires(dgm, GAMEMASTERS);
let mode = d.argument(dgm, "gamemode", ArgType::GameMode);
d.executes(mode, "defaultgamemode");
// give <targets> <item> [<count>]
let give = d.literal(root, "give");
d.requires(give, GAMEMASTERS);
let targets = d.argument(give, "targets", PLAYERS);
let item = d.argument(targets, "item", ArgType::Item);
d.executes(item, "give");
let count = d.argument(item, "count", integer(1));
d.executes(count, "give");
// teleport / tp
let tp = d.literal(root, "teleport");
d.requires(tp, GAMEMASTERS);
let loc = d.argument(tp, "location", ArgType::Vec3 { center: true });
d.executes(loc, "teleport.location");
let dest = d.argument(tp, "destination", ENTITY);
d.executes(dest, "teleport.destination");
let targets = d.argument(tp, "targets", ENTITIES);
let loc = d.argument(targets, "location", ArgType::Vec3 { center: true });
d.executes(loc, "teleport.targets.location");
let rot = d.argument(loc, "rotation", ArgType::Rotation);
d.executes(rot, "teleport.targets.location");
let facing = d.literal(loc, "facing");
let fe = d.literal(facing, "entity");
let fent = d.argument(fe, "facingEntity", ENTITY);
d.executes(fent, "teleport.targets.location");
let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor);
d.executes(anchor, "teleport.targets.location");
let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
d.executes(floc, "teleport.targets.location");
let dest = d.argument(targets, "destination", ENTITY);
d.executes(dest, "teleport.targets.destination");
let alias = d.literal(root, "tp");
d.requires(alias, GAMEMASTERS);
d.redirect(alias, tp);
// time: clock nodes for the dimension's default clock, plus `of <clock>`.
let time = d.literal(root, "time");
d.requires(time, GAMEMASTERS);
clock_nodes(&mut d, time);
let query = d.literal(time, "query");
let gt = d.literal(query, "gametime");
d.executes(gt, "time.query.gametime");
let of = d.literal(time, "of");
let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock));
clock_nodes(&mut d, clock);
// weather (clear|rain|thunder) [<duration>]
let weather = d.literal(root, "weather");
d.requires(weather, GAMEMASTERS);
for kind in ["clear", "rain", "thunder"] {
let k = d.literal(weather, kind);
d.executes(k, "weather");
let dur = d.argument(k, "duration", ArgType::Time { min: 1 });
d.executes(dur, "weather");
}
// kill [<targets>]
let kill = d.literal(root, "kill");
d.requires(kill, GAMEMASTERS);
d.executes(kill, "kill");
let t = d.argument(kill, "targets", ENTITIES);
d.executes(t, "kill");
// summon <entity> [<pos>] [<nbt>]
let summon = d.literal(root, "summon");
d.requires(summon, GAMEMASTERS);
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
d.executes(e, "summon");
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
d.executes(pos, "summon");
let nbt = d.argument(pos, "nbt", ArgType::Nbt);
d.executes(nbt, "summon");
// setblock <pos> <block> [destroy|keep|replace|strict]
let sb = d.literal(root, "setblock");
d.requires(sb, GAMEMASTERS);
let pos = d.argument(sb, "pos", ArgType::BlockPos);
let block = d.argument(pos, "block", ArgType::BlockState);
d.executes(block, "setblock");
for m in ["destroy", "keep", "replace", "strict"] {
let l = d.literal(block, m);
d.executes(l, "setblock");
}
// fill <from> <to> <block> [modes]
let fill = d.literal(root, "fill");
d.requires(fill, GAMEMASTERS);
let from = d.argument(fill, "from", ArgType::BlockPos);
let to = d.argument(from, "to", ArgType::BlockPos);
let block = d.argument(to, "block", ArgType::BlockState);
fill_modes(&mut d, block);
let replace = d.literal(block, "replace");
d.executes(replace, "fill");
let filter = d.argument(replace, "filter", ArgType::BlockPredicate);
fill_modes(&mut d, filter);
let keep = d.literal(block, "keep");
d.executes(keep, "fill");
// clone [from <dim>] <begin> <end> [to <dim>] <destination> [strict] [mask] [mode]
let clone = d.literal(root, "clone");
d.requires(clone, GAMEMASTERS);
clone_begin(&mut d, clone);
let from = d.literal(clone, "from");
let dim = d.argument(from, "sourceDimension", ArgType::Dimension);
clone_begin(&mut d, dim);
// experience / xp
let xp = d.literal(root, "experience");
d.requires(xp, GAMEMASTERS);
for (op, min) in [("add", i32::MIN), ("set", 0)] {
let o = d.literal(xp, op);
let t = d.argument(o, "target", PLAYERS);
let amount = d.argument(t, "amount", integer(min));
d.executes(amount, "experience");
for unit in ["points", "levels"] {
let u = d.literal(amount, unit);
d.executes(u, "experience");
}
}
let q = d.literal(xp, "query");
let t = d.argument(q, "target", PLAYER);
for unit in ["points", "levels"] {
let u = d.literal(t, unit);
d.executes(u, "experience");
}
let alias = d.literal(root, "xp");
d.requires(alias, GAMEMASTERS);
d.redirect(alias, xp);
// gamerule <rule> [<value>] (short and namespaced names)
let gr = d.literal(root, "gamerule");
d.requires(gr, GAMEMASTERS);
for rule in RULES {
for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] {
let r = d.literal(gr, &name);
d.executes(r, "gamerule");
let ty = match rule.default {
Value::Bool(_) => ArgType::Bool,
Value::Int(_) => ArgType::Integer { min: rule.min, max: rule.max },
};
let v = d.argument(r, "value", ty);
d.executes(v, "gamerule");
}
}
// difficulty [<difficulty>]
let diff = d.literal(root, "difficulty");
d.executes(diff, "difficulty");
for name in DIFFICULTIES {
let l = d.literal(diff, name);
d.requires(l, GAMEMASTERS);
d.executes(l, "difficulty");
}
let seed = d.literal(root, "seed");
d.executes(seed, "seed");
// spawnpoint [<targets>] [<pos>] [<rotation>]
let sp = d.literal(root, "spawnpoint");
d.requires(sp, GAMEMASTERS);
d.executes(sp, "spawnpoint");
let t = d.argument(sp, "targets", PLAYERS);
d.executes(t, "spawnpoint");
let pos = d.argument(t, "pos", ArgType::BlockPos);
d.executes(pos, "spawnpoint");
let rot = d.argument(pos, "rotation", ArgType::Rotation);
d.executes(rot, "spawnpoint");
// setworldspawn [<pos>] [<rotation>]
let ws = d.literal(root, "setworldspawn");
d.requires(ws, GAMEMASTERS);
d.executes(ws, "setworldspawn");
let pos = d.argument(ws, "pos", ArgType::BlockPos);
d.executes(pos, "setworldspawn");
let rot = d.argument(pos, "rotation", ArgType::Rotation);
d.executes(rot, "setworldspawn");
// clear [<targets>] [<item>] [<maxCount>]
let clear = d.literal(root, "clear");
d.requires(clear, GAMEMASTERS);
d.executes(clear, "clear");
let t = d.argument(clear, "targets", PLAYERS);
d.executes(t, "clear");
let item = d.argument(t, "item", ArgType::ItemPredicate);
d.executes(item, "clear");
let max = d.argument(item, "maxCount", integer(0));
d.executes(max, "clear");
// locate (structure|biome) <...>
let locate = d.literal(root, "locate");
d.requires(locate, GAMEMASTERS);
let s = d.literal(locate, "structure");
let a = d.argument(s, "structure", ArgType::Resource(Resource::Structure));
d.executes(a, "locate.structure");
let b = d.literal(locate, "biome");
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
d.executes(a, "locate.biome");
// say / me / msg / list
let say = d.literal(root, "say");
d.requires(say, GAMEMASTERS);
let m = d.argument(say, "message", ArgType::Message);
d.executes(m, "say");
let me = d.literal(root, "me");
let m = d.argument(me, "action", ArgType::Message);
d.executes(m, "me");
let msg = d.literal(root, "msg");
let t = d.argument(msg, "targets", PLAYERS);
let m = d.argument(t, "message", ArgType::Message);
d.executes(m, "msg");
for alias in ["tell", "w"] {
let a = d.literal(root, alias);
d.redirect(a, msg);
}
let list = d.literal(root, "list");
d.executes(list, "list");
let uuids = d.literal(list, "uuids");
d.executes(uuids, "list");
d
}
/// TimeCommand.addClockNodes.
fn clock_nodes(d: &mut Dispatcher, node: usize) {
let set = d.literal(node, "set");
let t = d.argument(set, "time", ArgType::Time { min: 0 });
d.executes(t, "time.set");
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
d.executes(marker, "time.set.marker");
let add = d.literal(node, "add");
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
d.executes(t, "time.add");
let pause = d.literal(node, "pause");
d.executes(pause, "time.pause");
let resume = d.literal(node, "resume");
d.executes(resume, "time.resume");
let rate = d.literal(node, "rate");
let r = d.argument(rate, "rate", ArgType::Float { min: 1.0e-5, max: 1000.0 });
d.executes(r, "time.rate");
let query = d.literal(node, "query");
let time = d.literal(query, "time");
d.executes(time, "time.query.time");
let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline));
d.executes(tl, "time.query.timeline");
let rep = d.literal(tl, "repetition");
d.executes(rep, "time.query.repetition");
}
/// FillCommand.wrapWithMode.
fn fill_modes(d: &mut Dispatcher, node: usize) {
d.executes(node, "fill");
for m in ["outline", "hollow", "destroy", "strict"] {
let l = d.literal(node, m);
d.executes(l, "fill");
}
}
fn clone_begin(d: &mut Dispatcher, node: usize) {
let begin = d.argument(node, "begin", ArgType::BlockPos);
let end = d.argument(begin, "end", ArgType::BlockPos);
clone_destination(d, end);
let to = d.literal(end, "to");
let dim = d.argument(to, "targetDimension", ArgType::Dimension);
clone_destination(d, dim);
}
fn clone_destination(d: &mut Dispatcher, node: usize) {
let dest = d.argument(node, "destination", ArgType::BlockPos);
clone_mask(d, dest);
let strict = d.literal(dest, "strict");
clone_mask(d, strict);
}
fn clone_mask(d: &mut Dispatcher, node: usize) {
d.executes(node, "clone");
for m in ["replace", "masked"] {
let l = d.literal(node, m);
clone_mode(d, l);
}
let filtered = d.literal(node, "filtered");
let filter = d.argument(filtered, "filter", ArgType::BlockPredicate);
clone_mode(d, filter);
}
fn clone_mode(d: &mut Dispatcher, node: usize) {
d.executes(node, "clone");
for m in ["force", "move", "normal"] {
let l = d.literal(node, m);
d.executes(l, "clone");
}
}
/// Game mode names for selector `gamemode=` and the argument.
pub fn game_modes() -> [&'static str; 4] {
GameMode::ALL.map(GameMode::name)
}
/// The shared vanilla tree.
pub fn dispatcher() -> &'static Dispatcher {
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
TREE.get_or_init(build)
}
#[allow(unused)]
const _: (u8, u8) = (ALL, GAMEMASTERS);