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 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 ¶m.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
625fn 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
637fn accepted_fields(device_letter: char) -> &'static [&'static str] {
647 match device_letter {
648 'C' | 'L' => &["ic"],
650 _ => &[],
651 }
652}
653
654#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661enum PositionalGrammar {
662 OneValue,
667 ControlAndGain,
670 SourceClauses,
672 DiodeModel,
675 Unchecked,
679}
680
681fn 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
700fn 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
712fn 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
775fn 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
784fn is_value_token(token: &str) -> bool {
788 Expression::parse_scalar(token).is_ok()
789}
790
791fn 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 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
933fn 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
986fn accepted_suffix(accepted: &'static [&'static str]) -> String {
989 match accepted {
990 [] => String::new(),
991 _ => format!(", plus optional {}", accepted.join("/")),
992 }
993}
994
995fn 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
1022fn 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#[derive(Debug, Clone, PartialEq)]
1086pub enum BuildError {
1087 Parse {
1089 message: String,
1091 line_start: usize,
1093 line_end: usize,
1095 },
1096 UnsupportedElement(String),
1098 InvalidElement {
1100 name: String,
1102 message: String,
1104 },
1105 InvalidElementField {
1108 line: usize,
1110 name: String,
1112 message: String,
1114 },
1115 DuplicateElement(String),
1117 UnknownControllingBranch(String),
1119 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 {}