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 order = index.names.len();
249        let mut a = Matrix::filled(order, order, Expression::zero());
250        let mut k = Matrix::filled(order, order, Expression::zero());
251        let mut b = Matrix::filled(order, inputs.len(), Expression::zero());
252        let mut warnings = Vec::new();
253
254        let inductances = elements
255            .iter()
256            .filter(|element| element.device_letter == 'L')
257            .map(|element| Ok((normalize(&element.name), scalar_value(element)?)))
258            .collect::<Result<HashMap<_, _>, BuildError>>()?;
259
260        for element in elements {
261            if let Some(state) = self.switch_state(element) {
262                let resistance = match state {
263                    SwitchState::On => self.options.on_resistance.clone(),
264                    SwitchState::Off => self.options.off_resistance.clone(),
265                };
266                stamp_admittance(&mut a, &index, element, resistance.reciprocal())?;
267                continue;
268            }
269
270            match element.device_letter {
271                'R' => {
272                    stamp_admittance(&mut a, &index, element, scalar_value(element)?.reciprocal())?
273                }
274                'C' => stamp_admittance(&mut k, &index, element, scalar_value(element)?)?,
275                'L' => stamp_inductor(&mut a, &mut k, &index, element)?,
276                'V' => stamp_voltage_source(
277                    &mut a,
278                    &mut b,
279                    &index,
280                    element,
281                    input_by_element[&normalize(&element.name)],
282                )?,
283                'I' => stamp_current_source(
284                    &mut b,
285                    &index,
286                    element,
287                    input_by_element[&normalize(&element.name)],
288                )?,
289                'G' => stamp_vccs(&mut a, &index, element)?,
290                'E' => stamp_vcvs(&mut a, &index, element)?,
291                'F' => stamp_cccs(&mut a, &index, element)?,
292                'H' => stamp_ccvs(&mut a, &index, element)?,
293                'K' => stamp_mutual_inductance(&mut k, &index, element, &inductances)?,
294                'D' => {
295                    let conductance = Expression::symbol(format!("{}_G", element.name));
296                    stamp_admittance(&mut a, &index, element, conductance)?;
297                    stamp_current_source(
298                        &mut b,
299                        &index,
300                        element,
301                        input_by_element[&normalize(&element.name)],
302                    )?;
303                }
304                _ => self.unsupported(element, &mut warnings)?,
305            }
306        }
307
308        let mut u = vec![Expression::zero(); order];
309        for row in 0..order {
310            for column in 0..inputs.len() {
311                u[row] = u[row].clone() + b[(row, column)].clone() * input_values[column].clone();
312            }
313        }
314
315        let mut parameter_defaults = BTreeMap::new();
316        for statement in statements {
317            if let Statement::Param(param) | Statement::GlobalParam(param) = statement {
318                for (name, raw_value) in &param.assignments {
319                    if let Ok(value) = Expression::parse_scalar(raw_value) {
320                        parameter_defaults.insert(name.clone(), value);
321                    } else {
322                        warnings.push(format!(
323                            "parameter '{name}' has an expression that is preserved by general-spice-core but is not a scalar MNA value"
324                        ));
325                    }
326                }
327            }
328        }
329
330        Ok(MnaSystem {
331            a,
332            k,
333            b,
334            u,
335            unknowns: index.names,
336            inputs,
337            input_values,
338            transient_sources,
339            initial_conditions,
340            parameter_defaults,
341            warnings,
342        })
343    }
344
345    fn is_branch_device(&self, element: &ElementInstance) -> bool {
346        self.switch_state(element).is_none()
347            && matches!(element.device_letter, 'V' | 'L' | 'E' | 'H')
348    }
349
350    fn switch_state(&self, element: &ElementInstance) -> Option<SwitchState> {
351        self.options
352            .switch_states
353            .get(&normalize(&element.name))
354            .copied()
355    }
356
357    fn unsupported(
358        &self,
359        element: &ElementInstance,
360        warnings: &mut Vec<String>,
361    ) -> Result<(), BuildError> {
362        let message = format!(
363            "element '{}' (device {}) has no linear MNA stamp",
364            element.name, element.device_letter
365        );
366        match self.options.unsupported_elements {
367            UnsupportedElementPolicy::Error => Err(BuildError::UnsupportedElement(message)),
368            UnsupportedElementPolicy::IgnoreWithWarning => {
369                warnings.push(message);
370                Ok(())
371            }
372        }
373    }
374}
375
376#[derive(Debug, Default)]
377struct UnknownIndex {
378    names: Vec<String>,
379    nodes: HashMap<String, usize>,
380    branches: HashMap<String, usize>,
381    nodes_finished: bool,
382}
383
384impl UnknownIndex {
385    fn add_node(&mut self, name: &str) {
386        if is_ground(name) {
387            return;
388        }
389        let key = normalize(name);
390        if !self.nodes.contains_key(&key) {
391            let index = self.names.len();
392            self.nodes.insert(key, index);
393            self.names.push(format!("V({name})"));
394        }
395    }
396
397    fn finish_nodes(&mut self) {
398        self.nodes_finished = true;
399    }
400
401    fn add_branch(&mut self, name: &str) -> Result<(), BuildError> {
402        debug_assert!(self.nodes_finished);
403        let key = normalize(name);
404        if self.branches.contains_key(&key) {
405            return Err(BuildError::DuplicateElement(name.to_string()));
406        }
407        let index = self.names.len();
408        self.branches.insert(key, index);
409        self.names.push(format!("I({name})"));
410        Ok(())
411    }
412
413    fn node(&self, name: &str) -> Option<usize> {
414        if is_ground(name) {
415            None
416        } else {
417            self.nodes.get(&normalize(name)).copied()
418        }
419    }
420
421    fn branch(&self, name: &str) -> Result<usize, BuildError> {
422        self.branches
423            .get(&normalize(name))
424            .copied()
425            .ok_or_else(|| BuildError::UnknownControllingBranch(name.to_string()))
426    }
427}
428
429fn stamp(
430    matrix: &mut Matrix<Expression>,
431    row: Option<usize>,
432    col: Option<usize>,
433    value: Expression,
434) {
435    if let (Some(row), Some(col)) = (row, col) {
436        matrix[(row, col)] = matrix[(row, col)].clone() + value;
437    }
438}
439
440fn stamp_input(matrix: &mut Matrix<Expression>, row: Option<usize>, col: usize, value: Expression) {
441    if let Some(row) = row {
442        matrix[(row, col)] = matrix[(row, col)].clone() + value;
443    }
444}
445
446fn two_nodes(element: &ElementInstance) -> Result<(&str, &str), BuildError> {
447    match element.nodes.as_slice() {
448        [positive, negative, ..] => Ok((positive, negative)),
449        _ => Err(BuildError::InvalidElement {
450            name: element.name.clone(),
451            message: "requires two terminals".into(),
452        }),
453    }
454}
455
456fn four_nodes(element: &ElementInstance) -> Result<(&str, &str, &str, &str), BuildError> {
457    match element.nodes.as_slice() {
458        [out_positive, out_negative, ctrl_positive, ctrl_negative] => {
459            Ok((out_positive, out_negative, ctrl_positive, ctrl_negative))
460        }
461        _ => Err(BuildError::InvalidElement {
462            name: element.name.clone(),
463            message: "requires the classic four-node linear form".into(),
464        }),
465    }
466}
467
468fn stamp_admittance(
469    matrix: &mut Matrix<Expression>,
470    index: &UnknownIndex,
471    element: &ElementInstance,
472    admittance: Expression,
473) -> Result<(), BuildError> {
474    let (positive, negative) = two_nodes(element)?;
475    let p = index.node(positive);
476    let n = index.node(negative);
477    stamp(matrix, p, p, admittance.clone());
478    stamp(matrix, n, n, admittance.clone());
479    stamp(matrix, p, n, -admittance.clone());
480    stamp(matrix, n, p, -admittance);
481    Ok(())
482}
483
484fn stamp_branch_incidence(
485    matrix: &mut Matrix<Expression>,
486    index: &UnknownIndex,
487    element: &ElementInstance,
488) -> Result<usize, BuildError> {
489    let (positive, negative) = two_nodes(element)?;
490    let branch = index.branch(&element.name)?;
491    let p = index.node(positive);
492    let n = index.node(negative);
493    stamp(matrix, p, Some(branch), Expression::one());
494    stamp(matrix, n, Some(branch), -Expression::one());
495    stamp(matrix, Some(branch), p, Expression::one());
496    stamp(matrix, Some(branch), n, -Expression::one());
497    Ok(branch)
498}
499
500fn stamp_inductor(
501    a: &mut Matrix<Expression>,
502    k: &mut Matrix<Expression>,
503    index: &UnknownIndex,
504    element: &ElementInstance,
505) -> Result<(), BuildError> {
506    let branch = stamp_branch_incidence(a, index, element)?;
507    stamp(k, Some(branch), Some(branch), -scalar_value(element)?);
508    Ok(())
509}
510
511fn stamp_voltage_source(
512    a: &mut Matrix<Expression>,
513    b: &mut Matrix<Expression>,
514    index: &UnknownIndex,
515    element: &ElementInstance,
516    input: usize,
517) -> Result<(), BuildError> {
518    let branch = stamp_branch_incidence(a, index, element)?;
519    stamp_input(b, Some(branch), input, Expression::one());
520    Ok(())
521}
522
523fn stamp_current_source(
524    b: &mut Matrix<Expression>,
525    index: &UnknownIndex,
526    element: &ElementInstance,
527    input: usize,
528) -> Result<(), BuildError> {
529    let (positive, negative) = two_nodes(element)?;
530    stamp_input(b, index.node(positive), input, -Expression::one());
531    stamp_input(b, index.node(negative), input, Expression::one());
532    Ok(())
533}
534
535fn stamp_vccs(
536    a: &mut Matrix<Expression>,
537    index: &UnknownIndex,
538    element: &ElementInstance,
539) -> Result<(), BuildError> {
540    let (op, on, cp, cn) = four_nodes(element)?;
541    let gain = scalar_value(element)?;
542    stamp(a, index.node(op), index.node(cp), gain.clone());
543    stamp(a, index.node(op), index.node(cn), -gain.clone());
544    stamp(a, index.node(on), index.node(cp), -gain.clone());
545    stamp(a, index.node(on), index.node(cn), gain);
546    Ok(())
547}
548
549fn stamp_vcvs(
550    a: &mut Matrix<Expression>,
551    index: &UnknownIndex,
552    element: &ElementInstance,
553) -> Result<(), BuildError> {
554    let (_, _, cp, cn) = four_nodes(element)?;
555    let branch = stamp_branch_incidence(a, index, element)?;
556    let gain = scalar_value(element)?;
557    stamp(a, Some(branch), index.node(cp), -gain.clone());
558    stamp(a, Some(branch), index.node(cn), gain);
559    Ok(())
560}
561
562fn stamp_cccs(
563    a: &mut Matrix<Expression>,
564    index: &UnknownIndex,
565    element: &ElementInstance,
566) -> Result<(), BuildError> {
567    let (positive, negative) = two_nodes(element)?;
568    let (control, gain) = control_and_gain(element)?;
569    let control = index.branch(control)?;
570    stamp(a, index.node(positive), Some(control), gain.clone());
571    stamp(a, index.node(negative), Some(control), -gain);
572    Ok(())
573}
574
575fn stamp_ccvs(
576    a: &mut Matrix<Expression>,
577    index: &UnknownIndex,
578    element: &ElementInstance,
579) -> Result<(), BuildError> {
580    let branch = stamp_branch_incidence(a, index, element)?;
581    let (control, gain) = control_and_gain(element)?;
582    let control = index.branch(control)?;
583    stamp(a, Some(branch), Some(control), -gain);
584    Ok(())
585}
586
587fn stamp_mutual_inductance(
588    k_matrix: &mut Matrix<Expression>,
589    index: &UnknownIndex,
590    element: &ElementInstance,
591    inductances: &HashMap<String, Expression>,
592) -> Result<(), BuildError> {
593    if element.nodes.len() < 2 {
594        return Err(BuildError::InvalidElement {
595            name: element.name.clone(),
596            message: "requires at least two inductor names".into(),
597        });
598    }
599    let coefficient = scalar_value(element)?;
600    for first in 0..element.nodes.len() {
601        for second in first + 1..element.nodes.len() {
602            let first_name = &element.nodes[first];
603            let second_name = &element.nodes[second];
604            let first_l = inductances
605                .get(&normalize(first_name))
606                .ok_or_else(|| BuildError::UnknownInductor(first_name.clone()))?;
607            let second_l = inductances
608                .get(&normalize(second_name))
609                .ok_or_else(|| BuildError::UnknownInductor(second_name.clone()))?;
610            let mutual = coefficient.clone() * (first_l.clone() * second_l.clone()).sqrt();
611            let first_branch = index.branch(first_name)?;
612            let second_branch = index.branch(second_name)?;
613            stamp(
614                k_matrix,
615                Some(first_branch),
616                Some(second_branch),
617                -mutual.clone(),
618            );
619            stamp(k_matrix, Some(second_branch), Some(first_branch), -mutual);
620        }
621    }
622    Ok(())
623}
624
625/// Device letters this crate has a linear stamp for, and therefore holds to a known parameter
626/// grammar. Anything else is `UnsupportedElementPolicy`'s business (error, or skip with a
627/// warning) and is deliberately *not* field-checked here: a `M`/`Q`/`J` card's own `L=1u W=10u`
628/// is perfectly valid netlist text this crate simply has no model for, and rejecting its fields
629/// would turn `IgnoreWithWarning` into a hard error.
630fn is_stamped_letter(device_letter: char) -> bool {
631    matches!(
632        device_letter,
633        'R' | 'C' | 'L' | 'K' | 'V' | 'I' | 'E' | 'F' | 'G' | 'H' | 'D'
634    )
635}
636
637/// The trailing `key=value` fields this crate understands on a device card it stamps, keyed by
638/// device letter and compared case-insensitively.
639///
640/// `general-spice-core` deliberately hands every token after the node list over uninterpreted,
641/// in [`ElementInstance::raw_params`]; deciding what they mean is this crate's job. Any key not
642/// listed here is rejected rather than dropped, because dropping it is not a harmless no-op —
643/// a silently ignored `tc1=`/`temp=`/`m=`, or a misspelled `ic=`, produces a plausible-looking
644/// waveform for a *different* circuit than the one the author wrote, with nothing on screen to
645/// say so.
646fn accepted_fields(device_letter: char) -> &'static [&'static str] {
647    match device_letter {
648        // See `MnaSystem::initial_conditions` for what `ic=` means on each, sign included.
649        'C' | 'L' => &["ic"],
650        _ => &[],
651    }
652}
653
654/// What a stamped device letter's *positional* (non-`key=value`) parameter list may contain.
655///
656/// `general-spice-core` hands every token after the node list over uninterpreted, so a
657/// positional token this crate does not read is dropped exactly as silently as an unknown
658/// field was before — `V1 1 0 10 wibble` and `V1 1 0 SNI(0 1 1k)` both used to simulate a
659/// plain 10 V / 0 V source and say nothing. These are the shapes each letter actually permits.
660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661enum PositionalGrammar {
662    /// Exactly one token, the element's own value. `R`/`C`/`L` (resistance, capacitance,
663    /// inductance), `K` (coupling coefficient — `general-spice-core` puts every earlier token
664    /// in `nodes` as an inductor name), and `E`/`G` in the classic four-node form, whose single
665    /// parameter is the gain.
666    OneValue,
667    /// Exactly two tokens: a controlling source's name, then a gain — `F`/`H`. The name itself
668    /// is checked later, by `UnknownControllingBranch`.
669    ControlAndGain,
670    /// An independent source's clause list — `V`/`I`. See [`validate_source_positional`].
671    SourceClauses,
672    /// A diode's model name, optional area factor and optional `OFF` — `D`. See
673    /// [`validate_diode_positional`], including what about it is deliberately not checked.
674    DiodeModel,
675    /// Positional tokens this crate deliberately does not check, while still checking the
676    /// card's `key=value` fields. Used for a switch-assigned element, whose parameters are
677    /// replaced wholesale by the on/off resistance.
678    Unchecked,
679}
680
681/// The positional grammar to hold `element` to, or `None` to skip validating the card entirely.
682///
683/// `None` is only ever returned for the two-node behavioral form of `E`/`G`
684/// (`E1 out 0 VALUE={...}` / `TABLE` / `POLY`), which this crate does not stamp at all: its
685/// tokens are neither a gain nor `key=value` fields, and `four_nodes` already rejects the card
686/// with a message that says exactly what is missing ("requires the classic four-node linear
687/// form"). Field-checking it first would replace that with a misleading `unknown field 'value'`.
688fn positional_grammar(element: &ElementInstance) -> Option<PositionalGrammar> {
689    match element.device_letter {
690        'R' | 'C' | 'L' | 'K' => Some(PositionalGrammar::OneValue),
691        'E' | 'G' if element.nodes.len() == 4 => Some(PositionalGrammar::OneValue),
692        'E' | 'G' => None,
693        'F' | 'H' => Some(PositionalGrammar::ControlAndGain),
694        'V' | 'I' => Some(PositionalGrammar::SourceClauses),
695        'D' => Some(PositionalGrammar::DiodeModel),
696        _ => Some(PositionalGrammar::Unchecked),
697    }
698}
699
700/// Splits a raw trailing token into `(key, value)` if it has the `key=value` shape, with the key
701/// lowercased for the case-insensitive comparison every SPICE dialect expects. A token with no
702/// `=`, or with an empty key (`=5`), is positional, not a field.
703fn as_field(token: &str) -> Option<(String, &str)> {
704    let (key, value) = token.split_once('=')?;
705    let key = key.trim();
706    if key.is_empty() {
707        return None;
708    }
709    Some((key.to_ascii_lowercase(), value))
710}
711
712/// Rejects a trailing token this crate would otherwise silently discard.
713///
714/// Mirrors the block (`kind=...`) parser's own diagnostics in
715/// [`crate::system_builder`] — same `line N: device '<name>' ...` shape — so a device card and a
716/// block line report a bad field the same way.
717///
718/// Two passes, because they fail for different reasons: every `key=value` token is checked
719/// against [`accepted_fields`], and whatever is left over — the positional tokens, in order —
720/// is checked against the letter's own [`PositionalGrammar`].
721fn validate_trailing_fields(
722    element: &ElementInstance,
723    grammar: PositionalGrammar,
724) -> Result<(), BuildError> {
725    let letter = element.device_letter;
726    let accepted = accepted_fields(letter);
727    let mut positional: Vec<&str> = Vec::new();
728
729    for token in &element.raw_params {
730        let Some((key, _)) = as_field(token) else {
731            positional.push(token.as_str());
732            continue;
733        };
734        if accepted.iter().any(|allowed| *allowed == key) {
735            continue;
736        }
737        return Err(BuildError::InvalidElementField {
738            line: element.span.start,
739            name: element.name.clone(),
740            message: match accepted {
741                [] => {
742                    format!("unknown field '{key}' (device {letter} accepts no key=value fields)")
743                }
744                _ => format!(
745                    "unknown field '{key}' (device {letter} accepts only: {})",
746                    accepted.join(", ")
747                ),
748            },
749        });
750    }
751
752    match grammar {
753        PositionalGrammar::OneValue if positional.len() > 1 => Err(field_error(
754            element,
755            format!(
756                "unexpected extra parameter '{}' (device {letter} takes exactly one value{})",
757                positional[1],
758                accepted_suffix(accepted)
759            ),
760        )),
761        PositionalGrammar::ControlAndGain if positional.len() > 2 => Err(field_error(
762            element,
763            format!(
764                "unexpected extra parameter '{}' (device {letter} takes exactly two values, a \
765                 controlling source name and a gain)",
766                positional[2]
767            ),
768        )),
769        PositionalGrammar::SourceClauses => validate_source_positional(element, &positional),
770        PositionalGrammar::DiodeModel => validate_diode_positional(element, &positional),
771        _ => Ok(()),
772    }
773}
774
775/// A positional-token diagnostic on `element`, in the same shape as the field diagnostics above.
776fn field_error(element: &ElementInstance, message: String) -> BuildError {
777    BuildError::InvalidElementField {
778        line: element.span.start,
779        name: element.name.clone(),
780        message,
781    }
782}
783
784/// Whether `token` is a value this crate can read — a SPICE number with or without a suffix, a
785/// symbol resolved later from `.param`, or a braced expression. Not a judgement about physical
786/// units, only about shape.
787fn is_value_token(token: &str) -> bool {
788    Expression::parse_scalar(token).is_ok()
789}
790
791/// Validates the positional parameters of an independent source card (`V`/`I`).
792///
793/// The grammar is a sequence of clauses, in any order, each of which this crate either reads or
794/// knowingly ignores:
795///
796/// - a bare value as the very first token — the implicit DC value (`V1 1 0 10`);
797/// - `DC <value>` — the explicit spelling of the same thing;
798/// - `AC <magnitude> [<phase>]` — read by no analysis this crate implements yet, but valid, and
799///   so accepted rather than rejected;
800/// - one call to one of [`TransientFunction::FUNCTION_NAMES`], whose arguments must actually
801///   parse as that function's parameter list.
802///
803/// Anything else is a typo. A second bare value (`V1 1 0 10 20`), a trailing word
804/// (`V1 1 0 10 wibble`), a misspelled function (`SNI(0 1 1k)`), a `DC` with nothing after it,
805/// and an unterminated argument list are all rejected here instead of being dropped.
806///
807/// Deliberately not checked: a symbol where an `AC` magnitude or phase belongs. `AC {gain}` is
808/// a legitimate parameterized magnitude, and nothing in the token itself distinguishes it from
809/// a misspelling, so at most two value-shaped tokens are consumed after `AC` and a third one
810/// falls through to the "unexpected extra value" arm.
811fn validate_source_positional(
812    element: &ElementInstance,
813    positional: &[&str],
814) -> Result<(), BuildError> {
815    let letter = element.device_letter;
816    let mut index = 0usize;
817    let mut seen_dc = false;
818    let mut seen_ac = false;
819    let mut seen_function = false;
820
821    while index < positional.len() {
822        let token = positional[index];
823        if token.eq_ignore_ascii_case("dc") {
824            if seen_dc {
825                return Err(field_error(
826                    element,
827                    format!("device {letter} declares a DC value more than once"),
828                ));
829            }
830            seen_dc = true;
831            match positional.get(index + 1) {
832                Some(value) if is_value_token(value) => index += 2,
833                Some(value) => {
834                    return Err(field_error(
835                        element,
836                        format!("'dc' is followed by '{value}', which is not a value"),
837                    ))
838                }
839                None => {
840                    return Err(field_error(
841                        element,
842                        "'dc' is not followed by a value".to_string(),
843                    ))
844                }
845            }
846        } else if token.eq_ignore_ascii_case("ac") {
847            if seen_ac {
848                return Err(field_error(
849                    element,
850                    format!("device {letter} declares an AC specification more than once"),
851                ));
852            }
853            seen_ac = true;
854            let mut consumed = 0usize;
855            while consumed < 2 {
856                match positional.get(index + 1 + consumed) {
857                    Some(next)
858                        if !next.eq_ignore_ascii_case("dc")
859                            && !next.eq_ignore_ascii_case("ac")
860                            && !next.contains('(')
861                            && is_value_token(next) =>
862                    {
863                        consumed += 1
864                    }
865                    _ => break,
866                }
867            }
868            if consumed == 0 {
869                return Err(field_error(
870                    element,
871                    "'ac' is not followed by a magnitude".to_string(),
872                ));
873            }
874            index += 1 + consumed;
875        } else if let Some(paren) = token.find('(') {
876            let name = &token[..paren];
877            if !TransientFunction::is_function_name(name) {
878                return Err(field_error(
879                    element,
880                    format!(
881                        "unknown source function '{name}' (device {letter} accepts {})",
882                        TransientFunction::FUNCTION_NAMES.join("/")
883                    ),
884                ));
885            }
886            if seen_function {
887                return Err(field_error(
888                    element,
889                    format!("device {letter} declares more than one transient function"),
890                ));
891            }
892            seen_function = true;
893            let Some(end) = positional[index..]
894                .iter()
895                .position(|token| token.contains(')'))
896                .map(|offset| offset + index)
897            else {
898                return Err(field_error(
899                    element,
900                    format!("'{name}(' is never closed by a ')'"),
901                ));
902            };
903            let call: Vec<String> = positional[index..=end]
904                .iter()
905                .map(|token| (*token).to_string())
906                .collect();
907            if TransientFunction::parse(&call).is_none() {
908                return Err(field_error(
909                    element,
910                    format!("'{}' is not a valid {name} parameter list", call.join(" ")),
911                ));
912            }
913            index = end + 1;
914        } else if index == 0 && is_value_token(token) {
915            // The implicit DC value, which SPICE allows only in first position.
916            seen_dc = true;
917            index += 1;
918        } else {
919            return Err(field_error(
920                element,
921                format!(
922                    "unexpected extra parameter '{token}' (device {letter} takes a DC value, an \
923                     'ac' specification, and/or one of {}{})",
924                    TransientFunction::FUNCTION_NAMES.join("/"),
925                    accepted_suffix(accepted_fields(letter))
926                ),
927            ));
928        }
929    }
930    Ok(())
931}
932
933/// Validates the positional parameters of a diode card (`D`).
934///
935/// SPICE's grammar here is a model name, an optional area factor and an optional `OFF` hint, so
936/// at most one non-`OFF` token beyond the model name is permitted, it has to be value-shaped,
937/// and `OFF` may not be repeated.
938///
939/// **The model name itself is deliberately not checked, and cannot be.** This crate does not
940/// stamp a diode from a device model at all — a `D` card becomes a symbolic conductance
941/// `{name}_G` plus a Norton current `{name}_Ioff` that the caller resolves per timestep (see
942/// the `'D'` arm of `build_statements`), so there is no model parameter set here to check a
943/// name against. Even a crate that did have one could not decide the question from the netlist
944/// alone: the `.model` card may live behind an `.include` this crate never resolves, so an
945/// unrecognized name means "not found here", not "misspelled". A misspelled diode model name
946/// is therefore a known, documented limit of this validation, recorded in the README.
947fn validate_diode_positional(
948    element: &ElementInstance,
949    positional: &[&str],
950) -> Result<(), BuildError> {
951    let mut off = 0usize;
952    let mut values: Vec<&str> = Vec::new();
953    for token in positional {
954        if token.eq_ignore_ascii_case("off") {
955            off += 1;
956        } else {
957            values.push(token);
958        }
959    }
960    if off > 1 {
961        return Err(field_error(
962            element,
963            "'off' is given more than once".to_string(),
964        ));
965    }
966    if let Some(area) = values.get(1) {
967        if !is_value_token(area) {
968            return Err(field_error(
969                element,
970                format!("'{area}' is not a value (device D's second parameter is its area factor)"),
971            ));
972        }
973    }
974    if let Some(extra) = values.get(2) {
975        return Err(field_error(
976            element,
977            format!(
978                "unexpected extra parameter '{extra}' (device D takes a model name, an optional \
979                 area factor and an optional 'off')"
980            ),
981        ));
982    }
983    Ok(())
984}
985
986/// The ", plus ..." tail of the extra-positional message, so a resistor (no fields at all) does
987/// not advertise an empty list.
988fn accepted_suffix(accepted: &'static [&'static str]) -> String {
989    match accepted {
990        [] => String::new(),
991        _ => format!(", plus optional {}", accepted.join("/")),
992    }
993}
994
995/// The raw text of a device card's `ic=` field, if it declares one. Already validated as an
996/// accepted key by [`validate_trailing_fields`], so reaching this on anything but `C`/`L` is a
997/// bug, not bad input.
998fn initial_condition_field(element: &ElementInstance) -> Option<&str> {
999    element
1000        .raw_params
1001        .iter()
1002        .find_map(|token| match as_field(token) {
1003            Some((key, value)) if key == "ic" => Some(value),
1004            _ => None,
1005        })
1006}
1007
1008fn scalar_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1009    let raw = element
1010        .raw_params
1011        .first()
1012        .ok_or_else(|| BuildError::InvalidElement {
1013            name: element.name.clone(),
1014            message: "has no scalar value".into(),
1015        })?;
1016    Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1017        name: element.name.clone(),
1018        message,
1019    })
1020}
1021
1022/// The DC value an independent source card declares, for a card
1023/// [`TransientFunction::parse_params`] found no waveform in.
1024///
1025/// Only the DC clause is read: an explicit `DC <value>`, or a bare leading value, which SPICE
1026/// allows as the implicit spelling of the same thing. A card that declares neither -- one
1027/// carrying only an `AC` specification, say -- has a DC value of zero, SPICE's own default,
1028/// rather than whatever `AC` happens to tokenize into. (It used to be read as `params.first()`
1029/// unconditionally, which turned `V1 1 0 AC 1` into a source whose value was a symbol named
1030/// `AC`.) `key=value` tokens are skipped: they are fields, already validated, never the value.
1031fn source_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1032    let params: Vec<&str> = element
1033        .raw_params
1034        .iter()
1035        .filter(|token| as_field(token).is_none())
1036        .map(|token| token.as_str())
1037        .collect();
1038    let raw = match params
1039        .iter()
1040        .position(|token| token.eq_ignore_ascii_case("dc"))
1041        .and_then(|index| params.get(index + 1))
1042    {
1043        Some(value) => *value,
1044        None => match params.first() {
1045            Some(first) if !first.eq_ignore_ascii_case("ac") && !first.contains('(') => *first,
1046            Some(_) => return Ok(Expression::zero()),
1047            None => {
1048                return Err(BuildError::InvalidElement {
1049                    name: element.name.clone(),
1050                    message: "has no source value".into(),
1051                })
1052            }
1053        },
1054    };
1055    Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1056        name: element.name.clone(),
1057        message,
1058    })
1059}
1060
1061fn control_and_gain(element: &ElementInstance) -> Result<(&str, Expression), BuildError> {
1062    match element.raw_params.as_slice() {
1063        [control, gain, ..] => Expression::parse_scalar(gain)
1064            .map(|gain| (control.as_str(), gain))
1065            .map_err(|message| BuildError::InvalidElement {
1066                name: element.name.clone(),
1067                message,
1068            }),
1069        _ => Err(BuildError::InvalidElement {
1070            name: element.name.clone(),
1071            message: "requires a controlling source and gain".into(),
1072        }),
1073    }
1074}
1075
1076fn normalize(value: &str) -> String {
1077    value.to_ascii_uppercase()
1078}
1079
1080fn is_ground(value: &str) -> bool {
1081    value == "0" || value.eq_ignore_ascii_case("gnd")
1082}
1083
1084/// Error returned while parsing or stamping a netlist.
1085#[derive(Debug, Clone, PartialEq)]
1086pub enum BuildError {
1087    /// `general-spice-core` rejected a statement.
1088    Parse {
1089        /// Parser message.
1090        message: String,
1091        /// First physical line.
1092        line_start: usize,
1093        /// Exclusive final physical line.
1094        line_end: usize,
1095    },
1096    /// A device does not have a linear stamp.
1097    UnsupportedElement(String),
1098    /// An element was syntactically parsed but cannot be stamped.
1099    InvalidElement {
1100        /// Element name.
1101        name: String,
1102        /// Explanation.
1103        message: String,
1104    },
1105    /// A device card carries a trailing parameter this crate does not recognize. Reported
1106    /// rather than silently discarded — see [`validate_trailing_fields`].
1107    InvalidElementField {
1108        /// 1-based physical line the device card was parsed from.
1109        line: usize,
1110        /// Element name.
1111        name: String,
1112        /// Explanation, already phrased to follow `device '<name>' `.
1113        message: String,
1114    },
1115    /// Two branch devices have the same case-insensitive name.
1116    DuplicateElement(String),
1117    /// A current-controlled source refers to a device without a branch current.
1118    UnknownControllingBranch(String),
1119    /// A mutual-inductance element refers to an unknown inductor.
1120    UnknownInductor(String),
1121}
1122
1123impl fmt::Display for BuildError {
1124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125        match self {
1126            Self::Parse {
1127                message,
1128                line_start,
1129                line_end,
1130            } => write!(
1131                f,
1132                "parse error at lines {line_start}..{line_end}: {message}"
1133            ),
1134            Self::UnsupportedElement(message) => f.write_str(message),
1135            Self::InvalidElement { name, message } => {
1136                write!(f, "cannot stamp element '{name}': {message}")
1137            }
1138            Self::InvalidElementField {
1139                line,
1140                name,
1141                message,
1142            } => write!(f, "line {line}: device '{name}' {message}"),
1143            Self::DuplicateElement(name) => {
1144                write!(f, "duplicate case-insensitive element name '{name}'")
1145            }
1146            Self::UnknownControllingBranch(name) => {
1147                write!(f, "unknown controlling branch '{name}'")
1148            }
1149            Self::UnknownInductor(name) => write!(f, "unknown coupled inductor '{name}'"),
1150        }
1151    }
1152}
1153
1154impl std::error::Error for BuildError {}