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

kicad_monkey_core/
schematic_connection_source.rs

1//! Checked, borrowed scalar-wire and junction facts from exact authored rows.
2//! These facts do not establish electrical contact or resolve drawing defaults.
3use crate::schematic_segment_index::{SchematicSegment, SchematicSegmentIndex};
4use crate::schematic_source::parse_iu;
5use crate::sexpr::{Lexer, Token, TokenKind, decode_quoted};
6use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
7use crate::{KiCadColor, SchematicDocument, SchematicPoint, SchematicSourceForm};
8use crate::{SourceBundleError, SourceBundleErrorKind};
9use std::collections::BTreeSet;
10use std::ops::Range;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum SchematicCarrierIssueKind {
14    Wire,
15    Junction,
16}
17
18/// One original wire/junction row omitted by import-only compact projection.
19/// Its original ordinal is not an index into the retained compact subset.
20#[derive(Clone, Debug, Eq, PartialEq)]
21pub struct SchematicCarrierIssue {
22    pub kind: SchematicCarrierIssueKind,
23    pub ordinal: usize,
24    pub source_range: Range<usize>,
25    pub error: SourceBundleError,
26}
27
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum SchematicWireLineStyle {
30    Default,
31    Solid,
32    Dash,
33    Dot,
34    DashDot,
35    DashDotDot,
36}
37
38/// Raw native settings. Missing, zero and negative widths remain distinct;
39/// interpreting defaults is the consumer's separate source-qualified decision.
40#[derive(Clone, Debug, PartialEq)]
41pub struct SchematicWireStroke {
42    pub width_iu: Option<i64>,
43    pub style: Option<SchematicWireLineStyle>,
44    pub color: Option<KiCadColor>,
45}
46
47#[derive(Clone, Debug)]
48pub struct SchematicWireRecord<'a> {
49    pub form: SchematicSourceForm<'a>,
50    pub uuid: Result<Option<String>, SourceBundleError>,
51    pub points: Result<[SchematicPoint; 2], SourceBundleError>,
52    pub stroke: Result<Option<SchematicWireStroke>, SourceBundleError>,
53}
54
55#[derive(Clone, Debug)]
56pub struct SchematicJunctionRecord<'a> {
57    pub form: SchematicSourceForm<'a>,
58    pub uuid: Result<Option<String>, SourceBundleError>,
59    pub at: Result<SchematicPoint, SourceBundleError>,
60    pub diameter_iu: Result<Option<i64>, SourceBundleError>,
61    pub color: Result<Option<KiCadColor>, SourceBundleError>,
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub enum SchematicWireGeometryOmissionReason {
66    Malformed(SourceBundleError),
67    ZeroLength,
68}
69
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct SchematicWireGeometryOmission {
72    pub ordinal: usize,
73    pub reason: SchematicWireGeometryOmissionReason,
74}
75
76/// Exact geometric containment over a selected original-row subset. Neither
77/// this index nor a successful query grants electrical-contact authority.
78#[derive(Debug)]
79pub struct SchematicWireGeometryIndex {
80    index: SchematicSegmentIndex,
81    omissions: Vec<SchematicWireGeometryOmission>,
82}
83
84impl SchematicWireGeometryIndex {
85    pub fn omissions(&self) -> &[SchematicWireGeometryOmission] {
86        &self.omissions
87    }
88
89    /// Original wire ordinals in source order. Uses the existing Source exact
90    /// integer segment predicate, including its checked-overflow errors.
91    pub fn containing(&self, point: SchematicPoint) -> Result<Vec<usize>, SourceBundleError> {
92        let mut ordinals = Vec::new();
93        self.index.for_each_containing(point, |segment| {
94            ordinals.push(segment.ordinal);
95            true
96        })?;
97        ordinals.sort_unstable();
98        Ok(ordinals)
99    }
100}
101
102/// One structural scan; each query checks only its original row. Ordinals are
103/// per kind, include malformed rows, and never stand in for an authored UUID.
104#[derive(Debug)]
105pub struct SchematicConnectionSourceView<'a> {
106    source: &'a str,
107    path: &'a str,
108    wires: Vec<FormSpan>,
109    junctions: Vec<FormSpan>,
110}
111
112impl SchematicDocument {
113    pub fn connection_sources(
114        &self,
115    ) -> Result<SchematicConnectionSourceView<'_>, SourceBundleError> {
116        SchematicConnectionSourceView::new(self.source(), self.source_path())
117    }
118}
119
120impl<'a> SchematicConnectionSourceView<'a> {
121    pub(crate) fn source_path(&self) -> &str {
122        self.path
123    }
124    pub(crate) fn new(source: &'a str, path: &'a str) -> Result<Self, SourceBundleError> {
125        let spans = scan_form_spans(
126            source,
127            &Selector {
128                heads: Some(BTreeSet::from(["wire".into(), "junction".into()])),
129                min_depth: Some(1),
130                max_depth: Some(1),
131                ..Selector::default()
132            },
133        )
134        .map_err(|e| failure(path, e))?;
135        let (wires, junctions) = spans
136            .into_iter()
137            .partition(|s| s.head.as_deref() == Some("wire"));
138        Ok(Self {
139            source,
140            path,
141            wires,
142            junctions,
143        })
144    }
145
146    pub fn wire_count(&self) -> usize {
147        self.wires.len()
148    }
149    pub fn junction_count(&self) -> usize {
150        self.junctions.len()
151    }
152
153    /// Borrow an indexed original form without invoking its eager fact readers.
154    /// Focused consumers can enforce their invocation budget before those reads.
155    pub(crate) fn wire_source_form(&self, ordinal: usize) -> Option<SchematicSourceForm<'a>> {
156        Some(self.form(self.wires.get(ordinal)?, ordinal))
157    }
158
159    pub(crate) fn junction_source_form(&self, ordinal: usize) -> Option<SchematicSourceForm<'a>> {
160        Some(self.form(self.junctions.get(ordinal)?, ordinal))
161    }
162
163    /// Index only caller-selected original wire ordinals, for example after
164    /// model-coordinate representability checks. Unknown/repeated selectors
165    /// are caller contract errors; selected malformed/zero rows are omissions.
166    pub fn wire_geometry_index(
167        &self,
168        original_ordinals: &[usize],
169    ) -> Result<SchematicWireGeometryIndex, SourceBundleError> {
170        let mut selected = BTreeSet::new();
171        for ordinal in original_ordinals {
172            if *ordinal >= self.wires.len() || !selected.insert(*ordinal) {
173                return Err(SourceBundleError::new(
174                    SourceBundleErrorKind::Contract,
175                    Some(self.path),
176                    format!("wire geometry selector {ordinal} is foreign or repeated"),
177                ));
178            }
179        }
180        let mut segments = Vec::new();
181        let mut omissions = Vec::new();
182        for ordinal in selected {
183            let span = &self.wires[ordinal];
184            match wire_points(&self.source[span.range.clone()], self.path) {
185                Ok([a, b]) => match SchematicSegment::new(a, b, ordinal) {
186                    Some(segment) => segments.push(segment),
187                    None => omissions.push(SchematicWireGeometryOmission {
188                        ordinal,
189                        reason: SchematicWireGeometryOmissionReason::ZeroLength,
190                    }),
191                },
192                Err(error) => omissions.push(SchematicWireGeometryOmission {
193                    ordinal,
194                    reason: SchematicWireGeometryOmissionReason::Malformed(error),
195                }),
196            }
197        }
198        Ok(SchematicWireGeometryIndex {
199            index: SchematicSegmentIndex::build(segments, self.path)?,
200            omissions,
201        })
202    }
203
204    pub fn wire(&self, ordinal: usize) -> Option<SchematicWireRecord<'a>> {
205        let form = self.form(self.wires.get(ordinal)?, ordinal);
206        Some(SchematicWireRecord {
207            uuid: optional_uuid(form.source, self.path),
208            points: wire_points(form.source, self.path),
209            stroke: stroke(form.source, self.path),
210            form,
211        })
212    }
213
214    pub fn junction(&self, ordinal: usize) -> Option<SchematicJunctionRecord<'a>> {
215        let form = self.form(self.junctions.get(ordinal)?, ordinal);
216        Some(SchematicJunctionRecord {
217            uuid: optional_uuid(form.source, self.path),
218            at: selected(form.source, "at", self.path).and_then(|at| {
219                point(
220                    at.ok_or_else(|| failure(self.path, "junction is missing at"))?,
221                    self.path,
222                )
223            }),
224            diameter_iu: optional_number(form.source, "diameter", self.path),
225            color: optional_color(form.source, self.path),
226            form,
227        })
228    }
229
230    fn form(&self, span: &FormSpan, ordinal: usize) -> SchematicSourceForm<'a> {
231        SchematicSourceForm {
232            ordinal,
233            source_range: span.range.clone(),
234            source: &self.source[span.range.clone()],
235        }
236    }
237}
238
239fn failure(path: &str, message: impl std::fmt::Display) -> SourceBundleError {
240    SourceBundleError::new(
241        SourceBundleErrorKind::Schematic,
242        Some(path),
243        message.to_string(),
244    )
245}
246
247fn children(source: &str, path: &str) -> Result<Vec<FormSpan>, SourceBundleError> {
248    scan_form_spans(
249        source,
250        &Selector {
251            min_depth: Some(1),
252            max_depth: Some(1),
253            ..Selector::default()
254        },
255    )
256    .map_err(|e| failure(path, e))
257}
258
259pub(crate) fn selected<'a>(
260    source: &'a str,
261    key: &str,
262    path: &str,
263) -> Result<Option<&'a str>, SourceBundleError> {
264    Ok(selected_range(source, key, path)?.map(|range| &source[range]))
265}
266
267pub(crate) fn selected_range(
268    source: &str,
269    key: &str,
270    path: &str,
271) -> Result<Option<Range<usize>>, SourceBundleError> {
272    let mut selected = None;
273    for span in children(source, path)?
274        .into_iter()
275        .filter(|s| s.head.as_deref() == Some(key))
276    {
277        if selected.is_some() {
278            return Err(failure(path, format!("duplicate {key} form")));
279        }
280        selected = Some(span.range);
281    }
282    Ok(selected)
283}
284
285/// Exactly N direct scalars: nested forms and surplus values cannot slide into
286/// a valid shape by being ignored during projection.
287pub(crate) fn scalars<'a>(
288    source: &'a str,
289    count: usize,
290    path: &str,
291) -> Result<Vec<Token<'a>>, SourceBundleError> {
292    let mut lexer = Lexer::new(source);
293    let mut next = || {
294        lexer
295            .next()
296            .transpose()
297            .map_err(|e| failure(path, e))?
298            .ok_or_else(|| failure(path, "incomplete scalar form"))
299    };
300    if next()?.kind != TokenKind::Left || next()?.kind != TokenKind::Atom {
301        return Err(failure(path, "expected a named scalar form"));
302    }
303    let mut values = Vec::with_capacity(count);
304    for _ in 0..count {
305        let token = next()?;
306        if matches!(token.kind, TokenKind::Left | TokenKind::Right) {
307            return Err(failure(path, "expected direct scalar value"));
308        }
309        values.push(token);
310    }
311    if next()?.kind != TokenKind::Right {
312        return Err(failure(path, "unexpected extra scalar or nested form"));
313    }
314    if lexer
315        .next()
316        .transpose()
317        .map_err(|e| failure(path, e))?
318        .is_some()
319    {
320        return Err(failure(path, "unexpected trailing source"));
321    }
322    Ok(values)
323}
324
325fn text(token: &Token<'_>, path: &str) -> Result<String, SourceBundleError> {
326    match token.kind {
327        TokenKind::Atom => Ok(token.lexeme.to_owned()),
328        TokenKind::QuotedString => Ok(decode_quoted(token.lexeme)),
329        _ => Err(failure(path, "expected string or atom")),
330    }
331}
332
333fn number(token: &Token<'_>, path: &str) -> Result<i64, SourceBundleError> {
334    if !matches!(token.kind, TokenKind::Integer | TokenKind::Float) {
335        return Err(failure(path, "expected numeric coordinate"));
336    }
337    parse_iu(token.lexeme, path)
338}
339
340pub(crate) fn optional_uuid(source: &str, path: &str) -> Result<Option<String>, SourceBundleError> {
341    selected(source, "uuid", path)?
342        .map(|s| text(&scalars(s, 1, path)?[0], path))
343        .transpose()
344}
345
346fn optional_number(source: &str, key: &str, path: &str) -> Result<Option<i64>, SourceBundleError> {
347    selected(source, key, path)?
348        .map(|s| number(&scalars(s, 1, path)?[0], path))
349        .transpose()
350}
351
352fn point(source: &str, path: &str) -> Result<SchematicPoint, SourceBundleError> {
353    let values = scalars(source, 2, path)?;
354    Ok(SchematicPoint {
355        x_iu: number(&values[0], path)?,
356        y_iu: number(&values[1], path)?,
357    })
358}
359
360fn wire_points(source: &str, path: &str) -> Result<[SchematicPoint; 2], SourceBundleError> {
361    let points = wire_point_sources(source, path)?;
362    Ok([point(points[0], path)?, point(points[1], path)?])
363}
364
365pub(crate) fn wire_point_sources<'a>(
366    source: &'a str,
367    path: &str,
368) -> Result<[&'a str; 2], SourceBundleError> {
369    let pts = selected(source, "pts", path)?.ok_or_else(|| failure(path, "wire is missing pts"))?;
370    let points = children(pts, path)?;
371    if points.len() != 2 || points.iter().any(|s| s.head.as_deref() != Some("xy")) {
372        return Err(failure(path, "scalar wire requires exactly two xy forms"));
373    }
374    container(pts, path)?;
375    Ok([&pts[points[0].range.clone()], &pts[points[1].range.clone()]])
376}
377
378/// A named container accepts child forms, never a direct value after its head.
379fn container(source: &str, path: &str) -> Result<(), SourceBundleError> {
380    let mut lexer = Lexer::new(source);
381    let mut depth = 0usize;
382    let mut root_head = false;
383    while let Some(token) = lexer.next().transpose().map_err(|e| failure(path, e))? {
384        match token.kind {
385            TokenKind::Left => depth += 1,
386            TokenKind::Right => depth -= 1,
387            _ if depth == 1 && !root_head => root_head = true,
388            _ if depth == 1 => return Err(failure(path, "unexpected direct value in container")),
389            _ => {}
390        }
391    }
392    Ok(())
393}
394
395pub(crate) fn stroke(
396    source: &str,
397    path: &str,
398) -> Result<Option<SchematicWireStroke>, SourceBundleError> {
399    selected(source, "stroke", path)?
400        .map(|source| {
401            container(source, path)?;
402            let style = selected(source, "type", path)?
403                .map(|s| {
404                    let values = scalars(s, 1, path)?;
405                    Ok(match text(&values[0], path)?.as_str() {
406                        "default" => SchematicWireLineStyle::Default,
407                        "solid" => SchematicWireLineStyle::Solid,
408                        "dash" => SchematicWireLineStyle::Dash,
409                        "dot" => SchematicWireLineStyle::Dot,
410                        "dash_dot" => SchematicWireLineStyle::DashDot,
411                        "dash_dot_dot" => SchematicWireLineStyle::DashDotDot,
412                        other => {
413                            return Err(failure(
414                                path,
415                                format!("unsupported wire stroke type {other}"),
416                            ));
417                        }
418                    })
419                })
420                .transpose()?;
421            Ok(SchematicWireStroke {
422                width_iu: optional_number(source, "width", path)?,
423                style,
424                color: optional_color(source, path)?,
425            })
426        })
427        .transpose()
428}
429
430fn optional_color(source: &str, path: &str) -> Result<Option<KiCadColor>, SourceBundleError> {
431    selected(source, "color", path)?
432        .map(|s| {
433            let values = scalars(s, 4, path)?;
434            let channel = |token: &Token<'_>| {
435                if token.kind != TokenKind::Integer {
436                    return Err(failure(path, "color channel requires integer"));
437                }
438                token
439                    .lexeme
440                    .parse::<i64>()
441                    .ok()
442                    .filter(|n| (0..=255).contains(n))
443                    .ok_or_else(|| failure(path, "color channel outside 0..255"))
444            };
445            if !matches!(values[3].kind, TokenKind::Integer | TokenKind::Float) {
446                return Err(failure(path, "color alpha requires number"));
447            }
448            let alpha = values[3]
449                .lexeme
450                .parse::<f64>()
451                .ok()
452                .filter(|v| v.is_finite() && (0.0..=1.0).contains(v))
453                .ok_or_else(|| failure(path, "color alpha outside 0..1"))?;
454            Ok(KiCadColor {
455                red: channel(&values[0])?,
456                green: channel(&values[1])?,
457                blue: channel(&values[2])?,
458                alpha,
459            })
460        })
461        .transpose()
462}