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
//! The global context.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use arcstr::ArcStr;
use config::Config;
use examples::get_snippets;
use gds::GdsUnits;
use indexmap::IndexMap;
use rust_decimal::prelude::ToPrimitive;
use substrate::schematic::{CellBuilder, ConvCacheKey, RawCellContentsBuilder};
use tracing::{span, Level};

use crate::block::Block;
use crate::cache::Cache;
use crate::diagnostics::SourceInfo;
use crate::error::Result;
use crate::execute::{Executor, LocalExecutor};
use crate::io::layout::{BundleBuilder, HardwareType as LayoutType};
use crate::io::schematic::{HardwareType as SchematicType, NodeContext, NodePriority, Port};
use crate::io::{Flatten, Flipped, HasNameTree};
use crate::layout::element::RawCell;
use crate::layout::error::{GdsExportError, LayoutError};
use crate::layout::gds::{GdsExporter, GdsImporter, ImportedGds};
use crate::layout::CellBuilder as LayoutCellBuilder;
use crate::layout::{Cell as LayoutCell, CellHandle as LayoutCellHandle};
use crate::layout::{Layout, LayoutContext};
use crate::pdk::layers::LayerContext;
use crate::pdk::layers::LayerId;
use crate::pdk::layers::Layers;
use crate::pdk::layers::{GdsLayerSpec, InstalledLayers};
use crate::pdk::Pdk;
use crate::schematic::conv::{export_multi_top_scir_lib, ConvError, RawLib};
use crate::schematic::schema::{FromSchema, Schema};
use crate::schematic::{
    Cell as SchematicCell, CellCacheKey, CellHandle as SchematicCellHandle, CellId, CellMetadata,
    InstancePath, RawCellInnerBuilder, SchemaCellCacheValue, SchemaCellHandle, Schematic,
    SchematicContext,
};
use crate::simulation::{SimController, SimulationContext, Simulator, Testbench};

/// The global context.
///
/// Stores configuration such as the PDK and tool plugins to use during generation.
///
/// Cheaply clonable.
///
/// # Examples
///
#[doc = get_snippets!("core", "generate")]
#[derive(Clone)]
pub struct Context {
    pub(crate) inner: Arc<RwLock<ContextInner>>,
    installations: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
    /// Map from `PDK` to `InstalledLayers<PDK>`.
    layers: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
    /// The executor to which commands should be submitted.
    pub executor: Arc<dyn Executor>,
    /// A cache for storing the results of expensive computations.
    pub cache: Cache,
}

impl Default for Context {
    fn default() -> Self {
        let cfg = Config::default().expect("requires valid Substrate configuration");

        Self {
            inner: Default::default(),
            installations: Default::default(),
            layers: Default::default(),
            executor: Arc::new(LocalExecutor),
            cache: Cache::new(
                cfg.cache
                    .into_cache()
                    .expect("requires valid Substrate cache configuration"),
            ),
        }
    }
}

impl Context {
    /// Creates a new [`Context`].
    pub fn new() -> Self {
        Self::default()
    }
}

/// An item that can be installed in a context.
pub trait Installation: Any + Send + Sync {
    /// A post-installation hook for additional context modifications
    /// required by the installation.
    ///
    /// PDKs, for example, should use this hook to install their layer
    /// set and standard cell libraries.
    #[allow(unused_variables)]
    fn post_install(&self, ctx: &mut ContextBuilder) {}
}

/// A private item that can be installed in a context after it is built.
pub trait PrivateInstallation: Any + Send + Sync {}

/// A [`Context`] with an associated PDK `PDK`.
pub struct PdkContext<PDK: Pdk + ?Sized> {
    /// PDK configuration and general data.
    pub pdk: Arc<PDK>,
    /// The PDK layer set.
    pub layers: Arc<PDK::Layers>,
    layer_ctx: Arc<RwLock<LayerContext>>,
    ctx: Context,
}

impl<PDK: Pdk> Deref for PdkContext<PDK> {
    type Target = Context;

    fn deref(&self) -> &Self::Target {
        &self.ctx
    }
}

/// Builder for creating a Substrate [`Context`].
pub struct ContextBuilder {
    installations: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
    /// Map from `PDK` to `InstalledLayers<PDK>`.
    layers: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
    executor: Arc<dyn Executor>,
    cache: Option<Cache>,
}

impl Default for ContextBuilder {
    fn default() -> Self {
        Self {
            installations: Default::default(),
            layers: Default::default(),
            executor: Arc::new(LocalExecutor),
            cache: None,
        }
    }
}

impl ContextBuilder {
    /// Creates a new, uninitialized builder.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the executor.
    pub fn executor<E: Executor>(&mut self, executor: E) -> &mut Self {
        self.executor = Arc::new(executor);
        self
    }

    /// Installs the given [`Installation`].
    ///
    /// Only one installation of any given type can exist. Overwrites
    /// conflicting installations of the same type.
    #[inline]
    pub fn install<I>(&mut self, installation: I) -> &mut Self
    where
        I: Installation,
    {
        let installation = Arc::new(installation);
        self.installations
            .insert(TypeId::of::<I>(), installation.clone());
        installation.post_install(self);
        self
    }

    /// Installs layers for a PDK.
    ///
    /// For use in [`Installation::post_install`] hooks for PDK types.
    pub fn install_pdk_layers<PDK: Pdk>(&mut self) -> Arc<PDK::Layers> {
        let mut ctx = LayerContext::default();
        let layers = ctx.install_layers::<PDK::Layers>();
        let result = layers.clone();
        self.layers.insert(
            TypeId::of::<PDK>(),
            Arc::new(InstalledLayers::<PDK> {
                layers,
                ctx: Arc::new(RwLock::new(ctx)),
            }),
        );
        result
    }

    /// Sets the desired cache configuration.
    pub fn cache(&mut self, cache: Cache) -> &mut Self {
        self.cache = Some(cache);
        self
    }

    /// Builds the context based on the configuration in this builder.
    pub fn build(&mut self) -> Context {
        let cfg = Config::default().expect("requires valid Substrate configuration");

        Context {
            inner: Arc::new(RwLock::new(ContextInner::new())),
            installations: Arc::new(self.installations.clone()),
            layers: Arc::new(self.layers.clone()),
            executor: self.executor.clone(),
            cache: self.cache.clone().unwrap_or_else(|| {
                Cache::new(
                    cfg.cache
                        .into_cache()
                        .expect("requires valid Substrate cache configuration"),
                )
            }),
        }
    }

    /// Gets an installation from the context installation map.
    pub fn get_installation<I: Installation>(&self) -> Option<Arc<I>> {
        retrieve_installation(&self.installations)
    }
}

impl<PDK: Pdk> Clone for PdkContext<PDK> {
    fn clone(&self) -> Self {
        Self {
            pdk: self.pdk.clone(),
            layers: self.layers.clone(),
            layer_ctx: self.layer_ctx.clone(),
            ctx: self.ctx.clone(),
        }
    }
}

#[derive(Debug, Default)]
pub(crate) struct ContextInner {
    pub(crate) schematic: SchematicContext,
    layout: LayoutContext,
    private_installations: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}

impl ContextInner {
    fn new() -> Self {
        Self::default()
    }
}

impl Context {
    /// Creates a builder for constructing a context.
    pub fn builder() -> ContextBuilder {
        Default::default()
    }

    /// Creates a [`PdkContext`] for the given installed PDK.
    ///
    /// The PDK must first be installed in the context.
    pub fn with_pdk<PDK: Pdk>(&self) -> PdkContext<PDK> {
        // Instantiate PDK layers.
        let pdk = self
            .installations
            .get(&TypeId::of::<PDK>())
            .expect("PDK must be installed")
            .clone()
            .downcast()
            .unwrap();

        let InstalledLayers { layers, ctx } = self
            .layers
            .get(&TypeId::of::<PDK>())
            .expect("PDK layer set must be installed")
            .downcast_ref::<InstalledLayers<PDK>>()
            .unwrap();

        PdkContext {
            pdk,
            layers: layers.clone(),
            layer_ctx: ctx.clone(),
            ctx: self.clone(),
        }
    }

    /// Allocates a new [`CellId`].
    fn alloc_cell_id(&self) -> CellId {
        let mut inner = self.inner.write().unwrap();
        let SchematicContext { next_id, .. } = &mut inner.schematic;
        next_id.increment();
        *next_id
    }

    /// Steps to create schematic:
    /// - Check if block has already been generated
    /// - If not:
    ///     - Create io_data, returning it immediately
    ///     - Use io_data and the cell_builder associated with it to
    ///       generate cell in background
    /// - If yes:
    ///     - Retrieve created cell ID, io_data, and handle to cell
    ///     - being generated and return immediately
    pub(crate) fn generate_schematic_inner<S: Schema + ?Sized, B: Schematic<S>>(
        &self,
        block: Arc<B>,
    ) -> SchemaCellHandle<S, B> {
        let key = CellCacheKey {
            block: block.clone(),
            phantom: PhantomData::<S>,
        };
        let block_clone = block.clone();
        let mut inner = self.inner.write().unwrap();
        let context = self.clone();
        let SchematicContext {
            next_id,
            cell_cache,
            ..
        } = &mut inner.schematic;
        let (metadata, handle) = cell_cache.generate_partial_blocking(
            key,
            |key| {
                next_id.increment();
                let (cell_builder, io_data) =
                    prepare_cell_builder(Some(*next_id), context, key.block.as_ref());
                let io_data = Arc::new(io_data);
                (
                    CellMetadata::<B> {
                        id: *next_id,
                        io_data: io_data.clone(),
                    },
                    (*next_id, cell_builder, io_data),
                )
            },
            move |_key, (id, mut cell_builder, io_data)| {
                let res = B::schematic(block_clone.as_ref(), io_data.as_ref(), &mut cell_builder);
                res.map(|data| SchemaCellCacheValue {
                    raw: Arc::new(cell_builder.finish()),
                    cell: Arc::new(SchematicCell::new(id, io_data, block_clone, Arc::new(data))),
                })
            },
        );

        SchemaCellHandle {
            handle: handle.clone(),
            cell: SchematicCellHandle {
                id: metadata.id,
                block,
                io_data: metadata.io_data.clone(),
                cell: handle.map(|res| {
                    Ok(res?
                        .as_ref()
                        .map_err(|e| e.clone())
                        .map(|SchemaCellCacheValue { cell, .. }| cell.clone()))
                }),
            },
        }
    }

    fn generate_cross_schematic_inner<
        S1: Schema + ?Sized,
        S2: FromSchema<S1> + ?Sized,
        B: Schematic<S1>,
    >(
        &self,
        block: Arc<B>,
    ) -> SchemaCellHandle<S2, B> {
        let handle = self.generate_schematic_inner(block);
        let mut inner = self.inner.write().unwrap();
        SchemaCellHandle {
            handle: inner.schematic.cell_cache.generate(
                ConvCacheKey::<B, S2, S1> {
                    block: handle.cell.block.clone(),
                    phantom: PhantomData,
                },
                move |_| {
                    let SchemaCellCacheValue { raw, cell } = handle
                        .handle
                        .try_get()
                        .unwrap()
                        .as_ref()
                        .map_err(|e| e.clone())?;
                    Ok(SchemaCellCacheValue {
                        raw: Arc::new((**raw).clone().convert_schema::<S2>()?),
                        cell: cell.clone(),
                    })
                },
            ),
            cell: handle.cell,
        }
    }

    /// Generates a schematic of a block in schema `S1` for use in schema `S2`.
    ///
    /// Can only generate a cross schematic with one layer of [`FromSchema`] indirection.
    pub fn generate_cross_schematic<
        S1: Schema + ?Sized,
        S2: FromSchema<S1> + ?Sized,
        B: Schematic<S1>,
    >(
        &self,
        block: B,
    ) -> SchemaCellHandle<S2, B> {
        self.generate_cross_schematic_inner(Arc::new(block))
    }

    /// Generates a schematic for `block` in the background.
    ///
    /// Returns a handle to the cell being generated.
    pub fn generate_schematic<S: Schema + ?Sized, T: Schematic<S>>(
        &self,
        block: T,
    ) -> SchemaCellHandle<S, T> {
        let block = Arc::new(block);
        self.generate_schematic_inner(block)
    }

    /// Export the given block and all sub-blocks as a SCIR library.
    ///
    /// Returns a SCIR library and metadata for converting between SCIR and Substrate formats.
    pub fn export_scir<S: Schema + ?Sized, T: Schematic<S>>(
        &self,
        block: T,
    ) -> Result<RawLib<S>, ConvError> {
        let cell = self.generate_schematic(block);
        // TODO: Handle errors.
        let SchemaCellCacheValue { raw, .. } = cell.handle.unwrap_inner();
        raw.to_scir_lib()
    }

    /// Export the given cells and all their subcells as a SCIR library.
    ///
    /// Returns a SCIR library and metadata for converting between SCIR and Substrate formats.
    pub fn export_scir_all<S: Schema + ?Sized>(
        &self,
        cells: &[&crate::schematic::RawCell<S>],
    ) -> Result<RawLib<S>, ConvError> {
        export_multi_top_scir_lib(cells)
    }

    /// Simulate the given testbench.
    ///
    /// The simulator must be installed in the context.
    pub fn simulate<S, T>(&self, block: T, work_dir: impl Into<PathBuf>) -> Result<T::Output>
    where
        S: Simulator,
        T: Testbench<S>,
    {
        let simulator = self
            .get_installation::<S>()
            .expect("Simulator must be installed");
        let block = Arc::new(block);
        let cell = self.generate_schematic_inner::<<S as Simulator>::Schema, _>(block.clone());
        // TODO: Handle errors.
        let SchemaCellCacheValue { raw, cell } = cell.handle.unwrap_inner();
        let lib = raw.to_scir_lib()?;
        let ctx = SimulationContext {
            lib: Arc::new(lib),
            work_dir: work_dir.into(),
            ctx: self.clone(),
        };
        let controller = SimController {
            tb: cell.clone(),
            simulator,
            ctx,
        };

        // TODO caching
        Ok(block.run(controller))
    }

    /// Installs the given [`PrivateInstallation`].
    ///
    /// Only one installation of any given type can exist. Overwrites
    /// conflicting installations of the same type.
    #[inline]
    pub fn install<I>(&mut self, installation: I) -> Arc<I>
    where
        I: PrivateInstallation,
    {
        let installation = Arc::new(installation);
        self.inner
            .write()
            .unwrap()
            .private_installations
            .insert(TypeId::of::<I>(), installation.clone());
        installation
    }

    /// Installs the given [`PrivateInstallation`].
    ///
    /// Returns the existing installation if one is present.
    #[inline]
    pub fn get_or_install<I>(&self, installation: I) -> Arc<I>
    where
        I: PrivateInstallation,
    {
        let installation = Arc::new(installation);
        self.inner
            .write()
            .unwrap()
            .private_installations
            .entry(TypeId::of::<I>())
            .or_insert(installation.clone())
            .clone()
            .downcast()
            .unwrap()
    }

    /// Gets a private installation from the context installation map.
    pub fn get_private_installation<I: PrivateInstallation>(&self) -> Option<Arc<I>> {
        retrieve_installation(&self.inner.read().unwrap().private_installations)
    }

    /// Gets an installation from the context installation map.
    pub fn get_installation<I: Installation>(&self) -> Option<Arc<I>> {
        retrieve_installation(&self.installations)
    }
}

fn retrieve_installation<I: Any + Send + Sync>(
    map: &HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
) -> Option<Arc<I>> {
    map.get(&TypeId::of::<I>())
        .map(|arc| arc.clone().downcast().unwrap())
}

impl<PDK: Pdk> PdkContext<PDK> {
    /// Creates a new global context.
    #[inline]
    pub fn new(pdk: PDK) -> Self {
        ContextBuilder::new().install(pdk).build().with_pdk()
    }

    /// Generates a layout for `block` in the background.
    ///
    /// Returns a handle to the cell being generated.
    pub fn generate_layout<T: Layout<PDK>>(&self, block: T) -> LayoutCellHandle<T> {
        let context_clone = self.clone();
        let mut inner_mut = self.ctx.inner.write().unwrap();
        let id = inner_mut.layout.get_id();
        let block = Arc::new(block);

        let span = span!(
            Level::INFO,
            "generating layout",
            block = %block.name(),
        )
        .or_current();

        LayoutCellHandle {
            block: block.clone(),
            cell: inner_mut.layout.cell_cache.generate(block, move |block| {
                let mut io_builder = block.io().builder();
                let mut cell_builder = LayoutCellBuilder::new(context_clone);
                let _guard = span.enter();
                let data = block.layout(&mut io_builder, &mut cell_builder);

                let io = io_builder.build()?;
                let ports = IndexMap::from_iter(
                    block
                        .io()
                        .flat_names(None)
                        .into_iter()
                        .zip(io.flatten_vec()),
                );
                data.map(|data| {
                    LayoutCell::new(
                        block.clone(),
                        data,
                        Arc::new(io),
                        Arc::new(cell_builder.finish(id, block.name()).with_ports(ports)),
                    )
                })
            }),
        }
    }

    /// Writes a layout to a GDS file.
    pub fn write_layout<T: Layout<PDK>>(&self, block: T, path: impl AsRef<Path>) -> Result<()> {
        let handle = self.generate_layout(block);
        let cell = handle.try_cell()?;

        let layer_ctx = self.layer_ctx.read().unwrap();
        let db_units = PDK::LAYOUT_DB_UNITS.to_f64().unwrap();
        GdsExporter::with_units(
            vec![cell.raw.clone()],
            &layer_ctx,
            GdsUnits::new(db_units / 1e-6, db_units),
        )
        .export()
        .map_err(LayoutError::from)?
        .save(path)
        .map_err(GdsExportError::from)
        .map_err(LayoutError::from)?;
        Ok(())
    }

    /// Writes a set of layout cells to a GDS file.
    pub fn write_layout_all(
        &self,
        cells: impl IntoIterator<Item = Arc<RawCell>>,
        path: impl AsRef<Path>,
    ) -> Result<()> {
        let layer_ctx = self.layer_ctx.read().unwrap();
        let db_units = PDK::LAYOUT_DB_UNITS.to_f64().unwrap();
        GdsExporter::with_units(
            cells.into_iter().collect::<Vec<_>>(),
            &layer_ctx,
            GdsUnits::new(db_units / 1e-6, db_units),
        )
        .export()
        .map_err(LayoutError::from)?
        .save(path)
        .map_err(GdsExportError::from)
        .map_err(LayoutError::from)?;
        Ok(())
    }

    /// Reads a layout from a GDS file.
    pub fn read_gds(&self, path: impl AsRef<Path>) -> Result<ImportedGds> {
        let lib = gds::GdsLibrary::load(path)?;
        let mut inner = self.ctx.inner.write().unwrap();
        let ContextInner { ref mut layout, .. } = *inner;
        let mut layer_ctx = self.layer_ctx.write().unwrap();
        let imported =
            GdsImporter::new(&lib, layout, &mut layer_ctx, Some(PDK::LAYOUT_DB_UNITS)).import()?;
        Ok(imported)
    }

    /// Reads the layout of a single cell from a GDS file.
    pub fn read_gds_cell(
        &self,
        path: impl AsRef<Path>,
        cell: impl Into<ArcStr>,
    ) -> Result<Arc<RawCell>> {
        let lib = gds::GdsLibrary::load(path)?;
        let mut inner = self.ctx.inner.write().unwrap();
        let ContextInner { ref mut layout, .. } = *inner;
        let mut layer_ctx = self.layer_ctx.write().unwrap();
        let imported = GdsImporter::new(&lib, layout, &mut layer_ctx, Some(PDK::LAYOUT_DB_UNITS))
            .import_cell(cell)?;
        Ok(imported)
    }

    /// Installs a new layer set in the context.
    ///
    /// Allows for accessing GDS layers or other extra layers that are not present in the PDK.
    pub fn install_layers<L: Layers>(&self) -> Arc<L> {
        let mut layer_ctx = self.layer_ctx.write().unwrap();
        layer_ctx.install_layers::<L>()
    }

    /// Gets a layer by its GDS layer spec.
    ///
    /// Should generally not be used except for situations involving GDS import, where
    /// layers may be imported at runtime.
    pub fn get_gds_layer(&self, spec: GdsLayerSpec) -> Option<LayerId> {
        let layer_ctx = self.layer_ctx.read().unwrap();
        layer_ctx.get_gds_layer(spec)
    }
}

/// Only public for use in ATOLL. Do NOT use externally.
///
/// If the `id` argument is Some, the cell will use the given ID.
/// Otherwise, a new [`CellId`] will be allocated by calling [`Context::alloc_cell_id`].
#[doc(hidden)]
pub fn prepare_cell_builder<S: Schema + ?Sized, T: Block>(
    id: Option<CellId>,
    context: Context,
    block: &T,
) -> (CellBuilder<S>, <<T as Block>::Io as SchematicType>::Bundle) {
    let id = id.unwrap_or_else(|| context.alloc_cell_id());
    let mut node_ctx = NodeContext::new();
    // outward-facing IO (to other enclosing blocks)
    let io_outward = block.io();
    // inward-facing IO (this block's IO ports as viewed by the interior of the
    // block)
    let io_internal = Flipped(io_outward.clone());
    // FIXME: the cell's IO should not be attributed to this call site
    let (nodes, io_data) =
        node_ctx.instantiate_directed(&io_internal, NodePriority::Io, SourceInfo::from_caller());
    let cell_name = block.name();

    let names = io_outward.flat_names(None);
    let outward_dirs = io_outward.flatten_vec();
    assert_eq!(nodes.len(), names.len());
    assert_eq!(nodes.len(), outward_dirs.len());

    let ports = nodes
        .iter()
        .copied()
        .zip(outward_dirs)
        .map(|(node, direction)| Port::new(node, direction))
        .collect();

    let node_names = HashMap::from_iter(nodes.into_iter().zip(names));

    (
        CellBuilder {
            id,
            root: InstancePath::new(id),
            cell_name,
            ctx: context,
            node_ctx,
            node_names,
            ports,
            flatten: false,
            contents: RawCellContentsBuilder::Cell(RawCellInnerBuilder::default()),
        },
        io_data,
    )
}