Skip to main content

sim_netlist/
lib.rs

1//! Machines defined in a file, without Rust code: a machine config (the tables every machine has: `[sim]`,
2//! `[effects]`, `[belt]`, `[motor]`, `[drive]`, `[ratings]`, `[cycle]`, ...) plus a `[machine]` table that wires
3//! components together as a netlist (see `netlist::NODES` and docs/machine-files.md).
4//!
5//! `from_text` checks a file's text into a `MachineEntry` that every front end takes like a registered machine;
6//! `sim_machines::load_file` reads the file (TOML, or JSON converted).
7
8pub mod geometry;
9pub mod linkage;
10pub mod machine;
11pub mod netlist;
12pub mod scissor;
13pub mod spatial;
14pub mod worm;
15
16pub use machine::ConfigMachine;
17pub use netlist::{Netlist, VERSION, json_schema};
18
19use machine::intern;
20use sim_core::{Config, ConfigError, Machine, MachineEntry};
21use std::collections::HashMap;
22use std::fmt;
23use std::path::PathBuf;
24use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
25use toml::{Table, Value};
26
27/// `MachineEntry::build` of every machine file: the netlist is in the config itself.
28pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
29    let machine = build_without_cylinders(cfg)?;
30    let cylinders = netlist::cylinders(cfg)?;
31    if cylinders.is_empty() {
32        return Ok(machine);
33    }
34    // The tool's axes, as `ConfigMachine` lays them: the first along x, the others along y, each up by its incline.
35    let carrying: Vec<_> = (Netlist::parse(cfg)?.axes.iter().enumerate())
36        .map(|(i, a)| {
37            let (up, across) = a.incline_deg.to_radians().sin_cos();
38            (a.id.clone(), (!a.rotary).then_some(if i == 0 { [across, 0.0, up] } else { [0.0, across, up] }))
39        })
40        .collect();
41    sim_components::pneumatic::attach(cfg, &cylinders, &carrying, machine)
42}
43
44fn build_without_cylinders(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
45    let net = Netlist::parse(cfg)?;
46    if let Some(scissor) = &net.scissor {
47        return sim_components::base::mount(cfg, Box::new(scissor::ScissorMachine::from_node(cfg, &net, scissor)?));
48    }
49    match &net.linkage {
50        Some(linkage) if linkage.gearboxes.len() == 3 => {
51            sim_components::base::mount(cfg, Box::new(spatial::Delta::from_node(cfg, &net, linkage)?))
52        }
53        Some(linkage) => {
54            sim_components::base::mount(cfg, Box::new(linkage::LinkageMachine::from_node(cfg, &net, linkage)?))
55        }
56        None => sim_components::base::mount(cfg, Box::new(ConfigMachine::new(cfg, &net)?)),
57    }
58}
59
60/// shortcut: a machine file brings no loss-free configs for the standard suite; the tests build their own.
61fn no_suite_configs() -> Vec<Config> {
62    Vec::new()
63}
64
65/// Why a machine file was refused: the file, the line the error is on where it can be found, and the error (a
66/// translation key and the config path it is about).
67#[derive(Debug, Clone, PartialEq)]
68pub struct FileError {
69    pub file: PathBuf,
70    pub line: Option<usize>,
71    pub error: ConfigError,
72}
73
74impl fmt::Display for FileError {
75    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76        write!(f, "{}", self.file.display())?;
77        if let Some(line) = self.line {
78            write!(f, ":{line}")?;
79        }
80        write!(f, ": {}: {}", self.error.key(), self.error.detail())
81    }
82}
83
84impl std::error::Error for FileError {}
85
86/// A machine file's TOML text, checked in full: the netlist, every key against `known` (the default configs of the
87/// registered machines, whose tables a machine file shares), and every value the machine and the simulation read.
88/// `fallback_id` names the machine where `machine.id` does not. `lines` says whether the text is the file as written,
89/// so that an error can name its line (a JSON file arrives here converted, and its lines are not these). The entry
90/// lives as long as the program. Files are read, and JSON converted, by `sim_machines::load_file`.
91pub fn from_text(
92    toml_text: &str,
93    lines: bool,
94    fallback_id: &str,
95    known: &[Config],
96) -> Result<&'static MachineEntry, (ConfigError, Option<usize>)> {
97    // What decides the result: the text, whether its lines are the file's (the error's line), and the id taken where
98    // the text has none. `known` is the registered machines' configs, fixed for the program; the catalogue is chosen
99    // before any part is looked up (`catalog::use_directory`), so it cannot change an entry already checked.
100    let key = (toml_text.to_string(), lines, fallback_id.to_string());
101    if let Some(&entry) = cache().get(&key) {
102        return Ok(entry);
103    }
104    let located = |e: ConfigError| {
105        let line = if lines { line_of(toml_text, e.detail()) } else { None };
106        (e, line)
107    };
108    let cfg = Config::parse(toml_text).map_err(|e| (e, None))?;
109    let net = Netlist::parse(&cfg).map_err(located)?;
110    cfg.check_keys(&schema(&cfg, &net, known), &sim_components::analysis::RATINGS_BEYOND_DEFAULT).map_err(located)?;
111    let text_of = |key: &str| cfg.get(key).ok().and_then(Value::as_str).map(str::to_string);
112    let id = text_of("machine.id").unwrap_or_else(|| fallback_id.to_string());
113    let name = text_of("machine.name").unwrap_or_else(|| id.clone());
114    // Everything the simulation reads at its start, with the parts the file names from the catalogue. Checked on an
115    // entry that is not kept (the simulation reads only its `build`), so a refused file leaks nothing.
116    let probe = MachineEntry { id: "", key: "", default_config: "", i18n: &[], build, suite_configs: no_suite_configs };
117    sim_components::Sim::new(&probe, &cfg).map_err(located)?;
118    let mut cache = cache();
119    // Another thread may have kept the same text meanwhile: its entry stays the one.
120    let entry = *cache.entry(key).or_insert_with(|| {
121        Box::leak(Box::new(MachineEntry {
122            id: intern(&id),
123            key: intern(&name),
124            default_config: Box::leak(toml_text.to_string().into_boxed_str()),
125            ..probe
126        }))
127    });
128    Ok(entry)
129}
130
131type Cache = HashMap<(String, bool, String), &'static MachineEntry>;
132
133/// The entries `from_text` has kept, by what decides them: a file loaded again (a sweep, an FMU made in a loop) is the
134/// same entry, not a new leaked one.
135fn cache() -> MutexGuard<'static, Cache> {
136    static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
137    CACHE.get_or_init(Default::default).lock().unwrap_or_else(PoisonError::into_inner)
138}
139
140/// How many entries `from_text` keeps: what a test reads to see that a refused file adds none.
141#[doc(hidden)]
142pub fn kept_entries() -> usize {
143    cache().len()
144}
145
146/// The keys a machine file may have: every key of a registered machine's default config, `[machine]`, every value
147/// the netlist names by its path (`"geometry.stroke_y_m"`), and per axis and guide of the netlist an `[axis.<id>]` and
148/// a friction table laid out as theirs.
149fn schema(cfg: &Config, net: &Netlist, known: &[Config]) -> Config {
150    fn merge(into: &mut Table, from: &Table) {
151        for (key, value) in from {
152            match (into.get_mut(key), value) {
153                (Some(Value::Table(a)), Value::Table(b)) => merge(a, b),
154                (None, v) => {
155                    into.insert(key.clone(), v.clone());
156                }
157                _ => {}
158            }
159        }
160    }
161    let mut all = Table::new();
162    for c in known {
163        if let Ok(text) = c.to_text() {
164            merge(&mut all, &text.parse().unwrap_or_default());
165        }
166    }
167    let axis = all.get("axis").and_then(|a| a.get("x")).cloned().unwrap_or_else(|| Value::Table(Table::new()));
168    let friction = all.get("friction_x").cloned().unwrap_or_else(|| Value::Table(Table::new()));
169    // A rotary axis's limits are in rad: max_velocity_rad_s, as the registered rotary table names them.
170    let turning = match &axis {
171        Value::Table(t) => Value::Table(t.iter().map(|(k, v)| (k.replace("_m_s", "_rad_s"), v.clone())).collect()),
172        other => other.clone(),
173    };
174    let mut axes = Table::new();
175    for a in &net.axes {
176        axes.insert(a.id.clone(), if a.rotary { turning.clone() } else { axis.clone() });
177    }
178    all.insert("axis".into(), Value::Table(axes));
179    // A motor's own tables (`catalog::motor_config`), laid out as the shared ones; a process force per axis.
180    for table in sim_components::catalog::PER_MOTOR_TABLES {
181        if let Some(Value::Table(shared)) = all.get(table).cloned() {
182            let plain: Table = shared.into_iter().filter(|(_, v)| !v.is_table()).collect();
183            if let Some(Value::Table(t)) = all.get_mut(table) {
184                for m in &net.motors {
185                    t.insert(m.id.clone(), Value::Table(plain.clone()));
186                }
187            }
188        }
189    }
190    if let Some(Value::Table(process)) = all.get_mut("process") {
191        for a in &net.axes {
192            process.insert(format!("force_{}_n", a.id), Value::Float(0.0));
193        }
194    }
195    for g in &net.guides {
196        // At a dotted path ("friction.x") as nested tables; where a known value is in the way, the file's table there
197        // stays unknown and is refused by name.
198        let nested = g
199            .friction
200            .rsplit('.')
201            .fold(friction.clone(), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
202        if let Value::Table(nested) = nested {
203            merge(&mut all, &nested);
204        }
205    }
206    // The value tables of screws, racks, linear motors and strain wave gears, laid out as the registered one-axis machines'.
207    for (layout, path) in &net.values {
208        let Some(known) = all.get(*layout).cloned() else { continue };
209        let nested =
210            path.rsplit('.').fold(known, |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
211        if let Value::Table(nested) = nested {
212            merge(&mut all, &nested);
213        }
214    }
215    for path in &net.refs {
216        let nested = path
217            .rsplit('.')
218            .fold(Value::Float(0.0), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
219        if let Value::Table(nested) = nested {
220            merge(&mut all, &nested);
221        }
222    }
223    // A dual-drive gantry's synchronisation (`gantry.sync`, read by the controller).
224    if net.gantry.as_ref().is_some_and(|g| g.drives.iter().flatten().count() >= 2) {
225        let sync = Table::from_iter([
226            ("sync".to_string(), Value::String("plain".into())),
227            ("sync_gain_1_s".to_string(), Value::Float(0.0)),
228        ]);
229        merge(&mut all, &Table::from_iter([("gantry".to_string(), Value::Table(sync))]));
230    }
231    // A pneumatic cylinder's table at its `values` path, and the effect switches only cylinders have.
232    for node in netlist::cylinders(cfg).unwrap_or_default() {
233        let table: Table = sim_components::pneumatic::TABLE.parse().unwrap_or_default();
234        let nested = node
235            .values
236            .rsplit('.')
237            .fold(Value::Table(table), |inner, part| Value::Table(Table::from_iter([(part.to_string(), inner)])));
238        let effects = sim_components::pneumatic::EFFECTS.map(|e| (e.to_string(), Value::Boolean(true)));
239        if let Value::Table(nested) = nested {
240            merge(&mut all, &nested);
241        }
242        merge(&mut all, &Table::from_iter([("effects".to_string(), Value::Table(Table::from_iter(effects)))]));
243    }
244    if let Ok(machine) = cfg.get("machine") {
245        all.insert("machine".into(), machine.clone());
246    }
247    all.insert("format_version".into(), Value::Integer(sim_core::config::FORMAT_VERSION));
248    Config::parse(&toml::to_string(&all).unwrap_or_default()).unwrap_or_else(|_| cfg.clone())
249}
250
251/// The line (from 1) of a TOML text that an error's path is about: `machine.<list>[<id>].<field>` (or `[#<n>]`, the
252/// n-th node of the list), or a dotted key `table.sub.key`. Falls back to the node or the table; `None` where neither
253/// is in the text.
254pub fn line_of(text: &str, detail: &str) -> Option<usize> {
255    let path = detail.split([' ', '(']).next().unwrap_or_default();
256    let lines: Vec<&str> = text.lines().collect();
257    let header = |line: &str| line.trim_start().starts_with('[');
258    let header_name =
259        |line: &str| line.split('#').next().unwrap_or_default().trim().trim_matches(['[', ']']).trim().to_string();
260    let key_of = |line: &str| line.split('=').next().unwrap_or_default().trim().trim_matches('"').to_string();
261    // The first line from `start` up to the next header that sets `key`.
262    let key_below = |start: usize, key: &str| {
263        (start..lines.len()).take_while(|&i| i == start || !header(lines[i])).find(|&i| key_of(lines[i]) == key)
264    };
265
266    if let Some(rest) = path.strip_prefix("machine.").filter(|r| r.contains('[')) {
267        let (list, rest) = rest.split_once('[')?;
268        let (node, field) = rest.split_once(']')?;
269        let field = field.trim_start_matches('.').split('.').next().unwrap_or_default();
270        let start = if let Some(n) = node.strip_prefix('#') {
271            let n: usize = n.parse().ok()?;
272            lines
273                .iter()
274                .enumerate()
275                .filter(|(_, l)| header(l) && header_name(l) == format!("machine.{list}"))
276                .nth(n.checked_sub(1)?)?
277                .0
278        } else {
279            // Ids are unique in a file: the line that gives this one starts its node (or is all of it, inline).
280            // The line that gives this id under a header of its list ([[machine.<list>]]), or inline under [machine]:
281            // the machine's own id and comments may give the same text elsewhere.
282            (0..lines.len()).find(|&i| {
283                let compact: String =
284                    lines[i].split('#').next().unwrap_or_default().chars().filter(|c| !c.is_whitespace()).collect();
285                let under = (0..=i).rev().find(|&h| header(lines[h])).map(|h| header_name(lines[h]));
286                compact.contains(&format!("id=\"{node}\""))
287                    && (under.as_deref() == Some(&format!("machine.{list}"))
288                        || (under.as_deref() == Some("machine") && compact.contains('{')))
289            })?
290        };
291        // The node's header is the nearest one above its id.
292        let top = (0..=start).rev().find(|&i| header(lines[i])).unwrap_or(start);
293        // A node written inline (`{ id = "a", ... }`) has no key lines of its own: then its id's line.
294        let found = if field.is_empty() { None } else { key_below(top, field) };
295        return Some(found.unwrap_or(start) + 1);
296    }
297    // The longest table prefix that has a header, then the key below it.
298    let parts: Vec<&str> = path.split('.').collect();
299    for split in (0..=parts.len()).rev() {
300        let (table, key) = (parts[..split].join("."), parts[split..].join("."));
301        let top =
302            if table.is_empty() { Some(0) } else { lines.iter().position(|l| header(l) && header_name(l) == table) };
303        if let Some(top) = top {
304            return Some(if key.is_empty() { top } else { key_below(top, &key).unwrap_or(top) } + 1);
305        }
306    }
307    None
308}