1use crate::sexpr::{ErrorKind, Sexp, parse};
5use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
6use crate::{
7 SchematicConnectionSourceView, SchematicDocument, SchematicLibrarySource,
8 SchematicNativeLoadedPoint, SchematicPoint, SchematicSourceForm, SchematicSymbolSourceView,
9 SourceBundleError, SourceBundleErrorKind, native_loaded_library_pin_point,
10};
11use std::collections::{BTreeMap, BTreeSet};
12use std::ops::Range;
13
14mod jumper_groups;
15pub use jumper_groups::{
16 SchematicJumperGroupRecord, SchematicJumperPin, SchematicJumperPinSelector,
17 SchematicLibraryJumperGroups, SchematicNativeJumperGroup,
18};
19
20#[derive(Clone, Copy, Debug)]
21pub struct SchematicPowerSourceLimits {
22 pub max_source_bytes: usize,
23 pub max_scan_bytes: usize,
24 pub max_pin_rows: usize,
25 pub max_inheritance_depth: usize,
26 pub max_contacts: usize,
27}
28impl Default for SchematicPowerSourceLimits {
29 fn default() -> Self {
30 Self {
31 max_source_bytes: 32 * 1024 * 1024,
32 max_scan_bytes: 64 * 1024 * 1024,
33 max_pin_rows: 100_000,
34 max_inheritance_depth: 128,
35 max_contacts: 1_000_000,
36 }
37 }
38}
39
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct SchematicPowerPinSelection {
45 pub unit: i64,
46 pub body_style: i64,
47}
48
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum SchematicNativePowerKind {
51 Ordinary,
52 Global,
53 Local,
54}
55
56#[derive(Clone, Copy, Debug, Eq, PartialEq)]
57pub enum SchematicNativePinElectricalType {
58 Input,
59 Output,
60 Bidirectional,
61 TriState,
62 Passive,
63 Unspecified,
64 PowerInput,
65 PowerOutput,
66 OpenCollector,
67 OpenEmitter,
68 Free,
69 NoConnect,
70}
71impl SchematicNativePinElectricalType {
72 pub fn propagates(self) -> bool {
73 self != Self::NoConnect
74 }
75}
76
77#[derive(Clone, Debug, Eq, PartialEq)]
81pub enum SchematicPowerNameSource {
82 None,
83 SymbolValue,
84 LibraryPinName(String),
85}
86
87#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
90pub struct SchematicNativePinSelector {
91 pub placement_ordinal: usize,
92 pub library_ordinal: usize,
93 pub drawing_ordinal: usize,
94 pub pin_ordinal: usize,
95}
96
97#[derive(Clone, Debug)]
98pub struct SchematicNativePowerPinFacts {
99 pub parent_power: SchematicNativePowerKind,
100 pub electrical_type: SchematicNativePinElectricalType,
101 pub hidden: bool,
102 pub base_name: String,
103 pub power_kind: SchematicNativePowerKind,
104 pub name_source: SchematicPowerNameSource,
105 pub position: SchematicNativeLoadedPoint,
106}
107
108#[derive(Clone, Debug)]
111pub struct SchematicNativePowerPin<'a> {
112 source: &'a str,
113 selector: SchematicNativePinSelector,
114 selection: SchematicPowerPinSelection,
115 facts: SchematicNativePowerPinFacts,
116}
117impl SchematicNativePowerPin<'_> {
118 pub(crate) fn selection(&self) -> SchematicPowerPinSelection {
119 self.selection
120 }
121 pub(crate) fn belongs_to_source(&self, source: &str) -> bool {
122 self.source.len() == source.len() && std::ptr::eq(self.source.as_ptr(), source.as_ptr())
123 }
124 pub fn selector(&self) -> SchematicNativePinSelector {
125 self.selector
126 }
127 pub fn facts(&self) -> &SchematicNativePowerPinFacts {
128 &self.facts
129 }
130}
131
132#[derive(Clone, Debug)]
133pub struct SchematicNativePowerPinRecord<'a> {
134 pub selector: SchematicNativePinSelector,
135 pub source_range: Range<usize>,
136 pub uuid: Result<Option<String>, SourceBundleError>,
137 pub number: Result<Option<String>, SourceBundleError>,
138 pub pin: Result<SchematicNativePowerPin<'a>, SourceBundleError>,
139}
140
141#[derive(Clone, Debug)]
142pub struct SchematicPowerParent<'a> {
143 pub source: SchematicSourceForm<'a>,
144 pub selected_library: String,
145 pub root_library: String,
146 pub parent_power: SchematicNativePowerKind,
147}
148
149#[derive(Clone, Debug)]
152pub struct SchematicPowerSelectionInventory<'a> {
153 pub source: SchematicSourceForm<'a>,
154 unit_count: i64,
155 body_style_count: i64,
156}
157impl SchematicPowerSelectionInventory<'_> {
158 pub fn admits(&self, selection: SchematicPowerPinSelection) -> bool {
159 selection.unit > 0
160 && selection.unit <= self.unit_count
161 && selection.body_style > 0
162 && selection.body_style <= self.body_style_count
163 }
164}
165
166#[derive(Clone, Debug)]
167pub struct SchematicPowerPlacement<'a> {
168 pub source: SchematicSourceForm<'a>,
169 pub selected_library: String,
170 pub root_library: String,
171 pub parent_power: SchematicNativePowerKind,
172 pub pins: Vec<SchematicNativePowerPinRecord<'a>>,
173}
174
175#[derive(Clone, Debug)]
176pub struct SchematicNativePinContextIssue {
177 pub placement_ordinal: usize,
178 pub pin: Option<SchematicNativePinSelector>,
179 pub error: SourceBundleError,
180}
181
182#[derive(Clone, Debug)]
185pub struct SchematicNativePinContext<'a> {
186 source: &'a str,
187 complete: bool,
188 pins: Vec<SchematicNativePowerPin<'a>>,
189 issues: Vec<SchematicNativePinContextIssue>,
190}
191impl<'a> SchematicNativePinContext<'a> {
192 pub(crate) fn without_selections(
193 source: &'a str,
194 path: &str,
195 placement_count: usize,
196 ) -> Result<Self, SourceBundleError> {
197 let mut issues = Vec::new();
198 issues.try_reserve_exact(placement_count).map_err(|_| {
199 failure(
200 path,
201 SourceBundleErrorKind::ResourceLimit,
202 "unselected native pin context issue allocation failed",
203 )
204 })?;
205 for placement_ordinal in 0..placement_count {
206 issues.push(SchematicNativePinContextIssue { placement_ordinal, pin: None,
207 error: content(path, "native pin context has no qualified effective selection for this original placement") });
208 }
209 Ok(Self {
210 source,
211 complete: placement_count == 0,
212 pins: Vec::new(),
213 issues,
214 })
215 }
216 pub fn is_complete(&self) -> bool {
217 self.complete
218 }
219 pub fn pins(&self) -> &[SchematicNativePowerPin<'a>] {
220 &self.pins
221 }
222 pub fn issues(&self) -> &[SchematicNativePinContextIssue] {
223 &self.issues
224 }
225 pub(crate) fn belongs_to_source(&self, source: &str) -> bool {
226 self.source.len() == source.len() && std::ptr::eq(self.source.as_ptr(), source.as_ptr())
227 }
228}
229
230#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
231pub enum SchematicNativePinContactTarget {
232 WireEndpoint { wire_ordinal: usize, vertex: u8 },
233 Junction { junction_ordinal: usize },
234 Pin(SchematicNativePinSelector),
235}
236#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
237pub struct SchematicNativePinContact {
238 pub pin: SchematicNativePinSelector,
239 pub target: SchematicNativePinContactTarget,
240}
241#[derive(Clone, Copy, Debug, Eq, PartialEq)]
242pub enum SchematicPowerContactIssueKind {
243 Wire,
244 Junction,
245}
246#[derive(Clone, Debug)]
247pub struct SchematicPowerContactIssue {
248 pub kind: SchematicPowerContactIssueKind,
249 pub ordinal: usize,
250 pub source_range: Range<usize>,
251 pub error: SourceBundleError,
252}
253#[derive(Clone, Debug, Default)]
254pub struct SchematicNativePinContacts {
255 pub contacts: Vec<SchematicNativePinContact>,
256 pub issues: Vec<SchematicPowerContactIssue>,
257}
258
259#[derive(Debug)]
260pub struct SchematicPowerSourceView<'a> {
261 source: &'a str,
262 path: &'a str,
263 symbols: SchematicSymbolSourceView<'a>,
264 connections: SchematicConnectionSourceView<'a>,
265 limits: SchematicPowerSourceLimits,
266 file_version: Option<u32>,
267}
268
269struct ResolvedPowerRoot<'view, 'source> {
270 placed: SchematicSourceForm<'source>,
271 root: SchematicLibrarySource<'view>,
272 selected_library: String,
273 parent_power: SchematicNativePowerKind,
274}
275impl SchematicDocument {
276 pub fn power_sources(
277 &self,
278 limits: SchematicPowerSourceLimits,
279 ) -> Result<SchematicPowerSourceView<'_>, SourceBundleError> {
280 if self.source().len() > limits.max_source_bytes {
281 return Err(failure(
282 self.source_path(),
283 SourceBundleErrorKind::ResourceLimit,
284 "power source byte budget exceeded",
285 ));
286 }
287 let mut budget = Budget::new(limits, self.source_path());
288 row_preflight(self.source(), RowSelection::Views, &mut budget)?;
289 let root = direct(self.source(), &["version"], &mut budget)?;
290 let file_version = match root.as_slice() {
291 [] => None,
292 [version] => {
293 let form = parse_form(&self.source()[version.range.clone()], &mut budget)?;
294 match list(&form) {
295 [_, Sexp::Integer(value)] => Some(
296 u32::try_from(*value)
297 .map_err(|_| content(self.source_path(), "file version exceeds u32"))?,
298 ),
299 _ => {
300 return Err(content(
301 self.source_path(),
302 "file version requires one native integer",
303 ));
304 }
305 }
306 }
307 _ => return Err(content(self.source_path(), "ambiguous file version")),
308 };
309 budget.scan(self.source().len())?;
312 budget.scan(self.source().len())?;
313 Ok(SchematicPowerSourceView {
314 source: self.source(),
315 path: self.source_path(),
316 symbols: self.symbol_sources()?,
317 connections: self.connection_sources()?,
318 limits,
319 file_version,
320 })
321 }
322}
323
324impl<'a> SchematicPowerSourceView<'a> {
325 pub fn parent_power(
328 &self,
329 ordinal: usize,
330 ) -> Result<Option<SchematicPowerParent<'a>>, SourceBundleError> {
331 let mut budget = Budget::new(self.limits, self.path);
332 Ok(self
333 .resolve_root(ordinal, &mut budget)?
334 .map(|resolved| SchematicPowerParent {
335 source: resolved.placed,
336 selected_library: resolved.selected_library,
337 root_library: resolved.root.name.to_owned(),
338 parent_power: resolved.parent_power,
339 }))
340 }
341
342 pub fn selection_inventory(
345 &self,
346 ordinal: usize,
347 ) -> Result<Option<SchematicPowerSelectionInventory<'a>>, SourceBundleError> {
348 let mut budget = Budget::new(self.limits, self.path);
349 self.selection_inventory_with_budget(ordinal, &mut budget)
350 }
351
352 fn selection_inventory_with_budget(
353 &self,
354 ordinal: usize,
355 budget: &mut Budget<'_>,
356 ) -> Result<Option<SchematicPowerSelectionInventory<'a>>, SourceBundleError> {
357 let Some(resolved) = self.resolve_root(ordinal, budget)? else {
358 return Ok(None);
359 };
360 let root = resolved.root;
361 let drawings = direct(root.form.source, &["symbol", "body_styles"], budget)?;
362 let mut unit_count = 1;
363 let mut style_count = body_style_count(root.form.source, &drawings, budget)?;
364 for drawing in drawings
365 .iter()
366 .filter(|span| span.head.as_deref() == Some("symbol"))
367 {
368 let (unit, style) = self.drawing_header(&root, drawing, budget)?;
369 unit_count = unit_count.max(unit);
370 style_count = style_count.max(style);
371 }
372 Ok(Some(SchematicPowerSelectionInventory {
373 source: resolved.placed,
374 unit_count,
375 body_style_count: style_count,
376 }))
377 }
378
379 fn drawing_header(
380 &self,
381 root: &SchematicLibrarySource<'_>,
382 drawing: &FormSpan,
383 budget: &mut Budget<'_>,
384 ) -> Result<(i64, i64), SourceBundleError> {
385 let name = parse_header(&root.form.source[drawing.range.clone()], budget)?;
386 drawing_selection(&name, root.name, self.path)
387 }
388
389 pub fn placement_pins(
392 &self,
393 ordinal: usize,
394 selection: SchematicPowerPinSelection,
395 ) -> Result<Option<SchematicPowerPlacement<'a>>, SourceBundleError> {
396 let mut budget = Budget::new(self.limits, self.path);
397 self.placement_pins_with_budget(ordinal, selection, &mut budget)
398 }
399
400 #[allow(
401 clippy::too_many_lines,
402 reason = "power-pin placement reader resolves symbol geometry, transforms, and budget checks together"
403 )]
404 fn placement_pins_with_budget(
405 &self,
406 ordinal: usize,
407 selection: SchematicPowerPinSelection,
408 budget: &mut Budget<'_>,
409 ) -> Result<Option<SchematicPowerPlacement<'a>>, SourceBundleError> {
410 if selection.unit <= 0 || selection.body_style <= 0 {
411 return Err(failure(
412 self.path,
413 SourceBundleErrorKind::Contract,
414 "power pin selection requires positive unit/body style",
415 ));
416 }
417 let Some(ResolvedPowerRoot {
418 placed,
419 root: current,
420 selected_library,
421 parent_power,
422 }) = self.resolve_root(ordinal, budget)?
423 else {
424 return Ok(None);
425 };
426 let pose = self.symbols.native_loaded_pose(ordinal).and_then(|pose| {
427 pose.ok_or_else(|| {
428 failure(
429 self.path,
430 SourceBundleErrorKind::Contract,
431 "enumerated placement disappeared",
432 )
433 })
434 });
435 let placed_rows = placed_selections(&placed, budget)?;
436 let drawings = direct(current.form.source, &["symbol", "body_styles"], budget)?;
437 let mut rows = Vec::new();
438 let mut active = Vec::new();
439 let mut counts = BTreeMap::<String, usize>::new();
440 let mut unknown_library_number = false;
441 let mut checked_rows = 0;
442 let mut max_unit = 1;
443 let mut max_style = body_style_count(current.form.source, &drawings, budget)?;
444 for (drawing_ordinal, drawing) in drawings
445 .into_iter()
446 .filter(|span| span.head.as_deref() == Some("symbol"))
447 .enumerate()
448 {
449 let source = ¤t.form.source[drawing.range.clone()];
450 let (unit, style) = self.drawing_header(¤t, &drawing, budget)?;
451 max_unit = max_unit.max(unit);
452 max_style = max_style.max(style);
453 if !(style == 0 || style == selection.body_style) {
454 continue;
455 }
456 for (pin_ordinal, pin) in direct(source, &["pin"], budget)?.into_iter().enumerate() {
457 if checked_rows >= self.limits.max_pin_rows {
458 return Err(budget.limit("power pin row budget exceeded"));
459 }
460 checked_rows += 1;
461 let start = current.form.source_range.start + drawing.range.start + pin.range.start;
462 let source_range = start..start + pin.range.len();
463 let form = parse_form(&source[pin.range], budget)?;
464 let selector = SchematicNativePinSelector {
465 placement_ordinal: ordinal,
466 library_ordinal: current.form.ordinal,
467 drawing_ordinal,
468 pin_ordinal,
469 };
470 let uuid = child_scalar(&form, "uuid", self.path);
471 let number = child_scalar_prefix(&form, "number", self.path);
472 let matching_number = number.as_ref().map_err(Clone::clone).and_then(|number| {
473 number
474 .as_deref()
475 .map(|number| native_pin_text(number, self.file_version, self.path))
476 .transpose()
477 });
478 if let Ok(Some(number)) = &matching_number {
479 *counts.entry(number.clone()).or_default() += 1;
480 } else {
481 unknown_library_number = true;
482 }
483 if !(unit == 0 || unit == selection.unit) {
484 continue;
485 }
486 active.push((selector, source_range, form, uuid, number, matching_number));
487 }
488 }
489 if selection.unit > max_unit || selection.body_style > max_style {
490 return Err(failure(
491 self.path,
492 SourceBundleErrorKind::Contract,
493 "selected unit/body style is outside this root definition",
494 ));
495 }
496 for (selector, source_range, form, uuid, number, matching_number) in active {
497 let pin: Result<SchematicNativePowerPin<'a>, SourceBundleError> = (|| {
498 let number = matching_number
499 .as_ref()
500 .map_err(Clone::clone)?
501 .as_deref()
502 .ok_or_else(|| content(self.path, "library pin number is missing"))?;
503 let alternate = placed_rows.selection(number, counts[number], self.path)?;
504 if alternate.is_some() && unknown_library_number {
505 return Err(content(
506 self.path,
507 "unqualified library pin number prevents unambiguous native alternate selection",
508 ));
509 }
510 let facts =
511 pin_facts(&form, alternate, parent_power, self.file_version, self.path)?;
512 let position = pose
513 .as_ref()
514 .map_err(Clone::clone)?
515 .place_library_pin(native_loaded_library_pin_point(&form)?)?;
516 Ok(SchematicNativePowerPin {
517 source: self.source,
518 selector,
519 selection,
520 facts: SchematicNativePowerPinFacts { position, ..facts },
521 })
522 })();
523 if let Err(error) = &pin
524 && error.kind != SourceBundleErrorKind::Schematic
525 {
526 return Err(error.clone());
527 }
528 rows.push(SchematicNativePowerPinRecord {
529 selector,
530 source_range,
531 uuid,
532 number,
533 pin,
534 });
535 }
536 Ok(Some(SchematicPowerPlacement {
537 source: placed,
538 selected_library,
539 root_library: current.name.to_owned(),
540 parent_power,
541 pins: rows,
542 }))
543 }
544
545 #[allow(
551 clippy::too_many_lines,
552 reason = "native pin context collects all placement pins and malformed diagnostics in one pass"
553 )]
554 pub fn native_pin_context(
555 &self,
556 selections: &[(usize, SchematicPowerPinSelection)],
557 ) -> Result<SchematicNativePinContext<'a>, SourceBundleError> {
558 let mut budget = Budget::new(self.limits, self.path);
559 if selections.len() > self.limits.max_pin_rows
560 || self.symbols.placed_count() > self.limits.max_pin_rows
561 {
562 return Err(budget.limit("native pin context row budget exceeded"));
563 }
564 let mut requested = BTreeMap::new();
565 for &(ordinal, selection) in selections {
566 if selection.unit <= 0 || selection.body_style <= 0 {
567 return Err(failure(
568 self.path,
569 SourceBundleErrorKind::Contract,
570 "native pin context selection requires positive unit/body style",
571 ));
572 }
573 if ordinal >= self.symbols.placed_count()
574 || requested.insert(ordinal, selection).is_some()
575 {
576 return Err(failure(
577 self.path,
578 SourceBundleErrorKind::Contract,
579 "foreign or repeated native pin context placement selector",
580 ));
581 }
582 }
583 let mut result = SchematicNativePinContext {
584 source: self.source,
585 complete: true,
586 pins: Vec::new(),
587 issues: Vec::new(),
588 };
589 for ordinal in 0..self.symbols.placed_count() {
590 let Some(&selection) = requested.get(&ordinal) else {
591 if result.pins.len().saturating_add(result.issues.len()) >= self.limits.max_pin_rows
592 {
593 return Err(budget.limit("native pin context aggregate pin budget exceeded"));
594 }
595 result.complete = false;
596 result.issues.push(SchematicNativePinContextIssue {
597 placement_ordinal: ordinal, pin: None,
598 error: content(self.path, "native pin context has no qualified effective selection for this original placement"),
599 });
600 continue;
601 };
602 let read = (|| {
603 let inventory = self
604 .selection_inventory_with_budget(ordinal, &mut budget)?
605 .expect("checked original placement");
606 if !inventory.admits(selection) {
607 return Err(failure(
608 self.path,
609 SourceBundleErrorKind::Contract,
610 "native pin context selection is outside the checked source inventory",
611 ));
612 }
613 self.placement_pins_with_budget(ordinal, selection, &mut budget)
614 })();
615 let read = match read {
616 Ok(Some(read)) => read,
617 Ok(None) => unreachable!("checked original placement"),
618 Err(error) if error.kind == SourceBundleErrorKind::Schematic => {
619 if result.pins.len().saturating_add(result.issues.len())
620 >= self.limits.max_pin_rows
621 {
622 return Err(
623 budget.limit("native pin context aggregate pin budget exceeded")
624 );
625 }
626 result.complete = false;
627 result.issues.push(SchematicNativePinContextIssue {
628 placement_ordinal: ordinal,
629 pin: None,
630 error,
631 });
632 continue;
633 }
634 Err(error) => return Err(error),
635 };
636 if result
637 .pins
638 .len()
639 .saturating_add(result.issues.len())
640 .saturating_add(read.pins.len())
641 > self.limits.max_pin_rows
642 {
643 return Err(budget.limit("native pin context aggregate pin budget exceeded"));
644 }
645 for row in read.pins {
646 match row.pin {
647 Ok(pin) => result.pins.push(pin),
648 Err(error) if error.kind == SourceBundleErrorKind::Schematic => {
649 result.complete = false;
650 result.issues.push(SchematicNativePinContextIssue {
651 placement_ordinal: ordinal,
652 pin: Some(row.selector),
653 error,
654 });
655 }
656 Err(error) => return Err(error),
657 }
658 }
659 }
660 Ok(result)
661 }
662
663 fn resolve_root(
664 &self,
665 ordinal: usize,
666 budget: &mut Budget<'_>,
667 ) -> Result<Option<ResolvedPowerRoot<'_, 'a>>, SourceBundleError> {
668 let Some(placed) = self.symbols.placed_symbol_source(ordinal) else {
669 return Ok(None);
670 };
671 row_preflight(placed.source, RowSelection::AllForms, budget)?;
672 budget.scans(placed.source.len(), 8)?;
675 let mut current = self
676 .symbols
677 .selected_library_symbol_source(ordinal)?
678 .ok_or_else(|| {
679 content(
680 self.path,
681 "selected embedded power/pin definition is missing",
682 )
683 })?;
684 let selected_library = current.name.to_owned();
685 let mut visited = BTreeSet::new();
686 let mut declarations = Vec::new();
687 loop {
688 if !visited.insert(current.form.ordinal) {
689 return Err(content(self.path, "power definition inheritance cycle"));
690 }
691 if visited.len() > self.limits.max_inheritance_depth {
692 return Err(budget.limit("power inheritance depth budget exceeded"));
693 }
694 let header = direct(current.form.source, &["power", "extends"], budget)?;
695 declarations.push(power_kind(current.form.source, &header, budget)?);
696 let parent = one_span(&header, "extends", self.path)?
697 .map(|span| parse_form(¤t.form.source[span.range.clone()], budget))
698 .transpose()?
699 .map(|form| scalar(&form, "extends", self.path))
700 .transpose()?
701 .flatten();
702 let Some(parent) = parent else { break };
703 current = self
704 .symbols
705 .library_symbol_source_for_key(&parent)
706 .ok_or_else(|| content(self.path, "power definition parent is missing"))?;
707 }
708 let parent_power = declarations
709 .last()
710 .copied()
711 .flatten()
712 .unwrap_or(SchematicNativePowerKind::Ordinary);
713 if declarations
714 .iter()
715 .flatten()
716 .any(|kind| *kind != parent_power)
717 {
718 return Err(content(
719 self.path,
720 "contradictory derived power flags are outside the checked root-power profile",
721 ));
722 }
723 Ok(Some(ResolvedPowerRoot {
724 placed,
725 root: current,
726 selected_library,
727 parent_power,
728 }))
729 }
730
731 #[allow(
735 clippy::cognitive_complexity,
736 clippy::too_many_lines,
737 reason = "power-pin contact resolution checks pins, wires, and junctions explicitly"
738 )]
739 pub fn contacts(
740 &self,
741 pins: &[&SchematicNativePowerPin<'a>],
742 wire_ordinals: &[usize],
743 junction_ordinals: &[usize],
744 ) -> Result<SchematicNativePinContacts, SourceBundleError> {
745 let mut budget = Budget::new(self.limits, self.path);
746 if pins.len() > self.limits.max_pin_rows
747 || wire_ordinals.len().saturating_add(junction_ordinals.len())
748 > self.limits.max_pin_rows
749 {
750 return Err(budget.limit("power contact row budget exceeded"));
751 }
752 let mut seen = BTreeSet::new();
753 let mut selections = BTreeMap::new();
754 let mut by_point = BTreeMap::<SchematicPoint, Vec<SchematicNativePinSelector>>::new();
755 for pin in pins {
756 if pin.source.len() != self.source.len()
757 || !std::ptr::eq(pin.source.as_ptr(), self.source.as_ptr())
758 || !seen.insert(pin.selector)
759 {
760 return Err(failure(
761 self.path,
762 SourceBundleErrorKind::Contract,
763 "foreign or repeated power pin handle",
764 ));
765 }
766 if selections
767 .insert(pin.selector.placement_ordinal, pin.selection)
768 .is_some_and(|old| old != pin.selection)
769 {
770 return Err(failure(
771 self.path,
772 SourceBundleErrorKind::Contract,
773 "mixed effective selections for one original placement",
774 ));
775 }
776 if pin.facts.electrical_type.propagates() {
777 by_point
778 .entry(pin.facts.position.at)
779 .or_default()
780 .push(pin.selector);
781 }
782 }
783 validate_ordinals(wire_ordinals, self.connections.wire_count(), self.path)?;
784 validate_ordinals(
785 junction_ordinals,
786 self.connections.junction_count(),
787 self.path,
788 )?;
789 for &ordinal in wire_ordinals {
790 let form = self
791 .connections
792 .wire_source_form(ordinal)
793 .expect("checked wire");
794 row_preflight(form.source, RowSelection::AllForms, &mut budget)?;
795 budget.scans(form.source.len(), 32)?;
796 }
797 for &ordinal in junction_ordinals {
798 let form = self
799 .connections
800 .junction_source_form(ordinal)
801 .expect("checked junction");
802 row_preflight(form.source, RowSelection::AllForms, &mut budget)?;
803 budget.scans(form.source.len(), 32)?;
804 }
805 let mut result = SchematicNativePinContacts::default();
806 let mut emit = |pin, target| -> Result<(), SourceBundleError> {
807 if result.contacts.len() >= self.limits.max_contacts {
808 return Err(budget.limit("power contact output budget exceeded"));
809 }
810 result
811 .contacts
812 .push(SchematicNativePinContact { pin, target });
813 Ok(())
814 };
815 for group in by_point.values_mut() {
816 group.sort_unstable();
817 for (i, &pin) in group.iter().enumerate() {
818 for &other in group.iter().skip(i + 1) {
819 emit(pin, SchematicNativePinContactTarget::Pin(other))?;
820 }
821 }
822 }
823 for &ordinal in wire_ordinals {
824 let row = self
825 .connections
826 .native_loaded_wire(ordinal)
827 .expect("checked original wire selector");
828 match row.points {
829 Ok([a, b]) if a.at != b.at => {
830 for (vertex, at) in [(0, a.at), (1, b.at)] {
831 for &pin in by_point.get(&at).into_iter().flatten() {
832 emit(
833 pin,
834 SchematicNativePinContactTarget::WireEndpoint {
835 wire_ordinal: ordinal,
836 vertex,
837 },
838 )?;
839 }
840 }
841 }
842 points => {
843 let error = points.err().unwrap_or_else(|| {
844 content(
845 self.path,
846 "native zero-length wire has no retained contact target",
847 )
848 });
849 if error.kind != SourceBundleErrorKind::Schematic {
850 return Err(error);
851 }
852 result.issues.push(SchematicPowerContactIssue {
853 kind: SchematicPowerContactIssueKind::Wire,
854 ordinal,
855 source_range: row.source.form.source_range,
856 error,
857 });
858 }
859 }
860 }
861 for &ordinal in junction_ordinals {
862 let row = self
863 .connections
864 .native_loaded_junction(ordinal)
865 .expect("checked original junction selector");
866 match row.at {
867 Ok(point) => {
868 for &pin in by_point.get(&point.at).into_iter().flatten() {
869 emit(
870 pin,
871 SchematicNativePinContactTarget::Junction {
872 junction_ordinal: ordinal,
873 },
874 )?;
875 }
876 }
877 Err(error) => {
878 if error.kind != SourceBundleErrorKind::Schematic {
879 return Err(error);
880 }
881 result.issues.push(SchematicPowerContactIssue {
882 kind: SchematicPowerContactIssueKind::Junction,
883 ordinal,
884 source_range: row.source.form.source_range,
885 error,
886 });
887 }
888 }
889 }
890 result.contacts.sort_unstable();
891 result.issues.sort_by_key(|issue| {
892 (
893 match issue.kind {
894 SchematicPowerContactIssueKind::Wire => 0,
895 SchematicPowerContactIssueKind::Junction => 1,
896 },
897 issue.ordinal,
898 )
899 });
900 Ok(result)
901 }
902}
903
904struct Budget<'a> {
905 limits: SchematicPowerSourceLimits,
906 path: &'a str,
907 scanned: usize,
908}
909impl<'a> Budget<'a> {
910 fn new(limits: SchematicPowerSourceLimits, path: &'a str) -> Self {
911 Self {
912 limits,
913 path,
914 scanned: 0,
915 }
916 }
917 fn limit(&self, reason: &str) -> SourceBundleError {
918 failure(self.path, SourceBundleErrorKind::ResourceLimit, reason)
919 }
920 fn scan(&mut self, bytes: usize) -> Result<(), SourceBundleError> {
921 self.scanned = self
922 .scanned
923 .checked_add(bytes)
924 .ok_or_else(|| self.limit("power scan byte count overflow"))?;
925 if self.scanned > self.limits.max_scan_bytes {
926 return Err(self.limit("power scan byte budget exceeded"));
927 }
928 Ok(())
929 }
930 fn scans(&mut self, bytes: usize, passes: usize) -> Result<(), SourceBundleError> {
931 self.scan(
932 bytes
933 .checked_mul(passes)
934 .ok_or_else(|| self.limit("power scan byte count overflow"))?,
935 )
936 }
937}
938fn failure(path: &str, kind: SourceBundleErrorKind, reason: impl ToString) -> SourceBundleError {
939 SourceBundleError::new(kind, Some(path), reason.to_string())
940}
941fn content(path: &str, reason: impl ToString) -> SourceBundleError {
942 failure(path, SourceBundleErrorKind::Schematic, reason)
943}
944fn parse_form(source: &str, budget: &mut Budget<'_>) -> Result<Sexp, SourceBundleError> {
945 row_preflight(source, RowSelection::AllForms, budget)?;
946 budget.scan(source.len())?;
947 let path = budget.path;
948 parse(source).map_err(|error| {
949 failure(
950 path,
951 if error.kind == ErrorKind::ResourceLimit {
952 SourceBundleErrorKind::ResourceLimit
953 } else {
954 SourceBundleErrorKind::Schematic
955 },
956 error,
957 )
958 })
959}
960fn direct(
961 source: &str,
962 heads: &[&str],
963 budget: &mut Budget<'_>,
964) -> Result<Vec<FormSpan>, SourceBundleError> {
965 row_preflight(source, RowSelection::Direct(heads), budget)?;
966 budget.scan(source.len())?;
967 let spans = scan_form_spans(
968 source,
969 &Selector {
970 heads: Some(heads.iter().map(|head| (*head).to_owned()).collect()),
971 min_depth: Some(1),
972 max_depth: Some(1),
973 ..Default::default()
974 },
975 )
976 .map_err(|error| {
977 failure(
978 budget.path,
979 if error.kind == ErrorKind::ResourceLimit {
980 SourceBundleErrorKind::ResourceLimit
981 } else {
982 SourceBundleErrorKind::Schematic
983 },
984 error,
985 )
986 })?;
987 if spans.len() > budget.limits.max_pin_rows {
988 return Err(budget.limit("power selected row budget exceeded"));
989 }
990 Ok(spans)
991}
992enum RowSelection<'a> {
993 Views,
994 Direct(&'a [&'a str]),
995 AllForms,
996}
997fn row_preflight(
1000 source: &str,
1001 selection: RowSelection<'_>,
1002 budget: &mut Budget<'_>,
1003) -> Result<(), SourceBundleError> {
1004 use crate::sexpr::{Lexer, TokenKind};
1005 budget.scan(source.len())?;
1006 let mut depth = 0usize;
1007 let mut head = false;
1008 let mut count = 0usize;
1009 for token in Lexer::new(source) {
1010 let token = token.map_err(|error| {
1011 failure(
1012 budget.path,
1013 if error.kind == ErrorKind::ResourceLimit {
1014 SourceBundleErrorKind::ResourceLimit
1015 } else {
1016 SourceBundleErrorKind::Schematic
1017 },
1018 error,
1019 )
1020 })?;
1021 match token.kind {
1022 TokenKind::Left => {
1023 depth += 1;
1024 if matches!(&selection, RowSelection::AllForms) {
1025 if count >= budget.limits.max_pin_rows {
1026 return Err(
1027 budget.limit("power selected form budget exceeded before allocation")
1028 );
1029 }
1030 count += 1;
1031 }
1032 head = true;
1033 }
1034 TokenKind::Right => {
1035 depth = depth.saturating_sub(1);
1036 head = false;
1037 }
1038 _ if head => {
1039 let quoted = token.kind == TokenKind::QuotedString;
1043 let selected = match &selection {
1044 RowSelection::Views => {
1045 (depth == 2
1046 && (quoted || matches!(token.lexeme, "symbol" | "wire" | "junction")))
1047 || (depth == 3 && (quoted || token.lexeme == "symbol"))
1048 }
1049 RowSelection::Direct(heads) => {
1050 depth == 2 && (quoted || heads.contains(&token.lexeme))
1051 }
1052 RowSelection::AllForms => false,
1053 };
1054 if selected {
1055 if count >= budget.limits.max_pin_rows {
1056 return Err(budget
1057 .limit("power selected row budget exceeded before span allocation"));
1058 }
1059 count += 1;
1060 }
1061 head = false;
1062 }
1063 _ => {}
1064 }
1065 }
1066 Ok(())
1067}
1068fn list(form: &Sexp) -> &[Sexp] {
1069 match form {
1070 Sexp::List(items) => items,
1071 _ => &[],
1072 }
1073}
1074fn text(form: &Sexp) -> Option<&str> {
1075 match form {
1076 Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
1077 _ => None,
1078 }
1079}
1080fn children<'a>(form: &'a Sexp, key: &'a str) -> impl Iterator<Item = &'a Sexp> {
1081 list(form)
1082 .iter()
1083 .filter(move |item| list(item).first().and_then(text) == Some(key))
1084}
1085fn scalar(form: &Sexp, key: &str, path: &str) -> Result<Option<String>, SourceBundleError> {
1086 if list(form).len() != 2 {
1087 return Err(content(
1088 path,
1089 format!("{key} requires one string/atom scalar"),
1090 ));
1091 }
1092 text(&list(form)[1])
1093 .map(|text| Some(text.to_owned()))
1094 .ok_or_else(|| content(path, format!("{key} requires one string/atom scalar")))
1095}
1096fn child_scalar(form: &Sexp, key: &str, path: &str) -> Result<Option<String>, SourceBundleError> {
1097 let mut values = children(form, key);
1098 let Some(value) = values.next() else {
1099 return Ok(None);
1100 };
1101 if values.next().is_some() {
1102 return Err(content(path, format!("ambiguous {key}")));
1103 }
1104 scalar(value, key, path)
1105}
1106fn child_scalar_prefix(
1107 form: &Sexp,
1108 key: &str,
1109 path: &str,
1110) -> Result<Option<String>, SourceBundleError> {
1111 let mut values = children(form, key);
1112 let Some(value) = values.next() else {
1113 return Ok(None);
1114 };
1115 if values.next().is_some() {
1116 return Err(content(path, format!("ambiguous {key}")));
1117 }
1118 if list(value)
1119 .iter()
1120 .skip(1)
1121 .filter(|item| !matches!(item, Sexp::List(_)))
1122 .count()
1123 != 1
1124 {
1125 return Err(content(
1126 path,
1127 format!("{key} requires exactly one leading string/atom scalar"),
1128 ));
1129 }
1130 text(
1131 list(value)
1132 .get(1)
1133 .ok_or_else(|| content(path, format!("missing {key}")))?,
1134 )
1135 .map(|value| Some(value.to_owned()))
1136 .ok_or_else(|| content(path, format!("invalid {key}")))
1137}
1138fn one_span<'a>(
1139 spans: &'a [FormSpan],
1140 key: &str,
1141 path: &str,
1142) -> Result<Option<&'a FormSpan>, SourceBundleError> {
1143 let mut found = spans
1144 .iter()
1145 .filter(|span| span.head.as_deref() == Some(key));
1146 let one = found.next();
1147 if found.next().is_some() {
1148 return Err(content(path, format!("ambiguous {key}")));
1149 }
1150 Ok(one)
1151}
1152fn power_kind(
1153 source: &str,
1154 header: &[FormSpan],
1155 budget: &mut Budget<'_>,
1156) -> Result<Option<SchematicNativePowerKind>, SourceBundleError> {
1157 let path = budget.path;
1158 let Some(span) = one_span(header, "power", path)? else {
1159 return Ok(None);
1160 };
1161 let form = parse_form(&source[span.range.clone()], budget)?;
1162 Ok(Some(match list(&form) {
1163 [_] => SchematicNativePowerKind::Global,
1164 [_, Sexp::Atom(value)] if value == "global" => SchematicNativePowerKind::Global,
1165 [_, Sexp::Atom(value)] if value == "local" => SchematicNativePowerKind::Local,
1166 _ => {
1167 return Err(content(
1168 path,
1169 "power requires bare/global/local native grammar",
1170 ));
1171 }
1172 }))
1173}
1174fn parse_header(source: &str, budget: &mut Budget<'_>) -> Result<String, SourceBundleError> {
1176 budget.scan(source.len())?;
1177 let mut tokens = crate::sexpr::Lexer::new(source);
1178 let mut values = Vec::new();
1179 for _ in 0..3 {
1180 values.push(
1181 tokens
1182 .next()
1183 .ok_or_else(|| content(budget.path, "incomplete drawing header"))?
1184 .map_err(|e| content(budget.path, e))?,
1185 );
1186 }
1187 let name = &values[2];
1188 match name.kind {
1189 crate::sexpr::TokenKind::QuotedString => Ok(crate::sexpr::decode_quoted(name.lexeme)),
1190 crate::sexpr::TokenKind::Atom => Ok(name.lexeme.to_owned()),
1191 _ => Err(content(budget.path, "drawing name must be a string/atom")),
1192 }
1193}
1194fn drawing_selection(name: &str, root: &str, path: &str) -> Result<(i64, i64), SourceBundleError> {
1195 let local = root.rsplit(':').next().unwrap_or(root);
1196 let suffix = name
1197 .strip_prefix(&format!("{root}_"))
1198 .or_else(|| name.strip_prefix(&format!("{local}_")))
1199 .ok_or_else(|| content(path, "drawing name does not select its root symbol"))?;
1200 let (unit, style) = suffix
1201 .split_once('_')
1202 .ok_or_else(|| content(path, "drawing unit/style suffix is missing"))?;
1203 let unit = unit
1204 .parse::<i64>()
1205 .map_err(|_| content(path, "invalid drawing unit"))?;
1206 let style = style
1207 .parse::<i64>()
1208 .map_err(|_| content(path, "invalid drawing body style"))?;
1209 if unit < 0 || style < 0 {
1210 return Err(content(path, "negative drawing unit/style"));
1211 }
1212 Ok((unit, style))
1213}
1214fn body_style_count(
1215 source: &str,
1216 spans: &[FormSpan],
1217 budget: &mut Budget<'_>,
1218) -> Result<i64, SourceBundleError> {
1219 let path = budget.path;
1220 let Some(span) = one_span(spans, "body_styles", path)? else {
1221 return Ok(1);
1222 };
1223 let form = parse_form(&source[span.range.clone()], budget)?;
1224 match &list(&form)[1..] {
1225 [Sexp::Atom(value)] if value == "demorgan" => Ok(2),
1226 values
1227 if !values.is_empty()
1228 && values.iter().all(|value| matches!(value, Sexp::Quoted(_))) =>
1229 {
1230 i64::try_from(values.len()).map_err(|_| {
1231 failure(
1232 path,
1233 SourceBundleErrorKind::ResourceLimit,
1234 "body style count exceeds i64",
1235 )
1236 })
1237 }
1238 _ => Err(content(
1239 path,
1240 "invalid pinned-native body style declaration",
1241 )),
1242 }
1243}
1244struct PlacedSelections {
1245 rows: BTreeMap<String, Vec<Result<Option<String>, SourceBundleError>>>,
1246 unknown: bool,
1247}
1248impl PlacedSelections {
1249 fn selection<'a>(
1250 &'a self,
1251 number: &str,
1252 library_count: usize,
1253 path: &str,
1254 ) -> Result<Option<&'a str>, SourceBundleError> {
1255 if self.unknown {
1256 return Err(content(
1257 path,
1258 "unreadable placed pin number prevents checked alternate selection",
1259 ));
1260 }
1261 let Some(rows) = self.rows.get(number) else {
1262 return Ok(None);
1263 };
1264 let mut selected = None;
1265 for row in rows {
1266 if let Some(name) = row
1267 .as_ref()
1268 .map_err(Clone::clone)?
1269 .as_deref()
1270 .filter(|name| !name.is_empty())
1271 {
1272 selected = Some(name);
1273 }
1274 }
1275 if selected.is_some() && (rows.len() != 1 || library_count != 1) {
1276 return Err(content(path, "ambiguous placed alternate selection"));
1277 }
1278 Ok(selected)
1279 }
1280}
1281fn placed_selections(
1282 placed: &SchematicSourceForm<'_>,
1283 budget: &mut Budget<'_>,
1284) -> Result<PlacedSelections, SourceBundleError> {
1285 let mut result = PlacedSelections {
1286 rows: BTreeMap::new(),
1287 unknown: false,
1288 };
1289 for span in direct(placed.source, &["pin"], budget)? {
1290 if result.rows.len() >= budget.limits.max_pin_rows {
1291 return Err(budget.limit("placed pin row budget exceeded"));
1292 }
1293 let form = parse_form(&placed.source[span.range], budget)?;
1294 let number = list(&form).get(1).and_then(text);
1295 let leading = list(&form)
1296 .iter()
1297 .skip(1)
1298 .filter(|item| !matches!(item, Sexp::List(_)))
1299 .count();
1300 match number.filter(|_| leading == 1) {
1301 Some(number) => result
1302 .rows
1303 .entry(number.to_owned())
1304 .or_default()
1305 .push(child_scalar(&form, "alternate", budget.path)),
1306 None => result.unknown = true,
1307 }
1308 }
1309 Ok(result)
1310}
1311fn electrical(
1312 form: &Sexp,
1313 path: &str,
1314) -> Result<SchematicNativePinElectricalType, SourceBundleError> {
1315 use SchematicNativePinElectricalType::*;
1316 match form {
1317 Sexp::Atom(value) => Ok(match value.as_str() {
1318 "input" => Input,
1319 "output" => Output,
1320 "bidirectional" => Bidirectional,
1321 "tri_state" => TriState,
1322 "passive" => Passive,
1323 "unspecified" => Unspecified,
1324 "power_in" => PowerInput,
1325 "power_out" => PowerOutput,
1326 "open_collector" => OpenCollector,
1327 "open_emitter" => OpenEmitter,
1328 "free" => Free,
1329 "no_connect" | "unconnected" => NoConnect,
1330 _ => return Err(content(path, "unknown native electrical pin type")),
1331 }),
1332 _ => Err(content(
1333 path,
1334 "electrical pin type must be a bare native keyword",
1335 )),
1336 }
1337}
1338fn hidden(form: &Sexp, path: &str) -> Result<bool, SourceBundleError> {
1339 let bare = list(form)
1340 .iter()
1341 .filter(|item| matches!(item,Sexp::Atom(value)if value=="hide"))
1342 .count();
1343 let values = children(form, "hide").collect::<Vec<_>>();
1344 if bare + values.len() > 1 {
1345 return Err(content(path, "ambiguous pin hide flag"));
1346 }
1347 if bare == 1 {
1348 return Ok(true);
1349 }
1350 let Some(value) = values.first() else {
1351 return Ok(false);
1352 };
1353 match list(value) {
1354 [_] => Ok(true),
1355 [_, Sexp::Atom(value)] if value == "yes" => Ok(true),
1356 [_, Sexp::Atom(value)] if value == "no" => Ok(false),
1357 _ => Err(content(path, "invalid native pin hide flag")),
1358 }
1359}
1360fn pin_facts(
1361 form: &Sexp,
1362 alternate: Option<&str>,
1363 parent_power: SchematicNativePowerKind,
1364 version: Option<u32>,
1365 path: &str,
1366) -> Result<SchematicNativePowerPinFacts, SourceBundleError> {
1367 let primary = electrical(
1368 list(form)
1369 .get(1)
1370 .ok_or_else(|| content(path, "pin electrical type is missing"))?,
1371 path,
1372 )?;
1373 shape(list(form).get(2), path)?;
1374 let raw_name = child_scalar_prefix(form, "name", path)?.unwrap_or_default();
1375 let base_name = native_pin_text(&raw_name, version, path)?;
1376 let mut selected = primary;
1377 if let Some(name) = alternate.filter(|name| !name.is_empty() && *name != base_name) {
1378 let mut found = None;
1379 for alt in children(form, "alternate") {
1380 let values = list(alt);
1381 if values.get(1).and_then(text) != Some(name) {
1382 continue;
1383 }
1384 if found.is_some() || values.len() != 4 {
1385 return Err(content(
1386 path,
1387 "ambiguous/malformed selected native alternate",
1388 ));
1389 }
1390 shape(values.get(3), path)?;
1391 found = Some(electrical(&values[2], path)?);
1392 }
1393 selected =
1394 found.ok_or_else(|| content(path, "selected native alternate is unavailable"))?;
1395 }
1396 let hidden = hidden(form, path)?;
1397 let power_kind = if selected != SchematicNativePinElectricalType::PowerInput {
1398 SchematicNativePowerKind::Ordinary
1399 } else {
1400 match parent_power {
1401 SchematicNativePowerKind::Ordinary if hidden => SchematicNativePowerKind::Global,
1402 kind => kind,
1403 }
1404 };
1405 let name_source = match (power_kind, parent_power) {
1406 (SchematicNativePowerKind::Ordinary, _) => SchematicPowerNameSource::None,
1407 (_, SchematicNativePowerKind::Ordinary) => {
1408 SchematicPowerNameSource::LibraryPinName(base_name.clone())
1409 }
1410 _ => SchematicPowerNameSource::SymbolValue,
1411 };
1412 Ok(SchematicNativePowerPinFacts {
1413 parent_power,
1414 electrical_type: selected,
1415 hidden,
1416 base_name,
1417 power_kind,
1418 name_source,
1419 position: SchematicNativeLoadedPoint {
1420 at: SchematicPoint { x_iu: 0, y_iu: 0 },
1421 normalized: false,
1422 clamped: false,
1423 },
1424 })
1425}
1426fn shape(form: Option<&Sexp>, path: &str) -> Result<(), SourceBundleError> {
1427 match form {
1428 Some(Sexp::Atom(value))
1429 if matches!(
1430 value.as_str(),
1431 "line"
1432 | "inverted"
1433 | "clock"
1434 | "inverted_clock"
1435 | "input_low"
1436 | "clock_low"
1437 | "output_low"
1438 | "edge_clock_high"
1439 | "non_logic"
1440 ) =>
1441 {
1442 Ok(())
1443 }
1444 _ => Err(content(path, "invalid native pin graphic shape")),
1445 }
1446}
1447fn native_pin_text(
1450 raw: &str,
1451 version: Option<u32>,
1452 path: &str,
1453) -> Result<String, SourceBundleError> {
1454 if raw.contains('~') && version.is_none() {
1455 return Err(content(
1456 path,
1457 "native tilde pin text requires the source file version",
1458 ));
1459 }
1460 if raw != "~" && raw.contains('~') && version.is_some_and(|version| version < 20210606) {
1461 return Err(content(
1462 path,
1463 "pre20210606 pin overbar conversion is outside the checked native profile",
1464 ));
1465 }
1466 if raw == "~" && version.is_some_and(|version| version < 20250318) {
1467 Ok(String::new())
1468 } else {
1469 Ok(raw.replace(' ', "_"))
1470 }
1471}
1472fn validate_ordinals(
1473 ordinals: &[usize],
1474 count: usize,
1475 path: &str,
1476) -> Result<(), SourceBundleError> {
1477 let mut seen = BTreeSet::new();
1478 for &ordinal in ordinals {
1479 if ordinal >= count || !seen.insert(ordinal) {
1480 return Err(failure(
1481 path,
1482 SourceBundleErrorKind::Contract,
1483 "foreign or repeated original connection selector",
1484 ));
1485 }
1486 }
1487 Ok(())
1488}