Files
horizon-airdef/crates/horizon-command/src/mod_tree.rs
T

245 lines
9.2 KiB
Rust

//! The command trees client mods describe (`command.set-tree`): literal
//! branches, typed words and numbers with bounds, optional branches, option
//! lists, put into a [`Dispatcher`] so the chat colours, completes and
//! checks them as it does vanilla's commands, and so the same parse decides
//! whether a line reaches the mod.
use crate::{ArgType, CmdResult, CommandError, Dispatcher, MOD_COMMAND, Reader, SuggestionsBuilder};
use horizon_client_core::text::Text;
use std::sync::Arc;
/// What one word takes.
#[derive(Clone, Debug, PartialEq)]
pub enum ModValue {
/// Any word; the given ones are suggested (a mod's `names` list included).
Word(Vec<String>),
Integer(Option<i32>, Option<i32>),
Number(Option<f64>, Option<f64>),
/// One of these words.
Choice(Vec<String>),
BlockPos,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ModOption {
pub key: String,
/// None: a bare flag.
pub value: Option<ModValue>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ModKind {
Value(ModValue),
/// The rest of the line.
Text,
Options {
entries: Vec<ModOption>,
/// Words that are no option, with the ones suggested; none refuses them.
free: Option<Vec<String>>,
},
}
/// A node of a flat tree: `children` index later nodes; node 0 follows the
/// command's name.
#[derive(Clone, Debug, PartialEq)]
pub struct ModNode {
pub name: String,
/// None: a literal.
pub kind: Option<ModKind>,
pub children: Vec<usize>,
pub runs: bool,
}
/// A word, and the words it may or must be.
#[derive(Debug, PartialEq)]
pub struct WordSet {
pub words: Vec<String>,
pub strict: bool,
}
impl WordSet {
pub fn parse(&self, reader: &mut Reader) -> CmdResult<String> {
let start = reader.cursor;
// A word is whatever stands up to the next space (a mod splits its line the same way).
let rest = reader.remaining();
let word = &rest[..rest.find(' ').unwrap_or(rest.len())];
reader.cursor += word.len();
let fail = |reader: &mut Reader, text: String| {
reader.cursor = start;
Err(CommandError::at(Text::literal(text), reader))
};
if word.is_empty() {
return fail(reader, "Expected a word".into());
}
if self.strict && !self.words.iter().any(|w| w == word) {
let list = self.words.join(", ");
return fail(reader, format!("Expected one of: {list}"));
}
Ok(word.to_owned())
}
}
/// `key=value` options and flags, taking the rest of the line in any order.
#[derive(Debug, PartialEq)]
pub struct OptionSet {
pub entries: Vec<ModOption>,
pub free: Option<Vec<String>>,
}
impl OptionSet {
fn entry(&self, key: &str) -> Option<&ModOption> {
self.entries.iter().find(|e| e.key == key)
}
/// The error for a value, or None when it is fine.
fn check(key: &str, kind: &ModValue, value: &str) -> Option<String> {
match kind {
ModValue::Integer(min, max) => match value.parse::<i32>() {
Err(_) => Some(format!("{key}: expected a whole number, found '{value}'")),
Ok(n) if min.is_some_and(|m| n < m) => {
Some(format!("{key}: must not be less than {}, found {n}", min.unwrap_or(0)))
}
Ok(n) if max.is_some_and(|m| n > m) => {
Some(format!("{key}: must not be more than {}, found {n}", max.unwrap_or(0)))
}
Ok(_) => None,
},
ModValue::Number(min, max) => match value.parse::<f64>() {
Ok(n) if n.is_finite() && min.is_none_or(|m| n >= m) && max.is_none_or(|m| n <= m) => None,
_ => Some(format!("{key}: expected a number in range, found '{value}'")),
},
ModValue::Choice(words) if !words.iter().any(|w| w == value) => {
Some(format!("{key}: expected one of: {}", words.join(", ")))
}
ModValue::Word(_) | ModValue::Choice(_) if value.is_empty() => {
Some(format!("{key}: expected a value"))
}
_ => None,
}
}
pub fn parse(&self, reader: &mut Reader) -> CmdResult<String> {
let text = reader.remaining();
let base = reader.cursor;
let mut used: Vec<&str> = Vec::new();
let mut at = 0;
for token in text.split(' ') {
let start = at;
at += token.len() + 1;
if token.is_empty() {
continue;
}
let fail = |reader: &mut Reader, message: String| {
reader.cursor = base + start;
Err(CommandError::at(Text::literal(message), reader))
};
let (key, value) = match token.split_once('=') {
Some((k, v)) => (k, Some(v)),
None => (token, None),
};
match (self.entry(key), value) {
(Some(e), v) => {
if used.contains(&key) {
return fail(reader, format!("'{key}' twice"));
}
match (&e.value, v) {
(None, None) => {}
(None, Some(_)) => return fail(reader, format!("'{key}' takes no value")),
(Some(_), None) => {
return fail(reader, format!("'{key}' needs a value: {key}=..."));
}
(Some(kind), Some(v)) => {
if let Some(m) = Self::check(key, kind, v) {
return fail(reader, m);
}
}
}
used.push(key);
}
(None, _) if self.free.is_some() && value.is_none() => {}
(None, _) => return fail(reader, format!("Unknown option '{token}'")),
}
}
reader.cursor = reader.string.len();
Ok(text.to_owned())
}
/// Candidates for the word being typed at the end of the line.
pub fn suggest(&self, builder: &mut SuggestionsBuilder) {
let rest = builder.remaining();
let token_start = builder.start + rest.rfind(' ').map_or(0, |i| i + 1);
let before = &rest[..token_start - builder.start];
let used: Vec<&str> = before
.split(' ')
.filter(|t| !t.is_empty())
.map(|t| t.split('=').next().unwrap_or(t))
.collect();
let mut b = builder.offset(token_start);
let typed = b.remaining().to_owned();
if let Some((key, value)) = typed.split_once('=') {
// A value: the choices of a valued option, after its `key=`.
if let Some(ModOption { value: Some(ModValue::Choice(words) | ModValue::Word(words)), .. }) = self.entry(key) {
let mut v = builder.offset(token_start + key.len() + 1);
let _ = value;
v.suggest_matching(words.iter().map(String::as_str));
builder.add(v);
}
return;
}
for e in &self.entries {
if used.contains(&e.key.as_str()) {
continue;
}
let text = if e.value.is_some() { format!("{}=", e.key) } else { e.key.clone() };
if text.starts_with(&typed) {
b.suggest(text);
}
}
if let Some(free) = &self.free {
b.suggest_matching(free.iter().map(String::as_str));
}
builder.add(b);
}
}
fn value_type(kind: &ModValue) -> ArgType {
match kind {
ModValue::Word(words) => ArgType::ModWord(Arc::new(WordSet { words: words.clone(), strict: false })),
ModValue::Choice(words) => ArgType::ModWord(Arc::new(WordSet { words: words.clone(), strict: true })),
ModValue::Integer(min, max) => ArgType::Integer {
min: min.unwrap_or(i32::MIN),
max: max.unwrap_or(i32::MAX),
},
ModValue::Number(min, max) => ArgType::Double {
min: min.unwrap_or(f64::MIN),
max: max.unwrap_or(f64::MAX),
},
ModValue::BlockPos => ArgType::BlockPos,
}
}
/// Adds the tree `nodes` below the command's literal `command`.
pub fn build(d: &mut Dispatcher, command: usize, nodes: &[ModNode]) {
fn add(d: &mut Dispatcher, parent: usize, nodes: &[ModNode], i: usize) {
let n = &nodes[i];
let id = match &n.kind {
None => d.literal(parent, &n.name),
Some(ModKind::Value(v)) => d.argument(parent, &n.name, value_type(v)),
Some(ModKind::Text) => d.argument(parent, &n.name, ArgType::Greedy),
Some(ModKind::Options { entries, free }) => d.argument(
parent,
&n.name,
ArgType::ModOptions(Arc::new(OptionSet { entries: entries.clone(), free: free.clone() })),
),
};
if n.runs {
d.executes(id, MOD_COMMAND);
}
for &c in &n.children {
if c > i && c < nodes.len() {
add(d, id, nodes, c);
}
}
}
let root = &nodes[0];
if root.runs {
d.executes(command, MOD_COMMAND);
}
for &c in &root.children {
if c > 0 && c < nodes.len() {
add(d, command, nodes, c);
}
}
}