1use crate::types::codegen::HasDefaultLayoutBundle;
4use schematic::{
5 HasNodeBundle, HasTerminalBundle, Node, NodeBundle, SchematicBundleKind, Terminal,
6 TerminalBundle,
7};
8
9use geometry::point::Point;
10use geometry::transform::{TransformRef, TranslateRef};
11
12use crate::schematic::{HasNestedView, NestedView};
13use std::fmt::Display;
14use std::ops::IndexMut;
15use std::{ops::DerefMut, slice::SliceIndex};
16
17use super::*;
18
19impl FlatLen for () {
20 fn len(&self) -> usize {
21 0
22 }
23}
24
25impl Flatten<Direction> for () {
26 fn flatten<E>(&self, _output: &mut E)
27 where
28 E: Extend<Direction>,
29 {
30 }
31}
32
33impl Flatten<Node> for () {
34 fn flatten<E>(&self, _output: &mut E)
35 where
36 E: Extend<Node>,
37 {
38 }
39}
40
41impl Flatten<Terminal> for () {
42 fn flatten<E>(&self, _output: &mut E)
43 where
44 E: Extend<Terminal>,
45 {
46 }
47}
48
49impl<D, T> Unflatten<D, T> for () {
50 fn unflatten<I>(_data: &D, _source: &mut I) -> Option<Self>
51 where
52 I: Iterator<Item = T>,
53 {
54 Some(())
55 }
56}
57
58impl HasNameTree for () {
59 fn names(&self) -> Option<Vec<NameTree>> {
60 None
61 }
62}
63
64impl HasBundleKind for () {
65 type BundleKind = ();
66
67 fn kind(&self) -> Self::BundleKind {}
68}
69
70impl HasNodeBundle for () {
71 type NodeBundle = ();
72}
73
74impl HasTerminalBundle for () {
75 type TerminalBundle = ();
76}
77
78impl SchematicBundleKind for () {
79 fn terminal_view(
80 _cell: CellId,
81 _cell_io: &NodeBundle<Self>,
82 _instance: InstanceId,
83 _instance_io: &NodeBundle<Self>,
84 ) -> TerminalBundle<Self> {
85 }
86}
87
88impl FlatLen for Signal {
89 fn len(&self) -> usize {
90 1
91 }
92}
93
94impl HasNameTree for Signal {
95 fn names(&self) -> Option<Vec<NameTree>> {
96 Some(vec![])
97 }
98}
99
100impl HasBundleKind for Signal {
101 type BundleKind = Signal;
102
103 fn kind(&self) -> Self::BundleKind {
104 Signal
105 }
106}
107
108impl HasNodeBundle for Signal {
109 type NodeBundle = Node;
110}
111
112impl HasTerminalBundle for Signal {
113 type TerminalBundle = Terminal;
114}
115
116impl SchematicBundleKind for Signal {
117 fn terminal_view(
118 cell: CellId,
119 cell_io: &NodeBundle<Self>,
120 instance: InstanceId,
121 instance_io: &NodeBundle<Self>,
122 ) -> TerminalBundle<Self> {
123 Terminal {
124 cell_id: cell,
125 cell_node: *cell_io,
126 instance_id: instance,
127 instance_node: *instance_io,
128 }
129 }
130}
131
132macro_rules! impl_direction {
133 ($dir:ident, $flatten_dir_bound:path, $flatten_dir_body:item) => {
134 impl<T> AsRef<T> for $dir<T> {
135 fn as_ref(&self) -> &T {
136 &self.0
137 }
138 }
139
140 impl<T> Deref for $dir<T> {
141 type Target = T;
142 fn deref(&self) -> &Self::Target {
143 &self.0
144 }
145 }
146
147 impl<T> DerefMut for $dir<T> {
148 fn deref_mut(&mut self) -> &mut Self::Target {
149 &mut self.0
150 }
151 }
152
153 impl<T> From<T> for $dir<T> {
154 fn from(value: T) -> Self {
155 $dir(value)
156 }
157 }
158
159 impl<T> Borrow<T> for $dir<T> {
160 fn borrow(&self) -> &T {
161 &self.0
162 }
163 }
164
165 impl<T: FlatLen> FlatLen for $dir<T> {
166 #[inline]
167 fn len(&self) -> usize {
168 self.0.len()
169 }
170 }
171
172 impl<T: $flatten_dir_bound> Flatten<Direction> for $dir<T> {
173 $flatten_dir_body
174 }
175
176 impl<T: HasBundleKind> HasBundleKind for $dir<T> {
177 type BundleKind = T::BundleKind;
178
179 fn kind(&self) -> Self::BundleKind {
180 self.0.kind()
181 }
182 }
183
184 impl<T: HasNameTree> HasNameTree for $dir<T> {
185 fn names(&self) -> Option<Vec<NameTree>> {
186 self.0.names()
187 }
188 }
189
190 impl<T: HasNodeBundle> HasNodeBundle for $dir<T> {
191 type NodeBundle = T::NodeBundle;
192 }
193
194 impl<T: HasTerminalBundle> HasTerminalBundle for $dir<T> {
195 type TerminalBundle = T::TerminalBundle;
196 }
197
198 impl<T: HasDefaultLayoutBundle> HasDefaultLayoutBundle for $dir<T> {
199 type Bundle<S: crate::layout::schema::Schema> = <T as HasDefaultLayoutBundle>::Bundle<S>;
200 }
201 };
202}
203
204impl_direction!(
205 Input,
206 FlatLen,
207 fn flatten<E>(&self, output: &mut E)
208 where
209 E: Extend<Direction>,
210 {
211 output.extend(std::iter::repeat_n(Direction::Input, self.0.len()))
212 }
213);
214impl_direction!(
215 Output,
216 FlatLen,
217 fn flatten<E>(&self, output: &mut E)
218 where
219 E: Extend<Direction>,
220 {
221 output.extend(std::iter::repeat_n(Direction::Output, self.0.len()))
222 }
223);
224impl_direction!(
225 InOut,
226 FlatLen,
227 fn flatten<E>(&self, output: &mut E)
228 where
229 E: Extend<Direction>,
230 {
231 output.extend(std::iter::repeat_n(Direction::InOut, self.0.len()))
232 }
233);
234impl_direction!(
235 Flipped,
236 Flatten<Direction>,
237 fn flatten<E>(&self, output: &mut E)
238 where
239 E: Extend<Direction>,
240 {
241 let inner = self.0.flatten_vec();
242 output.extend(inner.into_iter().map(|d| d.flip()))
243 }
244);
245
246impl<T: FlatLen> FlatLen for Array<T> {
247 fn len(&self) -> usize {
248 self.kind.len() * self.len
249 }
250}
251
252impl<T: Flatten<Direction>> Flatten<Direction> for Array<T> {
253 fn flatten<E>(&self, output: &mut E)
254 where
255 E: Extend<Direction>,
256 {
257 for _ in 0..self.len {
258 self.kind.flatten(output);
259 }
260 }
261}
262
263impl<T: HasNameTree> HasNameTree for Array<T> {
264 fn names(&self) -> Option<Vec<NameTree>> {
265 if self.len == 0 {
266 return None;
267 }
268 let inner = self.kind.names()?;
269 Some(
270 (0..self.len)
271 .map(|i| NameTree {
272 fragment: Some(NameFragment::Idx(i)),
273 children: inner.clone(),
274 })
275 .collect(),
276 )
277 }
278}
279impl<T: HasNodeBundle> HasNodeBundle for Array<T> {
280 type NodeBundle = ArrayBundle<T::NodeBundle>;
281}
282
283impl<T: HasTerminalBundle> HasTerminalBundle for Array<T> {
284 type TerminalBundle = ArrayBundle<T::TerminalBundle>;
285}
286
287impl<T: SchematicBundleKind> SchematicBundleKind for Array<T> {
288 fn terminal_view(
289 cell: CellId,
290 cell_io: &NodeBundle<Self>,
291 instance: InstanceId,
292 instance_io: &NodeBundle<Self>,
293 ) -> TerminalBundle<Self> {
294 ArrayBundle {
295 elems: cell_io
296 .elems
297 .iter()
298 .zip(instance_io.elems.iter())
299 .map(|(cell_elem, instance_elem)| {
300 <T as SchematicBundleKind>::terminal_view(
301 cell,
302 cell_elem,
303 instance,
304 instance_elem,
305 )
306 })
307 .collect(),
308 kind: cell_io.kind.clone(),
309 }
310 }
311}
312
313impl<T: HasBundleKind> HasBundleKind for Array<T> {
314 type BundleKind = Array<<T as HasBundleKind>::BundleKind>;
315
316 fn kind(&self) -> Self::BundleKind {
317 Array::new(self.len, self.kind.kind())
318 }
319}
320
321impl<T: HasBundleKind> HasBundleKind for ArrayBundle<T> {
322 type BundleKind = Array<<T as HasBundleKind>::BundleKind>;
323
324 fn kind(&self) -> Self::BundleKind {
325 Array::new(self.elems.len(), self.kind.clone())
326 }
327}
328
329impl<T: HasBundleKind + FlatLen> FlatLen for ArrayBundle<T> {
330 fn len(&self) -> usize {
331 self.elems.len() * self.kind.len()
332 }
333}
334
335impl<S, T: HasBundleKind + Flatten<S>> Flatten<S> for ArrayBundle<T> {
336 fn flatten<E>(&self, output: &mut E)
337 where
338 E: Extend<S>,
339 {
340 self.elems.iter().for_each(|e| e.flatten(output));
341 }
342}
343
344impl<S, T: HasBundleKind + Unflatten<<T as HasBundleKind>::BundleKind, S>>
345 Unflatten<Array<<T as HasBundleKind>::BundleKind>, S> for ArrayBundle<T>
346{
347 fn unflatten<I>(data: &Array<<T as HasBundleKind>::BundleKind>, source: &mut I) -> Option<Self>
348 where
349 I: Iterator<Item = S>,
350 {
351 let mut elems = Vec::new();
352 for _ in 0..data.len {
353 elems.push(T::unflatten(&data.kind, source)?);
354 }
355 Some(ArrayBundle {
356 elems,
357 kind: data.kind.clone(),
358 })
359 }
360}
361
362impl<
363 T: HasBundleKind
364 + HasNestedView<NestedView: HasBundleKind<BundleKind = <T as HasBundleKind>::BundleKind>>,
365> HasNestedView for ArrayBundle<T>
366{
367 type NestedView = ArrayBundle<NestedView<T>>;
368 fn nested_view(&self, parent: &InstancePath) -> NestedView<Self> {
369 ArrayBundle {
370 elems: self
371 .elems
372 .iter()
373 .map(|elem| elem.nested_view(parent))
374 .collect(),
375 kind: self.kind.clone(),
376 }
377 }
378}
379
380impl<T: HasBundleKind + TranslateRef> TranslateRef for ArrayBundle<T> {
381 fn translate_ref(&self, p: Point) -> Self {
382 Self {
383 elems: self
384 .elems
385 .iter()
386 .map(|elem| elem.translate_ref(p))
387 .collect(),
388 kind: self.kind.clone(),
389 }
390 }
391}
392
393impl<T: HasBundleKind + TransformRef> TransformRef for ArrayBundle<T> {
394 fn transform_ref(&self, trans: geometry::prelude::Transformation) -> Self {
395 Self {
396 elems: self
397 .elems
398 .iter()
399 .map(|elem| elem.transform_ref(trans))
400 .collect(),
401 kind: self.kind.clone(),
402 }
403 }
404}
405
406impl<T: HasBundleKind, I> Index<I> for ArrayBundle<T>
407where
408 I: SliceIndex<[T]>,
409{
410 type Output = <I as SliceIndex<[T]>>::Output;
411 #[inline]
412 fn index(&self, index: I) -> &Self::Output {
413 Index::index(&self.elems, index)
414 }
415}
416
417impl<T: HasBundleKind, I> IndexMut<I> for ArrayBundle<T>
418where
419 I: SliceIndex<[T]>,
420{
421 #[inline]
422 fn index_mut(&mut self, index: I) -> &mut Self::Output {
423 IndexMut::index_mut(&mut self.elems, index)
424 }
425}
426
427impl From<ArcStr> for NameFragment {
428 fn from(value: ArcStr) -> Self {
429 Self::Str(value)
430 }
431}
432
433impl From<&ArcStr> for NameFragment {
434 fn from(value: &ArcStr) -> Self {
435 Self::Str(value.clone())
436 }
437}
438
439impl From<&str> for NameFragment {
440 fn from(value: &str) -> Self {
441 Self::Str(ArcStr::from(value))
442 }
443}
444
445impl From<usize> for NameFragment {
446 fn from(value: usize) -> Self {
447 Self::Idx(value)
448 }
449}
450
451impl From<ArcStr> for NameBuf {
452 fn from(value: ArcStr) -> Self {
453 Self {
454 fragments: vec![NameFragment::from(value)],
455 }
456 }
457}
458
459impl From<&ArcStr> for NameBuf {
460 fn from(value: &ArcStr) -> Self {
461 Self {
462 fragments: vec![NameFragment::from(value)],
463 }
464 }
465}
466
467impl From<&str> for NameBuf {
468 fn from(value: &str) -> Self {
469 Self {
470 fragments: vec![NameFragment::from(value)],
471 }
472 }
473}
474
475impl From<usize> for NameBuf {
476 fn from(value: usize) -> Self {
477 Self {
478 fragments: vec![NameFragment::from(value)],
479 }
480 }
481}
482
483impl Display for NameFragment {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 match self {
486 Self::Str(s) => write!(f, "{s}"),
487 Self::Idx(i) => write!(f, "{i}"),
488 }
489 }
490}
491
492impl Display for NameBuf {
493 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494 if let Some(fragment) = self.fragments.first() {
495 write!(f, "{fragment}")?;
496 }
497 for fragment in self.fragments.iter().skip(1) {
498 write!(f, "_{fragment}")?;
499 }
500 Ok(())
501 }
502}
503
504impl NameTree {
505 pub fn new(fragment: impl Into<NameFragment>, children: Vec<NameTree>) -> Self {
507 Self {
508 fragment: Some(fragment.into()),
509 children,
510 }
511 }
512
513 pub fn with_optional_fragment(
515 fragment: Option<impl Into<NameFragment>>,
516 children: Vec<NameTree>,
517 ) -> Self {
518 Self {
519 fragment: fragment.map(|f| f.into()),
520 children,
521 }
522 }
523
524 pub fn with_empty_fragment(children: Vec<NameTree>) -> Self {
526 Self {
527 fragment: None,
528 children,
529 }
530 }
531
532 pub fn flatten(&self) -> Vec<NameBuf> {
534 self.flatten_inner(NameBuf::new())
535 }
536
537 fn flatten_inner(&self, mut parent: NameBuf) -> Vec<NameBuf> {
538 if let Some(fragment) = self.fragment.clone() {
539 parent.fragments.push(fragment);
540 }
541 if self.children.is_empty() {
542 return vec![parent];
543 }
544 self.children
545 .iter()
546 .flat_map(|c| c.flatten_inner(parent.clone()))
547 .collect()
548 }
549}
550
551impl FlatLen for NameTree {
552 fn len(&self) -> usize {
553 if self.children.is_empty() {
555 return 1;
556 }
557
558 self.children.iter().map(|c| c.len()).sum()
559 }
560}
561
562impl Flatten<NameBuf> for NameTree {
563 fn flatten<E>(&self, output: &mut E)
564 where
565 E: Extend<NameBuf>,
566 {
567 output.extend(self.flatten());
568 }
569 fn flatten_vec(&self) -> Vec<NameBuf> {
570 self.flatten()
571 }
572}
573
574impl NameBuf {
575 #[inline]
577 pub fn new() -> Self {
578 Default::default()
579 }
580
581 #[inline]
583 pub fn push(&mut self, fragment: impl Into<NameFragment>) {
584 self.fragments.push(fragment.into());
585 }
586
587 #[inline]
591 pub fn pop(&mut self) -> Option<NameFragment> {
592 self.fragments.pop()
593 }
594}
595
596impl<T: HasBundleKind> ArrayBundle<T> {
597 pub fn num_elems(&self) -> usize {
603 self.elems.len()
604 }
605
606 pub fn new(kind: T::BundleKind, elems: Vec<T>) -> Self {
611 for elem in elems.iter() {
612 assert_eq!(kind, elem.kind());
613 }
614 Self { kind, elems }
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use crate::types::*;
621
622 #[test]
623 fn flatten_name_tree() {
624 let tree = NameTree::new(
625 "io",
626 vec![
627 NameTree::new(
628 "pwr",
629 vec![NameTree::new("vdd", vec![]), NameTree::new("vss", vec![])],
630 ),
631 NameTree::new("out", vec![]),
632 ],
633 );
634
635 assert_eq!(
636 tree.flatten(),
637 vec![
638 NameBuf {
639 fragments: vec![
640 NameFragment::from("io"),
641 NameFragment::from("pwr"),
642 NameFragment::from("vdd")
643 ]
644 },
645 NameBuf {
646 fragments: vec![
647 NameFragment::from("io"),
648 NameFragment::from("pwr"),
649 NameFragment::from("vss")
650 ]
651 },
652 NameBuf {
653 fragments: vec![NameFragment::from("io"), NameFragment::from("out")]
654 },
655 ]
656 );
657 assert_eq!(tree.len(), 3);
658 }
659
660 #[test]
661 fn flatten_name_tree_with_empty_root() {
662 let tree = NameTree::with_empty_fragment(vec![
663 NameTree::new(
664 "pwr",
665 vec![NameTree::new("vdd", vec![]), NameTree::new("vss", vec![])],
666 ),
667 NameTree::new("out", vec![]),
668 ]);
669
670 assert_eq!(
671 tree.flatten(),
672 vec![
673 NameBuf {
674 fragments: vec![NameFragment::from("pwr"), NameFragment::from("vdd")]
675 },
676 NameBuf {
677 fragments: vec![NameFragment::from("pwr"), NameFragment::from("vss")]
678 },
679 NameBuf {
680 fragments: vec![NameFragment::from("out")]
681 },
682 ]
683 );
684 assert_eq!(tree.len(), 3);
685 }
686}