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

/// Implement the design rule traits from `libreda-db` for LEF.
/// This allows standardized read access to design-rules and technology data.
///
/// [`LEFDesignRuleAdapter`] creates the mapping between the layers defined in a layout and the layers defined in a LEF file
/// and then provides access to the LEF data via the technology traits.
use log;

use crate::common::Orient;
use crate::lef_ast;
use crate::lef_ast::{Layer, RoutingDirection, TechnologyLef, LEF};
use db::traits::*;
use libreda_db::prelude as db;
use libreda_db::technology::layerstack;
use libreda_db::technology::layerstack::{RoutingLayer, RoutingLayerStack, RoutingLayerType};
use libreda_db::technology::rules;
use libreda_db::technology::rules::RuleBase;
use num_traits::{FromPrimitive, ToPrimitive};
use std::collections::HashMap;
use std::marker::PhantomData;

/// Provides standardized read access to the design-rules defined in a LEF structure.
pub struct LEFDesignRuleAdapter<'a, L: db::LayoutBase> {
    /// Underlying LEF data.
    lef: &'a LEF,
    /// Data-base units per micron.
    dbu: f64,
    /// Mapping from layer IDs to actual LEF layer data.
    layer_mapping: HashMap<L::LayerId, &'a lef_ast::Layer>,
    /// Layers sorted by the processing order: Starts with layers close to the substrate, ends with top level metal layers.
    layer_stack: Vec<(L::LayerId, &'a lef_ast::Layer)>,
    ty: PhantomData<L>,
}

impl<'a, L> LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: ToPrimitive, // Need to be able to cast a float into Coord.
{
    /// Convert from a distance in data-base units into a LEF distance (f64).
    fn db_distance_to_lef(&self, db_distance: L::Coord) -> f64 {
        let dbu = self.dbu;

        db_distance
            .to_f64()
            .expect("Conversion from LEF distance unit to database distance unit failed.")
            / dbu
    }
}

impl<'a, L> LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: FromPrimitive, // Need to be able to cast a float into Coord.
{
    /// Convert from a LEF distance (f64) into the correct unit used by the layout.
    fn lef_distance_to_db(&self, lef_distance: f64) -> L::Coord {
        let dbu = self.dbu;

        L::Coord::from_f64(lef_distance * dbu)
            .expect("Conversion from LEF distance unit to database distance unit failed.")
    }
}

impl<'a, L> LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: FromPrimitive + ToPrimitive, // Need to be able to cast a float into Coord.
{
    /// Create a new design rule adapter for a LEF data structure.
    /// Derives the mapping from layer IDs and LEF layers based on the layer names.
    pub fn new(lef: &'a LEF, layout: &L) -> Self {
        let dbu = layout
            .dbu()
            .to_f64()
            .expect("failed to convert data-base unit from to f64");
        Self::new_from_layer_mapping(lef, &Self::extract_layer_mapping_from_layout(layout), dbu)
    }

    /// Create a new design rule adapter for a LEF data structure
    /// with a custom mapping between layer names and layer IDs.
    pub fn new_from_layer_mapping(
        lef: &'a LEF,
        layer_ids_by_name: &HashMap<String, L::LayerId>,
        dbu: f64,
    ) -> Self {
        assert!(
            dbu > 0.0,
            "'data-base units per micron' must be larger than 0"
        );

        let mut new = Self {
            lef,
            dbu,
            layer_mapping: Default::default(),
            layer_stack: Default::default(),
            ty: Default::default(),
        };

        new.create_layer_mapping(layer_ids_by_name);

        new
    }

    /// Find the mapping from layer names to layer IDs.
    fn extract_layer_mapping_from_layout(layout: &L) -> HashMap<String, L::LayerId> {
        layout
            .each_layer()
            .filter_map(|layer_id| {
                let layer_name = layout
                    .layer_info(&layer_id)
                    .name
                    .as_ref()
                    .map(|n| n.to_string());
                layer_name.map(|name| (name, layer_id))
            })
            .collect()
    }

    /// Initialize the mapping: layer ID -> LEF layer structure.
    fn create_layer_mapping(&mut self, layer_ids_by_name: &HashMap<String, L::LayerId>) {
        // Create look-up table: Layer name -> LEF layer
        let lef_layers_by_name = self
            .lef
            .technology
            .layers
            .iter()
            .map(|layer| (layer.name(), layer));

        // Create look-up table: Layer ID -> LEF layer
        let lef_layers_by_layer_id: Vec<_> = lef_layers_by_name
            .filter_map(|(layer_name, layer)| {
                let layer_id = layer_ids_by_name.get(layer_name);
                layer_id.map(|id| (id.clone(), layer))
            })
            .collect();

        self.layer_mapping = lef_layers_by_layer_id.iter().cloned().collect();

        self.layer_stack = lef_layers_by_layer_id;
    }
}

impl<'a, L: db::LayoutBase> layerstack::RoutingLayerStack for LEFDesignRuleAdapter<'a, L> {
    fn layer_stack(&self) -> Vec<RoutingLayer<Self::LayerId>> {
        self.layer_stack
            .iter()
            // Take routing and cut layers only.
            .filter_map(|(id, layer)| match layer {
                Layer::MasterSlice(_) => None,
                Layer::Cut(_) => Some(RoutingLayer::new(id.clone(), RoutingLayerType::Cut)),
                Layer::Routing(_) => Some(RoutingLayer::new(id.clone(), RoutingLayerType::Routing)),
            })
            .collect()
    }
}

impl<'a, L: db::LayoutBase> rules::RuleBase for LEFDesignRuleAdapter<'a, L> {
    type LayerId = L::LayerId;
}

impl<'a, L: db::LayoutBase> rules::DistanceRuleBase for LEFDesignRuleAdapter<'a, L> {
    type Distance = L::Coord;
    type Area = L::Coord;
}

impl<'a, L: db::LayoutBase> rules::MinimumSpacing for LEFDesignRuleAdapter<'a, L>
where
    L::Coord: ToPrimitive + FromPrimitive,
{
    fn min_spacing_absolute(&self, layer_id: &Self::LayerId) -> Option<Self::Distance> {
        self.layer_mapping
            .get(layer_id)
            .and_then(|layer| match layer {
                Layer::MasterSlice(_) => unimplemented!("Min spacing for MASTERSLICE layers."),
                Layer::Cut(_) => {
                    // log::warn!("Not implemented: minimum spacing for CUT layers.");
                    // TODO: minimum spacing for CUT layers
                    None
                }
                Layer::Routing(routing_layer) => {
                    // Get spacing based on routing_layer.spacing_table or routing_layer.spacing.
                    get_absolute_min_spacing_of_routing_layer(routing_layer)
                }
            })
            .map(|d| self.lef_distance_to_db(d))
    }

    fn min_spacing(
        &self,
        layer_id: &Self::LayerId,
        run_length: Self::Distance,
        width: Self::Distance,
    ) -> Option<Self::Distance> {
        let run_length = self.db_distance_to_lef(run_length);
        let width = self.db_distance_to_lef(width);

        self.layer_mapping
            .get(layer_id)
            .and_then(|layer| match layer {
                Layer::MasterSlice(_) => unimplemented!("Min spacing for MASTERSLICE layers."),
                Layer::Cut(_) => {
                    // TODO: unimplemented!("Min spacing for CUT layers.");
                    None
                }
                Layer::Routing(routing_layer) => {
                    // Get spacing based on routing_layer.spacing_table or routing_layer.spacing.
                    get_min_spacing_of_routing_layer(routing_layer, run_length, width)
                }
            })
            .map(|d| self.lef_distance_to_db(d))
    }
}

impl<'a, L: db::LayoutBase> rules::PreferredRoutingDirection for LEFDesignRuleAdapter<'a, L>
where
    L::Coord: ToPrimitive + FromPrimitive,
{
    fn preferred_routing_direction(&self, layer_id: &Self::LayerId) -> Option<db::Orientation2D> {
        self.layer_mapping
            .get(layer_id) // Find LEF layer.
            .and_then(|layer| match layer {
                Layer::Routing(routing_layer) => {
                    match routing_layer.direction {
                        RoutingDirection::Vertical => Some(db::Orientation2D::Vertical),
                        RoutingDirection::Horizontal => Some(db::Orientation2D::Horizontal),
                        RoutingDirection::Diag45 => {
                            // TODO
                            None
                        }
                        RoutingDirection::Diag135 => {
                            // TODO
                            None
                        }
                    }
                }
                _ => None, // No preferred routing direction for other layer types.
            })
    }
}

impl<'a, L> rules::RoutingRules for LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: ToPrimitive + FromPrimitive,
{
    fn default_pitch(&self, layer_id: &Self::LayerId) -> Option<(Self::Distance, Self::Distance)> {
        self.layer_mapping
            .get(layer_id)
            .and_then(|layer| match layer {
                Layer::MasterSlice(_) => unimplemented!("Default pitch for MASTERSLICE layers."),
                Layer::Cut(_) => None, // TODO
                Layer::Routing(routing_layer) => Some(routing_layer.pitch),
            })
            .map(|(pitch_x, pitch_y)| {
                (
                    self.lef_distance_to_db(pitch_x),
                    self.lef_distance_to_db(pitch_y),
                )
            })
    }
}

/// Get the minimal spacing on the given layer.
/// Return `None` if there's no spacing rule defined.
/// TODO: Currently only SPACINGTABLEs are considered. Also support SPACING statements.
fn get_absolute_min_spacing_of_routing_layer(routing_layer: &lef_ast::RoutingLayer) -> Option<f64> {
    if let Some(spacing_table) = &routing_layer.spacing_table {
        spacing_table
            .spacings
            .first()
            .and_then(|spacings| spacings.first())
            .copied()
            .or(Some(0.))
    } else {
        // Derive spacing from SPACING statements.
        routing_layer
            .spacing
            .iter()
            .map(|spacing_rule| spacing_rule.min_spacing)
            // Find minimum.
            .reduce(|min, x| if x < min { x } else { min })
    }
}

/// Get the minimal spacing on the given layer.
/// Return `None` if there's no spacing rule defined.
/// TODO: Currently only SPACINGTABLEs are considered. Also support SPACING statements.
fn get_min_spacing_of_routing_layer(
    routing_layer: &lef_ast::RoutingLayer,
    parallel_runlength: f64,
    width: f64,
) -> Option<f64> {
    if let Some(spacing_table) = &routing_layer.spacing_table {
        // Find correct row for the given width.
        let row = spacing_table
            .spacings
            .iter()
            .zip(&spacing_table.widths)
            .filter(|(row, &w)| w <= width)
            .last()
            .map(|(row, _)| row);
        row.and_then(|row| {
            // Find correct value based on the runlength.
            row.iter()
                .zip(&spacing_table.parallel_run_lengths)
                .filter(|(spacing, &run_length)| run_length <= parallel_runlength)
                .last()
                .map(|(&spacing, _)| spacing)
        })
    } else {
        // TODO: Derive spacing from SPACING statements.
        get_absolute_min_spacing_of_routing_layer(routing_layer)
    }
}

impl<'a, L> rules::MinimumWidth for LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: FromPrimitive,
{
    fn min_width(
        &self,
        layer_id: &Self::LayerId,
        shape_length: Option<Self::Distance>,
    ) -> Option<Self::Distance> {
        self.layer_mapping
            .get(layer_id)
            .and_then(|layer| match layer {
                Layer::MasterSlice(_) => {
                    unimplemented!("Minimum width for LEF 'masterslice' layers is not implemented.")
                }
                Layer::Cut(_) => {
                    None
                    // TODO unimplemented!("Minimum width for LEF 'cut' layers is not implemented.")
                }
                Layer::Routing(routing_layer) => routing_layer.min_width,
            })
            .map(|d| self.lef_distance_to_db(d))
    }
}

impl<'a, L> rules::DefaultWidth for LEFDesignRuleAdapter<'a, L>
where
    L: db::LayoutBase,
    L::Coord: FromPrimitive,
{
    fn default_width(
        &self,
        layer_id: &Self::LayerId,
        shape_length: Option<Self::Distance>,
    ) -> Option<Self::Distance> {
        self.layer_mapping
            .get(layer_id)
            .and_then(|layer| match layer {
                Layer::MasterSlice(_) => {
                    unimplemented!("Default width for LEF 'masterslice' layers is not implemented.")
                }
                Layer::Cut(_) => {
                    None
                    // TODO: unimplemented!("Default width for LEF 'cut' layers is not implemented.")
                }
                Layer::Routing(routing_layer) => Some(routing_layer.width),
            })
            .map(|d| self.lef_distance_to_db(d))
    }
}

#[cfg(test)]
mod tests {
    use crate::lef_parser::read_lef_chars;
    use crate::lef_tech_adapter::LEFDesignRuleAdapter;
    use db::technology::rules::*;
    use db::traits::*;
    use libreda_db::prelude as db;

    const LEF_DATA: &'static str = r#"
VERSION 5.5 ;
NAMESCASESENSITIVE ON ;
BUSBITCHARS "[]" ;
DIVIDERCHAR "/" ;

PROPERTYDEFINITIONS
  LAYER contactResistance REAL ;
END PROPERTYDEFINITIONS

UNITS
  DATABASE MICRONS 1000 ;
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 ;
  MINWIDTH 0.05 ;
  SPACING 0.065 ;
  RESISTANCE RPERSQ 0.38 ;

  SPACINGTABLE
    PARALLELRUNLENGTH   0.0  1.0
    WIDTH 0.0           0.1  0.3
    WIDTH 0.5           0.4  0.5
  ;

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.07 ;
    SPACING 0.075 ;
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.065 ;
  SAMENET metal2 metal2 0.07 ;
  SAMENET metal6 metal6 0.14 ;
  SAMENET metal5 metal5 0.14 ;
  SAMENET metal4 metal4 0.14 ;
  SAMENET metal3 metal3 0.07 ;
  SAMENET metal7 metal7 0.4 ;
  SAMENET metal8 metal8 0.4 ;
  SAMENET metal9 metal9 0.8 ;
  SAMENET metal10 metal10 0.8 ;
END SPACING

END LIBRARY

    "#;

    fn create_empty_layout() -> (db::Chip, Vec<<db::Chip as db::LayoutIds>::LayerId>) {
        // Create an empty layout with some layers which match the LEF layer names.
        let mut layout = db::Chip::new();
        layout.set_dbu(1000);

        let layer1 = layout.create_layer(1, 0);
        layout.set_layer_name(&layer1, Some("metal1".into()));

        let layer2 = layout.create_layer(2, 0);
        layout.set_layer_name(&layer2, Some("metal2".into()));

        (layout, vec![layer1, layer2])
    }

    #[test]
    fn test_lef_rule_adapter_pitch() {
        let lef = read_lef_chars(LEF_DATA.chars()).expect("Failed to parse LEF");

        let (layout, layers) = create_empty_layout();
        let layer1 = &layers[0];

        let rules = LEFDesignRuleAdapter::new(&lef, &layout);

        dbg!(rules.layer_mapping[layer1]);

        // Try to fetch design rules.
        assert_eq!(rules.default_pitch(layer1), Some((190, 190)));
        assert_eq!(rules.default_pitch_preferred_direction(layer1), Some(190));
    }

    #[test]
    fn test_lef_rule_adapter_min_width() {
        let lef = read_lef_chars(LEF_DATA.chars()).expect("Failed to parse LEF");

        let (layout, layers) = create_empty_layout();
        let layer1 = &layers[0];

        let rules = LEFDesignRuleAdapter::new(&lef, &layout);

        dbg!(rules.layer_mapping[layer1]);

        // Try to fetch design rules.
        assert_eq!(rules.min_width(layer1, None), Some(50));
    }

    #[test]
    fn test_lef_rule_adapter_default_width() {
        let lef = read_lef_chars(LEF_DATA.chars()).expect("Failed to parse LEF");

        let (layout, layers) = create_empty_layout();
        let layer1 = &layers[0];

        let rules = LEFDesignRuleAdapter::new(&lef, &layout);

        dbg!(rules.layer_mapping[layer1]);

        // Try to fetch design rules.
        assert_eq!(rules.default_width(layer1, None), Some(65));
    }

    #[test]
    fn test_lef_rule_adapter_spacing_table() {
        let lef = read_lef_chars(LEF_DATA.chars()).expect("Failed to parse LEF");

        let (layout, layers) = create_empty_layout();
        let layer1 = &layers[0];
        let layer2 = &layers[1];

        let rules = LEFDesignRuleAdapter::new(&lef, &layout);

        // Try to fetch design rules.

        assert_eq!(rules.min_spacing_absolute(layer1), Some(100));

        assert_eq!(rules.min_spacing(layer1, 0, 0), Some(100));

        assert_eq!(rules.min_spacing(layer1, 999, 0), Some(100));
        assert_eq!(rules.min_spacing(layer1, 1000, 0), Some(300));

        assert_eq!(rules.min_spacing(layer1, 0, 499), Some(100));
        assert_eq!(rules.min_spacing(&layer1, 0, 500), Some(400));
    }

    #[test]
    fn test_lef_rule_adapter_min_spacing() {
        let lef = read_lef_chars(LEF_DATA.chars()).expect("Failed to parse LEF");

        let (layout, layers) = create_empty_layout();
        let layer1 = &layers[0];
        let layer2 = &layers[1];

        let rules = LEFDesignRuleAdapter::new(&lef, &layout);

        dbg!(rules.layer_mapping[layer2]);

        // Spacing rules on metal2 without SPACINGTABLE
        assert_eq!(rules.min_spacing(layer2, 0, 0), Some(75));
        assert_eq!(rules.min_spacing_absolute(layer2), Some(75));
    }
}