Skip to main content

general_mna/
builder.rs

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