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

kicad_monkey_core/
schematic_symbol_source.rs

1//! Borrowed, ordered schematic symbol source for import and inspection.
2//!
3//! These views select authored forms; they do not render, bind pins, pack units,
4//! discover libraries, or choose a named assembly variant. A record ordinal is
5//! its position among siblings of that record kind, never a fabricated native ID.
6use crate::schematic_bundle_indexes::{index_library_symbol_names, library_symbol_index_for_key};
7use crate::schematic_source::{direct_scalars, parse_iu};
8use crate::sexpr::{Lexer, Sexp, TokenKind, parse};
9use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
10use crate::text_metadata::parse_text_effects;
11use crate::{
12    KiCadTextEffects, SchematicDocument, SchematicPoint, SchematicSymbolPin, SourceBundleError,
13    SourceBundleErrorKind,
14};
15use std::collections::{BTreeSet, HashMap};
16use std::ops::Range;
17
18mod native_text_size;
19pub use native_text_size::{SchematicFieldNativeTextSize, SchematicFieldWithNativeTextSize};
20
21/// An exact source form, with its absolute byte range in the document.
22#[derive(Clone, Debug)]
23pub struct SchematicSourceForm<'a> {
24    pub ordinal: usize,
25    pub source_range: Range<usize>,
26    pub source: &'a str,
27}
28
29/// An embedded definition's exact authored name and source, before flattening.
30#[derive(Clone, Debug)]
31pub struct SchematicLibrarySource<'a> {
32    pub name: &'a str,
33    pub form: SchematicSourceForm<'a>,
34}
35
36/// Authored placed field facts. `at` is in native schematic internal units in
37/// the source's sheet frame; it is not transformed into an owner's local frame.
38/// Visibility reflects source hide flags; font size and private/editor behavior
39/// remain explicit facts for the consumer to interpret.
40#[derive(Clone, Debug, PartialEq)]
41pub struct SchematicPlacedField {
42    pub key: String,
43    pub value: String,
44    pub at: Option<SchematicPoint>,
45    pub angle_degrees: f64,
46    pub effects: Option<KiCadTextEffects>,
47    pub visible: bool,
48    pub private: bool,
49    pub show_name: bool,
50}
51
52/// Native readable field axes after the parent symbol's quarter-turn/mirror.
53/// Angles use KiCad's text convention: 0 is horizontal, 90 reads upward in
54/// sheet coordinates. Alignment flips describe the transformed box, not glyph
55/// reflection; native field glyphs remain unmirrored.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct SchematicFieldFrame {
58    pub angle_degrees: i16,
59    pub horizontal_flipped: bool,
60    pub vertical_flipped: bool,
61}
62
63impl SchematicPlacedField {
64    /// Geometry-only equivalent of SCH_FIELD::GetDrawRotation and its
65    /// transformed alignment vectors (`IsHorizJustifyFlipped`,
66    /// `IsVertJustifyFlipped`, KiCad 10.0.8). No font metrics, text
67    /// measurement, source-position rewrite or model-frame conversion occurs.
68    pub fn effective_frame(
69        &self,
70        symbol: &crate::SchematicPlacedSymbol,
71    ) -> Result<SchematicFieldFrame, SourceBundleError> {
72        let angle = symbol.angle_degrees.rem_euclid(360.);
73        if !angle.is_finite() || angle.rem_euclid(90.) != 0. {
74            return Err(failure("", "field parent requires a native quarter turn"));
75        }
76        let field_angle = self.angle_degrees.rem_euclid(360.);
77        if !field_angle.is_finite() || (field_angle != 0. && field_angle != 90.) {
78            return Err(failure(
79                "",
80                "field requires a native horizontal or vertical angle",
81            ));
82        }
83        let transform = |(x, y): (i8, i8)| -> Result<(i8, i8), SourceBundleError> {
84            // The symbol's TRANSFORM on sheet +Y-down vectors: the parser's
85            // rotation (`TRANSFORM(0, 1, -1, 0)` at 90; the identity at 0 in
86            // KiCad 9 and 10, whose symbols are +Y-down), then its mirror. The
87            // field rectangle is already a sheet one, so no library flip.
88            let (x, y) = match angle as i16 {
89                0 => (x, y),
90                90 => (y, -x),
91                180 => (-x, -y),
92                270 => (-y, x),
93                _ => unreachable!(),
94            };
95            Ok(match symbol.mirror.as_deref() {
96                None => (x, y),
97                Some("x") => (x, -y),
98                Some("y") => (-x, y),
99                Some(_) => return Err(failure("", "unsupported native field-parent mirror")),
100            })
101        };
102        // EDA_TEXT::GetTextBox starts with a native +Y-down rectangle;
103        // SCH_FIELD then applies RotatePoint(angle), clockwise numerically.
104        // These are that rectangle's baseline/up vectors before the parent
105        // transform, not the library pin frame used for symbol graphics.
106        let (baseline, up) = if field_angle == 0. {
107            ((1, 0), (0, -1))
108        } else {
109            ((0, -1), (-1, 0))
110        };
111        let vertical = (field_angle == 90.) != (angle == 90. || angle == 270.);
112        let (readable_baseline, readable_up) = if vertical {
113            ((0, -1), (-1, 0))
114        } else {
115            ((1, 0), (0, -1))
116        };
117        let opposite = |actual: (i8, i8), expected: (i8, i8)| {
118            actual.0 * expected.0 + actual.1 * expected.1 < 0
119        };
120        Ok(SchematicFieldFrame {
121            angle_degrees: if vertical { 90 } else { 0 },
122            horizontal_flipped: opposite(transform(baseline)?, readable_baseline),
123            vertical_flipped: opposite(transform(up)?, readable_up),
124        })
125    }
126}
127
128/// One field result. Malformed display data does not discard adjacent fields.
129#[derive(Clone, Debug)]
130pub struct SchematicFieldRecord {
131    pub ordinal: usize,
132    pub source_range: Range<usize>,
133    pub field: Result<SchematicPlacedField, SourceBundleError>,
134}
135
136/// One raw placed pin record, never collapsed by number, UUID, unit or style.
137/// Matching these records to library pins is a separate checked operation.
138#[derive(Clone, Debug)]
139pub struct SchematicPinRecord {
140    pub ordinal: usize,
141    pub source_range: Range<usize>,
142    /// Independently checked authored UUID. A bad number or alternate does not
143    /// erase this fact. Absent and authored empty spelling remain distinct.
144    pub uuid: Result<Option<String>, SourceBundleError>,
145    /// Independently checked authored number selector; no empty fallback is
146    /// fabricated for an absent or malformed number.
147    pub number: Result<Option<String>, SourceBundleError>,
148    pub pin: Result<SchematicSymbolPin, SourceBundleError>,
149}
150
151/// A single structural scan over the document. Queries parse only selected
152/// records, so asking for many placements does not reparse the whole document.
153#[derive(Debug)]
154pub struct SchematicSymbolSourceView<'a> {
155    source: &'a str,
156    path: &'a str,
157    placed: Vec<FormSpan>,
158    library: Vec<FormSpan>,
159    names: Vec<String>,
160    library_index: HashMap<String, usize>,
161}
162
163impl SchematicDocument {
164    pub fn symbol_sources(&self) -> Result<SchematicSymbolSourceView<'_>, SourceBundleError> {
165        SchematicSymbolSourceView::new(self.source(), self.source_path())
166    }
167}
168
169impl<'a> SchematicSymbolSourceView<'a> {
170    pub(crate) fn source_path(&self) -> &str {
171        self.path
172    }
173    fn new(source: &'a str, path: &'a str) -> Result<Self, SourceBundleError> {
174        let spans = scan_form_spans(
175            source,
176            &Selector {
177                heads: Some(BTreeSet::from(["symbol".into()])),
178                min_depth: Some(1),
179                max_depth: Some(2),
180                ..Selector::default()
181            },
182        )
183        .map_err(|error| failure(path, error))?;
184        let mut placed = Vec::new();
185        let mut library = Vec::new();
186        let mut names = Vec::new();
187        for span in spans {
188            if span.path == ["kicad_sch", "symbol"] {
189                placed.push(span);
190            } else if span.path == ["kicad_sch", "lib_symbols", "symbol"] {
191                names.push(
192                    direct_scalars(source, &span, 1, path)?
193                        .into_iter()
194                        .next()
195                        .unwrap_or_default(),
196                );
197                library.push(span);
198            }
199        }
200        let library_index = index_library_symbol_names(
201            &names.iter().map(String::as_str).collect::<Vec<_>>(),
202            path,
203        )?;
204        Ok(Self {
205            source,
206            path,
207            placed,
208            library,
209            names,
210            library_index,
211        })
212    }
213
214    pub fn placed_count(&self) -> usize {
215        self.placed.len()
216    }
217    pub fn library_count(&self) -> usize {
218        self.library.len()
219    }
220
221    pub fn placed_symbol_source(&self, ordinal: usize) -> Option<SchematicSourceForm<'a>> {
222        self.placed
223            .get(ordinal)
224            .map(|span| self.form(ordinal, span))
225    }
226
227    pub fn library_symbol_source(&self, ordinal: usize) -> Option<SchematicLibrarySource<'_>> {
228        Some(SchematicLibrarySource {
229            name: self.names.get(ordinal)?,
230            form: self.form(ordinal, self.library.get(ordinal)?),
231        })
232    }
233
234    /// Existing source lookup, including inheritance: exact authored names
235    /// precede basename aliases, with the first exact source row retained.
236    pub fn library_symbol_source_for_key(&self, key: &str) -> Option<SchematicLibrarySource<'_>> {
237        let index = library_symbol_index_for_key(&self.library_index, key)?;
238        self.library_symbol_source(index)
239    }
240
241    /// Select the actual embedded source: lib_name override first, then lib_id;
242    /// exact full keys precede basename fallback. No external library is opened.
243    pub fn selected_library_symbol_source(
244        &self,
245        placed_ordinal: usize,
246    ) -> Result<Option<SchematicLibrarySource<'_>>, SourceBundleError> {
247        let Some(placed) = self.placed_symbol_source(placed_ordinal) else {
248            return Ok(None);
249        };
250        let spans = children(placed.source, &["lib_name", "lib_id"], self.path)?;
251        for key in ["lib_name", "lib_id"] {
252            let mut selected = spans
253                .iter()
254                .filter(|span| span.head.as_deref() == Some(key));
255            if let Some(span) = selected.next() {
256                if selected.next().is_some() {
257                    return Err(failure(
258                        self.path,
259                        format!("placed symbol {key} is ambiguous"),
260                    ));
261                }
262                let value = library_key(placed.source, span, key, self.path)?;
263                if let Some(source) = self.library_symbol_source_for_key(&value) {
264                    return Ok(Some(source));
265                }
266            }
267        }
268        Ok(None)
269    }
270
271    pub fn placed_fields(
272        &self,
273        placed_ordinal: usize,
274    ) -> Result<Vec<SchematicFieldRecord>, SourceBundleError> {
275        let Some(placed) = self.placed_symbol_source(placed_ordinal) else {
276            return Ok(Vec::new());
277        };
278        Ok(children(placed.source, &["property"], self.path)?
279            .into_iter()
280            .enumerate()
281            .map(|(ordinal, span)| {
282                let source_range = (placed.source_range.start + span.range.start)
283                    ..(placed.source_range.start + span.range.end);
284                let field = parse_field(&placed.source[span.range], source_range.start, self.path);
285                SchematicFieldRecord {
286                    ordinal,
287                    source_range,
288                    field,
289                }
290            })
291            .collect())
292    }
293
294    pub fn placed_pins(
295        &self,
296        placed_ordinal: usize,
297    ) -> Result<Vec<SchematicPinRecord>, SourceBundleError> {
298        let Some(placed) = self.placed_symbol_source(placed_ordinal) else {
299            return Ok(Vec::new());
300        };
301        Ok(children(placed.source, &["pin"], self.path)?
302            .into_iter()
303            .enumerate()
304            .map(|(ordinal, span)| {
305                let source_range = (placed.source_range.start + span.range.start)
306                    ..(placed.source_range.start + span.range.end);
307                let form =
308                    parse(&placed.source[span.range]).map_err(|error| failure(self.path, error));
309                let uuid = form
310                    .as_ref()
311                    .map_err(Clone::clone)
312                    .and_then(|form| pin_scalar(form, "uuid", self.path));
313                let number = form
314                    .as_ref()
315                    .map_err(Clone::clone)
316                    .and_then(|form| pin_number(form, self.path));
317                let pin = form
318                    .as_ref()
319                    .map_err(Clone::clone)
320                    .and_then(|form| parse_pin(form, self.path));
321                SchematicPinRecord {
322                    ordinal,
323                    source_range,
324                    uuid,
325                    number,
326                    pin,
327                }
328            })
329            .collect())
330    }
331
332    fn form(&self, ordinal: usize, span: &FormSpan) -> SchematicSourceForm<'a> {
333        SchematicSourceForm {
334            ordinal,
335            source_range: span.range.clone(),
336            source: &self.source[span.range.clone()],
337        }
338    }
339}
340
341fn children(source: &str, heads: &[&str], path: &str) -> Result<Vec<FormSpan>, SourceBundleError> {
342    children_with_error(source, heads, path, failure)
343}
344
345fn children_with_error(
346    source: &str,
347    heads: &[&str],
348    path: &str,
349    error: fn(&str, crate::sexpr::Error) -> SourceBundleError,
350) -> Result<Vec<FormSpan>, SourceBundleError> {
351    scan_form_spans(
352        source,
353        &Selector {
354            heads: Some(heads.iter().map(|name| (*name).to_owned()).collect()),
355            min_depth: Some(1),
356            max_depth: Some(1),
357            ..Selector::default()
358        },
359    )
360    .map_err(|cause| error(path, cause))
361}
362
363fn parse_field(
364    source: &str,
365    offset: usize,
366    path: &str,
367) -> Result<SchematicPlacedField, SourceBundleError> {
368    parse_field_with_error(source, offset, path, failure)
369}
370
371fn parse_field_with_error(
372    source: &str,
373    offset: usize,
374    path: &str,
375    error: fn(&str, crate::sexpr::Error) -> SourceBundleError,
376) -> Result<SchematicPlacedField, SourceBundleError> {
377    let form = parse(source).map_err(|cause| error(path, cause))?;
378    let values = list(&form);
379    let private = matches!(values.get(1), Some(Sexp::Atom(value)) if value == "private");
380    let start = 1 + usize::from(private);
381    let key = values
382        .get(start)
383        .and_then(text)
384        .ok_or_else(|| failure(path, "field key is missing"))?
385        .to_owned();
386    let value = values
387        .get(start + 1)
388        .and_then(text)
389        .ok_or_else(|| failure(path, "field value is missing"))?
390        .to_owned();
391    let spans = children_with_error(source, &["at", "effects"], path, error)?;
392    let at_span = spans.iter().find(|span| span.head.as_deref() == Some("at"));
393    let mut angle_degrees = 0.0;
394    let at = at_span
395        .map(|span| {
396            let position = child(&form, "at").expect("selected source position has a parsed form");
397            if spans
398                .iter()
399                .filter(|span| span.head.as_deref() == Some("at"))
400                .count()
401                != 1
402                || !(3..=4).contains(&list(position).len())
403                || list(position)[1..]
404                    .iter()
405                    .any(|value| matches!(value, Sexp::List(_)))
406            {
407                return Err(failure(
408                    path,
409                    "field position must have exactly x, y and an optional angle",
410                ));
411            }
412            let values = direct_scalars(source, span, 3, path)?;
413            if values.len() < 2 {
414                return Err(failure(path, "field position needs x and y"));
415            }
416            angle_degrees = values
417                .get(2)
418                .map(|value| {
419                    value
420                        .parse::<f64>()
421                        .map_err(|_| failure(path, "invalid field angle"))
422                })
423                .transpose()?
424                .unwrap_or(0.0);
425            if !angle_degrees.is_finite() {
426                return Err(failure(path, "field angle must be finite"));
427            }
428            Ok(SchematicPoint {
429                x_iu: parse_iu(&values[0], path)?,
430                y_iu: parse_iu(&values[1], path)?,
431            })
432        })
433        .transpose()?;
434    let mut effects = parse_text_effects(&form).map_err(|cause| error(path, cause))?;
435    let property_hidden = flag(&form, "hide", path)?;
436    let effects_hidden = child(&form, "effects")
437        .map(|effects| flag(effects, "hide", path))
438        .transpose()?
439        .unwrap_or(false);
440    let hidden = property_hidden || effects_hidden;
441    let private_flag = flag(&form, "private", path)?;
442    if let Some(effects) = &mut effects {
443        effects.hidden = hidden;
444        effects.source_range = spans
445            .iter()
446            .find(|span| span.head.as_deref() == Some("effects"))
447            .map(|span| (offset + span.range.start)..(offset + span.range.end));
448    }
449    Ok(SchematicPlacedField {
450        key,
451        value,
452        at,
453        angle_degrees,
454        effects,
455        visible: !hidden,
456        private: private || private_flag,
457        show_name: flag(&form, "show_name", path)?,
458    })
459}
460
461fn pin_scalar(form: &Sexp, key: &str, path: &str) -> Result<Option<String>, SourceBundleError> {
462    let mut authored = list(form)
463        .iter()
464        .filter(|item| list(item).first().and_then(text) == Some(key));
465    let Some(selected) = authored.next() else {
466        return Ok(None);
467    };
468    if authored.next().is_some() {
469        return Err(failure(
470            path,
471            format!("placed pin {key} must have one unambiguous scalar"),
472        ));
473    }
474    Ok(Some(single_string(selected, key, path)?))
475}
476
477fn pin_number(form: &Sexp, path: &str) -> Result<Option<String>, SourceBundleError> {
478    let mut scalars = list(form)
479        .iter()
480        .skip(1)
481        .filter(|item| !matches!(item, Sexp::List(_)));
482    let Some(number) = scalars.next() else {
483        return Ok(None);
484    };
485    if scalars.next().is_some() || !std::ptr::eq(number, &list(form)[1]) {
486        return Err(failure(
487            path,
488            "placed pin number must have one unambiguous leading scalar",
489        ));
490    }
491    text(number)
492        .map(|value| Some(value.to_owned()))
493        .ok_or_else(|| failure(path, "placed pin number must be a string or atom"))
494}
495
496fn parse_pin(form: &Sexp, path: &str) -> Result<SchematicSymbolPin, SourceBundleError> {
497    // Preserve the existing complete projection; the independent selector view
498    // above additionally distinguishes absence from malformed authored shape.
499    let number = list(form)
500        .get(1)
501        .and_then(text)
502        .ok_or_else(|| failure(path, "pin number is missing"))?
503        .to_owned();
504    Ok(SchematicSymbolPin {
505        number,
506        uuid: pin_scalar(form, "uuid", path)?.unwrap_or_default(),
507        alternate: pin_scalar(form, "alternate", path)?,
508    })
509}
510
511fn list(form: &Sexp) -> &[Sexp] {
512    if let Sexp::List(values) = form {
513        values
514    } else {
515        &[]
516    }
517}
518fn text(form: &Sexp) -> Option<&str> {
519    match form {
520        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
521        _ => None,
522    }
523}
524fn child<'a>(form: &'a Sexp, key: &str) -> Option<&'a Sexp> {
525    list(form)
526        .iter()
527        .find(|item| list(item).first().and_then(text) == Some(key))
528}
529fn single_string(form: &Sexp, key: &str, path: &str) -> Result<String, SourceBundleError> {
530    if list(form).len() != 2 {
531        return Err(failure(
532            path,
533            format!("{key} must have exactly one string or atom scalar"),
534        ));
535    }
536    list(form)
537        .get(1)
538        .and_then(text)
539        .map(str::to_owned)
540        .ok_or_else(|| failure(path, format!("{key} must be a string or atom scalar")))
541}
542fn library_key(
543    source: &str,
544    span: &FormSpan,
545    key: &str,
546    path: &str,
547) -> Result<String, SourceBundleError> {
548    let selected = &source[span.range.clone()];
549    let tokens = Lexer::new(selected)
550        .collect::<Result<Vec<_>, _>>()
551        .map_err(|error| failure(path, error))?;
552    if tokens.len() != 4
553        || tokens[0].kind != TokenKind::Left
554        || tokens[3].kind != TokenKind::Right
555        || !(matches!(tokens[2].kind, TokenKind::Atom | TokenKind::QuotedString)
556            || key == "lib_id" && matches!(tokens[2].kind, TokenKind::Integer | TokenKind::Float))
557    {
558        return Err(failure(
559            path,
560            format!("placed symbol {key} must have exactly one permitted scalar"),
561        ));
562    }
563    // Native lib_id also accepts numeric tokens. Keep the lexical spelling;
564    // integer/f64 formatting would corrupt names such as 001 or 1e3.
565    direct_scalars(source, span, 1, path)?
566        .into_iter()
567        .next()
568        .ok_or_else(|| failure(path, format!("missing {key}")))
569}
570fn flag(form: &Sexp, key: &str, path: &str) -> Result<bool, SourceBundleError> {
571    let bare = list(form)
572        .iter()
573        .any(|item| matches!(item, Sexp::Atom(value) if value == key));
574    let mut authored = list(form)
575        .iter()
576        .filter(|item| list(item).first().and_then(text) == Some(key));
577    let Some(value) = authored.next() else {
578        return Ok(bare);
579    };
580    if authored.next().is_some() || list(value).len() > 2 {
581        return Err(failure(path, format!("ambiguous or malformed {key} flag")));
582    }
583    if list(value).len() == 1 {
584        return Ok(true);
585    }
586    if let Some(Sexp::Integer(value)) = list(value).get(1) {
587        return match value {
588            1 => Ok(true),
589            0 => Ok(bare),
590            _ => Err(failure(path, format!("invalid {key} flag"))),
591        };
592    }
593    match list(value).get(1).and_then(text) {
594        Some("yes" | "true" | "1") => Ok(true),
595        Some("no" | "false" | "0") => Ok(bare),
596        _ => Err(failure(path, format!("invalid {key} flag"))),
597    }
598}
599fn failure(path: &str, message: impl std::fmt::Display) -> SourceBundleError {
600    SourceBundleError::new(
601        SourceBundleErrorKind::Schematic,
602        Some(path),
603        message.to_string(),
604    )
605}