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

kicad_monkey_core/
schematic_bundle.rs

1use crate::KiCadTitleBlock;
2use crate::schematic_bundle_indexes::{
3    index_bundle_legacy_instances, index_library_symbols, portable_file_stem,
4    resolve_library_pin_owners,
5};
6use crate::schematic_diagnostics::{KiCadDiagnostic, KiCadDiagnosticCode};
7use crate::schematic_effective::{SchematicEffectiveSymbol, resolve_effective_symbols};
8use crate::schematic_project::{ProjectSchematicSettings, project_schematic_settings};
9use crate::schematic_source::{
10    SchematicBusAlias, SchematicBusEntry, SchematicConnectivity, SchematicJunction, SchematicLabel,
11    SchematicLegacySymbolInstance, SchematicLibrarySymbol, SchematicNoConnect,
12    SchematicPlacedSymbol, SchematicPolyline, SchematicSheetPin, SchematicSymbolProperty,
13    parse_bus_aliases, parse_embedded_library_symbols, parse_legacy_symbol_instances,
14    parse_placed_symbols, parse_sheet_pin, parse_source_carriers,
15};
16use crate::schematic_terminals::{SchematicSymbolTerminal, resolve_symbol_terminals};
17use crate::sexpr::{Lexer, Token, TokenKind, decode_quoted};
18use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
19use crate::source_bundle::{SourceBundle, SourceBundleError, SourceBundleErrorKind};
20use kicad_monkey_contracts::generated::source_bundle_manifest::SourceKind;
21use std::borrow::Cow;
22use std::collections::{BTreeSet, HashMap, HashSet};
23mod definition_cache;
24mod document;
25mod hierarchy;
26mod path_helpers;
27mod repairs;
28mod sheet_parse;
29mod title_block;
30pub use definition_cache::{
31    MAX_SCHEMATIC_DEFINITION_CACHE_BYTES, ParsedSchematicDefinition, SchematicDefinitionCacheError,
32};
33use hierarchy::realize_occurrences;
34use path_helpers::{join_occurrence_path, nonempty_or, portable_file_name, portable_parent};
35use repairs::IndexRepairs;
36use sheet_parse::{SheetParseState, default_sheet};
37use title_block::parse_title_block;
38#[path = "assembly_variant.rs"]
39mod assembly_variant;
40pub use crate::assembly_variant_reader::{
41    KiCadAuthoredVariant, KiCadVariantField, KiCadVariantFlags, KiCadVariantInstance,
42};
43pub(crate) use assembly_variant::schematic_variant_evidence;
44pub use assembly_variant::{
45    KiCadAssemblyVariantContext, KiCadVariantDiagnostic, KiCadVariantFootprint, KiCadVariantSheet,
46    KiCadVariantSymbol,
47};
48
49pub use document::{SchematicDocument, SchematicImportRead};
50#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct SchematicSheet {
53    pub uuid: String,
54    pub sheet_name: String,
55    pub sheet_file: String,
56    pub in_bom: bool,
57    pub on_board: bool,
58    pub dnp: bool,
59    pub exclude_from_sim: bool,
60    pub properties: Vec<SchematicSymbolProperty>,
61    pub pins: Vec<SchematicSheetPin>,
62    pub page_instances: Vec<SchematicPageInstance>,
63}
64
65#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
66#[serde(deny_unknown_fields)]
67pub struct SchematicPageInstance {
68    pub path: String,
69    pub page_number: usize,
70}
71
72#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct SchematicDefinition {
75    pub source_path: String,
76    pub version: Option<String>,
77    pub generator: Option<String>,
78    pub generator_version: Option<String>,
79    pub uuid: Option<String>,
80    pub title_block: Option<KiCadTitleBlock>,
81    pub sheets: Vec<SchematicSheet>,
82    pub root_page_instances: Vec<SchematicPageInstance>,
83    pub symbols: Vec<SchematicPlacedSymbol>,
84    pub library_symbols: Vec<SchematicLibrarySymbol>,
85    pub legacy_symbol_instances: Vec<SchematicLegacySymbolInstance>,
86    pub wires: Vec<SchematicPolyline>,
87    pub buses: Vec<SchematicPolyline>,
88    pub bus_entries: Vec<SchematicBusEntry>,
89    pub bus_aliases: Vec<SchematicBusAlias>,
90    pub junctions: Vec<SchematicJunction>,
91    pub no_connects: Vec<SchematicNoConnect>,
92    pub labels: Vec<SchematicLabel>,
93    #[serde(skip)]
94    pub connectivity: SchematicConnectivity,
95    #[serde(skip)]
96    legacy_symbol_instance_by_path: HashMap<String, usize>,
97    #[serde(skip)]
98    pub(crate) library_symbol_by_key: HashMap<String, usize>,
99    #[serde(skip)]
100    pub(crate) library_pin_owner_by_symbol: Vec<Option<usize>>,
101}
102
103impl SchematicDefinition {
104    pub fn legacy_symbol_instance(&self, path: &str) -> Option<&SchematicLegacySymbolInstance> {
105        self.legacy_symbol_instance_by_path
106            .get(path.trim_end_matches('/'))
107            .map(|index| &self.legacy_symbol_instances[*index])
108    }
109}
110
111#[derive(Clone, Debug, Eq, PartialEq)]
112pub struct SchematicOccurrence {
113    pub index: usize,
114    pub source_path: String,
115    pub parent_index: Option<usize>,
116    pub parent_sheet_index: Option<usize>,
117    pub sheet_uuid: Option<String>,
118    pub sheet_name: String,
119    pub sheet_file: String,
120    pub occurrence_address: String,
121    pub legacy_address: String,
122    pub human_address: String,
123    pub effective_in_bom: bool,
124    pub effective_on_board: bool,
125    pub effective_dnp: bool,
126    pub effective_exclude_from_sim: bool,
127}
128
129#[derive(Clone, Debug)]
130pub struct SchematicBundleIndex {
131    project_name: String,
132    root_sheet_name: String,
133    project_file: String,
134    source_anchor: String,
135    project_settings: ProjectSchematicSettings,
136    definitions: Vec<SchematicDefinition>,
137    definition_by_path: HashMap<String, usize>,
138    occurrences: Vec<SchematicOccurrence>,
139    legacy_symbol_instance_by_path: HashMap<String, (usize, usize)>,
140    bundle_identity_sha256: [u8; 32],
141    repairs: IndexRepairs,
142}
143
144#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
145pub struct SchematicBundleIndexBuildProfile {
146    pub parse_definitions_ns: u64,
147    pub realize_occurrences_ns: u64,
148    pub assemble_indexes_ns: u64,
149}
150
151impl SchematicBundleIndex {
152    /// Scan every schematic source once, then realize the reachable hierarchy.
153    pub fn build(bundle: &SourceBundle) -> Result<Self, SourceBundleError> {
154        Self::build_internal(bundle, false).map(|(index, _profile)| index)
155    }
156
157    pub fn build_profiled(
158        bundle: &SourceBundle,
159    ) -> Result<(Self, SchematicBundleIndexBuildProfile), SourceBundleError> {
160        Self::build_internal(bundle, true)
161    }
162
163    fn build_internal(
164        bundle: &SourceBundle,
165        profile: bool,
166    ) -> Result<(Self, SchematicBundleIndexBuildProfile), SourceBundleError> {
167        let definitions_started = profile.then(std::time::Instant::now);
168        let mut repairs = IndexRepairs::default();
169        let mut definitions = Vec::new();
170        let mut definition_by_path = HashMap::new();
171        let root_path = bundle.root_schematic_path();
172        let root = repairs.parse_or_placeholder(bundle.root_schematic());
173        definition_by_path.insert(root.source_path.clone(), 0);
174        definitions.push(root);
175        for source in bundle.sources() {
176            if source.kind() != SourceKind::Schematic || source.path() == root_path {
177                continue;
178            }
179            let definition = repairs.parse_or_placeholder(source);
180            definition_by_path.insert(definition.source_path.clone(), definitions.len());
181            definitions.push(definition);
182        }
183        let parse_definitions_ns = elapsed_ns(definitions_started);
184        Self::assemble_definitions(
185            bundle,
186            Assembly {
187                definitions,
188                definition_by_path,
189                repairs,
190            },
191            profile,
192            parse_definitions_ns,
193        )
194    }
195
196    fn assemble_definitions(
197        bundle: &SourceBundle,
198        assembly: Assembly,
199        profile: bool,
200        parse_definitions_ns: u64,
201    ) -> Result<(Self, SchematicBundleIndexBuildProfile), SourceBundleError> {
202        let occurrences_started = profile.then(std::time::Instant::now);
203        let mut assembly = assembly;
204        let occurrences = realize_occurrences(bundle, &mut assembly)?;
205        let Assembly {
206            definitions,
207            definition_by_path,
208            mut repairs,
209        } = assembly;
210        let realize_occurrences_ns = elapsed_ns(occurrences_started);
211        let indexes_started = profile.then(std::time::Instant::now);
212        let legacy_symbol_instance_by_path = index_bundle_legacy_instances(&definitions);
213        let identity_path = bundle
214            .project_path()
215            .unwrap_or_else(|| bundle.root_schematic_path());
216        let project_name = bundle
217            .project_path()
218            .map_or_else(String::new, portable_file_stem);
219        let project_file = portable_file_name(identity_path).to_owned();
220        let source_anchor = portable_parent(identity_path).to_owned();
221        // KiCad opens the schematic with default project settings when the
222        // project file cannot be read; so does the index, with a row.
223        let project_settings = match project_schematic_settings(bundle.project()) {
224            Ok(settings) => settings,
225            Err(error) => {
226                repairs.diagnostics.push(KiCadDiagnostic::new(
227                    KiCadDiagnosticCode::ProjectUnreadable,
228                    bundle.project_path().unwrap_or_default(),
229                    "project",
230                    None,
231                    format!("project file could not be read ({error}); its settings are left out"),
232                ));
233                ProjectSchematicSettings::default()
234            }
235        };
236        let root_sheet_name = root_sheet_name(bundle, &project_name);
237        let bundle_identity_sha256 = bundle.bundle_identity_sha256();
238        let assemble_indexes_ns = elapsed_ns(indexes_started);
239        let index = Self {
240            project_name,
241            root_sheet_name,
242            project_file,
243            source_anchor,
244            project_settings,
245            definitions,
246            definition_by_path,
247            occurrences,
248            legacy_symbol_instance_by_path,
249            bundle_identity_sha256,
250            repairs,
251        };
252        Ok((
253            index,
254            SchematicBundleIndexBuildProfile {
255                parse_definitions_ns,
256                realize_occurrences_ns,
257                assemble_indexes_ns,
258            },
259        ))
260    }
261
262    /// Diagnostics for files and sheets the index repaired instead of
263    /// stopping, in the stable shared order.
264    pub fn diagnostics(&self) -> Vec<crate::KiCadDiagnostic> {
265        crate::sorted_diagnostics(self.repairs.diagnostics.iter().cloned())
266    }
267
268    /// Sheet indices, in source order, that KiCad removes from the file at
269    /// `source_path` because they repeat an ancestor.
270    pub fn removed_sheets(&self, source_path: &str) -> impl Iterator<Item = usize> + '_ {
271        self.repairs
272            .removed_sheets
273            .get(source_path)
274            .into_iter()
275            .flatten()
276            .copied()
277    }
278
279    /// Files that could not be read or parsed and are empty pages, with the
280    /// parse error, by bundle path.
281    pub fn unreadable_sources(&self) -> impl Iterator<Item = (&str, &SourceBundleError)> {
282        self.repairs
283            .unreadable
284            .iter()
285            .map(|(path, error)| (path.as_str(), error))
286    }
287
288    /// Source text every stage reads for `path`: the bundle bytes, or the
289    /// index's repaired text (unique UUIDs, or an empty page).
290    pub fn source_text<'a>(
291        &'a self,
292        bundle: &'a SourceBundle,
293        path: &str,
294    ) -> Result<Option<&'a str>, SourceBundleError> {
295        self.repairs.source_text(bundle, path)
296    }
297
298    pub fn definitions(&self) -> impl ExactSizeIterator<Item = &SchematicDefinition> {
299        self.definitions.iter()
300    }
301    pub fn subpart_settings(&self) -> crate::SchematicSubpartSettings {
302        self.project_settings.subparts
303    }
304    pub fn project_bus_aliases(&self) -> &[crate::ProjectBusAlias] {
305        &self.project_settings.bus_aliases
306    }
307    pub fn definition(&self, source_path: &str) -> Option<&SchematicDefinition> {
308        self.definition_by_path
309            .get(source_path)
310            .map(|index| &self.definitions[*index])
311    }
312
313    pub fn occurrences(&self) -> impl ExactSizeIterator<Item = &SchematicOccurrence> {
314        self.occurrences.iter()
315    }
316
317    pub fn occurrence(&self, occurrence_index: usize) -> Option<&SchematicOccurrence> {
318        occurrence_index
319            .checked_sub(1)
320            .and_then(|index| self.occurrences.get(index))
321            .filter(|occurrence| occurrence.index == occurrence_index)
322    }
323
324    pub fn project_name(&self) -> &str {
325        &self.project_name
326    }
327
328    /// The root sheet's name as KiCad 10.0.8 loads it, which `${SHEETNAME}`
329    /// shows on the root page: see [`crate::ProjectView::root_sheet_name`].
330    pub fn root_sheet_name(&self) -> &str {
331        &self.root_sheet_name
332    }
333
334    pub(crate) fn bundle_belongs_to(&self, bundle: &SourceBundle) -> bool {
335        self.bundle_identity_sha256 == bundle.bundle_identity_sha256()
336    }
337
338    /// Portable filename used by the compiled-graph identity scope.
339    pub fn project_file(&self) -> &str {
340        &self.project_file
341    }
342
343    /// Return a source path relative to the project/top-schematic directory.
344    pub fn portable_source_path<'a>(&self, source_path: &'a str) -> &'a str {
345        if self.source_anchor.is_empty() {
346            return source_path;
347        }
348        source_path
349            .strip_prefix(&self.source_anchor)
350            .and_then(|value| value.strip_prefix('/'))
351            .unwrap_or(source_path)
352    }
353
354    pub fn effective_symbols(
355        &self,
356        occurrence_index: usize,
357        variant_name: Option<&str>,
358    ) -> Result<Vec<SchematicEffectiveSymbol>, SourceBundleError> {
359        let occurrence = occurrence_index
360            .checked_sub(1)
361            .and_then(|index| self.occurrences.get(index))
362            .filter(|occurrence| occurrence.index == occurrence_index)
363            .ok_or_else(|| {
364                SourceBundleError::new(
365                    SourceBundleErrorKind::Schematic,
366                    None,
367                    "schematic occurrence index is out of range",
368                )
369            })?;
370        let definition = self.definition(&occurrence.source_path).ok_or_else(|| {
371            SourceBundleError::new(
372                SourceBundleErrorKind::MissingSource,
373                Some(&occurrence.source_path),
374                "schematic occurrence definition is missing",
375            )
376        })?;
377        resolve_effective_symbols(
378            definition,
379            occurrence,
380            &self.project_name,
381            variant_name,
382            &self.definitions,
383            &self.legacy_symbol_instance_by_path,
384        )
385    }
386
387    pub fn symbol_terminals(
388        &self,
389        occurrence_index: usize,
390    ) -> Result<Vec<SchematicSymbolTerminal>, SourceBundleError> {
391        let occurrence = occurrence_index
392            .checked_sub(1)
393            .and_then(|index| self.occurrences.get(index))
394            .filter(|occurrence| occurrence.index == occurrence_index)
395            .ok_or_else(|| {
396                SourceBundleError::new(
397                    SourceBundleErrorKind::Schematic,
398                    None,
399                    "schematic occurrence index is out of range",
400                )
401            })?;
402        let definition = self.definition(&occurrence.source_path).ok_or_else(|| {
403            SourceBundleError::new(
404                SourceBundleErrorKind::MissingSource,
405                Some(&occurrence.source_path),
406                "schematic occurrence definition is missing",
407            )
408        })?;
409        let effective = self.effective_symbols(occurrence_index, None)?;
410        resolve_symbol_terminals(definition, occurrence, &effective)
411    }
412}
413
414fn elapsed_ns(started: Option<std::time::Instant>) -> u64 {
415    started.map_or(0, |started| {
416        u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)
417    })
418}
419
420/// KiCad's root sheet name for this bundle. A missing or unreadable project
421/// loads as KiCad's default project, which names no sheet. A top-level sheet
422/// file exists when the bundle holds it.
423fn root_sheet_name(bundle: &SourceBundle, project_name: &str) -> String {
424    let document = bundle
425        .project()
426        .and_then(|project| crate::ProjectDocument::from_reader(project.bytes()).ok());
427    let Some(document) = document else {
428        return crate::project::ROOT_SHEET_DEFAULT_NAME.to_owned();
429    };
430    let project_dir = bundle.project_path().map_or("", portable_parent);
431    let relative = |path: &str| -> String {
432        if project_dir.is_empty() {
433            path.to_owned()
434        } else {
435            path.strip_prefix(project_dir)
436                .and_then(|rest| rest.strip_prefix('/'))
437                .unwrap_or(path)
438                .to_owned()
439        }
440    };
441    let exists = |file: &str| {
442        let path = if project_dir.is_empty() {
443            file.to_owned()
444        } else {
445            format!("{project_dir}/{file}")
446        };
447        bundle.source(&path).ok().flatten().is_some()
448    };
449    document.view().root_sheet_name(
450        project_name,
451        &relative(bundle.root_schematic_path()),
452        exists,
453    )
454}
455
456/// Definition of a page with no objects.
457fn empty_definition(source_path: &str) -> SchematicDefinition {
458    SchematicDefinition {
459        source_path: source_path.to_owned(),
460        version: None,
461        generator: None,
462        generator_version: None,
463        uuid: None,
464        title_block: None,
465        sheets: Vec::new(),
466        root_page_instances: Vec::new(),
467        symbols: Vec::new(),
468        library_symbols: Vec::new(),
469        legacy_symbol_instances: Vec::new(),
470        wires: Vec::new(),
471        buses: Vec::new(),
472        bus_entries: Vec::new(),
473        bus_aliases: Vec::new(),
474        junctions: Vec::new(),
475        no_connects: Vec::new(),
476        labels: Vec::new(),
477        connectivity: SchematicConnectivity::default(),
478        legacy_symbol_instance_by_path: HashMap::new(),
479        library_symbol_by_key: HashMap::new(),
480        library_pin_owner_by_symbol: Vec::new(),
481    }
482}
483
484/// Definitions, their path index and the repairs made while reading them.
485struct Assembly {
486    definitions: Vec<SchematicDefinition>,
487    definition_by_path: HashMap<String, usize>,
488    repairs: IndexRepairs,
489}
490
491fn parse_schematic_definition_text(
492    text: &str,
493    source_path: &str,
494) -> Result<SchematicDefinition, SourceBundleError> {
495    parse_schematic_definition_common(text, source_path, false).map(|(definition, _)| definition)
496}
497
498fn parse_schematic_definition_for_import(
499    text: &str,
500    source_path: &str,
501) -> Result<(SchematicDefinition, Vec<crate::SchematicCarrierIssue>), SourceBundleError> {
502    parse_schematic_definition_common(text, source_path, true)
503}
504
505fn parse_schematic_definition_common(
506    text: &str,
507    source_path: &str,
508    import_read_only: bool,
509) -> Result<(SchematicDefinition, Vec<crate::SchematicCarrierIssue>), SourceBundleError> {
510    let spans = scan_form_spans(text, &schematic_selector())
511        .map_err(|error| schematic_error(source_path, error))?;
512    let roots = spans
513        .iter()
514        .filter(|span| span.depth == 0)
515        .collect::<Vec<_>>();
516    if roots.len() != 1 || roots[0].head.as_deref() != Some("kicad_sch") {
517        return Err(SourceBundleError::new(
518            SourceBundleErrorKind::Schematic,
519            Some(source_path),
520            "schematic source must contain exactly one kicad_sch root",
521        ));
522    }
523
524    let mut definition = empty_definition(source_path);
525    populate_schematic_definition(&mut definition, text, &spans, source_path)?;
526    definition.title_block = parse_title_block(text, &spans, source_path)?;
527    definition.symbols = parse_placed_symbols(text, source_path, &spans)?;
528    definition.library_symbols = parse_embedded_library_symbols(text, source_path, &spans)?;
529    definition.library_symbol_by_key =
530        index_library_symbols(&definition.library_symbols, source_path, usize::MAX)?;
531    definition.library_pin_owner_by_symbol = resolve_library_pin_owners(
532        &definition.library_symbols,
533        &definition.library_symbol_by_key,
534    );
535    definition.bus_aliases = parse_bus_aliases(text, source_path, &spans)?;
536    definition.legacy_symbol_instances = parse_legacy_symbol_instances(text, source_path, &spans)?;
537    for (index, instance) in definition.legacy_symbol_instances.iter().enumerate() {
538        let path = instance.path.trim_end_matches('/');
539        if !path.is_empty() {
540            definition
541                .legacy_symbol_instance_by_path
542                .entry(path.to_owned())
543                .or_insert(index);
544        }
545    }
546    let (carriers, carrier_issues) = if import_read_only {
547        crate::schematic_source::parse_source_carriers_for_import(text, source_path, &spans)?
548    } else {
549        (
550            parse_source_carriers(text, source_path, &spans)?,
551            Vec::new(),
552        )
553    };
554    definition.wires = carriers.wires;
555    definition.buses = carriers.buses;
556    definition.bus_entries = carriers.bus_entries;
557    definition.junctions = carriers.junctions;
558    definition.no_connects = carriers.no_connects;
559    definition.labels = carriers.labels;
560    definition.connectivity = carriers.connectivity;
561    if definition
562        .sheets
563        .iter()
564        .any(|sheet| sheet.sheet_file.is_empty())
565    {
566        return Err(SourceBundleError::new(
567            SourceBundleErrorKind::Schematic,
568            Some(source_path),
569            "hierarchical sheet is missing Sheetfile",
570        ));
571    }
572    Ok((definition, carrier_issues))
573}
574
575fn populate_schematic_definition(
576    definition: &mut SchematicDefinition,
577    text: &str,
578    spans: &[FormSpan],
579    source_path: &str,
580) -> Result<(), SourceBundleError> {
581    let mut current_sheet: Option<usize> = None;
582    let mut sheet_states = Vec::new();
583    let mut page_budget = PageInstanceBudget::default();
584    for span in spans {
585        match (span.depth, span.head.as_deref()) {
586            (1, Some("version")) => {
587                set_once_scalar(&mut definition.version, text, span, source_path)?
588            }
589            (1, Some("generator")) => {
590                set_once_scalar(&mut definition.generator, text, span, source_path)?
591            }
592            (1, Some("generator_version")) => {
593                set_once_scalar(&mut definition.generator_version, text, span, source_path)?
594            }
595            (1, Some("uuid")) => set_once_scalar(&mut definition.uuid, text, span, source_path)?,
596            (1, Some("sheet")) => {
597                definition.sheets.push(default_sheet());
598                sheet_states.push(SheetParseState::default());
599                current_sheet = Some(definition.sheets.len() - 1);
600            }
601            (1, Some("sheet_instances")) => {
602                definition.root_page_instances =
603                    page_instances(text, span, source_path, &mut page_budget)?;
604            }
605            (2, head) if span.path.get(1).is_some_and(|part| part == "sheet") => {
606                let Some(index) = current_sheet else {
607                    return Err(SourceBundleError::new(
608                        SourceBundleErrorKind::Schematic,
609                        Some(source_path),
610                        "selected sheet child has no owning sheet",
611                    ));
612                };
613                parse_sheet_child(
614                    &mut definition.sheets[index],
615                    &mut sheet_states[index],
616                    head,
617                    text,
618                    span,
619                    source_path,
620                    &mut page_budget,
621                )?;
622            }
623            _ => {}
624        }
625    }
626    Ok(())
627}
628
629#[allow(
630    clippy::too_many_arguments,
631    reason = "sheet parsing updates the owner, local state, and one source-wide page budget"
632)]
633fn parse_sheet_child(
634    sheet: &mut SchematicSheet,
635    state: &mut SheetParseState,
636    head: Option<&str>,
637    text: &str,
638    span: &FormSpan,
639    source_path: &str,
640    page_budget: &mut PageInstanceBudget,
641) -> Result<(), SourceBundleError> {
642    match head {
643        Some("uuid") => {
644            if state.uuid_seen {
645                return Err(SourceBundleError::new(
646                    SourceBundleErrorKind::Schematic,
647                    Some(source_path),
648                    "duplicate sheet uuid form",
649                ));
650            }
651            state.uuid_seen = true;
652            set_once_required_string(&mut sheet.uuid, text, span, source_path)?;
653        }
654        Some("property") => parse_sheet_property(sheet, state, text, span, source_path)?,
655        Some("pin") => {
656            sheet.pins.push(parse_sheet_pin(text, span, source_path)?);
657        }
658        Some("instances") => {
659            sheet.page_instances = page_instances(text, span, source_path, page_budget)?;
660        }
661        Some(head) => parse_sheet_flag(sheet, state, head, text, span, source_path)?,
662        None => {}
663    }
664    Ok(())
665}
666
667fn parse_sheet_property(
668    sheet: &mut SchematicSheet,
669    state: &mut SheetParseState,
670    text: &str,
671    span: &FormSpan,
672    source_path: &str,
673) -> Result<(), SourceBundleError> {
674    state.property_count = state.property_count.saturating_add(1);
675    let values = direct_scalar_strings(text, span, 2, source_path)?;
676    if values.len() < 2 {
677        return Err(SourceBundleError::new(
678            SourceBundleErrorKind::Schematic,
679            Some(source_path),
680            "sheet property requires a name and value",
681        ));
682    }
683    sheet.properties.push(SchematicSymbolProperty {
684        key: values[0].clone(),
685        value: values[1].clone(),
686    });
687    match values[0].as_str() {
688        "Sheetname" | "Sheet name" if !state.sheet_name_seen => {
689            state.sheet_name_seen = true;
690            sheet.sheet_name.clone_from(&values[1]);
691        }
692        "Sheetfile" | "Sheet file" if !state.sheet_file_seen => {
693            state.sheet_file_seen = true;
694            sheet.sheet_file.clone_from(&values[1]);
695        }
696        _ => {}
697    }
698    Ok(())
699}
700
701fn parse_sheet_flag(
702    sheet: &mut SchematicSheet,
703    state: &mut SheetParseState,
704    head: &str,
705    text: &str,
706    span: &FormSpan,
707    source_path: &str,
708) -> Result<(), SourceBundleError> {
709    match head {
710        "in_bom" => set_first_boolean(
711            &mut state.in_bom_seen,
712            &mut sheet.in_bom,
713            text,
714            span,
715            source_path,
716        ),
717        "on_board" => set_first_boolean(
718            &mut state.on_board_seen,
719            &mut sheet.on_board,
720            text,
721            span,
722            source_path,
723        ),
724        "dnp" => set_first_boolean(&mut state.dnp_seen, &mut sheet.dnp, text, span, source_path),
725        "exclude_from_sim" => set_first_boolean(
726            &mut state.exclude_from_sim_seen,
727            &mut sheet.exclude_from_sim,
728            text,
729            span,
730            source_path,
731        ),
732        _ => Ok(()),
733    }
734}
735
736fn set_first_boolean(
737    seen: &mut bool,
738    target: &mut bool,
739    text: &str,
740    span: &FormSpan,
741    source_path: &str,
742) -> Result<(), SourceBundleError> {
743    if !*seen {
744        *seen = true;
745        *target = direct_yes_no(text, span, source_path)?;
746    }
747    Ok(())
748}
749
750fn set_once_scalar(
751    target: &mut Option<String>,
752    source: &str,
753    span: &FormSpan,
754    source_path: &str,
755) -> Result<(), SourceBundleError> {
756    if target.is_some() {
757        return Err(SourceBundleError::new(
758            SourceBundleErrorKind::Schematic,
759            Some(source_path),
760            format!(
761                "duplicate {} form",
762                span.head.as_deref().unwrap_or("scalar")
763            ),
764        ));
765    }
766    let values = direct_scalar_strings(source, span, 1, source_path)?;
767    let value = values.into_iter().next().ok_or_else(|| {
768        SourceBundleError::new(
769            SourceBundleErrorKind::Schematic,
770            Some(source_path),
771            format!(
772                "{} form is missing its value",
773                span.head.as_deref().unwrap_or("scalar")
774            ),
775        )
776    })?;
777    *target = Some(value);
778    Ok(())
779}
780
781fn set_once_required_string(
782    target: &mut String,
783    source: &str,
784    span: &FormSpan,
785    source_path: &str,
786) -> Result<(), SourceBundleError> {
787    if !target.is_empty() {
788        return Err(SourceBundleError::new(
789            SourceBundleErrorKind::Schematic,
790            Some(source_path),
791            format!(
792                "duplicate {} form",
793                span.head.as_deref().unwrap_or("scalar")
794            ),
795        ));
796    }
797    let values = direct_scalar_strings(source, span, 1, source_path)?;
798    *target = values.into_iter().next().ok_or_else(|| {
799        SourceBundleError::new(
800            SourceBundleErrorKind::Schematic,
801            Some(source_path),
802            format!(
803                "{} form is missing its value",
804                span.head.as_deref().unwrap_or("scalar")
805            ),
806        )
807    })?;
808    Ok(())
809}
810
811fn schematic_selector() -> Selector {
812    let paths = [
813        &["kicad_sch"][..],
814        &["kicad_sch", "version"],
815        &["kicad_sch", "generator"],
816        &["kicad_sch", "generator_version"],
817        &["kicad_sch", "uuid"],
818        &["kicad_sch", "title_block"],
819        &["kicad_sch", "title_block", "title"],
820        &["kicad_sch", "title_block", "date"],
821        &["kicad_sch", "title_block", "rev"],
822        &["kicad_sch", "title_block", "company"],
823        &["kicad_sch", "title_block", "comment"],
824        &["kicad_sch", "sheet"],
825        &["kicad_sch", "sheet", "uuid"],
826        &["kicad_sch", "sheet", "property"],
827        &["kicad_sch", "sheet", "in_bom"],
828        &["kicad_sch", "sheet", "on_board"],
829        &["kicad_sch", "sheet", "dnp"],
830        &["kicad_sch", "sheet", "exclude_from_sim"],
831        &["kicad_sch", "sheet", "pin"],
832        &["kicad_sch", "sheet", "instances"],
833        &["kicad_sch", "sheet_instances"],
834        &["kicad_sch", "wire"],
835        &["kicad_sch", "bus"],
836        &["kicad_sch", "bus_entry"],
837        &["kicad_sch", "bus_alias"],
838        &["kicad_sch", "junction"],
839        &["kicad_sch", "no_connect"],
840        &["kicad_sch", "label"],
841        &["kicad_sch", "global_label"],
842        &["kicad_sch", "hierarchical_label"],
843        &["kicad_sch", "symbol"],
844        &["kicad_sch", "lib_symbols"],
845        &["kicad_sch", "symbol_instances"],
846    ]
847    .into_iter()
848    .map(|path| path.iter().map(|part| (*part).to_owned()).collect())
849    .collect::<BTreeSet<Vec<String>>>();
850    Selector {
851        paths: Some(paths),
852        min_depth: Some(0),
853        max_depth: Some(2),
854        ..Selector::default()
855    }
856}
857
858fn page_instances(
859    text: &str,
860    span: &FormSpan,
861    source_path: &str,
862    budget: &mut PageInstanceBudget,
863) -> Result<Vec<SchematicPageInstance>, SourceBundleError> {
864    let form = span
865        .text(text)
866        .map_err(|error| schematic_error(source_path, error))?;
867    let mut lexer = Lexer::new(form);
868    let mut expecting_head = false;
869    let mut current_path = None;
870    let mut expecting_path_value = false;
871    let mut expecting_page_value = false;
872    let mut instances = Vec::new();
873    while let Some(token) = lexer
874        .next()
875        .transpose()
876        .map_err(|error| schematic_error(source_path, error))?
877    {
878        match token.kind {
879            TokenKind::Left => {
880                expecting_head = true;
881                expecting_path_value = false;
882                expecting_page_value = false;
883            }
884            TokenKind::Right => {
885                expecting_head = false;
886                expecting_path_value = false;
887                expecting_page_value = false;
888            }
889            _ if expecting_head => {
890                let head = decoded(token);
891                expecting_path_value = head == "path";
892                expecting_page_value = head == "page";
893                expecting_head = false;
894            }
895            _ if expecting_path_value => {
896                current_path = Some(decoded(token).into_owned());
897                expecting_path_value = false;
898            }
899            _ if expecting_page_value => {
900                let value = decoded(token);
901                expecting_page_value = false;
902                let Some(page_number) = value.parse().ok() else {
903                    continue;
904                };
905                let path = current_path.clone().unwrap_or_default();
906                budget.charge(&path, source_path)?;
907                instances.push(SchematicPageInstance { path, page_number });
908            }
909            _ => {}
910        }
911    }
912    Ok(instances)
913}
914
915#[derive(Default)]
916struct PageInstanceBudget {
917    count: usize,
918    path_bytes: usize,
919}
920
921impl PageInstanceBudget {
922    fn charge(&mut self, path: &str, source_path: &str) -> Result<(), SourceBundleError> {
923        self.count = self
924            .count
925            .checked_add(1)
926            .ok_or_else(|| schematic_limit(source_path, "sheet page instance count overflowed"))?;
927        self.path_bytes = self.path_bytes.checked_add(path.len()).ok_or_else(|| {
928            schematic_limit(source_path, "sheet page instance path bytes overflowed")
929        })?;
930        Ok(())
931    }
932}
933
934fn direct_yes_no(
935    source: &str,
936    span: &FormSpan,
937    source_path: &str,
938) -> Result<bool, SourceBundleError> {
939    match direct_scalar_strings(source, span, 1, source_path)?
940        .first()
941        .map(String::as_str)
942    {
943        Some("yes") => Ok(true),
944        Some("no") => Ok(false),
945        _ => Err(SourceBundleError::new(
946            SourceBundleErrorKind::Schematic,
947            Some(source_path),
948            "schematic boolean requires yes or no",
949        )),
950    }
951}
952
953fn direct_scalar_strings(
954    source: &str,
955    span: &FormSpan,
956    maximum: usize,
957    source_path: &str,
958) -> Result<Vec<String>, SourceBundleError> {
959    let text = span
960        .text(source)
961        .map_err(|error| schematic_error(source_path, error))?;
962    let mut lexer = Lexer::new(text);
963    let left = next_token(&mut lexer, source_path)?;
964    let head = next_token(&mut lexer, source_path)?;
965    if left.kind != TokenKind::Left || head.kind != TokenKind::Atom {
966        return Err(SourceBundleError::new(
967            SourceBundleErrorKind::Schematic,
968            Some(source_path),
969            "selected form has an invalid header",
970        ));
971    }
972    let mut depth = 1_usize;
973    let mut values = Vec::new();
974    for token in lexer {
975        let token = token.map_err(|error| schematic_error(source_path, error))?;
976        if collect_direct_scalar(token, &mut depth, &mut values, maximum, source_path)? {
977            break;
978        }
979    }
980    Ok(values)
981}
982
983fn collect_direct_scalar(
984    token: Token<'_>,
985    depth: &mut usize,
986    values: &mut Vec<String>,
987    maximum: usize,
988    source_path: &str,
989) -> Result<bool, SourceBundleError> {
990    match token.kind {
991        TokenKind::Left => *depth = depth.saturating_add(1),
992        TokenKind::Right => {
993            *depth = depth.saturating_sub(1);
994            return Ok(*depth == 0);
995        }
996        _ if *depth == 1 => push_direct_scalar(token, values, maximum, source_path)?,
997        _ => {}
998    }
999    Ok(false)
1000}
1001
1002fn push_direct_scalar(
1003    token: Token<'_>,
1004    values: &mut Vec<String>,
1005    _maximum: usize,
1006    _source_path: &str,
1007) -> Result<(), SourceBundleError> {
1008    let value = decoded(token);
1009    values.push(value.into_owned());
1010    Ok(())
1011}
1012
1013fn next_token<'a>(
1014    lexer: &mut Lexer<'a>,
1015    source_path: &str,
1016) -> Result<Token<'a>, SourceBundleError> {
1017    lexer
1018        .next()
1019        .transpose()
1020        .map_err(|error| schematic_error(source_path, error))?
1021        .ok_or_else(|| {
1022            SourceBundleError::new(
1023                SourceBundleErrorKind::Schematic,
1024                Some(source_path),
1025                "selected form ended before its header",
1026            )
1027        })
1028}
1029
1030fn decoded(token: Token<'_>) -> Cow<'_, str> {
1031    if token.kind == TokenKind::QuotedString {
1032        Cow::Owned(decode_quoted(token.lexeme))
1033    } else {
1034        Cow::Borrowed(token.lexeme)
1035    }
1036}
1037
1038fn schematic_error(path: &str, error: crate::Error) -> SourceBundleError {
1039    let kind = if error.kind == crate::ErrorKind::ResourceLimit {
1040        SourceBundleErrorKind::ResourceLimit
1041    } else {
1042        SourceBundleErrorKind::Schematic
1043    };
1044    SourceBundleError::new(kind, Some(path), error.to_string())
1045}
1046
1047fn schematic_limit(path: &str, message: impl Into<String>) -> SourceBundleError {
1048    SourceBundleError::new(SourceBundleErrorKind::ResourceLimit, Some(path), message)
1049}