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

kicad_monkey_core/
schematic_annotation_source.rs

1//! Bounded authored annotation reads, independent of compact connectivity and
2//! plot projections. Native positions use the pinned KiCad10.0.5 loader.
3use crate::sexpr::{ErrorKind, Lexer, Sexp, TokenKind, parse};
4use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
5use crate::{
6    KiCadTextEffects, SchematicDocument, SchematicNativeLoadedPoint, SchematicPoint,
7    SchematicSourceForm, SourceBundleError, SourceBundleErrorKind,
8};
9use std::collections::{BTreeMap, BTreeSet};
10
11mod contacts;
12mod presentation;
13mod sheets;
14pub use contacts::{
15    SchematicAnnotationContact, SchematicAnnotationContactIssue,
16    SchematicAnnotationContactIssueKind, SchematicAnnotationContactTarget,
17    SchematicAnnotationContacts, SchematicAnnotationWireContactKind, SchematicNativeWireParameter,
18};
19pub(crate) use contacts::{
20    exact as native_line_exact, native_hit as native_line_hit,
21    native_hit_with_accuracy as native_line_hit_with_accuracy, parameter as native_line_parameter,
22};
23pub use presentation::{
24    SchematicDirectiveCircle, SchematicDirectivePresentation, SchematicNamedPresentation,
25};
26pub use sheets::{
27    SchematicAuthoredSheetEntry, SchematicAuthoredSheetRecord, SchematicAuthoredSheetSources,
28    SchematicSheetContactTarget, SchematicSheetEntryContact, SchematicSheetEntrySelector,
29    SchematicSheetPropertyFacts,
30};
31
32#[derive(Clone, Copy, Debug)]
33pub struct SchematicAnnotationSourceLimits {
34    pub max_source_bytes: usize,
35    pub max_scan_bytes: usize,
36    /// All list forms, before structural-span or selected AST allocation.
37    pub max_list_forms: usize,
38    pub max_contact_checks: usize,
39    pub max_contacts: usize,
40}
41impl Default for SchematicAnnotationSourceLimits {
42    fn default() -> Self {
43        Self {
44            max_source_bytes: 32 * 1024 * 1024,
45            max_scan_bytes: 64 * 1024 * 1024,
46            max_list_forms: 100_000,
47            max_contact_checks: 4_000_000,
48            max_contacts: 1_000_000,
49        }
50    }
51}
52
53#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
54pub enum SchematicAuthoredAnnotationKind {
55    LocalLabel,
56    GlobalLabel,
57    HierarchicalLabel,
58    NoConnect,
59    DirectiveLabel,
60    /// Early KiCad7 spelling; kept distinct so original rows never merge.
61    LegacyNetclassFlag,
62}
63impl SchematicAuthoredAnnotationKind {
64    fn from_head(head: &str) -> Option<Self> {
65        Some(match head {
66            "label" => Self::LocalLabel,
67            "global_label" => Self::GlobalLabel,
68            "hierarchical_label" => Self::HierarchicalLabel,
69            "no_connect" => Self::NoConnect,
70            "directive_label" => Self::DirectiveLabel,
71            "netclass_flag" => Self::LegacyNetclassFlag,
72            _ => return None,
73        })
74    }
75}
76
77#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
78pub struct SchematicAnnotationSelector {
79    pub kind: SchematicAuthoredAnnotationKind,
80    pub ordinal: usize,
81}
82
83#[derive(Clone, Debug, PartialEq)]
84pub struct SchematicAnnotationProperty {
85    /// Original direct-child slot in its annotation, before any filtering.
86    pub ordinal: usize,
87    pub name: String,
88    pub value: String,
89    pub uuid: Result<Option<String>, SourceBundleError>,
90    pub position: Result<Option<SchematicNativeLoadedPoint>, SourceBundleError>,
91    pub angle_degrees: Result<Option<f64>, SourceBundleError>,
92    pub effects: Result<Option<KiCadTextEffects>, SourceBundleError>,
93    pub show_name: Result<Option<bool>, SourceBundleError>,
94}
95
96/// The source token is preserved, with no electrical-role inference. Native
97/// names such as `input` describe label paint here, not a declared port role.
98#[derive(Clone, Copy, Debug, Eq, PartialEq)]
99pub enum SchematicAnnotationShape {
100    Input,
101    Output,
102    Bidirectional,
103    TriState,
104    Passive,
105    Dot,
106    Round,
107    Diamond,
108    Rectangle,
109}
110
111#[derive(Clone, Debug)]
112pub struct SchematicNativeAnnotationFacts {
113    pub position: SchematicNativeLoadedPoint,
114    /// Authored spelling, before variables, native NETNAME escaping or any
115    /// consumer display encoding. A no-connect marker has no name.
116    pub text: Option<String>,
117}
118
119/// Private source ownership and facts cannot be fabricated by a consumer.
120/// This packet grants checked authored facts, not electrical contact authority.
121#[derive(Clone, Debug)]
122pub struct SchematicNativeAnnotation<'a> {
123    source: &'a str,
124    selector: SchematicAnnotationSelector,
125    facts: SchematicNativeAnnotationFacts,
126}
127impl SchematicNativeAnnotation<'_> {
128    pub fn selector(&self) -> SchematicAnnotationSelector {
129        self.selector
130    }
131    pub fn facts(&self) -> &SchematicNativeAnnotationFacts {
132        &self.facts
133    }
134}
135
136/// Each fact is checked independently. Bad UUID/paint does not erase a valid
137/// name and anchor; runtime/resource failures are never content omissions.
138#[derive(Clone, Debug)]
139pub struct SchematicAuthoredAnnotationRecord<'a> {
140    pub form: SchematicSourceForm<'a>,
141    pub selector: SchematicAnnotationSelector,
142    pub uuid: Result<Option<String>, SourceBundleError>,
143    /// Loaded authored name, including empty/contextual/aggregate expressions.
144    /// It is independent of both contact geometry and optional display facts.
145    pub authored_name: Result<Option<String>, SourceBundleError>,
146    /// One native contact anchor, independent of the readable naming facet.
147    pub site_position: Result<SchematicNativeLoadedPoint, SourceBundleError>,
148    /// Pinned constructor size: DEFAULT_NOCONNECT_SIZE=48 mil, 254 IU/mil.
149    /// This supplies only marker geometry, never a theme/project pen width.
150    pub no_connect_size_iu: Option<i64>,
151    pub annotation: Result<SchematicNativeAnnotation<'a>, SourceBundleError>,
152    pub angle_degrees: Result<Option<f64>, SourceBundleError>,
153    pub shape: Result<Option<SchematicAnnotationShape>, SourceBundleError>,
154    pub effects: Result<Option<KiCadTextEffects>, SourceBundleError>,
155    pub properties: Vec<Result<SchematicAnnotationProperty, SourceBundleError>>,
156}
157
158#[derive(Debug)]
159pub struct SchematicAnnotationSourceView<'a> {
160    source: &'a str,
161    path: &'a str,
162    rows: Vec<(SchematicAnnotationSelector, FormSpan)>,
163    row_index: BTreeMap<SchematicAnnotationSelector, usize>,
164    context_rows: Vec<FormSpan>,
165    limits: SchematicAnnotationSourceLimits,
166}
167impl SchematicDocument {
168    pub fn annotation_sources(
169        &self,
170        limits: SchematicAnnotationSourceLimits,
171    ) -> Result<SchematicAnnotationSourceView<'_>, SourceBundleError> {
172        let source = self.source();
173        let path = self.source_path();
174        if source.len() > limits.max_source_bytes {
175            return Err(failure(
176                path,
177                SourceBundleErrorKind::ResourceLimit,
178                "annotation source byte budget exceeded",
179            ));
180        }
181        let mut budget = Budget::new(limits, path);
182        budget.preflight(source)?;
183        budget.scan(source.len())?;
184        let spans = scan_form_spans(
185            source,
186            &Selector {
187                heads: Some(BTreeSet::from([
188                    "label".into(),
189                    "global_label".into(),
190                    "hierarchical_label".into(),
191                    "no_connect".into(),
192                    "directive_label".into(),
193                    "netclass_flag".into(),
194                    "wire".into(),
195                    "bus".into(),
196                    "junction".into(),
197                    "sheet".into(),
198                    "symbol".into(),
199                ])),
200                min_depth: Some(1),
201                max_depth: Some(1),
202                ..Default::default()
203            },
204        )
205        .map_err(|error| sexpr_error(path, error))?;
206        let mut counts = BTreeMap::new();
207        let (annotation_spans, context_rows): (Vec<_>, Vec<_>) =
208            spans.into_iter().partition(|span| {
209                SchematicAuthoredAnnotationKind::from_head(
210                    span.head.as_deref().expect("selected head"),
211                )
212                .is_some()
213            });
214        let rows: Vec<_> = annotation_spans
215            .into_iter()
216            .map(|span| {
217                let kind = SchematicAuthoredAnnotationKind::from_head(
218                    span.head.as_deref().expect("selected head"),
219                )
220                .expect("selected annotation kind");
221                let ordinal = counts.entry(kind).or_insert(0);
222                let selector = SchematicAnnotationSelector {
223                    kind,
224                    ordinal: *ordinal,
225                };
226                *ordinal += 1;
227                (selector, span)
228            })
229            .collect();
230        let row_index = rows
231            .iter()
232            .enumerate()
233            .map(|(index, (selector, _))| (*selector, index))
234            .collect();
235        Ok(SchematicAnnotationSourceView {
236            source,
237            path,
238            rows,
239            row_index,
240            context_rows,
241            limits,
242        })
243    }
244}
245impl<'a> SchematicAnnotationSourceView<'a> {
246    /// Checked original placement absence is independent of pin/root/version
247    /// readability. Any original placement makes this context incomplete and
248    /// grants no pin target; no selection or pin resolver is invoked here.
249    pub fn pin_context_without_selections(
250        &self,
251    ) -> Result<crate::SchematicNativePinContext<'a>, SourceBundleError> {
252        let count = self
253            .context_rows
254            .iter()
255            .filter(|span| span.head.as_deref() == Some("symbol"))
256            .count();
257        if count > self.limits.max_list_forms {
258            return Err(failure(
259                self.path,
260                SourceBundleErrorKind::ResourceLimit,
261                "unselected native pin context row budget exceeded",
262            ));
263        }
264        crate::SchematicNativePinContext::without_selections(self.source, self.path, count)
265    }
266    pub fn selectors(&self) -> impl ExactSizeIterator<Item = SchematicAnnotationSelector> + '_ {
267        self.rows.iter().map(|(selector, _)| *selector)
268    }
269
270    #[allow(
271        clippy::too_many_lines,
272        reason = "annotation record reader decodes each authored annotation variant explicitly"
273    )]
274    pub fn record(
275        &self,
276        selector: SchematicAnnotationSelector,
277    ) -> Result<Option<SchematicAuthoredAnnotationRecord<'a>>, SourceBundleError> {
278        let Some((_, span)) = self
279            .row_index
280            .get(&selector)
281            .map(|&index| &self.rows[index])
282        else {
283            return Ok(None);
284        };
285        let source = &self.source[span.range.clone()];
286        let mut budget = Budget::new(self.limits, self.path);
287        budget.preflight(source)?;
288        budget.scan(source.len())?;
289        let form = parse(source).map_err(|error| sexpr_error(self.path, error))?;
290        let site_position = native_position(&form, selector.kind, self.path);
291        let authored_name = if selector.kind == SchematicAuthoredAnnotationKind::NoConnect {
292            Ok(None)
293        } else {
294            leading_text(&form, self.path).map(|value| Some(value.to_owned()))
295        };
296        let annotation = (|| {
297            let position = site_position.clone()?;
298            let text = authored_name.clone()?;
299            Ok(SchematicNativeAnnotation {
300                source: self.source,
301                selector,
302                facts: SchematicNativeAnnotationFacts { position, text },
303            })
304        })();
305        let uuid = child_scalar(&form, "uuid", self.path);
306        let angle_degrees = (|| {
307            let Some(at) = child(&form, "at", self.path)? else {
308                return Ok(None);
309            };
310            if selector.kind == SchematicAuthoredAnnotationKind::NoConnect {
311                return Ok(None);
312            }
313            Ok(Some(number(
314                list(at).get(3),
315                self.path,
316                "annotation angle",
317            )?))
318        })();
319        let shape = (|| {
320            let Some(value) = child_scalar(&form, "shape", self.path)? else {
321                return Ok(None);
322            };
323            Ok(Some(match value.as_str() {
324                "input" => SchematicAnnotationShape::Input,
325                "output" => SchematicAnnotationShape::Output,
326                "bidirectional" => SchematicAnnotationShape::Bidirectional,
327                "tri_state" => SchematicAnnotationShape::TriState,
328                "passive" => SchematicAnnotationShape::Passive,
329                "dot" => SchematicAnnotationShape::Dot,
330                "round" => SchematicAnnotationShape::Round,
331                "diamond" => SchematicAnnotationShape::Diamond,
332                "rectangle" => SchematicAnnotationShape::Rectangle,
333                _ => return Err(content(self.path, "unknown annotation shape")),
334            }))
335        })();
336        let effects = (|| {
337            // Reject ambiguous child blocks before the existing shared decoder
338            // can choose its first match. Its existing value semantics remain.
339            child(&form, "effects", self.path)?;
340            crate::text_metadata::parse_text_effects(&form)
341                .map_err(|error| sexpr_error(self.path, error))
342        })();
343        let properties = list(&form)
344            .iter()
345            .enumerate()
346            .filter(|(_, value)| head(value) == Some("property"))
347            .map(|(ordinal, value)| {
348                let name = list(value)
349                    .get(1)
350                    .and_then(text)
351                    .ok_or_else(|| content(self.path, "property requires a name"))?;
352                let text_value = list(value)
353                    .get(2)
354                    .and_then(text)
355                    .ok_or_else(|| content(self.path, "property requires a value"))?;
356                Ok(SchematicAnnotationProperty {
357                    ordinal,
358                    name: name.to_owned(),
359                    value: text_value.to_owned(),
360                    uuid: child_scalar(value, "uuid", self.path),
361                    position: (|| {
362                        if child(value, "at", self.path)?.is_none() {
363                            return Ok(None);
364                        }
365                        native_position(
366                            value,
367                            SchematicAuthoredAnnotationKind::DirectiveLabel,
368                            self.path,
369                        )
370                        .map(Some)
371                    })(),
372                    angle_degrees: (|| {
373                        let Some(at) = child(value, "at", self.path)? else {
374                            return Ok(None);
375                        };
376                        number(list(at).get(3), self.path, "property angle").map(Some)
377                    })(),
378                    effects: (|| {
379                        child(value, "effects", self.path)?;
380                        crate::text_metadata::parse_text_effects(value)
381                            .map_err(|error| sexpr_error(self.path, error))
382                    })(),
383                    show_name: (|| {
384                        let Some(value) = child_scalar(value, "show_name", self.path)? else {
385                            return Ok(None);
386                        };
387                        match value.as_str() {
388                            "yes" => Ok(Some(true)),
389                            "no" => Ok(Some(false)),
390                            _ => Err(content(self.path, "property show_name requires yes or no")),
391                        }
392                    })(),
393                })
394            })
395            .collect();
396        Ok(Some(SchematicAuthoredAnnotationRecord {
397            form: SchematicSourceForm {
398                source,
399                source_range: span.range.clone(),
400                ordinal: selector.ordinal,
401            },
402            selector,
403            uuid,
404            authored_name,
405            site_position,
406            no_connect_size_iu: (selector.kind == SchematicAuthoredAnnotationKind::NoConnect)
407                .then_some(48 * 254),
408            annotation,
409            angle_degrees,
410            shape,
411            effects,
412            properties,
413        }))
414    }
415}
416
417struct Budget<'a> {
418    limits: SchematicAnnotationSourceLimits,
419    path: &'a str,
420    scanned: usize,
421}
422impl<'a> Budget<'a> {
423    fn new(limits: SchematicAnnotationSourceLimits, path: &'a str) -> Self {
424        Self {
425            limits,
426            path,
427            scanned: 0,
428        }
429    }
430    fn scan(&mut self, bytes: usize) -> Result<(), SourceBundleError> {
431        self.scanned = self.scanned.checked_add(bytes).ok_or_else(|| {
432            failure(
433                self.path,
434                SourceBundleErrorKind::ResourceLimit,
435                "annotation scan byte count overflow",
436            )
437        })?;
438        if self.scanned > self.limits.max_scan_bytes {
439            return Err(failure(
440                self.path,
441                SourceBundleErrorKind::ResourceLimit,
442                "annotation scan byte budget exceeded",
443            ));
444        }
445        Ok(())
446    }
447    fn preflight(&mut self, source: &str) -> Result<(), SourceBundleError> {
448        self.scan(source.len())?;
449        let mut forms = 0usize;
450        for token in Lexer::new(source) {
451            if token.map_err(|error| sexpr_error(self.path, error))?.kind == TokenKind::Left {
452                if forms >= self.limits.max_list_forms {
453                    return Err(failure(
454                        self.path,
455                        SourceBundleErrorKind::ResourceLimit,
456                        "annotation list budget exceeded before allocation",
457                    ));
458                }
459                forms += 1;
460            }
461        }
462        Ok(())
463    }
464}
465fn failure(path: &str, kind: SourceBundleErrorKind, reason: impl ToString) -> SourceBundleError {
466    SourceBundleError::new(kind, Some(path), reason.to_string())
467}
468fn content(path: &str, reason: impl ToString) -> SourceBundleError {
469    failure(path, SourceBundleErrorKind::Schematic, reason)
470}
471fn sexpr_error(path: &str, error: crate::sexpr::Error) -> SourceBundleError {
472    failure(
473        path,
474        if error.kind == ErrorKind::ResourceLimit {
475            SourceBundleErrorKind::ResourceLimit
476        } else {
477            SourceBundleErrorKind::Schematic
478        },
479        error,
480    )
481}
482fn list(form: &Sexp) -> &[Sexp] {
483    if let Sexp::List(values) = form {
484        values
485    } else {
486        &[]
487    }
488}
489fn text(form: &Sexp) -> Option<&str> {
490    match form {
491        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
492        _ => None,
493    }
494}
495fn head(form: &Sexp) -> Option<&str> {
496    list(form).first().and_then(text)
497}
498fn child<'a>(form: &'a Sexp, key: &str, path: &str) -> Result<Option<&'a Sexp>, SourceBundleError> {
499    let mut values = list(form).iter().filter(|value| head(value) == Some(key));
500    let value = values.next();
501    if values.next().is_some() {
502        return Err(content(path, format!("ambiguous {key}")));
503    }
504    Ok(value)
505}
506fn child_scalar(form: &Sexp, key: &str, path: &str) -> Result<Option<String>, SourceBundleError> {
507    let Some(value) = child(form, key, path)? else {
508        return Ok(None);
509    };
510    if list(value).len() != 2 {
511        return Err(content(path, format!("{key} requires one scalar")));
512    }
513    list(value)
514        .get(1)
515        .and_then(text)
516        .map(|value| Some(value.to_owned()))
517        .ok_or_else(|| content(path, format!("{key} requires a string or atom")))
518}
519fn leading_text<'a>(form: &'a Sexp, path: &str) -> Result<&'a str, SourceBundleError> {
520    let value = list(form)
521        .get(1)
522        .and_then(text)
523        .ok_or_else(|| content(path, "annotation requires leading text"))?;
524    if list(form)
525        .iter()
526        .skip(2)
527        .any(|value| !matches!(value, Sexp::List(_)))
528    {
529        return Err(content(path, "annotation has surplus direct scalar"));
530    }
531    Ok(value)
532}
533fn number(value: Option<&Sexp>, path: &str, field: &str) -> Result<f64, SourceBundleError> {
534    let number = match value {
535        Some(Sexp::Integer(value)) => *value as f64,
536        Some(Sexp::Float(value)) => *value,
537        _ => return Err(content(path, format!("{field} requires a number"))),
538    };
539    if !number.is_finite() {
540        return Err(content(path, format!("{field} requires a finite number")));
541    }
542    Ok(number)
543}
544fn native_position(
545    form: &Sexp,
546    kind: SchematicAuthoredAnnotationKind,
547    path: &str,
548) -> Result<SchematicNativeLoadedPoint, SourceBundleError> {
549    let Some(at) = child(form, "at", path)? else {
550        // Native constructors start at the origin if the field is absent.
551        return Ok(SchematicNativeLoadedPoint {
552            at: SchematicPoint { x_iu: 0, y_iu: 0 },
553            normalized: false,
554            clamped: false,
555        });
556    };
557    let count = if kind == SchematicAuthoredAnnotationKind::NoConnect {
558        3
559    } else {
560        4
561    };
562    if list(at).len() != count {
563        return Err(content(
564            path,
565            "annotation at has invalid coordinate/angle arity",
566        ));
567    }
568    let x = crate::schematic_native_load::loaded_number(
569        number(list(at).get(1), path, "annotation x")?,
570        path,
571    )?;
572    let y = crate::schematic_native_load::loaded_number(
573        number(list(at).get(2), path, "annotation y")?,
574        path,
575    )?;
576    Ok(SchematicNativeLoadedPoint {
577        at: SchematicPoint {
578            x_iu: x.iu,
579            y_iu: y.iu,
580        },
581        normalized: x.normalized || y.normalized,
582        clamped: x.clamped || y.clamped,
583    })
584}