1use crate::schematic_bus::expand_schematic_bus_label_from_map;
2use crate::schematic_segment_index::{SchematicSegment, SchematicSegmentIndex};
3use crate::{
4 SchematicBusExpansionErrorKind, SchematicDefinition, SchematicLabelScope, SchematicPoint,
5 SourceBundleError, SourceBundleErrorKind, is_schematic_bus_label,
6};
7use std::collections::{BTreeMap, HashMap, HashSet};
8
9#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
10#[repr(i8)]
11pub enum SchematicDriverPriority {
12 Invalid = -1,
13 None = 0,
14 Pin = 1,
15 SheetPin = 2,
16 HierarchicalLabel = 3,
17 LocalLabel = 4,
18 LocalPowerPin = 5,
19 GlobalPowerPin = 6,
20 Global = 7,
21}
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum SchematicBusDriverKind {
25 LocalLabel,
26 GlobalLabel,
27 HierarchicalLabel,
28 SheetPin,
29}
30
31impl SchematicBusDriverKind {
32 pub fn as_str(self) -> &'static str {
33 match self {
34 Self::LocalLabel => "local_label",
35 Self::GlobalLabel => "global_label",
36 Self::HierarchicalLabel => "hier_label",
37 Self::SheetPin => "sheet_pin",
38 }
39 }
40}
41
42#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct SchematicBusDriver {
44 pub text: String,
45 pub at: SchematicPoint,
46 pub priority: SchematicDriverPriority,
47 pub kind: SchematicBusDriverKind,
48 pub source_uuid: String,
49 pub source_order: usize,
50}
51
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct SchematicBusSubgraph {
54 pub coords: Vec<SchematicPoint>,
55 pub drivers: Vec<SchematicBusDriver>,
56 pub tap_wire_coords: Vec<SchematicPoint>,
57 pub chosen_name: String,
58 pub chosen_priority: SchematicDriverPriority,
59 pub chosen_kind: Option<SchematicBusDriverKind>,
60 pub members: Vec<String>,
61 pub repeated_aliases: Vec<String>,
64}
65
66pub fn build_schematic_bus_subgraphs(
67 definition: &SchematicDefinition,
68) -> Result<Vec<SchematicBusSubgraph>, SourceBundleError> {
69 let aliases = collect_schematic_bus_aliases(definition)?;
70 let mut geometry = SchematicConnectivityGeometry::build(definition)?;
71 build_schematic_bus_subgraphs_with_geometry(definition, &aliases, &mut geometry)
72}
73
74pub(crate) struct SchematicConnectivityGeometry {
75 bus_union: PointUnion,
76 bus_index: SchematicSegmentIndex,
77 wire_index: SchematicSegmentIndex,
78}
79
80impl SchematicConnectivityGeometry {
81 pub(crate) fn build(definition: &SchematicDefinition) -> Result<Self, SourceBundleError> {
82 let (bus_segments, bus_union) = collect_bus_segments(definition);
83 let wire_segments = collect_wire_segments(definition);
84 let bus_index = SchematicSegmentIndex::build(bus_segments, &definition.source_path)?;
85 let wire_index = SchematicSegmentIndex::build(wire_segments, &definition.source_path)?;
86 Ok(Self {
87 bus_union,
88 bus_index,
89 wire_index,
90 })
91 }
92
93 pub(crate) fn bus_index(&self) -> &SchematicSegmentIndex {
94 &self.bus_index
95 }
96
97 pub(crate) fn wire_index(&self) -> &SchematicSegmentIndex {
98 &self.wire_index
99 }
100}
101
102pub(crate) fn build_schematic_bus_subgraphs_with_geometry<'a>(
103 definition: &'a SchematicDefinition,
104 aliases: &HashMap<&'a str, &'a [String]>,
105 geometry: &mut SchematicConnectivityGeometry,
106) -> Result<Vec<SchematicBusSubgraph>, SourceBundleError> {
107 BusBuilder::new(definition, aliases, geometry)?.build()
108}
109
110pub(crate) fn collect_schematic_bus_aliases(
111 definition: &SchematicDefinition,
112) -> Result<HashMap<&str, &[String]>, SourceBundleError> {
113 let mut aliases = HashMap::with_capacity(definition.bus_aliases.len());
114 for alias in &definition.bus_aliases {
115 aliases.insert(alias.name.as_str(), alias.members.as_slice());
116 }
117 Ok(aliases)
118}
119
120struct BusBuilder<'a, 'g> {
121 definition: &'a SchematicDefinition,
122 aliases: &'g HashMap<&'a str, &'a [String]>,
123 bus_union: &'g mut PointUnion,
124 bus_index: &'g SchematicSegmentIndex,
125 wire_index: &'g SchematicSegmentIndex,
126}
127
128impl<'a, 'g> BusBuilder<'a, 'g> {
129 fn new(
130 definition: &'a SchematicDefinition,
131 aliases: &'g HashMap<&'a str, &'a [String]>,
132 geometry: &'g mut SchematicConnectivityGeometry,
133 ) -> Result<Self, SourceBundleError> {
134 Ok(Self {
135 definition,
136 aliases,
137 bus_union: &mut geometry.bus_union,
138 bus_index: &geometry.bus_index,
139 wire_index: &geometry.wire_index,
140 })
141 }
142
143 fn build(mut self) -> Result<Vec<SchematicBusSubgraph>, SourceBundleError> {
144 let taps = self.collect_taps()?;
145 let (mut out, root_to_index) = self.realize_physical_subgraphs(taps)?;
146 let mut orphans = Vec::new();
147 for driver in self.collect_drivers()? {
148 if let Some(index) = self.find_subgraph(driver.at, &root_to_index)? {
149 out[index].drivers.push(driver);
150 } else if self.is_bus_form(&driver.text)? {
151 orphans.push(driver);
152 }
153 }
154 self.add_orphan_subgraphs(&mut out, orphans)?;
155 self.resolve_names(&mut out)?;
156 Ok(out)
157 }
158
159 fn collect_taps(&mut self) -> Result<Vec<(SchematicPoint, SchematicPoint)>, SourceBundleError> {
160 let mut taps = Vec::new();
161 for entry in &self.definition.bus_entries {
162 let a = entry.at;
163 let b = entry
164 .wire_end()
165 .ok_or_else(|| schematic_error(self.definition, "bus-entry endpoint overflows"))?;
166 let (bus_side, wire_side) = self.classify_tap(a, b)?;
167 let bus_point = self.bus_union.add(bus_side);
168 if let Some(segment) = self.first_bus_segment(bus_side)? {
169 let endpoint = self.bus_union.add(segment.a);
170 self.bus_union.union(bus_point, endpoint);
171 }
172 taps.push((bus_side, wire_side));
173 }
174 Ok(taps)
175 }
176
177 fn classify_tap(
178 &mut self,
179 a: SchematicPoint,
180 b: SchematicPoint,
181 ) -> Result<(SchematicPoint, SchematicPoint), SourceBundleError> {
182 let a_bus = self.on_bus(a)?;
183 let b_bus = self.on_bus(b)?;
184 if a_bus && !b_bus {
185 return Ok((a, b));
186 }
187 if b_bus && !a_bus {
188 return Ok((b, a));
189 }
190 if a_bus && b_bus {
191 let a_wire = self.on_wire(a)?;
192 let b_wire = self.on_wire(b)?;
193 if a_wire && !b_wire {
194 return Ok((b, a));
195 }
196 return Ok((a, b));
197 }
198 Ok((b, a))
199 }
200
201 fn realize_physical_subgraphs(
202 &mut self,
203 taps: Vec<(SchematicPoint, SchematicPoint)>,
204 ) -> Result<(Vec<SchematicBusSubgraph>, HashMap<usize, usize>), SourceBundleError> {
205 let groups = self.bus_union.groups();
206 let mut out = Vec::with_capacity(groups.len());
207 let mut root_to_index = HashMap::with_capacity(groups.len());
208 for (root, mut coords) in groups {
209 coords.sort_unstable();
210 root_to_index.insert(root, out.len());
211 out.push(empty_subgraph(coords));
212 }
213 for (bus_side, wire_side) in taps {
214 let root = self
215 .bus_union
216 .root_for_point(bus_side)
217 .ok_or_else(|| schematic_error(self.definition, "bus tap root is missing"))?;
218 let index = *root_to_index
219 .get(&root)
220 .ok_or_else(|| schematic_error(self.definition, "bus tap subgraph is missing"))?;
221 out[index].tap_wire_coords.push(wire_side);
222 }
223 Ok((out, root_to_index))
224 }
225
226 fn collect_drivers(&mut self) -> Result<Vec<SchematicBusDriver>, SourceBundleError> {
227 let mut drivers = Vec::new();
228 for scope in [
229 SchematicLabelScope::Local,
230 SchematicLabelScope::Global,
231 SchematicLabelScope::Hierarchical,
232 ] {
233 for label in self
234 .definition
235 .labels
236 .iter()
237 .filter(|label| label.scope == scope)
238 {
239 let (priority, kind) = label_driver_type(scope);
240 self.push_driver(
241 &mut drivers,
242 &label.text,
243 label.at,
244 priority,
245 kind,
246 &label.uuid,
247 )?;
248 }
249 }
250 for sheet in &self.definition.sheets {
251 for pin in &sheet.pins {
252 self.push_driver(
253 &mut drivers,
254 &pin.name,
255 pin.at,
256 SchematicDriverPriority::SheetPin,
257 SchematicBusDriverKind::SheetPin,
258 &pin.uuid,
259 )?;
260 }
261 }
262 Ok(drivers)
263 }
264
265 fn push_driver(
266 &mut self,
267 drivers: &mut Vec<SchematicBusDriver>,
268 text: &str,
269 at: SchematicPoint,
270 priority: SchematicDriverPriority,
271 kind: SchematicBusDriverKind,
272 source_uuid: &str,
273 ) -> Result<(), SourceBundleError> {
274 drivers.push(SchematicBusDriver {
275 text: text.to_owned(),
276 at,
277 priority,
278 kind,
279 source_uuid: source_uuid.to_owned(),
280 source_order: drivers.len(),
281 });
282 Ok(())
283 }
284
285 fn find_subgraph(
286 &mut self,
287 point: SchematicPoint,
288 root_to_index: &HashMap<usize, usize>,
289 ) -> Result<Option<usize>, SourceBundleError> {
290 if let Some(root) = self.bus_union.root_for_point(point) {
291 return Ok(root_to_index.get(&root).copied());
292 }
293 let Some(segment) = self.first_bus_segment(point)? else {
294 return Ok(None);
295 };
296 let root = self
297 .bus_union
298 .root_for_point(segment.a)
299 .ok_or_else(|| schematic_error(self.definition, "bus segment root is missing"))?;
300 Ok(root_to_index.get(&root).copied())
301 }
302
303 fn add_orphan_subgraphs(
304 &mut self,
305 out: &mut Vec<SchematicBusSubgraph>,
306 orphans: Vec<SchematicBusDriver>,
307 ) -> Result<(), SourceBundleError> {
308 struct OrphanGroup {
309 output_index: usize,
310 coords: HashSet<SchematicPoint>,
311 }
312
313 let mut by_text = HashMap::<String, OrphanGroup>::new();
314 for driver in orphans {
315 let index = if let Some(group) = by_text.get_mut(&driver.text) {
316 if !group.coords.contains(&driver.at) {
317 group.coords.insert(driver.at);
318 out[group.output_index].coords.push(driver.at);
319 }
320 group.output_index
321 } else {
322 let index = out.len();
323 by_text.insert(
324 driver.text.clone(),
325 OrphanGroup {
326 output_index: index,
327 coords: HashSet::from([driver.at]),
328 },
329 );
330 out.push(empty_subgraph(vec![driver.at]));
331 index
332 };
333 out[index].drivers.push(driver);
334 }
335 for group in by_text.values() {
336 out[group.output_index].coords.sort_unstable();
337 }
338 Ok(())
339 }
340
341 fn resolve_names(&mut self, out: &mut [SchematicBusSubgraph]) -> Result<(), SourceBundleError> {
342 for subgraph in out {
343 let mut best: Option<&SchematicBusDriver> = None;
344 for driver in &subgraph.drivers {
345 if !self.is_bus_form(&driver.text)? {
346 continue;
347 }
348 if best.is_none_or(|current| driver_precedes(driver, current)) {
349 best = Some(driver);
350 }
351 }
352 let Some(best) = best else {
353 continue;
354 };
355 let chosen_name = best.text.clone();
356 let chosen_priority = best.priority;
357 let chosen_kind = best.kind;
358 let expansion = expand_schematic_bus_label_from_map(&chosen_name, self.aliases)
359 .map_err(|error| bus_expansion_error(self.definition, error))?;
360 subgraph.chosen_name = chosen_name;
361 subgraph.chosen_priority = chosen_priority;
362 subgraph.chosen_kind = Some(chosen_kind);
363 subgraph.members = expansion.members;
364 subgraph.repeated_aliases = expansion.repeated_aliases;
365 }
366 Ok(())
367 }
368
369 fn is_bus_form(&self, text: &str) -> Result<bool, SourceBundleError> {
370 if self.aliases.contains_key(text) {
371 return Ok(true);
372 }
373 is_schematic_bus_label(text).map_err(|error| bus_expansion_error(self.definition, error))
374 }
375
376 fn on_bus(&mut self, point: SchematicPoint) -> Result<bool, SourceBundleError> {
377 self.bus_index.any_containing(point)
378 }
379
380 fn on_wire(&mut self, point: SchematicPoint) -> Result<bool, SourceBundleError> {
381 self.wire_index.any_containing(point)
382 }
383
384 fn first_bus_segment(
385 &mut self,
386 point: SchematicPoint,
387 ) -> Result<Option<SchematicSegment>, SourceBundleError> {
388 self.bus_index.first_containing(point)
389 }
390}
391
392fn collect_bus_segments(definition: &SchematicDefinition) -> (Vec<SchematicSegment>, PointUnion) {
393 let mut segments = Vec::new();
394 let mut union = PointUnion::default();
395 for bus in &definition.buses {
396 let mut previous = None;
397 for point in &bus.points {
398 let current = union.add(*point);
399 if let Some((previous_index, previous_point)) = previous
400 && let Some(segment) = SchematicSegment::new(previous_point, *point, segments.len())
401 {
402 union.union(previous_index, current);
403 segments.push(segment);
404 }
405 previous = Some((current, *point));
406 }
407 }
408 (segments, union)
409}
410
411fn collect_wire_segments(definition: &SchematicDefinition) -> Vec<SchematicSegment> {
412 let mut segments = Vec::new();
413 for wire in &definition.wires {
414 for points in wire.points.windows(2) {
415 if let Some(segment) = SchematicSegment::new(points[0], points[1], segments.len()) {
416 segments.push(segment);
417 }
418 }
419 }
420 segments
421}
422
423fn label_driver_type(
424 scope: SchematicLabelScope,
425) -> (SchematicDriverPriority, SchematicBusDriverKind) {
426 match scope {
427 SchematicLabelScope::Local => (
428 SchematicDriverPriority::LocalLabel,
429 SchematicBusDriverKind::LocalLabel,
430 ),
431 SchematicLabelScope::Global => (
432 SchematicDriverPriority::Global,
433 SchematicBusDriverKind::GlobalLabel,
434 ),
435 SchematicLabelScope::Hierarchical => (
436 SchematicDriverPriority::HierarchicalLabel,
437 SchematicBusDriverKind::HierarchicalLabel,
438 ),
439 }
440}
441
442fn driver_precedes(candidate: &SchematicBusDriver, current: &SchematicBusDriver) -> bool {
443 candidate.priority > current.priority
444 || (candidate.priority == current.priority
445 && (candidate.text < current.text
446 || (candidate.text == current.text
447 && candidate.source_order < current.source_order)))
448}
449
450fn empty_subgraph(coords: Vec<SchematicPoint>) -> SchematicBusSubgraph {
451 SchematicBusSubgraph {
452 coords,
453 drivers: Vec::new(),
454 tap_wire_coords: Vec::new(),
455 chosen_name: String::new(),
456 chosen_priority: SchematicDriverPriority::None,
457 chosen_kind: None,
458 members: Vec::new(),
459 repeated_aliases: Vec::new(),
460 }
461}
462
463#[derive(Default)]
464struct PointUnion {
465 index_by_point: HashMap<SchematicPoint, usize>,
466 points: Vec<SchematicPoint>,
467 parent: Vec<usize>,
468 rank: Vec<u8>,
469}
470
471impl PointUnion {
472 fn add(&mut self, point: SchematicPoint) -> usize {
473 if let Some(index) = self.index_by_point.get(&point) {
474 return *index;
475 }
476 let index = self.points.len();
477 self.index_by_point.insert(point, index);
478 self.points.push(point);
479 self.parent.push(index);
480 self.rank.push(0);
481 index
482 }
483
484 fn root(&mut self, index: usize) -> usize {
485 let mut root = index;
486 while self.parent[root] != root {
487 root = self.parent[root];
488 }
489 let mut current = index;
490 while self.parent[current] != root {
491 let next = self.parent[current];
492 self.parent[current] = root;
493 current = next;
494 }
495 root
496 }
497
498 fn root_for_point(&mut self, point: SchematicPoint) -> Option<usize> {
499 let index = self.index_by_point.get(&point).copied()?;
500 Some(self.root(index))
501 }
502
503 fn union(&mut self, left: usize, right: usize) {
504 let mut left = self.root(left);
505 let mut right = self.root(right);
506 if left == right {
507 return;
508 }
509 if self.rank[left] < self.rank[right] {
510 std::mem::swap(&mut left, &mut right);
511 }
512 self.parent[right] = left;
513 if self.rank[left] == self.rank[right] {
514 self.rank[left] = self.rank[left].saturating_add(1);
515 }
516 }
517
518 fn groups(&mut self) -> Vec<(usize, Vec<SchematicPoint>)> {
519 let mut groups = BTreeMap::<usize, Vec<SchematicPoint>>::new();
520 for index in 0..self.points.len() {
521 let root = self.root(index);
522 groups.entry(root).or_default().push(self.points[index]);
523 }
524 let mut groups = groups.into_iter().collect::<Vec<_>>();
525 groups.sort_by_key(|(_, points)| points.iter().min().copied());
526 groups
527 }
528}
529
530fn schematic_error(
531 definition: &SchematicDefinition,
532 message: impl Into<String>,
533) -> SourceBundleError {
534 SourceBundleError::new(
535 SourceBundleErrorKind::Schematic,
536 Some(&definition.source_path),
537 message,
538 )
539}
540
541fn bus_expansion_error(
542 definition: &SchematicDefinition,
543 error: crate::SchematicBusExpansionError,
544) -> SourceBundleError {
545 let kind = if error.kind == SchematicBusExpansionErrorKind::ResourceLimit {
546 SourceBundleErrorKind::ResourceLimit
547 } else {
548 SourceBundleErrorKind::Schematic
549 };
550 SourceBundleError::new(kind, Some(&definition.source_path), error.to_string())
551}