1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::fmt;
3
4use general_spice_core::ast::{ElementInstance, Statement};
5use general_spice_core::{lexer, parser, Dialect};
6
7use crate::{DeviceAnnotation, Expression, InitialCondition, Matrix, MnaSystem, TransientFunction};
8
9#[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 pub annotation_fields: BTreeSet<String>,
52}
53
54impl Default for BuildOptions {
55 fn default() -> Self {
56 Self {
57 unsupported_elements: UnsupportedElementPolicy::Error,
58 switch_states: BTreeMap::new(),
59 on_resistance: Expression::symbol("Ron"),
60 off_resistance: Expression::symbol("Roff"),
61 annotation_fields: BTreeSet::new(),
62 }
63 }
64}
65
66impl BuildOptions {
67 pub fn set_switch(&mut self, element_name: impl Into<String>, state: SwitchState) {
69 self.switch_states
70 .insert(normalize(&element_name.into()), state);
71 }
72
73 pub fn annotate(&mut self, field: impl AsRef<str>) {
76 self.annotation_fields
77 .insert(field.as_ref().to_ascii_lowercase());
78 }
79}
80
81#[derive(Debug, Clone)]
83pub struct MnaBuilder {
84 dialect: Dialect,
85 options: BuildOptions,
86}
87
88impl MnaBuilder {
89 pub fn new(dialect: Dialect) -> Self {
91 Self {
92 dialect,
93 options: BuildOptions::default(),
94 }
95 }
96
97 pub fn with_options(dialect: Dialect, options: BuildOptions) -> Self {
99 Self { dialect, options }
100 }
101
102 pub fn options(&self) -> &BuildOptions {
104 &self.options
105 }
106
107 pub fn options_mut(&mut self) -> &mut BuildOptions {
109 &mut self.options
110 }
111
112 pub fn build_fragment(&self, source: &str) -> Result<MnaSystem, BuildError> {
114 let lines = lexer::preprocess(source, self.dialect);
115 let parsed = parser::parse(&lines, self.dialect);
116 self.finish_parse(parsed)
117 }
118
119 pub fn build_document(&self, source: &str) -> Result<MnaSystem, BuildError> {
121 let lines = lexer::preprocess(source, self.dialect);
122 let parsed = parser::parse_document(&lines, self.dialect);
123 self.finish_parse(parsed)
124 }
125
126 fn finish_parse(&self, parsed: Vec<parser::ParseResult>) -> Result<MnaSystem, BuildError> {
127 let mut statements = Vec::with_capacity(parsed.len());
128 for result in parsed {
129 match result {
130 Ok(statement) => statements.push(statement),
131 Err(error) => {
132 return Err(BuildError::Parse {
133 message: error.message,
134 line_start: error.span.start,
135 line_end: error.span.end,
136 })
137 }
138 }
139 }
140 self.build_statements(&statements)
141 }
142
143 pub fn build_statements(&self, statements: &[Statement]) -> Result<MnaSystem, BuildError> {
145 let elements: Vec<&ElementInstance> = statements
146 .iter()
147 .filter_map(|statement| match statement {
148 Statement::ElementInstance(element) => Some(element),
149 _ => None,
150 })
151 .collect();
152
153 let mut seen: HashMap<String, &str> = HashMap::new();
166 for element in &elements {
167 if seen
168 .insert(normalize(&element.name), element.name.as_str())
169 .is_some()
170 {
171 return Err(BuildError::DuplicateElement(element.name.clone()));
172 }
173 }
174
175 for element in &elements {
176 let grammar = match self.switch_state(element) {
180 Some(_) => Some(PositionalGrammar::Unchecked),
181 None if is_stamped_letter(element.device_letter) => positional_grammar(element),
182 None => None,
183 };
184 if let Some(grammar) = grammar {
185 validate_trailing_fields(element, grammar, &self.options.annotation_fields)?;
186 }
187 }
188
189 let mut index = UnknownIndex::default();
190 for element in &elements {
191 if element.device_letter == 'K' {
192 continue;
193 }
194 let node_count = if self.switch_state(element).is_some() {
195 element.nodes.len().min(2)
196 } else {
197 element.nodes.len()
198 };
199 for node in &element.nodes[..node_count] {
200 index.add_node(node);
201 }
202 }
203 index.finish_nodes();
204
205 for element in &elements {
206 if self.is_branch_device(element) {
207 index.add_branch(&element.name)?;
208 }
209 }
210
211 let mut inputs = Vec::new();
212 let mut input_values = Vec::new();
213 let mut input_by_element = HashMap::new();
214 let mut transient_sources = BTreeMap::new();
215 for element in &elements {
216 if matches!(element.device_letter, 'V' | 'I') {
217 let column = inputs.len();
218 input_by_element.insert(normalize(&element.name), column);
220 inputs.push(element.name.clone());
221 if let Some(transient_fn) = TransientFunction::parse_params(&element.raw_params) {
222 transient_sources.insert(element.name.clone(), transient_fn);
228 input_values.push(Expression::symbol(element.name.clone()));
229 } else {
230 input_values.push(source_value(element)?);
231 }
232 } else if element.device_letter == 'D' {
233 let column = inputs.len();
241 input_by_element.insert(normalize(&element.name), column);
243 inputs.push(element.name.clone());
244 input_values.push(Expression::symbol(format!("{}_Ioff", element.name)));
245 }
246 }
247
248 let mut initial_conditions = Vec::new();
253 for element in &elements {
254 if self.switch_state(element).is_some() {
255 continue;
256 }
257 let Some(raw) = initial_condition_field(element) else {
258 continue;
259 };
260 let value = Expression::parse_scalar(raw).map_err(|message| {
261 BuildError::InvalidElementField {
262 line: element.span.start,
263 name: element.name.clone(),
264 message: format!("field 'ic' is not a value: {message}"),
265 }
266 })?;
267 match element.device_letter {
268 'C' => {
269 let (positive, negative) = two_nodes(element)?;
270 initial_conditions.push(InitialCondition::CapacitorVoltage {
271 element: element.name.clone(),
272 positive: index.node(positive),
273 negative: index.node(negative),
274 value,
275 });
276 }
277 'L' => initial_conditions.push(InitialCondition::InductorCurrent {
278 element: element.name.clone(),
279 branch: index.branch(&element.name)?,
280 value,
281 }),
282 _ => unreachable!("ic= accepted only on C and L"),
285 }
286 }
287
288 let mut annotations = Vec::new();
294 if !self.options.annotation_fields.is_empty() {
295 for element in &elements {
296 for token in &element.raw_params {
297 let Some((key, value)) = as_field(token) else {
298 continue;
299 };
300 if !self.options.annotation_fields.contains(&key) {
301 continue;
302 }
303 if accepted_fields(element.device_letter)
310 .iter()
311 .any(|stamped| *stamped == key)
312 {
313 continue;
314 }
315 annotations.push(DeviceAnnotation {
316 element: element.name.clone(),
317 device_letter: element.device_letter,
318 key,
319 value: value.to_string(),
320 line: element.span.start,
321 });
322 }
323 }
324 }
325
326 let mut warnings = Vec::new();
327
328 for statement in statements {
339 match statement {
340 Statement::Ic(assignments, span) => {
341 for (target, raw) in assignments {
342 initial_conditions.push(dot_ic_condition(
343 target, raw, span.start, &elements, &index,
344 )?);
345 }
346 }
347 Statement::Nodeset(_, span) | Statement::NodesetAll(_, span) => {
348 warnings.push(format!(
349 "line {}: .NODESET is a hint for a DC operating-point solve, which \
350 this crate does not perform -- it has no effect here; use .IC or ic= \
351 to declare a starting state",
352 span.start
353 ));
354 }
355 _ => {}
356 }
357 }
358
359 let order = index.names.len();
360 let mut a = Matrix::filled(order, order, Expression::zero());
361 let mut k = Matrix::filled(order, order, Expression::zero());
362 let mut b = Matrix::filled(order, inputs.len(), Expression::zero());
363
364 let inductances = elements
365 .iter()
366 .filter(|element| element.device_letter == 'L')
367 .map(|element| Ok((normalize(&element.name), scalar_value(element)?)))
368 .collect::<Result<HashMap<_, _>, BuildError>>()?;
369
370 for element in elements {
371 if let Some(state) = self.switch_state(element) {
372 let resistance = match state {
373 SwitchState::On => self.options.on_resistance.clone(),
374 SwitchState::Off => self.options.off_resistance.clone(),
375 };
376 stamp_admittance(&mut a, &index, element, resistance.reciprocal())?;
377 continue;
378 }
379
380 match element.device_letter {
381 'R' => {
382 stamp_admittance(&mut a, &index, element, scalar_value(element)?.reciprocal())?
383 }
384 'C' => stamp_admittance(&mut k, &index, element, scalar_value(element)?)?,
385 'L' => stamp_inductor(&mut a, &mut k, &index, element)?,
386 'V' => stamp_voltage_source(
387 &mut a,
388 &mut b,
389 &index,
390 element,
391 input_by_element[&normalize(&element.name)],
392 )?,
393 'I' => stamp_current_source(
394 &mut b,
395 &index,
396 element,
397 input_by_element[&normalize(&element.name)],
398 )?,
399 'G' => stamp_vccs(&mut a, &index, element)?,
400 'E' => stamp_vcvs(&mut a, &index, element)?,
401 'F' => stamp_cccs(&mut a, &index, element)?,
402 'H' => stamp_ccvs(&mut a, &index, element)?,
403 'K' => stamp_mutual_inductance(&mut k, &index, element, &inductances)?,
404 'D' => {
405 let conductance = Expression::symbol(format!("{}_G", element.name));
406 stamp_admittance(&mut a, &index, element, conductance)?;
407 stamp_current_source(
408 &mut b,
409 &index,
410 element,
411 input_by_element[&normalize(&element.name)],
412 )?;
413 }
414 _ => self.unsupported(element, &mut warnings)?,
415 }
416 }
417
418 let mut u = vec![Expression::zero(); order];
419 for row in 0..order {
420 for column in 0..inputs.len() {
421 u[row] = u[row].clone() + b[(row, column)].clone() * input_values[column].clone();
422 }
423 }
424
425 let mut parameter_defaults = BTreeMap::new();
426 for statement in statements {
427 if let Statement::Param(param) | Statement::GlobalParam(param) = statement {
428 for (name, raw_value) in ¶m.assignments {
429 if let Ok(value) = Expression::parse_scalar(raw_value) {
430 parameter_defaults.insert(name.clone(), value);
431 } else {
432 warnings.push(format!(
433 "parameter '{name}' has an expression that is preserved by general-spice-core but is not a scalar MNA value"
434 ));
435 }
436 }
437 }
438 }
439
440 Ok(MnaSystem {
441 a,
442 k,
443 b,
444 u,
445 unknowns: index.names,
446 inputs,
447 input_values,
448 transient_sources,
449 initial_conditions,
450 parameter_defaults,
451 warnings,
452 annotations,
453 })
454 }
455
456 fn is_branch_device(&self, element: &ElementInstance) -> bool {
457 self.switch_state(element).is_none()
458 && matches!(element.device_letter, 'V' | 'L' | 'E' | 'H')
459 }
460
461 fn switch_state(&self, element: &ElementInstance) -> Option<SwitchState> {
462 self.options
463 .switch_states
464 .get(&normalize(&element.name))
465 .copied()
466 }
467
468 fn unsupported(
469 &self,
470 element: &ElementInstance,
471 warnings: &mut Vec<String>,
472 ) -> Result<(), BuildError> {
473 let message = format!(
474 "element '{}' (device {}) has no linear MNA stamp",
475 element.name, element.device_letter
476 );
477 match self.options.unsupported_elements {
478 UnsupportedElementPolicy::Error => Err(BuildError::UnsupportedElement(message)),
479 UnsupportedElementPolicy::IgnoreWithWarning => {
480 warnings.push(message);
481 Ok(())
482 }
483 }
484 }
485}
486
487#[derive(Debug, Default)]
488struct UnknownIndex {
489 names: Vec<String>,
490 nodes: HashMap<String, usize>,
491 branches: HashMap<String, usize>,
492 nodes_finished: bool,
493}
494
495impl UnknownIndex {
496 fn add_node(&mut self, name: &str) {
497 if is_ground(name) {
498 return;
499 }
500 let key = normalize(name);
501 if !self.nodes.contains_key(&key) {
502 let index = self.names.len();
503 self.nodes.insert(key, index);
504 self.names.push(format!("V({name})"));
505 }
506 }
507
508 fn finish_nodes(&mut self) {
509 self.nodes_finished = true;
510 }
511
512 fn add_branch(&mut self, name: &str) -> Result<(), BuildError> {
513 debug_assert!(self.nodes_finished);
514 let key = normalize(name);
515 if self.branches.contains_key(&key) {
516 return Err(BuildError::DuplicateElement(name.to_string()));
517 }
518 let index = self.names.len();
519 self.branches.insert(key, index);
520 self.names.push(format!("I({name})"));
521 Ok(())
522 }
523
524 fn node(&self, name: &str) -> Option<usize> {
525 if is_ground(name) {
526 None
527 } else {
528 self.nodes.get(&normalize(name)).copied()
529 }
530 }
531
532 fn branch(&self, name: &str) -> Result<usize, BuildError> {
533 self.branches
534 .get(&normalize(name))
535 .copied()
536 .ok_or_else(|| BuildError::UnknownControllingBranch(name.to_string()))
537 }
538}
539
540fn stamp(
541 matrix: &mut Matrix<Expression>,
542 row: Option<usize>,
543 col: Option<usize>,
544 value: Expression,
545) {
546 if let (Some(row), Some(col)) = (row, col) {
547 matrix[(row, col)] = matrix[(row, col)].clone() + value;
548 }
549}
550
551fn stamp_input(matrix: &mut Matrix<Expression>, row: Option<usize>, col: usize, value: Expression) {
552 if let Some(row) = row {
553 matrix[(row, col)] = matrix[(row, col)].clone() + value;
554 }
555}
556
557fn two_nodes(element: &ElementInstance) -> Result<(&str, &str), BuildError> {
558 match element.nodes.as_slice() {
559 [positive, negative, ..] => Ok((positive, negative)),
560 _ => Err(BuildError::InvalidElement {
561 name: element.name.clone(),
562 message: "requires two terminals".into(),
563 }),
564 }
565}
566
567fn four_nodes(element: &ElementInstance) -> Result<(&str, &str, &str, &str), BuildError> {
568 match element.nodes.as_slice() {
569 [out_positive, out_negative, ctrl_positive, ctrl_negative] => {
570 Ok((out_positive, out_negative, ctrl_positive, ctrl_negative))
571 }
572 _ => Err(BuildError::InvalidElement {
573 name: element.name.clone(),
574 message: "requires the classic four-node linear form".into(),
575 }),
576 }
577}
578
579fn stamp_admittance(
580 matrix: &mut Matrix<Expression>,
581 index: &UnknownIndex,
582 element: &ElementInstance,
583 admittance: Expression,
584) -> Result<(), BuildError> {
585 let (positive, negative) = two_nodes(element)?;
586 let p = index.node(positive);
587 let n = index.node(negative);
588 stamp(matrix, p, p, admittance.clone());
589 stamp(matrix, n, n, admittance.clone());
590 stamp(matrix, p, n, -admittance.clone());
591 stamp(matrix, n, p, -admittance);
592 Ok(())
593}
594
595fn stamp_branch_incidence(
596 matrix: &mut Matrix<Expression>,
597 index: &UnknownIndex,
598 element: &ElementInstance,
599) -> Result<usize, BuildError> {
600 let (positive, negative) = two_nodes(element)?;
601 let branch = index.branch(&element.name)?;
602 let p = index.node(positive);
603 let n = index.node(negative);
604 stamp(matrix, p, Some(branch), Expression::one());
605 stamp(matrix, n, Some(branch), -Expression::one());
606 stamp(matrix, Some(branch), p, Expression::one());
607 stamp(matrix, Some(branch), n, -Expression::one());
608 Ok(branch)
609}
610
611fn stamp_inductor(
612 a: &mut Matrix<Expression>,
613 k: &mut Matrix<Expression>,
614 index: &UnknownIndex,
615 element: &ElementInstance,
616) -> Result<(), BuildError> {
617 let branch = stamp_branch_incidence(a, index, element)?;
618 stamp(k, Some(branch), Some(branch), -scalar_value(element)?);
619 Ok(())
620}
621
622fn stamp_voltage_source(
623 a: &mut Matrix<Expression>,
624 b: &mut Matrix<Expression>,
625 index: &UnknownIndex,
626 element: &ElementInstance,
627 input: usize,
628) -> Result<(), BuildError> {
629 let branch = stamp_branch_incidence(a, index, element)?;
630 stamp_input(b, Some(branch), input, Expression::one());
631 Ok(())
632}
633
634fn stamp_current_source(
635 b: &mut Matrix<Expression>,
636 index: &UnknownIndex,
637 element: &ElementInstance,
638 input: usize,
639) -> Result<(), BuildError> {
640 let (positive, negative) = two_nodes(element)?;
641 stamp_input(b, index.node(positive), input, -Expression::one());
642 stamp_input(b, index.node(negative), input, Expression::one());
643 Ok(())
644}
645
646fn stamp_vccs(
647 a: &mut Matrix<Expression>,
648 index: &UnknownIndex,
649 element: &ElementInstance,
650) -> Result<(), BuildError> {
651 let (op, on, cp, cn) = four_nodes(element)?;
652 let gain = scalar_value(element)?;
653 stamp(a, index.node(op), index.node(cp), gain.clone());
654 stamp(a, index.node(op), index.node(cn), -gain.clone());
655 stamp(a, index.node(on), index.node(cp), -gain.clone());
656 stamp(a, index.node(on), index.node(cn), gain);
657 Ok(())
658}
659
660fn stamp_vcvs(
661 a: &mut Matrix<Expression>,
662 index: &UnknownIndex,
663 element: &ElementInstance,
664) -> Result<(), BuildError> {
665 let (_, _, cp, cn) = four_nodes(element)?;
666 let branch = stamp_branch_incidence(a, index, element)?;
667 let gain = scalar_value(element)?;
668 stamp(a, Some(branch), index.node(cp), -gain.clone());
669 stamp(a, Some(branch), index.node(cn), gain);
670 Ok(())
671}
672
673fn stamp_cccs(
674 a: &mut Matrix<Expression>,
675 index: &UnknownIndex,
676 element: &ElementInstance,
677) -> Result<(), BuildError> {
678 let (positive, negative) = two_nodes(element)?;
679 let (control, gain) = control_and_gain(element)?;
680 let control = index.branch(control)?;
681 stamp(a, index.node(positive), Some(control), gain.clone());
682 stamp(a, index.node(negative), Some(control), -gain);
683 Ok(())
684}
685
686fn stamp_ccvs(
687 a: &mut Matrix<Expression>,
688 index: &UnknownIndex,
689 element: &ElementInstance,
690) -> Result<(), BuildError> {
691 let branch = stamp_branch_incidence(a, index, element)?;
692 let (control, gain) = control_and_gain(element)?;
693 let control = index.branch(control)?;
694 stamp(a, Some(branch), Some(control), -gain);
695 Ok(())
696}
697
698fn stamp_mutual_inductance(
699 k_matrix: &mut Matrix<Expression>,
700 index: &UnknownIndex,
701 element: &ElementInstance,
702 inductances: &HashMap<String, Expression>,
703) -> Result<(), BuildError> {
704 if element.nodes.len() < 2 {
705 return Err(BuildError::InvalidElement {
706 name: element.name.clone(),
707 message: "requires at least two inductor names".into(),
708 });
709 }
710 let coefficient = scalar_value(element)?;
711 for first in 0..element.nodes.len() {
712 for second in first + 1..element.nodes.len() {
713 let first_name = &element.nodes[first];
714 let second_name = &element.nodes[second];
715 let first_l = inductances
716 .get(&normalize(first_name))
717 .ok_or_else(|| BuildError::UnknownInductor(first_name.clone()))?;
718 let second_l = inductances
719 .get(&normalize(second_name))
720 .ok_or_else(|| BuildError::UnknownInductor(second_name.clone()))?;
721 let mutual = coefficient.clone() * (first_l.clone() * second_l.clone()).sqrt();
722 let first_branch = index.branch(first_name)?;
723 let second_branch = index.branch(second_name)?;
724 stamp(
725 k_matrix,
726 Some(first_branch),
727 Some(second_branch),
728 -mutual.clone(),
729 );
730 stamp(k_matrix, Some(second_branch), Some(first_branch), -mutual);
731 }
732 }
733 Ok(())
734}
735
736fn is_stamped_letter(device_letter: char) -> bool {
742 matches!(
743 device_letter,
744 'R' | 'C' | 'L' | 'K' | 'V' | 'I' | 'E' | 'F' | 'G' | 'H' | 'D'
745 )
746}
747
748fn accepted_fields(device_letter: char) -> &'static [&'static str] {
758 match device_letter {
759 'C' | 'L' => &["ic"],
761 _ => &[],
762 }
763}
764
765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
772enum PositionalGrammar {
773 OneValue,
778 ControlAndGain,
781 SourceClauses,
783 DiodeModel,
786 Unchecked,
790}
791
792fn positional_grammar(element: &ElementInstance) -> Option<PositionalGrammar> {
800 match element.device_letter {
801 'R' | 'C' | 'L' | 'K' => Some(PositionalGrammar::OneValue),
802 'E' | 'G' if element.nodes.len() == 4 => Some(PositionalGrammar::OneValue),
803 'E' | 'G' => None,
804 'F' | 'H' => Some(PositionalGrammar::ControlAndGain),
805 'V' | 'I' => Some(PositionalGrammar::SourceClauses),
806 'D' => Some(PositionalGrammar::DiodeModel),
807 _ => Some(PositionalGrammar::Unchecked),
808 }
809}
810
811fn as_field(token: &str) -> Option<(String, &str)> {
815 let (key, value) = token.split_once('=')?;
816 let key = key.trim();
817 if key.is_empty() {
818 return None;
819 }
820 Some((key.to_ascii_lowercase(), value))
821}
822
823fn validate_trailing_fields(
833 element: &ElementInstance,
834 grammar: PositionalGrammar,
835 annotation_fields: &BTreeSet<String>,
836) -> Result<(), BuildError> {
837 let letter = element.device_letter;
838 let accepted = accepted_fields(letter);
839 let mut positional: Vec<&str> = Vec::new();
840
841 for token in &element.raw_params {
842 let Some((key, _)) = as_field(token) else {
843 positional.push(token.as_str());
844 continue;
845 };
846 if accepted.iter().any(|allowed| *allowed == key) {
847 continue;
848 }
849 if annotation_fields.contains(&key) {
854 continue;
855 }
856 return Err(BuildError::InvalidElementField {
857 line: element.span.start,
858 name: element.name.clone(),
859 message: match accepted {
860 [] => {
861 format!("unknown field '{key}' (device {letter} accepts no key=value fields)")
862 }
863 _ => format!(
864 "unknown field '{key}' (device {letter} accepts only: {})",
865 accepted.join(", ")
866 ),
867 },
868 });
869 }
870
871 match grammar {
872 PositionalGrammar::OneValue if positional.len() > 1 => Err(field_error(
873 element,
874 format!(
875 "unexpected extra parameter '{}' (device {letter} takes exactly one value{})",
876 positional[1],
877 accepted_suffix(accepted)
878 ),
879 )),
880 PositionalGrammar::ControlAndGain if positional.len() > 2 => Err(field_error(
881 element,
882 format!(
883 "unexpected extra parameter '{}' (device {letter} takes exactly two values, a \
884 controlling source name and a gain)",
885 positional[2]
886 ),
887 )),
888 PositionalGrammar::SourceClauses => validate_source_positional(element, &positional),
889 PositionalGrammar::DiodeModel => validate_diode_positional(element, &positional),
890 _ => Ok(()),
891 }
892}
893
894fn field_error(element: &ElementInstance, message: String) -> BuildError {
896 BuildError::InvalidElementField {
897 line: element.span.start,
898 name: element.name.clone(),
899 message,
900 }
901}
902
903fn is_value_token(token: &str) -> bool {
907 Expression::parse_scalar(token).is_ok()
908}
909
910fn validate_source_positional(
931 element: &ElementInstance,
932 positional: &[&str],
933) -> Result<(), BuildError> {
934 let letter = element.device_letter;
935 let mut index = 0usize;
936 let mut seen_dc = false;
937 let mut seen_ac = false;
938 let mut seen_function = false;
939
940 while index < positional.len() {
941 let token = positional[index];
942 if token.eq_ignore_ascii_case("dc") {
943 if seen_dc {
944 return Err(field_error(
945 element,
946 format!("device {letter} declares a DC value more than once"),
947 ));
948 }
949 seen_dc = true;
950 match positional.get(index + 1) {
951 Some(value) if is_value_token(value) => index += 2,
952 Some(value) => {
953 return Err(field_error(
954 element,
955 format!("'dc' is followed by '{value}', which is not a value"),
956 ))
957 }
958 None => {
959 return Err(field_error(
960 element,
961 "'dc' is not followed by a value".to_string(),
962 ))
963 }
964 }
965 } else if token.eq_ignore_ascii_case("ac") {
966 if seen_ac {
967 return Err(field_error(
968 element,
969 format!("device {letter} declares an AC specification more than once"),
970 ));
971 }
972 seen_ac = true;
973 let mut consumed = 0usize;
974 while consumed < 2 {
975 match positional.get(index + 1 + consumed) {
976 Some(next)
977 if !next.eq_ignore_ascii_case("dc")
978 && !next.eq_ignore_ascii_case("ac")
979 && !next.contains('(')
980 && is_value_token(next) =>
981 {
982 consumed += 1
983 }
984 _ => break,
985 }
986 }
987 if consumed == 0 {
988 return Err(field_error(
989 element,
990 "'ac' is not followed by a magnitude".to_string(),
991 ));
992 }
993 index += 1 + consumed;
994 } else if let Some(paren) = token.find('(') {
995 let name = &token[..paren];
996 if !TransientFunction::is_function_name(name) {
997 return Err(field_error(
998 element,
999 format!(
1000 "unknown source function '{name}' (device {letter} accepts {})",
1001 TransientFunction::FUNCTION_NAMES.join("/")
1002 ),
1003 ));
1004 }
1005 if seen_function {
1006 return Err(field_error(
1007 element,
1008 format!("device {letter} declares more than one transient function"),
1009 ));
1010 }
1011 seen_function = true;
1012 let Some(end) = positional[index..]
1013 .iter()
1014 .position(|token| token.contains(')'))
1015 .map(|offset| offset + index)
1016 else {
1017 return Err(field_error(
1018 element,
1019 format!("'{name}(' is never closed by a ')'"),
1020 ));
1021 };
1022 let call: Vec<String> = positional[index..=end]
1023 .iter()
1024 .map(|token| (*token).to_string())
1025 .collect();
1026 if TransientFunction::parse(&call).is_none() {
1027 return Err(field_error(
1028 element,
1029 format!("'{}' is not a valid {name} parameter list", call.join(" ")),
1030 ));
1031 }
1032 index = end + 1;
1033 } else if index == 0 && is_value_token(token) {
1034 seen_dc = true;
1036 index += 1;
1037 } else {
1038 return Err(field_error(
1039 element,
1040 format!(
1041 "unexpected extra parameter '{token}' (device {letter} takes a DC value, an \
1042 'ac' specification, and/or one of {}{})",
1043 TransientFunction::FUNCTION_NAMES.join("/"),
1044 accepted_suffix(accepted_fields(letter))
1045 ),
1046 ));
1047 }
1048 }
1049 Ok(())
1050}
1051
1052fn validate_diode_positional(
1067 element: &ElementInstance,
1068 positional: &[&str],
1069) -> Result<(), BuildError> {
1070 let mut off = 0usize;
1071 let mut values: Vec<&str> = Vec::new();
1072 for token in positional {
1073 if token.eq_ignore_ascii_case("off") {
1074 off += 1;
1075 } else {
1076 values.push(token);
1077 }
1078 }
1079 if off > 1 {
1080 return Err(field_error(
1081 element,
1082 "'off' is given more than once".to_string(),
1083 ));
1084 }
1085 if let Some(area) = values.get(1) {
1086 if !is_value_token(area) {
1087 return Err(field_error(
1088 element,
1089 format!("'{area}' is not a value (device D's second parameter is its area factor)"),
1090 ));
1091 }
1092 }
1093 if let Some(extra) = values.get(2) {
1094 return Err(field_error(
1095 element,
1096 format!(
1097 "unexpected extra parameter '{extra}' (device D takes a model name, an optional \
1098 area factor and an optional 'off')"
1099 ),
1100 ));
1101 }
1102 Ok(())
1103}
1104
1105fn accepted_suffix(accepted: &'static [&'static str]) -> String {
1108 match accepted {
1109 [] => String::new(),
1110 _ => format!(", plus optional {}", accepted.join("/")),
1111 }
1112}
1113
1114fn dot_ic_condition(
1136 target: &str,
1137 raw_value: &str,
1138 line: usize,
1139 elements: &[&ElementInstance],
1140 index: &UnknownIndex,
1141) -> Result<InitialCondition, BuildError> {
1142 let error = |message: String| BuildError::InvalidInitialConditionDirective {
1143 line,
1144 target: target.to_string(),
1145 message,
1146 };
1147 let target_trimmed = target.trim();
1148 let Some((kind, inner)) = target_trimmed
1149 .strip_suffix(')')
1150 .and_then(|without_close| without_close.split_once('('))
1151 else {
1152 return Err(error(
1153 "is not of the form V(<node>), V(<node>,<node>) or I(<inductor>)".into(),
1154 ));
1155 };
1156 let value = Expression::parse_scalar(raw_value)
1157 .map_err(|message| error(format!("value '{raw_value}' is not a value: {message}")))?;
1158 let element_label = format!(".IC {target_trimmed}");
1159
1160 let node_index = |name: &str| -> Result<Option<usize>, BuildError> {
1161 let name = name.trim();
1162 if is_ground(name) {
1163 return Ok(None);
1164 }
1165 index
1166 .node(name)
1167 .map(Some)
1168 .ok_or_else(|| error(format!("names node '{name}', which no element connects to")))
1169 };
1170
1171 match kind.trim().to_ascii_uppercase().as_str() {
1172 "V" => {
1173 let (positive, negative) = match inner.split_once(',') {
1174 Some((first, second)) => (node_index(first)?, node_index(second)?),
1175 None => (node_index(inner)?, None),
1176 };
1177 if positive.is_none() && negative.is_none() {
1178 return Err(error(
1179 "assigns a voltage to ground, which is the reference and is always 0".into(),
1180 ));
1181 }
1182 Ok(InitialCondition::CapacitorVoltage {
1183 element: element_label,
1184 positive,
1185 negative,
1186 value,
1187 })
1188 }
1189 "I" => {
1190 let name = inner.trim();
1191 let Some(element) = elements
1192 .iter()
1193 .find(|element| element.name.eq_ignore_ascii_case(name))
1194 else {
1195 return Err(error(format!(
1196 "names element '{name}', which this netlist does not declare"
1197 )));
1198 };
1199 if element.device_letter != 'L' {
1200 return Err(error(format!(
1201 "names '{name}', which is not an inductor -- I(...) declares an inductor's \
1202 initial current; a node voltage is V(<node>)"
1203 )));
1204 }
1205 Ok(InitialCondition::InductorCurrent {
1206 element: element_label,
1207 branch: index.branch(name).map_err(|_| {
1208 error(format!(
1209 "names '{name}', which has no branch current in this system (a \
1210 switch-assigned element is stamped as a plain resistance)"
1211 ))
1212 })?,
1213 value,
1214 })
1215 }
1216 other => Err(error(format!(
1217 "'{other}(...)' is not a state -- only V(<node>), V(<node>,<node>) and I(<inductor>) \
1218 can be assigned"
1219 ))),
1220 }
1221}
1222
1223fn initial_condition_field(element: &ElementInstance) -> Option<&str> {
1224 element
1225 .raw_params
1226 .iter()
1227 .find_map(|token| match as_field(token) {
1228 Some((key, value)) if key == "ic" => Some(value),
1229 _ => None,
1230 })
1231}
1232
1233fn scalar_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1234 let raw = element
1235 .raw_params
1236 .first()
1237 .ok_or_else(|| BuildError::InvalidElement {
1238 name: element.name.clone(),
1239 message: "has no scalar value".into(),
1240 })?;
1241 Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1242 name: element.name.clone(),
1243 message,
1244 })
1245}
1246
1247fn source_value(element: &ElementInstance) -> Result<Expression, BuildError> {
1257 let params: Vec<&str> = element
1258 .raw_params
1259 .iter()
1260 .filter(|token| as_field(token).is_none())
1261 .map(|token| token.as_str())
1262 .collect();
1263 let raw = match params
1264 .iter()
1265 .position(|token| token.eq_ignore_ascii_case("dc"))
1266 .and_then(|index| params.get(index + 1))
1267 {
1268 Some(value) => *value,
1269 None => match params.first() {
1270 Some(first) if !first.eq_ignore_ascii_case("ac") && !first.contains('(') => *first,
1271 Some(_) => return Ok(Expression::zero()),
1272 None => {
1273 return Err(BuildError::InvalidElement {
1274 name: element.name.clone(),
1275 message: "has no source value".into(),
1276 })
1277 }
1278 },
1279 };
1280 Expression::parse_scalar(raw).map_err(|message| BuildError::InvalidElement {
1281 name: element.name.clone(),
1282 message,
1283 })
1284}
1285
1286fn control_and_gain(element: &ElementInstance) -> Result<(&str, Expression), BuildError> {
1287 match element.raw_params.as_slice() {
1288 [control, gain, ..] => Expression::parse_scalar(gain)
1289 .map(|gain| (control.as_str(), gain))
1290 .map_err(|message| BuildError::InvalidElement {
1291 name: element.name.clone(),
1292 message,
1293 }),
1294 _ => Err(BuildError::InvalidElement {
1295 name: element.name.clone(),
1296 message: "requires a controlling source and gain".into(),
1297 }),
1298 }
1299}
1300
1301fn normalize(value: &str) -> String {
1302 value.to_ascii_uppercase()
1303}
1304
1305fn is_ground(value: &str) -> bool {
1306 value == "0" || value.eq_ignore_ascii_case("gnd")
1307}
1308
1309#[derive(Debug, Clone, PartialEq)]
1311pub enum BuildError {
1312 Parse {
1314 message: String,
1316 line_start: usize,
1318 line_end: usize,
1320 },
1321 UnsupportedElement(String),
1323 InvalidElement {
1325 name: String,
1327 message: String,
1329 },
1330 InvalidElementField {
1333 line: usize,
1335 name: String,
1337 message: String,
1339 },
1340 DuplicateElement(String),
1342 UnknownControllingBranch(String),
1344 UnknownInductor(String),
1346 InvalidInitialConditionDirective {
1352 line: usize,
1354 target: String,
1356 message: String,
1358 },
1359}
1360
1361impl fmt::Display for BuildError {
1362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363 match self {
1364 Self::Parse {
1365 message,
1366 line_start,
1367 line_end,
1368 } => write!(
1369 f,
1370 "parse error at lines {line_start}..{line_end}: {message}"
1371 ),
1372 Self::UnsupportedElement(message) => f.write_str(message),
1373 Self::InvalidElement { name, message } => {
1374 write!(f, "cannot stamp element '{name}': {message}")
1375 }
1376 Self::InvalidElementField {
1377 line,
1378 name,
1379 message,
1380 } => write!(f, "line {line}: device '{name}' {message}"),
1381 Self::DuplicateElement(name) => {
1382 write!(f, "duplicate case-insensitive element name '{name}'")
1383 }
1384 Self::UnknownControllingBranch(name) => {
1385 write!(f, "unknown controlling branch '{name}'")
1386 }
1387 Self::UnknownInductor(name) => write!(f, "unknown coupled inductor '{name}'"),
1388 Self::InvalidInitialConditionDirective {
1389 line,
1390 target,
1391 message,
1392 } => write!(f, "line {line}: .IC '{target}' {message}"),
1393 }
1394 }
1395}
1396
1397impl std::error::Error for BuildError {}