Skip to main content

general_mna/
builder.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::fmt;
3
4use general_spice_core::ast::{ElementInstance, Statement};
5use general_spice_core::{lexer, parser, Dialect};
6
7use crate::{DeviceAnnotation, Expression, InitialCondition, Matrix, MnaSystem, TransientFunction};
8
9/// Treatment of parsed devices for which this linear MNA crate has no stamp.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum UnsupportedElementPolicy {
12    /// Stop and report the unsupported element.
13    Error,
14    /// Skip it and append a warning to the result.
15    IgnoreWithWarning,
16}
17
18/// State assigned to an idealized converter switch.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum SwitchState {
21    /// Use [`BuildOptions::on_resistance`].
22    On,
23    /// Use [`BuildOptions::off_resistance`].
24    Off,
25}
26
27/// Options controlling matrix construction.
28#[derive(Debug, Clone, PartialEq)]
29pub struct BuildOptions {
30    /// Handling of nonlinear or otherwise unstamped devices.
31    pub unsupported_elements: UnsupportedElementPolicy,
32    /// Case-insensitive element-name to switch state mapping.
33    pub switch_states: BTreeMap<String, SwitchState>,
34    /// Resistance used for switches in the on state.
35    pub on_resistance: Expression,
36    /// Resistance used for switches in the off state.
37    pub off_resistance: Expression,
38    /// Field names the caller owns, accepted on any device card, carried through to
39    /// [`MnaSystem::annotations`] verbatim and never stamped.
40    ///
41    /// Empty by default, which is exactly today's behaviour: an unregistered `key=value`
42    /// token is still rejected by [`validate_trailing_fields`], with the same message. A
43    /// registered name is accepted on *every* device letter, because the thing being
44    /// annotated is the component, not a particular stamp.
45    ///
46    /// Registration rather than a list of known rating names: `i_max` is a current limit to
47    /// a converter simulator and would be something else to the next consumer, so a name
48    /// baked in here would make a stamping library the owner of someone else's vocabulary,
49    /// and every new annotation would need a release of this crate before a netlist could
50    /// use it. Names are compared case-insensitively, like every other field.
51    pub annotation_fields: BTreeSet<String>,
52}
53
54impl Default for BuildOptions {
55    fn default() -> Self {
56        Self {
57            unsupported_elements: UnsupportedElementPolicy::Error,
58            switch_states: BTreeMap::new(),
59            on_resistance: Expression::symbol("Ron"),
60            off_resistance: Expression::symbol("Roff"),
61            annotation_fields: BTreeSet::new(),
62        }
63    }
64}
65
66impl BuildOptions {
67    /// Adds or replaces a case-insensitive switch-state override.
68    pub fn set_switch(&mut self, element_name: impl Into<String>, state: SwitchState) {
69        self.switch_states
70            .insert(normalize(&element_name.into()), state);
71    }
72
73    /// Registers a field name this crate will accept on any device card and hand back
74    /// through [`MnaSystem::annotations`] without interpreting it.
75    pub fn annotate(&mut self, field: impl AsRef<str>) {
76        self.annotation_fields
77            .insert(field.as_ref().to_ascii_lowercase());
78    }
79}
80
81/// Builds MNA systems from `general-spice-core` statements or netlist text.
82#[derive(Debug, Clone)]
83pub struct MnaBuilder {
84    dialect: Dialect,
85    options: BuildOptions,
86}
87
88impl MnaBuilder {
89    /// Creates a builder for a SPICE dialect.
90    pub fn new(dialect: Dialect) -> Self {
91        Self {
92            dialect,
93            options: BuildOptions::default(),
94        }
95    }
96
97    /// Creates a builder with explicit options.
98    pub fn with_options(dialect: Dialect, options: BuildOptions) -> Self {
99        Self { dialect, options }
100    }
101
102    /// Returns the build options.
103    pub fn options(&self) -> &BuildOptions {
104        &self.options
105    }
106
107    /// Returns mutable build options.
108    pub fn options_mut(&mut self) -> &mut BuildOptions {
109        &mut self.options
110    }
111
112    /// Parses a title-less netlist fragment and builds its MNA system.
113    pub fn build_fragment(&self, source: &str) -> Result<MnaSystem, BuildError> {
114        let lines = lexer::preprocess(source, self.dialect);
115        let parsed = parser::parse(&lines, self.dialect);
116        self.finish_parse(parsed)
117    }
118
119    /// Parses a complete SPICE document, whose first line is the title.
120    pub fn build_document(&self, source: &str) -> Result<MnaSystem, BuildError> {
121        let lines = lexer::preprocess(source, self.dialect);
122        let parsed = parser::parse_document(&lines, self.dialect);
123        self.finish_parse(parsed)
124    }
125
126    fn finish_parse(&self, parsed: Vec<parser::ParseResult>) -> Result<MnaSystem, BuildError> {
127        let mut statements = Vec::with_capacity(parsed.len());
128        for result in parsed {
129            match result {
130                Ok(statement) => statements.push(statement),
131                Err(error) => {
132                    return Err(BuildError::Parse {
133                        message: error.message,
134                        line_start: error.span.start,
135                        line_end: error.span.end,
136                    })
137                }
138            }
139        }
140        self.build_statements(&statements)
141    }
142
143    /// Builds an MNA system from an already parsed AST.
144    pub fn build_statements(&self, statements: &[Statement]) -> Result<MnaSystem, BuildError> {
145        let elements: Vec<&ElementInstance> = statements
146            .iter()
147            .filter_map(|statement| match statement {
148                Statement::ElementInstance(element) => Some(element),
149                _ => None,
150            })
151            .collect();
152
153        // Every element name is unique, case-insensitively, whatever the device letter.
154        //
155        // Checked here, once, for all of them -- not as a side effect of building something
156        // keyed by name. Doing it the second way is how this escaped for so long: a duplicate
157        // `V`, `I`, `L`, `E`, `H` or `D` name collided in `inputs`/`branches` and was rejected,
158        // because those letters own an entry there, while two resistors or two capacitors
159        // stamped on top of each other in silence and produced a system that solves. The
160        // numbers that came out were even right, since stamping is positional and never looks
161        // a name up -- but every *reference* by name (a `kind=rule` card's `target=`, a
162        // `kind=measure`, a controlling branch, a `.IC`, a caller's `switch_states`, a GUI's
163        // highlight) then resolves to one of the two arbitrarily, and the author is never told
164        // that the other one exists.
165        let mut seen: HashMap<String, &str> = HashMap::new();
166        for element in &elements {
167            if seen
168                .insert(normalize(&element.name), element.name.as_str())
169                .is_some()
170            {
171                return Err(BuildError::DuplicateElement(element.name.clone()));
172            }
173        }
174
175        for element in &elements {
176            // A switch-assigned element is stamped as a plain on/off admittance whatever its
177            // device letter, so its own positional grammar is not this crate's to enforce --
178            // only its `key=value` tokens, which would still be silently dropped.
179            let grammar = match self.switch_state(element) {
180                Some(_) => Some(PositionalGrammar::Unchecked),
181                None if is_stamped_letter(element.device_letter) => positional_grammar(element),
182                None => None,
183            };
184            if let Some(grammar) = grammar {
185                validate_trailing_fields(element, grammar, &self.options.annotation_fields)?;
186            }
187        }
188
189        let mut index = UnknownIndex::default();
190        for element in &elements {
191            if element.device_letter == 'K' {
192                continue;
193            }
194            let node_count = if self.switch_state(element).is_some() {
195                element.nodes.len().min(2)
196            } else {
197                element.nodes.len()
198            };
199            for node in &element.nodes[..node_count] {
200                index.add_node(node);
201            }
202        }
203        index.finish_nodes();
204
205        for element in &elements {
206            if self.is_branch_device(element) {
207                index.add_branch(&element.name)?;
208            }
209        }
210
211        let mut inputs = Vec::new();
212        let mut input_values = Vec::new();
213        let mut input_by_element = HashMap::new();
214        let mut transient_sources = BTreeMap::new();
215        for element in &elements {
216            if matches!(element.device_letter, 'V' | 'I') {
217                let column = inputs.len();
218                // Unique by the pass above, so this never overwrites a column.
219                input_by_element.insert(normalize(&element.name), column);
220                inputs.push(element.name.clone());
221                if let Some(transient_fn) = TransientFunction::parse_params(&element.raw_params) {
222                    // A time-varying source is stamped as a named symbol, not a baked
223                    // literal, exactly like a PWL diode's own `{name}_Ioff` just below --
224                    // the caller supplies its numeric value fresh at every step via
225                    // `evaluate`'s `values` map, using `transient_sources` to know it needs
226                    // to (see this type's own doc comment for the full contract).
227                    transient_sources.insert(element.name.clone(), transient_fn);
228                    input_values.push(Expression::symbol(element.name.clone()));
229                } else {
230                    input_values.push(source_value(element)?);
231                }
232            } else if element.device_letter == 'D' {
233                // A piecewise-linear (or otherwise externally companion-modeled) diode is
234                // stamped as a conductance (see the 'D' arm below) plus a Norton current
235                // source of value `{name}_Ioff`. Both are per-instance symbolic parameters —
236                // not parsed from the netlist, since which segment (and therefore which
237                // numeric G/Ioff) is active is decided per timestep by the caller's own
238                // piecewise-linear mode-selection, not by this crate. See `elspice-pwl`'s
239                // `docs/architecture.md` for why this is the right split of responsibility.
240                let column = inputs.len();
241                // Unique by the pass above, so this never overwrites a column.
242                input_by_element.insert(normalize(&element.name), column);
243                inputs.push(element.name.clone());
244                input_values.push(Expression::symbol(format!("{}_Ioff", element.name)));
245            }
246        }
247
248        // `ic=` initial conditions, resolved against the unknown ordering now that `index` is
249        // final. Deliberately collected *after* stamping and kept out of `a`/`k`/`b`/`u`: an
250        // initial condition constrains `x` at one instant, it does not change the circuit's
251        // equations. `MnaSystem::initial_state` turns these into a consistent starting vector.
252        let mut initial_conditions = Vec::new();
253        for element in &elements {
254            if self.switch_state(element).is_some() {
255                continue;
256            }
257            let Some(raw) = initial_condition_field(element) else {
258                continue;
259            };
260            let value = Expression::parse_scalar(raw).map_err(|message| {
261                BuildError::InvalidElementField {
262                    line: element.span.start,
263                    name: element.name.clone(),
264                    message: format!("field 'ic' is not a value: {message}"),
265                }
266            })?;
267            match element.device_letter {
268                'C' => {
269                    let (positive, negative) = two_nodes(element)?;
270                    initial_conditions.push(InitialCondition::CapacitorVoltage {
271                        element: element.name.clone(),
272                        positive: index.node(positive),
273                        negative: index.node(negative),
274                        value,
275                    });
276                }
277                'L' => initial_conditions.push(InitialCondition::InductorCurrent {
278                    element: element.name.clone(),
279                    branch: index.branch(&element.name)?,
280                    value,
281                }),
282                // Unreachable: `accepted_fields` only offers `ic` on `C`/`L`, so any other
283                // letter carrying one was already rejected by `validate_trailing_fields`.
284                _ => unreachable!("ic= accepted only on C and L"),
285            }
286        }
287
288        // Registered annotations, collected for every element whatever its letter and
289        // whatever its grammar, and deliberately independent of stamping: nothing below
290        // reads `annotations`, and no annotation reaches `a`/`k`/`b`/`u`. Netlist order,
291        // and card order within a line, so a report can point at them in the order a
292        // reader wrote them.
293        let mut annotations = Vec::new();
294        if !self.options.annotation_fields.is_empty() {
295            for element in &elements {
296                for token in &element.raw_params {
297                    let Some((key, value)) = as_field(token) else {
298                        continue;
299                    };
300                    if !self.options.annotation_fields.contains(&key) {
301                        continue;
302                    }
303                    // A field this crate stamps is never an annotation, even when the caller
304                    // registered its name. `validate_trailing_fields` checks `accepted` first
305                    // for the same reason, and the two must agree: without this, a registered
306                    // `ic` became an initial condition *and* an annotation, and a consumer
307                    // reading the annotations would have seen a rating that was really a
308                    // starting value.
309                    if accepted_fields(element.device_letter)
310                        .iter()
311                        .any(|stamped| *stamped == key)
312                    {
313                        continue;
314                    }
315                    annotations.push(DeviceAnnotation {
316                        element: element.name.clone(),
317                        device_letter: element.device_letter,
318                        key,
319                        value: value.to_string(),
320                        line: element.span.start,
321                    });
322                }
323            }
324        }
325
326        let mut warnings = Vec::new();
327
328        // `.IC V(node)=value` / `.IC I(inductor)=value` lines (already dotted-path-resolved by
329        // `hierarchy::flatten` when written inside a `.subckt` body). `general-spice-core`
330        // parses the directive into `Statement::Ic`; until now nothing here read it, so a
331        // deck's `.IC` line was accepted and its run started from rest anyway -- the one
332        // outcome an initial condition must never have. Each assignment becomes the very same
333        // `InitialCondition` an `ic=` field produces (a node voltage is a "capacitor voltage"
334        // whose second terminal is ground), so `MnaSystem::initial_state` applies it, and
335        // checks it against every `ic=`, with no separate code path. `.NODESET` is a hint to
336        // an operating-point solve this crate does not perform, so it is reported as a
337        // warning rather than dropped without a trace.
338        for statement in statements {
339            match statement {
340                Statement::Ic(assignments, span) => {
341                    for (target, raw) in assignments {
342                        initial_conditions.push(dot_ic_condition(
343                            target, raw, span.start, &elements, &index,
344                        )?);
345                    }
346                }
347                Statement::Nodeset(_, span) | Statement::NodesetAll(_, span) => {
348                    warnings.push(format!(
349                        "line {}: .NODESET is a hint for a DC operating-point solve, which \
350                         this crate does not perform -- it has no effect here; use .IC or ic= \
351                         to declare a starting state",
352                        span.start
353                    ));
354                }
355                _ => {}
356            }
357        }
358
359        let order = index.names.len();
360        let mut a = Matrix::filled(order, order, Expression::zero());
361        let mut k = Matrix::filled(order, order, Expression::zero());
362        let mut b = Matrix::filled(order, inputs.len(), Expression::zero());
363
364        let inductances = elements
365            .iter()
366            .filter(|element| element.device_letter == 'L')
367            .map(|element| Ok((normalize(&element.name), scalar_value(element)?)))
368            .collect::<Result<HashMap<_, _>, BuildError>>()?;
369
370        for element in elements {
371            if let Some(state) = self.switch_state(element) {
372                let resistance = match state {
373                    SwitchState::On => self.options.on_resistance.clone(),
374                    SwitchState::Off => self.options.off_resistance.clone(),
375                };
376                stamp_admittance(&mut a, &index, element, resistance.reciprocal())?;
377                continue;
378            }
379
380            match element.device_letter {
381                'R' => {
382                    stamp_admittance(&mut a, &index, element, scalar_value(element)?.reciprocal())?
383                }
384                'C' => stamp_admittance(&mut k, &index, element, scalar_value(element)?)?,
385                'L' => stamp_inductor(&mut a, &mut k, &index, element)?,
386                'V' => stamp_voltage_source(
387                    &mut a,
388                    &mut b,
389                    &index,
390                    element,
391                    input_by_element[&normalize(&element.name)],
392                )?,
393                'I' => stamp_current_source(
394                    &mut b,
395                    &index,
396                    element,
397                    input_by_element[&normalize(&element.name)],
398                )?,
399                'G' => stamp_vccs(&mut a, &index, element)?,
400                'E' => stamp_vcvs(&mut a, &index, element)?,
401                'F' => stamp_cccs(&mut a, &index, element)?,
402                'H' => stamp_ccvs(&mut a, &index, element)?,
403                'K' => stamp_mutual_inductance(&mut k, &index, element, &inductances)?,
404                'D' => {
405                    let conductance = Expression::symbol(format!("{}_G", element.name));
406                    stamp_admittance(&mut a, &index, element, conductance)?;
407                    stamp_current_source(
408                        &mut b,
409                        &index,
410                        element,
411                        input_by_element[&normalize(&element.name)],
412                    )?;
413                }
414                _ => self.unsupported(element, &mut warnings)?,
415            }
416        }
417
418        let mut u = vec![Expression::zero(); order];
419        for row in 0..order {
420            for column in 0..inputs.len() {
421                u[row] = u[row].clone() + b[(row, column)].clone() * input_values[column].clone();
422            }
423        }
424
425        let mut parameter_defaults = BTreeMap::new();
426        for statement in statements {
427            if let Statement::Param(param) | Statement::GlobalParam(param) = statement {
428                for (name, raw_value) in &param.assignments {
429                    if let Ok(value) = Expression::parse_scalar(raw_value) {
430                        parameter_defaults.insert(name.clone(), value);
431                    } else {
432                        warnings.push(format!(
433                            "parameter '{name}' has an expression that is preserved by general-spice-core but is not a scalar MNA value"
434                        ));
435                    }
436                }
437            }
438        }
439
440        Ok(MnaSystem {
441            a,
442            k,
443            b,
444            u,
445            unknowns: index.names,
446            inputs,
447            input_values,
448            transient_sources,
449            initial_conditions,
450            parameter_defaults,
451            warnings,
452            annotations,
453        })
454    }
455
456    fn is_branch_device(&self, element: &ElementInstance) -> bool {
457        self.switch_state(element).is_none()
458            && matches!(element.device_letter, 'V' | 'L' | 'E' | 'H')
459    }
460
461    fn switch_state(&self, element: &ElementInstance) -> Option<SwitchState> {
462        self.options
463            .switch_states
464            .get(&normalize(&element.name))
465            .copied()
466    }
467
468    fn unsupported(
469        &self,
470        element: &ElementInstance,
471        warnings: &mut Vec<String>,
472    ) -> Result<(), BuildError> {
473        let message = format!(
474            "element '{}' (device {}) has no linear MNA stamp",
475            element.name, element.device_letter
476        );
477        match self.options.unsupported_elements {
478            UnsupportedElementPolicy::Error => Err(BuildError::UnsupportedElement(message)),
479            UnsupportedElementPolicy::IgnoreWithWarning => {
480                warnings.push(message);
481                Ok(())
482            }
483        }
484    }
485}
486
487#[derive(Debug, Default)]
488struct UnknownIndex {
489    names: Vec<String>,
490    nodes: HashMap<String, usize>,
491    branches: HashMap<String, usize>,
492    nodes_finished: bool,
493}
494
495impl UnknownIndex {
496    fn add_node(&mut self, name: &str) {
497        if is_ground(name) {
498            return;
499        }
500        let key = normalize(name);
501        if !self.nodes.contains_key(&key) {
502            let index = self.names.len();
503            self.nodes.insert(key, index);
504            self.names.push(format!("V({name})"));
505        }
506    }
507
508    fn finish_nodes(&mut self) {
509        self.nodes_finished = true;
510    }
511
512    fn add_branch(&mut self, name: &str) -> Result<(), BuildError> {
513        debug_assert!(self.nodes_finished);
514        let key = normalize(name);
515        if self.branches.contains_key(&key) {
516            return Err(BuildError::DuplicateElement(name.to_string()));
517        }
518        let index = self.names.len();
519        self.branches.insert(key, index);
520        self.names.push(format!("I({name})"));
521        Ok(())
522    }
523
524    fn node(&self, name: &str) -> Option<usize> {
525        if is_ground(name) {
526            None
527        } else {
528            self.nodes.get(&normalize(name)).copied()
529        }
530    }
531
532    fn branch(&self, name: &str) -> Result<usize, BuildError> {
533        self.branches
534            .get(&normalize(name))
535            .copied()
536            .ok_or_else(|| BuildError::UnknownControllingBranch(name.to_string()))
537    }
538}
539
540fn stamp(
541    matrix: &mut Matrix<Expression>,
542    row: Option<usize>,
543    col: Option<usize>,
544    value: Expression,
545) {
546    if let (Some(row), Some(col)) = (row, col) {
547        matrix[(row, col)] = matrix[(row, col)].clone() + value;
548    }
549}
550
551fn stamp_input(matrix: &mut Matrix<Expression>, row: Option<usize>, col: usize, value: Expression) {
552    if let Some(row) = row {
553        matrix[(row, col)] = matrix[(row, col)].clone() + value;
554    }
555}
556
557fn two_nodes(element: &ElementInstance) -> Result<(&str, &str), BuildError> {
558    match element.nodes.as_slice() {
559        [positive, negative, ..] => Ok((positive, negative)),
560        _ => Err(BuildError::InvalidElement {
561            name: element.name.clone(),
562            message: "requires two terminals".into(),
563        }),
564    }
565}
566
567fn four_nodes(element: &ElementInstance) -> Result<(&str, &str, &str, &str), BuildError> {
568    match element.nodes.as_slice() {
569        [out_positive, out_negative, ctrl_positive, ctrl_negative] => {
570            Ok((out_positive, out_negative, ctrl_positive, ctrl_negative))
571        }
572        _ => Err(BuildError::InvalidElement {
573            name: element.name.clone(),
574            message: "requires the classic four-node linear form".into(),
575        }),
576    }
577}
578
579fn stamp_admittance(
580    matrix: &mut Matrix<Expression>,
581    index: &UnknownIndex,
582    element: &ElementInstance,
583    admittance: Expression,
584) -> Result<(), BuildError> {
585    let (positive, negative) = two_nodes(element)?;
586    let p = index.node(positive);
587    let n = index.node(negative);
588    stamp(matrix, p, p, admittance.clone());
589    stamp(matrix, n, n, admittance.clone());
590    stamp(matrix, p, n, -admittance.clone());
591    stamp(matrix, n, p, -admittance);
592    Ok(())
593}
594
595fn stamp_branch_incidence(
596    matrix: &mut Matrix<Expression>,
597    index: &UnknownIndex,
598    element: &ElementInstance,
599) -> Result<usize, BuildError> {
600    let (positive, negative) = two_nodes(element)?;
601    let branch = index.branch(&element.name)?;
602    let p = index.node(positive);
603    let n = index.node(negative);
604    stamp(matrix, p, Some(branch), Expression::one());
605    stamp(matrix, n, Some(branch), -Expression::one());
606    stamp(matrix, Some(branch), p, Expression::one());
607    stamp(matrix, Some(branch), n, -Expression::one());
608    Ok(branch)
609}
610
611fn stamp_inductor(
612    a: &mut Matrix<Expression>,
613    k: &mut Matrix<Expression>,
614    index: &UnknownIndex,
615    element: &ElementInstance,
616) -> Result<(), BuildError> {
617    let branch = stamp_branch_incidence(a, index, element)?;
618    stamp(k, Some(branch), Some(branch), -scalar_value(element)?);
619    Ok(())
620}
621
622fn stamp_voltage_source(
623    a: &mut Matrix<Expression>,
624    b: &mut Matrix<Expression>,
625    index: &UnknownIndex,
626    element: &ElementInstance,
627    input: usize,
628) -> Result<(), BuildError> {
629    let branch = stamp_branch_incidence(a, index, element)?;
630    stamp_input(b, Some(branch), input, Expression::one());
631    Ok(())
632}
633
634fn stamp_current_source(
635    b: &mut Matrix<Expression>,
636    index: &UnknownIndex,
637    element: &ElementInstance,
638    input: usize,
639) -> Result<(), BuildError> {
640    let (positive, negative) = two_nodes(element)?;
641    stamp_input(b, index.node(positive), input, -Expression::one());
642    stamp_input(b, index.node(negative), input, Expression::one());
643    Ok(())
644}
645
646fn stamp_vccs(
647    a: &mut Matrix<Expression>,
648    index: &UnknownIndex,
649    element: &ElementInstance,
650) -> Result<(), BuildError> {
651    let (op, on, cp, cn) = four_nodes(element)?;
652    let gain = scalar_value(element)?;
653    stamp(a, index.node(op), index.node(cp), gain.clone());
654    stamp(a, index.node(op), index.node(cn), -gain.clone());
655    stamp(a, index.node(on), index.node(cp), -gain.clone());
656    stamp(a, index.node(on), index.node(cn), gain);
657    Ok(())
658}
659
660fn stamp_vcvs(
661    a: &mut Matrix<Expression>,
662    index: &UnknownIndex,
663    element: &ElementInstance,
664) -> Result<(), BuildError> {
665    let (_, _, cp, cn) = four_nodes(element)?;
666    let branch = stamp_branch_incidence(a, index, element)?;
667    let gain = scalar_value(element)?;
668    stamp(a, Some(branch), index.node(cp), -gain.clone());
669    stamp(a, Some(branch), index.node(cn), gain);
670    Ok(())
671}
672
673fn stamp_cccs(
674    a: &mut Matrix<Expression>,
675    index: &UnknownIndex,
676    element: &ElementInstance,
677) -> Result<(), BuildError> {
678    let (positive, negative) = two_nodes(element)?;
679    let (control, gain) = control_and_gain(element)?;
680    let control = index.branch(control)?;
681    stamp(a, index.node(positive), Some(control), gain.clone());
682    stamp(a, index.node(negative), Some(control), -gain);
683    Ok(())
684}
685
686fn stamp_ccvs(
687    a: &mut Matrix<Expression>,
688    index: &UnknownIndex,
689    element: &ElementInstance,
690) -> Result<(), BuildError> {
691    let branch = stamp_branch_incidence(a, index, element)?;
692    let (control, gain) = control_and_gain(element)?;
693    let control = index.branch(control)?;
694    stamp(a, Some(branch), Some(control), -gain);
695    Ok(())
696}
697
698fn stamp_mutual_inductance(
699    k_matrix: &mut Matrix<Expression>,
700    index: &UnknownIndex,
701    element: &ElementInstance,
702    inductances: &HashMap<String, Expression>,
703) -> Result<(), BuildError> {
704    if element.nodes.len() < 2 {
705        return Err(BuildError::InvalidElement {
706            name: element.name.clone(),
707            message: "requires at least two inductor names".into(),
708        });
709    }
710    let coefficient = scalar_value(element)?;
711    for first in 0..element.nodes.len() {
712        for second in first + 1..element.nodes.len() {
713            let first_name = &element.nodes[first];
714            let second_name = &element.nodes[second];
715            let first_l = inductances
716                .get(&normalize(first_name))
717                .ok_or_else(|| BuildError::UnknownInductor(first_name.clone()))?;
718            let second_l = inductances
719                .get(&normalize(second_name))
720                .ok_or_else(|| BuildError::UnknownInductor(second_name.clone()))?;
721            let mutual = coefficient.clone() * (first_l.clone() * second_l.clone()).sqrt();
722            let first_branch = index.branch(first_name)?;
723            let second_branch = index.branch(second_name)?;
724            stamp(
725                k_matrix,
726                Some(first_branch),
727                Some(second_branch),
728                -mutual.clone(),
729            );
730            stamp(k_matrix, Some(second_branch), Some(first_branch), -mutual);
731        }
732    }
733    Ok(())
734}
735
736/// Device letters this crate has a linear stamp for, and therefore holds to a known parameter
737/// grammar. Anything else is `UnsupportedElementPolicy`'s business (error, or skip with a
738/// warning) and is deliberately *not* field-checked here: a `M`/`Q`/`J` card's own `L=1u W=10u`
739/// is perfectly valid netlist text this crate simply has no model for, and rejecting its fields
740/// would turn `IgnoreWithWarning` into a hard error.
741fn is_stamped_letter(device_letter: char) -> bool {
742    matches!(
743        device_letter,
744        'R' | 'C' | 'L' | 'K' | 'V' | 'I' | 'E' | 'F' | 'G' | 'H' | 'D'
745    )
746}
747
748/// The trailing `key=value` fields this crate understands on a device card it stamps, keyed by
749/// device letter and compared case-insensitively.
750///
751/// `general-spice-core` deliberately hands every token after the node list over uninterpreted,
752/// in [`ElementInstance::raw_params`]; deciding what they mean is this crate's job. Any key not
753/// listed here is rejected rather than dropped, because dropping it is not a harmless no-op —
754/// a silently ignored `tc1=`/`temp=`/`m=`, or a misspelled `ic=`, produces a plausible-looking
755/// waveform for a *different* circuit than the one the author wrote, with nothing on screen to
756/// say so.
757fn accepted_fields(device_letter: char) -> &'static [&'static str] {
758    match device_letter {
759        // See `MnaSystem::initial_conditions` for what `ic=` means on each, sign included.
760        'C' | 'L' => &["ic"],
761        _ => &[],
762    }
763}
764
765/// What a stamped device letter's *positional* (non-`key=value`) parameter list may contain.
766///
767/// `general-spice-core` hands every token after the node list over uninterpreted, so a
768/// positional token this crate does not read is dropped exactly as silently as an unknown
769/// field was before — `V1 1 0 10 wibble` and `V1 1 0 SNI(0 1 1k)` both used to simulate a
770/// plain 10 V / 0 V source and say nothing. These are the shapes each letter actually permits.
771#[derive(Debug, Clone, Copy, PartialEq, Eq)]
772enum PositionalGrammar {
773    /// Exactly one token, the element's own value. `R`/`C`/`L` (resistance, capacitance,
774    /// inductance), `K` (coupling coefficient — `general-spice-core` puts every earlier token
775    /// in `nodes` as an inductor name), and `E`/`G` in the classic four-node form, whose single
776    /// parameter is the gain.
777    OneValue,
778    /// Exactly two tokens: a controlling source's name, then a gain — `F`/`H`. The name itself
779    /// is checked later, by `UnknownControllingBranch`.
780    ControlAndGain,
781    /// An independent source's clause list — `V`/`I`. See [`validate_source_positional`].
782    SourceClauses,
783    /// A diode's model name, optional area factor and optional `OFF` — `D`. See
784    /// [`validate_diode_positional`], including what about it is deliberately not checked.
785    DiodeModel,
786    /// Positional tokens this crate deliberately does not check, while still checking the
787    /// card's `key=value` fields. Used for a switch-assigned element, whose parameters are
788    /// replaced wholesale by the on/off resistance.
789    Unchecked,
790}
791
792/// The positional grammar to hold `element` to, or `None` to skip validating the card entirely.
793///
794/// `None` is only ever returned for the two-node behavioral form of `E`/`G`
795/// (`E1 out 0 VALUE={...}` / `TABLE` / `POLY`), which this crate does not stamp at all: its
796/// tokens are neither a gain nor `key=value` fields, and `four_nodes` already rejects the card
797/// with a message that says exactly what is missing ("requires the classic four-node linear
798/// form"). Field-checking it first would replace that with a misleading `unknown field 'value'`.
799fn positional_grammar(element: &ElementInstance) -> Option<PositionalGrammar> {
800    match element.device_letter {
801        'R' | 'C' | 'L' | 'K' => Some(PositionalGrammar::OneValue),
802        'E' | 'G' if element.nodes.len() == 4 => Some(PositionalGrammar::OneValue),
803        'E' | 'G' => None,
804        'F' | 'H' => Some(PositionalGrammar::ControlAndGain),
805        'V' | 'I' => Some(PositionalGrammar::SourceClauses),
806        'D' => Some(PositionalGrammar::DiodeModel),
807        _ => Some(PositionalGrammar::Unchecked),
808    }
809}
810
811/// Splits a raw trailing token into `(key, value)` if it has the `key=value` shape, with the key
812/// lowercased for the case-insensitive comparison every SPICE dialect expects. A token with no
813/// `=`, or with an empty key (`=5`), is positional, not a field.
814fn as_field(token: &str) -> Option<(String, &str)> {
815    let (key, value) = token.split_once('=')?;
816    let key = key.trim();
817    if key.is_empty() {
818        return None;
819    }
820    Some((key.to_ascii_lowercase(), value))
821}
822
823/// Rejects a trailing token this crate would otherwise silently discard.
824///
825/// Mirrors the block (`kind=...`) parser's own diagnostics in
826/// [`crate::system_builder`] — same `line N: device '<name>' ...` shape — so a device card and a
827/// block line report a bad field the same way.
828///
829/// Two passes, because they fail for different reasons: every `key=value` token is checked
830/// against [`accepted_fields`], and whatever is left over — the positional tokens, in order —
831/// is checked against the letter's own [`PositionalGrammar`].
832fn validate_trailing_fields(
833    element: &ElementInstance,
834    grammar: PositionalGrammar,
835    annotation_fields: &BTreeSet<String>,
836) -> Result<(), BuildError> {
837    let letter = element.device_letter;
838    let accepted = accepted_fields(letter);
839    let mut positional: Vec<&str> = Vec::new();
840
841    for token in &element.raw_params {
842        let Some((key, _)) = as_field(token) else {
843            positional.push(token.as_str());
844            continue;
845        };
846        if accepted.iter().any(|allowed| *allowed == key) {
847            continue;
848        }
849        // A field the caller registered through `BuildOptions::annotate`. Accepted on any
850        // device letter and collected into `MnaSystem::annotations`; this crate never reads
851        // its value. Checked after `accepted` so a stamped field can never be shadowed by a
852        // registration — `ic` on a capacitor stays an initial condition.
853        if annotation_fields.contains(&key) {
854            continue;
855        }
856        return Err(BuildError::InvalidElementField {
857            line: element.span.start,
858            name: element.name.clone(),
859            message: match accepted {
860                [] => {
861                    format!("unknown field '{key}' (device {letter} accepts no key=value fields)")
862                }
863                _ => format!(
864                    "unknown field '{key}' (device {letter} accepts only: {})",
865                    accepted.join(", ")
866                ),
867            },
868        });
869    }
870
871    match grammar {
872        PositionalGrammar::OneValue if positional.len() > 1 => Err(field_error(
873            element,
874            format!(
875                "unexpected extra parameter '{}' (device {letter} takes exactly one value{})",
876                positional[1],
877                accepted_suffix(accepted)
878            ),
879        )),
880        PositionalGrammar::ControlAndGain if positional.len() > 2 => Err(field_error(
881            element,
882            format!(
883                "unexpected extra parameter '{}' (device {letter} takes exactly two values, a \
884                 controlling source name and a gain)",
885                positional[2]
886            ),
887        )),
888        PositionalGrammar::SourceClauses => validate_source_positional(element, &positional),
889        PositionalGrammar::DiodeModel => validate_diode_positional(element, &positional),
890        _ => Ok(()),
891    }
892}
893
894/// A positional-token diagnostic on `element`, in the same shape as the field diagnostics above.
895fn field_error(element: &ElementInstance, message: String) -> BuildError {
896    BuildError::InvalidElementField {
897        line: element.span.start,
898        name: element.name.clone(),
899        message,
900    }
901}
902
903/// Whether `token` is a value this crate can read — a SPICE number with or without a suffix, a
904/// symbol resolved later from `.param`, or a braced expression. Not a judgement about physical
905/// units, only about shape.
906fn is_value_token(token: &str) -> bool {
907    Expression::parse_scalar(token).is_ok()
908}
909
910/// Validates the positional parameters of an independent source card (`V`/`I`).
911///
912/// The grammar is a sequence of clauses, in any order, each of which this crate either reads or
913/// knowingly ignores:
914///
915/// - a bare value as the very first token — the implicit DC value (`V1 1 0 10`);
916/// - `DC <value>` — the explicit spelling of the same thing;
917/// - `AC <magnitude> [<phase>]` — read by no analysis this crate implements yet, but valid, and
918///   so accepted rather than rejected;
919/// - one call to one of [`TransientFunction::FUNCTION_NAMES`], whose arguments must actually
920///   parse as that function's parameter list.
921///
922/// Anything else is a typo. A second bare value (`V1 1 0 10 20`), a trailing word
923/// (`V1 1 0 10 wibble`), a misspelled function (`SNI(0 1 1k)`), a `DC` with nothing after it,
924/// and an unterminated argument list are all rejected here instead of being dropped.
925///
926/// Deliberately not checked: a symbol where an `AC` magnitude or phase belongs. `AC {gain}` is
927/// a legitimate parameterized magnitude, and nothing in the token itself distinguishes it from
928/// a misspelling, so at most two value-shaped tokens are consumed after `AC` and a third one
929/// falls through to the "unexpected extra value" arm.
930fn validate_source_positional(
931    element: &ElementInstance,
932    positional: &[&str],
933) -> Result<(), BuildError> {
934    let letter = element.device_letter;
935    let mut index = 0usize;
936    let mut seen_dc = false;
937    let mut seen_ac = false;
938    let mut seen_function = false;
939
940    while index < positional.len() {
941        let token = positional[index];
942        if token.eq_ignore_ascii_case("dc") {
943            if seen_dc {
944                return Err(field_error(
945                    element,
946                    format!("device {letter} declares a DC value more than once"),
947                ));
948            }
949            seen_dc = true;
950            match positional.get(index + 1) {
951                Some(value) if is_value_token(value) => index += 2,
952                Some(value) => {
953                    return Err(field_error(
954                        element,
955                        format!("'dc' is followed by '{value}', which is not a value"),
956                    ))
957                }
958                None => {
959                    return Err(field_error(
960                        element,
961                        "'dc' is not followed by a value".to_string(),
962                    ))
963                }
964            }
965        } else if token.eq_ignore_ascii_case("ac") {
966            if seen_ac {
967                return Err(field_error(
968                    element,
969                    format!("device {letter} declares an AC specification more than once"),
970                ));
971            }
972            seen_ac = true;
973            let mut consumed = 0usize;
974            while consumed < 2 {
975                match positional.get(index + 1 + consumed) {
976                    Some(next)
977                        if !next.eq_ignore_ascii_case("dc")
978                            && !next.eq_ignore_ascii_case("ac")
979                            && !next.contains('(')
980                            && is_value_token(next) =>
981                    {
982                        consumed += 1
983                    }
984                    _ => break,
985                }
986            }
987            if consumed == 0 {
988                return Err(field_error(
989                    element,
990                    "'ac' is not followed by a magnitude".to_string(),
991                ));
992            }
993            index += 1 + consumed;
994        } else if let Some(paren) = token.find('(') {
995            let name = &token[..paren];
996            if !TransientFunction::is_function_name(name) {
997                return Err(field_error(
998                    element,
999                    format!(
1000                        "unknown source function '{name}' (device {letter} accepts {})",
1001                        TransientFunction::FUNCTION_NAMES.join("/")
1002                    ),
1003                ));
1004            }
1005            if seen_function {
1006                return Err(field_error(
1007                    element,
1008                    format!("device {letter} declares more than one transient function"),
1009                ));
1010            }
1011            seen_function = true;
1012            let Some(end) = positional[index..]
1013                .iter()
1014                .position(|token| token.contains(')'))
1015                .map(|offset| offset + index)
1016            else {
1017                return Err(field_error(
1018                    element,
1019                    format!("'{name}(' is never closed by a ')'"),
1020                ));
1021            };
1022            let call: Vec<String> = positional[index..=end]
1023                .iter()
1024                .map(|token| (*token).to_string())
1025                .collect();
1026            if TransientFunction::parse(&call).is_none() {
1027                return Err(field_error(
1028                    element,
1029                    format!("'{}' is not a valid {name} parameter list", call.join(" ")),
1030                ));
1031            }
1032            index = end + 1;
1033        } else if index == 0 && is_value_token(token) {
1034            // The implicit DC value, which SPICE allows only in first position.
1035            seen_dc = true;
1036            index += 1;
1037        } else {
1038            return Err(field_error(
1039                element,
1040                format!(
1041                    "unexpected extra parameter '{token}' (device {letter} takes a DC value, an \
1042                     'ac' specification, and/or one of {}{})",
1043                    TransientFunction::FUNCTION_NAMES.join("/"),
1044                    accepted_suffix(accepted_fields(letter))
1045                ),
1046            ));
1047        }
1048    }
1049    Ok(())
1050}
1051
1052/// Validates the positional parameters of a diode card (`D`).
1053///
1054/// SPICE's grammar here is a model name, an optional area factor and an optional `OFF` hint, so
1055/// at most one non-`OFF` token beyond the model name is permitted, it has to be value-shaped,
1056/// and `OFF` may not be repeated.
1057///
1058/// **The model name itself is deliberately not checked, and cannot be.** This crate does not
1059/// stamp a diode from a device model at all — a `D` card becomes a symbolic conductance
1060/// `{name}_G` plus a Norton current `{name}_Ioff` that the caller resolves per timestep (see
1061/// the `'D'` arm of `build_statements`), so there is no model parameter set here to check a
1062/// name against. Even a crate that did have one could not decide the question from the netlist
1063/// alone: the `.model` card may live behind an `.include` this crate never resolves, so an
1064/// unrecognized name means "not found here", not "misspelled". A misspelled diode model name
1065/// is therefore a known, documented limit of this validation, recorded in the README.
1066fn validate_diode_positional(
1067    element: &ElementInstance,
1068    positional: &[&str],
1069) -> Result<(), BuildError> {
1070    let mut off = 0usize;
1071    let mut values: Vec<&str> = Vec::new();
1072    for token in positional {
1073        if token.eq_ignore_ascii_case("off") {
1074            off += 1;
1075        } else {
1076            values.push(token);
1077        }
1078    }
1079    if off > 1 {
1080        return Err(field_error(
1081            element,
1082            "'off' is given more than once".to_string(),
1083        ));
1084    }
1085    if let Some(area) = values.get(1) {
1086        if !is_value_token(area) {
1087            return Err(field_error(
1088                element,
1089                format!("'{area}' is not a value (device D's second parameter is its area factor)"),
1090            ));
1091        }
1092    }
1093    if let Some(extra) = values.get(2) {
1094        return Err(field_error(
1095            element,
1096            format!(
1097                "unexpected extra parameter '{extra}' (device D takes a model name, an optional \
1098                 area factor and an optional 'off')"
1099            ),
1100        ));
1101    }
1102    Ok(())
1103}
1104
1105/// The ", plus ..." tail of the extra-positional message, so a resistor (no fields at all) does
1106/// not advertise an empty list.
1107fn accepted_suffix(accepted: &'static [&'static str]) -> String {
1108    match accepted {
1109        [] => String::new(),
1110        _ => format!(", plus optional {}", accepted.join("/")),
1111    }
1112}
1113
1114/// The raw text of a device card's `ic=` field, if it declares one. Already validated as an
1115/// accepted key by [`validate_trailing_fields`], so reaching this on anything but `C`/`L` is a
1116/// bug, not bad input.
1117/// Resolves one `.IC` assignment into the [`InitialCondition`] an `ic=` field would have
1118/// produced, against the finished unknown index.
1119///
1120/// Accepted targets, case-insensitively: `V(<node>)`, the node's voltage above ground (a
1121/// [`InitialCondition::CapacitorVoltage`] with a ground second terminal); `V(<n1>,<n2>)`, the
1122/// difference `V(n1) - V(n2)` (both terminals as written); `I(<inductor>)`, the current through
1123/// that inductor from its first node to its second, the same sign as `ic=` on the card itself.
1124/// `I(...)` of anything but an inductor (a voltage source has a branch current too, but no state
1125/// to start) is rejected: an initial *state* is what `.IC` declares.
1126///
1127/// Every value flows into `MnaSystem::initial_state` exactly like an `ic=`, so a `.IC V(b)=5`
1128/// next to `C1 b 0 1e-6 ic=4` is reported by the same `ConflictingConditions` check as two
1129/// disagreeing `ic=` capacitors, not resolved in favour of whichever came last.
1130///
1131/// Targets arrive here already flat: a `.IC` written inside a `.subckt` body has had its node
1132/// and element names resolved by `hierarchy::flatten` (port -> caller's node, internal name ->
1133/// `X1.`-prefixed, ground unchanged) before `build_statements` runs, so the unknown index is
1134/// the only namespace this function ever looks names up in.
1135fn dot_ic_condition(
1136    target: &str,
1137    raw_value: &str,
1138    line: usize,
1139    elements: &[&ElementInstance],
1140    index: &UnknownIndex,
1141) -> Result<InitialCondition, BuildError> {
1142    let error = |message: String| BuildError::InvalidInitialConditionDirective {
1143        line,
1144        target: target.to_string(),
1145        message,
1146    };
1147    let target_trimmed = target.trim();
1148    let Some((kind, inner)) = target_trimmed
1149        .strip_suffix(')')
1150        .and_then(|without_close| without_close.split_once('('))
1151    else {
1152        return Err(error(
1153            "is not of the form V(<node>), V(<node>,<node>) or I(<inductor>)".into(),
1154        ));
1155    };
1156    let value = Expression::parse_scalar(raw_value)
1157        .map_err(|message| error(format!("value '{raw_value}' is not a value: {message}")))?;
1158    let element_label = format!(".IC {target_trimmed}");
1159
1160    let node_index = |name: &str| -> Result<Option<usize>, BuildError> {
1161        let name = name.trim();
1162        if is_ground(name) {
1163            return Ok(None);
1164        }
1165        index
1166            .node(name)
1167            .map(Some)
1168            .ok_or_else(|| error(format!("names node '{name}', which no element connects to")))
1169    };
1170
1171    match kind.trim().to_ascii_uppercase().as_str() {
1172        "V" => {
1173            let (positive, negative) = match inner.split_once(',') {
1174                Some((first, second)) => (node_index(first)?, node_index(second)?),
1175                None => (node_index(inner)?, None),
1176            };
1177            if positive.is_none() && negative.is_none() {
1178                return Err(error(
1179                    "assigns a voltage to ground, which is the reference and is always 0".into(),
1180                ));
1181            }
1182            Ok(InitialCondition::CapacitorVoltage {
1183                element: element_label,
1184                positive,
1185                negative,
1186                value,
1187            })
1188        }
1189        "I" => {
1190            let name = inner.trim();
1191            let Some(element) = elements
1192                .iter()
1193                .find(|element| element.name.eq_ignore_ascii_case(name))
1194            else {
1195                return Err(error(format!(
1196                    "names element '{name}', which this netlist does not declare"
1197                )));
1198            };
1199            if element.device_letter != 'L' {
1200                return Err(error(format!(
1201                    "names '{name}', which is not an inductor -- I(...) declares an inductor's \
1202                     initial current; a node voltage is V(<node>)"
1203                )));
1204            }
1205            Ok(InitialCondition::InductorCurrent {
1206                element: element_label,
1207                branch: index.branch(name).map_err(|_| {
1208                    error(format!(
1209                        "names '{name}', which has no branch current in this system (a \
1210                         switch-assigned element is stamped as a plain resistance)"
1211                    ))
1212                })?,
1213                value,
1214            })
1215        }
1216        other => Err(error(format!(
1217            "'{other}(...)' is not a state -- only V(<node>), V(<node>,<node>) and I(<inductor>) \
1218             can be assigned"
1219        ))),
1220    }
1221}
1222
1223fn initial_condition_field(element: &ElementInstance) -> Option<&str> {
1224    element
1225        .raw_params
1226        .iter()
1227        .find_map(|token| match as_field(token) {
1228            Some((key, value)) if key == "ic" => Some(value),
1229            _ => None,
1230        })
1231}
1232
1233fn scalar_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1234    let raw = element
1235        .raw_params
1236        .first()
1237        .ok_or_else(|| BuildError::InvalidElement {
1238            name: element.name.clone(),
1239            message: "has no scalar value".into(),
1240        })?;
1241    Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1242        name: element.name.clone(),
1243        message,
1244    })
1245}
1246
1247/// The DC value an independent source card declares, for a card
1248/// [`TransientFunction::parse_params`] found no waveform in.
1249///
1250/// Only the DC clause is read: an explicit `DC <value>`, or a bare leading value, which SPICE
1251/// allows as the implicit spelling of the same thing. A card that declares neither -- one
1252/// carrying only an `AC` specification, say -- has a DC value of zero, SPICE's own default,
1253/// rather than whatever `AC` happens to tokenize into. (It used to be read as `params.first()`
1254/// unconditionally, which turned `V1 1 0 AC 1` into a source whose value was a symbol named
1255/// `AC`.) `key=value` tokens are skipped: they are fields, already validated, never the value.
1256fn source_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1257    let params: Vec<&str> = element
1258        .raw_params
1259        .iter()
1260        .filter(|token| as_field(token).is_none())
1261        .map(|token| token.as_str())
1262        .collect();
1263    let raw = match params
1264        .iter()
1265        .position(|token| token.eq_ignore_ascii_case("dc"))
1266        .and_then(|index| params.get(index + 1))
1267    {
1268        Some(value) => *value,
1269        None => match params.first() {
1270            Some(first) if !first.eq_ignore_ascii_case("ac") && !first.contains('(') => *first,
1271            Some(_) => return Ok(Expression::zero()),
1272            None => {
1273                return Err(BuildError::InvalidElement {
1274                    name: element.name.clone(),
1275                    message: "has no source value".into(),
1276                })
1277            }
1278        },
1279    };
1280    Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1281        name: element.name.clone(),
1282        message,
1283    })
1284}
1285
1286fn control_and_gain(element: &ElementInstance) -> Result<(&str, Expression), BuildError> {
1287    match element.raw_params.as_slice() {
1288        [control, gain, ..] => Expression::parse_scalar(gain)
1289            .map(|gain| (control.as_str(), gain))
1290            .map_err(|message| BuildError::InvalidElement {
1291                name: element.name.clone(),
1292                message,
1293            }),
1294        _ => Err(BuildError::InvalidElement {
1295            name: element.name.clone(),
1296            message: "requires a controlling source and gain".into(),
1297        }),
1298    }
1299}
1300
1301fn normalize(value: &str) -> String {
1302    value.to_ascii_uppercase()
1303}
1304
1305fn is_ground(value: &str) -> bool {
1306    value == "0" || value.eq_ignore_ascii_case("gnd")
1307}
1308
1309/// Error returned while parsing or stamping a netlist.
1310#[derive(Debug, Clone, PartialEq)]
1311pub enum BuildError {
1312    /// `general-spice-core` rejected a statement.
1313    Parse {
1314        /// Parser message.
1315        message: String,
1316        /// First physical line.
1317        line_start: usize,
1318        /// Exclusive final physical line.
1319        line_end: usize,
1320    },
1321    /// A device does not have a linear stamp.
1322    UnsupportedElement(String),
1323    /// An element was syntactically parsed but cannot be stamped.
1324    InvalidElement {
1325        /// Element name.
1326        name: String,
1327        /// Explanation.
1328        message: String,
1329    },
1330    /// A device card carries a trailing parameter this crate does not recognize. Reported
1331    /// rather than silently discarded — see [`validate_trailing_fields`].
1332    InvalidElementField {
1333        /// 1-based physical line the device card was parsed from.
1334        line: usize,
1335        /// Element name.
1336        name: String,
1337        /// Explanation, already phrased to follow `device '<name>' `.
1338        message: String,
1339    },
1340    /// Two branch devices have the same case-insensitive name.
1341    DuplicateElement(String),
1342    /// A current-controlled source refers to a device without a branch current.
1343    UnknownControllingBranch(String),
1344    /// A mutual-inductance element refers to an unknown inductor.
1345    UnknownInductor(String),
1346    /// A `.IC` line assigns something this crate cannot start from: a target that is not
1347    /// `V(<node>)`, `V(<node>,<node>)` or `I(<inductor>)`, a node or element the netlist does
1348    /// not have, ground, or a value that does not parse. Reported rather than dropped, for the
1349    /// same reason as [`InvalidElementField`](Self::InvalidElementField) — see
1350    /// [`dot_ic_condition`].
1351    InvalidInitialConditionDirective {
1352        /// 1-based physical line of the `.IC` statement.
1353        line: usize,
1354        /// The assignment's left-hand side as written.
1355        target: String,
1356        /// Explanation, already phrased to follow `.IC '<target>' `.
1357        message: String,
1358    },
1359}
1360
1361impl fmt::Display for BuildError {
1362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363        match self {
1364            Self::Parse {
1365                message,
1366                line_start,
1367                line_end,
1368            } => write!(
1369                f,
1370                "parse error at lines {line_start}..{line_end}: {message}"
1371            ),
1372            Self::UnsupportedElement(message) => f.write_str(message),
1373            Self::InvalidElement { name, message } => {
1374                write!(f, "cannot stamp element '{name}': {message}")
1375            }
1376            Self::InvalidElementField {
1377                line,
1378                name,
1379                message,
1380            } => write!(f, "line {line}: device '{name}' {message}"),
1381            Self::DuplicateElement(name) => {
1382                write!(f, "duplicate case-insensitive element name '{name}'")
1383            }
1384            Self::UnknownControllingBranch(name) => {
1385                write!(f, "unknown controlling branch '{name}'")
1386            }
1387            Self::UnknownInductor(name) => write!(f, "unknown coupled inductor '{name}'"),
1388            Self::InvalidInitialConditionDirective {
1389                line,
1390                target,
1391                message,
1392            } => write!(f, "line {line}: .IC '{target}' {message}"),
1393        }
1394    }
1395}
1396
1397impl std::error::Error for BuildError {}