Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/schematic_source/
symbols.rs

1use super::{
2    SchematicPoint, carrier_form_spans, child_point, child_scalar, direct_scalars, limit_error,
3    parse_symbol_instances, source_error,
4};
5use crate::sexpr_projection::FormSpan;
6use crate::source_bundle::SourceBundleError;
7use std::collections::HashMap;
8use std::fmt;
9use std::sync::Arc;
10
11use super::SchematicSymbolInstance;
12
13#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
14#[serde(deny_unknown_fields)]
15pub struct SchematicPlacedSymbol {
16    pub lib_id: String,
17    pub lib_name: String,
18    pub at: SchematicPoint,
19    #[serde(with = "angle_bits")]
20    pub angle_degrees: f64,
21    pub mirror: Option<String>,
22    pub unit: i64,
23    pub convert: i64,
24    pub exclude_from_sim: bool,
25    pub in_bom: bool,
26    pub on_board: bool,
27    pub in_pos_files: bool,
28    pub dnp: bool,
29    pub fields_autoplaced: bool,
30    pub uuid: String,
31    pub properties: Vec<SchematicSymbolProperty>,
32    pub pins: Vec<SchematicSymbolPin>,
33    pub instances: Vec<SchematicSymbolInstance>,
34    #[serde(skip)]
35    instance_by_project_path: HashMap<Arc<str>, HashMap<Arc<str>, InstanceIndexEntry>>,
36    #[serde(skip)]
37    instance_by_path: HashMap<Arc<str>, InstanceIndexEntry>,
38    #[serde(skip)]
39    suffix_index: InstanceSuffixIndex,
40    #[serde(skip)]
41    first_instance_by_project: HashMap<Arc<str>, usize>,
42}
43
44mod angle_bits {
45    use serde::{Deserialize, Deserializer, Serializer};
46    pub(super) fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
47        serializer.serialize_u64(value.to_bits())
48    }
49    pub(super) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
50        let value = f64::from_bits(u64::deserialize(deserializer)?);
51        if value.is_finite() {
52            Ok(value)
53        } else {
54            Err(serde::de::Error::custom(
55                "cached Source angle is not finite",
56            ))
57        }
58    }
59}
60
61impl SchematicPlacedSymbol {
62    pub(crate) fn rebuild_instance_indexes(
63        &mut self,
64        retained_bytes: &mut usize,
65        source_path: &str,
66    ) -> Result<(), SourceBundleError> {
67        for instance in &mut self.instances {
68            instance.rebuild_variant_index();
69        }
70        let indexes =
71            index_symbol_instances(&self.instances, usize::MAX, retained_bytes, source_path)?;
72        self.instance_by_project_path = indexes.by_project_path;
73        self.instance_by_path = indexes.by_path;
74        self.suffix_index = indexes.suffix_index;
75        self.first_instance_by_project = indexes.first_by_project;
76        Ok(())
77    }
78    pub fn instance_for_project(
79        &self,
80        project: &str,
81        path: &str,
82    ) -> Result<Option<&SchematicSymbolInstance>, SchematicSymbolInstanceLookupError> {
83        let entry = self
84            .instance_by_project_path
85            .get(project)
86            .and_then(|paths| paths.get(normalized_path(path)));
87        self.resolve_instance_entry(entry)
88    }
89
90    pub fn unique_instance_for_path(
91        &self,
92        path: &str,
93    ) -> Result<Option<&SchematicSymbolInstance>, SchematicSymbolInstanceLookupError> {
94        self.resolve_instance_entry(self.instance_by_path.get(normalized_path(path)))
95    }
96
97    pub(crate) fn compatible_instance_for_project(
98        &self,
99        project: &str,
100        path: &str,
101    ) -> Result<Option<&SchematicSymbolInstance>, SchematicSymbolInstanceLookupError> {
102        let (ordered, prefixes) = self
103            .suffix_index
104            .by_project
105            .get(project)
106            .zip(self.suffix_index.prefixes_by_project.get(project))
107            .unwrap_or((&self.suffix_index.all, &self.suffix_index.prefixes_all));
108        let entry = self.suffix_index.query(path, ordered, prefixes);
109        self.resolve_instance_entry(entry.as_ref())
110    }
111
112    pub(crate) fn first_instance_for_project(
113        &self,
114        project: &str,
115    ) -> Option<&SchematicSymbolInstance> {
116        self.first_instance_by_project
117            .get(project)
118            .map(|index| &self.instances[*index])
119            .or_else(|| self.instances.first())
120    }
121
122    fn resolve_instance_entry(
123        &self,
124        entry: Option<&InstanceIndexEntry>,
125    ) -> Result<Option<&SchematicSymbolInstance>, SchematicSymbolInstanceLookupError> {
126        let Some(entry) = entry else {
127            return Ok(None);
128        };
129        if entry.matches > 1 {
130            return Err(SchematicSymbolInstanceLookupError {
131                matches: entry.matches,
132            });
133        }
134        Ok(Some(&self.instances[entry.index]))
135    }
136}
137
138#[derive(Clone, Copy, Debug, Eq, PartialEq)]
139pub struct SchematicSymbolInstanceLookupError {
140    pub matches: usize,
141}
142
143impl fmt::Display for SchematicSymbolInstanceLookupError {
144    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145        write!(
146            formatter,
147            "symbol instance lookup is ambiguous across {} records",
148            self.matches
149        )
150    }
151}
152
153impl std::error::Error for SchematicSymbolInstanceLookupError {}
154
155#[derive(Clone, Copy, Debug, Eq, PartialEq)]
156struct InstanceIndexEntry {
157    index: usize,
158    matches: usize,
159}
160
161impl InstanceIndexEntry {
162    fn merge(self, other: Self) -> Self {
163        Self {
164            index: self.index.min(other.index),
165            matches: self.matches.saturating_add(other.matches),
166        }
167    }
168}
169
170#[derive(Clone, Debug, Default, Eq, PartialEq)]
171struct InstanceSuffixIndex {
172    reversed_bytes: Vec<u8>,
173    reversed_ranges: Vec<InstancePathRange>,
174    by_project: HashMap<Arc<str>, Vec<usize>>,
175    all: Vec<usize>,
176    prefixes_by_project: HashMap<Arc<str>, HashMap<PathFingerprint, FingerprintBucket>>,
177    prefixes_all: HashMap<PathFingerprint, FingerprintBucket>,
178}
179
180#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
181struct InstancePathRange {
182    start: usize,
183    end: usize,
184}
185
186#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
187struct PathFingerprint {
188    first: u64,
189    second: u64,
190    length: usize,
191}
192
193#[derive(Clone, Debug, Eq, PartialEq)]
194enum FingerprintBucket {
195    One(InstanceIndexEntry),
196    Collision(Vec<InstanceIndexEntry>),
197}
198
199#[derive(Debug, Default)]
200struct SchematicSymbolInstanceIndexes {
201    by_project_path: HashMap<Arc<str>, HashMap<Arc<str>, InstanceIndexEntry>>,
202    by_path: HashMap<Arc<str>, InstanceIndexEntry>,
203    suffix_index: InstanceSuffixIndex,
204    first_by_project: HashMap<Arc<str>, usize>,
205}
206
207impl InstanceSuffixIndex {
208    fn insert(&mut self, path: &str, project: &Arc<str>, instance_index: usize) {
209        let path = normalized_path(path);
210        let start = self.reversed_bytes.len();
211        self.reversed_bytes.extend(path.bytes().rev());
212        self.reversed_ranges.push(InstancePathRange {
213            start,
214            end: self.reversed_bytes.len(),
215        });
216        let project_paths = self.by_project.entry(Arc::clone(project)).or_default();
217        if path.is_empty() {
218            return;
219        }
220        project_paths.push(instance_index);
221        self.all.push(instance_index);
222    }
223
224    fn finish(
225        &mut self,
226        by_project_path: &HashMap<Arc<str>, HashMap<Arc<str>, InstanceIndexEntry>>,
227        by_path: &HashMap<Arc<str>, InstanceIndexEntry>,
228    ) {
229        let bytes = &self.reversed_bytes;
230        let ranges = &self.reversed_ranges;
231        let compare = |left: &usize, right: &usize| {
232            reversed_path(bytes, ranges, *left)
233                .cmp(reversed_path(bytes, ranges, *right))
234                .then(left.cmp(right))
235        };
236        self.all.sort_unstable_by(compare);
237        for ordered in self.by_project.values_mut() {
238            ordered.sort_unstable_by(compare);
239        }
240        self.prefixes_all = fingerprint_index(by_path, bytes, ranges);
241        for (project, paths) in by_project_path {
242            self.prefixes_by_project
243                .insert(Arc::clone(project), fingerprint_index(paths, bytes, ranges));
244        }
245    }
246
247    fn query(
248        &self,
249        path: &str,
250        ordered: &[usize],
251        prefixes: &HashMap<PathFingerprint, FingerprintBucket>,
252    ) -> Option<InstanceIndexEntry> {
253        let path = normalized_path(path);
254        if path.is_empty() {
255            return None;
256        }
257        let reversed = path.bytes().rev().collect::<Vec<_>>();
258        let mut result = None;
259        let mut fingerprint = PathFingerprint::default();
260        for (offset, byte) in reversed.iter().copied().enumerate() {
261            fingerprint.push(byte);
262            if offset + 1 < reversed.len()
263                && let Some(bucket) = prefixes.get(&fingerprint)
264                && let Some(entry) = bucket.matching(&reversed[..=offset], self)
265            {
266                merge_index_entry(&mut result, entry);
267            }
268        }
269        let start =
270            ordered.partition_point(|index| self.reversed_path(*index) < reversed.as_slice());
271        let end = prefix_successor(&reversed).map_or(ordered.len(), |upper| {
272            ordered.partition_point(|index| self.reversed_path(*index) < upper.as_slice())
273        });
274        if end > start {
275            merge_index_entry(
276                &mut result,
277                InstanceIndexEntry {
278                    index: ordered[start],
279                    matches: end - start,
280                },
281            );
282        }
283        result
284    }
285
286    fn reversed_path(&self, instance_index: usize) -> &[u8] {
287        reversed_path(&self.reversed_bytes, &self.reversed_ranges, instance_index)
288    }
289}
290
291fn prefix_successor(prefix: &[u8]) -> Option<Vec<u8>> {
292    let mut successor = prefix.to_vec();
293    while successor.last() == Some(&u8::MAX) {
294        successor.pop();
295    }
296    let last = successor.last_mut()?;
297    *last += 1;
298    Some(successor)
299}
300
301impl Default for PathFingerprint {
302    fn default() -> Self {
303        Self {
304            first: 0xcbf2_9ce4_8422_2325,
305            second: 0x8422_2325_cbf2_9ce4,
306            length: 0,
307        }
308    }
309}
310
311impl PathFingerprint {
312    fn push(&mut self, byte: u8) {
313        self.first = self
314            .first
315            .wrapping_mul(0x0000_0100_0000_01b3)
316            .wrapping_add(u64::from(byte) + 1);
317        self.second = self
318            .second
319            .wrapping_mul(0x9e37_79b1_85eb_ca87)
320            .wrapping_add(u64::from(byte) + 0x100);
321        self.length += 1;
322    }
323
324    fn for_reversed_path(path: &[u8]) -> Self {
325        let mut fingerprint = Self::default();
326        for byte in path {
327            fingerprint.push(*byte);
328        }
329        fingerprint
330    }
331}
332
333impl FingerprintBucket {
334    fn matching(
335        &self,
336        path: &[u8],
337        suffix_index: &InstanceSuffixIndex,
338    ) -> Option<InstanceIndexEntry> {
339        match self {
340            Self::One(entry) => (suffix_index.reversed_path(entry.index) == path).then_some(*entry),
341            Self::Collision(entries) => entries
342                .iter()
343                .find(|entry| suffix_index.reversed_path(entry.index) == path)
344                .copied(),
345        }
346    }
347}
348
349fn fingerprint_index(
350    paths: &HashMap<Arc<str>, InstanceIndexEntry>,
351    reversed_bytes: &[u8],
352    reversed_ranges: &[InstancePathRange],
353) -> HashMap<PathFingerprint, FingerprintBucket> {
354    let mut index = HashMap::with_capacity(paths.len());
355    for entry in paths
356        .values()
357        .filter(|entry| !reversed_path(reversed_bytes, reversed_ranges, entry.index).is_empty())
358    {
359        let path = reversed_path(reversed_bytes, reversed_ranges, entry.index);
360        let fingerprint = PathFingerprint::for_reversed_path(path);
361        index
362            .entry(fingerprint)
363            .and_modify(|bucket| match bucket {
364                FingerprintBucket::One(first) => {
365                    *bucket = FingerprintBucket::Collision(vec![*first, *entry]);
366                }
367                FingerprintBucket::Collision(entries) => entries.push(*entry),
368            })
369            .or_insert(FingerprintBucket::One(*entry));
370    }
371    index
372}
373
374fn reversed_path<'a>(
375    bytes: &'a [u8],
376    ranges: &[InstancePathRange],
377    instance_index: usize,
378) -> &'a [u8] {
379    let range = ranges[instance_index];
380    &bytes[range.start..range.end]
381}
382
383fn merge_index_entry(target: &mut Option<InstanceIndexEntry>, entry: InstanceIndexEntry) {
384    *target = Some(target.map_or(entry, |current| current.merge(entry)));
385}
386
387#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
388#[serde(deny_unknown_fields)]
389pub struct SchematicSymbolProperty {
390    pub key: String,
391    pub value: String,
392}
393
394#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
395#[serde(deny_unknown_fields)]
396pub struct SchematicSymbolPin {
397    pub number: String,
398    pub uuid: String,
399    pub alternate: Option<String>,
400}
401
402pub(crate) fn parse_placed_symbols(
403    source: &str,
404    source_path: &str,
405    spans: &[FormSpan],
406) -> Result<Vec<SchematicPlacedSymbol>, SourceBundleError> {
407    let mut symbols = Vec::new();
408    let mut retained_instance_index_bytes = 0_usize;
409    for span in spans
410        .iter()
411        .filter(|span| span.depth == 1 && span.head.as_deref() == Some("symbol"))
412    {
413        let text = span
414            .text(source)
415            .map_err(|error| source_error(source_path, error.to_string()))?;
416        symbols.push(parse_symbol(
417            text,
418            source_path,
419            &mut retained_instance_index_bytes,
420        )?);
421    }
422    Ok(symbols)
423}
424
425fn parse_symbol(
426    source: &str,
427    source_path: &str,
428    retained_instance_index_bytes: &mut usize,
429) -> Result<SchematicPlacedSymbol, SourceBundleError> {
430    let spans = carrier_form_spans(
431        source,
432        &[
433            "symbol",
434            "lib_id",
435            "lib_name",
436            "at",
437            "mirror",
438            "unit",
439            "convert",
440            "body_style",
441            "exclude_from_sim",
442            "in_bom",
443            "on_board",
444            "in_pos_files",
445            "dnp",
446            "fields_autoplaced",
447            "uuid",
448            "property",
449            "pin",
450            "instances",
451        ],
452        source_path,
453    )?;
454    let at_span = child(&spans, "at");
455    let at = at_span.map_or(Ok(SchematicPoint { x_iu: 0, y_iu: 0 }), |span| {
456        child_point_from_span(source, span, source_path)
457    })?;
458    let angle_degrees = at_span.map_or(Ok(0.0), |span| {
459        let values = direct_scalars(source, span, 3, source_path)?;
460        values
461            .get(2)
462            .map_or(Ok(0.0), |value| finite_f64(value, source_path))
463    })?;
464    let instances = parse_symbol_instances(source, child(&spans, "instances"), source_path)?;
465    let indexes = index_symbol_instances(
466        &instances,
467        usize::MAX,
468        retained_instance_index_bytes,
469        source_path,
470    )?;
471    Ok(SchematicPlacedSymbol {
472        lib_id: scalar(source, &spans, "lib_id", source_path)?.unwrap_or_default(),
473        lib_name: scalar(source, &spans, "lib_name", source_path)?.unwrap_or_default(),
474        at,
475        angle_degrees,
476        mirror: scalar(source, &spans, "mirror", source_path)?,
477        unit: integer(source, &spans, "unit", 1, source_path)?,
478        convert: body_style(source, &spans, source_path)?,
479        exclude_from_sim: boolean(source, &spans, "exclude_from_sim", false, source_path)?,
480        in_bom: boolean(source, &spans, "in_bom", true, source_path)?,
481        on_board: boolean(source, &spans, "on_board", true, source_path)?,
482        in_pos_files: boolean(source, &spans, "in_pos_files", true, source_path)?,
483        dnp: boolean(source, &spans, "dnp", false, source_path)?,
484        fields_autoplaced: maybe_absent_boolean(source, &spans, "fields_autoplaced", source_path)?,
485        uuid: scalar(source, &spans, "uuid", source_path)?.unwrap_or_default(),
486        properties: parse_properties(source, &spans, source_path)?,
487        pins: parse_pins(source, &spans, source_path)?,
488        instances,
489        instance_by_project_path: indexes.by_project_path,
490        instance_by_path: indexes.by_path,
491        suffix_index: indexes.suffix_index,
492        first_instance_by_project: indexes.first_by_project,
493    })
494}
495
496fn body_style(
497    source: &str,
498    spans: &[FormSpan],
499    source_path: &str,
500) -> Result<i64, SourceBundleError> {
501    // KiCad 10.0.5 parseSYMBOL accepts these as aliases to SetBodyStyle.
502    // Setters run in authored order, so the last declaration wins.
503    let mut value = 1;
504    for span in spans.iter().filter(|span| {
505        span.depth == 1 && matches!(span.head.as_deref(), Some("convert" | "body_style"))
506    }) {
507        value = direct_scalars(source, span, 1, source_path)?
508            .first()
509            .ok_or_else(|| source_error(source_path, "body style integer is missing"))?
510            .parse::<i64>()
511            .map_err(|_| source_error(source_path, "invalid body style integer"))?;
512    }
513    Ok(value)
514}
515
516fn index_symbol_instances(
517    instances: &[SchematicSymbolInstance],
518    _max_index_bytes: usize,
519    retained_bytes: &mut usize,
520    source_path: &str,
521) -> Result<SchematicSymbolInstanceIndexes, SourceBundleError> {
522    let mut indexes = SchematicSymbolInstanceIndexes {
523        by_path: HashMap::with_capacity(instances.len()),
524        ..SchematicSymbolInstanceIndexes::default()
525    };
526    for (index, instance) in instances.iter().enumerate() {
527        let path = normalized_path(&instance.path);
528        let required = instance_index_bytes(path).ok_or_else(|| {
529            limit_error(source_path, "symbol instance index byte count overflows")
530        })?;
531        let candidate_bytes = retained_bytes.checked_add(required).ok_or_else(|| {
532            limit_error(source_path, "symbol instance index byte count overflows")
533        })?;
534        *retained_bytes = candidate_bytes;
535        let path_key = indexes
536            .by_path
537            .get_key_value(path)
538            .map_or_else(|| Arc::<str>::from(path), |(key, _)| Arc::clone(key));
539        update_instance_index(
540            indexes
541                .by_project_path
542                .entry(Arc::clone(&instance.project))
543                .or_default(),
544            Arc::clone(&path_key),
545            index,
546        );
547        update_instance_index(&mut indexes.by_path, path_key, index);
548        indexes.suffix_index.insert(path, &instance.project, index);
549        indexes
550            .first_by_project
551            .entry(Arc::clone(&instance.project))
552            .or_insert(index);
553    }
554    indexes
555        .suffix_index
556        .finish(&indexes.by_project_path, &indexes.by_path);
557    Ok(indexes)
558}
559
560fn update_instance_index(
561    index: &mut HashMap<Arc<str>, InstanceIndexEntry>,
562    path: Arc<str>,
563    instance_index: usize,
564) {
565    index
566        .entry(path)
567        .and_modify(|entry| entry.matches = entry.matches.saturating_add(1))
568        .or_insert(InstanceIndexEntry {
569            index: instance_index,
570            matches: 1,
571        });
572}
573
574fn instance_index_bytes(path: &str) -> Option<usize> {
575    let range_bytes = std::mem::size_of::<InstancePathRange>();
576    if path.is_empty() {
577        return Some(range_bytes);
578    }
579    path.len()
580        .checked_mul(2)
581        .and_then(|bytes| bytes.checked_add(range_bytes))
582        .and_then(|bytes| bytes.checked_add(2 * std::mem::size_of::<usize>()))
583        .and_then(|bytes| bytes.checked_add(2 * std::mem::size_of::<PathFingerprint>()))
584        .and_then(|bytes| bytes.checked_add(2 * std::mem::size_of::<InstanceIndexEntry>()))
585}
586
587fn normalized_path(path: &str) -> &str {
588    path.trim_end_matches('/')
589}
590
591fn parse_properties(
592    source: &str,
593    spans: &[FormSpan],
594    source_path: &str,
595) -> Result<Vec<SchematicSymbolProperty>, SourceBundleError> {
596    let mut properties = Vec::new();
597    for span in direct_children(spans, "property") {
598        let text = span
599            .text(source)
600            .map_err(|error| source_error(source_path, error.to_string()))?;
601        let private = crate::sexpr::Lexer::new(text)
602            .nth(2)
603            .transpose()
604            .map_err(|error| source_error(source_path, error.to_string()))?
605            .is_some_and(|token| {
606                token.kind == crate::sexpr::TokenKind::Atom && token.lexeme == "private"
607            });
608        let offset = usize::from(private);
609        let values = direct_scalars(source, span, 2 + offset, source_path)?;
610        properties.push(SchematicSymbolProperty {
611            key: values.get(offset).cloned().unwrap_or_default(),
612            value: values.get(offset + 1).cloned().unwrap_or_default(),
613        });
614    }
615    Ok(properties)
616}
617
618fn parse_pins(
619    source: &str,
620    spans: &[FormSpan],
621    source_path: &str,
622) -> Result<Vec<SchematicSymbolPin>, SourceBundleError> {
623    let mut pins = Vec::new();
624    for span in direct_children(spans, "pin") {
625        let text = span
626            .text(source)
627            .map_err(|error| source_error(source_path, error.to_string()))?;
628        let nested = carrier_form_spans(text, &["pin", "uuid", "alternate"], source_path)?;
629        let root = nested
630            .iter()
631            .find(|selected| selected.depth == 0)
632            .ok_or_else(|| source_error(source_path, "symbol pin root is missing"))?;
633        let number = direct_scalars(text, root, 1, source_path)?
634            .into_iter()
635            .next()
636            .unwrap_or_default();
637        pins.push(SchematicSymbolPin {
638            number,
639            uuid: child_scalar(text, &nested, "uuid", source_path)?.unwrap_or_default(),
640            alternate: child_scalar(text, &nested, "alternate", source_path)?,
641        });
642    }
643    Ok(pins)
644}
645
646fn child_point_from_span(
647    source: &str,
648    span: &FormSpan,
649    source_path: &str,
650) -> Result<SchematicPoint, SourceBundleError> {
651    let local = [span.clone()];
652    child_point(
653        source,
654        &local,
655        span.head.as_deref().unwrap_or("at"),
656        SchematicPoint { x_iu: 0, y_iu: 0 },
657        source_path,
658    )
659}
660
661fn direct_children<'a>(spans: &'a [FormSpan], head: &'a str) -> impl Iterator<Item = &'a FormSpan> {
662    spans
663        .iter()
664        .filter(move |span| span.depth == 1 && span.head.as_deref() == Some(head))
665}
666
667fn child<'a>(spans: &'a [FormSpan], head: &str) -> Option<&'a FormSpan> {
668    spans
669        .iter()
670        .find(|span| span.depth == 1 && span.head.as_deref() == Some(head))
671}
672
673fn scalar(
674    source: &str,
675    spans: &[FormSpan],
676    head: &str,
677    source_path: &str,
678) -> Result<Option<String>, SourceBundleError> {
679    child_scalar(source, spans, head, source_path)
680}
681
682fn integer(
683    source: &str,
684    spans: &[FormSpan],
685    head: &str,
686    default: i64,
687    source_path: &str,
688) -> Result<i64, SourceBundleError> {
689    scalar(source, spans, head, source_path)?.map_or(Ok(default), |value| {
690        value
691            .parse::<i64>()
692            .map_err(|_| source_error(source_path, format!("invalid {head} integer")))
693    })
694}
695
696fn boolean(
697    source: &str,
698    spans: &[FormSpan],
699    head: &str,
700    default: bool,
701    source_path: &str,
702) -> Result<bool, SourceBundleError> {
703    Ok(scalar(source, spans, head, source_path)?.map_or(default, |value| value == "yes"))
704}
705
706fn maybe_absent_boolean(
707    source: &str,
708    spans: &[FormSpan],
709    head: &str,
710    source_path: &str,
711) -> Result<bool, SourceBundleError> {
712    let Some(span) = child(spans, head) else {
713        return Ok(false);
714    };
715    Ok(direct_scalars(source, span, 1, source_path)?
716        .first()
717        .is_none_or(|value| value == "yes"))
718}
719
720fn finite_f64(value: &str, source_path: &str) -> Result<f64, SourceBundleError> {
721    let value = value
722        .parse::<f64>()
723        .map_err(|_| source_error(source_path, "invalid symbol angle"))?;
724    if value.is_finite() {
725        Ok(value)
726    } else {
727        Err(source_error(source_path, "symbol angle must be finite"))
728    }
729}