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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
// Copyright (c) 2021-2021 Thomas Kramer.
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Import LEF and DEF structures by populating data base structures.

use libreda_db::prelude::{self as db, NetlistEditUtil};
use libreda_db::prelude::{Angle, CoordinateType, Direction, Scale, TerminalId, TryCastCoord};
use libreda_db::traits::*;

use crate::def_ast;
use crate::def_ast::{NetTerminal, RoutingPoint, DEF};
use crate::lef_ast::{Layer, RectOrPolygon, Shape, SignalUse, ViaDefinition, ViaShape, LEF};

use crate::common::{Orient, PinDirection};
use num_traits::{FromPrimitive, NumCast, PrimInt, Zero};
use std::collections::HashMap;
use std::fmt::Formatter;

/// Error type returned from LEF/DEF input and output functions.
#[derive(Debug, Clone)]
pub enum LefDefImportError {
    /// The model (aka template or cell type) of a component instance was not found.
    ComponentModelNotFound {
        /// Name of the affected component.
        component_name: String,
        /// Name of the model which was not found.
        model_name: String,
    },
    /// A component was referenced by name but not found.
    ComponentNotFound(String),
    /// A via is referenced by name but cannot be found.
    ViaNotFound(String),
    /// The layer could not be found in the target design and the creation of new layers is disabled.
    LayerNotFound(String),
    /// Cell of this name is already present in the layout and now being redefined in during the import.
    CellNameAlreadyExists(String),
    /// Unspecified error.
    Other(String),
}

impl std::fmt::Display for LefDefImportError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            LefDefImportError::ComponentModelNotFound { component_name, model_name } => {
                write!(f, "Model of component '{}' not found: '{}'", component_name, model_name)
            }
            LefDefImportError::LayerNotFound(layer) => write!(f, "the layer '{}' could not be found in the target design and the creation of new layers is disabled", layer),
            LefDefImportError::ComponentNotFound(component_name) => write!(f, "component was referenced but not found: '{}'", component_name),
            LefDefImportError::ViaNotFound(via_name) => write!(f, "component is referenced but not found: '{}'", via_name),
            LefDefImportError::CellNameAlreadyExists(cell_name) => write!(f, "cell '{}' already exists", cell_name),
            LefDefImportError::Other(msg) => write!(f, "{}", msg)
        };

        Ok(())
    }
}

/// Control the import of a LEF library.
/// This is inspired of the `LEFDEFReaderConfiguration` of KLayout.
#[derive(Clone)]
pub struct LEFImportOptions<C: L2NEdit> {
    // /// Data-base unit for coordinates.
    // pub dbu: Option<C::Coord>,
    /// Enable import of pins.
    pub import_pins: bool,
    /// Also import ground and supply pins. This gets overwritten when `import_pins` is false.
    pub import_power_pins: bool,
    /// Append this string to layer names of pins. Default is ".PIN".
    pub pin_suffix: String,
    /// Enable import of obstruction shapes.
    pub import_obstructions: bool,
    /// Append this string to layer names of obstructions. Default is ".OBS".
    pub obstruction_suffix: String,
    /// Import via definitions as cells.
    pub import_via_definitions: bool,
    /// Import vias 'generated' vias. Only matters with `import_via_definitions = true`.
    pub import_generated_vias: bool,
    /// Import 'fixed' vias. Only matters with `import_via_definitions = true`.
    pub import_fixed_vias: bool,
    /// Enable import of cell outlines and define on which layer they should be put.
    pub import_cell_outlines: bool,
    /// Layer to be used for cell outlines (abutment boxes).
    pub cell_outline_layer: Option<String>,
    /// Mapping from LEF layer names to layer IDs.
    pub layer_mapping: HashMap<String, C::LayerId>,
    /// Create layers which are missing in the current design.
    pub create_missing_layers: bool,
    /// If a cell with the same name as the via already exists, skip it during import instead of failing.
    pub skip_existing_vias: bool,
}

impl<C: L2NEdit> Default for LEFImportOptions<C> {
    fn default() -> Self {
        Self {
            // dbu: None,
            import_pins: true,
            import_power_pins: true,
            pin_suffix: ".PIN".to_string(),
            import_obstructions: true,
            obstruction_suffix: ".OBS".to_string(),
            import_via_definitions: true,
            import_generated_vias: true,
            import_fixed_vias: true,
            import_cell_outlines: true,
            cell_outline_layer: Some("OUTLINE".to_string()),
            layer_mapping: Default::default(),
            create_missing_layers: true,
            skip_existing_vias: false,
        }
    }
}

impl<C: L2NEdit> LEFImportOptions<C> {
    /// Try to get a layer ID by the layer name or optionally create a new layer.
    /// Test the layer mapping but also the layout for existing layers.
    fn get_or_create_layer_by_name(
        &self,
        chip: &mut C,
        layer_name: &String,
    ) -> Result<C::LayerId, LefDefImportError> {
        let layer =
            // First try to get the layer from the layer map...
            self.layer_mapping.get(layer_name)
                .cloned()
                // ... then try to get it from the layout by name...
                .or_else(|| chip.layer_by_name(layer_name.as_str()))
                // ... as a last resort try to create the layer but only if creation of layers is enabled.
                .or_else(|| if self.create_missing_layers {
                    let next_idx = chip.each_layer()
                        .map(|id| chip.layer_info(&id).index)
                        .max()
                        .unwrap_or(0) + 1;
                    log::debug!("Create layer: {}", layer_name);
                    let layer_id = chip.create_layer(next_idx, 0);
                    chip.set_layer_name(&layer_id, Some(layer_name.clone().into()));
                    Some(layer_id)
                } else {
                    None
                });

        // Return an error when no layer was found.
        layer.ok_or_else(|| LefDefImportError::LayerNotFound(layer_name.clone()))
    }
}

/// 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 import of DEF structures.
#[derive(Clone)]
pub struct DEFImportOptions<C: L2NEdit> {
    /// Options for importing the LEF.
    pub lef_import_options: LEFImportOptions<C>,
    /// Enable import of blockage shapes.
    pub import_blockages: bool,
    /// Append this string to layer names of blockages. Default is ".BLOCKAGE".
    pub blockages_suffix: String,
    /// Enable import of nets.
    pub import_nets: bool,
    /// Enable import of routes.
    pub import_wiring: bool,
    /// Enable import of fixed via definitions. Vias are imported as cells.
    pub import_fixed_vias: bool,
    /// If true: If a via name already exists, don't import it.
    /// If false: Return an error if the via name already exists.
    pub skip_existing_vias: bool,
}

impl<C: L2NEdit> Default for DEFImportOptions<C> {
    fn default() -> Self {
        Self {
            lef_import_options: Default::default(),
            import_blockages: true,
            blockages_suffix: ".BLOCKAGE".to_string(),
            import_nets: true,
            import_wiring: true,
            import_fixed_vias: true,
            skip_existing_vias: false,
        }
    }
}

/// Convert a LEF structure into a `Chip` data structure using default import options.
/// Use `import_lef_into_db()` for better control over the import strategy.
pub fn lef_to_db<C, Crd>(lef: &LEF) -> Result<C, LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType,
    C: L2NEdit<Coord = Crd> + Default,
{
    let mut chip = C::default();
    let options = Default::default();
    import_lef_into_db(&options, lef, &mut chip).map(|_| chip)
}

/// Populate `chip` with the contents of the LEF data-structure.
pub fn import_lef_into_db<C, Crd>(
    options: &LEFImportOptions<C>,
    lef: &LEF,
    chip: &mut C,
) -> Result<(), LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType,
    C: L2NEdit<Coord = Crd>,
{
    // let dbu_per_micron = lef.technology.units.database_microns;
    assert!(
        chip.dbu() > Crd::zero(),
        "Data-base distance unit (DBU) must be a positive number"
    );
    let dbu_per_micron = chip.dbu().to_u64().expect("failed to convert DBU to u64");

    // Setup layers.
    for (i, layer) in lef.technology.layers.iter().enumerate() {
        let result = options.get_or_create_layer_by_name(chip, layer.name());
        if let Err(err) = result {
            // Dont't abort yet on this error. Could be that the layer is then never used.
            // Emit a warning instead.
            log::warn!("Failed to create layer: {} ({})", layer.name(), err)
        }
    }

    // Import via definitions.
    if options.import_via_definitions {
        import_lef_vias(options, lef, chip)?;
    }

    // Create macro cells.
    for (macro_name, lef_macro) in &lef.library.macros {
        let cell = chip.create_cell(macro_name.to_string().into());

        // Insert pins.
        if options.import_pins {
            // Cache for pin names with suffix.
            let mut pin_layer_name_cache = HashMap::new();
            for macro_pin in &lef_macro.pins {
                // Eventually skip power pins.
                let signal_use = macro_pin.signal_use.unwrap_or(SignalUse::Signal);
                let is_power_ground_pin =
                    signal_use == SignalUse::Power || signal_use == SignalUse::Ground;
                if !options.import_power_pins && is_power_ground_pin {
                    continue;
                }

                // Get signal direction.
                let direction = match &macro_pin.direction {
                    None => Direction::None,
                    Some(d) => match d {
                        PinDirection::Input => Direction::Input,
                        PinDirection::Output(_tristate) => Direction::Output,
                        PinDirection::Inout => Direction::InOut,
                        PinDirection::Feedthru => Direction::InOut,
                    },
                };

                // Create electrical pin.
                let pin = chip.create_pin(&cell, macro_pin.name.clone().into(), direction);

                // Insert pin shapes.
                for port in &macro_pin.ports {
                    for layer_geometry in &port.geometries {
                        // Find the target layer for the pin.
                        // Append the layer suffix.
                        let layer_name = pin_layer_name_cache
                            .entry(&layer_geometry.layer_name)
                            .or_insert_with(|| {
                                format!("{}{}", layer_geometry.layer_name, options.pin_suffix)
                            });
                        let layer = options.get_or_create_layer_by_name(chip, layer_name)?;

                        for g in &layer_geometry.geometries {
                            let geo = convert_geometry(dbu_per_micron, &g.shape);
                            let shape_id = chip.insert_shape(&cell, &layer, geo);
                            chip.set_pin_of_shape(&shape_id, Some(pin.clone()));
                        }
                    }
                }
            }
        }

        // Import cell outline.
        if options.import_cell_outlines {
            if let Some((width, height)) = lef_macro.size {
                if let Some(outline_layer_name) = &options.cell_outline_layer {
                    // Get the rectangular outline shape.
                    let shape = Shape::Rect(
                        lef_macro.origin,
                        lef_macro.origin + db::Point::new(width, height),
                    );
                    // Convert units.
                    let geo = convert_geometry(dbu_per_micron, &shape);

                    let outline_layer =
                        options.get_or_create_layer_by_name(chip, outline_layer_name)?;

                    // Insert outline shape on layer.
                    chip.insert_shape(&cell, &outline_layer, geo);
                }
            }
        }

        // Import obstruction shapes.
        if options.import_obstructions {
            let mut obs_layer_name_cache = HashMap::new();
            for obs in &lef_macro.obs {
                // Find the target layer for the obstruction.
                // Append the layer suffix.
                let layer_name = obs_layer_name_cache
                    .entry(&obs.layer_name)
                    .or_insert_with(|| format!("{}{}", obs.layer_name, options.obstruction_suffix));
                let layer = options.get_or_create_layer_by_name(chip, layer_name)?;

                for g in &obs.geometries {
                    let geo = convert_geometry(dbu_per_micron, &g.shape);
                    chip.insert_shape(&cell, &layer, geo);
                }
            }
        }
    }

    Ok(())
}

/// Import LEF via definitions as cells into the layout.
/// On success returns a vector with the IDs of the new via cells.
pub fn import_lef_vias<C, Crd>(
    options: &LEFImportOptions<C>,
    lef: &LEF,
    chip: &mut C,
) -> Result<Vec<C::CellId>, LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType,
    C: L2NEdit<Coord = Crd>,
{
    let dbu_per_micron: f64 = chip.dbu().to_f64().unwrap();

    let mut via_cells = vec![];

    for (via_name, via) in &lef.vias {
        // Check that no cell with this name exists.
        if chip.cell_by_name(via_name).is_some() {
            if options.skip_existing_vias {
                continue;
            } else {
                return Err(LefDefImportError::CellNameAlreadyExists(via_name.clone()));
            }
        }

        let via_cell = chip.create_cell(via_name.clone().into());

        match via {
            ViaDefinition::GeneratedVia(via) => {
                if options.import_generated_vias {
                    todo!("import of generated vias")
                }
            }
            ViaDefinition::FixedVia(via) => {
                if options.import_fixed_vias {
                    for (layer_name, shapes) in &via.geometry {
                        let layer = options.get_or_create_layer_by_name(chip, layer_name)?;

                        for shape in shapes {
                            // TODO import mask number
                            let geometry: db::Geometry<f64> = match &shape.shape {
                                RectOrPolygon::Rect((p1, p2)) => {
                                    db::Rect::new(*p1, *p2).scale(dbu_per_micron).into()
                                }
                                RectOrPolygon::Polygon(points) => {
                                    // Create a rectilinear polygon if possible.
                                    let p = db::SimplePolygon::new(points.to_vec())
                                        .scale(dbu_per_micron);
                                    if let Some(p) = db::SimpleRPolygon::try_new(p.points()) {
                                        p.into()
                                    } else {
                                        p.into()
                                    }
                                }
                            };

                            let geo: db::Geometry<C::Coord> =
                                geometry.try_cast().expect("cast from f64 failed");

                            // Add the shape to the layout.
                            chip.insert_shape(&via_cell, &layer, geo);
                        }
                    }
                }
            }
            _ => {}
        };

        via_cells.push(via_cell);
    }

    Ok(via_cells)
}

/// Convert a LEF and a DEF structure into a `Chip` data structure.
/// Currently this reads only the placement of the cells. No wires are created.
pub fn lefdef_to_db<C, Crd>(
    options: &DEFImportOptions<C>,
    lef: &LEF,
    def: &DEF,
) -> Result<C, LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt,
    C: L2NEdit<Coord = Crd> + Default,
{
    let mut chip = C::default();

    // First read the library.
    import_lef_into_db(&options.lef_import_options, lef, &mut chip)?;
    import_def_into_db(&options, Some(lef), def, &mut chip).map(|_| chip)
}

/// Import the netlist from the DEF structure into the `top_cell`.
///
/// **Caveat**: Adds connections of pins but does not clear the existing netlist before. Existing connections
/// may be disrupted.
pub fn import_def_netlist<C, Crd>(
    options: &DEFImportOptions<C>,
    def: &DEF,
    top_cell: &C::CellId,
    chip: &mut C,
) -> Result<(), LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt,
    C: L2NEdit<Coord = Crd>,
{
    log::info!(
        "Import netlist from DEF. Number of nets: {}",
        def.nets.len()
    );
    let mut nets_by_name = HashMap::new();

    // Process each net.
    for net in &def.nets {
        if let Some(net_name) = &net.name {
            // Get or create net ID.
            let net_id = nets_by_name
                .entry(net_name)
                .or_insert_with(|| chip.create_net(&top_cell, Some(net_name.to_string().into())));

            for term in &net.terminals {
                // Find net terminal based on the given component and pin names.
                let term_id: TerminalId<C> = match term {
                    NetTerminal::ComponentPin {
                        component_name,
                        pin_name,
                    } => {
                        // Pin instance.
                        let inst = chip
                            .cell_instance_by_name(&top_cell, component_name.as_str())
                            .ok_or_else(|| {
                                LefDefImportError::ComponentNotFound(component_name.to_string())
                            })?;
                        let cell = chip.template_cell(&inst);
                        let pin_id =
                            chip.pin_by_name(&cell, pin_name.as_str()).ok_or_else(|| {
                                LefDefImportError::Other(format!(
                                    "Pin of component not found: {}",
                                    pin_name
                                ))
                            })?;
                        let pin_inst = chip.pin_instance(&inst, &pin_id);

                        TerminalId::PinInstId(pin_inst)
                    }
                    NetTerminal::IoPin(pin_name) => {
                        // Pin.
                        let pin_id =
                            chip.pin_by_name(&top_cell, pin_name.as_str())
                                .ok_or_else(|| {
                                    LefDefImportError::Other(format!(
                                        "Pin of top-level cell not found: {}",
                                        pin_name
                                    ))
                                })?;

                        TerminalId::PinId(pin_id)
                    }
                };
                // Attach the terminal to the net.
                chip.connect_terminal(&term_id, Some(net_id.clone()));
            }
        } else {
            log::warn!("DEF import of nets without name (MUSTJOIN nets) is not implemented yet.");
        }
    }
    Ok(())
}

/// Import DEF via definitons as cells into the layout.
pub fn import_def_vias<C, Crd>(
    options: &DEFImportOptions<C>,
    def: &DEF,
    chip: &mut C,
) -> Result<(), LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType,
    C: L2NEdit<Coord = Crd>,
{
    log::debug!("import via definitions from DEF");

    for (via_name, via) in &def.vias {
        log::debug!("import via '{}'", via_name);

        // Check that no cell with this name exists.
        if chip.cell_by_name(via_name).is_some() {
            if options.skip_existing_vias {
                continue;
            } else {
                return Err(LefDefImportError::CellNameAlreadyExists(via_name.clone()));
            }
        }

        let via_cell = chip.create_cell(via_name.clone().into());

        match via {
            def_ast::ViaDefinition::ViaGeometry(via_geometry) => {
                log::debug!("import of via geometry '{}'", via_name);
                for geometry in via_geometry {
                    // TODO: For multi-patterning import mask number.
                    if geometry.mask_num.is_some() {
                        log::warn!("via mask number is ignored");
                    }

                    let layer = options
                        .lef_import_options
                        .get_or_create_layer_by_name(chip, &geometry.layer)?;

                    let geometry: db::Geometry<db::Coord> = match &geometry.shape {
                        def_ast::RectOrPolygon::Rect(r) => r.clone().into(),
                        def_ast::RectOrPolygon::Polygon(p) => p.clone().into(),
                    };

                    let geo: db::Geometry<C::Coord> = geometry.try_cast().expect("cast failed");

                    // Add the shape to the layout.
                    chip.insert_shape(&via_cell, &layer, geo);
                }
            }
            def_ast::ViaDefinition::ViaRule => {
                log::debug!("skip import of via rule '{}'", via_name);
            }
        }
    }

    Ok(())
}

/// Import routes/wiring from the nets in the DEF structure.
pub fn import_def_regular_wiring<C, Crd>(
    options: &DEFImportOptions<C>,
    lef: &LEF,
    def: &DEF,
    top_cell: &C::CellId,
    chip: &mut C,
) -> Result<(), LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt,
    C: L2NEdit<Coord = Crd>,
{
    log::info!(
        "Import wiring from DEF. Number of nets with wiring: {}",
        def.nets
            .iter()
            .filter(|net| !net.regular_wiring.is_empty())
            .count()
    );

    // Find default wiring widths from LEF.
    let default_wiring_widths = {
        let mut default_wiring_widths = HashMap::new();
        let units_per_micron: f64 = chip.dbu().to_f64().unwrap();

        for layer in &lef.technology.layers {
            match layer {
                Layer::MasterSlice(_) => {
                    // Ignore
                }
                Layer::Cut(_) => {
                    // Ignore
                }
                Layer::Routing(routing_layer) => {
                    // Find the layer by its name.
                    if let Some(layer_id) = chip.layer_by_name(routing_layer.name.as_str()) {
                        // Get wire width and convert to database units.
                        let default_widths_microns = routing_layer.width;
                        let default_widths_dbu =
                            db::Coord::from_f64(default_widths_microns * units_per_micron)
                                .expect("Failed to cast default path width to database units.");

                        // Store the wiring widths.
                        default_wiring_widths.insert(layer_id, default_widths_dbu);
                    } else {
                        log::warn!("Layer '{}' is not present in the current design. Default wiring width will be ignored during import.", &routing_layer.name);
                    }
                }
            }
        }
        default_wiring_widths
    };

    // Process each net.
    for net in &def.nets {
        let net_name = net.name.as_ref().ok_or_else(|| {
            LefDefImportError::Other("Wiring for unnamed nets is not supported.".into())
        })?;

        log::debug!("Import wiring for net '{}'", &net_name);

        let net_id = chip
            .net_by_name(top_cell, net_name.as_str())
            .ok_or_else(|| LefDefImportError::Other(format!("Net not found: {}", net_name)))?;

        for regular_wiring in &net.regular_wiring {
            let _wiring_class = regular_wiring.class; // TODO: Wiring class is for now ignored.
            for wiring in &regular_wiring.wiring {
                let _style = wiring.style_num; // TODO: Style is ignored for now.
                let _taper_rule = &wiring.taper_rule; // TODO: Taper rule is ignored for now.

                // Current location of the path.
                let mut current_layer = options
                    .lef_import_options
                    .get_or_create_layer_by_name(chip, &wiring.start_layer_name)?;
                let mut current_point = None;

                // Find default wiring widths from LEF.
                let path_width = *default_wiring_widths.get(&current_layer).ok_or_else(|| {
                    LefDefImportError::Other(format!(
                        "No default wiring width defined for layer '{}'",
                        &wiring.start_layer_name
                    ))
                })?;

                let _2 = Crd::one() + Crd::one();

                let mut begin_ext = path_width / 2;
                let mut end_ext = path_width / 2;
                let mut path: Vec<db::Point<_>> = Vec::new();
                let mut paths: Vec<db::Path<Crd>> = Vec::new();

                for routing_point in &wiring.routing_points {
                    match routing_point {
                        RoutingPoint::Point {
                            point,
                            ext_value,
                            mask_num,
                        } => {
                            if let Some(ext_value) = ext_value {
                                if current_point.is_none() {
                                    // Extension at beginning of path.
                                    begin_ext = *ext_value;
                                }
                                end_ext = *ext_value;
                            }
                            current_point = Some(point.clone());
                            path.push(point.clone());
                        }
                        RoutingPoint::Via {
                            via_name,
                            orient,
                            via_mask_num,
                        } => {
                            // Import the via by creating a instance of the via cell with the same name.
                            if let Some(p) = current_point {
                                // Place a via cell at the current point.
                                let via_cell =
                                    chip.cell_by_name(via_name.as_str()).ok_or_else(|| {
                                        LefDefImportError::ViaNotFound(via_name.clone())
                                    })?;

                                // Get the orientation and displacement of the via instance.
                                let transform = if let Some(orient) = orient {
                                    def_orient_to_transform(orient)
                                } else {
                                    db::SimpleTransform::identity()
                                }
                                .then(&db::SimpleTransform::translate(p.v().cast()));

                                // Create the via instance.
                                let via_instance =
                                    chip.create_cell_instance(&top_cell, &via_cell, None);

                                // Set the placement of the via instance.
                                chip.set_transform(&via_instance, transform);
                            } else {
                                log::error!("current point in wiring path is not known");
                            }
                        }
                        RoutingPoint::Rect { rect, mask_num } => {
                            // Insert the rectangle into the layout.
                            let rect = rect.cast();
                            let shape_id = chip.insert_shape(top_cell, &current_layer, rect.into());
                            // Associate with the net.
                            chip.set_net_of_shape(&shape_id, Some(net_id.clone()));
                        }
                        RoutingPoint::Virtual(p) => {
                            current_point = Some(p.clone());
                            let finished_path = std::mem::replace(&mut path, vec![]);

                            let finished_path = db::Path::new_extended(
                                finished_path,
                                path_width,
                                begin_ext,
                                end_ext,
                            )
                            .cast();
                            paths.push(finished_path);
                        }
                    }
                }

                // Store current path.
                let finished_path =
                    db::Path::new_extended(path, path_width, begin_ext, end_ext).cast();
                paths.push(finished_path);

                // Write paths to layout.
                for path in paths {
                    if path.len() > 1 {
                        // Skip paths without segments.
                        let path = path.cast(); // Cast to correct coordinate type.
                        let shape_id = chip.insert_shape(top_cell, &current_layer, path.into());
                        // Associate with the net.
                        chip.set_net_of_shape(&shape_id, Some(net_id.clone()));
                    }
                }
            }
        }
    }
    Ok(())
}

/// Convert a LEF and a DEF structure into a `Chip` data structure.
///
/// A LEF data structure may be necessary for the definition of default wiring lengths.
/// An error will be returned if the LEF data structure is omitted but needed.
pub fn import_def_into_db<C, Crd>(
    options: &DEFImportOptions<C>,
    lef: Option<&LEF>,
    def: &DEF,
    chip: &mut C,
) -> Result<(), LefDefImportError>
where
    Crd: NumCast + Ord + CoordinateType + PrimInt,
    C: L2NEdit<Coord = Crd>,
{
    if options.import_fixed_vias {
        import_def_vias(options, def, chip)?;
    }

    let top_cell = chip.create_cell(def.design_name.clone().unwrap_or("TOP".to_string()).into());
    log::info!("Import '{}' from DEF.", chip.cell_name(&top_cell));

    // Create pins.
    log::info!("Import top-level pins: {}", def.pins.len());
    for pin in &def.pins {
        let pin_dir = match &pin.direction {
            None => Direction::None,
            Some(d) => match d {
                PinDirection::Input => Direction::Input,
                PinDirection::Output(_tristate) => Direction::Output,
                PinDirection::Inout => Direction::InOut,
                PinDirection::Feedthru => Direction::InOut,
            },
        };
        chip.create_pin(&top_cell, pin.net_name.to_string().into(), pin_dir);
    }

    // Import outline of top cell (DIEAREA).
    if options.lef_import_options.import_cell_outlines {
        if let Some(die_area) = &def.die_area {
            if let Some(outline_layer_name) = &options.lef_import_options.cell_outline_layer {
                let outline_layer = options
                    .lef_import_options
                    .get_or_create_layer_by_name(chip, outline_layer_name)?;

                // Insert outline shape on layer.
                let geometry = die_area.cast().into();
                chip.insert_shape(&top_cell, &outline_layer, geometry);
            }
        }
    }

    // Create components (instances).
    log::info!(
        "Import components from DEF. Number of components: {}",
        def.components.len()
    );
    for component in &def.components {
        // Find template cell.
        let module = chip.cell_by_name(component.model_name.as_str()).ok_or(
            LefDefImportError::ComponentModelNotFound {
                component_name: component.name.clone(),
                model_name: component.model_name.clone(),
            },
        )?;

        // Create instance.
        let inst =
            chip.create_cell_instance(&top_cell, &module, Some(component.name.clone().into()));

        if let Some((displacement, orientation, is_fixed)) = &component.position {
            let tf = def_orient_to_transform(orientation)
                .then(&db::SimpleTransform::translate(displacement.v().cast()));

            chip.set_transform(&inst, tf);
        }
    }

    if options.import_blockages {
        // TODO: Import blockages.
    }

    // Import netlist.
    if options.import_nets {
        import_def_netlist(options, def, &top_cell, chip)?;
    }

    // Import routes.
    if options.import_wiring {
        let lef = lef.ok_or_else(|| {
            LefDefImportError::Other(
                "No LEF data is provided but needed for import of wiring.".into(),
            )
        })?;
        import_def_regular_wiring(options, lef, def, &top_cell, chip)?;
    }

    Ok(())
}

/// Convert a DEF `Orient` type into a 90-degree rotation transform.
fn def_orient_to_transform<Crd>(orient: &Orient) -> db::SimpleTransform<Crd>
where
    Crd: CoordinateType,
{
    let (orientation, flipped) = orient.decomposed();
    let angle = match orientation {
        Orient::N => Angle::R0,
        Orient::S => Angle::R180,
        Orient::E => Angle::R270,
        Orient::W => Angle::R90,
        _ => unreachable!(), // .decomposed() does not return any of this variants.
    };

    db::SimpleTransform::new(flipped, angle, Crd::one(), db::Vector::zero())
}

#[test]
fn test_lefdef_to_chip() {
    use crate::def_parser::read_def_chars;
    use crate::lef_parser::read_lef_chars;
    let data = r#"
# Parts from gscl45nm.lef.

VERSION 5.5 ;
NAMESCASESENSITIVE ON ;
BUSBITCHARS "[]" ;
DIVIDERCHAR "/" ;

PROPERTYDEFINITIONS
  LAYER contactResistance REAL ;
END PROPERTYDEFINITIONS

UNITS
  DATABASE MICRONS 2000 ;
END UNITS
MANUFACTURINGGRID 0.0025 ;
LAYER poly
  TYPE MASTERSLICE ;
END poly

LAYER contact
  TYPE CUT ;
  SPACING 0.075 ;
  PROPERTY contactResistance 10.5 ;
END contact

LAYER metal1
  TYPE ROUTING ;
  DIRECTION HORIZONTAL ;
  PITCH 0.19 ;
  WIDTH 0.065 ;
  SPACING 0.065 ;
  RESISTANCE RPERSQ 0.38 ;
END metal1

LAYER via1
  TYPE CUT ;
  SPACING 0.075 ;
  PROPERTY contactResistance 5.69 ;
END via1

LAYER metal2
  TYPE ROUTING ;
  DIRECTION VERTICAL ;
  PITCH 0.19 ;
  WIDTH 0.065 ;
  SPACING 0.065 ;
  RESISTANCE RPERSQ 0.38 ;
END metal2

LAYER OVERLAP
  TYPE OVERLAP ;
END OVERLAP

VIA M2_M1_via DEFAULT
  LAYER metal1 ;
    RECT -0.0675 -0.0325 0.0675 0.0325 ;
  LAYER via1 ;
    RECT -0.0325 -0.0325 0.0325 0.0325 ;
  LAYER metal2 ;
    RECT -0.035 -0.0675 0.035 0.0675 ;
END M2_M1_via

VIARULE M2_M1 GENERATE
  LAYER metal1 ;
    ENCLOSURE 0 0.035 ;
  LAYER metal2 ;
    ENCLOSURE 0 0.035 ;
  LAYER via1 ;
    RECT -0.0325 -0.0325 0.0325 0.0325 ;
    SPACING 0.14 BY 0.14 ;
END M2_M1

VIARULE M1_POLY GENERATE
  LAYER poly ;
    ENCLOSURE 0 0 ;
  LAYER metal1 ;
    ENCLOSURE 0 0.035 ;
  LAYER contact ;
    RECT -0.0325 -0.0325 0.0325 0.0325 ;
    SPACING 0.14 BY 0.14 ;
END M1_POLY

SPACING
  SAMENET metal1 metal1 0.1 ;
  SAMENET metal2 metal2 0.1 ;
END SPACING

SITE CoreSite
  CLASS CORE ;
  SIZE 0.38 BY 2.47 ;
END CoreSite

MACRO INVX1
  CLASS CORE ;
  ORIGIN 0 0 ;
  FOREIGN INVX1 0 0 ;
  SIZE 0.57 BY 2.47 ;
  SYMMETRY X Y ;
  SITE CoreSite ;
  PIN A
    DIRECTION INPUT ;
    USE SIGNAL ;
    PORT
      LAYER metal1 ;
        RECT 0.1575 0.4875 0.2575 0.6225 ;
    END
  END A
  PIN Y
    DIRECTION OUTPUT ;
    USE SIGNAL ;
    PORT
      LAYER metal1 ;
        RECT 0.3475 0.2175 0.4125 1.815 ;
        RECT 0.3125 0.2175 0.4475 0.4225 ;
    END
  END Y
  PIN gnd
    DIRECTION INOUT ;
    USE GROUND ;
    SHAPE ABUTMENT ;
    PORT
      LAYER metal1 ;
        RECT 0.1625 -0.065 0.2275 0.4225 ;
        RECT 0 -0.065 0.57 0.065 ;
    END
  END gnd
  PIN vdd
    DIRECTION INOUT ;
    USE POWER ;
    SHAPE ABUTMENT ;
    PORT
      LAYER metal1 ;
        RECT 0.1625 1.265 0.2275 2.535 ;
        RECT 0 2.405 0.57 2.535 ;
    END
  END vdd
END INVX1


MACRO INVX2
  CLASS CORE ;
  ORIGIN 0 0 ;
  FOREIGN INVX1 0 0 ;
  SIZE 0.57 BY 2.47 ;
  SYMMETRY X Y ;
  SITE CoreSite ;
  PIN A
    DIRECTION INPUT ;
    USE SIGNAL ;
    PORT
      LAYER metal1 ;
        RECT 0.1575 0.4875 0.2575 0.6225 ;
    END
  END A
  PIN Y
    DIRECTION OUTPUT ;
    USE SIGNAL ;
    PORT
      LAYER metal1 ;
        RECT 0.3475 0.2175 0.4125 1.815 ;
        RECT 0.3125 0.2175 0.4475 0.4225 ;
    END
  END Y
  PIN gnd
    DIRECTION INOUT ;
    USE GROUND ;
    SHAPE ABUTMENT ;
    PORT
      LAYER metal1 ;
        RECT 0.1625 -0.065 0.2275 0.4225 ;
        RECT 0 -0.065 0.57 0.065 ;
    END
  END gnd
  PIN vdd
    DIRECTION INOUT ;
    USE POWER ;
    SHAPE ABUTMENT ;
    PORT
      LAYER metal1 ;
        RECT 0.1625 1.265 0.2275 2.535 ;
        RECT 0 2.405 0.57 2.535 ;
    END
  END vdd
END INVX2

END LIBRARY

    "#;

    let result = read_lef_chars(data.chars());
    let lef = result.expect("LEF parsing failed.");

    let def_data = r#"
VERSION 5.7 ;
DIVIDERCHAR "/" ;
BUSBITCHARS "[]" ;
DESIGN test_design ;
UNITS DISTANCE MICRONS 2000 ;
TECHNOLOGY FreePDK45 ;

DIEAREA ( 0 0 ) ( 10000 10000 ) ;

PINS 2 ;
- IN + NET IN
    + DIRECTION INPUT
- OUT + NET OUT
    + DIRECTION OUTPUT
END PINS

COMPONENTS 3 ;
    - _1_ INVX1 ;
    - _2_ INVX2 ;
    - _3_ INVX2 ;
END COMPONENTS

NETS 6 ;
- IN ( PIN IN ) ;
- OUT ( PIN OUT ) ;
- net1 ( _1_ A ) ;
END NETS

END DESIGN
"#;

    let result = read_def_chars(def_data.chars());
    let def = result.expect("DEF parsing failed.");

    let mut chip = db::Chip::new();
    let mut options = DEFImportOptions::default();
    options.lef_import_options.import_power_pins = false;
    // Import LEF.
    {
        let result = import_lef_into_db(&options.lef_import_options, &lef, &mut chip);
        if result.is_err() {
            dbg!(&result);
        }
    }
    // Import DEF.
    {
        let result = import_def_into_db(&options, Some(&lef), &def, &mut chip);
        if result.is_err() {
            dbg!(&result);
        }
    }

    assert_eq!(chip.num_cells(), 1 + 2 + 1); // TOP + INVX1 + INVX2 + a via

    let top = chip.cell_by_name("test_design").unwrap();
    assert_eq!(chip.num_child_instances(&top), 3);

    let invx1 = chip.cell_by_name("INVX1").expect("Cell not found.");
    assert_eq!(chip.num_pins(&invx1), 2);

    assert_eq!(chip.num_internal_nets(&top), 3 + 2); // + HIGH and LOW

    // Check if pin A of instance _1_ is indeed connected to net1.
    let pin_a = chip.pin_by_name(&invx1, "A").expect("Pin A not found.");
    let inst1 = chip
        .cell_instance_by_name(&top, "_1_")
        .expect("Cell instance _1_ not found.");
    let net = chip
        .net_of_pin_instance(&chip.pin_instance(&inst1, &pin_a))
        .expect("No net connected to _1_:A.");
    assert_eq!(chip.net_name(&net), Some("net1".to_string()));
}