Skip to main content

general_mna/
system_builder.rs

1//! Builds a unified [`System`] (electrical MNA matrices + block/signal-domain graph) from one
2//! source text, via `general-spice-core`'s grammar — both the electrical `ElementInstance`
3//! lines (fed to the existing [`crate::MnaBuilder`], unchanged) and the new first-class
4//! `BlockInstance` lines (see `general-spice-core`'s own `docs/GRAMMAR.md` §12). Replaces the
5//! hand-rolled ~700-line parser that used to live in `general-simulator-cli`'s `main.rs`, which
6//! worked directly off `*`-disguised comment lines instead of real grammar.
7
8use std::cell::RefCell;
9use std::collections::{BTreeMap, BTreeSet};
10
11use continuous_blocks::{
12    CoordinateTransform, DiscreteIntegrationMethod, DiscretePid, FlipFlopKind, Hysteresis,
13    LatchPriority, LogicOp, Pid, SettledStateError, StateSpace, TransferFunction, Vco,
14};
15use general_spice_core::ast::Statement;
16use general_spice_core::dialect::Dialect;
17use general_spice_core::{lexer, parser};
18use pwl_devices::{IdealDiode, IdealSwitch};
19
20use crate::block_graph::{
21    BlockInstance, BlockKind, ConstValue, GainValue, GateBinding, Phys2SigTarget, PhysicalDomain,
22    PidClamp, SampleTimeSpec, Signal,
23};
24use crate::hierarchy;
25use crate::{MnaBuilder, MnaSystem, TransientFunction};
26
27/// The result of [`build_system`]: everything a simulator needs, already split into its own
28/// electrical (`mna`/`ideal_diodes`/`ideal_switches`/`gates`) and signal-domain (`blocks`)
29/// halves.
30#[derive(Debug)]
31pub struct System {
32    /// The electrical MNA system, built by [`crate::MnaBuilder`] from the netlist's element lines.
33    pub mna: MnaSystem,
34    /// Every `D` instance, keyed by name, as a companion ideal-diode model.
35    pub ideal_diodes: BTreeMap<String, IdealDiode>,
36    /// Every ideal-switch instance, keyed by name.
37    pub ideal_switches: BTreeMap<String, IdealSwitch>,
38    /// Each ideal switch's resolved gate-drive signal, keyed by the same name as
39    /// `ideal_switches`.
40    pub gates: BTreeMap<String, GateBinding>,
41    /// Every block/signal-domain (`kind=...`) instance, in source declaration order.
42    pub blocks: Vec<BlockInstance>,
43    /// Every ideal switch's shared on-resistance (`dae-runtime`'s switch model uses one shared
44    /// value per call) — `0.0` if there are no ideal switches at all. `build_system` already
45    /// enforces every declared ideal switch agrees on this value.
46    pub shared_r_on: f64,
47}
48
49enum Kind {
50    IdealDiode(IdealDiode),
51    IdealSwitch {
52        ideal_switch: IdealSwitch,
53        r_on: f64,
54        gate: GateBinding,
55    },
56    Block(BlockInstance),
57}
58
59/// Parses `source` under `dialect` and flattens every `.subckt`/`X`-instance into one flat,
60/// dotted-path-named statement list (see `hierarchy::flatten`) — the shared first step behind
61/// [`build_system`] and behind any downstream consumer (e.g. `dae-runtime`) that needs to build
62/// its own `MnaSystem` from the same, already-hierarchy-resolved statements rather than
63/// re-parsing raw text (and silently losing hierarchy) itself.
64///
65/// **`source` is parsed as a fragment, not a full document** (`general_spice_core::parser::parse`,
66/// not `parse_document`) — unlike the `MnaBuilder::build_document`/`build_fragment` distinction
67/// in this same crate's own README, there is no mandatory title line here: the *first* line of
68/// `source` is a real element/block statement, not skipped. A `general-simulator` netlist that
69/// leads with a title line (the normal SPICE-file convention) will have that line parsed as an
70/// element/block declaration and almost always fail — verified directly: an otherwise-correct
71/// netlist with a leading `"<title>"` text line failed with `UnsupportedElement`, naming a
72/// device letter taken from the title's own first word, not from anything the netlist author
73/// wrote as a device.
74pub fn parse_and_flatten(source: &str, dialect: Dialect) -> Result<Vec<Statement>, String> {
75    let processed = lexer::preprocess(source, dialect);
76    let statements: Vec<Statement> = parser::parse(&processed, dialect)
77        .into_iter()
78        .collect::<Result<_, _>>()
79        .map_err(|e: parser::ParseError| format!("line {}: {}", e.span.start, e.message))?;
80    hierarchy::flatten(&statements)
81}
82
83/// Parses `source` under `dialect` and builds the complete [`System`] — the one entry point a
84/// simulator needs; no parsing code of its own required downstream. Electrical statements go
85/// through the existing [`MnaBuilder`] machinery unchanged; block/signal-domain statements
86/// (`Statement::BlockInstance`) are dispatched by `build_kind` into an `ideal_diode`/
87/// `ideal_switch`/block entry, keyed by the statement's own name.
88///
89/// **No mandatory title line** — see [`parse_and_flatten`]'s own doc comment, which this
90/// function calls first.
91pub fn build_system(source: &str, dialect: Dialect) -> Result<System, String> {
92    let statements = parse_and_flatten(source, dialect)?;
93
94    let mna = MnaBuilder::new(dialect)
95        .build_statements(&statements)
96        // `Display`, not `Debug`: every `BuildError` variant formats itself as a readable
97        // sentence (and `InvalidElementField` as a `line N: device '<name>' ...` diagnostic
98        // matching this module's own block-field errors), which a struct dump would bury.
99        .map_err(|e| e.to_string())?;
100
101    let mut ideal_diodes = BTreeMap::new();
102    let mut ideal_switches = BTreeMap::new();
103    let mut gates = BTreeMap::new();
104    let mut blocks = Vec::new();
105    let mut shared_r_on: Option<f64> = None;
106    // (phys2sig name, branch=<name>, 1-based line number) for every `kind=phys2sig
107    // branch=<name>` block -- checked below, once `mna.unknowns` (and every element's own name)
108    // is fully known, against the classic MNA footgun: `branch=` naming an element with no
109    // current unknown at all (only V/L/E/H sources get one -- see
110    // `MnaBuilder::is_branch_device`), which used to silently read back 0.0 forever instead of
111    // erroring.
112    let mut phys2sig_branch_checks: Vec<(String, String, usize)> = Vec::new();
113
114    for stmt in &statements {
115        let Statement::BlockInstance(bi) = stmt else {
116            continue;
117        };
118        match build_kind(bi)? {
119            Kind::IdealDiode(d) => {
120                ideal_diodes.insert(bi.name.clone(), d);
121            }
122            Kind::IdealSwitch {
123                ideal_switch,
124                r_on,
125                gate,
126            } => {
127                match shared_r_on {
128                    None => shared_r_on = Some(r_on),
129                    Some(existing) if (existing - r_on).abs() > 1e-15 => {
130                        return Err(format!(
131                            "all ideal switches must share the same r_on (dae-runtime's switch \
132                             model uses one shared on-resistance per call); got {existing} and \
133                             {r_on}"
134                        ));
135                    }
136                    Some(_) => {}
137                }
138                gates.insert(bi.name.clone(), gate);
139                ideal_switches.insert(bi.name.clone(), ideal_switch);
140            }
141            Kind::Block(instance) => {
142                if let BlockKind::Phys2Sig(Phys2SigTarget::Current(branch)) = &instance.kind {
143                    let line_number = bi.span.start.saturating_sub(1);
144                    phys2sig_branch_checks.push((
145                        instance.name.clone(),
146                        branch.clone(),
147                        line_number,
148                    ));
149                }
150                blocks.push(instance);
151            }
152        }
153    }
154
155    for (phys2sig_name, branch, line_number) in &phys2sig_branch_checks {
156        let unknown = format!("I({branch})");
157        if mna.unknowns.iter().any(|u| u == &unknown) {
158            continue;
159        }
160        let element_exists = statements.iter().any(|s| {
161            matches!(
162                s,
163                Statement::ElementInstance(e) if e.name.eq_ignore_ascii_case(branch)
164            )
165        });
166        if element_exists {
167            return Err(format!(
168                "line {}: device '{phys2sig_name}' kind='phys2sig' branch='{branch}' has no \
169                 current unknown available (only V/L/E/H sources carry a branch-current \
170                 unknown) -- insert a 0V voltage source in series in the branch you want to \
171                 measure and probe its current instead",
172                line_number + 1
173            ));
174        }
175        return Err(format!(
176            "line {}: device '{phys2sig_name}' kind='phys2sig' branch='{branch}' names no such \
177             element",
178            line_number + 1
179        ));
180    }
181
182    Ok(System {
183        mna,
184        ideal_diodes,
185        ideal_switches,
186        gates,
187        blocks,
188        shared_r_on: shared_r_on.unwrap_or(0.0),
189    })
190}
191
192fn parse_signal(text: &str) -> Signal {
193    match text.strip_prefix("prev:") {
194        Some(name) => Signal::BlockPrev(name.to_string()),
195        None => Signal::Block(text.to_string()),
196    }
197}
198
199/// Splits `text` on top-level commas only — one inside a nested `[...]` (bracket depth > 0)
200/// doesn't count — so `"[1,2],[3,4]"` splits into `["[1,2]", "[3,4]"]`, not four pieces. The
201/// one primitive every Python-list-literal field below (`num=`/`den=`/`a=`/`b=`/`c=`/`points=`)
202/// is built from, so a matrix's row separator and a vector's entry separator are the same
203/// operation applied at a different nesting depth, not two different parsers.
204fn split_top_level(text: &str) -> Vec<&str> {
205    let mut depth = 0i32;
206    let mut start = 0usize;
207    let mut parts = Vec::new();
208    for (i, c) in text.char_indices() {
209        match c {
210            '[' => depth += 1,
211            ']' => depth -= 1,
212            ',' if depth == 0 => {
213                parts.push(text[start..i].trim());
214                start = i + c.len_utf8();
215            }
216            _ => {}
217        }
218    }
219    parts.push(text[start..].trim());
220    parts
221}
222
223/// Strips a field's required outer `[...]` — every list-valued field here is a real Python list
224/// literal (`num=[1,2,3]`, `a=[[1,2],[3,4]]`), never the bare comma/semicolon/colon delimiters
225/// an earlier version of this grammar used, so a Python list built from the same numbers can be
226/// pasted into a `.cir` file (spaces after commas included: [`split_top_level`]/the `f64` parse
227/// below both trim) without reformatting.
228fn strip_brackets<'a>(
229    text: &'a str,
230    name: &str,
231    field: &str,
232    line_number: usize,
233) -> Result<&'a str, String> {
234    let trimmed = text.trim();
235    trimmed
236        .strip_prefix('[')
237        .and_then(|s| s.strip_suffix(']'))
238        .ok_or_else(|| {
239            format!(
240                "line {}: device '{name}' field '{field}' must be a Python-style list, e.g. \
241                 '[1,2,3]' or '[[1,2],[3,4]]' (got '{text}')",
242                line_number + 1
243            )
244        })
245}
246
247/// Parses a `[[<x>,<y>],[<x>,<y>],...]` point list (a `kind=pwc`/`kind=pwl` reference schedule,
248/// or a `kind=table` lookup table) — a Python list of 2-element `[x, y]` lists, exactly the
249/// shape `numpy.array(points)` would expect for an `Nx2` table. Sorted ascending by `x` on
250/// return.
251fn parse_xy_points(
252    text: &str,
253    name: &str,
254    field: &str,
255    line_number: usize,
256) -> Result<Vec<(f64, f64)>, String> {
257    let rows = parse_matrix_rows(text, name, field, line_number)?;
258    let mut points = Vec::with_capacity(rows.len());
259    for row in rows {
260        let [x, y] = row.as_slice() else {
261            return Err(format!(
262                "line {}: device '{name}' field '{field}': each entry must be a 2-element \
263                 '[x,y]' list (got '{row:?}')",
264                line_number + 1
265            ));
266        };
267        points.push((*x, *y));
268    }
269    points.sort_by(|a, b| a.0.total_cmp(&b.0));
270    Ok(points)
271}
272
273/// The `key=value` fields of one block line, remembering every key any parser asks about.
274///
275/// [`build_kind`]'s per-`kind` arms read only the keys they need and never look at what is
276/// left over, so a misspelled or misplaced field (`G kind=tf ... wibble=3`) used to parse and
277/// run as if it had never been written — a block-side twin of the device-card silent drop
278/// `validate_trailing_fields` closes in [`crate::builder`]. Rather than hand-maintaining an
279/// accepted-key list per arm (and keeping it in step with every conditional field: `clamp_lo`
280/// vs `clamp_lo_in`, `reset`, `up_down`, `outputs`, the `ic=`/`y0=` that
281/// [`parse_block_initial_condition`] reads after the arm), every [`get`](Self::get) /
282/// [`contains_key`](Self::contains_key) records its key, and [`unread`](Self::unread) reports
283/// what nobody asked for once the block has been built. A key is "accepted" exactly when
284/// some code path looked it up, present or not — which is the same thing as "would have had
285/// an effect".
286struct Fields {
287    map: BTreeMap<String, String>,
288    looked_up: RefCell<BTreeSet<String>>,
289}
290
291impl Fields {
292    fn new(map: BTreeMap<String, String>) -> Self {
293        Self {
294            map,
295            looked_up: RefCell::new(BTreeSet::new()),
296        }
297    }
298
299    fn get(&self, key: &str) -> Option<&String> {
300        self.looked_up.borrow_mut().insert(key.to_string());
301        self.map.get(key)
302    }
303
304    fn contains_key(&self, key: &str) -> bool {
305        self.get(key).is_some()
306    }
307
308    /// Whether `key` is present, **without** marking it as a field this kind accepts.
309    ///
310    /// Needed only for the renamed-field checks. Those have to ask "did the deck use the old
311    /// spelling?", and asking through [`Self::get`] marks the old name as looked up -- which put
312    /// `v_th` into the "accepts only: ..." list of the very error that rejects it. A rejected
313    /// name must not appear in the list of names a kind accepts.
314    fn present_unread(&self, key: &str) -> bool {
315        self.map.contains_key(key)
316    }
317
318    /// The first field (in key order) present on the line that no parser ever looked up, and
319    /// the sorted list of every key that was looked up (the line's own `kind=` excluded from
320    /// both) for the error message.
321    fn unread(&self) -> Option<(&str, Vec<String>)> {
322        let looked_up = self.looked_up.borrow();
323        let stray = self
324            .map
325            .keys()
326            .find(|key| key.as_str() != "kind" && !looked_up.contains(key.as_str()))?;
327        let accepted = looked_up
328            .iter()
329            .filter(|key| key.as_str() != "kind")
330            .cloned()
331            .collect();
332        Some((stray.as_str(), accepted))
333    }
334}
335
336/// Parses the `ts=`/`freq=`/`to=` fields shared by
337/// `kind=cscript`/`kind=pyblock`/`kind=pyfunc`/`kind=octfunc` into a [`SampleTimeSpec`] —
338/// `ts=variable` (only when `allow_variable`, i.e. never for `pyfunc`/`octfunc`, both
339/// stateless) selects [`SampleTimeSpec::Variable`]; a numeric `ts=`/`freq=` selects
340/// [`SampleTimeSpec::Periodic`], with `to=` giving its own explicit `offset` (defaulting to
341/// `0.0` when omitted — see [`SampleTimeSpec`]'s own doc comment for why `0.0`, not `period`, is
342/// what actually preserves this project's pre-existing behavior for every netlist that never
343/// used `to=` at all). `to=`, when given, must satisfy `0.0 <= to < period`. `kind_str` (the
344/// netlist's own `kind=` token, e.g. `"pyfunc"`/`"octfunc"`) names the specific block kind in
345/// the `ts=variable`-rejected error message when `!allow_variable`; unused otherwise.
346fn parse_sample_time(
347    fields: &Fields,
348    name: &str,
349    line_number: usize,
350    allow_variable: bool,
351    kind_str: &str,
352) -> Result<Option<SampleTimeSpec>, String> {
353    let get = |key: &str| -> Result<f64, String> {
354        fields
355            .get(key)
356            .ok_or_else(|| {
357                format!(
358                    "line {}: device '{name}' missing field '{key}'",
359                    line_number + 1
360                )
361            })?
362            .parse::<f64>()
363            .map_err(|_| {
364                format!(
365                    "line {}: device '{name}' field '{key}' is not a number",
366                    line_number + 1
367                )
368            })
369    };
370
371    if fields.get("ts").map(String::as_str) == Some("variable") {
372        if !allow_variable {
373            // pyfunc keeps its own pre-existing exact wording (including the "use kind=pyblock
374            // instead" suggestion -- a real, stateful alternative exists for it); octfunc has no
375            // stateful counterpart in this workspace to suggest switching to, so its own message
376            // simply omits that clause rather than suggesting something that doesn't exist.
377            let suggestion = if kind_str == "pyfunc" {
378                " -- use kind=pyblock instead"
379            } else {
380                ""
381            };
382            return Err(format!(
383                "line {}: device '{name}': ts=variable is not available for kind={kind_str} (a \
384                 stateless function call has no instance to remember a requested next-hit \
385                 time against){suggestion}",
386                line_number + 1
387            ));
388        }
389        if fields.contains_key("freq") || fields.contains_key("to") {
390            return Err(format!(
391                "line {}: device '{name}': ts=variable is exclusive with 'freq'/'to' (the \
392                 block computes its own schedule; there's no fixed period/offset to combine \
393                 it with)",
394                line_number + 1
395            ));
396        }
397        return Ok(Some(SampleTimeSpec::Variable));
398    }
399
400    let period = match (fields.get("ts"), fields.get("freq")) {
401        (Some(_), Some(_)) => {
402            return Err(format!(
403                "line {}: device '{name}': 'ts' and 'freq' are mutually exclusive (both set \
404                 this block's sample time)",
405                line_number + 1
406            ))
407        }
408        (Some(_), None) => Some(get("ts")?),
409        (None, Some(_)) => Some(1.0 / get("freq")?),
410        (None, None) => None,
411    };
412
413    match (period, fields.get("to")) {
414        (None, Some(_)) => Err(format!(
415            "line {}: device '{name}': 'to' requires 'ts' or 'freq' (a phase offset has \
416             nothing to offset without a period)",
417            line_number + 1
418        )),
419        (None, None) => Ok(None),
420        (Some(period), None) => Ok(Some(SampleTimeSpec::Periodic {
421            period,
422            offset: 0.0,
423        })),
424        (Some(period), Some(_)) => {
425            let offset = get("to")?;
426            if !(0.0..period).contains(&offset) {
427                return Err(format!(
428                    "line {}: device '{name}': 'to' ({offset}) must satisfy 0 <= to < ts \
429                     ({period})",
430                    line_number + 1
431                ));
432            }
433            Ok(Some(SampleTimeSpec::Periodic { period, offset }))
434        }
435    }
436}
437
438/// Parses the same `ts=`/`freq=`/`to=` fields as [`parse_sample_time`], but for the three
439/// discrete-time blocks (`kind=discretestatespace`/`discretetf`/`discretepid`) where a sample
440/// time isn't optional the way it is for `cscript`/`pyblock`/`pyfunc` -- a discrete system's own
441/// dynamics *are* its sample period, so there's no "continuous" fallback for an omitted `ts=`/
442/// `freq=` to mean, and `ts=variable` doesn't compose with a fixed-period recursion at all (its
443/// own coefficients are baked in at that one period). See `discrete-time-blocks.md`.
444fn parse_required_periodic_sample_time(
445    fields: &Fields,
446    name: &str,
447    line_number: usize,
448) -> Result<SampleTimeSpec, String> {
449    match parse_sample_time(fields, name, line_number, true, "")? {
450        Some(SampleTimeSpec::Periodic { period, offset }) => {
451            Ok(SampleTimeSpec::Periodic { period, offset })
452        }
453        Some(SampleTimeSpec::Variable) => Err(format!(
454            "line {}: device '{name}': ts=variable is not available here -- a discrete block's \
455             own recursion has its coefficients baked in at one fixed sample period, which \
456             'the block decides its own next execution time' doesn't compose with",
457            line_number + 1
458        )),
459        None => Err(format!(
460            "line {}: device '{name}': missing 'ts=' or 'freq=' -- a discrete-time block's own \
461             sample period is not optional (its dynamics *are* that period), unlike the \
462             optional 'ts='/'freq=' on kind=cscript/pyblock/pyfunc",
463            line_number + 1
464        )),
465    }
466}
467
468/// Parses a `kind=const` block's `value=` field: a bare scalar (`value=5`, unchanged from
469/// before vector signals existed) or a Python-style flat list (`value=[1,2,3]`), a fixed
470/// constant vector.
471fn parse_const_value(
472    text: &str,
473    name: &str,
474    field: &str,
475    line_number: usize,
476) -> Result<ConstValue, String> {
477    if text.trim().starts_with('[') {
478        Ok(ConstValue::Vector(parse_vector(
479            text,
480            name,
481            field,
482            line_number,
483        )?))
484    } else {
485        text.trim()
486            .parse::<f64>()
487            .map(ConstValue::Scalar)
488            .map_err(|_| {
489                format!(
490                    "line {}: device '{name}' field '{field}' is not a number",
491                    line_number + 1
492                )
493            })
494    }
495}
496
497/// Parses a `kind=gain` block's `k=` field: a bare scalar (`k=2.0`, unchanged from before
498/// vector signals existed) or a Python-style *nested* list (`k=[[1,0],[0,1]]`), a fixed `M x N`
499/// matrix for a genuine matrix-vector product. A flat list (`k=[1,2,3]`) is not a valid `Gain`
500/// shape at all -- unlike `Const`, `Gain`'s own value is never itself a vector -- so it's
501/// rejected here with a clear error rather than silently guessed at.
502fn parse_gain_value(
503    text: &str,
504    name: &str,
505    field: &str,
506    line_number: usize,
507) -> Result<GainValue, String> {
508    let trimmed = text.trim();
509    if trimmed.starts_with('[') {
510        let inner = strip_brackets(text, name, field, line_number)?;
511        if inner.trim_start().starts_with('[') {
512            return Ok(GainValue::Matrix(parse_matrix_rows(
513                text,
514                name,
515                field,
516                line_number,
517            )?));
518        }
519        return Err(format!(
520            "line {}: device '{name}' field '{field}' must be a scalar (e.g. '2.0') or a \
521             matrix (e.g. '[[1,0],[0,1]]') -- got a flat list '{text}', which is not a valid \
522             Gain shape",
523            line_number + 1
524        ));
525    }
526    trimmed.parse::<f64>().map(GainValue::Scalar).map_err(|_| {
527        format!(
528            "line {}: device '{name}' field '{field}' is not a number",
529            line_number + 1
530        )
531    })
532}
533
534/// Parses a `kind=statespace` block's `b=`/`c=` field: a flat list (`b=[1,0]`, `c=[1,0]` — the
535/// original SISO shorthand, unchanged) or a genuine matrix (`b=[[1,0],[0,1]]`,
536/// `c=[[1,0],[0,1]]`, for real MIMO). `as_column`: `true` wraps a flat-list result as an `n x 1`
537/// column matrix (`b`'s own shorthand meaning "exactly one input"); `false` wraps it as a `1 x
538/// n` row matrix (`c`'s own shorthand meaning "exactly one output").
539fn parse_matrix_or_vector_shorthand(
540    text: &str,
541    name: &str,
542    field: &str,
543    line_number: usize,
544    as_column: bool,
545) -> Result<Vec<Vec<f64>>, String> {
546    let inner = strip_brackets(text, name, field, line_number)?;
547    if inner.trim_start().starts_with('[') {
548        return parse_matrix_rows(text, name, field, line_number);
549    }
550    let v = parse_vector(text, name, field, line_number)?;
551    Ok(if as_column {
552        v.into_iter().map(|x| vec![x]).collect()
553    } else {
554        vec![v]
555    })
556}
557
558/// Parses a Python-style list of numbers, e.g. a `kind=statespace` block's `b=[1,2]`/`c=[1,0]`
559/// vector or a `kind=tf` block's `num=[1,2]`/`den=[1,3,2]` coefficients.
560fn parse_vector(
561    text: &str,
562    name: &str,
563    field: &str,
564    line_number: usize,
565) -> Result<Vec<f64>, String> {
566    let inner = strip_brackets(text, name, field, line_number)?;
567    if inner.is_empty() {
568        return Ok(Vec::new());
569    }
570    split_top_level(inner)
571        .into_iter()
572        .map(|v| {
573            let parsed: f64 = v.parse().map_err(|_| {
574                format!(
575                    "line {}: device '{name}' field '{field}' entry '{v}' is not a number",
576                    line_number + 1
577                )
578            })?;
579            // `f64::from_str` accepts "nan"/"inf"/"-inf" as valid floats, but a NaN or
580            // infinity here would otherwise silently reach a downstream `partial_cmp().unwrap()`
581            // (this file's own `points` sort, or `lcp-solver`'s pivot selection) and panic the
582            // whole process instead of failing this one netlist line cleanly.
583            if !parsed.is_finite() {
584                return Err(format!(
585                    "line {}: device '{name}' field '{field}' entry '{v}' must be a finite \
586                     number (got {parsed})",
587                    line_number + 1
588                ));
589            }
590            Ok(parsed)
591        })
592        .collect()
593}
594
595/// Parses a `kind=statespace` block's `a` matrix: a Python-style list of row lists, e.g.
596/// `a=[[1,2],[3,4]]` — exactly `numpy.array([[1,2],[3,4]])`'s own literal shape.
597fn parse_matrix_rows(
598    text: &str,
599    name: &str,
600    field: &str,
601    line_number: usize,
602) -> Result<Vec<Vec<f64>>, String> {
603    let inner = strip_brackets(text, name, field, line_number)?;
604    if inner.is_empty() {
605        return Ok(Vec::new());
606    }
607    split_top_level(inner)
608        .into_iter()
609        .map(|row| parse_vector(row, name, field, line_number))
610        .collect()
611}
612
613fn build_kind(stmt: &general_spice_core::ast::BlockInstance) -> Result<Kind, String> {
614    let name = &stmt.name;
615    let line_number = stmt.span.start.saturating_sub(1);
616    let fields = Fields::new(stmt.fields.iter().cloned().collect());
617
618    let get = |key: &str| -> Result<f64, String> {
619        fields
620            .get(key)
621            .ok_or_else(|| {
622                format!(
623                    "line {}: device '{name}' missing field '{key}'",
624                    line_number + 1
625                )
626            })?
627            .parse::<f64>()
628            .map_err(|_| {
629                format!(
630                    "line {}: device '{name}' field '{key}' is not a number",
631                    line_number + 1
632                )
633            })
634    };
635
636    let get_str = |key: &str| -> Result<String, String> {
637        fields.get(key).cloned().ok_or_else(|| {
638            format!(
639                "line {}: device '{name}' missing field '{key}'",
640                line_number + 1
641            )
642        })
643    };
644
645    // Field names a reader could take two ways are refused rather than reinterpreted. The
646    // vocabulary rule is that a name says which device owns the parameter and uses that device's
647    // own datasheet word for the quantity -- so a diode's forward threshold is `v_f` ($V_F$), and
648    // on a switch every body-diode field carries `body_`. `v_th` is gone from the language in
649    // both places, because in power electronics it means the MOSFET gate threshold
650    // ($V_{GS(th)}$) and nothing else, and on a `kind=ideal_switch` line it used to mean the body
651    // diode's forward drop. Writing `v_th=5` for a 5 V gate produced a switch that still turned
652    // on at 0.5 *and* a body diode with a 5 V forward drop: a valid deck, a completed run, and a
653    // converter whose freewheeling path had silently changed.
654    //
655    // Hard errors, never accepted aliases: an alias is how a double meaning survives a rename.
656    // `present_unread` rather than `get`: a rejected spelling must not end up in the
657    // "accepts only: ..." list of the error that rejects it, which is what happened first time.
658    let renamed = |old: &str, replacement: &str, why: &str| -> Option<String> {
659        fields.present_unread(old).then(|| {
660            format!(
661                "line {}: device '{name}' field '{old}' no longer exists -- write \
662                 '{replacement}'. {why}",
663                line_number + 1
664            )
665        })
666    };
667
668    let kind = fields
669        .get("kind")
670        .map(String::as_str)
671        .unwrap_or("ideal_diode");
672    let entry = match kind {
673        "ideal_diode" => {
674            if let Some(message) = renamed(
675                "v_th",
676                "v_f",
677                "A diode's forward threshold is $V_F$ on every datasheet; `v_th` means the \
678                 MOSFET gate threshold and belongs to no diode.",
679            ) {
680                return Err(message);
681            }
682            Kind::IdealDiode(IdealDiode::new(
683                get("g_breakdown")?,
684                get("v_breakdown")?,
685                get("g_off")?,
686                get("v_f")?,
687                get("g_on")?,
688            ))
689        }
690        "ideal_switch" => {
691            if let Some(message) = renamed(
692                "v_th",
693                "body_v_f",
694                "On a switch this field was never the gate threshold: it is the body diode's \
695                 forward voltage, and the gate path never read it. If you meant the gate \
696                 threshold, that is 'v_gs_th' and it defaults to 0.5.",
697            ) {
698                return Err(message);
699            }
700            // The other four body-diode fields, which were spelled exactly as a standalone
701            // diode's. Prefixed now so that reading a switch line says which of its two devices
702            // each number describes.
703            for (old, replacement) in [
704                ("g_on", "body_g_on"),
705                ("g_off", "body_g_off"),
706                ("v_breakdown", "body_v_breakdown"),
707                ("g_breakdown", "body_g_breakdown"),
708            ] {
709                if let Some(message) = renamed(
710                    old,
711                    replacement,
712                    "On a switch, every field describing the body diode carries the `body_` \
713                     prefix; `r_on` stays bare because it is the channel, which is the switch's \
714                     own.",
715                ) {
716                    return Err(message);
717                }
718            }
719            let body_diode = IdealDiode::new(
720                get("body_g_breakdown")?,
721                get("body_v_breakdown")?,
722                get("body_g_off")?,
723                get("body_v_f")?,
724                get("body_g_on")?,
725            );
726            let r_on = get("r_on")?;
727            // Every gate is block-driven -- gate=block ctrl=<name>, reading that block's
728            // current output (>= 0.5 means on). No other gate= spelling exists: a
729            // permanently-off gate is an explicit `Const(0.0)` wired through
730            // `kind=sig2phys domain=voltage` (an ideal switch's gate is itself a voltage, the
731            // same Signal-to-PS boundary a V-source's own magnitude uses -- no dedicated
732            // gate-only converter).
733            // Optional, defaulting to the 0.5 this was hard-coded to before the field existed,
734            // so every deck written against the old language keeps its exact behaviour.
735            let v_gs_th = match fields.get("v_gs_th") {
736                None => 0.5,
737                Some(_) => get("v_gs_th")?,
738            };
739            let gate = match fields.get("gate").map(String::as_str) {
740                Some("block") => GateBinding::Block {
741                    ctrl: get_str("ctrl")?,
742                    v_gs_th,
743                },
744                Some(other) => {
745                    return Err(format!(
746                        "line {}: unknown gate spec '{other}' (only gate=block ctrl=<name> \
747                             exists -- every gate is block-driven)",
748                        line_number + 1
749                    ))
750                }
751                None => {
752                    return Err(format!(
753                        "line {}: device '{name}' missing field 'gate' (gate=block \
754                             ctrl=<name> -- every gate is block-driven, see this file's own \
755                             module doc comment)",
756                        line_number + 1
757                    ))
758                }
759            };
760            Kind::IdealSwitch {
761                ideal_switch: IdealSwitch::new(r_on, body_diode),
762                r_on,
763                gate,
764            }
765        }
766        "const" => Kind::Block(BlockInstance {
767            name: name.to_string(),
768            kind: BlockKind::Const(parse_const_value(
769                &get_str("value")?,
770                name,
771                "value",
772                line_number,
773            )?),
774            inputs: Vec::new(),
775            ic: None,
776        }),
777        "time" => Kind::Block(BlockInstance {
778            name: name.to_string(),
779            kind: BlockKind::Time,
780            inputs: Vec::new(),
781            ic: None,
782        }),
783        // "repeat=true" is optional on both "pwc" and "pwl" (default false, unchanged
784        // hold-flat-past-the-end behavior) -- wraps time into the breakpoint list's own
785        // [first, last) span once past the last point, making it periodic. See
786        // `dae_runtime::block_graph`'s own doc comment on `BlockKind::Pwc`/`BlockKind::Pwl`
787        // for why these are two distinct block kinds (interpolation style) rather than one
788        // with a flag, and why "pwl" here means real piecewise-*linear* SPICE PWL semantics
789        // while the older piecewise-*constant* block was renamed to "pwc" to free that name
790        // up.
791        "pwc" => {
792            let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
793            let repeat = fields.get("repeat").map(|s| s == "true").unwrap_or(false);
794            Kind::Block(BlockInstance {
795                name: name.to_string(),
796                kind: BlockKind::Pwc { points, repeat },
797                inputs: Vec::new(),
798                ic: None,
799            })
800        }
801        "pwl" => {
802            let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
803            let repeat = fields.get("repeat").map(|s| s == "true").unwrap_or(false);
804            Kind::Block(BlockInstance {
805                name: name.to_string(),
806                kind: BlockKind::Pwl { points, repeat },
807                inputs: Vec::new(),
808                ic: None,
809            })
810        }
811        // "sinwave"/"pulsewave"/"expwave"/"sffmwave": the electrical domain's other four
812        // time-varying source forms (see `general_mna::TransientFunction`'s own doc comment
813        // for the exact formula each implements), reused directly rather than
814        // reimplemented, with the same field names/order/defaults as ngspice/Xyce's own
815        // SIN()/PULSE()/EXP()/SFFM() -- so a `kind=sinwave ...` reference schedule and a
816        // `V1 a 0 SIN(...)` source built from the same numbers are bit-for-bit the same
817        // waveform. Named "...wave" rather than the bare SPICE keyword specifically to
818        // avoid colliding with the pre-existing `kind=sin`/`kind=exp` waveform-arithmetic
819        // *functions* (`sin(x)`/`exp(x)` of an input signal, see the `MathFn1` fallback
820        // dispatch below) -- "pulse"/"sffm" have no such collision today, but are named the
821        // same way for consistency across the family rather than only where forced to.
822        "sinwave" => {
823            let get_opt = |key: &str, default: f64| -> f64 {
824                fields
825                    .get(key)
826                    .and_then(|s| s.parse::<f64>().ok())
827                    .unwrap_or(default)
828            };
829            Kind::Block(BlockInstance {
830                name: name.to_string(),
831                kind: BlockKind::Waveform(TransientFunction::Sin {
832                    v0: get_opt("v0", 0.0),
833                    va: get("va")?,
834                    freq: get("freq")?,
835                    td: get_opt("td", 0.0),
836                    theta: get_opt("theta", 0.0),
837                    phase: get_opt("phase", 0.0),
838                }),
839                inputs: Vec::new(),
840                ic: None,
841            })
842        }
843        "pulsewave" => {
844            let get_opt = |key: &str, default: f64| -> f64 {
845                fields
846                    .get(key)
847                    .and_then(|s| s.parse::<f64>().ok())
848                    .unwrap_or(default)
849            };
850            Kind::Block(BlockInstance {
851                name: name.to_string(),
852                kind: BlockKind::Waveform(TransientFunction::Pulse {
853                    v1: get("v1")?,
854                    v2: get("v2")?,
855                    td: get_opt("td", 0.0),
856                    tr: get_opt("tr", 0.0),
857                    tf: get_opt("tf", 0.0),
858                    pw: get_opt("pw", f64::MAX / 4.0),
859                    per: get_opt("per", f64::MAX / 4.0),
860                }),
861                inputs: Vec::new(),
862                ic: None,
863            })
864        }
865        "expwave" => {
866            let get_opt = |key: &str, default: f64| -> f64 {
867                fields
868                    .get(key)
869                    .and_then(|s| s.parse::<f64>().ok())
870                    .unwrap_or(default)
871            };
872            let td1 = get_opt("td1", 0.0);
873            // td2 defaults to "effectively never" (matching pulsewave's own pw/per
874            // defaults just above), NOT td1 -- TransientFunction::Exp treats `t < td2` as
875            // "still in the rise phase," so a naive td1 default would make every omitted-
876            // td2 call fall straight into the *fall* phase at t=0 instead of never falling
877            // at all (a real bug caught by this file's own dae-runtime-level test).
878            Kind::Block(BlockInstance {
879                name: name.to_string(),
880                kind: BlockKind::Waveform(TransientFunction::Exp {
881                    v1: get("v1")?,
882                    v2: get("v2")?,
883                    td1,
884                    tau1: get_opt("tau1", 1.0),
885                    td2: get_opt("td2", f64::MAX / 4.0),
886                    tau2: get_opt("tau2", 1.0),
887                }),
888                inputs: Vec::new(),
889                ic: None,
890            })
891        }
892        "sffmwave" => {
893            let get_opt = |key: &str, default: f64| -> f64 {
894                fields
895                    .get(key)
896                    .and_then(|s| s.parse::<f64>().ok())
897                    .unwrap_or(default)
898            };
899            Kind::Block(BlockInstance {
900                name: name.to_string(),
901                kind: BlockKind::Waveform(TransientFunction::Sffm {
902                    v0: get_opt("v0", 0.0),
903                    va: get("va")?,
904                    fc: get("fc")?,
905                    mdi: get_opt("mdi", 0.0),
906                    fs: get("fs")?,
907                }),
908                inputs: Vec::new(),
909                ic: None,
910            })
911        }
912        "sum" => {
913            let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
914            let signs: Vec<f64> = get_str("signs")?
915                .split(',')
916                .map(|s| {
917                    s.parse::<f64>().map_err(|_| {
918                        format!(
919                            "line {}: device '{name}' field 'signs' entry '{s}' is not a \
920                                 number",
921                            line_number + 1
922                        )
923                    })
924                })
925                .collect::<Result<_, _>>()?;
926            if inputs.len() != signs.len() {
927                return Err(format!(
928                    "line {}: device '{name}': 'inputs' has {} entries but 'signs' has {} \
929                         (need one sign per input)",
930                    line_number + 1,
931                    inputs.len(),
932                    signs.len()
933                ));
934            }
935            Kind::Block(BlockInstance {
936                name: name.to_string(),
937                kind: BlockKind::Sum(signs),
938                inputs,
939                ic: None,
940            })
941        }
942        "gain" => Kind::Block(BlockInstance {
943            name: name.to_string(),
944            kind: BlockKind::Gain(parse_gain_value(&get_str("k")?, name, "k", line_number)?),
945            inputs: vec![parse_signal(&get_str("in")?)],
946            ic: None,
947        }),
948        "pid" => {
949            let pid = Pid::new(get("kp")?, get("ki")?, get("kd")?, get("n")?).map_err(|e| {
950                format!(
951                    "line {}: device '{name}': invalid PID ({e:?})",
952                    line_number + 1
953                )
954            })?;
955            let error_input = parse_signal(&get_str("in")?);
956            let (clamp, inputs) = match (fields.get("clamp_lo_in"), fields.get("clamp_hi_in")) {
957                (Some(lo), Some(hi)) => (
958                    PidClamp::Dynamic,
959                    vec![error_input, parse_signal(lo), parse_signal(hi)],
960                ),
961                (None, None) => (
962                    PidClamp::Fixed(get("clamp_lo")?, get("clamp_hi")?),
963                    vec![error_input],
964                ),
965                _ => {
966                    return Err(format!(
967                        "line {}: device '{name}': 'clamp_lo_in'/'clamp_hi_in' must both be \
968                             given together (dynamic clamp) or both omitted (fixed clamp= \
969                             clamp_lo/clamp_hi)",
970                        line_number + 1
971                    ))
972                }
973            };
974            Kind::Block(BlockInstance {
975                name: name.to_string(),
976                kind: BlockKind::Pid { pid, clamp },
977                inputs,
978                ic: None,
979            })
980        }
981        "vco" => {
982            let vco = Vco::new(get("f_min")?, get("f_max")?).map_err(|e| {
983                format!(
984                    "line {}: device '{name}': invalid vco ({e:?})",
985                    line_number + 1
986                )
987            })?;
988            Kind::Block(BlockInstance {
989                name: name.to_string(),
990                kind: BlockKind::Vco(vco),
991                inputs: vec![parse_signal(&get_str("in")?)],
992                ic: None,
993            })
994        }
995        // "pwm"/"pspwm": fixed-frequency and frequency+phase+duty active-high-complementary
996        // PWM modulators (see `dae_runtime::BlockKind::Pwm`/`PhaseShiftPwm`'s own doc
997        // comments for the full design) -- both default `red`/`fed` (dead time, seconds) to
998        // 0.0, the ideal gap-free/overlap-free complementary pair.
999        "pwm" => {
1000            let output_names = match fields.get("outputs") {
1001                Some(names) => {
1002                    let names: Vec<String> = names.split(',').map(str::to_string).collect();
1003                    if names.len() != 2 {
1004                        return Err(format!(
1005                            "line {}: device '{name}': 'outputs' needs exactly 2 entries \
1006                                 (main, complement; got {})",
1007                            line_number + 1,
1008                            names.len()
1009                        ));
1010                    }
1011                    names
1012                }
1013                None => vec![name.to_string(), format!("{name}_comp")],
1014            };
1015            Kind::Block(BlockInstance {
1016                name: name.to_string(),
1017                kind: BlockKind::Pwm {
1018                    freq_hz: get("freq")?,
1019                    red: fields
1020                        .get("red")
1021                        .map(|s| s.parse::<f64>())
1022                        .transpose()
1023                        .map_err(|_| {
1024                            format!(
1025                                "line {}: device '{name}' field 'red' is not a number",
1026                                line_number + 1
1027                            )
1028                        })?
1029                        .unwrap_or(0.0),
1030                    fed: fields
1031                        .get("fed")
1032                        .map(|s| s.parse::<f64>())
1033                        .transpose()
1034                        .map_err(|_| {
1035                            format!(
1036                                "line {}: device '{name}' field 'fed' is not a number",
1037                                line_number + 1
1038                            )
1039                        })?
1040                        .unwrap_or(0.0),
1041                    output_names,
1042                },
1043                inputs: vec![parse_signal(&get_str("in")?)],
1044                ic: None,
1045            })
1046        }
1047        "pspwm" => {
1048            let osc = Vco::new(get("f_min")?, get("f_max")?).map_err(|e| {
1049                format!(
1050                    "line {}: device '{name}': invalid pspwm oscillator ({e:?})",
1051                    line_number + 1
1052                )
1053            })?;
1054            let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1055            if inputs.len() != 3 {
1056                return Err(format!(
1057                    "line {}: device '{name}' kind='pspwm' needs 3 inputs \
1058                         (freq,phase,duty; got {})",
1059                    line_number + 1,
1060                    inputs.len()
1061                ));
1062            }
1063            let output_names = match fields.get("outputs") {
1064                Some(names) => {
1065                    let names: Vec<String> = names.split(',').map(str::to_string).collect();
1066                    if names.len() != 2 {
1067                        return Err(format!(
1068                            "line {}: device '{name}': 'outputs' needs exactly 2 entries \
1069                                 (main, complement; got {})",
1070                            line_number + 1,
1071                            names.len()
1072                        ));
1073                    }
1074                    names
1075                }
1076                None => vec![name.to_string(), format!("{name}_comp")],
1077            };
1078            let get_opt = |key: &str| -> Result<f64, String> {
1079                fields
1080                    .get(key)
1081                    .map(|s| s.parse::<f64>())
1082                    .transpose()
1083                    .map_err(|_| {
1084                        format!(
1085                            "line {}: device '{name}' field '{key}' is not a number",
1086                            line_number + 1
1087                        )
1088                    })
1089                    .map(|v| v.unwrap_or(0.0))
1090            };
1091            Kind::Block(BlockInstance {
1092                name: name.to_string(),
1093                kind: BlockKind::PhaseShiftPwm {
1094                    osc,
1095                    red: get_opt("red")?,
1096                    fed: get_opt("fed")?,
1097                    output_names,
1098                },
1099                inputs,
1100                ic: None,
1101            })
1102        }
1103        "hysteresis" => {
1104            let hysteresis = Hysteresis::new(get("high")?, get("low")?).map_err(|e| {
1105                format!(
1106                    "line {}: device '{name}': invalid hysteresis ({e:?})",
1107                    line_number + 1
1108                )
1109            })?;
1110            Kind::Block(BlockInstance {
1111                name: name.to_string(),
1112                kind: BlockKind::Hysteresis(hysteresis),
1113                inputs: vec![parse_signal(&get_str("in")?)],
1114                ic: None,
1115            })
1116        }
1117        "srlatch" => {
1118            let priority = match fields.get("priority") {
1119                Some(s) => LatchPriority::from_name(s).ok_or_else(|| {
1120                    format!(
1121                        "line {}: device '{name}' field 'priority' must be 'set' or 'reset' \
1122                         (got '{s}')",
1123                        line_number + 1
1124                    )
1125                })?,
1126                None => LatchPriority::Set,
1127            };
1128            Kind::Block(BlockInstance {
1129                name: name.to_string(),
1130                kind: BlockKind::SrLatch { priority },
1131                inputs: vec![
1132                    parse_signal(&get_str("set")?),
1133                    parse_signal(&get_str("reset")?),
1134                ],
1135                ic: None,
1136            })
1137        }
1138        "counter" => {
1139            let modulus = match fields.get("modulus") {
1140                Some(s) => Some(s.parse::<u32>().map_err(|_| {
1141                    format!(
1142                        "line {}: device '{name}' field 'modulus' is not a non-negative integer",
1143                        line_number + 1
1144                    )
1145                })?),
1146                None => None,
1147            };
1148            let mut inputs = vec![parse_signal(&get_str("clk")?)];
1149            let up_down = fields.contains_key("up_down");
1150            if up_down {
1151                inputs.push(parse_signal(&get_str("up_down")?));
1152            }
1153            let reset = fields.contains_key("reset");
1154            if reset {
1155                inputs.push(parse_signal(&get_str("reset")?));
1156            }
1157            Kind::Block(BlockInstance {
1158                name: name.to_string(),
1159                kind: BlockKind::Counter {
1160                    up_down,
1161                    modulus,
1162                    reset,
1163                },
1164                inputs,
1165                ic: None,
1166            })
1167        }
1168        "cscript" => {
1169            let lib = std::path::PathBuf::from(get_str("lib")?);
1170            let output_names = match fields.get("outputs") {
1171                Some(names) => names.split(',').map(str::to_string).collect(),
1172                None => vec![name.to_string()],
1173            };
1174            let inputs = match fields.get("inputs") {
1175                Some(list) => list.split(',').map(parse_signal).collect(),
1176                None => vec![parse_signal(&get_str("in")?)],
1177            };
1178            let sample_time = parse_sample_time(&fields, name, line_number, true, "cscript")?;
1179            let xc_count = match fields.get("xc_count") {
1180                Some(s) => s.parse::<usize>().map_err(|_| {
1181                    format!(
1182                        "line {}: device '{name}' field 'xc_count' is not a non-negative \
1183                         integer",
1184                        line_number + 1
1185                    )
1186                })?,
1187                None => 0,
1188            };
1189            Kind::Block(BlockInstance {
1190                name: name.to_string(),
1191                kind: BlockKind::CScript {
1192                    lib,
1193                    output_names,
1194                    sample_time,
1195                    xc_count,
1196                },
1197                inputs,
1198                ic: None,
1199            })
1200        }
1201        "pyblock" => {
1202            // Same field set as "cscript" above (output_names/inputs/sample_time/xc_count
1203            // parsing all identical), except `path=` names a `.py` source file instead of a
1204            // precompiled `.so` -- see BlockKind::PyBlock's own doc comment.
1205            let path = std::path::PathBuf::from(get_str("path")?);
1206            let output_names = match fields.get("outputs") {
1207                Some(names) => names.split(',').map(str::to_string).collect(),
1208                None => vec![name.to_string()],
1209            };
1210            let inputs = match fields.get("inputs") {
1211                Some(list) => list.split(',').map(parse_signal).collect(),
1212                None => vec![parse_signal(&get_str("in")?)],
1213            };
1214            let sample_time = parse_sample_time(&fields, name, line_number, true, "pyblock")?;
1215            let xc_count = match fields.get("xc_count") {
1216                Some(s) => s.parse::<usize>().map_err(|_| {
1217                    format!(
1218                        "line {}: device '{name}' field 'xc_count' is not a non-negative \
1219                         integer",
1220                        line_number + 1
1221                    )
1222                })?,
1223                None => 0,
1224            };
1225            Kind::Block(BlockInstance {
1226                name: name.to_string(),
1227                kind: BlockKind::PyBlock {
1228                    path,
1229                    output_names,
1230                    sample_time,
1231                    xc_count,
1232                },
1233                inputs,
1234                ic: None,
1235            })
1236        }
1237        "pyfunc" => {
1238            // A genuinely separate contract from "pyblock" above (not a mode of it) -- see
1239            // BlockKind::PyFunction's own doc comment. `function=` is required (no default):
1240            // this contract exists specifically for a descriptively-named plain function, not
1241            // a fixed `output` entry point.
1242            let path = std::path::PathBuf::from(get_str("path")?);
1243            let function = get_str("function")?;
1244            let output_names = match fields.get("outputs") {
1245                Some(names) => names.split(',').map(str::to_string).collect(),
1246                None => vec![name.to_string()],
1247            };
1248            let inputs = match fields.get("inputs") {
1249                Some(list) => list.split(',').map(parse_signal).collect(),
1250                None => vec![parse_signal(&get_str("in")?)],
1251            };
1252            let sample_time = parse_sample_time(&fields, name, line_number, false, "pyfunc")?;
1253            Kind::Block(BlockInstance {
1254                name: name.to_string(),
1255                kind: BlockKind::PyFunction {
1256                    path,
1257                    function,
1258                    output_names,
1259                    sample_time,
1260                },
1261                inputs,
1262                ic: None,
1263            })
1264        }
1265        "octfunc" => {
1266            // The .m-file counterpart to "pyfunc" above -- identical field set/parsing (see
1267            // BlockKind::OctFunc's own doc comment): `function=` required, no default,
1268            // ts=variable rejected the same way and with the same wording (a stateless function
1269            // call has no instance to remember a next-hit time against).
1270            let path = std::path::PathBuf::from(get_str("path")?);
1271            let function = get_str("function")?;
1272            let output_names = match fields.get("outputs") {
1273                Some(names) => names.split(',').map(str::to_string).collect(),
1274                None => vec![name.to_string()],
1275            };
1276            let inputs = match fields.get("inputs") {
1277                Some(list) => list.split(',').map(parse_signal).collect(),
1278                None => vec![parse_signal(&get_str("in")?)],
1279            };
1280            let sample_time = parse_sample_time(&fields, name, line_number, false, "octfunc")?;
1281            Kind::Block(BlockInstance {
1282                name: name.to_string(),
1283                kind: BlockKind::OctFunc {
1284                    path,
1285                    function,
1286                    output_names,
1287                    sample_time,
1288                },
1289                inputs,
1290                ic: None,
1291            })
1292        }
1293        "octblock" => {
1294            // The stateful sibling of "octfunc" above (not a mode of it -- see
1295            // BlockKind::OctBlock's own doc comment): same output_names/inputs/sample_time/
1296            // xc_count field shape "pyblock" uses (ts=variable allowed), plus `function=`
1297            // required the way "octfunc"/"pyfunc" both require it -- `path=` here names a
1298            // *directory* (the file-per-function contract), not a single `.m` file.
1299            let path = std::path::PathBuf::from(get_str("path")?);
1300            let function = get_str("function")?;
1301            let output_names = match fields.get("outputs") {
1302                Some(names) => names.split(',').map(str::to_string).collect(),
1303                None => vec![name.to_string()],
1304            };
1305            let inputs = match fields.get("inputs") {
1306                Some(list) => list.split(',').map(parse_signal).collect(),
1307                None => vec![parse_signal(&get_str("in")?)],
1308            };
1309            let sample_time = parse_sample_time(&fields, name, line_number, true, "octblock")?;
1310            let xc_count = match fields.get("xc_count") {
1311                Some(s) => s.parse::<usize>().map_err(|_| {
1312                    format!(
1313                        "line {}: device '{name}' field 'xc_count' is not a non-negative \
1314                         integer",
1315                        line_number + 1
1316                    )
1317                })?,
1318                None => 0,
1319            };
1320            Kind::Block(BlockInstance {
1321                name: name.to_string(),
1322                kind: BlockKind::OctBlock {
1323                    path,
1324                    function,
1325                    output_names,
1326                    sample_time,
1327                    xc_count,
1328                },
1329                inputs,
1330                ic: None,
1331            })
1332        }
1333        "statespace" => {
1334            let a = parse_matrix_rows(&get_str("a")?, name, "a", line_number)?;
1335            // `b=`/`c=` accept either their original SISO shorthand (a flat list -- `b=[1,0]`
1336            // means "one input," `c=[1,0]` means "one output," exactly as before vector
1337            // signals existed) or a genuine matrix (`b=[[1,0],[0,1]]`, n x p for p inputs;
1338            // `c=[[1,0]]`, q x n for q outputs) for a real MIMO declaration. Detected the same
1339            // way `parse_gain_value` detects a matrix: does the field, after stripping its own
1340            // outer brackets, immediately start with another `[`.
1341            let b = parse_matrix_or_vector_shorthand(&get_str("b")?, name, "b", line_number, true)?;
1342            let c =
1343                parse_matrix_or_vector_shorthand(&get_str("c")?, name, "c", line_number, false)?;
1344            let p = b.first().map_or(0, |row| row.len());
1345            let q = c.len();
1346            // `d=` defaults to an all-zero q x p matrix when omitted (generalizing the old
1347            // default of 0.0 cleanly); given as a matrix (`d=[[..],..]`) for MIMO, or a bare
1348            // scalar only when the system is genuinely 1x1 (SISO) -- a lone scalar has no
1349            // unambiguous placement in a larger D matrix, so it's rejected rather than guessed
1350            // at once q>1 or p>1.
1351            let d = match fields.get("d") {
1352                None => vec![vec![0.0; p]; q],
1353                Some(text) if text.trim().starts_with('[') => {
1354                    parse_matrix_rows(text, name, "d", line_number)?
1355                }
1356                Some(text) => {
1357                    if q != 1 || p != 1 {
1358                        return Err(format!(
1359                            "line {}: device '{name}' field 'd' is a bare scalar, but this \
1360                             system has {q} output(s) and {p} input(s) -- declare \
1361                             'd=[[...],...]' ({q}x{p}) for a MIMO system, a bare scalar is only \
1362                             valid for a 1x1 (SISO) one",
1363                            line_number + 1
1364                        ));
1365                    }
1366                    let v: f64 = text.trim().parse().map_err(|_| {
1367                        format!(
1368                            "line {}: device '{name}' field 'd' is not a number",
1369                            line_number + 1
1370                        )
1371                    })?;
1372                    vec![vec![v]]
1373                }
1374            };
1375            // No `e=` field exposed at the CLI level yet, so this is always the trivial
1376            // (always-valid) e=None case -- StateSpace::new still runs the same check every
1377            // other block-kind constructor here does, so a future `e=` field only has to
1378            // add parsing, not a new validation path.
1379            let ss = StateSpace::new(a, b, c, d, None).map_err(|e| {
1380                format!(
1381                    "line {}: device '{name}': invalid statespace ({e:?})",
1382                    line_number + 1
1383                )
1384            })?;
1385            // `in=<signal>` (SISO shorthand, p must be 1) or `inputs=<signal>,<signal>,...`
1386            // (exactly p entries, each independently scalar or vector -- flattened by
1387            // `dae-runtime`'s own evaluate_blocks into the u vector `StateSpace::rk4_step`
1388            // expects; the *total* flattened length must equal p, checked there, not here,
1389            // since arity from a vector-valued upstream signal isn't knowable from netlist text
1390            // alone).
1391            let inputs = match fields.get("inputs") {
1392                Some(list) => list.split(',').map(parse_signal).collect(),
1393                None => vec![parse_signal(&get_str("in")?)],
1394            };
1395            Kind::Block(BlockInstance {
1396                name: name.to_string(),
1397                kind: BlockKind::StateSpace(ss),
1398                inputs,
1399                ic: None,
1400            })
1401        }
1402        "tf" => {
1403            let num = parse_vector(&get_str("num")?, name, "num", line_number)?;
1404            let den = parse_vector(&get_str("den")?, name, "den", line_number)?;
1405            let tf = TransferFunction::new(num, den).map_err(|e| {
1406                format!(
1407                    "line {}: device '{name}': invalid transfer function ({e:?})",
1408                    line_number + 1
1409                )
1410            })?;
1411            Kind::Block(BlockInstance {
1412                name: name.to_string(),
1413                kind: BlockKind::TransferFunction(tf),
1414                inputs: vec![parse_signal(&get_str("in")?)],
1415                ic: None,
1416            })
1417        }
1418        "discretestatespace" => {
1419            let a = parse_matrix_rows(&get_str("a")?, name, "a", line_number)?;
1420            let b = parse_matrix_or_vector_shorthand(&get_str("b")?, name, "b", line_number, true)?;
1421            let c =
1422                parse_matrix_or_vector_shorthand(&get_str("c")?, name, "c", line_number, false)?;
1423            let p = b.first().map_or(0, |row| row.len());
1424            let q = c.len();
1425            let d = match fields.get("d") {
1426                None => vec![vec![0.0; p]; q],
1427                Some(text) if text.trim().starts_with('[') => {
1428                    parse_matrix_rows(text, name, "d", line_number)?
1429                }
1430                Some(text) => {
1431                    if q != 1 || p != 1 {
1432                        return Err(format!(
1433                            "line {}: device '{name}' field 'd' is a bare scalar, but this \
1434                             system has {q} output(s) and {p} input(s) -- declare \
1435                             'd=[[...],...]' ({q}x{p}) for a MIMO system, a bare scalar is only \
1436                             valid for a 1x1 (SISO) one",
1437                            line_number + 1
1438                        ));
1439                    }
1440                    let v: f64 = text.trim().parse().map_err(|_| {
1441                        format!(
1442                            "line {}: device '{name}' field 'd' is not a number",
1443                            line_number + 1
1444                        )
1445                    })?;
1446                    vec![vec![v]]
1447                }
1448            };
1449            let ss = StateSpace::new(a, b, c, d, None).map_err(|e| {
1450                format!(
1451                    "line {}: device '{name}': invalid discrete statespace ({e:?})",
1452                    line_number + 1
1453                )
1454            })?;
1455            let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1456            let inputs = match fields.get("inputs") {
1457                Some(list) => list.split(',').map(parse_signal).collect(),
1458                None => vec![parse_signal(&get_str("in")?)],
1459            };
1460            Kind::Block(BlockInstance {
1461                name: name.to_string(),
1462                kind: BlockKind::DiscreteStateSpace { ss, sample_time },
1463                inputs,
1464                ic: None,
1465            })
1466        }
1467        "discretetf" => {
1468            let num = parse_vector(&get_str("num")?, name, "num", line_number)?;
1469            let den = parse_vector(&get_str("den")?, name, "den", line_number)?;
1470            let tf = TransferFunction::new(num, den).map_err(|e| {
1471                format!(
1472                    "line {}: device '{name}': invalid discrete transfer function ({e:?})",
1473                    line_number + 1
1474                )
1475            })?;
1476            let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1477            Kind::Block(BlockInstance {
1478                name: name.to_string(),
1479                kind: BlockKind::DiscreteTransferFunction { tf, sample_time },
1480                inputs: vec![parse_signal(&get_str("in")?)],
1481                ic: None,
1482            })
1483        }
1484        "discretepid" => {
1485            let sample_time = parse_required_periodic_sample_time(&fields, name, line_number)?;
1486            let period = match sample_time {
1487                SampleTimeSpec::Periodic { period, .. } => period,
1488                SampleTimeSpec::Variable => {
1489                    unreachable!("parse_required_periodic_sample_time already rejected ts=variable")
1490                }
1491            };
1492            let method_name = fields
1493                .get("integration_method")
1494                .map(String::as_str)
1495                .unwrap_or("forward");
1496            let method = DiscreteIntegrationMethod::from_name(method_name).ok_or_else(|| {
1497                format!(
1498                    "line {}: device '{name}': unknown integration_method '{method_name}' \
1499                     (expected 'forward', 'backward', or 'trapezoidal')",
1500                    line_number + 1
1501                )
1502            })?;
1503            let pid = DiscretePid {
1504                kp: get("kp")?,
1505                ki: get("ki")?,
1506                kd: get("kd")?,
1507                n: get("n")?,
1508                period,
1509                method,
1510            };
1511            let error_input = parse_signal(&get_str("in")?);
1512            let (clamp, inputs) = match (fields.get("clamp_lo_in"), fields.get("clamp_hi_in")) {
1513                (Some(lo), Some(hi)) => (
1514                    PidClamp::Dynamic,
1515                    vec![error_input, parse_signal(lo), parse_signal(hi)],
1516                ),
1517                (None, None) => (
1518                    PidClamp::Fixed(get("clamp_lo")?, get("clamp_hi")?),
1519                    vec![error_input],
1520                ),
1521                _ => {
1522                    return Err(format!(
1523                        "line {}: device '{name}': 'clamp_lo_in'/'clamp_hi_in' must both be \
1524                             given together (dynamic clamp) or both omitted (fixed clamp= \
1525                             clamp_lo/clamp_hi)",
1526                        line_number + 1
1527                    ))
1528                }
1529            };
1530            Kind::Block(BlockInstance {
1531                name: name.to_string(),
1532                kind: BlockKind::DiscretePid {
1533                    pid,
1534                    clamp,
1535                    sample_time,
1536                },
1537                inputs,
1538                ic: None,
1539            })
1540        }
1541        "product" => Kind::Block(BlockInstance {
1542            name: name.to_string(),
1543            kind: BlockKind::Product,
1544            inputs: get_str("inputs")?.split(',').map(parse_signal).collect(),
1545            ic: None,
1546        }),
1547        "saturation" => Kind::Block(BlockInstance {
1548            name: name.to_string(),
1549            kind: BlockKind::Saturation(get("limit")?),
1550            inputs: vec![parse_signal(&get_str("in")?)],
1551            ic: None,
1552        }),
1553        "table" => {
1554            let points = parse_xy_points(&get_str("points")?, name, "points", line_number)?;
1555            Kind::Block(BlockInstance {
1556                name: name.to_string(),
1557                kind: BlockKind::Table(points),
1558                inputs: vec![parse_signal(&get_str("in")?)],
1559                ic: None,
1560            })
1561        }
1562        "phys2sig" => {
1563            let target = match (fields.get("node"), fields.get("branch")) {
1564                (Some(node), None) => Phys2SigTarget::Voltage(node.clone()),
1565                (None, Some(branch)) => Phys2SigTarget::Current(branch.clone()),
1566                (Some(_), Some(_)) => {
1567                    return Err(format!(
1568                        "line {}: device '{name}': 'node' and 'branch' are mutually \
1569                             exclusive (a phys2sig reads either a node voltage or a branch \
1570                             current, never both)",
1571                        line_number + 1
1572                    ))
1573                }
1574                (None, None) => {
1575                    return Err(format!(
1576                        "line {}: device '{name}' kind='phys2sig' needs 'node=<name>' (reads \
1577                             V(node)) or 'branch=<name>' (reads I(branch))",
1578                        line_number + 1
1579                    ))
1580                }
1581            };
1582            Kind::Block(BlockInstance {
1583                name: name.to_string(),
1584                kind: BlockKind::Phys2Sig(target),
1585                inputs: Vec::new(),
1586                ic: None,
1587            })
1588        }
1589        "sig2phys" => {
1590            let domain = match get_str("domain")?.as_str() {
1591                "voltage" => PhysicalDomain::Voltage,
1592                "current" => PhysicalDomain::Current,
1593                other => {
1594                    return Err(format!(
1595                        "line {}: device '{name}' field 'domain' must be 'voltage' or \
1596                             'current' (got '{other}')",
1597                        line_number + 1
1598                    ))
1599                }
1600            };
1601            Kind::Block(BlockInstance {
1602                name: name.to_string(),
1603                kind: BlockKind::Sig2Phys { domain },
1604                inputs: vec![parse_signal(&get_str("in")?)],
1605                ic: None,
1606            })
1607        }
1608        "clarke" | "clarkeinv" | "park" | "parkinv" | "clarkepark" | "clarkeparkinv" => {
1609            let ct = match kind {
1610                "clarke" => CoordinateTransform::Clarke,
1611                "clarkeinv" => CoordinateTransform::ClarkeInv,
1612                "park" => CoordinateTransform::Park,
1613                "parkinv" => CoordinateTransform::ParkInv,
1614                "clarkepark" => CoordinateTransform::ClarkePark,
1615                "clarkeparkinv" => CoordinateTransform::ClarkeParkInv,
1616                _ => unreachable!("matched above"),
1617            };
1618            let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1619            if inputs.len() != ct.input_count() {
1620                return Err(format!(
1621                    "line {}: device '{name}' kind='{kind}' needs {} inputs (got {})",
1622                    line_number + 1,
1623                    ct.input_count(),
1624                    inputs.len()
1625                ));
1626            }
1627            let output_names = match fields.get("outputs") {
1628                Some(names) => {
1629                    let names: Vec<String> = names.split(',').map(str::to_string).collect();
1630                    if names.len() != 3 {
1631                        return Err(format!(
1632                            "line {}: device '{name}': 'outputs' needs exactly 3 entries \
1633                                 (got {})",
1634                            line_number + 1,
1635                            names.len()
1636                        ));
1637                    }
1638                    names
1639                }
1640                // Default: block's own name aliases the first (primary) output, same as
1641                // `kind=cscript`'s default; the other two get readable auto-generated names
1642                // from this transform's own conventional output names (e.g. `<name>_beta`).
1643                None => {
1644                    let suffixes = ct.output_names();
1645                    std::iter::once(name.to_string())
1646                        .chain(suffixes[1..].iter().map(|s| format!("{name}_{s}")))
1647                        .collect()
1648                }
1649            };
1650            Kind::Block(BlockInstance {
1651                name: name.to_string(),
1652                kind: BlockKind::CoordinateTransform {
1653                    kind: ct,
1654                    output_names,
1655                },
1656                inputs,
1657                ic: None,
1658            })
1659        }
1660        "pmsm" => {
1661            let pmsm = continuous_blocks::Pmsm::new(
1662                get("r_s")?,
1663                get("l_d")?,
1664                get("l_q")?,
1665                get("lambda_pm")?,
1666                get("pole_pairs")?,
1667                get("inertia")?,
1668                get("friction")?,
1669            )
1670            .map_err(|e| {
1671                format!(
1672                    "line {}: device '{name}': invalid pmsm ({e:?})",
1673                    line_number + 1
1674                )
1675            })?;
1676            let inputs: Vec<Signal> = get_str("inputs")?.split(',').map(parse_signal).collect();
1677            if inputs.len() != 3 {
1678                return Err(format!(
1679                    "line {}: device '{name}' kind='pmsm' needs 3 inputs (vd,vq,t_load; \
1680                         got {})",
1681                    line_number + 1,
1682                    inputs.len()
1683                ));
1684            }
1685            let output_names = match fields.get("outputs") {
1686                Some(names) => {
1687                    let names: Vec<String> = names.split(',').map(str::to_string).collect();
1688                    if names.len() != 4 {
1689                        return Err(format!(
1690                            "line {}: device '{name}': 'outputs' needs exactly 4 entries \
1691                                 (got {})",
1692                            line_number + 1,
1693                            names.len()
1694                        ));
1695                    }
1696                    names
1697                }
1698                // Default: block's own name aliases the first (primary) output (`id`), same
1699                // convention as `kind=cscript`/`kind=clarke`; the other three get readable
1700                // auto-generated names.
1701                None => {
1702                    let suffixes = ["id", "iq", "omega_m", "theta_e"];
1703                    std::iter::once(name.to_string())
1704                        .chain(suffixes[1..].iter().map(|s| format!("{name}_{s}")))
1705                        .collect()
1706                }
1707            };
1708            Kind::Block(BlockInstance {
1709                name: name.to_string(),
1710                kind: BlockKind::Pmsm { pmsm, output_names },
1711                inputs,
1712                ic: None,
1713            })
1714        }
1715        other => {
1716            // Not one of the block kinds above: try the real-valued waveform-arithmetic
1717            // function library (cos, sin, exp, sqrt, atan2, hypot, if, limit, ...) before
1718            // giving up — see `continuous_blocks::waveform_arithmetic` for the full list.
1719            if let Some(f) = continuous_blocks::MathFn1::from_name(other) {
1720                Kind::Block(BlockInstance {
1721                    name: name.to_string(),
1722                    kind: BlockKind::MathFn1(f),
1723                    inputs: vec![parse_signal(&get_str("in")?)],
1724                    ic: None,
1725                })
1726            } else if let Some(f) = continuous_blocks::MathFn2::from_name(other) {
1727                Kind::Block(BlockInstance {
1728                    name: name.to_string(),
1729                    kind: BlockKind::MathFn2(f),
1730                    inputs: vec![
1731                        parse_signal(&get_str("in1")?),
1732                        parse_signal(&get_str("in2")?),
1733                    ],
1734                    ic: None,
1735                })
1736            } else if let Some(f) = continuous_blocks::MathFn3::from_name(other) {
1737                Kind::Block(BlockInstance {
1738                    name: name.to_string(),
1739                    kind: BlockKind::MathFn3(f),
1740                    inputs: vec![
1741                        parse_signal(&get_str("in1")?),
1742                        parse_signal(&get_str("in2")?),
1743                        parse_signal(&get_str("in3")?),
1744                    ],
1745                    ic: None,
1746                })
1747            } else if let Some(op) = LogicOp::from_name(other) {
1748                let inputs = if op.is_unary() {
1749                    vec![parse_signal(&get_str("in")?)]
1750                } else {
1751                    let list = get_str("inputs")?;
1752                    let parsed: Vec<Signal> = list.split(',').map(parse_signal).collect();
1753                    if parsed.len() < 2 {
1754                        return Err(format!(
1755                            "line {}: device '{name}': kind={other} needs at least 2 \
1756                             comma-separated inputs= entries (got {})",
1757                            line_number + 1,
1758                            parsed.len()
1759                        ));
1760                    }
1761                    parsed
1762                };
1763                Kind::Block(BlockInstance {
1764                    name: name.to_string(),
1765                    kind: BlockKind::LogicGate(op),
1766                    inputs,
1767                    ic: None,
1768                })
1769            } else if let Some(kind) = FlipFlopKind::from_name(other) {
1770                let mut inputs = vec![parse_signal(&get_str("clk")?)];
1771                match kind {
1772                    FlipFlopKind::D => inputs.push(parse_signal(&get_str("d")?)),
1773                    FlipFlopKind::T => inputs.push(parse_signal(&get_str("t")?)),
1774                    FlipFlopKind::Jk => {
1775                        inputs.push(parse_signal(&get_str("j")?));
1776                        inputs.push(parse_signal(&get_str("k")?));
1777                    }
1778                }
1779                let reset = fields.contains_key("reset");
1780                if reset {
1781                    inputs.push(parse_signal(&get_str("reset")?));
1782                }
1783                Kind::Block(BlockInstance {
1784                    name: name.to_string(),
1785                    kind: BlockKind::FlipFlop { kind, reset },
1786                    inputs,
1787                    ic: None,
1788                })
1789            } else {
1790                return Err(format!(
1791                    "line {}: unknown device kind '{other}'",
1792                    line_number + 1
1793                ));
1794            }
1795        }
1796    };
1797
1798    let entry = match entry {
1799        Kind::Block(mut block) => {
1800            block.ic = parse_block_initial_condition(&block.kind, &fields, name, line_number)?;
1801            Kind::Block(block)
1802        }
1803        other => other,
1804    };
1805
1806    // Only now, with every conditional lookup done, is a field nobody asked for a field this
1807    // line would have silently dropped. The same `line N: device '<name>' unknown field` shape
1808    // as the device-card check in `builder.rs`, so a bad field reads the same on either kind
1809    // of line. No block kind forwards open-ended user parameters through its fields (the
1810    // `cscript`/`pyblock`/`octblock` escape hatches take theirs from their own library or
1811    // script, not the netlist line), so no kind is exempt.
1812    if let Some((stray, accepted)) = fields.unread() {
1813        return Err(format!(
1814            "line {}: device '{name}' unknown field '{stray}' (kind={kind} accepts only: {})",
1815            line_number + 1,
1816            accepted.join(", ")
1817        ));
1818    }
1819    Ok(entry)
1820}
1821
1822/// Resolves a block's `ic=` (and, for `kind=tf`/`kind=discretetf`, `y0=`) into
1823/// [`BlockInstance::ic`]'s already-validated state vector — see that field's own doc comment
1824/// for the per-kind layout. Runs once, after the block's own `kind=` arm has built it, so every
1825/// check below has the finished block (its state count, its `ki`, its `modulus`) to check
1826/// against, and so no individual arm has to know initial conditions exist.
1827///
1828/// An `ic=` on a kind with no state of its own to start is rejected rather than dropped: a
1829/// silently ignored initial condition is a run that starts somewhere other than where its
1830/// author believes, with nothing in the output to say so.
1831fn parse_block_initial_condition(
1832    kind: &BlockKind,
1833    fields: &Fields,
1834    name: &str,
1835    line_number: usize,
1836) -> Result<Option<Vec<f64>>, String> {
1837    let line = line_number + 1;
1838    let ic_text = fields.get("ic");
1839    let y0_text = fields.get("y0");
1840    let accepts_y0 = matches!(
1841        kind,
1842        BlockKind::TransferFunction(_) | BlockKind::DiscreteTransferFunction { .. }
1843    );
1844    if y0_text.is_some() && !accepts_y0 {
1845        return Err(format!(
1846            "line {line}: device '{name}' field 'y0' is only valid on kind=tf/kind=discretetf \
1847             (a settled output to start from) -- use 'ic' for this kind's initial condition"
1848        ));
1849    }
1850    if ic_text.is_some() && y0_text.is_some() {
1851        return Err(format!(
1852            "line {line}: device '{name}': 'ic' (the state vector) and 'y0' (the settled \
1853             output) both set an initial condition -- give one or the other"
1854        ));
1855    }
1856
1857    let finite = |values: Vec<f64>| -> Result<Vec<f64>, String> {
1858        match values.iter().find(|v| !v.is_finite()) {
1859            Some(v) => Err(format!(
1860                "line {line}: device '{name}' initial condition must be finite (got {v})"
1861            )),
1862            None => Ok(values),
1863        }
1864    };
1865    // `ic=` as a state vector: a Python-style list, or a bare number for a one-state block.
1866    let state_vector = |text: &str, states: usize| -> Result<Vec<f64>, String> {
1867        let values = if text.trim().starts_with('[') {
1868            parse_vector(text, name, "ic", line_number)?
1869        } else {
1870            vec![text
1871                .trim()
1872                .parse::<f64>()
1873                .map_err(|_| format!("line {line}: device '{name}' field 'ic' is not a number"))?]
1874        };
1875        if values.len() != states {
1876            return Err(format!(
1877                "line {line}: device '{name}' field 'ic' has {} value(s), but this block has \
1878                 {states} state(s)",
1879                values.len()
1880            ));
1881        }
1882        finite(values)
1883    };
1884    let scalar = |text: &str, key: &str| -> Result<f64, String> {
1885        let v = text
1886            .trim()
1887            .parse::<f64>()
1888            .map_err(|_| format!("line {line}: device '{name}' field '{key}' is not a number"))?;
1889        finite(vec![v]).map(|v| v[0])
1890    };
1891    let settled = |result: Result<Vec<f64>, SettledStateError>, key: &str, what: &str| {
1892        result.map_err(|e| match e {
1893            SettledStateError::NoStates => format!(
1894                "line {line}: device '{name}' field '{key}': this {what} has no state to \
1895                 initialize (its denominator is a constant)"
1896            ),
1897            SettledStateError::ZeroDcNumerator => format!(
1898                "line {line}: device '{name}' field '{key}': this {what}'s numerator is zero \
1899                 at DC, so its settled output is always 0 and no state holds the requested one"
1900            ),
1901        })
1902    };
1903
1904    let Some(ic_text) = ic_text else {
1905        return match (kind, y0_text) {
1906            (BlockKind::TransferFunction(tf), Some(y0)) => settled(
1907                tf.settled_state(scalar(y0, "y0")?),
1908                "y0",
1909                "transfer function",
1910            )
1911            .map(Some),
1912            (BlockKind::DiscreteTransferFunction { tf, .. }, Some(y0)) => settled(
1913                tf.settled_state_discrete(scalar(y0, "y0")?),
1914                "y0",
1915                "transfer function",
1916            )
1917            .map(Some),
1918            _ => Ok(None),
1919        };
1920    };
1921
1922    let ic = match kind {
1923        BlockKind::StateSpace(ss) | BlockKind::DiscreteStateSpace { ss, .. } => {
1924            state_vector(ic_text, ss.states())?
1925        }
1926        BlockKind::TransferFunction(tf) | BlockKind::DiscreteTransferFunction { tf, .. } => {
1927            state_vector(ic_text, tf.den.len() - 1)?
1928        }
1929        BlockKind::Pid { pid, .. } => {
1930            if pid.ki == 0.0 {
1931                return Err(format!(
1932                    "line {line}: device '{name}' field 'ic' pre-loads the integrator, but this \
1933                     PID has ki=0 -- there is no integrator to hold it"
1934                ));
1935            }
1936            settled(
1937                pid.to_transfer_function()
1938                    .settled_state(scalar(ic_text, "ic")?),
1939                "ic",
1940                "PID",
1941            )?
1942        }
1943        BlockKind::DiscretePid { pid, .. } => {
1944            if pid.ki == 0.0 {
1945                return Err(format!(
1946                    "line {line}: device '{name}' field 'ic' pre-loads the integrator, but this \
1947                     PID has ki=0 -- there is no integrator to hold it"
1948                ));
1949            }
1950            vec![scalar(ic_text, "ic")? / pid.ki]
1951        }
1952        BlockKind::Vco(_) | BlockKind::PhaseShiftPwm { .. } => {
1953            let phase = scalar(ic_text, "ic")?;
1954            if !(0.0..1.0).contains(&phase) {
1955                return Err(format!(
1956                    "line {line}: device '{name}' field 'ic' is the initial phase in cycles and \
1957                     must satisfy 0 <= ic < 1 (got {phase})"
1958                ));
1959            }
1960            vec![phase]
1961        }
1962        BlockKind::Pmsm { .. } => state_vector(ic_text, 4)?,
1963        BlockKind::Hysteresis(_) | BlockKind::SrLatch { .. } | BlockKind::FlipFlop { .. } => {
1964            match ic_text.trim() {
1965                "0" => vec![0.0],
1966                "1" => vec![1.0],
1967                other => {
1968                    return Err(format!(
1969                        "line {line}: device '{name}' field 'ic' is the initial logic output \
1970                         and must be 0 or 1 (got '{other}')"
1971                    ))
1972                }
1973            }
1974        }
1975        BlockKind::Counter { modulus, .. } => {
1976            let count = ic_text.trim().parse::<i64>().map_err(|_| {
1977                format!("line {line}: device '{name}' field 'ic' is not an integer")
1978            })?;
1979            if let Some(m) = modulus {
1980                if count < 0 || count >= i64::from(*m) {
1981                    return Err(format!(
1982                        "line {line}: device '{name}' field 'ic' must satisfy 0 <= ic < \
1983                         modulus ({m}) (got {count})"
1984                    ));
1985                }
1986            }
1987            vec![count as f64]
1988        }
1989        _ => {
1990            return Err(format!(
1991                "line {line}: device '{name}' field 'ic': this kind has no state to \
1992                 initialize -- 'ic' is accepted on statespace, tf, pid, discretestatespace, \
1993                 discretetf, discretepid, vco, pspwm, pmsm, hysteresis, srlatch, the \
1994                 flip-flops, and counter"
1995            ))
1996        }
1997    };
1998    Ok(Some(ic))
1999}