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

//! Data types specific to DEF.

use crate::common::{Orient, PinDirection, PropertyType, PropertyValue};
use crate::stream_parser::LefDefParseError;
use libreda_db::prelude as db;
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

/// Integer type used for mask numbers.
pub type MaskNum = u8;
/// Integer coordinate type.
pub type Coord = db::Coord;

/// Representation of a design as defined in DEF.
#[derive(Clone, Debug)]
pub struct DEF {
    /// Version of the DEF syntax.
    pub version: Option<String>,
    /// Characters that are used to mark bus bit indices. Default are `[` and `]`.
    pub busbitchars: (char, char),
    /// Character used as path separator. Default is `/`.
    pub dividerchar: char,
    /// Name of the design.
    pub design_name: Option<String>,
    // DESIGN
    /// Name of the technology.
    pub technology: Option<String>,
    /// Distance units per micron.
    /// Values supported by LEF are: 100, 200, 1000, 2000, 10000, 20000
    /// The database unit value in LEF must be greater or equal to the one in DEF to avoid round-off errors.
    pub units: u32,
    /// Arbitrary text.
    pub history: Vec<String>,
    /// Definitions of custom properties used in the design.
    pub property_definitions: BTreeMap<String, DEFPropertyDefinition>,
    /// Shape of the die.
    pub die_area: Option<db::SimpleRPolygon<Coord>>,
    /// Rows stored by their name.
    pub rows: BTreeMap<String, Row>,
    /// Routing grid for standard-cell based designs.
    pub tracks: Vec<Tracks>,
    /// TODO
    pub gcell_grid: Vec<()>,
    /// Geometry definitions of the vias used in the design.
    pub vias: BTreeMap<String, ViaDefinition>,
    /// Styles of wire ends.
    pub styles: Vec<()>,
    /// TODO
    pub nondefault_rules: (),
    /// Regions are named geometrical locations that can be used to place components.
    pub regions: BTreeMap<String, Region>,
    /// Components of the design. This includes placed and unplaced cells and macros.
    pub components: Vec<Component>,
    /// Definitions of external pins of the design. Associates external pin names with internal nets and
    /// pin geometries.
    pub pins: Vec<Pin>,
    /// Definitions of pin properties.
    /// TODO
    pub pin_properties: (),
    /// Placement and routing blockages.
    pub blockages: Vec<Blockage>,
    /// TODO
    pub slots: (),
    ///  TODO
    pub fills: (),
    /// Definitions of special nets.
    /// Special nets include nets like include power, clock, RF, and analog signals.
    /// They should not be touched by the signal router.
    pub special_nets: BTreeMap<String, ()>,
    /// Definitions of normal signal nets.
    pub nets: Vec<Net>,
    /// Scan-chain definitions.
    pub scan_chains: (),
    /// Groups of components.
    pub groups: BTreeMap<String, Vec<Group>>,
    /// BEGINEXT blocks with non-standard extensions of the DEF format.
    pub extensions: (),
}

impl Default for DEF {
    fn default() -> Self {
        DEF {
            version: Some("5.8".into()),
            busbitchars: ('[', ']'),
            dividerchar: '/',
            design_name: None,
            technology: None,
            units: 0,
            history: Default::default(),
            property_definitions: Default::default(),
            die_area: Default::default(),
            rows: Default::default(),
            tracks: Default::default(),
            gcell_grid: Default::default(),
            vias: Default::default(),
            styles: Default::default(),
            nondefault_rules: Default::default(),
            regions: Default::default(),
            components: Default::default(),
            pins: Default::default(),
            pin_properties: Default::default(),
            blockages: Default::default(),
            slots: Default::default(),
            fills: Default::default(),
            special_nets: Default::default(),
            nets: Default::default(),
            scan_chains: Default::default(),
            groups: Default::default(),
            extensions: Default::default(),
        }
    }
}

/// Holds either the value of the SPACING argument or DESIGNRULEWIDTH argument of a geometrical
/// layer as used in the LAYER definition in PIN or OBS.
#[derive(Clone, Debug)]
pub enum SpacingOrDesignRuleWidth {
    /// Minimal allowed spacing between this shape and other shapes.
    MinSpacing(Coord),
    /// Effective design rule width.
    DesignRuleWidth(Coord),
}

/// Either a metal/via blockage or a component placement blockage..
#[derive(Clone, Debug)]
pub enum Blockage {
    /// Block component placement.
    PlacementBlockage(PlacementBlockage),
    /// Metal or via blockage.
    LayerBlockage(LayerBlockage),
}

/// Either a rectangle or a polygon.
#[derive(Clone, Debug)]
pub enum RectOrPolygon {
    /// Axis-aligned rectangle.
    Rect(db::Rect<Coord>),
    /// Polygon.
    Polygon(db::SimplePolygon<Coord>),
}

/// Define a region on a layer that is blocked from being used.
#[derive(Clone, Debug, Default)]
pub struct LayerBlockage {
    /// Layer of the blockage.
    pub layer: String,
    /// Block insertion of slots.
    pub slots: bool,
    /// Block insertion of metal fills.
    pub fills: bool,
    /// TBD
    pub pushdown: bool,
    /// Blockage does not concern power and ground nets, only signals.
    pub except_pg_net: bool,
    /// TBD
    pub component: Option<String>,
    /// TBD
    pub spacing: Option<Coord>,
    /// Either minimal allowed spacing or an effective width.
    pub spacing_or_designrule_width: Option<SpacingOrDesignRuleWidth>,
    /// Mask number.
    pub mask_num: Option<MaskNum>,
    /// Geometry of the blockage area.
    pub blockage_shapes: Vec<RectOrPolygon>,
}

/// Specify the type of a soft blockage.
#[derive(Clone, Debug)]
pub enum PlacementBlockageType {
    /// Initial placement shall not use the blocked area, but later stages can use it.
    Soft,
    /// Give a maximal usage density for the initial placement in this area.
    /// The density is given in percent and must have a value in the range `[0.0, ..., 100.0]`.
    Partial(f64),
}

/// Define a region where placement of components is not allowed.
#[derive(Clone, Debug, Default)]
pub struct PlacementBlockage {
    /// Type of the blockage (placement blockage or routing/metal/via blockage).
    pub blockage_type: Option<PlacementBlockageType>,
    /// Blockage was pushed down through hierarchy from a component on a higher level.
    pub pushdown: bool,
    /// Name of the associated component.
    pub component: Option<String>,
    /// Rectangles that cover the blocked region.
    pub rects: Vec<db::Rect<Coord>>,
}

/// Property definition used in DEF.
#[derive(Clone, Debug)]
pub struct DEFPropertyDefinition {
    /// DEF object type associated with this property.
    pub object_type: DEFPropertyObjectType,
    /// Data type of the property value.
    pub property_type: PropertyType,
    /// Optional min and max values.
    pub range: Option<(PropertyValue, PropertyValue)>,
    /// Default value of such a property.
    pub default_value: Option<PropertyValue>,
}

/// Type of parent object of the property.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DEFPropertyObjectType {
    /// Property belongs to a component.
    Component,
    /// Property belongs to a pin of a component.
    ComponentPin,
    /// Property belongs to the design.
    Design,
    /// Property belongs to a group.
    Group,
    /// Property belongs to a net.
    Net,
    /// Property belongs to a 'non-default-rule'.
    NonDefaultRule,
    /// Property belongs to a region.
    Region,
    /// Property belongs to a row.
    Row,
    /// Property belongs to a special net.
    SpecialNet,
}

impl FromStr for DEFPropertyObjectType {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "COMPONENT" => Ok(Self::Component),
            "COMPONENTPIN" => Ok(Self::ComponentPin),
            "DESIGN" => Ok(Self::Design),
            "GROUP" => Ok(Self::Group),
            "NET" => Ok(Self::Net),
            "NONDEFAULTRULE" => Ok(Self::NonDefaultRule),
            "REGION" => Ok(Self::Region),
            "ROW" => Ok(Self::Row),
            "SPECIALNET" => Ok(Self::SpecialNet),
            _ => Err(()),
        }
    }
}

impl fmt::Display for DEFPropertyObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Component => f.write_str("COMPONENT"),
            Self::ComponentPin => f.write_str("COMPONENTPIN"),
            Self::Design => f.write_str("DESIGN"),
            Self::Group => f.write_str("GROUP"),
            Self::Net => f.write_str("NET"),
            Self::NonDefaultRule => f.write_str("NONDEFAULTRULE"),
            Self::Region => f.write_str("REGION"),
            Self::Row => f.write_str("ROW"),
            Self::SpecialNet => f.write_str("SPECIALNET"),
        }
    }
}

/// Instantiation of a component in DEF.
#[derive(Clone, Debug, Default)]
pub struct Component {
    /// Name of the component instance.
    pub name: String,
    /// Name of the component template/model.
    pub model_name: String,
    /// Name of the electrically equivalent master.
    pub eeq_master: Option<String>,
    /// Tells where this component has been created.
    pub source: ComponentSource,
    /// Placement location of the component.
    /// `(location, orientation, is fixed)`
    pub position: Option<(db::Point<i32>, Orient, bool)>,
    /// Placement halo. Defines a placement blockage around the component.
    /// If `is_soft` is set, then the blockage does not need to be respected after the initial placement.
    /// `(is_soft, left, bottom, right, top)`.
    pub halo: Option<(bool, i32, i32, i32, i32)>,
    /// Routing halo. TODO.
    /// Structure is `(haloDist, minLayer, maxLayer)`.
    pub route_halo: Option<(i32, String, String)>,
    /// Weight of the component placement. Tells how costly a relocation of the component is.
    pub weight: u32,
    /// Name of the region where this component should be placed.
    pub region: Option<String>,
    /// Custom properties.
    pub properties: BTreeMap<String, PropertyValue>,
}

/// Source of a component.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ComponentSource {
    /// Component comes from the original netlist. This is the default value.
    Netlist,
    /// Physical component that connects only to power and ground nets.
    /// (Filler cells, well-taps, decoupling capacitors).
    Dist,
    /// Component generated by the user for some other reason.
    User,
    /// Component was inserted to meet timing constraints.
    Timing,
}

impl Default for ComponentSource {
    fn default() -> Self {
        Self::Netlist
    }
}

impl FromStr for ComponentSource {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "NETLIST" => Ok(Self::Netlist),
            "DIST" => Ok(Self::Dist),
            "USER" => Ok(Self::User),
            "TIMING" => Ok(Self::Timing),
            _ => Err(()),
        }
    }
}

impl fmt::Display for ComponentSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Netlist => f.write_str("NETLIST"),
            Self::Dist => f.write_str("DIST"),
            Self::User => f.write_str("USER"),
            Self::Timing => f.write_str("TIMING"),
        }
    }
}

/// Source of a net.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum NetSource {
    /// Physical component that connects only to power and ground nets.
    /// (Filler cells, well-taps, decoupling capacitors).
    Dist,
    /// Physical component that connects only to power and ground nets.
    /// (Filler cells, well-taps, decoupling capacitors).
    Netlist,
    /// Net belongs to a scan-chain.
    Test,
    /// Component was inserted to meet timing constraints.
    Timing,
    /// Component generated by the user for some other reason.
    User,
}

impl Default for NetSource {
    fn default() -> Self {
        Self::Netlist
    }
}

impl FromStr for NetSource {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "DIST" => Ok(Self::Dist),
            "NETLIST" => Ok(Self::Netlist),
            "TEST" => Ok(Self::Test),
            "TIMING" => Ok(Self::Timing),
            "USER" => Ok(Self::User),
            _ => Err(()),
        }
    }
}

impl fmt::Display for NetSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Dist => f.write_str("DIST"),
            Self::Netlist => f.write_str("NETLIST"),
            Self::Test => f.write_str("TEST"),
            Self::Timing => f.write_str("TIMING"),
            Self::User => f.write_str("USER"),
        }
    }
}

/// Routing pattern of a net.
/// Default: `Steiner`
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum NetPattern {
    /// Minimize skews in timing delays for clock nets.
    Balanced,
    /// Minimize net length.
    Steiner,
    /// Minimize delays for global nets.
    Trunk,
    /// For ECL designs.
    WiredLogic,
}

impl Default for NetPattern {
    fn default() -> Self {
        Self::Steiner
    }
}

impl FromStr for NetPattern {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "BALANCED" => Ok(Self::Balanced),
            "STEINER" => Ok(Self::Steiner),
            "TRUNK" => Ok(Self::Trunk),
            "WIREDLOGIC" => Ok(Self::WiredLogic),
            _ => Err(()),
        }
    }
}

impl fmt::Display for NetPattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Balanced => f.write_str("BALANCED"),
            Self::Steiner => f.write_str("STEINER"),
            Self::Trunk => f.write_str("TRUNK"),
            Self::WiredLogic => f.write_str("WIREDLOGIC"),
        }
    }
}

/// An internal pin or external pin of another component where a net can be attached.
#[derive(Clone, Debug)]
pub enum NetTerminal {
    /// Pin of a component instance.
    ComponentPin {
        // TODO: Use string interning here.
        /// Name of the component instance.
        component_name: String,
        /// Name of the pin.
        pin_name: String,
    },
    /// Name of an IO pin of the design.
    IoPin(String),
}

/// TBD
#[derive(Clone, Debug)]
pub struct Mustjoin {
    /// Name of the component.
    pub component_name: String,
    /// Name of a pin that belongs to the MUSTJOIN net.
    pub pin_name: String,
}

// /// A net either has a name or it is declared as MUSTJOIN.
// #[derive(Clone, Debug)]
// pub enum NameOrMustjoin {
//     /// Name of the net.
//     Name(String),
//     Mustjoin {
//         /// Name of the component.
//         component_name: String,
//         /// Name of a pin that belongs to the MUSTJOIN net.
//         pin_name: String,
//     }
// }

/// Wiring class. Tells whether a wiring can be changed by tools, manually or not at all.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum WiringClass {
    /// Route cannot be changed at all.
    COVER,
    /// Route cannot be changed by automatic tools, only by interactive commands.
    FIXED,
    /// Route can be changed by automatic tool.
    /// A net that is routed must also specify the layer name.
    ROUTED,
    /// Last wide segment is not shielded.
    NOSHIELD,
}

impl FromStr for WiringClass {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "COVER" => Ok(Self::COVER),
            "FIXED" => Ok(Self::FIXED),
            "ROUTED" => Ok(Self::ROUTED),
            "NOSHIELD" => Ok(Self::NOSHIELD),
            _ => Err(()),
        }
    }
}

impl fmt::Display for WiringClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::COVER => f.write_str("COVER"),
            Self::FIXED => f.write_str("FIXED"),
            Self::ROUTED => f.write_str("ROUTED"),
            Self::NOSHIELD => f.write_str("NOSHIELD"),
        }
    }
}

/// Represent an element of regular (non-special) wiring.
#[derive(Clone, Debug)]
pub enum RegularWiringElement {
    /// A point in the euclidean plane.
    Point {
        /// x-coordinate
        x: Coord,
        /// y-coordinate
        y: Coord,
        /// Optional extension.
        ext_value: Option<Coord>,
    },
    /// Via.
    Via {
        /// Name of the via.
        via_name: String,
    },
    /// Mask number.
    MaskNum(u32),
    /// Via-mask number.
    ViaMaskNum(ViaMaskNum),
    /// Virtual wiring element. A point in the euclidean plane.
    Virtual {
        /// x-coordinate
        x: Coord,
        /// y-coordinate
        y: Coord,
    },
    /// An axis aligned rectangle. TODO
    Rect(),
}

/// 'Vertex' in the routing path.
#[derive(Clone, Debug)]
pub enum RoutingPoint {
    /// A simple vertex of a path.
    Point {
        /// Location of the path vertex.
        point: db::Point<Coord>,
        /// Extension of the wire past the endpoint. Default is half the wire width.
        ext_value: Option<Coord>,
        /// Mask-number of the following path segment.
        mask_num: Option<MaskNum>,
    },
    /// A via, placed at the location of the last path vertex.
    Via {
        /// Name of the via to be used.
        via_name: String,
        /// Rotation of the via.
        orient: Option<Orient>,
        /// Mask-number of the via geometries.
        via_mask_num: Option<ViaMaskNum>,
    },
    /// A rectangular shape with absolute coordinates.
    Rect {
        /// Rectangle. Absolute coordinates.
        /// DEF stores coordinates relative to the last path point, but here the coordinates are already resolved.
        rect: db::Rect<Coord>,
        /// Mask-number of the rectangle.
        mask_num: Option<MaskNum>,
    },
    /// A 'virtual' path vertex. The path segment leading to the virtual vertex is not materialized.
    /// This is equal to ending the path at the last point and starting a new path at the virtual vertex, hence
    /// allows to create discontinuous paths.
    Virtual(db::Point<Coord>),
}

/// Wiring statement which makes up the [`RegularWiring`].
#[derive(Clone, Debug)]
pub struct RegularWiringStatement {
    /// Layer where the wire starts.
    pub start_layer_name: String,
    /// Name of the taper rule to be used.
    pub taper_rule: Option<String>,
    /// Routing style number.
    pub style_num: u32,
    // TODO: Check this.
    /// Routing path.
    pub routing_points: Vec<RoutingPoint>,
}

/// Representation of regular wiring.
#[derive(Clone, Debug)]
pub struct RegularWiring {
    /// Wiring class.
    pub class: WiringClass,
    /// The wiring segments which make this wiring.
    pub wiring: Vec<RegularWiringStatement>,
}

/// Definition of a net and possibly its routes.
#[derive(Clone, Debug)]
pub struct Net {
    /// Name of the net.
    /// Must be generated for MUSTJOIN nets.
    /// 'MUSTJOIN' is an invalid net name.
    pub name: Option<String>,
    /// Net name is generated for MUSTJOIN nets.
    pub mustjoin: Option<Mustjoin>,
    /// Terminals connected to the net.
    pub terminals: Vec<NetTerminal>,
    /// Names of special nets that are used to shield this net.
    /// The shield nets must be defined earlier in 'SPECIALNETS'.
    pub shield_nets: Vec<String>,
    vpin: BTreeMap<String, ()>,
    subnets: BTreeMap<String, ()>,
    /// Crosstalk class number.
    /// Default is `0` which will not be written to DEF.
    /// Should be a value from 0 to 200.
    pub xtalk_class: u16,
    /// Use another width rule than the default rule defined in the LEF WIDTH statement for the routing layer.
    pub non_default_rule: Option<String>,
    /// Specify the physical wiring.
    pub regular_wiring: Vec<RegularWiring>,
    /// Source from where the net was created.
    pub source: NetSource,
    /// Fixed bump: TBD
    pub fixed_bump: bool,
    /// Frequency of the net.
    /// Used as a hint for the router.
    pub frequency: Option<f64>,
    /// If this net results from partitioning another net, then
    /// this refers to the original net.
    pub original: Option<String>,
    /// Usage type of the net.
    pub net_use: DEFSignalUse,
    /// Desired routing pattern for the net.
    pub pattern: NetPattern,
    /// Estimated wire capacitance of this net.
    pub est_cap: Option<f64>,
    /// Weight of the net. Nets with high weight should be tried to keep short by routing tools.
    /// Default = 1.
    pub weight: u32,
    /// Additional properties.
    pub properties: BTreeMap<String, PropertyValue>,
}

/// Custom implementation of default because `weight` deviates from the default of `u32`.
impl Default for Net {
    fn default() -> Self {
        Net {
            name: Default::default(),
            mustjoin: Default::default(),
            terminals: Default::default(),
            shield_nets: Default::default(),
            vpin: Default::default(),
            subnets: Default::default(),
            xtalk_class: Default::default(),
            non_default_rule: Default::default(),
            regular_wiring: Default::default(),
            source: Default::default(),
            fixed_bump: Default::default(),
            frequency: Default::default(),
            original: Default::default(),
            net_use: Default::default(),
            pattern: Default::default(),
            est_cap: Default::default(),
            weight: 1,
            properties: Default::default(),
        }
    }
}

/// Definiton of a special net and possibly its routes.
#[derive(Clone, Debug, Default)]
pub struct SpecialNet {}

/// External pin definition in DEF.
/// Associates an external pin name with the internal net name.
#[derive(Clone, Debug, Default)]
pub struct Pin {
    /// Name of the external pin.
    pub pin_name: String,
    /// Name of the internal net.
    pub net_name: String,
    /// Mark the pin as 'special'. Special pins are to be routed with a special router with special wiring.
    pub special: bool,
    /// Signal direction of the pin. Typically this is specified in the timing library, not in DEF.
    pub direction: Option<PinDirection>,
    /// TBD
    pub net_expr: Option<String>,
    /// Net name where this pin should be connected if it is tied HIGH (constant logical 1).
    pub supply_sensitivity: Option<String>,
    /// Net name where this pin should be connected if it is tied LOW (constant logical 0).
    pub ground_sensitivity: Option<String>,
    /// Type of the signal for this pin. Default is 'SIGNAL'.
    pub signal_use: DEFSignalUse,

    /// Anntenna rules. TODO
    pub antenna_rules: (),

    /// Definitions of physical shapes of the pin.
    pub ports: Vec<PinPort>,
}

/// Definition of the port of a pin.
#[derive(Clone, Debug, Default)]
pub struct PinPort {
    /// Shapes of this port.
    pub port_statements: Vec<PinPortStatement>,
}

/// Definition of the shapes of a pin port.
#[derive(Clone, Debug)]
pub enum PinPortStatement {
    /// Rectangular shape of the pin port.
    Layer {
        /// Name of the layer.
        layer_name: String,
        /// Mask number.
        mask_num: Option<MaskNum>,
        /// SPACING: minimum spacing between other routing shapes an this pin.
        /// DESIGNRULEWIDTH: effective width of this pin used for calculating spacing.
        spacing_or_width: Option<SpacingOrDesignRuleWidth>,
        /// Rectangular shape on this port.
        rect: db::Rect<Coord>,
    },
    /// Polygon shape of the pin port.
    Polygon {
        /// Name of the layer.
        layer_name: String,
        /// Mask number.
        mask_num: Option<MaskNum>,
        /// SPACING: minimum spacing between other routing shapes an this pin.
        /// DESIGNRULEWIDTH: effective width of this pin used for calculating spacing.
        spacing_or_width: Option<SpacingOrDesignRuleWidth>,
        /// Polygon shape on this port.
        polygon: db::SimplePolygon<Coord>,
    },
    /// Via which is part of the pin port.
    Via {
        /// Name of the via.
        via_name: String,
        /// Mask number.
        mask_num: Option<ViaMaskNum>,
        /// Location of the via.
        location: db::Point<Coord>,
    },
}

/// Signal usage type of a pin in DEF.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DEFSignalUse {
    /// Digital data signal.
    SIGNAL,
    /// Supply net.
    POWER,
    /// Ground net.
    GROUND,
    /// Clock signal.
    CLOCK,
    /// Tie-signal.
    TIEOFF,
    /// Analog signal.
    ANALOG,
    /// Scan chain signal.
    SCAN,
    /// Reset signal.
    RESET,
}

impl Default for DEFSignalUse {
    fn default() -> Self {
        Self::SIGNAL
    }
}

impl FromStr for DEFSignalUse {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "SIGNAL" => Ok(Self::SIGNAL),
            "POWER" => Ok(Self::POWER),
            "GROUND" => Ok(Self::GROUND),
            "CLOCK" => Ok(Self::CLOCK),
            "TIEOFF" => Ok(Self::TIEOFF),
            "ANALOG" => Ok(Self::ANALOG),
            "SCAN" => Ok(Self::SCAN),
            "RESET" => Ok(Self::RESET),
            _ => Err(()),
        }
    }
}

impl fmt::Display for DEFSignalUse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SIGNAL => f.write_str("SIGNAL"),
            Self::POWER => f.write_str("POWER"),
            Self::GROUND => f.write_str("GROUND"),
            Self::CLOCK => f.write_str("CLOCK"),
            Self::TIEOFF => f.write_str("TIEOFF"),
            Self::ANALOG => f.write_str("ANALOG"),
            Self::SCAN => f.write_str("SCAN"),
            Self::RESET => f.write_str("RESET"),
        }
    }
}

/// Mask number of a via for multi patterning.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ViaMaskNum {
    /// Mask number of top layer.
    pub top_mask_num: MaskNum,
    /// Mask number of cut layer.
    pub cut_mask_num: MaskNum,
    /// Mask number of bottom layer.
    pub bottom_mask_num: MaskNum,
}

impl FromStr for ViaMaskNum {
    type Err = LefDefParseError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if input.len() != 3 {
            Err(LefDefParseError::InvalidLiteral(input.to_string()))
        } else {
            Ok(Self {
                top_mask_num: MaskNum::from_str_radix(&input[0..1], 16)?,
                cut_mask_num: MaskNum::from_str_radix(&input[1..2], 16)?,
                bottom_mask_num: MaskNum::from_str_radix(&input[2..3], 16)?,
            })
        }
    }
}

impl fmt::Display for ViaMaskNum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:#0x}{:#0x}{:#0x}",
            self.top_mask_num, self.cut_mask_num, self.bottom_mask_num
        )
    }
}

/// Defines a physical area that can be used to place components or groups.
#[derive(Clone, Debug, Default)]
pub struct Region {
    /// Physical region defined as a set of rectangles.
    pub regions: Vec<db::Rect<Coord>>,
    /// Type of the region constraint.
    /// Default: Assigned cells are placed in the region. Other cells can be placed in the region as well.
    pub region_type: Option<RegionType>,
    /// Properties of the region.
    pub properties: (),
}

/// Type of the region. A region defines a physical are where components should be placed.
/// Fence regions force components to be placed inside, guides are not hard constraints.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RegionType {
    /// Hard constraint. Only components assigned to this region are allowed to be placed here.
    Fence,
    /// Soft constraint (can be violated if necessary).
    Guide,
}

impl FromStr for RegionType {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "FENCE" => Ok(Self::Fence),
            "GUIDE" => Ok(Self::Guide),
            _ => Err(()),
        }
    }
}

impl fmt::Display for RegionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Fence => f.write_str("FENCE"),
            Self::Guide => f.write_str("GUIDE"),
        }
    }
}

/// Define a group of components.
/// Optionally restrict the component locations to a region.
#[derive(Clone, Debug, Default)]
pub struct Group {
    /// Names or name patterns of the components that belong to this group.
    pub component_names: Vec<String>,
    /// Name of the region in which the group must lie.
    /// Region restrictions defined by the component overwrite the restrictions defined by its group.
    pub region_name: Option<String>,
    /// User defined properties.
    pub properties: BTreeMap<String, PropertyValue>,
}

/// Definition of a standard-cell row.
#[derive(Clone, Debug, Default)]
pub struct Row {
    /// Name of the site where this row is located.
    pub site_name: String,
    /// Origin of the row.
    pub orig: (Coord, Coord),
    /// Orientation of all sites in the row.
    pub site_orient: Orient,
    /// Specify the repetition pattern of the referenced site.
    pub step_pattern: RowStepPattern,
    /// Properties associated with the row.
    pub properties: BTreeMap<String, PropertyValue>,
}

/// Repetition pattern for rows.
#[derive(Clone, Debug)]
pub struct RowStepPattern {
    /// Number of repetitions in x-direction. At least one of `num_x` or `num_y` must be `1`.
    pub num_x: u32,
    /// Number of repetitions in y-direction. At least one of `num_x` or `num_y` must be `1`.
    pub num_y: u32,
    /// Step size for x and y direction. By default
    /// the step size equals the size of the referenced site
    /// such that sites are arranged without overlap nor gap between.
    pub step: Option<(Coord, Coord)>,
}

impl Default for RowStepPattern {
    fn default() -> Self {
        Self {
            num_x: 1,
            num_y: 1,
            step: None,
        }
    }
}

/// Definition routing tracks as a grid of equally spaced lines.
#[derive(Clone, Debug, Default)]
pub struct Tracks {
    /// Direction of the track. Can be horizontal when 'Y' is defined in DEF (true) or vertical with 'X' in DEF (false).
    pub is_horizontal: bool,
    /// Distance of the track line to the origin.
    /// For horizontal tracks this is the vertical offset (y coordinate),
    /// for vertical tracks this is the horizontal offset (y coordinate).
    pub start: Coord,
    /// Number of tracks for the grid. Must be larger than 0.
    pub num_tracks: u32,
    /// Spacing between tracks.
    pub step: Coord,
    /// An optional tuple `( mask number, SAMEMASK )`.
    /// mask number: Mask of the first track as used for double or triple patterning.
    /// Usually the mask is cycled for all subsequent tracks.
    /// SAMEMASK: Use the same mask number for all tracks.
    pub mask: Option<(MaskNum, bool)>,
    /// Routing layers to be used for this track. Possibly more than one.
    pub layers: Vec<String>,
}

/// Definition of via geometries or rules to generate a via.
#[derive(Clone, Debug)]
pub enum ViaDefinition {
    /// Explicit definition of the via by a set of geometrical shapes.
    ViaGeometry(Vec<ViaGeometry>),
    /// Implicit definition by design rules for the via.
    ViaRule,
}

/// Geometrical shapes of a via.
#[derive(Clone, Debug)]
pub struct ViaGeometry {
    /// Name of the
    pub layer: String,
    /// Mask number.
    pub mask_num: Option<MaskNum>,
    /// Rectangle or polygon shape.
    pub shape: RectOrPolygon,
}

/// Rule for via creation.
#[derive(Clone, Debug)]
pub struct ViaRule {
    /// Width and height of the via cut.
    pub cut_size: (Coord, Coord),
    /// Bottom metal layer of the via.
    pub bot_metal_layer: String,
    /// Layer of the via cut.
    pub cut_layer: String,
    /// Top metal layer of the via.
    pub top_metal_layer: String,
    /// Spacing in x and y directions.
    pub cut_spacing: (Coord, Coord),
    /// Via enclosure: bottom x, bottom y, top x, top y.
    pub enclosure: (Coord, Coord, Coord, Coord),
    num_cut_rows: u32,
    num_cut_cols: u32,
    origin: db::Point<Coord>,
    offset: (),
    cut_pattern: (),
}