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

kicad_monkey_core/
schematic_design.rs

1use crate::schematic_netlist::name_schematic_subgraph;
2use crate::{
3    KiCadDiagnostic, KiCadDiagnosticCode, SchematicBundleIndex, SchematicBusDriverKind,
4    SchematicDriverPriority, SchematicPinDriver, SchematicPoint, SchematicSubpartSettings,
5    SchematicWireDriverKind, SchematicWireSubgraph, SourceBundleError, SourceBundleErrorKind,
6};
7use std::collections::{HashMap, HashSet};
8mod bus_promotion;
9mod driver_choice;
10mod driver_storage;
11mod occurrence_compile;
12mod sheet_pin_targets;
13mod types;
14mod union_find;
15use bus_promotion::{BusPromotion, collect_design_bus_aliases, promote_bus_members};
16use driver_choice::{DriverChoice, checked_join, consider_choice, sheet_depth};
17use driver_storage::merged_driver_shape;
18use occurrence_compile::{DesignCompilationBudget, compile_design_occurrence};
19use sheet_pin_targets::SheetPinTargetIndex;
20pub use types::{
21    SchematicDesignNet, SchematicDesignNetEndpoint, SchematicDesignNetMember,
22    SchematicDesignNetTerminal, SchematicHierarchyNetBinding, SchematicScalarDesignNetlist,
23};
24use union_find::UnionFind;
25
26fn append_unique(target: &mut Vec<String>, source: &[String]) {
27    let additions = {
28        let mut seen = target.iter().map(String::as_str).collect::<HashSet<_>>();
29        source
30            .iter()
31            .filter(|value| !value.is_empty() && seen.insert(value.as_str()))
32            .cloned()
33            .collect::<Vec<_>>()
34    };
35    target.extend(additions);
36}
37
38fn nonempty<'a>(preferred: &'a str, fallback: &'a str) -> &'a str {
39    if preferred.is_empty() {
40        fallback
41    } else {
42        preferred
43    }
44}
45
46fn endpoint(
47    role: &str,
48    element_id: &str,
49    object_id: &str,
50    name: &str,
51    source_sheet: &str,
52    point: SchematicPoint,
53) -> SchematicDesignNetEndpoint {
54    let endpoint_id = if object_id.is_empty() {
55        format!("{role}:{name}:{}:{}", point.x_iu, point.y_iu)
56    } else {
57        format!("{role}:{object_id}")
58    };
59    SchematicDesignNetEndpoint {
60        endpoint_id,
61        role: role.to_owned(),
62        element_id: element_id.to_owned(),
63        object_id: object_id.to_owned(),
64        name: name.to_owned(),
65        source_sheet: source_sheet.to_owned(),
66        connection_point: Some(point),
67    }
68}
69
70fn push_endpoint(
71    endpoints: &mut Vec<SchematicDesignNetEndpoint>,
72    seen: &mut HashSet<(String, String, String)>,
73    endpoint: SchematicDesignNetEndpoint,
74) {
75    let key = (
76        endpoint.endpoint_id.clone(),
77        endpoint.role.clone(),
78        endpoint.source_sheet.clone(),
79    );
80    if seen.insert(key) {
81        endpoints.push(endpoint);
82    }
83}
84
85pub fn build_schematic_scalar_design_nets(
86    index: &SchematicBundleIndex,
87    code_offset: u64,
88) -> Result<SchematicScalarDesignNetlist, SourceBundleError> {
89    build_schematic_scalar_design_nets_with_settings(index, code_offset, index.subpart_settings())
90}
91
92pub fn build_schematic_scalar_design_nets_with_settings(
93    index: &SchematicBundleIndex,
94    code_offset: u64,
95    subparts: SchematicSubpartSettings,
96) -> Result<SchematicScalarDesignNetlist, SourceBundleError> {
97    Ok(build_schematic_compiled_design(index, code_offset, subparts)?.netlist)
98}
99
100pub(crate) fn build_schematic_compiled_design(
101    index: &SchematicBundleIndex,
102    code_offset: u64,
103    subparts: SchematicSubpartSettings,
104) -> Result<SchematicCompiledDesign, SourceBundleError> {
105    DesignBuilder::new(index, code_offset, subparts)?.build()
106}
107
108#[derive(Debug)]
109pub(crate) struct SchematicCompiledDesign {
110    pub(crate) netlist: SchematicScalarDesignNetlist,
111    pub(crate) occurrences: Vec<CompiledOccurrence>,
112    pub(crate) unmaterialized_net_names: HashMap<(usize, usize), String>,
113}
114
115impl SchematicCompiledDesign {
116    /// Every occurrence with no connectivity: what the compilation keeps when
117    /// the design's connectivity could not be compiled.
118    pub(crate) fn unconnected(index: &SchematicBundleIndex) -> Self {
119        Self {
120            netlist: SchematicScalarDesignNetlist {
121                nets: Vec::new(),
122                hierarchy_bindings: Vec::new(),
123            },
124            occurrences: index
125                .occurrences()
126                .map(|occurrence| CompiledOccurrence {
127                    occurrence_index: occurrence.index,
128                    source_path: occurrence.source_path.clone(),
129                    human_address: occurrence.human_address.clone(),
130                    legacy_address: occurrence.legacy_address.clone(),
131                    subgraphs: Vec::new(),
132                    coord_to_subgraph: HashMap::new(),
133                    bus_subgraphs: Vec::new(),
134                    bus_coord_to_subgraph: HashMap::new(),
135                    bus_member_wire_subgraphs: Vec::new(),
136                })
137                .collect(),
138            unmaterialized_net_names: HashMap::new(),
139        }
140    }
141
142    /// One `bus_alias_cycle` warning for each bus whose chosen name met an
143    /// alias again inside that alias's own expansion, on the label that chose
144    /// the name.
145    pub(crate) fn alias_cycle_diagnostics(
146        &self,
147        index: &SchematicBundleIndex,
148    ) -> Vec<KiCadDiagnostic> {
149        let mut diagnostics = Vec::new();
150        for occurrence in &self.occurrences {
151            for bus in &occurrence.bus_subgraphs {
152                if bus.repeated_aliases.is_empty() {
153                    continue;
154                }
155                let driver = bus.drivers.iter().find(|driver| {
156                    driver.text == bus.chosen_name && Some(driver.kind) == bus.chosen_kind
157                });
158                let object_kind = match bus.chosen_kind {
159                    Some(SchematicBusDriverKind::LocalLabel) | None => "label",
160                    Some(SchematicBusDriverKind::GlobalLabel) => "global_label",
161                    Some(SchematicBusDriverKind::HierarchicalLabel) => "hierarchical_label",
162                    Some(SchematicBusDriverKind::SheetPin) => "pin",
163                };
164                let mut diagnostic = KiCadDiagnostic::new(
165                    KiCadDiagnosticCode::BusAliasCycle,
166                    &occurrence.source_path,
167                    object_kind,
168                    driver.map(|driver| driver.source_uuid.clone()),
169                    format!(
170                        "bus {:?}: alias {} repeats inside its own expansion; \
171                         the repeat is one scalar bus member",
172                        bus.chosen_name,
173                        bus.repeated_aliases
174                            .iter()
175                            .map(|alias| format!("{alias:?}"))
176                            .collect::<Vec<_>>()
177                            .join(", ")
178                    ),
179                );
180                if let Some(row) = index.occurrence(occurrence.occurrence_index) {
181                    diagnostic = diagnostic.on_occurrence(&row.occurrence_address);
182                }
183                diagnostics.push(diagnostic);
184            }
185        }
186        diagnostics
187    }
188}
189
190#[derive(Debug)]
191pub(crate) struct CompiledOccurrence {
192    pub(crate) occurrence_index: usize,
193    source_path: String,
194    human_address: String,
195    legacy_address: String,
196    pub(crate) subgraphs: Vec<SchematicWireSubgraph>,
197    coord_to_subgraph: HashMap<crate::SchematicPoint, usize>,
198    bus_subgraphs: Vec<crate::SchematicBusSubgraph>,
199    bus_coord_to_subgraph: HashMap<crate::SchematicPoint, usize>,
200    bus_member_wire_subgraphs: Vec<Vec<Option<usize>>>,
201}
202
203struct OutputShape {
204    members: usize,
205    terminals: usize,
206}
207
208struct MaterializedDesign {
209    nets: Vec<SchematicDesignNet>,
210    unmaterialized_net_names: HashMap<(usize, usize), String>,
211}
212
213struct DesignBuilder<'a> {
214    index: &'a SchematicBundleIndex,
215    code_offset: u64,
216    sheet_pin_targets: SheetPinTargetIndex,
217    design_bus_aliases: HashMap<&'a str, &'a [String]>,
218    compiled: Vec<CompiledOccurrence>,
219    flat: Vec<(usize, usize)>,
220    offsets: Vec<usize>,
221    union: UnionFind,
222}
223
224impl<'a> DesignBuilder<'a> {
225    fn new(
226        index: &'a SchematicBundleIndex,
227        code_offset: u64,
228        subparts: SchematicSubpartSettings,
229    ) -> Result<Self, SourceBundleError> {
230        let sheet_pin_targets = SheetPinTargetIndex::build(index)?;
231        let design_bus_aliases = collect_design_bus_aliases(index)?;
232        let mut compiled = Vec::with_capacity(index.occurrences().len());
233        let mut budget = DesignCompilationBudget::new();
234        for occurrence in index.occurrences() {
235            compiled.push(compile_design_occurrence(
236                index,
237                occurrence,
238                subparts,
239                &design_bus_aliases,
240                &mut budget,
241            )?);
242        }
243        let mut flat = Vec::with_capacity(budget.subgraph_count());
244        let mut offsets = Vec::with_capacity(compiled.len() + 1);
245        for (occurrence_array_index, occurrence) in compiled.iter().enumerate() {
246            offsets.push(flat.len());
247            flat.extend(
248                (0..occurrence.subgraphs.len())
249                    .map(|subgraph_index| (occurrence_array_index, subgraph_index)),
250            );
251        }
252        offsets.push(flat.len());
253        Ok(Self {
254            index,
255            code_offset,
256            sheet_pin_targets,
257            design_bus_aliases,
258            compiled,
259            union: UnionFind::new(flat.len()),
260            flat,
261            offsets,
262        })
263    }
264
265    fn build(mut self) -> Result<SchematicCompiledDesign, SourceBundleError> {
266        let hierarchy_bindings = self.bind_hierarchy()?;
267        self.merge_global_labels()?;
268        self.merge_global_power()?;
269        let promotion = promote_bus_members(
270            &self.compiled,
271            self.index,
272            &self.offsets,
273            &self.design_bus_aliases,
274        )?;
275        for &(left, right) in &promotion.wire_unions {
276            self.union.union(left, right);
277        }
278        let groups = self.ordered_groups();
279        self.preflight_output_shape(&groups)?;
280        let suffix_indices = self.sheet_pin_suffix_indices()?;
281        let materialized = self.materialize(groups, &suffix_indices, &promotion)?;
282        Ok(SchematicCompiledDesign {
283            netlist: SchematicScalarDesignNetlist {
284                nets: materialized.nets,
285                hierarchy_bindings,
286            },
287            occurrences: self.compiled,
288            unmaterialized_net_names: materialized.unmaterialized_net_names,
289        })
290    }
291
292    fn flat_index(&self, occurrence_array_index: usize, subgraph_index: usize) -> usize {
293        self.offsets[occurrence_array_index] + subgraph_index
294    }
295
296    fn bind_hierarchy(&mut self) -> Result<Vec<SchematicHierarchyNetBinding>, SourceBundleError> {
297        let mut bindings = Vec::new();
298        let mut unions = Vec::new();
299        for child_array_index in 0..self.compiled.len() {
300            self.collect_child_bindings(child_array_index, &mut bindings, &mut unions)?;
301        }
302        for (left, right) in unions {
303            self.union.union(left, right);
304        }
305        Ok(bindings)
306    }
307
308    fn collect_child_bindings(
309        &self,
310        child_array_index: usize,
311        bindings: &mut Vec<SchematicHierarchyNetBinding>,
312        unions: &mut Vec<(usize, usize)>,
313    ) -> Result<(), SourceBundleError> {
314        let occurrence_index = self.compiled[child_array_index].occurrence_index;
315        let occurrence = self.index.occurrence(occurrence_index).ok_or_else(|| {
316            self.error("compiled schematic occurrence disappeared from its index")
317        })?;
318        let (Some(parent_index), Some(parent_sheet_index)) =
319            (occurrence.parent_index, occurrence.parent_sheet_index)
320        else {
321            return Ok(());
322        };
323        let parent_array_index = parent_index - 1;
324        let parent_definition = self
325            .index
326            .definition(&self.compiled[parent_array_index].source_path)
327            .ok_or_else(|| self.error("parent schematic definition is missing"))?;
328        let sheet = parent_definition
329            .sheets
330            .get(parent_sheet_index)
331            .ok_or_else(|| self.error("hierarchy occurrence parent sheet index is out of range"))?;
332        let child_by_name = self.child_hierarchical_labels(child_array_index)?;
333        for pin in &sheet.pins {
334            let parent_subgraph = self.compiled[parent_array_index]
335                .coord_to_subgraph
336                .get(&pin.at)
337                .copied();
338            let child_match = child_by_name.get(pin.name.as_str()).copied();
339            self.push_binding_union(
340                parent_array_index,
341                child_array_index,
342                parent_subgraph,
343                child_match,
344                unions,
345            )?;
346            let child_uuid = child_match.map(|(_, uuid)| uuid);
347            let sheet_pin_id =
348                crate::schematic_connectivity::schematic_sheet_pin_group_id(sheet, pin);
349            bindings.push(SchematicHierarchyNetBinding {
350                parent_occurrence_index: parent_index,
351                child_occurrence_index: occurrence_index,
352                sheet_pin_name: pin.name.clone(),
353                sheet_pin_uuid: sheet_pin_id,
354                hierarchical_label_uuid: child_uuid.map(str::to_owned),
355                parent_subgraph_index: parent_subgraph,
356                child_subgraph_index: child_match.map(|(subgraph, _)| subgraph),
357            });
358        }
359        Ok(())
360    }
361
362    fn child_hierarchical_labels(
363        &self,
364        child_array_index: usize,
365    ) -> Result<HashMap<&str, (usize, &str)>, SourceBundleError> {
366        let mut by_name = HashMap::new();
367        for (subgraph_index, subgraph) in self.compiled[child_array_index]
368            .subgraphs
369            .iter()
370            .enumerate()
371        {
372            for label in &subgraph.label_drivers {
373                if label.kind != SchematicWireDriverKind::HierarchicalLabel
374                    || by_name.contains_key(label.text.as_str())
375                {
376                    continue;
377                }
378                by_name.insert(
379                    label.text.as_str(),
380                    (subgraph_index, label.source_uuid.as_str()),
381                );
382            }
383        }
384        Ok(by_name)
385    }
386
387    fn push_binding_union(
388        &self,
389        parent_occurrence: usize,
390        child_occurrence: usize,
391        parent_subgraph: Option<usize>,
392        child_match: Option<(usize, &str)>,
393        unions: &mut Vec<(usize, usize)>,
394    ) -> Result<(), SourceBundleError> {
395        let (Some(parent_subgraph), Some((child_subgraph, _))) = (parent_subgraph, child_match)
396        else {
397            return Ok(());
398        };
399        unions.push((
400            self.flat_index(parent_occurrence, parent_subgraph),
401            self.flat_index(child_occurrence, child_subgraph),
402        ));
403        Ok(())
404    }
405
406    fn merge_global_labels(&mut self) -> Result<(), SourceBundleError> {
407        let mut first_by_name = HashMap::<&str, usize>::new();
408        let mut unions = Vec::new();
409        for (flat_index, (occurrence_index, subgraph_index)) in self.flat.iter().enumerate() {
410            for label in &self.compiled[*occurrence_index].subgraphs[*subgraph_index].label_drivers
411            {
412                if label.kind != SchematicWireDriverKind::GlobalLabel {
413                    continue;
414                }
415                if let Some(first) = first_by_name.get(label.text.as_str()) {
416                    unions.push((*first, flat_index));
417                } else {
418                    first_by_name.insert(label.text.as_str(), flat_index);
419                }
420            }
421        }
422        for (left, right) in unions {
423            self.union.union(left, right);
424        }
425        Ok(())
426    }
427
428    fn merge_global_power(&mut self) -> Result<(), SourceBundleError> {
429        let mut first_by_name = HashMap::<&str, usize>::new();
430        let mut unions = Vec::new();
431        for (flat_index, (occurrence_index, subgraph_index)) in self.flat.iter().enumerate() {
432            for pin in &self.compiled[*occurrence_index].subgraphs[*subgraph_index].pin_drivers {
433                if !pin.is_power || pin.priority != SchematicDriverPriority::GlobalPowerPin {
434                    continue;
435                }
436                if let Some(first) = first_by_name.get(pin.power_value.as_str()) {
437                    unions.push((*first, flat_index));
438                } else {
439                    first_by_name.insert(pin.power_value.as_str(), flat_index);
440                }
441            }
442        }
443        for (left, right) in unions {
444            self.union.union(left, right);
445        }
446        Ok(())
447    }
448
449    fn ordered_groups(&mut self) -> Vec<Vec<usize>> {
450        let mut group_index_by_root = HashMap::new();
451        let mut groups = Vec::<Vec<usize>>::new();
452        for flat_index in 0..self.flat.len() {
453            let root = self.union.find(flat_index);
454            let group_index = *group_index_by_root.entry(root).or_insert_with(|| {
455                groups.push(Vec::new());
456                groups.len() - 1
457            });
458            groups[group_index].push(flat_index);
459        }
460        groups
461    }
462
463    fn preflight_output_shape(&self, groups: &[Vec<usize>]) -> Result<(), SourceBundleError> {
464        let mut net_count = 0_usize;
465        let mut member_count = 0_usize;
466        let mut terminal_count = 0_usize;
467        for group in groups {
468            let Some(shape) = self.group_output_shape(group)? else {
469                continue;
470            };
471            net_count = net_count
472                .checked_add(1)
473                .ok_or_else(|| self.limit_error("design net count overflows"))?;
474            member_count = member_count
475                .checked_add(shape.members)
476                .ok_or_else(|| self.limit_error("design net member count overflows"))?;
477            terminal_count = terminal_count
478                .checked_add(shape.terminals)
479                .ok_or_else(|| self.limit_error("design terminal count overflows"))?;
480        }
481        if net_count != 0 {
482            let last = u64::try_from(net_count - 1)
483                .map_err(|_| self.limit_error("design net code exceeds the platform size"))?;
484            self.code_offset
485                .checked_add(last)
486                .ok_or_else(|| self.limit_error("design net code overflows"))?;
487        }
488        Ok(())
489    }
490
491    fn group_output_shape(
492        &self,
493        group: &[usize],
494    ) -> Result<Option<OutputShape>, SourceBundleError> {
495        let mut terminals = HashSet::new();
496        let mut has_driver = false;
497        let mut driver_count = 0_usize;
498        for &flat_index in group {
499            let (occurrence, subgraph) = self.flat[flat_index];
500            let subgraph = &self.compiled[occurrence].subgraphs[subgraph];
501            has_driver |= !subgraph.pin_drivers.is_empty() || !subgraph.label_drivers.is_empty();
502            driver_count = driver_count
503                .checked_add(subgraph.pin_drivers.len())
504                .and_then(|value| value.checked_add(subgraph.label_drivers.len()))
505                .ok_or_else(|| self.limit_error("merged design driver count overflows"))?;
506            terminals.extend(
507                subgraph
508                    .pin_drivers
509                    .iter()
510                    .filter(|pin| !pin.reference.is_empty() && !pin.reference.starts_with('#'))
511                    .map(|pin| (pin.reference.as_str(), pin.pin_number.as_str())),
512            );
513        }
514        Ok(
515            (has_driver && !terminals.is_empty()).then_some(OutputShape {
516                members: group.len(),
517                terminals: terminals.len(),
518            }),
519        )
520    }
521
522    fn materialize(
523        &mut self,
524        groups: Vec<Vec<usize>>,
525        suffix_indices: &HashMap<(usize, usize), usize>,
526        promotion: &BusPromotion,
527    ) -> Result<MaterializedDesign, SourceBundleError> {
528        let mut nets = Vec::new();
529        let mut unmaterialized_net_names = HashMap::new();
530        let mut seen_synthetic_sheet_pin_names = HashMap::<String, usize>::new();
531        for group in groups {
532            let (mut merged, choice) = self.merged_subgraph(&group, promotion)?;
533            let Some(choice) = choice else {
534                continue;
535            };
536            merged.chosen_name = choice.raw_name;
537            merged.chosen_priority = choice.priority;
538            merged.chosen_kind = Some(choice.kind);
539            let source_path = &self.compiled[self.flat[group[0]].0].source_path;
540            let (mut name, auto_named) =
541                name_schematic_subgraph(source_path, &choice.sheet_path, &merged, usize::MAX)?;
542            self.apply_sheet_pin_suffix(
543                &mut name,
544                choice.kind,
545                choice.sheet_pin_key,
546                suffix_indices,
547                &mut seen_synthetic_sheet_pin_names,
548            )?;
549            let terminal_refs = self.terminal_refs(&group);
550            if terminal_refs.is_empty() {
551                for flat_index in group {
552                    let (occurrence, subgraph_index) = self.flat[flat_index];
553                    unmaterialized_net_names.insert(
554                        (self.compiled[occurrence].occurrence_index, subgraph_index),
555                        name.clone(),
556                    );
557                }
558                continue;
559            }
560            let terminals = self.materialize_terminals(terminal_refs)?;
561            let graphical = self.materialize_graphical(&group)?;
562            let endpoints = self.materialize_endpoints(&group)?;
563            let members = group
564                .iter()
565                .map(|flat_index| {
566                    let (occurrence, subgraph_index) = self.flat[*flat_index];
567                    SchematicDesignNetMember {
568                        occurrence_index: self.compiled[occurrence].occurrence_index,
569                        subgraph_index,
570                    }
571                })
572                .collect();
573            let code =
574                self.code_offset
575                    .checked_add(u64::try_from(nets.len()).map_err(|_| {
576                        self.limit_error("design net code exceeds the platform size")
577                    })?)
578                    .ok_or_else(|| self.limit_error("design net code overflows"))?;
579            nets.push(SchematicDesignNet {
580                name,
581                code,
582                driver_priority: merged.chosen_priority,
583                driver_kind: merged.chosen_kind,
584                auto_named,
585                members,
586                terminals,
587                graphical,
588                endpoints,
589            });
590        }
591        Ok(MaterializedDesign {
592            nets,
593            unmaterialized_net_names,
594        })
595    }
596
597    fn materialize_graphical(
598        &mut self,
599        group: &[usize],
600    ) -> Result<crate::SchematicGraphicalIds, SourceBundleError> {
601        let mut graphical = crate::SchematicGraphicalIds::default();
602        for &flat_index in group {
603            let (occurrence, subgraph_index) = self.flat[flat_index];
604            let source = &self.compiled[occurrence].subgraphs[subgraph_index].graphical;
605            append_unique(&mut graphical.wires, &source.wires);
606            append_unique(&mut graphical.junctions, &source.junctions);
607            append_unique(&mut graphical.labels, &source.labels);
608            append_unique(&mut graphical.power_ports, &source.power_ports);
609            append_unique(&mut graphical.ports, &source.ports);
610            append_unique(&mut graphical.sheet_entries, &source.sheet_entries);
611        }
612        Ok(graphical)
613    }
614
615    fn materialize_endpoints(
616        &mut self,
617        group: &[usize],
618    ) -> Result<Vec<SchematicDesignNetEndpoint>, SourceBundleError> {
619        let mut endpoints = Vec::new();
620        let mut seen = HashSet::new();
621        for &flat_index in group {
622            let (occurrence, subgraph_index) = self.flat[flat_index];
623            let compiled = &self.compiled[occurrence];
624            let subgraph = &compiled.subgraphs[subgraph_index];
625            for label in &subgraph.label_drivers {
626                let role = match label.kind {
627                    SchematicWireDriverKind::HierarchicalLabel => "port",
628                    SchematicWireDriverKind::SheetPin => "sheet_entry",
629                    _ => continue,
630                };
631                let element_id = nonempty(&label.render_id, &label.source_uuid);
632                let object_id = nonempty(&label.source_uuid, element_id);
633                push_endpoint(
634                    &mut endpoints,
635                    &mut seen,
636                    endpoint(
637                        role,
638                        element_id,
639                        object_id,
640                        &label.text,
641                        &compiled.legacy_address,
642                        label.at,
643                    ),
644                );
645            }
646            for pin in &subgraph.pin_drivers {
647                if !(pin.is_power && pin.reference.starts_with('#')) {
648                    continue;
649                }
650                let element_id = nonempty(&pin.symbol_uuid, &pin.source_pin_uuid);
651                let object_id = nonempty(&pin.source_pin_uuid, element_id);
652                let name = nonempty(&pin.power_value, nonempty(&pin.pin_name, &pin.reference));
653                push_endpoint(
654                    &mut endpoints,
655                    &mut seen,
656                    endpoint(
657                        "power_port",
658                        element_id,
659                        object_id,
660                        name,
661                        &compiled.legacy_address,
662                        pin.at,
663                    ),
664                );
665            }
666        }
667        Ok(endpoints)
668    }
669
670    fn apply_sheet_pin_suffix(
671        &self,
672        name: &mut String,
673        kind: SchematicWireDriverKind,
674        sheet_pin_key: Option<(usize, usize)>,
675        suffix_indices: &HashMap<(usize, usize), usize>,
676        seen_synthetic_names: &mut HashMap<String, usize>,
677    ) -> Result<(), SourceBundleError> {
678        if kind != SchematicWireDriverKind::SheetPin {
679            return Ok(());
680        }
681        let suffix = if let Some(key) = sheet_pin_key {
682            suffix_indices
683                .get(&key)
684                .copied()
685                .filter(|value| *value != 0)
686        } else {
687            let next = seen_synthetic_names.entry(name.clone()).or_default();
688            let suffix = (*next != 0).then_some(*next);
689            *next = next
690                .checked_add(1)
691                .ok_or_else(|| self.limit_error("sheet-pin suffix count overflows"))?;
692            suffix
693        };
694        let Some(suffix) = suffix else {
695            return Ok(());
696        };
697        let suffix = format!("_{suffix}");
698        name.push_str(&suffix);
699        Ok(())
700    }
701
702    fn terminal_refs(&self, group: &[usize]) -> Vec<PinLocator> {
703        let mut pins = Vec::new();
704        for &flat_index in group {
705            let (occurrence, subgraph_index) = self.flat[flat_index];
706            pins.extend(
707                self.compiled[occurrence].subgraphs[subgraph_index]
708                    .pin_drivers
709                    .iter()
710                    .enumerate()
711                    .filter(|(_, pin)| !pin.reference.is_empty() && !pin.reference.starts_with('#'))
712                    .map(|(pin_index, _)| PinLocator {
713                        occurrence,
714                        subgraph_index,
715                        pin_index,
716                    }),
717            );
718        }
719        pins.sort_by(|left, right| {
720            let left = left.pin(self);
721            let right = right.pin(self);
722            left.reference
723                .cmp(&right.reference)
724                .then_with(|| left.pin_number.cmp(&right.pin_number))
725        });
726        pins.dedup_by(|left, right| {
727            let left = left.pin(self);
728            let right = right.pin(self);
729            left.reference == right.reference && left.pin_number == right.pin_number
730        });
731        pins
732    }
733
734    fn materialize_terminals(
735        &mut self,
736        pins: Vec<PinLocator>,
737    ) -> Result<Vec<SchematicDesignNetTerminal>, SourceBundleError> {
738        let mut terminals = Vec::with_capacity(pins.len());
739        for locator in pins {
740            let pin = locator.pin(self);
741            let svg_id = if pin.pin_svg_id.is_empty() {
742                &pin.symbol_uuid
743            } else {
744                &pin.pin_svg_id
745            };
746            let sheet_path = &self.compiled[locator.occurrence].legacy_address;
747            terminals.push(SchematicDesignNetTerminal {
748                occurrence_index: self.compiled[locator.occurrence].occurrence_index,
749                symbol_index: pin.symbol_index,
750                designator: pin.reference.clone(),
751                pin: pin.pin_number.clone(),
752                pin_name: pin.pin_name.clone(),
753                pin_type: pin.electrical_type.clone(),
754                sheet_path: sheet_path.clone(),
755                source_pin_id: pin.source_pin_uuid.clone(),
756                svg_id: svg_id.clone(),
757            });
758        }
759        Ok(terminals)
760    }
761
762    fn merged_subgraph(
763        &self,
764        group: &[usize],
765        promotion: &BusPromotion,
766    ) -> Result<(SchematicWireSubgraph, Option<DriverChoice>), SourceBundleError> {
767        let choice = self.choose_driver(group, promotion)?;
768        let choice_strings = choice.as_ref().map(|choice| {
769            [
770                choice.full_name.as_str(),
771                choice.sheet_path.as_str(),
772                choice.raw_name.as_str(),
773            ]
774        });
775        let shape = merged_driver_shape(
776            group.iter().map(|flat_index| {
777                let (occurrence, subgraph_index) = self.flat[*flat_index];
778                &self.compiled[occurrence].subgraphs[subgraph_index]
779            }),
780            choice_strings,
781        )
782        .ok_or_else(|| self.limit_error("merged design driver bytes overflow"))?;
783        let _driver_count = shape
784            .pins
785            .checked_add(shape.labels)
786            .ok_or_else(|| self.limit_error("merged design driver count overflows"))?;
787        let mut merged = SchematicWireSubgraph {
788            coords: Vec::new(),
789            pin_drivers: Vec::with_capacity(shape.pins),
790            label_drivers: Vec::with_capacity(shape.labels),
791            graphical: Default::default(),
792            chosen_name: String::new(),
793            chosen_priority: SchematicDriverPriority::None,
794            chosen_kind: None,
795            no_connect: false,
796        };
797        for &flat_index in group {
798            let (occurrence, subgraph_index) = self.flat[flat_index];
799            let subgraph = &self.compiled[occurrence].subgraphs[subgraph_index];
800            merged.no_connect |= subgraph.no_connect;
801            merged
802                .pin_drivers
803                .extend(subgraph.pin_drivers.iter().cloned());
804            merged
805                .label_drivers
806                .extend(subgraph.label_drivers.iter().cloned());
807        }
808        Ok((merged, choice))
809    }
810
811    fn choose_driver(
812        &self,
813        group: &[usize],
814        promotion: &BusPromotion,
815    ) -> Result<Option<DriverChoice>, SourceBundleError> {
816        let mut best = None;
817        let mut order = 0_usize;
818        for &flat_index in group {
819            let (occurrence, subgraph_index) = self.flat[flat_index];
820            let compiled = &self.compiled[occurrence];
821            let subgraph = &compiled.subgraphs[subgraph_index];
822            for label in &subgraph.label_drivers {
823                consider_choice(&mut best, self.label_choice(occurrence, label, order)?);
824                order += 1;
825            }
826            for pin in &subgraph.pin_drivers {
827                consider_choice(&mut best, self.pin_choice(occurrence, pin, order)?);
828                order += 1;
829            }
830        }
831        let mut override_order = 0_usize;
832        for &flat_index in group {
833            for value in promotion.overrides_for(flat_index) {
834                consider_choice(
835                    &mut best,
836                    DriverChoice {
837                        priority: value.priority.max(SchematicDriverPriority::LocalPowerPin),
838                        depth: value.depth,
839                        shape_rank: 1,
840                        implicit: false,
841                        full_name: value.text.clone(),
842                        sheet_path: value.sheet_path.clone(),
843                        order: override_order,
844                        kind: value.kind,
845                        raw_name: value.text.clone(),
846                        sheet_pin_key: None,
847                    },
848                );
849                override_order = override_order
850                    .checked_add(1)
851                    .ok_or_else(|| self.limit_error("design bus override order overflows"))?;
852            }
853        }
854        Ok(best)
855    }
856
857    fn label_choice(
858        &self,
859        occurrence: usize,
860        label: &crate::SchematicLabelDriver,
861        order: usize,
862    ) -> Result<DriverChoice, SourceBundleError> {
863        let compiled = &self.compiled[occurrence];
864        let sheet_path = self.label_sheet_path(occurrence, label);
865        let full_name = if label.kind == SchematicWireDriverKind::GlobalLabel {
866            label.text.clone()
867        } else {
868            checked_join(&sheet_path, &label.text, usize::MAX)
869                .ok_or_else(|| self.limit_error("design driver name bytes exceed their limit"))?
870        };
871        Ok(DriverChoice {
872            priority: label.priority,
873            depth: sheet_depth(&compiled.human_address),
874            shape_rank: usize::from(
875                label.kind != SchematicWireDriverKind::SheetPin || label.shape != "output",
876            ),
877            implicit: false,
878            full_name,
879            sheet_path,
880            order,
881            kind: label.kind,
882            raw_name: label.text.clone(),
883            sheet_pin_key: (label.kind == SchematicWireDriverKind::SheetPin)
884                .then_some((occurrence, label.source_order)),
885        })
886    }
887
888    fn pin_choice(
889        &self,
890        occurrence: usize,
891        pin: &SchematicPinDriver,
892        order: usize,
893    ) -> Result<DriverChoice, SourceBundleError> {
894        let compiled = &self.compiled[occurrence];
895        let raw_name = if pin.is_power && !pin.power_value.is_empty() {
896            pin.power_value.clone()
897        } else {
898            format!("{}-{}", pin.reference, pin.pin_number)
899        };
900        let power = pin.is_power
901            && matches!(
902                pin.priority,
903                SchematicDriverPriority::GlobalPowerPin | SchematicDriverPriority::LocalPowerPin
904            );
905        let full_name = if power {
906            raw_name.clone()
907        } else {
908            checked_join(&compiled.human_address, &raw_name, usize::MAX)
909                .ok_or_else(|| self.limit_error("design driver name bytes exceed their limit"))?
910        };
911        Ok(DriverChoice {
912            priority: pin.priority,
913            depth: sheet_depth(&compiled.human_address),
914            shape_rank: 1,
915            implicit: pin.is_implicit_hidden_power,
916            full_name,
917            sheet_path: compiled.human_address.clone(),
918            order,
919            kind: pin.kind,
920            raw_name,
921            sheet_pin_key: None,
922        })
923    }
924
925    fn label_sheet_path(
926        &self,
927        occurrence_array_index: usize,
928        label: &crate::SchematicLabelDriver,
929    ) -> String {
930        if label.kind == SchematicWireDriverKind::SheetPin {
931            let parent_occurrence = self.compiled[occurrence_array_index].occurrence_index;
932            if let Some(target) = self.sheet_pin_targets.target_path(parent_occurrence, label) {
933                return target.to_owned();
934            }
935        }
936        self.compiled[occurrence_array_index].human_address.clone()
937    }
938
939    fn sheet_pin_suffix_indices(
940        &self,
941    ) -> Result<HashMap<(usize, usize), usize>, SourceBundleError> {
942        let mut grouped = HashMap::<String, Vec<(usize, usize, (usize, usize))>>::new();
943        let mut fallback = 0_usize;
944        for occurrence in 0..self.compiled.len() {
945            for subgraph in &self.compiled[occurrence].subgraphs {
946                for label in &subgraph.label_drivers {
947                    if label.kind != SchematicWireDriverKind::SheetPin {
948                        continue;
949                    }
950                    let sheet_path = self.label_sheet_path(occurrence, label);
951                    let fake = SchematicWireSubgraph {
952                        coords: Vec::new(),
953                        pin_drivers: Vec::new(),
954                        label_drivers: Vec::new(),
955                        graphical: Default::default(),
956                        chosen_name: label.text.clone(),
957                        chosen_priority: label.priority,
958                        chosen_kind: Some(label.kind),
959                        no_connect: false,
960                    };
961                    let (base, _) = name_schematic_subgraph(
962                        &self.compiled[occurrence].source_path,
963                        &sheet_path,
964                        &fake,
965                        usize::MAX,
966                    )?;
967                    grouped.entry(base).or_default().push((
968                        label.source_order,
969                        fallback,
970                        (occurrence, label.source_order),
971                    ));
972                    fallback = fallback
973                        .checked_add(1)
974                        .ok_or_else(|| self.limit_error("sheet-pin suffix order overflows"))?;
975                }
976            }
977        }
978        let mut result = HashMap::new();
979        for entries in grouped.values_mut() {
980            entries.sort_by_key(|value| (value.0, value.1));
981            for (suffix, (_, _, key)) in entries.iter().enumerate() {
982                result.insert(*key, suffix);
983            }
984        }
985        Ok(result)
986    }
987
988    fn error(&self, message: &str) -> SourceBundleError {
989        SourceBundleError::new(
990            SourceBundleErrorKind::Schematic,
991            self.compiled
992                .first()
993                .map(|value| value.source_path.as_str()),
994            message,
995        )
996    }
997
998    fn limit_error(&self, message: &str) -> SourceBundleError {
999        limit_error(
1000            self.compiled
1001                .first()
1002                .map(|value| value.source_path.as_str()),
1003            message,
1004        )
1005    }
1006}
1007
1008#[derive(Clone, Copy)]
1009struct PinLocator {
1010    occurrence: usize,
1011    subgraph_index: usize,
1012    pin_index: usize,
1013}
1014
1015impl PinLocator {
1016    fn pin<'a>(&self, builder: &'a DesignBuilder<'_>) -> &'a SchematicPinDriver {
1017        &builder.compiled[self.occurrence].subgraphs[self.subgraph_index].pin_drivers
1018            [self.pin_index]
1019    }
1020}
1021
1022fn limit_error(path: Option<&str>, message: &str) -> SourceBundleError {
1023    SourceBundleError::new(SourceBundleErrorKind::ResourceLimit, path, message)
1024}