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
// Copyright (c) 2021-2021 Thomas Kramer.
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Export libreda-db structures to LEF and DEF.

use libreda_db::prelude as db;
use libreda_db::prelude::reference_access::*;
use libreda_db::prelude::{
    Angle, CoordinateType, Direction, MapPointwise, Scale, TerminalId, ToPolygon, TryBoundingBox,
    TryCastCoord,
};
use libreda_db::traits::*;

use crate::common::{Orient, PinDirection};
use crate::def_ast::{Component, Net, NetTerminal, Pin, DEF};
use crate::def_writer::write_def;
use crate::lef_ast::{Shape, SignalUse, LEF};
use num_traits::{NumCast, PrimInt};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Formatter;

/// Error type returned from LEF/DEF output functions.
#[derive(Debug, Clone)]
pub enum LefDefExportError {
    /// A named entry such as a MACRO already exists in the LEF or DEF structure.
    NameAlreadyExists(String),
    /// A layer in the database has no name defined in the name-mapping, hence cannot be written to LEF or DEF.
    UnknownLayerName,
    /// Unspecified error.
    Other(String),
}

impl std::fmt::Display for LefDefExportError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            LefDefExportError::NameAlreadyExists(name) => {
                write!(f, "Name already exists in LEF/DEF structure: {}", name)
            }
            LefDefExportError::UnknownLayerName => {
                write!(f, "No LEF/DEF layer name is known for a data-base layer.")
            }
            LefDefExportError::Other(msg) => write!(f, "{}", msg),
        };

        Ok(())
    }
}

// /// Convert a LEF shape into a database shape with the correct units.
// fn convert_geometry<C: CoordinateType + NumCast>(dbu_per_micron: u64, shape: &Shape) -> db::Geometry<C> {
//     let dbu_per_micron = dbu_per_micron as f64;
//     // Convert the LEF geometry into a database geometry.
//     let geo: db::Geometry<f64> = match shape {
//         Shape::Path(width, points) => {
//             db::Path::new(points, *width)
//                 .scale(dbu_per_micron).into()
//         }
//         Shape::Rect(p1, p2) => {
//             db::Rect::new(p1, p2)
//                 .scale(dbu_per_micron).into()
//         }
//         Shape::Polygon(points) => {
//             db::SimplePolygon::new(points.clone())
//                 .scale(dbu_per_micron).into()
//         }
//     };
//     let geo: db::Geometry<C> = geo.try_cast()
//         .expect("Cast from float failed."); // This should actually not fail.
//     geo
// }

/// Control the export into DEF structures.
#[derive(Clone)]
pub struct DEFExportOptions<C: L2NBase> {
    /// Enable the export of nets. Default is `true`.
    pub export_nets: bool,
    /// Also export nets which don't connect to anything else.
    pub keep_unconnected_nets: bool,
    /// Export components (cell instances). Default is `true`.
    pub export_components: bool,
    /// Provide alternative names for layers. For all other layers
    /// the default name defined in the [`trait@L2NBase`] type will be used.
    pub layer_mapping: HashMap<C::LayerId, String>,
    /// Take the die-area from this layer.
    /// The layer must contain a single shape.
    pub outline_layer: Option<C::LayerId>,
}

impl<C: L2NBase> Default for DEFExportOptions<C> {
    fn default() -> Self {
        Self {
            export_nets: true,
            keep_unconnected_nets: false,
            export_components: true,
            layer_mapping: Default::default(),
            outline_layer: Default::default(),
        }
    }
}

fn get_cell_outline_bbox<C, Crd>(
    cell: &CellRef<C>,
    outline_layer: &C::LayerId,
) -> Option<db::Rect<Crd>>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt + std::fmt::Display,
    C: L2NBase<Coord = Crd>,
{
    let shapes: Vec<_> = cell.each_shape_per_layer(outline_layer).collect();

    if shapes.len() == 1 {
        let shape = shapes.first().unwrap();
        let geometry = shape.geometry_cloned();
        let bbox = geometry.try_bounding_box();
        if bbox.is_none() {
            log::error!(
                "Outline shape of cell '{}' has no defined bounding box.",
                cell.name()
            );
        }
        bbox
    } else {
        log::error!(
            "Cell '{}' should have exactly one outline shape but has {}.",
            cell.name(),
            shapes.len()
        );
        None
    }
}

/// Populate a [`DEF`] structure from a type implementing the [`trait@L2NBase`] trait.
pub fn export_db_to_def<C, Crd>(
    options: &DEFExportOptions<C>,
    chip: &C,
    top_cell: &C::CellId,
    def: &mut DEF,
) -> Result<(), LefDefExportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt + std::fmt::Display,
    C: L2NBase<Coord = Crd>,
{
    log::info!("Export cell to DEF structure: {}", chip.cell_name(top_cell));

    // Set the design name.
    def.design_name = Some(chip.cell_name(top_cell).into());

    // Set distance units.
    def.units = chip.dbu().to_u32().ok_or_else(|| {
        LefDefExportError::Other(format!(
            "Cannot convert DBU ({}) into a unsigned 32-bit integer.",
            chip.dbu()
        ))
    })?;

    let top = chip.cell_ref(top_cell);

    if options.outline_layer.is_none() {
        return Err(LefDefExportError::Other(
            "Outline layer must be specified in export options.".into(),
        ));
    }
    let outline_layer = options
        .outline_layer
        .as_ref()
        .expect("outline_layer is not specified.");

    // Set die area.
    {
        let top_cell_outline_shapes: Vec<_> = chip.each_shape_id(top_cell, outline_layer).collect();

        if top_cell_outline_shapes.len() == 1 {
            // There is exactly one outline shape.
            let shape_id = top_cell_outline_shapes.first().unwrap();
            let geometry = chip.with_shape(shape_id, |_layer, s| s.clone());
            let polygon = geometry.to_polygon().exterior;
            if let Some(rpolygon) = db::SimpleRPolygon::try_new(polygon.points()) {
                let rpolygon: db::SimpleRPolygon<i32> = rpolygon.try_cast().ok_or_else(|| {
                    LefDefExportError::Other(
                        "Failed to convert DIEAREA into i32 coordinates.".into(),
                    )
                })?; // Convert coordinate data type.
                def.die_area = Some(rpolygon);
            } else {
                log::error!("Failed to convert die area into a rectilinear polygon.");
            }
        } else {
            log::warn!(
                "Top cell should have exactly one outline shape but has {}. DIEAREA is not set.",
                top_cell_outline_shapes.len()
            );
        }
    }

    // Find all macro outlines. They are needed to express the position of the components because
    // the positions are relative to the lower-left corner of the rotated and flipped macro.
    let macro_outlines = {
        let mut macro_outlines = HashMap::new();
        let mut cells_without_outline: Vec<CellRef<C>> = Vec::new();
        for subcell in top.each_cell_dependency() {
            if let Some(outline) = get_cell_outline_bbox(&subcell, outline_layer) {
                macro_outlines.insert(subcell.id(), outline);
            } else {
                cells_without_outline.push(subcell);
            }
        }
        if !cells_without_outline.is_empty() {
            log::error!(
                "Number of cells without outline: {}",
                cells_without_outline.len()
            );
            for cell in &cells_without_outline {
                log::error!("Cell '{}' has no outline.", cell.name());
            }
            return Err(LefDefExportError::Other(format!(
                "{} cells have no outline.",
                cells_without_outline.len()
            )));
        }
        macro_outlines
    };

    // Create components (child instances inside the top cell)
    // Also get a mapping of the possibly created instance names.
    let instance_names = export_instances_to_def(options, top.clone(), &macro_outlines, def)?;

    // Export nets.
    let net_names = export_nets_and_pins_to_def(options, top.clone(), &instance_names, def)?;

    Ok(())
}

// Sort by Option<String> such that `Nones` come at the end of a sorted list.
fn compare_name<S: Ord>(a: &Option<S>, b: &Option<S>) -> Ordering {
    match (a, b) {
        (None, None) => Ordering::Equal,
        (_, None) => Ordering::Less,
        (None, _) => Ordering::Greater,
        (Some(a), Some(b)) => a.cmp(&b),
    }
}

/// Populate a [`DEF`] structure with the component instances.
/// Return a name mapping from instance IDs to their DEF names.
/// The mapping contains possibly generated instance names.
fn export_instances_to_def<C, Crd>(
    options: &DEFExportOptions<C>,
    top: CellRef<C>,
    macro_outlines: &HashMap<C::CellId, db::Rect<Crd>>,
    def: &mut DEF,
) -> Result<HashMap<C::CellInstId, String>, LefDefExportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt,
    C: L2NBase<Coord = Crd>,
{
    log::info!("Export instances to DEF: {}", top.num_child_instances());

    // Create components.
    let mut instances: Vec<_> = top.each_cell_instance().collect();
    // Sort the instances by name. Instances without name will come at the end.
    instances.sort_by(|a, b| compare_name(&a.name(), &b.name()));

    // Generate names for unnamed instances.
    let mut instance_names = HashMap::new();
    let mut instance_name_counter = 1;
    let mut get_instance_name = |inst: &CellInstRef<C>| -> String {
        let name = instance_names.entry(inst.id()).or_insert_with(|| {
            if let Some(name) = inst.name() {
                name.into()
            } else {
                loop {
                    let new_name = format!("__{}__", instance_name_counter);
                    instance_name_counter += 1;
                    if top.cell_instance_by_name(new_name.as_str()).is_none() {
                        // Name is still free.
                        break new_name;
                    }
                }
            }
        });
        name.clone()
    };

    // Export components.
    for inst in instances {
        // Set component name.
        let mut component = Component::default();
        component.name = get_instance_name(&inst);
        // Set model/template name
        component.model_name = inst.template().name().into();

        // Set the component placement.
        let is_fixed = false; // TODO
        let tf = inst.get_transform();
        // Compute displacement (coordinate of lower left corner of the rotated bounding box).
        let displacement: db::Point<_> = {
            let outline = macro_outlines
                .get(&inst.template_id())
                .expect("Macro outline not found.");
            let outline_transformed = outline.transform(|p| tf.transform_point(p));
            outline_transformed.lower_left().cast()
        };
        let orient = match tf.rotation {
            Angle::R0 => Orient::N,
            Angle::R90 => Orient::W,
            Angle::R180 => Orient::S,
            Angle::R270 => Orient::E,
        };
        let orient = if tf.mirror { orient.flipped() } else { orient };
        component.position = Some((displacement, orient, is_fixed));

        def.components.push(component)
    }

    // Return the name mapping.
    Ok(instance_names)
}

/// Populate a [`DEF`] structure with nets and top-level pins.
/// Return a name mapping from net IDs to their DEF names.
/// The mapping contains possibly generated instance names.
///
/// # Parameters
/// * `instance_names`: Mapping from cell instance IDs to their DEF names. This is generated by `export_instances_to_def()`.
fn export_nets_and_pins_to_def<C, Crd>(
    options: &DEFExportOptions<C>,
    top: CellRef<C>,
    instance_names: &HashMap<C::CellInstId, String>,
    def: &mut DEF,
) -> Result<HashMap<C::NetId, String>, LefDefExportError>
where
    C: L2NBase<Coord = Crd>,
{
    log::info!("Export nets to DEF: {}", top.num_internal_nets());

    // Export nets.
    // Generate names for unnamed instances.
    let mut net_names = HashMap::new();
    let mut net_name_generator = 1;
    let mut create_new_net_name = |prefix: &str| -> String {
        loop {
            let new_name = format!("__{}{}__", prefix, net_name_generator);
            net_name_generator += 1;
            if top.net_by_name(new_name.as_str()).is_none() {
                // Name is still free.
                break new_name;
            }
        }
    };
    let mut get_net_name = |net: &NetRef<C>| -> String {
        let name = net_names.entry(net.id()).or_insert_with(|| {
            if let Some(name) = net.name() {
                name.into()
            } else {
                create_new_net_name("")
            }
        });
        name.clone()
    };

    let mut nets: Vec<_> = top.each_net().collect();
    nets.sort_by(|a, b| compare_name(&a.name(), &b.name()));

    // Convert all nets.
    for net_ref in nets {
        // Create the DEF net.
        let mut net = Net::default();
        // Set the name.
        net.name = Some(get_net_name(&net_ref).to_string());

        // Set connected terminals.
        for pin in net_ref.each_pin() {
            net.terminals.push(NetTerminal::IoPin(pin.name().into()));
        }
        for pin in net_ref.each_pin_instance() {
            net.terminals.push(NetTerminal::ComponentPin {
                component_name: instance_names
                    .get(&pin.cell_instance().id())
                    .expect("Cell instance not found.")
                    .to_string(),
                pin_name: pin.pin().name().into(),
            });
        }

        if !net.terminals.is_empty() || options.keep_unconnected_nets {
            def.nets.push(net);
        }
    }

    // Create external pins.
    let mut pins: Vec<_> = top.each_pin().collect();
    pins.sort_by_key(|pin| pin.name());

    for pin_ref in pins {
        let mut pin = Pin::default();
        // Set the pin name.
        pin.pin_name = pin_ref.name().into();
        // Set the net name attached to the pin or create a dummy net if none is attached (required by DEF).
        pin.net_name = pin_ref
            .net()
            .map(|net| {
                net_names
                    .get(&net.id())
                    .expect("Net name not found.")
                    .clone()
            })
            .unwrap_or_else(|| {
                // There is no net connected to the external pin but DEF requires
                // that a net is specified.
                // Create an unconnected dummy net.
                let new_net_name = create_new_net_name("pin_unconnected");

                // Make sure the new net is also listed in the NETS section.
                let mut net = Net::default();
                net.name = Some(new_net_name.clone());
                def.nets.push(net);

                new_net_name
            });

        // Append the newly created pin to the list of pins.
        def.pins.push(pin);
    }

    Ok(net_names)
}

#[test]
fn test_export_to_def() {
    use db::traits::*;
    use libreda_db::prelude as db;

    let mut chip = db::Chip::new();
    let outline_layer = chip.create_layer(1, 0);
    let top_cell = chip.create_cell("TOP".to_string());

    // Create pins of the top cell.
    let pin_a = chip.create_pin(&top_cell, "Input_A".to_string(), db::Direction::Input);
    let pin_b = chip.create_pin(&top_cell, "Output_Y".to_string(), db::Direction::Output);

    // Create nets in the top cell.
    let net_a = chip.create_net(&top_cell, Some("net_a".to_string()));
    let net_b = chip.create_net(&top_cell, Some("net_b".to_string()));

    chip.connect_pin(&pin_a, Some(net_a.clone()));
    chip.connect_pin(&pin_b, Some(net_b.clone()));

    // Create a sub cell.
    let sub_cell = chip.create_cell("SUB".to_string());
    // Create cell outline.
    chip.insert_shape(
        &sub_cell,
        &outline_layer,
        db::Rect::new((0, 0), (10, 10)).into(),
    );

    // Create sub cell instances in TOP.
    chip.create_cell_instance(&top_cell, &sub_cell, Some("inst1".to_string()));
    chip.create_cell_instance(&top_cell, &sub_cell, Some("inst2".to_string()));
    // Create unnamed instances.
    chip.create_cell_instance(&top_cell, &sub_cell, None);
    chip.create_cell_instance(&top_cell, &sub_cell, None);

    let mut def = DEF::default();
    let mut export_options = DEFExportOptions::default();
    export_options.outline_layer = Some(outline_layer);
    let result = export_db_to_def(&export_options, &chip, &top_cell, &mut def);
    if result.is_err() {
        dbg!(&result);
    }
    result.expect("DEF export failed.");

    let mut buffer: Vec<u8> = Vec::new();
    write_def(&mut buffer, &def).expect("Writing DEF failed.");

    let def_string = String::from_utf8(buffer).expect("DEF writer output is not valid UTF-8.");
    println!("{}", &def_string);
}