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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum UnsupportedElementPolicy {
12 Error,
14 IgnoreWithWarning,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum SwitchState {
21 On,
23 Off,
25}
26
27#[derive(Debug, Clone, PartialEq)]
29pub struct BuildOptions {
30 pub unsupported_elements: UnsupportedElementPolicy,
32 pub switch_states: BTreeMap<String, SwitchState>,
34 pub on_resistance: Expression,
36 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 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#[derive(Debug, Clone)]
61pub struct MnaBuilder {
62 dialect: Dialect,
63 options: BuildOptions,
64}
65
66impl MnaBuilder {
67 pub fn new(dialect: Dialect) -> Self {
69 Self {
70 dialect,
71 options: BuildOptions::default(),
72 }
73 }
74
75 pub fn with_options(dialect: Dialect, options: BuildOptions) -> Self {
77 Self { dialect, options }
78 }
79
80 pub fn options(&self) -> &BuildOptions {
82 &self.options
83 }
84
85 pub fn options_mut(&mut self) -> &mut BuildOptions {
87 &mut self.options
88 }
89
90 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 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 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 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 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 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 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!("ic= accepted only on C and L"),
245 }
246 }
247
248 let mut warnings = Vec::new();
249
250 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 ¶m.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
657fn 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
669fn accepted_fields(device_letter: char) -> &'static [&'static str] {
679 match device_letter {
680 'C' | 'L' => &["ic"],
682 _ => &[],
683 }
684}
685
686#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693enum PositionalGrammar {
694 OneValue,
699 ControlAndGain,
702 SourceClauses,
704 DiodeModel,
707 Unchecked,
711}
712
713fn 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
732fn 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
744fn 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
807fn 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
816fn is_value_token(token: &str) -> bool {
820 Expression::parse_scalar(token).is_ok()
821}
822
823fn 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 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
965fn 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
1018fn accepted_suffix(accepted: &'static [&'static str]) -> String {
1021 match accepted {
1022 [] => String::new(),
1023 _ => format!(", plus optional {}", accepted.join("/")),
1024 }
1025}
1026
1027fn 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
1160fn 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#[derive(Debug, Clone, PartialEq)]
1224pub enum BuildError {
1225 Parse {
1227 message: String,
1229 line_start: usize,
1231 line_end: usize,
1233 },
1234 UnsupportedElement(String),
1236 InvalidElement {
1238 name: String,
1240 message: String,
1242 },
1243 InvalidElementField {
1246 line: usize,
1248 name: String,
1250 message: String,
1252 },
1253 DuplicateElement(String),
1255 UnknownControllingBranch(String),
1257 UnknownInductor(String),
1259 InvalidInitialConditionDirective {
1265 line: usize,
1267 target: String,
1269 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 {}