substrate/layout/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! Substrate's layout generator framework.

use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
use std::{marker::PhantomData, sync::Arc, thread};

use arcstr::ArcStr;
use cache::{error::TryInnerError, mem::TypeCache, CacheHandle};
use geometry::prelude::Rect;
use geometry::transform::{TransformRef, TranslateRef};
use geometry::{
    prelude::{Bbox, Point},
    transform::{Transform, TransformMut, Transformation, Translate, TranslateMut},
    union::BoundingUnion,
};
use layir::LayerBbox;
use once_cell::sync::OnceCell;
use schema::Schema;

use crate::context::Context;
use crate::error::Error;
use crate::error::Result;
use crate::types::layout::LayoutBundle;
use crate::types::{HasBundleKind, IoKind};

use self::element::{CellId, Element, RawCell, RawInstance};

pub mod conv;
pub mod element;
pub mod error;
pub mod schema;
#[cfg(test)]
mod tests;
pub mod tiling;
pub mod tracks;

use crate::block::Block;

/// Data exported from a generated layout.
///
/// Contained data is transformed with the containing instance
/// according to its [`TransformRef`] implementation.
pub trait LayoutData: TransformRef + Send + Sync {}
impl<T: TransformRef + Send + Sync> LayoutData for T {}

/// The layer type associated with a layout cell.
pub type CellLayer<T> = <<T as Layout>::Schema as Schema>::Layer;
/// The bundle associated with a layout cell.
pub type CellBundle<T> = <T as Layout>::Bundle;

/// A block that can be laid out in a given layout [`Schema`].
pub trait Layout: Block {
    /// The schema this layout is associated with.
    type Schema: Schema;
    /// The bundle representing this block's layout IO.
    type Bundle: LayoutBundle<Self::Schema> + HasBundleKind<BundleKind = IoKind<Self>>;
    /// Extra data to be shared with other blocks that instantiate this block's layout.
    type Data: LayoutData;
    /// Generates the block's layout.
    fn layout(&self, cell: &mut CellBuilder<Self::Schema>) -> Result<(Self::Bundle, Self::Data)>;
}

impl<T: Layout> Layout for Arc<T> {
    type Schema = T::Schema;
    type Bundle = T::Bundle;
    type Data = T::Data;
    fn layout(&self, cell: &mut CellBuilder<Self::Schema>) -> Result<(Self::Bundle, Self::Data)> {
        T::layout(self.as_ref(), cell)
    }
}

/// Layout-specific context data.
///
/// Stores generated layout cells as well as state used for assigning unique cell IDs.
#[derive(Debug, Default)]
pub struct LayoutContext {
    next_id: CellId,
    pub(crate) cell_cache: TypeCache,
}

impl LayoutContext {
    #[allow(dead_code)]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn get_id(&mut self) -> CellId {
        self.next_id.increment();
        self.next_id
    }
}

/// A generic layout cell.
///
/// Stores its underlying block, extra data created during generation, as well as a raw cell
/// containing its primitive elements.
#[allow(dead_code)]
pub struct Cell<T: Layout> {
    /// Block whose layout this cell represents.
    block: Arc<T>,
    /// Extra data created during layout generation.
    data: T::Data,
    pub(crate) io: T::Bundle,
    pub(crate) raw: Arc<RawCell<<T::Schema as Schema>::Layer>>,
}

impl<T: Layout> Cell<T> {
    pub(crate) fn new(
        block: Arc<T>,
        data: T::Data,
        io: T::Bundle,
        raw: Arc<RawCell<CellLayer<T>>>,
    ) -> Self {
        Self {
            block,
            data,
            io,
            raw,
        }
    }

    /// Returns the block whose layout this cell represents.
    pub fn block(&self) -> &T {
        &self.block
    }

    /// Returns extra data created by the cell's schematic generator.
    pub fn data(&self) -> &T::Data {
        &self.data
    }

    /// Returns the geometry of the cell's IO.
    pub fn io(&self) -> &T::Bundle {
        &self.io
    }

    /// The raw layout geometry contained by this cell.
    pub fn raw(&self) -> &Arc<RawCell<CellLayer<T>>> {
        &self.raw
    }
}

impl<T: Layout> Bbox for Cell<T> {
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.raw.bbox()
    }
}

impl<T: Layout> LayerBbox<<T::Schema as Schema>::Layer> for Cell<T>
where
    <T::Schema as Schema>::Layer: PartialEq,
{
    fn layer_bbox(&self, layer: &<T::Schema as Schema>::Layer) -> Option<Rect> {
        self.raw.layer_bbox(layer)
    }
}

/// A handle to a schematic cell that is being generated.
pub struct CellHandle<T: Layout> {
    pub(crate) block: Arc<T>,
    pub(crate) cell: CacheHandle<Result<Cell<T>>>,
}

impl<T: Layout> Clone for CellHandle<T> {
    fn clone(&self) -> Self {
        Self {
            block: self.block.clone(),
            cell: self.cell.clone(),
        }
    }
}

impl<T: Layout> CellHandle<T> {
    /// Tries to access the underlying [`Cell`].
    ///
    /// Blocks until cell generation completes and returns an error if one was thrown during generation.
    pub fn try_cell(&self) -> Result<&Cell<T>> {
        self.cell.try_inner().map_err(|e| match e {
            TryInnerError::CacheError(e) => Error::CacheError(e.clone()),
            TryInnerError::GeneratorError(e) => e.clone(),
        })
    }

    /// Returns the underlying [`Cell`].
    ///
    /// Blocks until cell generation completes.
    ///
    /// # Panics
    ///
    /// Panics if generation fails.
    pub fn cell(&self) -> &Cell<T> {
        self.try_cell().expect("cell generation failed")
    }
}

/// A transformed view of a cell, usually created by accessing the cell of an instance.
pub struct TransformedCell<T: Layout> {
    /// Block whose layout this cell represents.
    block: Arc<T>,
    /// Extra data created during layout generation.
    ///
    /// This is the result of applying `trans` to the original cell's data.
    /// If `trans` changes, this field must be updated.
    data: T::Data,
    /// The geometry of the cell's IO.
    ///
    /// This is the result of applying `trans` to the original cell's IO.
    /// If `trans` changes, this field must be updated.
    io: T::Bundle,
    /// The underlying raw cell.
    ///
    /// This field should NOT be modified if `trans` changes.
    raw: Arc<RawCell<CellLayer<T>>>,
    /// The transformation applied to all geometry stored in the raw cell (`raw`).
    trans: Transformation,
}

impl<T: Layout> TransformedCell<T> {
    /// Creates a new transformed cell from the given cell and transformation.
    pub fn new(cell: &Cell<T>, trans: Transformation) -> Self {
        Self {
            block: cell.block.clone(),
            data: cell.data.transform_ref(trans),
            io: cell.io.transform_ref(trans),
            raw: cell.raw.clone(),
            trans,
        }
    }

    /// Returns the block whose layout this cell represents.
    pub fn block(&self) -> &T {
        &self.block
    }

    /// Returns extra data created by the cell's schematic generator.
    pub fn data(&self) -> &T::Data {
        &self.data
    }
}

impl<T: Layout> TranslateRef for TransformedCell<T> {
    fn translate_ref(&self, p: Point) -> Self {
        Self {
            block: self.block.clone(),
            data: self.data.translate_ref(p),
            io: self.io.translate_ref(p),
            raw: self.raw.clone(),
            trans: self.trans.translate_ref(p.x, p.y),
        }
    }
}

impl<T: Layout> TransformRef for TransformedCell<T> {
    fn transform_ref(&self, trans: Transformation) -> Self {
        Self {
            block: self.block.clone(),
            data: self.data.transform_ref(trans),
            io: self.io.transform_ref(trans),
            raw: self.raw.clone(),
            trans: Transformation::cascade(trans, self.trans),
        }
    }
}

impl<T: Layout> Bbox for TransformedCell<T> {
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.raw.bbox().transform(self.trans)
    }
}

impl<T: Layout> LayerBbox<<T::Schema as Schema>::Layer> for TransformedCell<T>
where
    CellLayer<T>: PartialEq,
{
    fn layer_bbox(&self, layer: &<T::Schema as Schema>::Layer) -> Option<Rect> {
        self.raw.layer_bbox(layer).transform(self.trans)
    }
}

/// A generic layout instance.
///
/// Stores a pointer to its underlying cell and its instantiated transformation.
#[allow(dead_code)]
pub struct Instance<T: Layout> {
    cell: CellHandle<T>,
    trans: Transformation,
}

impl<T: Layout> Clone for Instance<T> {
    fn clone(&self) -> Self {
        Self {
            cell: self.cell.clone(),
            ..*self
        }
    }
}

impl<T: Layout> Instance<T> {
    pub(crate) fn new(cell: CellHandle<T>) -> Self {
        Instance {
            cell,
            trans: Transformation::default(),
        }
    }

    /// Tries to access a transformed view of the underlying [`Cell`], blocking on generation.
    ///
    /// Blocks until cell generation completes.
    ///
    /// The returned object provides coordinates in the parent cell's coordinate system.
    /// If you want coordinates in the child cell's coordinate system,
    /// consider using [`Instance::try_raw_cell`] instead.
    ///
    /// Returns an error if one was thrown during generation.
    // TODO: this recomputes transformations every time it is called.
    pub fn try_cell(&self) -> Result<TransformedCell<T>> {
        self.cell
            .try_cell()
            .map(|cell| TransformedCell::new(cell, self.trans))
    }

    /// Returns a transformed view of the underlying [`Cell`].
    ///
    /// Blocks until cell generation completes.
    ///
    /// The returned object provides coordinates in the parent cell's coordinate system.
    /// If you want coordinates in the child cell's coordinate system,
    /// consider using [`Instance::raw_cell`] instead.
    ///
    /// # Panics
    ///
    /// Panics if an error was thrown during generation.
    pub fn cell(&self) -> TransformedCell<T> {
        self.try_cell().expect("cell generation failed")
    }

    /// Tries to access a transformed view of the underlying [`Cell`], blocking on generation.
    ///
    /// Blocks until cell generation completes.
    ///
    /// The returned cell does not store any information related
    /// to this instance's transformation.
    /// Consider using [`Instance::try_cell`] instead.
    ///
    /// Returns an error if one was thrown during generation.
    pub fn try_raw_cell(&self) -> Result<&Cell<T>> {
        self.cell.try_cell()
    }

    /// Returns a transformed view of the underlying [`Cell`].
    ///
    /// Blocks until cell generation completes.
    ///
    /// The returned cell does not store any information related
    /// to this instance's transformation.
    /// Consider using [`Instance::cell`] instead.
    ///
    /// # Panics
    ///
    /// Panics if an error was thrown during generation.
    pub fn raw_cell(&self) -> &Cell<T> {
        self.try_raw_cell().expect("cell generation failed")
    }

    /// Tries to access extra data created by the cell's schematic generator.
    ///
    /// Blocks until cell generation completes.
    ///
    /// Returns an error if one was thrown during generation.
    pub fn try_data(&self) -> Result<T::Data> {
        Ok(self.try_cell()?.data)
    }

    /// Tries to access extra data created by the cell's schematic generator.
    ///
    /// Blocks until cell generation completes.
    ///
    /// # Panics
    ///
    /// Panics if an error was thrown during generation.
    pub fn data(&self) -> T::Data {
        self.cell().data
    }

    /// Returns the underlying block used to create this instance's cell.
    pub fn block(&self) -> &T {
        self.cell.block.as_ref()
    }

    /// Returns a transformed view of the underlying [`Cell`]'s IO.
    ///
    /// Blocks until cell generation completes.
    ///
    /// Returns an error if one was thrown during generation.
    pub fn try_io(&self) -> Result<T::Bundle> {
        Ok(self.try_cell()?.io)
    }

    /// Returns a transformed view of the underlying [`Cell`]'s IO.
    ///
    /// Blocks until cell generation completes.
    ///
    /// # Panics
    ///
    /// Panics if an error was thrown during generation.
    pub fn io(&self) -> T::Bundle {
        self.cell().io
    }

    /// The transformation of this instance.
    pub fn transformation(&self) -> &Transformation {
        &self.trans
    }

    /// A mutable reference to a transformation of this instance.
    pub fn transformation_mut(&mut self) -> &mut Transformation {
        &mut self.trans
    }
}

impl<T: Layout> Bbox for Instance<T> {
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.cell().bbox()
    }
}

impl<T: Layout> LayerBbox<<T::Schema as Schema>::Layer> for Instance<T>
where
    CellLayer<T>: PartialEq,
{
    fn layer_bbox(&self, layer: &<T::Schema as Schema>::Layer) -> Option<Rect> {
        self.cell().layer_bbox(layer)
    }
}

impl<T: Layout> TranslateMut for Instance<T> {
    fn translate_mut(&mut self, p: Point) {
        self.transform_mut(Transformation::from_offset(p))
    }
}

impl<T: Layout> TransformMut for Instance<T> {
    fn transform_mut(&mut self, trans: Transformation) {
        self.trans = Transformation::cascade(trans, self.trans);
    }
}

impl<T: Layout> TranslateRef for Instance<T> {
    fn translate_ref(&self, p: Point) -> Self {
        self.clone().translate(p)
    }
}

impl<T: Layout> TransformRef for Instance<T> {
    fn transform_ref(&self, trans: Transformation) -> Self {
        self.clone().transform(trans)
    }
}

impl<I: Layout> Draw<I::Schema> for Instance<I> {
    fn draw(self, recv: &mut DrawReceiver<I::Schema>) -> Result<()> {
        recv.draw_instance(self);
        Ok(())
    }
}

impl<I: Layout> Draw<I::Schema> for &Instance<I> {
    fn draw(self, recv: &mut DrawReceiver<I::Schema>) -> Result<()> {
        recv.draw_instance((*self).clone());
        Ok(())
    }
}

/// A layout cell builder.
///
/// Constructed once for each invocation of [`Layout::layout`].
pub struct CellBuilder<S: Schema> {
    container: Container<S>,
    /// The current global context.
    pub ctx: Context,
}

impl<S: Schema> CellBuilder<S> {
    /// Creates a new layout builder.
    pub fn new(ctx: Context) -> Self {
        Self {
            container: Container::new(),
            ctx,
        }
    }

    pub(crate) fn finish(self, id: CellId, name: ArcStr) -> RawCell<S::Layer> {
        let mut cell = RawCell::new(id, name);

        self.container.finish(&mut cell.elements);

        cell
    }

    /// Generate an instance of `block`.
    ///
    /// Returns immediately, allowing generation to complete in the background. Attempting to
    /// access the generated instance's cell will block until generation is complete.
    pub fn generate<I: Layout>(&mut self, block: I) -> Instance<I> {
        let cell = self.ctx.generate_layout(block);
        Instance::new(cell)
    }

    /// Generate an instance of `block`.
    ///
    /// Blocks on generation, returning only once the instance's cell is populated. Useful for
    /// handling errors thrown by the generation of a cell immediately.
    pub fn generate_blocking<I: Layout>(&mut self, block: I) -> Result<Instance<I>> {
        let cell = self.ctx.generate_layout(block);
        cell.try_cell()?;
        Ok(Instance::new(cell))
    }

    /// Draw layout object `obj`.
    ///
    /// For instances, a new thread is spawned to add the instance once the underlying cell has
    /// been generated. If generation fails, the spawned thread may panic after this function has
    /// been called.
    ///
    /// For error recovery, instance generation results should be checked using [`Instance::try_cell`]
    /// before calling `draw`.
    ///
    /// # Panics
    ///
    /// May cause a panic if generation of an underlying instance fails.
    pub fn draw(&mut self, obj: impl Draw<S>) -> Result<()> {
        Container::draw(&mut self.container, obj)
    }

    /// Gets the global context.
    pub fn ctx(&self) -> &Context {
        &self.ctx
    }
}

impl<S: Schema> Bbox for CellBuilder<S> {
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.container.bbox()
    }
}

impl<S: Schema> LayerBbox<S::Layer> for CellBuilder<S> {
    fn layer_bbox(&self, layer: &S::Layer) -> Option<Rect> {
        self.container.layer_bbox(layer)
    }
}

type RawInstanceHandle<S> = Arc<OnceCell<Option<RawInstance<<S as Schema>::Layer>>>>;

/// A receiver for drawing layout objects.
///
/// Implements the primitive functions that layout objects need to implement [`Draw`].
pub struct DrawReceiver<S: Schema> {
    phantom: PhantomData<S>,
    containers: Vec<Container<S>>,
    instances: Vec<RawInstanceHandle<S>>,
    elements: Vec<Element<S::Layer>>,
    trans: Transformation,
}

impl<S: Schema> Debug for DrawReceiver<S>
where
    S::Layer: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DrawReceiver")
            .field("phantom", &self.phantom)
            .field("containers", &self.containers)
            .field("instances", &self.instances)
            .field("elements", &self.elements)
            .field("trans", &self.trans)
            .finish()
    }
}

impl<S: Schema> Clone for DrawReceiver<S>
where
    S::Layer: Clone,
{
    fn clone(&self) -> Self {
        Self {
            phantom: PhantomData,
            containers: self.containers.clone(),
            instances: self.instances.clone(),
            elements: self.elements.clone(),
            trans: self.trans,
        }
    }
}

impl<S: Schema> DrawReceiver<S> {
    pub(crate) fn new() -> Self {
        Self {
            phantom: PhantomData,
            containers: Vec::new(),
            instances: Vec::new(),
            elements: Vec::new(),
            trans: Transformation::default(),
        }
    }

    /// Blocks on instances and returns pointers to them.
    fn get_instances(&self) -> Vec<&RawInstance<S::Layer>> {
        self.instances
            .iter()
            .map(|instance| instance.wait().as_ref().unwrap())
            .collect()
    }

    pub(crate) fn finish(self, elements: &mut Vec<Element<S::Layer>>) {
        for instance in self
            .instances
            .into_iter()
            .map(|instance| instance.wait().clone().unwrap())
        {
            elements.push(instance.transform(self.trans).into());
        }

        elements.extend(
            self.elements
                .into_iter()
                .map(|element| element.transform(self.trans)),
        );

        for mut container in self.containers {
            container.transform_mut(self.trans);
            container.finish(elements);
        }
    }

    pub(crate) fn draw_container(&mut self, container: Container<S>) {
        self.containers.push(container);
    }

    pub(crate) fn draw_element(&mut self, element: impl Into<Element<S::Layer>>) {
        let element = element.into();
        self.elements.push(element);
    }
}

impl<S: Schema> DrawReceiver<S> {
    pub(crate) fn draw_instance<I: Layout<Schema = S>>(&mut self, inst: Instance<I>) {
        let instance = Arc::new(OnceCell::new());
        self.instances.push(instance.clone());

        let cell = inst.cell.clone();
        thread::spawn(move || {
            instance.set(cell.try_cell().ok().map(|cell| RawInstance {
                cell: cell.raw.clone(),
                trans: inst.trans,
            }))
        });
    }

    /// Draw layout object `obj`.
    ///
    /// For instances, a new thread is spawned to add the instance once the underlying cell has
    /// been generated. If generation fails, the spawned thread may panic after this function has
    /// been called.
    ///
    /// For error recovery, instance generation results should be checked using [`Instance::try_cell`]
    /// before calling `draw`.
    ///
    /// # Panics
    ///
    /// May cause a panic if generation of an underlying instance fails.
    pub fn draw(&mut self, obj: impl Draw<S>) -> Result<()> {
        obj.draw(self)
    }
}

impl<S: Schema> Draw<S> for DrawReceiver<S> {
    fn draw(self, recv: &mut DrawReceiver<S>) -> Result<()> {
        recv.containers.extend(self.containers);
        recv.instances.extend(self.instances);
        recv.elements.extend(self.elements);
        Ok(())
    }
}

impl<S: Schema> Bbox for DrawReceiver<S> {
    // TODO: process containers?
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.get_instances()
            .bbox()
            .bounding_union(&self.elements.bbox())
    }
}

impl<S: Schema> LayerBbox<S::Layer> for DrawReceiver<S> {
    fn layer_bbox(&self, layer: &S::Layer) -> Option<Rect> {
        self.get_instances()
            .layer_bbox(layer)
            .bounding_union(&self.elements.layer_bbox(layer))
    }
}

/// An object that can be drawn in a [`CellBuilder`].
pub trait Draw<S: Schema>: DrawBoxed<S> {
    /// Draws `self` inside `recv`.
    fn draw(self, recv: &mut DrawReceiver<S>) -> Result<()>;
}

/// An object where `Box<Self>` can be drawn.
pub trait DrawBoxed<S: Schema> {
    /// Draws `self` inside `recv`.
    fn draw_boxed(self: Box<Self>, recv: &mut DrawReceiver<S>) -> Result<()>;
}

impl<S: Schema, T: Draw<S>> DrawBoxed<S> for T {
    fn draw_boxed(self: Box<Self>, recv: &mut DrawReceiver<S>) -> Result<()> {
        (*self).draw(recv)
    }
}

/// Draws an object into a new [`Container`].
// TODO: Decide if this trait should be made public.
#[allow(dead_code)]
pub(crate) trait DrawContainer<S: Schema>: Draw<S> {
    /// Draws `self` into a new [`Container`].
    fn draw_container(self) -> Result<Container<S>>;
}

impl<S: Schema, T: Draw<S>> DrawContainer<S> for T {
    fn draw_container(self) -> Result<Container<S>> {
        let mut container = Container::new();
        Container::draw(&mut container, self)?;
        Ok(container)
    }
}

impl<S: Schema, T: Draw<S> + ?Sized> Draw<S> for Box<T> {
    fn draw(self, recv: &mut DrawReceiver<S>) -> Result<()> {
        self.draw_boxed(recv)
    }
}

/// TODO: Temporarily private until we decide whether it is worth exposing.
pub(crate) struct Container<S: Schema> {
    recvs: Vec<DrawReceiver<S>>,
    trans: Transformation,
}

impl<S: Schema> Clone for Container<S>
where
    S::Layer: Clone,
{
    fn clone(&self) -> Self {
        Self {
            recvs: self.recvs.clone(),
            trans: self.trans,
        }
    }
}

impl<S: Schema> Debug for Container<S>
where
    S::Layer: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Container")
            .field("recvs", &self.recvs)
            .field("trans", &self.trans)
            .finish()
    }
}

impl<S: Schema> Default for Container<S> {
    fn default() -> Self {
        Self {
            recvs: vec![DrawReceiver::new()],
            trans: Transformation::default(),
        }
    }
}

impl<S: Schema> Container<S> {
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn finish(self, elements: &mut Vec<Element<S::Layer>>) {
        for mut recv in self.recvs {
            recv.trans = Transformation::cascade(self.trans, recv.trans);
            recv.finish(elements);
        }
    }

    pub(crate) fn recv_mut(&mut self) -> &mut DrawReceiver<S> {
        self.recvs.last_mut().unwrap()
    }
}

impl<S: Schema> Container<S> {
    /// Draw layout object `obj`.
    ///
    /// For instances, a new thread is spawned to add the instance once the underlying cell has
    /// been generated. If generation fails, the spawned thread may panic after this function has
    /// been called.
    ///
    /// For error recovery, instance generation results should be checked using [`Instance::try_cell`]
    /// before calling `draw`.
    ///
    /// # Panics
    ///
    /// May cause a panic if generation of an underlying instance fails.
    pub fn draw(&mut self, obj: impl Draw<S>) -> Result<()> {
        self.recv_mut().draw(obj)
    }
}

impl<S: Schema> Bbox for Container<S> {
    fn bbox(&self) -> Option<geometry::rect::Rect> {
        self.recvs.bbox().transform(self.trans)
    }
}

impl<S: Schema> LayerBbox<S::Layer> for Container<S> {
    fn layer_bbox(&self, layer: &S::Layer) -> Option<Rect> {
        self.recvs.layer_bbox(layer).transform(self.trans)
    }
}

impl<S: Schema> Draw<S> for Container<S> {
    fn draw(self, recv: &mut DrawReceiver<S>) -> Result<()> {
        recv.draw_container(self);
        Ok(())
    }
}

impl<S: Schema> TranslateMut for Container<S> {
    fn translate_mut(&mut self, p: Point) {
        self.transform_mut(Transformation::from_offset(p))
    }
}

impl<S: Schema> TransformMut for Container<S> {
    fn transform_mut(&mut self, trans: Transformation) {
        self.trans = Transformation::cascade(trans, self.trans);
        let mut recv = DrawReceiver::new();
        recv.trans = self.trans.inv();
        self.recvs.push(recv);
    }
}

/// A layout library in a given schema.
pub struct LayoutLibrary<S: Schema> {
    inner: layir::Library<S::Layer>,
}

impl<S: Schema> Deref for LayoutLibrary<S> {
    type Target = layir::Library<S::Layer>;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<S: Schema> DerefMut for LayoutLibrary<S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}