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

kicad_monkey_core/
schematic_source.rs

1use crate::sexpr::{Lexer, Token, TokenKind, decode_quoted};
2use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
3use crate::source_bundle::{SourceBundleError, SourceBundleErrorKind};
4use std::borrow::Cow;
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6mod bus_aliases;
7mod library_symbols;
8mod symbol_instances;
9mod symbols;
10pub use bus_aliases::SchematicBusAlias;
11pub(crate) use bus_aliases::parse_bus_aliases;
12pub(crate) use library_symbols::parse_embedded_library_symbols;
13pub use library_symbols::{SchematicLibraryPin, SchematicLibrarySubsymbol, SchematicLibrarySymbol};
14pub use symbol_instances::{
15    SchematicLegacySymbolInstance, SchematicSymbolInstance, SchematicSymbolInstanceVariant,
16    SchematicSymbolVariantField,
17};
18pub(crate) use symbol_instances::{parse_legacy_symbol_instances, parse_symbol_instances};
19pub(crate) use symbols::parse_placed_symbols;
20pub use symbols::{
21    SchematicPlacedSymbol, SchematicSymbolInstanceLookupError, SchematicSymbolPin,
22    SchematicSymbolProperty,
23};
24pub const SCHEMATIC_IU_PER_MM: i64 = 10_000;
25
26/// Exact schematic-grid coordinate used by connectivity rather than floating point.
27#[derive(
28    Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
29)]
30#[serde(deny_unknown_fields)]
31pub struct SchematicPoint {
32    pub x_iu: i64,
33    pub y_iu: i64,
34}
35
36impl SchematicPoint {
37    pub fn x_mm(self) -> f64 {
38        self.x_iu as f64 / SCHEMATIC_IU_PER_MM as f64
39    }
40
41    pub fn y_mm(self) -> f64 {
42        self.y_iu as f64 / SCHEMATIC_IU_PER_MM as f64
43    }
44}
45
46/// A source wire or bus polyline.
47#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct SchematicPolyline {
50    pub uuid: String,
51    pub points: Vec<SchematicPoint>,
52}
53
54/// The stored origin and diagonal size of a bus entry.
55#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct SchematicBusEntry {
58    pub uuid: String,
59    pub at: SchematicPoint,
60    pub size: SchematicPoint,
61}
62
63impl SchematicBusEntry {
64    pub fn wire_end(&self) -> Option<SchematicPoint> {
65        Some(SchematicPoint {
66            x_iu: self.at.x_iu.checked_add(self.size.x_iu)?,
67            y_iu: self.at.y_iu.checked_add(self.size.y_iu)?,
68        })
69    }
70}
71
72/// A junction marker at one exact schematic coordinate.
73#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
74#[serde(deny_unknown_fields)]
75pub struct SchematicJunction {
76    pub uuid: String,
77    pub at: SchematicPoint,
78}
79
80/// An intentional no-connect marker.
81#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct SchematicNoConnect {
84    pub uuid: String,
85    pub at: SchematicPoint,
86}
87
88#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
89#[serde(deny_unknown_fields)]
90pub enum SchematicLabelScope {
91    Local,
92    Global,
93    Hierarchical,
94}
95
96/// Connectivity-relevant fields shared by local, global, and hierarchical labels.
97#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
98#[serde(deny_unknown_fields)]
99pub struct SchematicLabel {
100    pub scope: SchematicLabelScope,
101    pub text: String,
102    pub shape: String,
103    pub uuid: String,
104    pub at: SchematicPoint,
105}
106
107#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
108#[serde(deny_unknown_fields)]
109pub struct SchematicSheetPin {
110    pub name: String,
111    pub shape: SchematicPinShape,
112    pub uuid: String,
113    pub at: SchematicPoint,
114}
115
116#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
117#[serde(deny_unknown_fields)]
118pub enum SchematicPinShape {
119    Input,
120    Output,
121    Bidirectional,
122    TriState,
123    Passive,
124    Dot,
125    Round,
126    Diamond,
127    Rectangle,
128}
129
130impl SchematicPinShape {
131    pub fn as_str(self) -> &'static str {
132        match self {
133            Self::Input => "input",
134            Self::Output => "output",
135            Self::Bidirectional => "bidirectional",
136            Self::TriState => "tri_state",
137            Self::Passive => "passive",
138            Self::Dot => "dot",
139            Self::Round => "round",
140            Self::Diamond => "diamond",
141            Self::Rectangle => "rectangle",
142        }
143    }
144
145    fn from_source(value: Option<&str>) -> Self {
146        match value {
147            Some("output") => Self::Output,
148            Some("bidirectional") => Self::Bidirectional,
149            Some("tri_state") => Self::TriState,
150            Some("passive") => Self::Passive,
151            Some("dot") => Self::Dot,
152            Some("round") => Self::Round,
153            Some("diamond") => Self::Diamond,
154            Some("rectangle") => Self::Rectangle,
155            _ => Self::Input,
156        }
157    }
158}
159
160/// Deterministic connected components over wire endpoints and registered carrier points.
161#[derive(Clone, Debug, Default, Eq, PartialEq)]
162pub struct SchematicConnectivity {
163    points: Vec<SchematicPoint>,
164    components: Vec<Vec<SchematicPoint>>,
165    component_by_point: BTreeMap<SchematicPoint, usize>,
166}
167
168impl SchematicConnectivity {
169    pub fn points(&self) -> impl ExactSizeIterator<Item = &SchematicPoint> {
170        self.points.iter()
171    }
172
173    pub fn components(&self) -> impl ExactSizeIterator<Item = &[SchematicPoint]> {
174        self.components.iter().map(Vec::as_slice)
175    }
176
177    pub fn component(&self, point: SchematicPoint) -> Option<&[SchematicPoint]> {
178        self.component_by_point
179            .get(&point)
180            .map(|index| self.components[*index].as_slice())
181    }
182
183    pub fn connected(&self, left: SchematicPoint, right: SchematicPoint) -> bool {
184        self.component_by_point
185            .get(&left)
186            .is_some_and(|left_index| self.component_by_point.get(&right) == Some(left_index))
187    }
188}
189
190#[derive(Debug, Default)]
191pub(crate) struct SchematicSourceCarriers {
192    pub wires: Vec<SchematicPolyline>,
193    pub buses: Vec<SchematicPolyline>,
194    pub bus_entries: Vec<SchematicBusEntry>,
195    pub junctions: Vec<SchematicJunction>,
196    pub no_connects: Vec<SchematicNoConnect>,
197    pub labels: Vec<SchematicLabel>,
198    pub connectivity: SchematicConnectivity,
199}
200
201pub(crate) fn parse_source_carriers(
202    source: &str,
203    source_path: &str,
204    spans: &[FormSpan],
205) -> Result<SchematicSourceCarriers, SourceBundleError> {
206    let _carrier_count = spans
207        .iter()
208        .filter(|span| span.depth == 1 && is_carrier(span.head.as_deref()))
209        .count();
210    let mut carriers = SchematicSourceCarriers::default();
211    for span in spans
212        .iter()
213        .filter(|span| span.depth == 1 && is_carrier(span.head.as_deref()))
214    {
215        parse_carrier(&mut carriers, source, span, source_path)?;
216    }
217    carriers.connectivity = build_connectivity(&carriers, source_path)?;
218    Ok(carriers)
219}
220
221/// Import-only recovery of typed wire/junction content failures. Structural
222/// scanning has already validated the complete document; other carrier kinds
223/// and connectivity/invariant failures retain the strict error boundary.
224pub(crate) fn parse_source_carriers_for_import(
225    source: &str,
226    source_path: &str,
227    spans: &[FormSpan],
228) -> Result<(SchematicSourceCarriers, Vec<crate::SchematicCarrierIssue>), SourceBundleError> {
229    use crate::{SchematicCarrierIssue, SchematicCarrierIssueKind};
230    let mut carriers = SchematicSourceCarriers::default();
231    let mut issues = Vec::new();
232    let (mut wire_ordinal, mut junction_ordinal) = (0, 0);
233    for span in spans
234        .iter()
235        .filter(|s| s.depth == 1 && is_carrier(s.head.as_deref()))
236    {
237        // An invalid span is a programming failure, never a recoverable row.
238        span.text(source)
239            .map_err(|e| source_error(source_path, e.to_string()))?;
240        let kind_ordinal = match span.head.as_deref() {
241            Some("wire") => {
242                let ordinal = wire_ordinal;
243                wire_ordinal += 1;
244                Some((SchematicCarrierIssueKind::Wire, ordinal))
245            }
246            Some("junction") => {
247                let ordinal = junction_ordinal;
248                junction_ordinal += 1;
249                Some((SchematicCarrierIssueKind::Junction, ordinal))
250            }
251            _ => None,
252        };
253        if let Err(error) = parse_carrier(&mut carriers, source, span, source_path) {
254            if let Some((kind, ordinal)) =
255                kind_ordinal.filter(|_| error.kind == SourceBundleErrorKind::Schematic)
256            {
257                issues.push(SchematicCarrierIssue {
258                    kind,
259                    ordinal,
260                    source_range: span.range.clone(),
261                    error,
262                });
263            } else {
264                return Err(error);
265            }
266        }
267    }
268    carriers.connectivity = build_connectivity(&carriers, source_path)?;
269    Ok((carriers, issues))
270}
271
272pub(crate) fn parse_sheet_pin(
273    source: &str,
274    span: &FormSpan,
275    source_path: &str,
276) -> Result<SchematicSheetPin, SourceBundleError> {
277    let text = span
278        .text(source)
279        .map_err(|error| source_error(source_path, error.to_string()))?;
280    let spans = carrier_form_spans(text, &["pin", "at", "uuid"], source_path)?;
281    let root = spans
282        .iter()
283        .find(|selected| selected.depth == 0 && selected.head.as_deref() == Some("pin"))
284        .ok_or_else(|| source_error(source_path, "sheet pin root is missing"))?;
285    let values = direct_scalars(text, root, 2, source_path)?;
286    Ok(SchematicSheetPin {
287        name: values.first().cloned().unwrap_or_default(),
288        shape: SchematicPinShape::from_source(values.get(1).map(String::as_str)),
289        uuid: child_scalar(text, &spans, "uuid", source_path)?.unwrap_or_default(),
290        at: child_point(
291            text,
292            &spans,
293            "at",
294            SchematicPoint { x_iu: 0, y_iu: 0 },
295            source_path,
296        )?,
297    })
298}
299
300fn parse_carrier(
301    carriers: &mut SchematicSourceCarriers,
302    source: &str,
303    span: &FormSpan,
304    source_path: &str,
305) -> Result<(), SourceBundleError> {
306    let text = span
307        .text(source)
308        .map_err(|error| source_error(source_path, error.to_string()))?;
309    match span.head.as_deref() {
310        Some("wire") => {
311            let value = parse_polyline(text, "wire", source_path)?;
312            carriers.wires.push(value);
313        }
314        Some("bus") => {
315            let value = parse_polyline(text, "bus", source_path)?;
316            carriers.buses.push(value);
317        }
318        Some("bus_entry") => {
319            carriers
320                .bus_entries
321                .push(parse_bus_entry(text, source_path)?);
322        }
323        Some("junction") => {
324            carriers
325                .junctions
326                .push(parse_point_marker(text, "junction", source_path)?);
327        }
328        Some("no_connect") => {
329            let marker = parse_point_marker(text, "no_connect", source_path)?;
330            carriers.no_connects.push(SchematicNoConnect {
331                uuid: marker.uuid,
332                at: marker.at,
333            });
334        }
335        Some(head @ ("label" | "global_label" | "hierarchical_label")) => {
336            carriers.labels.push(parse_label(text, head, source_path)?);
337        }
338        _ => {}
339    }
340    Ok(())
341}
342
343fn is_carrier(head: Option<&str>) -> bool {
344    matches!(
345        head,
346        Some(
347            "wire"
348                | "bus"
349                | "bus_entry"
350                | "junction"
351                | "no_connect"
352                | "label"
353                | "global_label"
354                | "hierarchical_label"
355        )
356    )
357}
358
359fn parse_polyline(
360    source: &str,
361    root_head: &str,
362    source_path: &str,
363) -> Result<SchematicPolyline, SourceBundleError> {
364    let spans = carrier_form_spans(source, &[root_head, "xy", "uuid"], source_path)?;
365    let mut points = Vec::new();
366    for span in spans
367        .iter()
368        .filter(|span| span.depth == 2 && span.head.as_deref() == Some("xy"))
369    {
370        points.push(parse_point(source, span, source_path)?);
371    }
372    Ok(SchematicPolyline {
373        uuid: child_scalar(source, &spans, "uuid", source_path)?.unwrap_or_default(),
374        points,
375    })
376}
377
378fn parse_bus_entry(
379    source: &str,
380    source_path: &str,
381) -> Result<SchematicBusEntry, SourceBundleError> {
382    let spans = carrier_form_spans(source, &["bus_entry", "at", "size", "uuid"], source_path)?;
383    let at = child_point(
384        source,
385        &spans,
386        "at",
387        SchematicPoint { x_iu: 0, y_iu: 0 },
388        source_path,
389    )?;
390    let size = child_point(
391        source,
392        &spans,
393        "size",
394        SchematicPoint {
395            x_iu: 25_400,
396            y_iu: 25_400,
397        },
398        source_path,
399    )?;
400    let value = SchematicBusEntry {
401        uuid: child_scalar(source, &spans, "uuid", source_path)?.unwrap_or_default(),
402        at,
403        size,
404    };
405    value.wire_end().ok_or_else(|| {
406        source_error(
407            source_path,
408            "bus-entry endpoint overflows the schematic grid",
409        )
410    })?;
411    Ok(value)
412}
413
414fn parse_point_marker(
415    source: &str,
416    root_head: &str,
417    source_path: &str,
418) -> Result<SchematicJunction, SourceBundleError> {
419    let spans = carrier_form_spans(source, &[root_head, "at", "uuid"], source_path)?;
420    Ok(SchematicJunction {
421        uuid: child_scalar(source, &spans, "uuid", source_path)?.unwrap_or_default(),
422        at: child_point(
423            source,
424            &spans,
425            "at",
426            SchematicPoint { x_iu: 0, y_iu: 0 },
427            source_path,
428        )?,
429    })
430}
431
432fn parse_label(
433    source: &str,
434    root_head: &str,
435    source_path: &str,
436) -> Result<SchematicLabel, SourceBundleError> {
437    let spans = carrier_form_spans(source, &[root_head, "at", "shape", "uuid"], source_path)?;
438    let root = spans
439        .iter()
440        .find(|span| span.depth == 0 && span.head.as_deref() == Some(root_head))
441        .ok_or_else(|| source_error(source_path, "schematic label root is missing"))?;
442    let text = direct_scalars(source, root, 1, source_path)?
443        .into_iter()
444        .next()
445        .unwrap_or_default();
446    let scope = match root_head {
447        "label" => SchematicLabelScope::Local,
448        "global_label" => SchematicLabelScope::Global,
449        "hierarchical_label" => SchematicLabelScope::Hierarchical,
450        _ => unreachable!("caller restricts label heads"),
451    };
452    Ok(SchematicLabel {
453        scope,
454        text,
455        shape: child_scalar(source, &spans, "shape", source_path)?.unwrap_or_else(|| {
456            if scope == SchematicLabelScope::Local {
457                String::new()
458            } else {
459                "input".to_owned()
460            }
461        }),
462        uuid: child_scalar(source, &spans, "uuid", source_path)?.unwrap_or_default(),
463        at: child_point(
464            source,
465            &spans,
466            "at",
467            SchematicPoint { x_iu: 0, y_iu: 0 },
468            source_path,
469        )?,
470    })
471}
472
473fn carrier_form_spans(
474    source: &str,
475    heads: &[&str],
476    source_path: &str,
477) -> Result<Vec<FormSpan>, SourceBundleError> {
478    scan_form_spans(
479        source,
480        &Selector {
481            heads: Some(
482                heads
483                    .iter()
484                    .map(|head| (*head).to_owned())
485                    .collect::<BTreeSet<_>>(),
486            ),
487            min_depth: Some(0),
488            max_depth: Some(2),
489            ..Selector::default()
490        },
491    )
492    .map_err(|error| source_error(source_path, error.to_string()))
493}
494
495fn child_point(
496    source: &str,
497    spans: &[FormSpan],
498    head: &str,
499    default: SchematicPoint,
500    source_path: &str,
501) -> Result<SchematicPoint, SourceBundleError> {
502    spans
503        .iter()
504        .find(|span| span.depth == 1 && span.head.as_deref() == Some(head))
505        .map_or(Ok(default), |span| parse_point(source, span, source_path))
506}
507
508fn child_scalar(
509    source: &str,
510    spans: &[FormSpan],
511    head: &str,
512    source_path: &str,
513) -> Result<Option<String>, SourceBundleError> {
514    spans
515        .iter()
516        .find(|span| span.depth == 1 && span.head.as_deref() == Some(head))
517        .map(|span| direct_scalars(source, span, 1, source_path))
518        .transpose()
519        .map(|values| values.and_then(|mut values| values.pop()))
520}
521
522fn parse_point(
523    source: &str,
524    span: &FormSpan,
525    source_path: &str,
526) -> Result<SchematicPoint, SourceBundleError> {
527    // `(at X Y ANGLE)` carries a third direct scalar; connectivity consumes X/Y.
528    let values = direct_scalars(source, span, 3, source_path)?;
529    if values.len() < 2 {
530        return Err(source_error(
531            source_path,
532            "schematic point requires X and Y coordinates",
533        ));
534    }
535    Ok(SchematicPoint {
536        x_iu: parse_iu(&values[0], source_path)?,
537        y_iu: parse_iu(&values[1], source_path)?,
538    })
539}
540
541pub(crate) fn parse_iu(value: &str, source_path: &str) -> Result<i64, SourceBundleError> {
542    let decimal = parse_decimal(value).ok_or_else(|| {
543        source_error(
544            source_path,
545            format!("invalid schematic coordinate {value:?}"),
546        )
547    })?;
548    scaled_decimal_to_i64(&decimal).ok_or_else(|| {
549        source_error(
550            source_path,
551            "schematic coordinate is outside the internal-unit range",
552        )
553    })
554}
555
556struct DecimalParts {
557    negative: bool,
558    digits: Vec<u8>,
559    scale_shift: i64,
560}
561
562fn parse_decimal(value: &str) -> Option<DecimalParts> {
563    let (negative, unsigned) = match value.as_bytes().first() {
564        Some(b'-') => (true, &value[1..]),
565        Some(b'+') => (false, &value[1..]),
566        _ => (false, value),
567    };
568    let exponent_at = unsigned.find(['e', 'E']);
569    let (mantissa, exponent_text) = exponent_at.map_or((unsigned, None), |index| {
570        (&unsigned[..index], Some(&unsigned[index + 1..]))
571    });
572    let exponent = exponent_text.map_or(Some(0), parse_exponent)?;
573    let mut digits = Vec::with_capacity(mantissa.len());
574    let mut decimal_seen = false;
575    let mut fractional_digits = 0_usize;
576    for byte in mantissa.bytes() {
577        match byte {
578            b'0'..=b'9' => {
579                digits.push(byte);
580                fractional_digits += usize::from(decimal_seen);
581            }
582            b'.' if !decimal_seen => decimal_seen = true,
583            _ => return None,
584        }
585    }
586    if digits.is_empty()
587        || unsigned[exponent_at.unwrap_or(unsigned.len())..]
588            .matches(['e', 'E'])
589            .count()
590            > 1
591    {
592        return None;
593    }
594    let first_nonzero = digits.iter().position(|digit| *digit != b'0');
595    let digits = first_nonzero.map_or_else(Vec::new, |index| digits.split_off(index));
596    let fraction = i64::try_from(fractional_digits).unwrap_or(i64::MAX);
597    Some(DecimalParts {
598        negative,
599        digits,
600        scale_shift: exponent.saturating_sub(fraction).saturating_add(4),
601    })
602}
603
604fn parse_exponent(value: &str) -> Option<i64> {
605    let (negative, digits) = match value.as_bytes().first() {
606        Some(b'-') => (true, &value[1..]),
607        Some(b'+') => (false, &value[1..]),
608        _ => (false, value),
609    };
610    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
611        return None;
612    }
613    let magnitude = digits.bytes().fold(0_i64, |current, byte| {
614        current
615            .saturating_mul(10)
616            .saturating_add(i64::from(byte - b'0'))
617    });
618    Some(if negative { -magnitude } else { magnitude })
619}
620
621fn scaled_decimal_to_i64(decimal: &DecimalParts) -> Option<i64> {
622    if decimal.digits.is_empty() {
623        return Some(0);
624    }
625    let magnitude = if decimal.scale_shift >= 0 {
626        scaled_integer_magnitude(&decimal.digits, decimal.scale_shift)?
627    } else {
628        rounded_fractional_magnitude(&decimal.digits, decimal.scale_shift)?
629    };
630    signed_magnitude(magnitude, decimal.negative)
631}
632
633fn scaled_integer_magnitude(digits: &[u8], shift: i64) -> Option<u64> {
634    let shift = usize::try_from(shift).ok()?;
635    if digits.len().checked_add(shift)? > 19 {
636        return None;
637    }
638    let mut magnitude = parse_digit_magnitude(digits)?;
639    for _ in 0..shift {
640        magnitude = magnitude.checked_mul(10)?;
641    }
642    Some(magnitude)
643}
644
645fn rounded_fractional_magnitude(digits: &[u8], shift: i64) -> Option<u64> {
646    let discarded = usize::try_from(shift.unsigned_abs()).ok()?;
647    if discarded > digits.len() {
648        return Some(0);
649    }
650    let retained = digits.len() - discarded;
651    let mut magnitude = parse_digit_magnitude(&digits[..retained])?;
652    if should_round_up(&digits[retained..], magnitude) {
653        magnitude = magnitude.checked_add(1)?;
654    }
655    Some(magnitude)
656}
657
658fn parse_digit_magnitude(digits: &[u8]) -> Option<u64> {
659    digits.iter().try_fold(0_u64, |current, digit| {
660        current
661            .checked_mul(10)?
662            .checked_add(u64::from(*digit - b'0'))
663    })
664}
665
666fn should_round_up(discarded: &[u8], retained: u64) -> bool {
667    match discarded.first() {
668        Some(b'6'..=b'9') => true,
669        Some(b'5') => discarded[1..].iter().any(|digit| *digit != b'0') || retained % 2 == 1,
670        _ => false,
671    }
672}
673
674fn signed_magnitude(magnitude: u64, negative: bool) -> Option<i64> {
675    if negative {
676        if magnitude == i64::MAX as u64 + 1 {
677            Some(i64::MIN)
678        } else {
679            i64::try_from(magnitude).ok().map(|value| -value)
680        }
681    } else {
682        i64::try_from(magnitude).ok()
683    }
684}
685
686pub(crate) fn direct_scalars(
687    source: &str,
688    span: &FormSpan,
689    _maximum: usize,
690    source_path: &str,
691) -> Result<Vec<String>, SourceBundleError> {
692    let text = span
693        .text(source)
694        .map_err(|error| source_error(source_path, error.to_string()))?;
695    let mut lexer = Lexer::new(text);
696    require_header(&mut lexer, source_path)?;
697    let mut depth = 1_usize;
698    let mut values = Vec::new();
699    for token in lexer {
700        let token = token.map_err(|error| source_error(source_path, error.to_string()))?;
701        match token.kind {
702            TokenKind::Left => depth = depth.saturating_add(1),
703            TokenKind::Right => {
704                depth = depth.saturating_sub(1);
705                if depth == 0 {
706                    break;
707                }
708            }
709            _ if depth == 1 => {
710                let decoded = decoded(token);
711                values.push(decoded.into_owned());
712            }
713            _ => {}
714        }
715    }
716    Ok(values)
717}
718
719fn require_header(lexer: &mut Lexer<'_>, source_path: &str) -> Result<(), SourceBundleError> {
720    let left = next_token(lexer, source_path)?;
721    let head = next_token(lexer, source_path)?;
722    if left.kind == TokenKind::Left && head.kind == TokenKind::Atom {
723        Ok(())
724    } else {
725        Err(source_error(
726            source_path,
727            "selected schematic form has an invalid header",
728        ))
729    }
730}
731
732fn next_token<'a>(
733    lexer: &mut Lexer<'a>,
734    source_path: &str,
735) -> Result<Token<'a>, SourceBundleError> {
736    lexer
737        .next()
738        .transpose()
739        .map_err(|error| source_error(source_path, error.to_string()))?
740        .ok_or_else(|| {
741            source_error(
742                source_path,
743                "selected schematic form ended before its header",
744            )
745        })
746}
747
748fn decoded(token: Token<'_>) -> Cow<'_, str> {
749    if token.kind == TokenKind::QuotedString {
750        Cow::Owned(decode_quoted(token.lexeme))
751    } else {
752        Cow::Borrowed(token.lexeme)
753    }
754}
755
756fn build_connectivity(
757    carriers: &SchematicSourceCarriers,
758    source_path: &str,
759) -> Result<SchematicConnectivity, SourceBundleError> {
760    rebuild_connectivity(
761        &carriers.wires,
762        &carriers.buses,
763        &carriers.bus_entries,
764        &carriers.junctions,
765        source_path,
766    )
767}
768
769pub(crate) fn rebuild_connectivity(
770    wires: &[SchematicPolyline],
771    buses: &[SchematicPolyline],
772    entries: &[SchematicBusEntry],
773    junctions: &[SchematicJunction],
774    source_path: &str,
775) -> Result<SchematicConnectivity, SourceBundleError> {
776    let mut union = PointUnion::default();
777    for wire in wires {
778        union.add_polyline(&wire.points);
779    }
780    for bus in buses {
781        for point in &bus.points {
782            union.add(*point);
783        }
784    }
785    for entry in entries {
786        union.add(entry.at);
787        union.add(entry.wire_end().ok_or_else(|| {
788            source_error(
789                source_path,
790                "bus-entry endpoint overflows the schematic grid",
791            )
792        })?);
793    }
794    for junction in junctions {
795        union.add(junction.at);
796    }
797    Ok(union.finish())
798}
799
800#[derive(Default)]
801struct PointUnion {
802    index_by_point: HashMap<SchematicPoint, usize>,
803    points: Vec<SchematicPoint>,
804    parent: Vec<usize>,
805    rank: Vec<u8>,
806}
807
808impl PointUnion {
809    fn add(&mut self, point: SchematicPoint) -> usize {
810        if let Some(index) = self.index_by_point.get(&point) {
811            return *index;
812        }
813        let index = self.points.len();
814        self.index_by_point.insert(point, index);
815        self.points.push(point);
816        self.parent.push(index);
817        self.rank.push(0);
818        index
819    }
820
821    fn add_polyline(&mut self, points: &[SchematicPoint]) {
822        let mut previous = None;
823        for point in points {
824            let current = self.add(*point);
825            if let Some(previous) = previous
826                && previous != current
827            {
828                self.union(previous, current);
829            }
830            previous = Some(current);
831        }
832    }
833
834    fn root(&mut self, index: usize) -> usize {
835        let mut root = index;
836        while self.parent[root] != root {
837            root = self.parent[root];
838        }
839        let mut current = index;
840        while self.parent[current] != root {
841            let next = self.parent[current];
842            self.parent[current] = root;
843            current = next;
844        }
845        root
846    }
847
848    fn union(&mut self, left: usize, right: usize) {
849        let mut left_root = self.root(left);
850        let mut right_root = self.root(right);
851        if left_root == right_root {
852            return;
853        }
854        if self.rank[left_root] < self.rank[right_root] {
855            std::mem::swap(&mut left_root, &mut right_root);
856        }
857        self.parent[right_root] = left_root;
858        if self.rank[left_root] == self.rank[right_root] {
859            self.rank[left_root] = self.rank[left_root].saturating_add(1);
860        }
861    }
862
863    fn finish(mut self) -> SchematicConnectivity {
864        let mut grouped = BTreeMap::<usize, Vec<SchematicPoint>>::new();
865        for index in 0..self.points.len() {
866            let root = self.root(index);
867            grouped.entry(root).or_default().push(self.points[index]);
868        }
869        let mut components = grouped.into_values().collect::<Vec<_>>();
870        for component in &mut components {
871            component.sort_unstable();
872        }
873        components.sort_unstable();
874        let mut component_by_point = BTreeMap::new();
875        for (component_index, component) in components.iter().enumerate() {
876            for point in component {
877                component_by_point.insert(*point, component_index);
878            }
879        }
880        let points = component_by_point.keys().copied().collect();
881        SchematicConnectivity {
882            points,
883            components,
884            component_by_point,
885        }
886    }
887}
888
889fn source_error(source_path: &str, message: impl Into<String>) -> SourceBundleError {
890    SourceBundleError::new(SourceBundleErrorKind::Schematic, Some(source_path), message)
891}
892
893fn limit_error(source_path: &str, message: impl Into<String>) -> SourceBundleError {
894    SourceBundleError::new(
895        SourceBundleErrorKind::ResourceLimit,
896        Some(source_path),
897        message,
898    )
899}
900
901#[cfg(test)]
902mod tests;