Skip to main content

sim_core/
config.rs

1//! Machine configuration: one TOML file per machine, with a format version and units in the field names.
2
3use toml::{Table, Value};
4
5pub const FORMAT_VERSION: i64 = 1;
6
7/// The limit that the shared readers (`Config::positive`, `non_negative`, `f64`) refused a value for.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Bound {
10    /// Above zero (`positive`).
11    Positive,
12    /// Zero or above (`non_negative`).
13    NonNegative,
14    /// Not a finite number of at most 1e15 in size (`number`).
15    Number,
16}
17
18/// Carries a translation key and a detail (usually the config path), never display text.
19#[derive(Debug, Clone)]
20pub enum ConfigError {
21    Parse(String),
22    Version(String),
23    Missing(String),
24    Type(String),
25    Invalid(String),
26    /// `Invalid` at a path, with the limit it broke where a shared reader knows it: the same key and detail as
27    /// `Invalid` (and equal to it), so that a front end that does not look at the limit shows what it always did.
28    Bounded(Bound, String),
29    /// A key that the machine's default config does not have.
30    Unknown(String),
31    /// A value refused for a reason with a message of its own: the translation key, and the value's name (a part name
32    /// that the catalogue does not have, under the key for its kind; a pose the machine cannot reach, at its path).
33    Part(&'static str, String),
34}
35
36impl ConfigError {
37    pub fn key(&self) -> &'static str {
38        match self {
39            Self::Parse(_) => "error-config-parse",
40            Self::Version(_) => "error-config-version",
41            Self::Missing(_) => "error-config-missing",
42            Self::Type(_) => "error-config-type",
43            Self::Invalid(_) | Self::Bounded(..) => "error-config-invalid",
44            Self::Unknown(_) => "error-config-unknown",
45            Self::Part(key, _) => key,
46        }
47    }
48    pub fn detail(&self) -> &str {
49        match self {
50            Self::Parse(d)
51            | Self::Version(d)
52            | Self::Missing(d)
53            | Self::Type(d)
54            | Self::Invalid(d)
55            | Self::Bounded(_, d)
56            | Self::Unknown(d)
57            | Self::Part(_, d) => d,
58        }
59    }
60}
61
62/// Errors are equal when key and detail are: what every test and front end goes by, so `Bounded` equals `Invalid`.
63impl PartialEq for ConfigError {
64    fn eq(&self, other: &Self) -> bool {
65        (self.key(), self.detail()) == (other.key(), other.detail())
66    }
67}
68
69/// What `Config::hint` finds to say beside an error.
70#[derive(Debug, Clone, PartialEq)]
71pub enum ConfigHint {
72    /// The path of the config nearest to the misspelt one.
73    Nearest(String),
74    /// The value (in TOML syntax) at the path that was refused.
75    Value(String),
76    /// The value that was refused, and the limit it broke.
77    Bounded(String, Bound),
78}
79
80/// The Levenshtein distance of two strings, in characters.
81fn edit_distance(a: &str, b: &str) -> usize {
82    let b: Vec<char> = b.chars().collect();
83    let mut row: Vec<usize> = (0..=b.len()).collect();
84    for (i, ca) in a.chars().enumerate() {
85        let mut diagonal = std::mem::replace(&mut row[0], i + 1);
86        for (j, cb) in b.iter().enumerate() {
87            let above = row[j + 1];
88            row[j + 1] = (diagonal + usize::from(ca != *cb)).min(above + 1).min(row[j] + 1);
89            diagonal = above;
90        }
91    }
92    row[b.len()]
93}
94
95type Result<T> = std::result::Result<T, ConfigError>;
96
97#[derive(Debug, Clone, PartialEq)]
98pub struct Config(Table);
99
100impl Config {
101    pub fn parse(text: &str) -> Result<Self> {
102        let table: Table = text.parse().map_err(|e: toml::de::Error| ConfigError::Parse(e.to_string()))?;
103        match table.get("format_version").and_then(Value::as_integer) {
104            Some(FORMAT_VERSION) => Ok(Self(table)),
105            other => Err(ConfigError::Version(format!("{other:?}"))),
106        }
107    }
108
109    pub fn get(&self, path: &str) -> Result<&Value> {
110        let mut parts = path.split('.');
111        let mut value = self.0.get(parts.next().unwrap_or(""));
112        for part in parts {
113            value = value.and_then(|v| v.get(part));
114        }
115        value.ok_or_else(|| ConfigError::Missing(path.into()))
116    }
117
118    /// A number. NaN and infinity are valid TOML and a value of no quantity, so they never pass; nor does a number beyond
119    /// 1e15 or, but for zero, below 1e-15 in size (`number`).
120    pub fn f64(&self, path: &str) -> Result<f64> {
121        number(as_f64(self.get(path)?).ok_or_else(|| ConfigError::Type(path.into()))?, path)
122    }
123
124    /// A value that may be zero but not negative (dampings, frictions, a payload).
125    pub fn non_negative(&self, path: &str) -> Result<f64> {
126        let v = self.f64(path)?;
127        if v >= 0.0 { Ok(v) } else { Err(ConfigError::Bounded(Bound::NonNegative, path.into())) }
128    }
129
130    /// A value that must be strictly positive (masses, radii, stiffnesses, cycle times).
131    pub fn positive(&self, path: &str) -> Result<f64> {
132        let v = self.f64(path)?;
133        if v > 0.0 && v.is_finite() { Ok(v) } else { Err(ConfigError::Bounded(Bound::Positive, path.into())) }
134    }
135
136    pub fn bool(&self, path: &str) -> Result<bool> {
137        self.get(path)?.as_bool().ok_or_else(|| ConfigError::Type(path.into()))
138    }
139
140    pub fn f64s(&self, path: &str) -> Result<Vec<f64>> {
141        let err = || ConfigError::Type(path.into());
142        self.get(path)?.as_array().ok_or_else(err)?.iter().map(|v| number(as_f64(v).ok_or_else(err)?, path)).collect()
143    }
144
145    /// Refuses a key that neither `schema` (a machine's default config) nor `optional` has, so that a
146    /// misspelt key in a config file cannot pass silently. `[bounds]` is left out: it has its own check, and
147    /// so are the entries of arrays, which the code that reads them checks.
148    pub fn check_keys(&self, schema: &Config, optional: &[&str]) -> Result<()> {
149        fn walk(prefix: &str, table: &Table, schema: &Config, optional: &[&str]) -> Result<()> {
150            for (key, value) in table {
151                let path = if prefix.is_empty() { key.clone() } else { format!("{prefix}.{key}") };
152                if path == "bounds" {
153                    continue;
154                }
155                if schema.get(&path).is_err() && !optional.contains(&path.as_str()) {
156                    return Err(ConfigError::Unknown(path));
157                }
158                if let Value::Table(t) = value {
159                    walk(&path, t, schema, optional)?;
160                }
161            }
162            Ok(())
163        }
164        walk("", &self.0, schema, optional)
165    }
166
167    pub fn array(&self, path: &str) -> Result<&Vec<Value>> {
168        self.get(path)?.as_array().ok_or_else(|| ConfigError::Type(path.into()))
169    }
170
171    /// Overwrites an existing value. New keys and type changes are rejected, so a typo cannot pass silently.
172    pub fn set(&mut self, path: &str, value: Value) -> Result<()> {
173        // A version `parse` would refuse is refused here too: a config set to it could be written but not read again
174        // (found by the property test of `set_text`, 15 November 2026).
175        if path == "format_version" && value.as_integer() != Some(FORMAT_VERSION) {
176            return Err(ConfigError::Version(format!("{:?}", value.as_integer())));
177        }
178        let value = of_type(self.get(path)?, value, path)?;
179        self.insert(path, value)
180    }
181
182    /// `set`, and where the config has not got `path`, adds it where a file may have it (`check_keys` with the same
183    /// `schema` and `optional` takes it): in the type `schema` has there, or as given for a key of `optional`. A path of
184    /// neither is refused as by `set` (`Missing`), so a misspelt key still cannot pass silently.
185    pub fn set_within(&mut self, path: &str, value: Value, schema: &Config, optional: &[&str]) -> Result<()> {
186        if path == "format_version" || self.get(path).is_ok() {
187            return self.set(path, value);
188        }
189        let value = match schema.get(path) {
190            Ok(Value::Table(_)) => return Err(ConfigError::Type(path.into())),
191            Ok(old) => of_type(old, value, path)?,
192            Err(_) if optional.contains(&path) && !value.is_table() => value,
193            Err(e) => return Err(e),
194        };
195        self.insert(path, value)
196    }
197
198    /// `value` at `path`, with the tables on the way made where they are missing.
199    fn insert(&mut self, path: &str, value: Value) -> Result<()> {
200        let (parents, leaf) = path.rsplit_once('.').unwrap_or(("", path));
201        let mut table = &mut self.0;
202        for part in parents.split('.').filter(|p| !p.is_empty()) {
203            table = table
204                .entry(part)
205                .or_insert_with(|| Value::Table(Table::new()))
206                .as_table_mut()
207                .ok_or_else(|| ConfigError::Type(path.into()))?;
208        }
209        table.insert(leaf.into(), value);
210        Ok(())
211    }
212
213    /// Applies one `path=value` assignment, with the value in TOML syntax.
214    pub fn set_text(&mut self, assignment: &str) -> Result<()> {
215        let (path, value) = assignment_of(assignment)?;
216        self.set(path, value)
217    }
218
219    /// `set_text` as `set_within` adds a key.
220    pub fn set_text_within(&mut self, assignment: &str, schema: &Config, optional: &[&str]) -> Result<()> {
221        let (path, value) = assignment_of(assignment)?;
222        self.set_within(path, value, schema, optional)
223    }
224
225    /// The config as TOML text, which `parse` reads back to the same config. Comments are not kept.
226    pub fn to_text(&self) -> Result<String> {
227        toml::to_string(&self.0).map_err(|e| ConfigError::Parse(e.to_string()))
228    }
229
230    /// Extra help for an error of this config, for a front end to append to its message (the error itself, its key and
231    /// its detail stay as they are): for a path that is missing or unknown the nearest path the config has, where one
232    /// is close (at most 2 edits, or a third of the path's length); for a value out of range or of the wrong type the
233    /// value the path has.
234    pub fn hint(&self, error: &ConfigError) -> Option<ConfigHint> {
235        self.hint_within(error, &Config(Table::new()), &[])
236    }
237
238    /// `hint`, with the paths `set_within` may add (`schema`'s and `optional`) among those a misspelt one is near.
239    pub fn hint_within(&self, error: &ConfigError, schema: &Config, optional: &[&str]) -> Option<ConfigHint> {
240        // A float as Rust writes it: 1e300, where TOML's text spells out all 301 digits.
241        let shown = |value: &Value| match value {
242            Value::Float(f) if f.is_finite() => format!("{f:?}"),
243            other => other.to_string(),
244        };
245        match error {
246            ConfigError::Missing(path) | ConfigError::Unknown(path) => {
247                let near = path.chars().count().div_ceil(3).max(2);
248                let paths = self.leaves().into_iter().chain(schema.leaves()).map(|(p, _)| p);
249                let paths = paths.chain(optional.iter().map(|p| p.to_string()));
250                let (distance, nearest) = paths.map(|p| (edit_distance(path, &p), p)).min_by_key(|(d, _)| *d)?;
251                (distance > 0 && distance <= near).then_some(ConfigHint::Nearest(nearest))
252            }
253            ConfigError::Bounded(bound, path) => {
254                self.get(path).ok().map(|value| ConfigHint::Bounded(shown(value), *bound))
255            }
256            ConfigError::Invalid(path) | ConfigError::Type(path) => {
257                self.get(path).ok().map(|value| ConfigHint::Value(shown(value)))
258            }
259            _ => None,
260        }
261    }
262
263    /// Every scalar value with its dotted path, for the parameter panel and the translation check.
264    pub fn leaves(&self) -> Vec<(String, Value)> {
265        fn walk(prefix: &str, table: &Table, out: &mut Vec<(String, Value)>) {
266            for (key, value) in table {
267                let path = if prefix.is_empty() { key.clone() } else { format!("{prefix}.{key}") };
268                match value {
269                    Value::Table(t) => walk(&path, t, out),
270                    Value::Array(_) => {}
271                    v => out.push((path, v.clone())),
272                }
273            }
274        }
275        let mut out = Vec::new();
276        walk("", &self.0, &mut out);
277        out
278    }
279}
280
281/// The largest and the smallest non-zero size of a number a config may hold, in its SI unit. The shipped configs and the
282/// catalogue lie between 1e-6 (an encoder step, m) and 2.1e11 (steel's Young's modulus, Pa); a value beyond is a slip
283/// of the exponent, and 1e30 or 1e-30 in a stiffness, damping, inductance or ratio overflowed the integration to NaN.
284const LARGEST: f64 = 1e15;
285const SMALLEST: f64 = 1e-15;
286
287/// `value` as a config's number at `path`, for a reader that takes it from TOML itself: refused out of range.
288pub fn number(value: f64, path: &str) -> Result<f64> {
289    if value.abs() < SMALLEST {
290        // What is left of a sum in floating point (a pose of 5e-17 m) is zero, not a slip of the exponent; as zero, a
291        // key that must be positive still refuses it.
292        Ok(0.0)
293    } else if value.abs() <= LARGEST {
294        Ok(value)
295    } else {
296        Err(ConfigError::Bounded(Bound::Number, path.into()))
297    }
298}
299
300/// The path and the value (TOML syntax) of one `path=value` assignment.
301fn assignment_of(assignment: &str) -> Result<(&str, Value)> {
302    let bad = || ConfigError::Parse(assignment.into());
303    let (path, value) = assignment.split_once('=').ok_or_else(bad)?;
304    let mut parsed: Table = format!("v = {value}").parse().map_err(|_| bad())?;
305    // One assignment: a second line ("a = 1\nb = 2") parsed beside `v` and was dropped without a word.
306    if parsed.len() != 1 {
307        return Err(bad());
308    }
309    Ok((path.trim(), parsed.remove("v").ok_or_else(bad)?))
310}
311
312/// `new` in the type of `old`: an integer where a float was is the float, any other change of type is refused.
313fn of_type(old: &Value, new: Value, path: &str) -> Result<Value> {
314    match (old, new) {
315        (Value::Float(_), Value::Integer(i)) => Ok(Value::Float(i as f64)),
316        (old, new) if old.same_type(&new) => Ok(new),
317        _ => Err(ConfigError::Type(path.into())),
318    }
319}
320
321fn as_f64(value: &Value) -> Option<f64> {
322    match value {
323        Value::Float(f) => Some(*f),
324        Value::Integer(i) => Some(*i as f64),
325        _ => None,
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    const TEXT: &str = "format_version = 1\n[a]\nmass_kg = 2.0\non = true\n[a.b]\nlist = [1, 2.5]\n";
334
335    /// A typo of one letter finds the path it was meant for (also one missing from the config altogether, `Unknown`), a
336    /// name far off finds none, a path of the config itself is no typo of itself, and a refused value is shown.
337    #[test]
338    fn hints_name_the_nearest_path_and_the_value() {
339        let c = Config::parse(TEXT).unwrap();
340        let near = |p: &str| c.hint(&ConfigError::Missing(p.into()));
341        assert_eq!(near("a.mas_kg"), Some(ConfigHint::Nearest("a.mass_kg".into())));
342        assert_eq!(c.hint(&ConfigError::Unknown("a.onn".into())), Some(ConfigHint::Nearest("a.on".into())));
343        assert_eq!(near("something.entirely_else"), None);
344        assert_eq!(near("a.mass_kg"), None);
345        assert_eq!(c.hint(&ConfigError::Invalid("a.mass_kg".into())), Some(ConfigHint::Value("2.0".into())));
346        assert_eq!(c.hint(&ConfigError::Invalid("a.nowhere".into())), None);
347        assert_eq!(c.hint(&ConfigError::Parse("x".into())), None);
348        assert_eq!(edit_distance("kitten", "sitting"), 3);
349    }
350
351    /// A value refused by a shared reader is shown with the limit it broke (`positive`: above zero, `non_negative`: not
352    /// below zero, `f64`: size), under the same key and detail as any `Invalid`; a site that checks for itself
353    /// (`Invalid`) is shown with its value only.
354    #[test]
355    fn hints_name_the_limit_a_shared_reader_refused() {
356        let c = Config::parse("format_version = 1\nzero = 0.0\nneg = -5.5\nbig = 1e20\n").unwrap();
357        let hint = |e: Result<f64>| c.hint(&e.unwrap_err());
358        assert_eq!(hint(c.positive("neg")), Some(ConfigHint::Bounded("-5.5".into(), Bound::Positive)));
359        assert_eq!(hint(c.positive("zero")), Some(ConfigHint::Bounded("0.0".into(), Bound::Positive)));
360        assert_eq!(hint(c.non_negative("neg")), Some(ConfigHint::Bounded("-5.5".into(), Bound::NonNegative)));
361        assert_eq!(hint(c.f64("big")), Some(ConfigHint::Bounded("1e20".into(), Bound::Number)));
362        let refused = c.positive("neg").unwrap_err();
363        assert_eq!((refused.key(), refused.detail()), ("error-config-invalid", "neg"));
364        assert_eq!(refused, ConfigError::Invalid("neg".into()));
365        assert_eq!(c.hint(&ConfigError::Invalid("neg".into())), Some(ConfigHint::Value("-5.5".into())));
366    }
367
368    #[test]
369    fn reads_values_by_path() {
370        let c = Config::parse(TEXT).unwrap();
371        assert_eq!(c.f64("a.mass_kg").unwrap(), 2.0);
372        assert!(c.bool("a.on").unwrap());
373        assert_eq!(c.f64s("a.b.list").unwrap(), vec![1.0, 2.5]);
374        assert_eq!(c.f64("a.nope"), Err(ConfigError::Missing("a.nope".into())));
375        assert_eq!(c.f64("a.on"), Err(ConfigError::Type("a.on".into())));
376    }
377
378    #[test]
379    fn rejects_wrong_format_version() {
380        assert!(matches!(Config::parse("format_version = 2"), Err(ConfigError::Version(_))));
381        assert!(matches!(Config::parse("x = 1"), Err(ConfigError::Version(_))));
382        let mut cfg = Config::parse("format_version = 1").unwrap();
383        assert!(matches!(cfg.set_text("format_version = 2"), Err(ConfigError::Version(_))));
384        assert!(cfg.set_text("format_version = 1").is_ok() && Config::parse(&cfg.to_text().unwrap()).is_ok());
385    }
386
387    #[test]
388    fn set_keeps_types_and_rejects_new_keys() {
389        let mut c = Config::parse(TEXT).unwrap();
390        c.set_text("a.mass_kg = 3").unwrap();
391        assert_eq!(c.f64("a.mass_kg").unwrap(), 3.0);
392        c.set_text("a.on=false").unwrap();
393        assert!(!c.bool("a.on").unwrap());
394        assert!(c.set_text("a.typo = 1").is_err());
395        assert!(c.set_text("a.on = 1").is_err());
396        assert_eq!(c.leaves().len(), 3);
397    }
398
399    /// A key the config has not got is added where the schema has it (in the schema's type: an integer for a float is the
400    /// float, a bool for it refused) or the optional list names it, with its tables; a misspelt one is still refused, and
401    /// the hint finds the key it was meant for among those it could have added.
402    #[test]
403    fn set_within_adds_the_keys_a_file_may_have() {
404        let schema = Config::parse("format_version = 1\n[a]\nmass_kg = 2.0\n[d.x]\nkp = 0.5\n").unwrap();
405        let optional = ["r.altitude_m"];
406        let mut c = Config::parse("format_version = 1\n[a]\nmass_kg = 2.0\n").unwrap();
407        c.set_text_within("d.x.kp = 1", &schema, &optional).unwrap();
408        assert_eq!(c.get("d.x.kp"), Ok(&Value::Float(1.0)));
409        c.set_text_within("r.altitude_m = 2000", &schema, &optional).unwrap();
410        assert_eq!(c.f64("r.altitude_m"), Ok(2000.0));
411        assert_eq!(c.set_text_within("a.mass_kg = 3", &schema, &optional), Ok(()));
412        assert_eq!(c.set_text_within("d.x.kp = true", &schema, &optional), Err(ConfigError::Type("d.x.kp".into())));
413        assert_eq!(c.set_text_within("d.x = 1", &schema, &optional), Err(ConfigError::Type("d.x".into())));
414        let misspelt = c.set_text_within("r.altitud_m = 2000", &schema, &optional).unwrap_err();
415        assert_eq!(misspelt, ConfigError::Missing("r.altitud_m".into()));
416        let fresh = Config::parse("format_version = 1\n").unwrap();
417        assert_eq!(fresh.hint_within(&misspelt, &schema, &optional), Some(ConfigHint::Nearest("r.altitude_m".into())));
418        assert_eq!(fresh.hint(&misspelt), None);
419        assert_eq!(Config::parse(&c.to_text().unwrap()), Ok(c));
420    }
421
422    /// NaN and infinity are numbers to TOML and to no component: no read lets them through.
423    #[test]
424    fn numbers_that_are_not_finite_or_negative_are_refused_with_their_key() {
425        let c = Config::parse("format_version = 1\na = nan\nb = -inf\nc = [1.0, nan]\nd = -1.0\ne = 0.0\n").unwrap();
426        for path in ["a", "b"] {
427            assert_eq!(c.f64(path), Err(ConfigError::Invalid(path.into())));
428            assert_eq!(c.positive(path), Err(ConfigError::Invalid(path.into())));
429            assert_eq!(c.non_negative(path), Err(ConfigError::Invalid(path.into())));
430        }
431        assert_eq!(c.f64s("c"), Err(ConfigError::Invalid("c".into())));
432        assert_eq!((c.f64("d"), c.non_negative("d")), (Ok(-1.0), Err(ConfigError::Invalid("d".into()))));
433        assert_eq!(c.non_negative("e"), Ok(0.0));
434    }
435
436    /// The default config is the schema: a key it does not have is refused by name, except under `[bounds]`
437    /// and where it is named as optional.
438    #[test]
439    fn a_key_the_schema_does_not_have_is_refused() {
440        let schema = Config::parse(TEXT).unwrap();
441        let file = |text: &str| {
442            Config::parse(&format!("format_version = 1\n{text}")).unwrap().check_keys(&schema, &["a.more_kg"])
443        };
444        assert_eq!(file("[a]\nmass_kg = 3.0\nmore_kg = 1.0\n[bounds]\nanything = [1, 2]\n"), Ok(()));
445        assert_eq!(file("[a]\nmas_kg = 3.0\n"), Err(ConfigError::Unknown("a.mas_kg".into())));
446        assert_eq!(file("[a.b]\nlist = [1]\nmore = 1\n"), Err(ConfigError::Unknown("a.b.more".into())));
447        assert_eq!(file("[typo]\nx = 1\n"), Err(ConfigError::Unknown("typo".into())));
448    }
449}