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

kicad_monkey_core/
schematic_effective.rs

1use crate::{
2    SchematicDefinition, SchematicLegacySymbolInstance, SchematicOccurrence, SchematicPlacedSymbol,
3    SchematicSymbolInstance, SourceBundleError, SourceBundleErrorKind,
4};
5use std::collections::{BTreeMap, HashMap};
6
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct SchematicEffectiveSymbol {
9    pub symbol_index: usize,
10    pub uuid: String,
11    pub lib_id: String,
12    pub reference: String,
13    pub value: String,
14    pub unit: i64,
15    pub convert: i64,
16    pub dnp: bool,
17    pub exclude_from_sim: bool,
18    pub in_bom: bool,
19    pub on_board: bool,
20    pub in_pos_files: bool,
21    pub fields: BTreeMap<String, String>,
22    /// Authored declaration order; effective values remain owned by `fields`.
23    pub field_order: Vec<String>,
24    pub instance_project: Option<String>,
25    pub instance_path: Option<String>,
26}
27
28impl SchematicDefinition {
29    /// Resolve one placed record for a standalone base-design occurrence.
30    /// Selection is local to this parsed definition: no files are discovered or
31    /// opened. Omitted paths use the native root addresses (/{root UUID}, /).
32    /// Modern project/path selection and legacy fallbacks share the bundle
33    /// resolver. A bad/ambiguous record errors locally; its neighbors remain
34    /// queryable. Named variant overrides are deliberately not applied here.
35    pub fn effective_symbol_base(
36        &self,
37        symbol_ordinal: usize,
38        project_name: &str,
39        occurrence_address: Option<&str>,
40        legacy_address: Option<&str>,
41    ) -> Result<Option<SchematicEffectiveSymbol>, SourceBundleError> {
42        let Some(symbol) = self.symbols.get(symbol_ordinal) else {
43            return Ok(None);
44        };
45        let root_address = format!(
46            "/{}",
47            self.uuid.as_deref().unwrap_or("root").trim_matches('/')
48        );
49        let occurrence = SchematicOccurrence {
50            index: 1,
51            source_path: self.source_path.clone(),
52            parent_index: None,
53            parent_sheet_index: None,
54            sheet_uuid: None,
55            sheet_name: "root".into(),
56            sheet_file: String::new(),
57            occurrence_address: occurrence_address.unwrap_or(&root_address).into(),
58            legacy_address: legacy_address.unwrap_or("/").into(),
59            human_address: "/".into(),
60            effective_in_bom: true,
61            effective_on_board: true,
62            effective_dnp: false,
63            effective_exclude_from_sim: false,
64        };
65        resolve_effective_symbol(
66            &occurrence,
67            project_name,
68            None,
69            symbol_ordinal,
70            symbol,
71            |path| self.legacy_symbol_instance(path),
72        )
73        .map(Some)
74    }
75}
76
77impl SchematicEffectiveSymbol {
78    /// Effective names in authored order, followed by additional effective fields.
79    /// Exact duplicate names keep their first position and existing last-value semantics.
80    pub fn field_names_in_source_order(&self) -> Vec<&str> {
81        let mut seen = std::collections::BTreeSet::new();
82        self.field_order
83            .iter()
84            .chain(self.fields.keys())
85            .filter(|name| self.fields.contains_key(*name) && seen.insert(name.as_str()))
86            .map(String::as_str)
87            .collect()
88    }
89}
90
91pub(crate) fn resolve_effective_symbols(
92    definition: &SchematicDefinition,
93    occurrence: &SchematicOccurrence,
94    project_name: &str,
95    variant_name: Option<&str>,
96    definitions: &[SchematicDefinition],
97    legacy_index: &HashMap<String, (usize, usize)>,
98) -> Result<Vec<SchematicEffectiveSymbol>, SourceBundleError> {
99    definition
100        .symbols
101        .iter()
102        .enumerate()
103        .map(|(index, symbol)| {
104            resolve_effective_symbol(
105                occurrence,
106                project_name,
107                variant_name,
108                index,
109                symbol,
110                |path| {
111                    legacy_index
112                        .get(path)
113                        .and_then(|(definition_index, instance_index)| {
114                            definitions.get(*definition_index).and_then(|definition| {
115                                definition.legacy_symbol_instances.get(*instance_index)
116                            })
117                        })
118                },
119            )
120        })
121        .collect()
122}
123
124fn resolve_effective_symbol<'a>(
125    occurrence: &SchematicOccurrence,
126    project_name: &str,
127    variant_name: Option<&str>,
128    symbol_index: usize,
129    symbol: &SchematicPlacedSymbol,
130    legacy_lookup: impl FnOnce(&str) -> Option<&'a SchematicLegacySymbolInstance>,
131) -> Result<SchematicEffectiveSymbol, SourceBundleError> {
132    let modern = resolve_modern_instance(symbol, project_name, occurrence)?;
133    let legacy_path = legacy_symbol_path(&occurrence.legacy_address, &symbol.uuid);
134    let legacy = modern
135        .is_none()
136        .then(|| legacy_lookup(legacy_path.trim_end_matches('/')))
137        .flatten();
138    let mut fields = symbol
139        .properties
140        .iter()
141        .map(|property| (property.key.clone(), property.value.clone()))
142        .collect::<BTreeMap<_, _>>();
143    let mut field_order = symbol
144        .properties
145        .iter()
146        .map(|property| property.key.clone())
147        .collect::<Vec<_>>();
148    let variant = variant_name.and_then(|name| modern.and_then(|instance| instance.variant(name)));
149    if let Some(variant) = variant {
150        for field in &variant.fields {
151            if !field_order.contains(&field.name) {
152                field_order.push(field.name.clone());
153            }
154            fields.insert(field.name.clone(), field.value.clone());
155        }
156    }
157    let reference = modern
158        .map(|instance| instance.reference.as_str())
159        .filter(|reference| !reference.is_empty())
160        .or_else(|| {
161            legacy
162                .map(|instance| instance.reference.as_str())
163                .filter(|reference| !reference.is_empty())
164        })
165        .or_else(|| fields.get("Reference").map(String::as_str))
166        .unwrap_or_default()
167        .to_owned();
168    let unit = modern.map_or_else(
169        || legacy.map_or(symbol.unit, |instance| instance.unit),
170        |instance| instance.unit,
171    );
172    let dnp = variant.and_then(|value| value.dnp).unwrap_or(symbol.dnp);
173    let exclude_from_sim = variant
174        .and_then(|value| value.exclude_from_sim)
175        .unwrap_or(symbol.exclude_from_sim);
176    let in_bom = variant
177        .and_then(|value| value.in_bom)
178        .unwrap_or(symbol.in_bom);
179    let on_board = variant
180        .and_then(|value| value.on_board)
181        .unwrap_or(symbol.on_board);
182    let in_pos_files = variant
183        .and_then(|value| value.in_pos_files)
184        .unwrap_or(symbol.in_pos_files);
185    Ok(SchematicEffectiveSymbol {
186        symbol_index,
187        uuid: symbol.uuid.clone(),
188        lib_id: symbol.lib_id.clone(),
189        reference,
190        value: fields.get("Value").cloned().unwrap_or_default(),
191        unit,
192        convert: symbol.convert,
193        dnp: occurrence.effective_dnp || dnp,
194        exclude_from_sim: occurrence.effective_exclude_from_sim || exclude_from_sim,
195        in_bom: occurrence.effective_in_bom && in_bom,
196        on_board: occurrence.effective_on_board && on_board,
197        in_pos_files,
198        fields,
199        field_order,
200        instance_project: modern.map(|instance| instance.project.to_string()),
201        instance_path: modern.map(|instance| instance.path.clone()),
202    })
203}
204
205fn resolve_modern_instance<'a>(
206    symbol: &'a SchematicPlacedSymbol,
207    project_name: &str,
208    occurrence: &SchematicOccurrence,
209) -> Result<Option<&'a SchematicSymbolInstance>, SourceBundleError> {
210    for path in [&occurrence.occurrence_address, &occurrence.legacy_address] {
211        if let Some(instance) = exact_instance(symbol, project_name, path)? {
212            return Ok(Some(instance));
213        }
214    }
215    let target = occurrence.legacy_address.trim_end_matches('/');
216    if !target.is_empty() {
217        match symbol.compatible_instance_for_project(project_name, target) {
218            Ok(Some(instance)) => return Ok(Some(instance)),
219            Ok(None) => {}
220            Err(error) => return Err(ambiguity_error(occurrence, error.matches)),
221        }
222    }
223    Ok(symbol.first_instance_for_project(project_name))
224}
225
226fn exact_instance<'a>(
227    symbol: &'a SchematicPlacedSymbol,
228    project_name: &str,
229    path: &str,
230) -> Result<Option<&'a SchematicSymbolInstance>, SourceBundleError> {
231    match symbol.instance_for_project(project_name, path) {
232        Ok(Some(instance)) => Ok(Some(instance)),
233        Ok(None) => symbol
234            .unique_instance_for_path(path)
235            .map_err(|error| lookup_error(path, error.matches)),
236        Err(error) => Err(lookup_error(path, error.matches)),
237    }
238}
239
240fn legacy_symbol_path(sheet_path: &str, symbol_uuid: &str) -> String {
241    let sheet = sheet_path.trim_end_matches('/');
242    if symbol_uuid.is_empty() {
243        sheet.to_owned()
244    } else if sheet.is_empty() {
245        format!("/{symbol_uuid}")
246    } else {
247        format!("{sheet}/{symbol_uuid}")
248    }
249}
250
251fn lookup_error(path: &str, matches: usize) -> SourceBundleError {
252    SourceBundleError::new(
253        SourceBundleErrorKind::Schematic,
254        None,
255        format!("symbol instance path {path:?} is ambiguous across {matches} records"),
256    )
257}
258
259fn ambiguity_error(occurrence: &SchematicOccurrence, matches: usize) -> SourceBundleError {
260    SourceBundleError::new(
261        SourceBundleErrorKind::Schematic,
262        Some(&occurrence.source_path),
263        format!("symbol instance suffix match is ambiguous across {matches} records"),
264    )
265}