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

kicad_monkey_core/
schematic_compilation.rs

1//! Immutable base compilation with exact provider/source joins; not a wire format.
2
3use crate::compiled_schematic_graph::{build_graph_from_compiled, empty_graph};
4use crate::schematic_design::{SchematicCompiledDesign, build_schematic_compiled_design};
5use crate::{
6    KiCadDiagnostic, KiCadDiagnosticCode, KiCadNetlistComponent, ProjectDocument, ProjectView,
7    SchematicBundleIndex, SchematicDesignNetMember, SchematicDriverPriority, SchematicOccurrence,
8    SchematicPlacedSymbol, SchematicScalarDesignNetlist, SchematicWireDriverKind,
9    SchematicWireSubgraph, SourceBundle, SourceBundleError, SourceBundleErrorKind,
10};
11use kicad_monkey_contracts::generated::compiled_schematic_graph::CompiledSchematicGraphA0;
12
13mod bindings;
14mod page_plot;
15mod source_fields;
16pub use page_plot::{
17    KiCadCompiledPagePlot, KiCadDnpPresentation, KiCadPagePlotError, KiCadPagePlotOptions,
18    KiCadPageSource, KiCadPlotBlockRange, KiCadPlotSourceBinding, KiCadPlotTextSource,
19};
20
21/// Indices address only this compilation's retained index, not persistent model IDs.
22#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
23pub struct KiCadSymbolOccurrence {
24    pub occurrence_index: usize,
25    pub symbol_index: usize,
26}
27
28#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
29pub struct KiCadPhysicalPinIndex {
30    pub component_index: usize,
31    pub pin_index: usize,
32}
33
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct KiCadPhysicalPin {
36    pub number: String,
37    pub name: Option<String>,
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct KiCadCompiledComponent {
42    /// String fields use the existing provider materializer/merge policy. Use
43    /// fields for component parameters; properties also contains export synthesis.
44    pub facts: KiCadNetlistComponent,
45    pub sources: Vec<KiCadSymbolOccurrence>,
46    pub pins: Vec<KiCadPhysicalPin>,
47}
48
49/// Selected schematic assembly facts in the unchanged physical component order.
50/// Blocking source diagnostics keep facts unavailable; no PCB acquisition or
51/// alternate electrical compilation is implied by an assembly selection.
52#[derive(Clone, Debug)]
53pub struct KiCadSchematicVariant {
54    pub components: Option<Vec<KiCadNetlistComponent>>,
55    pub diagnostics: Vec<crate::KiCadVariantDiagnostic>,
56}
57
58#[derive(Clone, Debug, Eq, Hash, PartialEq)]
59pub enum KiCadNamingField {
60    LabelText {
61        source_path: String,
62        label_index: usize,
63    },
64    SheetPinName {
65        source_path: String,
66        sheet_index: usize,
67        pin_index: usize,
68    },
69    SymbolProperty {
70        source_path: String,
71        symbol_index: usize,
72        property_index: usize,
73    },
74}
75
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub struct KiCadNamingFieldView<'a> {
78    pub document_path: &'a str,
79    pub object_uuid: &'a str,
80    pub owner_uuid: Option<&'a str>,
81    pub field_name: &'a str,
82    pub raw_value: &'a str,
83}
84
85#[derive(Clone, Debug, Eq, PartialEq)]
86pub enum KiCadContactSource {
87    Pin {
88        symbol: KiCadSymbolOccurrence,
89        pin_number: String,
90        source_pin_uuid: Option<String>,
91    },
92    NamingField {
93        occurrence_index: usize,
94        field: KiCadNamingField,
95    },
96}
97
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct KiCadPageBinding {
100    pub graph_page_index: usize,
101    pub occurrence_index: usize,
102}
103#[derive(Clone, Debug, Eq, PartialEq)]
104pub struct KiCadBodyBinding {
105    pub graph_component_index: usize,
106    pub source: KiCadSymbolOccurrence,
107    pub component_index: Option<usize>,
108}
109#[derive(Clone, Debug, Eq, PartialEq)]
110pub struct KiCadContactBinding {
111    pub graph_terminal_index: usize,
112    pub source: KiCadContactSource,
113    pub physical_pin: Option<KiCadPhysicalPinIndex>,
114    pub no_connect: Option<bool>,
115}
116#[derive(Clone, Debug, Eq, PartialEq)]
117pub struct KiCadScalarTerminalBinding {
118    pub net_index: usize,
119    pub terminal_index: usize,
120    pub physical_pin: KiCadPhysicalPinIndex,
121}
122#[derive(Clone, Debug, Eq, PartialEq)]
123pub struct KiCadIslandBinding {
124    pub graph_local_net_index: usize,
125    pub member: SchematicDesignNetMember,
126    pub net_index: Option<usize>,
127}
128#[derive(Clone, Debug, Eq, PartialEq)]
129pub struct KiCadWireBinding {
130    pub member: SchematicDesignNetMember,
131    pub wire_index: usize,
132}
133#[derive(Clone, Debug, Eq, PartialEq)]
134pub struct KiCadNamingContribution {
135    pub member: SchematicDesignNetMember,
136    pub field: Option<KiCadNamingField>,
137    pub effective_text: String,
138    pub kind: SchematicWireDriverKind,
139    pub priority: SchematicDriverPriority,
140}
141#[derive(Clone, Debug, Eq, PartialEq)]
142pub struct KiCadNetNaming {
143    pub net_index: usize,
144    pub aliases: Vec<String>,
145}
146
147#[derive(Clone, Debug, Default, Eq, PartialEq)]
148pub struct KiCadCompilationBindings {
149    pub pages: Vec<KiCadPageBinding>,
150    pub bodies: Vec<KiCadBodyBinding>,
151    pub contacts: Vec<KiCadContactBinding>,
152    pub scalar_terminals: Vec<KiCadScalarTerminalBinding>,
153    pub islands: Vec<KiCadIslandBinding>,
154    pub wires: Vec<KiCadWireBinding>,
155    pub naming_contributions: Vec<KiCadNamingContribution>,
156    pub net_naming: Vec<KiCadNetNaming>,
157}
158
159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160pub enum KiCadCompilationIssueArea {
161    Components,
162    Terminals,
163    Sources,
164    NetClasses,
165    Variants,
166}
167#[derive(Clone, Debug, Eq, PartialEq)]
168pub struct KiCadCompilationIssue {
169    pub area: KiCadCompilationIssueArea,
170    pub occurrence_index: Option<usize>,
171    pub reason: String,
172}
173
174#[derive(Debug)]
175pub struct KiCadSchematicCompilation {
176    bundle: SourceBundle,
177    index: SchematicBundleIndex,
178    project: Option<ProjectDocument>,
179    compiled: SchematicCompiledDesign,
180    graph: CompiledSchematicGraphA0,
181    components: Vec<KiCadCompiledComponent>,
182    bindings: KiCadCompilationBindings,
183    issues: Vec<KiCadCompilationIssue>,
184    diagnostics: Vec<KiCadDiagnostic>,
185}
186
187impl KiCadSchematicCompilation {
188    pub fn build(bundle: SourceBundle) -> Result<Self, SourceBundleError> {
189        let index = SchematicBundleIndex::build(&bundle)?;
190        let mut diagnostics = index.diagnostics();
191        let project = project_or_defaults(&bundle, &index, &mut diagnostics);
192        let project_view = project.as_ref().map(ProjectDocument::view);
193        let parts = build_schematic_compiled_design(&index, 1, index.subpart_settings())
194            .and_then(|compiled| {
195                diagnostics.extend(compiled.alias_cycle_diagnostics(&index));
196                CompiledParts::build(&index, compiled, project_view)
197            })
198            .unwrap_or_else(|error| {
199                diagnostics.push(connectivity_not_compiled(&index, &error));
200                CompiledParts::unconnected(&index, project_view, &mut diagnostics)
201            });
202        diagnostics.extend(parts.diagnostics);
203        Ok(Self {
204            bundle,
205            index,
206            project,
207            compiled: parts.compiled,
208            graph: parts.graph,
209            components: parts.components,
210            bindings: parts.bindings,
211            issues: parts.issues,
212            diagnostics: crate::sorted_diagnostics(diagnostics),
213        })
214    }
215
216    /// Everything the compilation drew or compiled by a repair instead of
217    /// stopping, in the stable shared order. Page diagnostics are a subset.
218    pub fn diagnostics(&self) -> &[KiCadDiagnostic] {
219        &self.diagnostics
220    }
221
222    pub fn bundle(&self) -> &SourceBundle {
223        &self.bundle
224    }
225    pub fn index(&self) -> &SchematicBundleIndex {
226        &self.index
227    }
228    pub fn project(&self) -> Option<ProjectView<'_>> {
229        self.project.as_ref().map(ProjectDocument::view)
230    }
231    pub fn scalar(&self) -> &SchematicScalarDesignNetlist {
232        &self.compiled.netlist
233    }
234    pub fn graph(&self) -> &CompiledSchematicGraphA0 {
235        &self.graph
236    }
237    pub fn components(&self) -> &[KiCadCompiledComponent] {
238        &self.components
239    }
240    /// Resolve one exact catalogued variant using retained source evidence and
241    /// the native materializer. Result indices address self.components().
242    pub fn variant_components(
243        &self,
244        name: &str,
245    ) -> Result<KiCadSchematicVariant, SourceBundleError> {
246        let project = self
247            .project()
248            .ok_or_else(|| failure("variant requires a retained project"))?;
249        let catalog = project
250            .variants()
251            .map_err(|error| failure(&format!("variant catalog: {error}")))?;
252        if catalog
253            .iter()
254            .filter(|variant| variant.name == name)
255            .count()
256            != 1
257        {
258            return Err(failure("variant requires one exact catalog entry"));
259        }
260        let (symbols, diagnostics) =
261            crate::schematic_bundle::schematic_variant_evidence(&self.index, &self.bundle, name)?;
262        let components = if diagnostics.iter().any(|issue| issue.blocking) {
263            None
264        } else {
265            Some(crate::kicad_netlist::materialize_variant_components(
266                &self.index,
267                Some(project),
268                &self.components,
269                &symbols,
270            )?)
271        };
272        Ok(KiCadSchematicVariant {
273            components,
274            diagnostics,
275        })
276    }
277    pub fn bindings(&self) -> &KiCadCompilationBindings {
278        &self.bindings
279    }
280    pub fn issues(&self) -> &[KiCadCompilationIssue] {
281        &self.issues
282    }
283
284    pub fn symbol(
285        &self,
286        source: KiCadSymbolOccurrence,
287    ) -> Result<(&SchematicOccurrence, &SchematicPlacedSymbol), SourceBundleError> {
288        source_fields::symbol(&self.index, source)
289    }
290    pub fn subgraph(
291        &self,
292        member: SchematicDesignNetMember,
293    ) -> Result<&SchematicWireSubgraph, SourceBundleError> {
294        member
295            .occurrence_index
296            .checked_sub(1)
297            .and_then(|position| self.compiled.occurrences.get(position))
298            .filter(|row| row.occurrence_index == member.occurrence_index)
299            .and_then(|row| row.subgraphs.get(member.subgraph_index))
300            .ok_or_else(|| failure("compiled subgraph selector is out of range"))
301    }
302    pub fn naming_field(
303        &self,
304        field: &KiCadNamingField,
305    ) -> Result<KiCadNamingFieldView<'_>, SourceBundleError> {
306        source_fields::naming_field(&self.index, field)
307    }
308}
309
310/// What compiling the design's connectivity, components and bindings yields.
311struct CompiledParts {
312    compiled: SchematicCompiledDesign,
313    graph: CompiledSchematicGraphA0,
314    components: Vec<KiCadCompiledComponent>,
315    bindings: KiCadCompilationBindings,
316    issues: Vec<KiCadCompilationIssue>,
317    diagnostics: Vec<KiCadDiagnostic>,
318}
319
320impl CompiledParts {
321    fn build(
322        index: &SchematicBundleIndex,
323        compiled: SchematicCompiledDesign,
324        project: Option<ProjectView<'_>>,
325    ) -> Result<Self, SourceBundleError> {
326        let (graph, mut bindings, mut diagnostics) = build_graph_from_compiled(index, &compiled)?;
327        let mut issues = Vec::new();
328        let components = crate::kicad_netlist::build_complete_components(
329            index,
330            &compiled,
331            project,
332            &mut issues,
333            &mut diagnostics,
334        )?;
335        bindings::complete_bindings(
336            index,
337            &compiled,
338            &graph,
339            &components,
340            &mut bindings,
341            &mut issues,
342        )?;
343        Ok(Self {
344            compiled,
345            graph,
346            components,
347            bindings,
348            issues,
349            diagnostics,
350        })
351    }
352
353    /// The pages, hierarchy and components with no connectivity. When even that
354    /// structure does not compile, its error is reported and the parts keep no
355    /// graph, components or bindings. Pages plot from the index either way.
356    fn unconnected(
357        index: &SchematicBundleIndex,
358        project: Option<ProjectView<'_>>,
359        diagnostics: &mut Vec<KiCadDiagnostic>,
360    ) -> Self {
361        Self::build(index, SchematicCompiledDesign::unconnected(index), project).unwrap_or_else(
362            |error| {
363                diagnostics.push(structure_not_compiled(index, &error));
364                Self {
365                    compiled: SchematicCompiledDesign::unconnected(index),
366                    graph: empty_graph(),
367                    components: Vec::new(),
368                    bindings: KiCadCompilationBindings::default(),
369                    issues: Vec::new(),
370                    diagnostics: Vec::new(),
371                }
372            },
373        )
374    }
375}
376
377fn connectivity_not_compiled(
378    index: &SchematicBundleIndex,
379    error: &SourceBundleError,
380) -> KiCadDiagnostic {
381    let root = index
382        .occurrences()
383        .next()
384        .map(|occurrence| occurrence.source_path.clone())
385        .unwrap_or_default();
386    KiCadDiagnostic::new(
387        KiCadDiagnosticCode::ConnectivityNotCompiled,
388        error.source_path.clone().unwrap_or(root),
389        "schematic",
390        None,
391        format!(
392            "connectivity was not compiled ({}); pages are drawn without nets",
393            error.message
394        ),
395    )
396}
397
398/// The second `connectivity_not_compiled` row: the structure without nets did
399/// not compile either, so components and the compiled graph are left out too.
400fn structure_not_compiled(
401    index: &SchematicBundleIndex,
402    error: &SourceBundleError,
403) -> KiCadDiagnostic {
404    let mut diagnostic = connectivity_not_compiled(index, error);
405    diagnostic.message = format!(
406        "the pages, hierarchy and components without nets were not compiled either ({}); \
407         components and the compiled graph are left out, and pages are drawn without them",
408        error.message
409    );
410    diagnostic
411}
412
413/// Parse the project; an unreadable project leaves its settings out, and the
414/// schematic compiles with KiCad's defaults.
415fn project_or_defaults(
416    bundle: &SourceBundle,
417    index: &SchematicBundleIndex,
418    diagnostics: &mut Vec<KiCadDiagnostic>,
419) -> Option<ProjectDocument> {
420    let source = bundle.project()?;
421    match ProjectDocument::from_reader(source.bytes()) {
422        Ok(project) => Some(project),
423        Err(error) => {
424            let reported = index
425                .diagnostics()
426                .iter()
427                .any(|row| row.code == KiCadDiagnosticCode::ProjectUnreadable);
428            if !reported {
429                diagnostics.push(KiCadDiagnostic::new(
430                    KiCadDiagnosticCode::ProjectUnreadable,
431                    source.path(),
432                    "project",
433                    None,
434                    format!("project file could not be read ({error}); its settings are left out"),
435                ));
436            }
437            None
438        }
439    }
440}
441
442pub(crate) fn failure(message: &str) -> SourceBundleError {
443    SourceBundleError::new(SourceBundleErrorKind::Schematic, None, message)
444}
445pub(crate) use source_fields::{label_field, power_field};
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    use serde_json::json;
452
453    const ROOT: &str = r#"(kicad_sch (uuid root)
454      (lib_symbols (symbol "Demo:One" (symbol "Demo:One_1_1"
455        (pin passive line (at 0 0 0) (name "P") (number "1")))))
456      (symbol (lib_id "Demo:One") (at 0 0 0) (uuid r1) (unit 1)
457        (property "Reference" "R1") (property "Value" "One") (pin "1" (uuid r1-pin)))
458      (wire (pts (xy 0 0) (xy 20 0)) (uuid w)))"#;
459
460    fn bundle() -> SourceBundle {
461        let manifest = serde_json::from_value(json!({
462            "type": "kicad_monkey.source_bundle_manifest",
463            "schema": "kicad_monkey.source_bundle_manifest.a0",
464            "version": "a0",
465            "root_schematic_path": "root.kicad_sch",
466            "sources": [{"path": "root.kicad_sch", "kind": "schematic", "slot": 0,
467                "source_bytes": ROOT.len().to_string()}],
468        }))
469        .unwrap();
470        SourceBundle::from_manifest(manifest, vec![ROOT.as_bytes().to_vec()]).unwrap()
471    }
472
473    /// A project file nested past `PROJECT_MAX_JSON_DEPTH` is unreadable: one
474    /// error row names the file, and the schematic compiles without it.
475    #[test]
476    fn over_deep_project_is_one_row_naming_the_file() {
477        let depth = crate::project::PROJECT_MAX_JSON_DEPTH + 88;
478        let project = format!("{}0{}", "{\"a\":".repeat(depth), "}".repeat(depth));
479        let manifest = serde_json::from_value(json!({
480            "type": "kicad_monkey.source_bundle_manifest",
481            "schema": "kicad_monkey.source_bundle_manifest.a0",
482            "version": "a0",
483            "root_schematic_path": "root.kicad_sch",
484            "project_path": "root.kicad_pro",
485            "sources": [
486                {"path": "root.kicad_pro", "kind": "project", "slot": 0,
487                    "source_bytes": project.len().to_string()},
488                {"path": "root.kicad_sch", "kind": "schematic", "slot": 1,
489                    "source_bytes": ROOT.len().to_string()},
490            ],
491        }))
492        .unwrap();
493        let bundle = SourceBundle::from_manifest(
494            manifest,
495            vec![project.into_bytes(), ROOT.as_bytes().to_vec()],
496        )
497        .expect("the bundle keeps an unreadable project");
498        let compilation = KiCadSchematicCompilation::build(bundle)
499            .expect("the schematic compiles without its project");
500        let rows = compilation
501            .diagnostics()
502            .iter()
503            .filter(|row| row.code == KiCadDiagnosticCode::ProjectUnreadable)
504            .collect::<Vec<_>>();
505        assert_eq!(rows.len(), 1);
506        assert_eq!(rows[0].source_path, "root.kicad_pro");
507        assert_eq!(rows[0].severity(), crate::KiCadDiagnosticSeverity::Error);
508        assert!(
509            rows[0].message.contains("stack-safety"),
510            "{}",
511            rows[0].message
512        );
513        assert_eq!(compilation.index().occurrences().len(), 1);
514    }
515
516    /// When connectivity does not compile, the compilation keeps its pages,
517    /// hierarchy and components without nets, and reports one error that is
518    /// not a drawing diagnostic. Real inputs still reach this path: a symbol
519    /// whose pins share a number on different nets, which the compiled graph
520    /// refuses (the Rust-only known limit in
521    /// `docs/design/native-retained-schematic-compilation.md`).
522    #[test]
523    fn unconnected_parts_keep_pages_and_components_without_nets() {
524        let bundle = bundle();
525        let index = SchematicBundleIndex::build(&bundle).unwrap();
526        let mut diagnostics = Vec::new();
527        let parts = CompiledParts::unconnected(&index, None, &mut diagnostics);
528        assert!(diagnostics.is_empty());
529        assert!(parts.compiled.netlist.nets.is_empty());
530        assert!(parts.graph.local_net_occurrences.is_empty());
531        assert_eq!(parts.graph.page_occurrences.len(), 1);
532        assert_eq!(parts.components.len(), 1);
533        let diagnostic = connectivity_not_compiled(&index, &failure("refused"));
534        assert_eq!(
535            diagnostic.code,
536            KiCadDiagnosticCode::ConnectivityNotCompiled
537        );
538        assert_eq!(diagnostic.severity(), crate::KiCadDiagnosticSeverity::Error);
539        assert_eq!(diagnostic.source_path, "root.kicad_sch");
540        assert!(diagnostic.message.contains("refused"));
541        assert!(!diagnostic.code.concerns_drawing());
542        // When the structure without nets does not compile either, that error
543        // is a second row instead of being discarded.
544        let structure = structure_not_compiled(&index, &failure("refused again"));
545        assert_eq!(structure.code, KiCadDiagnosticCode::ConnectivityNotCompiled);
546        assert!(
547            structure
548                .message
549                .contains("were not compiled either (refused again)"),
550            "{}",
551            structure.message
552        );
553    }
554}