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

kicad_monkey_core/
schematic_bus_source.rs

1//! Checked, bounded authored bus facts and optional fixed-vector qualification.
2//! This does not invoke the legacy bus builder or assemble a project.
3use crate::sexpr::{ErrorKind, Lexer, TokenKind};
4use crate::sexpr_projection::{Selector, scan_form_spans};
5use crate::{
6    SchematicDocument, SchematicNativeLoadedPoint, SchematicNativeWireParameter, SchematicPoint,
7    SchematicSourceForm, SchematicWireStroke, SourceBundleError, SourceBundleErrorKind,
8};
9use std::collections::{BTreeMap, BTreeSet};
10
11mod declarations;
12mod facts;
13mod qualify;
14pub use declarations::{SchematicBusAliasDeclarationRecord, SchematicBusAliasDeclarations};
15
16#[derive(Clone, Copy, Debug)]
17pub struct SchematicBusSourceLimits {
18    pub max_source_bytes: usize,
19    pub max_scan_bytes: usize,
20    pub max_list_forms: usize,
21    pub max_depth: usize,
22    pub max_vector_width: usize,
23    pub max_expanded_slots: usize,
24    pub max_work: usize,
25    /// The widest pen, IU, a bus stored with no width can resolve to
26    /// (`SCH_LINE::GetPenWidth`): KiCad's 12 mil default, which a freshly
27    /// loaded bus keeps while its connectivity is dirty, or its net class's
28    /// bus width, so in a project the widest of its net classes' bus widths
29    /// too. `GetBus` reaches no farther from such a bus than one unit plus
30    /// half this pen (`SCH_SCREEN::GetLine`, `SCH_LINE::HitTest`), so a point
31    /// beyond that is off it whatever pen the bus resolves to.
32    pub widest_default_bus_pen_iu: i64,
33}
34/// KiCad's default bus width, 12 mil (`DEFAULT_BUS_WIDTH_MILS`), in IU.
35const KICAD_DEFAULT_BUS_PEN_IU: i64 = 3048;
36impl Default for SchematicBusSourceLimits {
37    fn default() -> Self {
38        Self {
39            max_source_bytes: 32 * 1024 * 1024,
40            max_scan_bytes: 64 * 1024 * 1024,
41            max_list_forms: 100_000,
42            max_depth: 256,
43            max_vector_width: 4096,
44            max_expanded_slots: 1_000_000,
45            max_work: 10_000_000,
46            widest_default_bus_pen_iu: KICAD_DEFAULT_BUS_PEN_IU,
47        }
48    }
49}
50#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
51pub enum SchematicBusSourceKind {
52    Bus,
53    Entry,
54    Junction,
55    Wire,
56    LocalLabel,
57    GlobalLabel,
58    HierarchicalLabel,
59    DirectiveLabel,
60    LegacyNetclassFlag,
61    Alias,
62    Sheet,
63    Symbol,
64    NoConnect,
65}
66impl SchematicBusSourceKind {
67    pub fn as_str(self) -> &'static str {
68        match self {
69            Self::Bus => "bus",
70            Self::Entry => "bus_entry",
71            Self::Junction => "junction",
72            Self::Wire => "wire",
73            Self::LocalLabel => "label",
74            Self::GlobalLabel => "global_label",
75            Self::HierarchicalLabel => "hierarchical_label",
76            Self::DirectiveLabel => "directive_label",
77            Self::LegacyNetclassFlag => "netclass_flag",
78            Self::Alias => "bus_alias",
79            Self::Sheet => "sheet",
80            Self::Symbol => "symbol",
81            Self::NoConnect => "no_connect",
82        }
83    }
84    fn from_head(head: &str) -> Option<Self> {
85        [
86            Self::Bus,
87            Self::Entry,
88            Self::Junction,
89            Self::Wire,
90            Self::LocalLabel,
91            Self::GlobalLabel,
92            Self::HierarchicalLabel,
93            Self::DirectiveLabel,
94            Self::LegacyNetclassFlag,
95            Self::Alias,
96            Self::Sheet,
97            Self::Symbol,
98            Self::NoConnect,
99        ]
100        .into_iter()
101        .find(|kind| kind.as_str() == head)
102    }
103    fn label(self) -> bool {
104        matches!(
105            self,
106            Self::LocalLabel | Self::GlobalLabel | Self::HierarchicalLabel
107        )
108    }
109    fn label_anchor(self) -> bool {
110        self.label() || matches!(self, Self::DirectiveLabel | Self::LegacyNetclassFlag)
111    }
112}
113#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
114pub struct SchematicBusSourceSelector {
115    pub kind: SchematicBusSourceKind,
116    pub ordinal: usize,
117}
118
119/// Written bounds stay distinct from ascending electrical order. No member
120/// strings are allocated to establish this fact.
121#[derive(Clone, Debug, Eq, PartialEq)]
122pub struct SchematicBusVectorFacts {
123    pub prefix: String,
124    pub written_first: i32,
125    pub written_last: i32,
126    pub low_index: i32,
127    pub high_index: i32,
128    pub width: u32,
129}
130#[derive(Clone, Debug)]
131pub struct SchematicBusLabelFacts {
132    pub text: String,
133    pub vector: Option<SchematicBusVectorFacts>,
134}
135#[derive(Clone, Debug)]
136pub enum SchematicBusGeometry {
137    Line([SchematicNativeLoadedPoint; 2]),
138    Entry([SchematicNativeLoadedPoint; 2]),
139    Point(SchematicNativeLoadedPoint),
140}
141#[derive(Clone, Debug)]
142pub struct SchematicBusSourceRecord<'a> {
143    pub selector: SchematicBusSourceSelector,
144    pub form: SchematicSourceForm<'a>,
145    pub uuid: Result<Option<String>, SourceBundleError>,
146    pub geometry: Result<Option<SchematicBusGeometry>, SourceBundleError>,
147    pub stroke: Result<Option<SchematicWireStroke>, SourceBundleError>,
148    /// Native GetBus hit radius from an explicit positive source width. None
149    /// means effective/default pen settings are deliberately unresolved.
150    pub native_bus_hit_radius_iu: Result<Option<i64>, SourceBundleError>,
151    pub label: Result<Option<SchematicBusLabelFacts>, SourceBundleError>,
152}
153#[derive(Clone, Debug)]
154pub struct SchematicBusSourceIssue {
155    pub selector: SchematicBusSourceSelector,
156    pub source_range: std::ops::Range<usize>,
157    pub reason: String,
158}
159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160pub enum SchematicBusContactAuthority {
161    StoredEndpoint,
162    Junction,
163    LabelOverlap,
164    LabelFallback,
165}
166#[derive(Clone, Debug)]
167pub struct SchematicBusLineContact {
168    pub bus: SchematicBusSourceSelector,
169    pub vertex: Option<u8>,
170    pub parameter: SchematicNativeWireParameter,
171    pub tolerant: bool,
172}
173/// One original source point authorizes these incidences. The point is not
174/// permission to snap retained geometry; tolerant contacts keep their parameter.
175#[derive(Clone, Debug)]
176pub struct SchematicBusContactSite {
177    pub source: SchematicBusSourceSelector,
178    pub position: SchematicPoint,
179    pub authority: SchematicBusContactAuthority,
180    pub contacts: Vec<SchematicBusLineContact>,
181}
182#[derive(Clone, Debug)]
183pub struct SchematicBusGroupFacts {
184    pub buses: Vec<SchematicBusSourceSelector>,
185    pub vector: SchematicBusVectorFacts,
186    pub providers: Vec<SchematicBusSourceSelector>,
187    pub sites: Vec<SchematicBusContactSite>,
188}
189/// Physical bus incidence, independent of a membership declaration or width.
190/// Labels are only those whose native contact context was independently proved.
191#[derive(Clone, Debug)]
192pub struct SchematicAuthoredBusGroupFacts {
193    pub buses: Vec<SchematicBusSourceSelector>,
194    pub labels: Vec<SchematicBusSourceSelector>,
195    pub sites: Vec<SchematicBusContactSite>,
196}
197#[derive(Clone, Copy, Debug, Eq, PartialEq)]
198pub enum SchematicBusEntryArtworkRole {
199    /// GetBus is proved to succeed at this endpoint. Its native scalar veto
200    /// prevents through-entry scalar bridging; no RTree candidate is selected.
201    NativeBusVeto {
202        endpoint: u8,
203    },
204    ElectricallyInert,
205    /// Geometry and paint remain usable, but artwork-only lowering has not
206    /// been proved to preserve all native scalar connectivity.
207    UnqualifiedConnectivity,
208}
209#[derive(Clone, Debug)]
210pub struct SchematicBusEntryArtworkFacts {
211    pub entry: SchematicBusSourceSelector,
212    pub endpoints: [SchematicNativeLoadedPoint; 2],
213    pub role: SchematicBusEntryArtworkRole,
214    /// Original 1-IU line-hit witnesses, not the stroke-aware GetBus candidate
215    /// inventory or a native RTree selection. No member binding is implied.
216    pub bus_line_witnesses: Vec<SchematicBusSourceSelector>,
217}
218#[derive(Clone, Debug)]
219pub struct SchematicBusMemberNameLink {
220    pub provider: SchematicBusSourceSelector,
221    pub scalar_label: SchematicBusSourceSelector,
222    pub index: i32,
223}
224#[derive(Clone, Copy, Debug, Eq, PartialEq)]
225pub enum SchematicBusJunctionRole {
226    Scalar,
227    Bus,
228    Unqualified,
229}
230#[derive(Clone, Debug)]
231pub struct SchematicBusJunctionFacts {
232    pub junction: SchematicBusSourceSelector,
233    pub role: SchematicBusJunctionRole,
234}
235
236/// Source-issued receipt. Public facts are borrowed through getters; a consumer
237/// cannot construct a receipt or substitute facts from an equal-text document.
238#[derive(Debug)]
239pub struct SchematicStandaloneBusSource<'a> {
240    source: &'a str,
241    records: Vec<SchematicBusSourceRecord<'a>>,
242    groups: Vec<SchematicBusGroupFacts>,
243    authored_groups: Vec<SchematicAuthoredBusGroupFacts>,
244    entries: Vec<SchematicBusEntryArtworkFacts>,
245    links: Vec<SchematicBusMemberNameLink>,
246    junctions: Vec<SchematicBusJunctionFacts>,
247    issues: Vec<SchematicBusSourceIssue>,
248}
249impl SchematicStandaloneBusSource<'_> {
250    pub fn belongs_to(&self, document: &SchematicDocument) -> bool {
251        self.source.len() == document.source().len()
252            && std::ptr::eq(self.source.as_ptr(), document.source().as_ptr())
253    }
254    pub fn records(&self) -> &[SchematicBusSourceRecord<'_>] {
255        &self.records
256    }
257    pub fn groups(&self) -> &[SchematicBusGroupFacts] {
258        &self.groups
259    }
260    pub fn authored_groups(&self) -> &[SchematicAuthoredBusGroupFacts] {
261        &self.authored_groups
262    }
263    pub fn entry_artwork(&self) -> &[SchematicBusEntryArtworkFacts] {
264        &self.entries
265    }
266    pub fn member_name_links(&self) -> &[SchematicBusMemberNameLink] {
267        &self.links
268    }
269    pub fn junctions(&self) -> &[SchematicBusJunctionFacts] {
270        &self.junctions
271    }
272    pub fn issues(&self) -> &[SchematicBusSourceIssue] {
273        &self.issues
274    }
275    pub fn record(
276        &self,
277        selector: SchematicBusSourceSelector,
278    ) -> Option<&SchematicBusSourceRecord<'_>> {
279        self.records.iter().find(|row| row.selector == selector)
280    }
281}
282
283impl SchematicDocument {
284    pub fn standalone_bus_sources(
285        &self,
286        limits: SchematicBusSourceLimits,
287    ) -> Result<SchematicStandaloneBusSource<'_>, SourceBundleError> {
288        self.standalone_bus_with_context(limits, None, true)
289    }
290    pub fn standalone_bus_sources_with_pin_context(
291        &self,
292        limits: SchematicBusSourceLimits,
293        context: &crate::SchematicNativePinContext<'_>,
294    ) -> Result<SchematicStandaloneBusSource<'_>, SourceBundleError> {
295        if !context.belongs_to_source(self.source()) {
296            return Err(contract(
297                self.source_path(),
298                "foreign bus native pin context",
299            ));
300        }
301        self.standalone_bus_with_context(limits, Some(context), true)
302    }
303    /// Retain original bus drawing and qualified physical contacts without
304    /// parsing ranges, expanding members, or requiring a naming driver.
305    pub fn authored_bus_sources(
306        &self,
307        limits: SchematicBusSourceLimits,
308    ) -> Result<SchematicStandaloneBusSource<'_>, SourceBundleError> {
309        self.standalone_bus_with_context(limits, None, false)
310    }
311    pub fn authored_bus_sources_with_pin_context(
312        &self,
313        limits: SchematicBusSourceLimits,
314        context: &crate::SchematicNativePinContext<'_>,
315    ) -> Result<SchematicStandaloneBusSource<'_>, SourceBundleError> {
316        if !context.belongs_to_source(self.source()) {
317            return Err(contract(
318                self.source_path(),
319                "foreign authored bus pin context",
320            ));
321        }
322        self.standalone_bus_with_context(limits, Some(context), false)
323    }
324    fn standalone_bus_with_context(
325        &self,
326        limits: SchematicBusSourceLimits,
327        context: Option<&crate::SchematicNativePinContext<'_>>,
328        qualify_vectors: bool,
329    ) -> Result<SchematicStandaloneBusSource<'_>, SourceBundleError> {
330        let (source, path) = (self.source(), self.source_path());
331        let mut budget = Budget::new(limits, path);
332        budget.preflight(source)?;
333        budget.scan(source.len())?;
334        let spans = scan_form_spans(
335            source,
336            &Selector {
337                heads: Some(BTreeSet::from(
338                    [
339                        "bus",
340                        "bus_entry",
341                        "junction",
342                        "wire",
343                        "label",
344                        "global_label",
345                        "hierarchical_label",
346                        "directive_label",
347                        "netclass_flag",
348                        "bus_alias",
349                        "sheet",
350                        "symbol",
351                        "no_connect",
352                    ]
353                    .map(str::to_owned),
354                )),
355                min_depth: Some(1),
356                max_depth: Some(1),
357                ..Default::default()
358            },
359        )
360        .map_err(|error| sexpr_error(path, error))?;
361        let mut counts = BTreeMap::new();
362        let mut records = Vec::new();
363        // Charge a conservative fixed workspace for selected rows before
364        // record/line/union/map/reason allocation. Variable contact and member
365        // expansions have their own preflight charges during qualification.
366        budget.slots(
367            spans
368                .len()
369                .checked_mul(24)
370                .ok_or_else(|| resource(path, "bus row workspace overflow"))?,
371        )?;
372        budget.work(
373            spans
374                .len()
375                .checked_mul(12)
376                .ok_or_else(|| resource(path, "bus row work overflow"))?,
377        )?;
378        records
379            .try_reserve_exact(spans.len())
380            .map_err(|_| resource(path, "bus record allocation failed"))?;
381        for span in spans {
382            let kind = SchematicBusSourceKind::from_head(span.head.as_deref().unwrap())
383                .ok_or_else(|| contract(path, "selected bus family disappeared"))?;
384            let ordinal = counts.entry(kind).or_insert(0usize);
385            let selector = SchematicBusSourceSelector {
386                kind,
387                ordinal: *ordinal,
388            };
389            *ordinal += 1;
390            records.push(facts::record(
391                source,
392                path,
393                selector,
394                span.range,
395                &mut budget,
396                qualify_vectors,
397            )?);
398        }
399        let mut out = SchematicStandaloneBusSource {
400            source,
401            records,
402            groups: Vec::new(),
403            authored_groups: Vec::new(),
404            entries: Vec::new(),
405            links: Vec::new(),
406            junctions: Vec::new(),
407            issues: Vec::new(),
408        };
409        qualify::apply(&mut out, &mut budget, context, qualify_vectors)?;
410        Ok(out)
411    }
412}
413
414struct Budget<'a> {
415    limits: SchematicBusSourceLimits,
416    path: &'a str,
417    scanned: usize,
418    work: usize,
419    slots: usize,
420}
421impl<'a> Budget<'a> {
422    fn new(limits: SchematicBusSourceLimits, path: &'a str) -> Self {
423        Self {
424            limits,
425            path,
426            scanned: 0,
427            work: 0,
428            slots: 0,
429        }
430    }
431    fn preflight(&mut self, source: &str) -> Result<(), SourceBundleError> {
432        if source.len() > self.limits.max_source_bytes {
433            return Err(resource(self.path, "bus source byte limit exceeded"));
434        }
435        self.scan(source.len())?;
436        let (mut count, mut depth) = (0usize, 0usize);
437        for token in Lexer::new(source) {
438            match token.map_err(|error| sexpr_error(self.path, error))?.kind {
439                TokenKind::Left => {
440                    count += 1;
441                    depth += 1;
442                    if count > self.limits.max_list_forms || depth > self.limits.max_depth {
443                        return Err(resource(
444                            self.path,
445                            "bus list/depth limit exceeded before span/AST allocation",
446                        ));
447                    }
448                }
449                TokenKind::Right => depth = depth.saturating_sub(1),
450                _ => {}
451            }
452        }
453        Ok(())
454    }
455    fn scan(&mut self, n: usize) -> Result<(), SourceBundleError> {
456        self.scanned = self
457            .scanned
458            .checked_add(n)
459            .filter(|n| *n <= self.limits.max_scan_bytes)
460            .ok_or_else(|| resource(self.path, "bus charged scan limit exceeded"))?;
461        Ok(())
462    }
463    fn work(&mut self, n: usize) -> Result<(), SourceBundleError> {
464        self.work = self
465            .work
466            .checked_add(n)
467            .filter(|n| *n <= self.limits.max_work)
468            .ok_or_else(|| resource(self.path, "bus qualification work limit exceeded"))?;
469        Ok(())
470    }
471    fn slots(&mut self, n: usize) -> Result<(), SourceBundleError> {
472        self.slots = self
473            .slots
474            .checked_add(n)
475            .filter(|n| *n <= self.limits.max_expanded_slots)
476            .ok_or_else(|| {
477                resource(
478                    self.path,
479                    "bus expanded slot limit exceeded before allocation",
480                )
481            })?;
482        Ok(())
483    }
484}
485fn failure(path: &str, kind: SourceBundleErrorKind, reason: impl ToString) -> SourceBundleError {
486    SourceBundleError::new(kind, Some(path), reason.to_string())
487}
488fn content(path: &str, reason: impl ToString) -> SourceBundleError {
489    failure(path, SourceBundleErrorKind::Schematic, reason)
490}
491fn resource(path: &str, reason: impl ToString) -> SourceBundleError {
492    failure(path, SourceBundleErrorKind::ResourceLimit, reason)
493}
494fn contract(path: &str, reason: impl ToString) -> SourceBundleError {
495    failure(path, SourceBundleErrorKind::Contract, reason)
496}
497fn sexpr_error(path: &str, error: crate::sexpr::Error) -> SourceBundleError {
498    failure(
499        path,
500        if error.kind == ErrorKind::ResourceLimit {
501            SourceBundleErrorKind::ResourceLimit
502        } else {
503            SourceBundleErrorKind::Schematic
504        },
505        error,
506    )
507}
508fn facet<T>(
509    value: Result<T, SourceBundleError>,
510) -> Result<Result<T, SourceBundleError>, SourceBundleError> {
511    match value {
512        Err(error) if error.kind != SourceBundleErrorKind::Schematic => Err(error),
513        value => Ok(value),
514    }
515}