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

kicad_monkey_core/
assembly_variant.rs

1//! Captured, exact selected-variant evidence; no saved Design/PCB carrier.
2
3use super::SchematicBundleIndex;
4use crate::assembly_variant_reader::{self as reader, KiCadAuthoredVariant, KiCadVariantInstance};
5use crate::{
6    PcbBoardVariant, PcbFamily, PcbView, ProjectDocument, ProjectVariant, SchematicEffectiveSymbol,
7    SourceBundle, SourceBundleError,
8};
9use sha2::{Digest, Sha256};
10use std::collections::BTreeMap;
11
12#[path = "assembly_variant_schematic.rs"]
13mod schematic;
14
15pub(crate) fn schematic_variant_evidence(
16    index: &SchematicBundleIndex,
17    bundle: &SourceBundle,
18    name: &str,
19) -> Result<(Vec<KiCadVariantSymbol>, Vec<KiCadVariantDiagnostic>), SourceBundleError> {
20    let mut diagnostics = Vec::new();
21    let (symbols, _) = schematic::resolve(index, bundle, name, true, &mut diagnostics)?;
22    Ok((symbols, diagnostics))
23}
24#[cfg(test)]
25#[path = "assembly_variant_tests.rs"]
26mod tests;
27
28/// Scoped Source completeness; incomplete evidence never mutates physical PCB data.
29#[derive(Clone, Debug, Eq, PartialEq)]
30pub struct KiCadVariantDiagnostic {
31    pub blocking: bool,
32    pub code: &'static str,
33    pub source_key: String,
34    pub reference: Option<String>,
35    pub message: String,
36}
37
38/// One occurrence's effective flags plus exact authored symbol override evidence.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct KiCadVariantSymbol {
41    pub occurrence_index: usize,
42    pub symbol_index: usize,
43    pub source_key: String,
44    pub effective: SchematicEffectiveSymbol,
45    pub instance: Option<KiCadVariantInstance>,
46    pub authored: Option<KiCadAuthoredVariant>,
47    pub qualified: bool,
48}
49
50/// Actual sheet-instance evidence; fields belong to this sheet, not its descendants.
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct KiCadVariantSheet {
53    pub occurrence_index: usize,
54    pub source_key: String,
55    pub instance: Option<KiCadVariantInstance>,
56    pub authored: Option<KiCadAuthoredVariant>,
57    pub qualified: bool,
58}
59
60/// Native board effective exclusions and DNP, independent of schematic flags.
61#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct KiCadVariantFootprint {
63    pub footprint_index: usize,
64    pub footprint_uuid: Option<String>,
65    pub source_key: String,
66    pub dnp: bool,
67    pub in_bom: bool,
68    pub in_pos_files: bool,
69    pub authored: Option<KiCadAuthoredVariant>,
70    pub qualified: bool,
71}
72
73/// Private captured-source binding, exact project catalog, and immutable selected evidence.
74#[derive(Clone, Debug)]
75pub struct KiCadAssemblyVariantContext {
76    name: String,
77    selected: Option<ProjectVariant>,
78    project_path: String,
79    catalog: Vec<ProjectVariant>,
80    board_catalog: Vec<PcbBoardVariant>,
81    bundle_digest: [u8; 32],
82    board_digest: [u8; 32],
83    symbols: Vec<KiCadVariantSymbol>,
84    sheets: Vec<KiCadVariantSheet>,
85    footprints: Vec<KiCadVariantFootprint>,
86    diagnostics: Vec<KiCadVariantDiagnostic>,
87}
88
89impl KiCadAssemblyVariantContext {
90    pub fn name(&self) -> &str {
91        &self.name
92    }
93    pub fn selected(&self) -> Option<&ProjectVariant> {
94        self.selected.as_ref()
95    }
96    pub fn project_path(&self) -> &str {
97        &self.project_path
98    }
99    pub fn catalog(&self) -> &[ProjectVariant] {
100        &self.catalog
101    }
102    pub fn board_catalog(&self) -> &[PcbBoardVariant] {
103        &self.board_catalog
104    }
105    pub fn symbols(&self) -> &[KiCadVariantSymbol] {
106        &self.symbols
107    }
108    pub fn sheets(&self) -> &[KiCadVariantSheet] {
109        &self.sheets
110    }
111    pub fn footprints(&self) -> &[KiCadVariantFootprint] {
112        &self.footprints
113    }
114    pub fn diagnostics(&self) -> &[KiCadVariantDiagnostic] {
115        &self.diagnostics
116    }
117    pub fn complete(&self) -> bool {
118        self.selected.is_some() && !self.diagnostics.iter().any(|row| row.blocking)
119    }
120    pub fn matches_sources(&self, bundle: &SourceBundle, board_source: &str) -> bool {
121        self.bundle_digest == bundle.bundle_identity_sha256()
122            && self.board_digest == <[u8; 32]>::from(Sha256::digest(board_source.as_bytes()))
123    }
124}
125
126impl SchematicBundleIndex {
127    /// Resolve one exact named project variant from the same captured bundle and
128    /// acquired board families. Unknown/ambiguous scopes remain explicit diagnostics.
129    #[allow(
130        clippy::too_many_lines,
131        reason = "assembly variant resolver validates project variant rules against board footprints explicitly"
132    )]
133    pub fn selected_assembly_variant_context(
134        &self,
135        bundle: &SourceBundle,
136        board: &PcbView<'_>,
137        name: &str,
138    ) -> Result<KiCadAssemblyVariantContext, SourceBundleError> {
139        if self.bundle_identity_sha256 != bundle.bundle_identity_sha256() {
140            return Err(reader::error(
141                bundle.root_schematic_path(),
142                "variant index belongs to a different source bundle",
143            ));
144        }
145        if name.is_empty() {
146            return Err(reader::error(
147                bundle.root_schematic_path(),
148                "selected variant context requires a nonempty named selection",
149            ));
150        }
151        if ![
152            PcbFamily::Footprints,
153            PcbFamily::FootprintProperties,
154            PcbFamily::Variants,
155        ]
156        .iter()
157        .all(|family| board.selection().contains(*family))
158        {
159            return Err(reader::error(
160                bundle.root_schematic_path(),
161                "variant context requires acquired footprint, property and variant families",
162            ));
163        }
164        let project = bundle.project().ok_or_else(|| {
165            reader::error(
166                bundle.root_schematic_path(),
167                "named variant requires its project source",
168            )
169        })?;
170        let document = ProjectDocument::from_reader(project.bytes())
171            .map_err(|fault| reader::error(project.path(), fault.to_string()))?;
172        let catalog = document
173            .view()
174            .variants()
175            .map_err(|fault| reader::error(project.path(), fault.to_string()))?;
176        let selected = catalog
177            .iter()
178            .filter(|variant| variant.name == name)
179            .collect::<Vec<_>>();
180        let mut diagnostics = Vec::new();
181        let board_catalog = board
182            .variants()
183            .collect::<Result<Vec<_>, _>>()
184            .map_err(|fault| reader::error("PCB", fault.to_string()))?;
185        let board_matches = board_catalog
186            .iter()
187            .filter(|entry| entry.name == name)
188            .count();
189        if board_matches > 1 {
190            issue(
191                &mut diagnostics,
192                true,
193                "variant.board_catalog_ambiguous",
194                "PCB",
195                None,
196                "Selected board catalog has duplicate named entries",
197            );
198        }
199        if !board_catalog.is_empty() && board_matches == 0 {
200            issue(
201                &mut diagnostics,
202                false,
203                "variant.board_catalog_absent",
204                "PCB",
205                None,
206                "Selected project variant is absent from the board catalog; missing footprint clauses inherit native base state",
207            );
208        }
209        let selected = match selected.as_slice() {
210            [selected] => Some((*selected).clone()),
211            _ => {
212                issue(
213                    &mut diagnostics,
214                    true,
215                    "variant.catalog_selection",
216                    project.path(),
217                    None,
218                    "Requested variant requires one exact canonical project-catalog entry",
219                );
220                None
221            }
222        };
223        let (symbols, sheets) =
224            schematic::resolve(self, bundle, name, selected.is_some(), &mut diagnostics)?;
225        let footprints = self.footprint_variants(
226            board,
227            name,
228            selected.is_some() && board_matches < 2,
229            &mut diagnostics,
230        )?;
231        Ok(KiCadAssemblyVariantContext {
232            name: name.into(),
233            selected,
234            project_path: project.path().into(),
235            catalog,
236            board_catalog,
237            bundle_digest: self.bundle_identity_sha256,
238            board_digest: Sha256::digest(board.source().as_bytes()).into(),
239            symbols,
240            sheets,
241            footprints,
242            diagnostics,
243        })
244    }
245
246    fn footprint_variants(
247        &self,
248        board: &PcbView<'_>,
249        name: &str,
250        selected: bool,
251        diagnostics: &mut Vec<KiCadVariantDiagnostic>,
252    ) -> Result<Vec<KiCadVariantFootprint>, SourceBundleError> {
253        let mut output = Vec::new();
254        let forms = board
255            .top_level_forms()
256            .filter(|span| span.head.as_deref() == Some("footprint"))
257            .map(|span| (span.range.start, span))
258            .collect::<BTreeMap<_, _>>();
259        for (index, footprint) in board.footprints().enumerate() {
260            let footprint = footprint.map_err(|fault| reader::error("PCB", fault.to_string()))?;
261            // The raw footprint span is matched by its exact Source-owned range, never refdes/order inference.
262            let span = forms
263                .get(&footprint.source_range.start)
264                .copied()
265                .filter(|span| span.range == footprint.source_range)
266                .ok_or_else(|| {
267                    reader::error("PCB", "variant footprint has no acquired source span")
268                })?;
269            let children = reader::children(board.source(), Some(span), "PCB")?;
270            let mut authored = Vec::new();
271            for form in children
272                .iter()
273                .filter(|form| form.head.as_deref() == Some("variant"))
274            {
275                let variant = reader::parse_variant(board.source(), form, "PCB", true)?;
276                if variant.name == name {
277                    authored.push(variant);
278                }
279            }
280            let key = format!(
281                "PCB@footprint:{index}@{}",
282                footprint.uuid.as_deref().unwrap_or("")
283            );
284            let (variant, qualified) = choose(
285                authored,
286                selected,
287                &key,
288                footprint.reference.as_deref(),
289                diagnostics,
290            );
291            let has = |attribute| footprint.attributes.iter().any(|value| value == attribute);
292            let flags = variant.as_ref().map(|variant| &variant.flags);
293            output.push(KiCadVariantFootprint {
294                footprint_index: index,
295                footprint_uuid: footprint.uuid,
296                source_key: key,
297                dnp: flags.and_then(|flags| flags.dnp).unwrap_or(has("dnp")),
298                in_bom: !flags
299                    .and_then(|flags| flags.exclude_from_bom)
300                    .unwrap_or(has("exclude_from_bom")),
301                in_pos_files: !flags
302                    .and_then(|flags| flags.exclude_from_pos_files)
303                    .unwrap_or(has("exclude_from_pos_files")),
304                authored: variant,
305                qualified,
306            });
307        }
308        Ok(output)
309    }
310}
311
312pub(super) fn issue(
313    diagnostics: &mut Vec<KiCadVariantDiagnostic>,
314    blocking: bool,
315    code: &'static str,
316    key: &str,
317    reference: Option<&str>,
318    message: &str,
319) {
320    diagnostics.push(KiCadVariantDiagnostic {
321        blocking,
322        code,
323        source_key: key.into(),
324        reference: reference.map(str::to_owned),
325        message: message.into(),
326    });
327}
328
329pub(super) fn choose(
330    variants: Vec<KiCadAuthoredVariant>,
331    selected: bool,
332    key: &str,
333    reference: Option<&str>,
334    diagnostics: &mut Vec<KiCadVariantDiagnostic>,
335) -> (Option<KiCadAuthoredVariant>, bool) {
336    let mut qualified = selected;
337    if variants.len() > 1 {
338        issue(
339            diagnostics,
340            true,
341            "variant.duplicate_override",
342            key,
343            reference,
344            "Selected scope has duplicate variant clauses",
345        );
346        qualified = false;
347    }
348    let variant = variants.into_iter().next();
349    if variant
350        .as_ref()
351        .is_some_and(|variant| !variant.unsupported_tokens.is_empty())
352    {
353        issue(
354            diagnostics,
355            true,
356            "variant.unsupported_semantics",
357            key,
358            reference,
359            "Selected variant contains unqualified semantic tokens",
360        );
361        qualified = false;
362    }
363    (variant.filter(|_| selected), qualified)
364}
365
366pub(super) fn normalized_bom(
367    literal: Option<bool>,
368    version: Option<&str>,
369    key: &str,
370    reference: Option<&str>,
371    diagnostics: &mut Vec<KiCadVariantDiagnostic>,
372) -> (Option<bool>, bool) {
373    let Some(literal) = literal else {
374        return (None, true);
375    };
376    match version.and_then(|value| value.parse::<u64>().ok()) {
377        Some(version) => (
378            Some(if version < 20_260_306 {
379                !literal
380            } else {
381                literal
382            }),
383            true,
384        ),
385        None => {
386            issue(
387                diagnostics,
388                true,
389                "variant.bom_version_unknown",
390                key,
391                reference,
392                "Variant in_bom interpretation requires the schematic's native file version",
393            );
394            (None, false)
395        }
396    }
397}