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
//! The Sky 130 nm process development kit.
//!
//! Includes both open source and commercial PDK flavors.
#![warn(missing_docs)]

use std::collections::HashMap;
use std::convert::Infallible;
use std::path::PathBuf;

use arcstr::ArcStr;
use ngspice::Ngspice;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use spectre::Spectre;
use substrate::pdk::Pdk;
use unicase::UniCase;

use crate::layers::Sky130Layers;
use crate::mos::{MosKind, MosParams};
use scir::schema::{FromSchema, Schema};
use scir::{Instance, ParamValue};
use spice::Spice;
use substrate::context::{ContextBuilder, Installation};

pub mod atoll;
pub mod corner;
pub mod layers;
pub mod mos;
pub mod stdcells;

/// A primitive of the Sky 130 PDK.
#[derive(Debug, Clone)]
pub enum Primitive {
    /// A raw instance with associated cell `cell`.
    RawInstance {
        /// The associated cell.
        cell: ArcStr,
        /// The ordered ports of the instance.
        ports: Vec<ArcStr>,
        /// The parameters of the instance.
        params: HashMap<ArcStr, ParamValue>,
    },
    /// A Sky 130 MOSFET with ports "D", "G", "S", and "B".
    Mos {
        /// The MOSFET kind.
        kind: MosKind,
        /// The MOSFET parameters.
        params: MosParams,
    },
}

/// An error converting to/from the [`Sky130Pdk`] schema.
#[derive(Debug, Clone, Copy)]
pub enum ConvError {
    /// A primitive that is not supported by the target schema was encountered.
    UnsupportedPrimitive,
    /// A primitive is missing a required parameter.
    MissingParameter,
    /// A primitive has an extra parameter.
    ExtraParameter,
    /// A primitive has an invalid value for a certain parameter.
    InvalidParameter,
}

impl scir::schema::Schema for Sky130Pdk {
    type Primitive = Primitive;
}

impl FromSchema<Spice> for Sky130Pdk {
    type Error = ConvError;

    fn convert_primitive(
        primitive: <Spice as scir::schema::Schema>::Primitive,
    ) -> Result<<Self as scir::schema::Schema>::Primitive, Self::Error> {
        match &primitive {
            spice::Primitive::RawInstance {
                cell,
                ports,
                params,
            } => Ok(if let Some(kind) = MosKind::try_from_str(cell) {
                Primitive::Mos {
                    kind,
                    params: MosParams {
                        w: i64::try_from(
                            *params
                                .get(&UniCase::new(arcstr::literal!("w")))
                                .and_then(|expr| expr.get_numeric())
                                .ok_or(ConvError::MissingParameter)?
                                * dec!(1000),
                        )
                        .map_err(|_| ConvError::InvalidParameter)?,
                        l: i64::try_from(
                            *params
                                .get(&UniCase::new(arcstr::literal!("l")))
                                .and_then(|expr| expr.get_numeric())
                                .ok_or(ConvError::MissingParameter)?
                                * dec!(1000),
                        )
                        .map_err(|_| ConvError::InvalidParameter)?,
                        nf: i64::try_from(
                            params
                                .get(&UniCase::new(arcstr::literal!("nf")))
                                .and_then(|expr| expr.get_numeric())
                                .copied()
                                .unwrap_or(dec!(1)),
                        )
                        .map_err(|_| ConvError::InvalidParameter)?,
                    },
                }
            } else {
                Primitive::RawInstance {
                    cell: cell.clone(),
                    ports: ports.clone(),
                    params: params
                        .clone()
                        .into_iter()
                        .map(|(k, v)| (k.into_inner(), v))
                        .collect(),
                }
            }),
            _ => Err(ConvError::UnsupportedPrimitive),
        }
    }

    fn convert_instance(
        instance: &mut Instance,
        primitive: &<Spice as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        match primitive {
            spice::Primitive::RawInstance { cell, ports, .. } => {
                if MosKind::try_from_str(cell).is_some() {
                    let connections = instance.connections_mut();
                    for (port, mapped_port) in ports.iter().zip(["D", "G", "S", "B"]) {
                        let concat = connections.remove(port).unwrap();
                        connections.insert(mapped_port.into(), concat);
                    }
                }
            }
            _ => return Err(ConvError::UnsupportedPrimitive),
        }
        Ok(())
    }
}

impl FromSchema<Sky130Pdk> for Spice {
    type Error = Infallible;
    fn convert_primitive(
        primitive: <Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<<Spice as scir::schema::Schema>::Primitive, Self::Error> {
        Ok(match primitive {
            Primitive::RawInstance {
                cell,
                ports,
                params,
            } => spice::Primitive::RawInstance {
                cell,
                ports,
                params: params
                    .into_iter()
                    .map(|(k, v)| (UniCase::new(k), v))
                    .collect(),
            },
            Primitive::Mos { kind, params } => spice::Primitive::RawInstance {
                cell: kind.open_subckt(),
                ports: vec!["D".into(), "G".into(), "S".into(), "B".into()],
                params: HashMap::from_iter([
                    (
                        UniCase::new(arcstr::literal!("w")),
                        Decimal::new(params.w, 3).into(),
                    ),
                    (
                        UniCase::new(arcstr::literal!("l")),
                        Decimal::new(params.l, 3).into(),
                    ),
                    (
                        UniCase::new(arcstr::literal!("nf")),
                        Decimal::from(params.nf).into(),
                    ),
                ]),
            },
        })
    }
    fn convert_instance(
        _instance: &mut Instance,
        _primitive: &<Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl FromSchema<Sky130Pdk> for Ngspice {
    type Error = Infallible;
    fn convert_primitive(
        primitive: <Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<<Ngspice as scir::schema::Schema>::Primitive, Self::Error> {
        Ok(ngspice::Primitive::Spice(<Spice as FromSchema<
            Sky130Pdk,
        >>::convert_primitive(
            primitive
        )?))
    }
    fn convert_instance(
        instance: &mut Instance,
        primitive: &<Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        <Spice as FromSchema<Sky130Pdk>>::convert_instance(instance, primitive)
    }
}

impl FromSchema<Sky130Pdk> for Spectre {
    type Error = Infallible;
    fn convert_primitive(
        primitive: <Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<<Spectre as scir::schema::Schema>::Primitive, Self::Error> {
        Ok(match primitive {
            Primitive::RawInstance {
                cell,
                ports,
                params,
            } => spectre::Primitive::RawInstance {
                cell,
                ports,
                params,
            },
            Primitive::Mos { kind, params } => spectre::Primitive::RawInstance {
                cell: kind.commercial_subckt(),
                ports: vec!["D".into(), "G".into(), "S".into(), "B".into()],
                params: HashMap::from_iter([
                    (arcstr::literal!("w"), Decimal::new(params.w, 3).into()),
                    (arcstr::literal!("l"), Decimal::new(params.l, 3).into()),
                    (arcstr::literal!("nf"), Decimal::from(params.nf).into()),
                ]),
            },
        })
    }
    fn convert_instance(
        _instance: &mut Instance,
        _primitive: &<Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl scir::schema::Schema for Sky130CommercialSchema {
    type Primitive = Primitive;
}

impl FromSchema<Sky130Pdk> for Sky130CommercialSchema {
    type Error = Infallible;

    fn convert_primitive(
        primitive: <Sky130Pdk as Schema>::Primitive,
    ) -> Result<<Self as Schema>::Primitive, Self::Error> {
        Ok(primitive)
    }

    fn convert_instance(
        _instance: &mut Instance,
        _primitive: &<Sky130Pdk as Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl FromSchema<Sky130CommercialSchema> for Spice {
    type Error = Infallible;
    fn convert_primitive(
        primitive: <Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<<Spice as scir::schema::Schema>::Primitive, Self::Error> {
        Ok(match primitive {
            Primitive::RawInstance {
                cell,
                ports,
                params,
            } => spice::Primitive::RawInstance {
                cell,
                ports,
                params: params
                    .into_iter()
                    .map(|(k, v)| (UniCase::new(k), v))
                    .collect(),
            },
            Primitive::Mos { kind, params } => spice::Primitive::Mos {
                model: kind.commercial_subckt(),
                params: HashMap::from_iter([
                    (
                        UniCase::new(arcstr::literal!("w")),
                        Decimal::new(params.w, 3).into(),
                    ),
                    (
                        UniCase::new(arcstr::literal!("l")),
                        Decimal::new(params.l, 3).into(),
                    ),
                    (
                        UniCase::new(arcstr::literal!("nf")),
                        Decimal::from(params.nf).into(),
                    ),
                    (UniCase::new(arcstr::literal!("mult")), dec!(1).into()),
                ]),
            },
        })
    }
    fn convert_instance(
        _instance: &mut Instance,
        _primitive: &<Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl FromSchema<Sky130CommercialSchema> for Spectre {
    type Error = Infallible;
    fn convert_primitive(
        primitive: <Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<<Spectre as scir::schema::Schema>::Primitive, Self::Error> {
        Ok(match primitive {
            Primitive::RawInstance {
                cell,
                ports,
                params,
            } => spectre::Primitive::RawInstance {
                cell,
                ports,
                params,
            },
            Primitive::Mos { kind, params } => spectre::Primitive::RawInstance {
                cell: kind.commercial_subckt(),
                ports: vec!["D".into(), "G".into(), "S".into(), "B".into()],
                params: HashMap::from_iter([
                    (arcstr::literal!("w"), Decimal::new(params.w, 3).into()),
                    (arcstr::literal!("l"), Decimal::new(params.l, 3).into()),
                    (arcstr::literal!("nf"), Decimal::from(params.nf).into()),
                ]),
            },
        })
    }
    fn convert_instance(
        _instance: &mut Instance,
        _primitive: &<Sky130Pdk as scir::schema::Schema>::Primitive,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// The Sky 130 PDK.
#[derive(Debug, Clone)]
pub struct Sky130Pdk {
    open_root_dir: Option<PathBuf>,
    commercial_root_dir: Option<PathBuf>,
}

/// A schema for the commercial PDK.
#[derive(Debug, Clone)]
pub struct Sky130CommercialSchema;

impl Sky130Pdk {
    /// Creates an instantiation of the open PDK.
    #[inline]
    pub fn open(root_dir: impl Into<PathBuf>) -> Self {
        Self {
            open_root_dir: Some(root_dir.into()),
            commercial_root_dir: None,
        }
    }

    /// Creates an instantiation of the commercial PDK.
    #[inline]
    pub fn commercial(root_dir: impl Into<PathBuf>) -> Self {
        Self {
            open_root_dir: None,
            commercial_root_dir: Some(root_dir.into()),
        }
    }
    /// Creates an instance of the PDK with the given root directories.
    #[inline]
    pub fn new(open_root_dir: impl Into<PathBuf>, commercial_root_dir: impl Into<PathBuf>) -> Self {
        Self {
            open_root_dir: Some(open_root_dir.into()),
            commercial_root_dir: Some(commercial_root_dir.into()),
        }
    }
}

impl Installation for Sky130Pdk {
    fn post_install(&self, ctx: &mut ContextBuilder) {
        let layers = ctx.install_pdk_layers::<Sky130Pdk>();

        ctx.install(layers.atoll_layer_stack());
    }
}

impl Pdk for Sky130Pdk {
    type Layers = Sky130Layers;
    const LAYOUT_DB_UNITS: Decimal = dec!(1e-9);
}