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

//! Interface definitions for cell delay look-up as it is provided for example by Liberty libraries.

use uom::si::{
    capacitance::farad,
    f64::{Capacitance, Time},
    time::second,
};

use super::liberty_util::*;
use crate::traits::timing_library::{EdgePolarity, TimingLibrary};
use itertools::Itertools;
use liberty_io::{CapacitiveLoadUnit, Group, TimeUnit};
use std::{collections::HashMap, str::FromStr};

/// Lookup table which maps a `(capacitance, time)`-pair to a time.
type SlewLut = Interp<Time, Capacitance, Time>;
/// Lookup table which maps a `(capacitance, time)`-pair to a time.
type DelayLut = Interp<Time, Capacitance, Time>;
/// Lookup table which maps the slew of the constrained and related signal
/// to a constraint (e.g. setup or hold time).
type ConstraintLut = Interp<Time, Time, Time>;

/// Delay tables.
#[derive(Default, Clone, Debug)]
pub struct DelayArc {
    /// The delay is valid for rising edges of the related signal.
    pub rising_edge: bool,
    /// The delay is valid for falling edges of the related signal.
    pub falling_edge: bool,
    /// Lookup-table for rise transition times.
    pub rise_transition: Option<SlewLut>,
    /// Lookup-table for fall transition times.
    pub fall_transition: Option<SlewLut>,
    /// Lookup-table for rise times.
    pub cell_rise: Option<DelayLut>,
    /// Lookup-table for fall times.
    pub cell_fall: Option<DelayLut>,
}

/// Setup and hold constraints.
#[derive(Default, Clone, Debug)]
pub struct ConstraintArc {
    /// Constraint for rising edges of the constrained signal.
    pub rise_constraint: Option<ConstraintLut>,
    /// Constraint for falling edges of the constrained signal.
    pub fall_constraint: Option<ConstraintLut>,
}

/// Timing library based on a 'liberty' library.
#[derive(Clone, Debug)]
pub struct LibertyTimingLibrary<'a> {
    /// Liberty library group.
    pub(crate) lib: &'a Group,
    table_templates: HashMap<String, LuTableTemplate>,
    time_unit: Time,
    capacitive_load_unit: Capacitance,
    /// Mapping from `(cell_name, pin_name, related_pin_name)` to the delay arc structure.
    pub(crate) cells: HashMap<String, Cell>,
}

/// Timing model of a cell.
#[derive(Clone, Default, Debug)]
pub(crate) struct Cell {
    /// Timing information of pins.
    pub(crate) pins: HashMap<String, Pin>,
}

/// Timing information of an output pin.
#[derive(Default, Debug, Clone)]
pub struct Pin {
    /// Input capacitance of the pin.
    pub(crate) capacitance: Capacitance,
    /// Mapping from related pin name to the delay/slew values.
    pub(crate) delay_arcs: HashMap<String, DelayArc>,
    /// Hold constraints relative to rising clock edges.
    /// Mapping from related pin name to the constraint values.
    pub(crate) hold_rising: HashMap<String, ConstraintArc>,
    /// Hold constraints relative to falling clock edges.
    /// Mapping from related pin name to the constraint values.
    pub(crate) hold_falling: HashMap<String, ConstraintArc>,
    /// Setup constraints relative to rising clock edges.
    /// Mapping from related pin name to the constraint values.
    pub(crate) setup_rising: HashMap<String, ConstraintArc>,
    /// Setup constraints relative to falling clock edges.
    /// Mapping from related pin name to the constraint values.
    pub(crate) setup_falling: HashMap<String, ConstraintArc>,
}

/// Template for lookup-tables.
#[derive(Clone, Debug)]
struct LuTableTemplate {
    /// Name of the first variable.
    var1: String,
    /// Name of the second variable (if defined).
    var2: Option<String>,
    /// Dimension of the table.
    size: (usize, usize),
}

/// Read all lookup table templates in this library group and
/// put them into a `HashMap` indexed by their name.
fn read_template_tables(lib: &Group) -> Result<HashMap<String, LuTableTemplate>, LibertyErr> {
    assert_eq!(
        lib.name, "library",
        "Expected a library group, got '{}'.",
        lib.name
    );
    let mut table_templates = HashMap::new();

    // Process table templates.
    for template in lib.find_groups_by_name("lu_table_template") {
        let template_name = template.arguments.first().ok_or_else(|| {
            log::error!("lu_table_template has no name argument.");
            LibertyErr::InvalidLuTableTemplate("<noname>".to_string())
        })?;

        let variable_1 = template
            .get_simple_attribute("variable_1")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                log::error!(
                    "lu_table_template({}): `variable_1` is not defined.",
                    template_name
                );
                LibertyErr::InvalidLuTableTemplate(template_name.to_string())
            })?;
        // variable_2 may not be defined for x*1 sized tables.
        let variable_2 = template
            .get_simple_attribute("variable_2")
            .and_then(|v| v.as_str());

        let index1 = template
            .get_simple_attribute("index_1")
            .and_then(|v| v.as_str())
            .map(liberty_io::util::parse_float_array)
            .ok_or_else(|| {
                log::error!(
                    "`{}` is not well formatted in {}.",
                    "index_1",
                    template_name.to_string()
                );
                LibertyErr::InvalidLuTableTemplate(template_name.to_string())
            })?
            .map_err(|_| {
                log::error!(
                    "`{}` is not well formatted in {}.",
                    "index_1",
                    template_name.to_string()
                );
                LibertyErr::InvalidLuTableTemplate(template_name.to_string())
            })?;

        let index1_size = index1.len();

        let index2_size = if variable_2.is_some() {
            let index2 = template
                .get_simple_attribute("index_2")
                .and_then(|v| v.as_str())
                .map(liberty_io::util::parse_float_array)
                .ok_or_else(|| {
                    log::error!(
                        "`{}` is not well formatted in {}.",
                        "index_2",
                        template_name.to_string()
                    );
                    LibertyErr::InvalidLuTableTemplate(template_name.to_string())
                })?
                .map_err(|_| {
                    log::error!(
                        "`{}` is not well formatted in {}.",
                        "index_2",
                        template_name.to_string()
                    );
                    LibertyErr::InvalidLuTableTemplate(template_name.to_string())
                })?;
            index2.len()
        } else {
            1
        };

        let template = LuTableTemplate {
            var1: variable_1.to_string(),
            var2: variable_2.map(|v| v.to_string()),
            size: (index1_size, index2_size),
        };

        // Store the template.
        table_templates.insert(template_name.to_string(), template);
    }

    Ok(table_templates)
}

/// Read a lookup table with indices and put it into an interpolator struct
/// such that the lookup table can be evaluated like a function.
///
///
/// * `required_var1_name`: The name of the variable which should be used as first variable in the interpolated function.
/// * `required_var2_name`: The name of the variable which should be used as second variable in the interpolated function.
/// * `cell_name`: Name of the cell. Used for log output.
/// * `pin_name`: Name of the pin. Used for log output.
///
fn get_interpolated_timing_table(
    timing_group: &Group,
    table_group: &Group,
    table_templates: &HashMap<String, LuTableTemplate>,
    required_var1_name: &str,
    required_var2_name: &str,
    cell_name: &str,
    pin_name: &str,
) -> Result<Interp, LibertyErr> {
    assert_eq!(
        timing_group.name, "timing",
        "Expected a timing group. Found: '{}'",
        timing_group.name
    );

    let template_name = table_group
        .arguments
        .first()
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            let msg = format!(
                "Timing table {} has no template name defined in cell {}, pin {}.",
                table_group.name, cell_name, pin_name
            );
            log::error!("{}", msg);
            LibertyErr::Other(msg)
        })?;

    let mut interp = get_timing_table(
        timing_group,
        &table_group.name,
        "index_1",
        "index_2",
        "values",
    )?;

    // Check the template and validate table dimensions.
    // Make sure the variables are correctly ordered.
    {
        let (num_vars,) = if template_name == "scalar" {
            (0,)
        } else {
            let template = table_templates.get(template_name).ok_or_else(|| {
                log::error!(
                    "LUT table template is used but not defined: {}",
                    template_name
                );
                let msg = format!(
                    "LUT table template is used but not defined: {}",
                    template_name
                );
                LibertyErr::Other(msg)
            })?;

            let num_vars = if template.var2.is_some() { 2 } else { 1 };

            let var_names = [Some(template.var1.as_str()), template.var2.as_deref()];

            let output_cap_var = var_names
                .iter()
                .find_position(|&&name| name == Some(required_var1_name))
                .map(|(pos, _)| pos);

            let input_transition_var = var_names
                .iter()
                .find_position(|&&name| name == Some(required_var2_name))
                .map(|(pos, _)| pos);

            // Fix variable ordering.
            match (output_cap_var, input_transition_var) {
                (Some(0), Some(1)) => {
                    debug_assert_eq!(num_vars, 2);
                } // Ordering is fine.
                (Some(1), _) | (_, Some(0)) => {
                    debug_assert!(num_vars > 0);
                    // Fix variable ordering.
                    interp = interp.swap_variables();
                }
                _ => {
                    debug_assert_eq!(num_vars, 0);
                } // Variable ordering does not matter.
            }

            (num_vars,)
        };

        let actual_num_vars = match &interp {
            Interp::Scalar(_) => 0,
            Interp::Interp1D1(_) | Interp::Interp1D2(_) => 1,
            Interp::Interp2D(_) => 2,
        };

        if num_vars != actual_num_vars {
            log::error!(
                "Table dimension mismatch. Template '{}' defines {} variables but found {}.",
                template_name,
                num_vars,
                actual_num_vars
            );
            return Err(LibertyErr::TableMalformed);
        }
    }

    Ok(interp)
}

impl<'a> LibertyTimingLibrary<'a> {
    /// Create a new timing library based on a liberty structure.
    pub fn new(lib: &'a Group) -> Result<Self, LibertyErr> {
        // Check that `lib` is really a `library` group.
        if lib.name != "library" {
            Err(LibertyErr::Other(format!(
                "Group must be a `library` group but it is `{}`",
                lib.name
            )))?;
        }

        let mut l = Self {
            lib,
            table_templates: HashMap::default(),
            cells: Default::default(),
            time_unit: Default::default(),
            capacitive_load_unit: Default::default(),
        };

        l.init_units()?;

        let delay_model = lib
            .get_simple_attribute("delay_model")
            .and_then(|v| v.as_str());

        if delay_model != Some("table_lookup") {
            log::error!(
                "Delay model is not supported. Must be `table_lookup`. delay_model = {:?}",
                delay_model
            );
            Err(LibertyErr::UnsupportedDelayModel(
                delay_model.unwrap_or("<unknown>").to_string(),
            ))?;
        }

        // Read table templates.
        l.table_templates = read_template_tables(lib)?;

        // Process cells.
        for cell_group in lib.find_groups_by_name("cell") {
            let cell_name = get_cell_name(cell_group)?;

            let mut cell = Cell::default();
            // Process all pins.
            for pin_group in cell_group.find_groups_by_name("pin") {
                // Get pin name.
                let pin_name = pin_group
                    .arguments
                    .first()
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        let msg =
                            format!("Pin group in cell `{}` has no name argument.", cell_name);
                        log::error!("{}", msg);
                        LibertyErr::Other(msg)
                    })?;

                // Get pin capacitance.
                let capacitance = pin_group
                    .get_simple_attribute("capacitance")
                    .and_then(|v| v.as_float())
                    .unwrap_or_default()
                    * l.capacitive_load_unit;

                let mut pin = Pin {
                    capacitance,
                    ..Default::default()
                };

                // Process timing groups.
                for timing_group in pin_group.find_groups_by_name("timing") {
                    // Get related pin name.
                    let related_pin = timing_group
                        .get_simple_attribute("related_pin")
                        .and_then(|v| v.as_str())
                        .ok_or_else(|| {
                            log::error!(
                                "Timing group has no related pin in cell `{}`, pin `{}`.",
                                cell_name,
                                pin_name
                            );
                            LibertyErr::AttributeNotFound("related_pin".to_string())
                        })?;

                    let timing_type = timing_group
                        .get_simple_attribute("timing_type")
                        .and_then(|v| v.as_str())
                        .unwrap_or("combinational"); // Default is 'combinational'.

                    let is_delay_arc = matches!(
                        timing_type,
                        "combinational"
                            | "combinational_rise"
                            | "combinational_fall"
                            | "rising_edge"
                            | "falling_edge"
                    );

                    let is_constraint_arc = matches!(
                        timing_type,
                        "hold_rising" | "hold_falling" | "setup_rising" | "setup_falling"
                    );
                    // println!("{}: {} -> {} {}", cell_name, related_pin, pin_name, is_delay_arc);

                    // Read a delay arc.
                    if is_delay_arc {
                        let mut delay_arc = DelayArc::default();

                        match timing_type {
                            "combinational" => {
                                delay_arc.falling_edge = true;
                                delay_arc.rising_edge = true;
                            }
                            "rising_edge" | "combinational_rise" => delay_arc.rising_edge = true,
                            "falling_edge" | "combinational_fall" => delay_arc.falling_edge = true,
                            t => log::warn!("Unexpected timing_type: {}", t),
                        };

                        // Process NDLM timing tables.
                        for table_group in &timing_group.groups {
                            // let delay_table_names = ["rise_transition", "fall_transition", "cell_rise", "cell_fall"];
                            // let is_delay_arc = delay_table_names.contains(&table_group.name.as_str());

                            let required_var1_name = "total_output_net_capacitance";
                            let required_var2_name = "input_net_transition";

                            let interp = get_interpolated_timing_table(
                                timing_group,
                                table_group,
                                &l.table_templates,
                                required_var1_name,
                                required_var2_name,
                                cell_name,
                                pin_name,
                            )?;

                            // Convert units.
                            let interp = interp
                                .map_values(|&t| t * l.time_unit)
                                .map_x_axis(|cap| cap * l.capacitive_load_unit)
                                .map_y_axis(|t| t * l.time_unit);

                            // Store the table.
                            match table_group.name.as_str() {
                                "rise_transition" => delay_arc.rise_transition = Some(interp),
                                "fall_transition" => delay_arc.fall_transition = Some(interp),
                                "cell_rise" => delay_arc.cell_rise = Some(interp),
                                "cell_fall" => delay_arc.cell_fall = Some(interp),
                                n => {
                                    log::warn!("Unsupported timing table: '{}'", n);
                                }
                            }
                        }

                        pin.delay_arcs.insert(related_pin.to_string(), delay_arc);
                    }

                    // Read a constraint arc.
                    if is_constraint_arc {
                        let mut constraint_arc = ConstraintArc::default();

                        // Process NDLM timing tables.
                        for table_group in &timing_group.groups {
                            // let delay_table_names = ["rise_transition", "fall_transition", "cell_rise", "cell_fall"];
                            // let constraint_table_names = ["rise_constraint", "fall_constraint"];
                            // let is_delay_arc = delay_table_names.contains(&table_group.name.as_str());
                            // let is_constraint_arc = constraint_table_names.contains(&table_group.name.as_str());

                            let required_var1_name = "related_pin_transition";
                            let required_var2_name = "constrained_pin_transition";

                            let interp = get_interpolated_timing_table(
                                timing_group,
                                table_group,
                                &l.table_templates,
                                required_var1_name,
                                required_var2_name,
                                cell_name,
                                pin_name,
                            )?;

                            // Convert to SI units.
                            let interp = interp
                                .map_values(|&t| t * l.time_unit)
                                .map_x_axis(|t| t * l.time_unit)
                                .map_y_axis(|t| t * l.time_unit);

                            // Store the table.
                            match table_group.name.as_str() {
                                "rise_constraint" => constraint_arc.rise_constraint = Some(interp),
                                "fall_constraint" => constraint_arc.fall_constraint = Some(interp),
                                n => {
                                    log::warn!("Unsupported timing table: '{}'", n);
                                }
                            }
                        }

                        // Store the constraint arc.
                        match timing_type {
                            "hold_rising" => &mut pin.hold_rising,
                            "hold_falling" => &mut pin.hold_falling,
                            "setup_rising" => &mut pin.setup_rising,
                            "setup_falling" => &mut pin.setup_falling,
                            _ => unreachable!(
                                "Unexpected timing type for constraint arc: '{}'",
                                timing_type
                            ),
                        }
                        .insert(related_pin.to_string(), constraint_arc);
                    }
                }
                cell.pins.insert(pin_name.to_string(), pin);
            }
            l.cells.insert(cell_name.to_string(), cell);
        }

        Ok(l)
    }

    /// Load units from the liberty data structure.
    fn init_units(&mut self) -> Result<(), LibertyErr> {
        // Get time unit.
        {
            let time_unit_str = self
                .lib
                .get_simple_attribute("time_unit")
                .ok_or(LibertyErr::UnitNotDefined("time_unit"))?
                .as_str()
                .ok_or(LibertyErr::UnitNotDefined("time_unit is not a string"))?;

            let time_unit_sec = TimeUnit::from_str(time_unit_str)
                .map_err(|_| LibertyErr::UnitNotDefined("Failed to parse time_unit."))?;

            self.time_unit = Time::new::<second>(time_unit_sec.as_seconds());
        }

        // Get capacitance unit.
        {
            let cap_unit = self
                .lib
                .get_complex_attribute("capacitive_load_unit")
                .ok_or(LibertyErr::UnitNotDefined("capacitive_load_unit"))?;

            let c = CapacitiveLoadUnit::try_from(cap_unit.as_slice())
                .map_err(|_| LibertyErr::UnitNotDefined("capacitive_load_unit is malformed"))?;

            self.capacitive_load_unit = Capacitance::new::<farad>(c.as_farad());
        }

        Ok(())
    }

    /// Find a pin by the name of the cell and the name of the pin.
    pub fn get_pin(&self, cell: &str, output_pin: &str) -> Option<&Pin> {
        self.cells.get(cell).and_then(|c| c.pins.get(output_pin))
    }

    pub(crate) fn get_delay_arc(
        &self,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
    ) -> Option<&DelayArc> {
        self.get_pin(cell, output_pin)
            .and_then(|p| p.delay_arcs.get(related_pin))
    }

    pub(crate) fn get_hold_rising_arc(
        &self,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
    ) -> Option<&ConstraintArc> {
        self.get_pin(cell, output_pin)
            .and_then(|p| p.hold_rising.get(related_pin))
    }

    pub(crate) fn get_hold_falling_arc(
        &self,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
    ) -> Option<&ConstraintArc> {
        self.get_pin(cell, output_pin)
            .and_then(|p| p.hold_falling.get(related_pin))
    }
    pub(crate) fn get_setup_rising_arc(
        &self,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
    ) -> Option<&ConstraintArc> {
        self.get_pin(cell, output_pin)
            .and_then(|p| p.setup_rising.get(related_pin))
    }
    pub(crate) fn get_setup_falling_arc(
        &self,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
    ) -> Option<&ConstraintArc> {
        self.get_pin(cell, output_pin)
            .and_then(|p| p.setup_falling.get(related_pin))
    }
}

fn get_cell_name(cell_group: &Group) -> Result<&str, LibertyErr> {
    let cell_name = cell_group
        .arguments
        .first()
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            let msg = "Cell group has no name argument.";
            log::error!("{}", msg);

            LibertyErr::Other(msg.to_string())
        })?;
    Ok(cell_name)
}

impl<'a> TimingLibrary for LibertyTimingLibrary<'a> {
    fn get_slew(
        &self,
        edge_polarity: EdgePolarity,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
        input_slew: Time,
        output_capacitance: Capacitance,
    ) -> Option<Time> {
        self.get_delay_arc(cell, output_pin, related_pin)
            .and_then(|d| match edge_polarity {
                EdgePolarity::Rise => d.rise_transition.as_ref(),
                EdgePolarity::Fall => d.fall_transition.as_ref(),
            })
            .map(|f| {
                // println!("?_transition({}, {}) = {}", output_capacitance, input_slew, f.eval2d((input_slew, output_capacitance)));
                f.eval2d((output_capacitance, input_slew))
            })
    }

    fn get_cell_delay(
        &self,
        edge_polarity: EdgePolarity,
        cell: &str,
        output_pin: &str,
        related_pin: &str,
        input_slew: Time,
        output_capacitance: Capacitance,
    ) -> Option<Time> {
        self.get_delay_arc(cell, output_pin, related_pin)
            .and_then(|d| match edge_polarity {
                EdgePolarity::Rise => d.cell_rise.as_ref(),
                EdgePolarity::Fall => d.cell_fall.as_ref(),
            })
            .map(|f| f.eval2d((output_capacitance, input_slew)))
    }

    fn get_hold_constraint(
        &self,
        cell: &str,
        constrained_pin: &str,
        related_pin: &str,
        constrained_edge_polarity: EdgePolarity,
        related_edge_polarity: EdgePolarity,
        related_pin_transition: Time,
        constrained_pin_transition: Time,
        output_load: Capacitance,
    ) -> Option<Time> {
        self.get_pin(cell, constrained_pin)
            .and_then(|p| match related_edge_polarity {
                EdgePolarity::Rise => p.hold_rising.get(related_pin),
                EdgePolarity::Fall => p.hold_falling.get(related_pin),
            })
            .and_then(|arc| match constrained_edge_polarity {
                EdgePolarity::Rise => arc.rise_constraint.as_ref(),
                EdgePolarity::Fall => arc.fall_constraint.as_ref(),
            })
            .map(|f| f.eval2d((related_pin_transition, constrained_pin_transition)))
    }

    fn get_setup_constraint(
        &self,
        cell: &str,
        constrained_pin: &str,
        related_pin: &str,
        constrained_edge_polarity: EdgePolarity,
        related_edge_polarity: EdgePolarity,
        related_pin_transition: Time,
        constrained_pin_transition: Time,
        output_load: Capacitance,
    ) -> Option<Time> {
        self.get_pin(cell, constrained_pin)
            .and_then(|p| match related_edge_polarity {
                EdgePolarity::Rise => p.setup_rising.get(related_pin),
                EdgePolarity::Fall => p.setup_falling.get(related_pin),
            })
            .and_then(|arc| match constrained_edge_polarity {
                EdgePolarity::Rise => arc.rise_constraint.as_ref(),
                EdgePolarity::Fall => arc.fall_constraint.as_ref(),
            })
            .map(|f| f.eval2d((related_pin_transition, constrained_pin_transition)))
    }
}

#[test]
fn test_load_timing_library_freepdk45() {
    use std::fs::File;
    use std::io::BufReader;

    // Parse the liberty file.
    let f = File::open("./tests/data/freepdk45/gscl45nm.lib").unwrap();
    let mut buf = BufReader::new(f);
    let result = liberty_io::read_liberty_bytes(&mut buf);
    let library = result.unwrap();
    assert_eq!(library.name.to_string(), "library");
    assert_eq!(library.arguments[0].to_string(), "gscl45nm");

    // Load the timing library structure.

    let timing_library = LibertyTimingLibrary::new(&library).unwrap();
}

#[test]
fn test_lut_variable_ordering() {
    // Parse the liberty file.

    let data = r#"
    library() {

      time_unit: "1ns" ;
      capacitive_load_unit (1, pf);
    
      delay_model: table_lookup;
      lu_table_template(delay_template_2x3) {
        variable_1 : total_output_net_capacitance;
        variable_2 : input_net_transition;
        index_1 ("1000.0, 1001.0");
        index_2 ("1000.0, 1001.0, 1002.0");
      }
      lu_table_template(delay_template_2x3_swapped_vars) {
        variable_1 : input_net_transition;
        variable_2 : total_output_net_capacitance;
        index_1 ("1000.0, 1001.0, 1002.0");
        index_2 ("1000.0, 1001.0");
      }
      cell(INVX1) {
        pin(Y) {
            timing() {
                related_pin: "A";
                cell_rise(delay_template_2x3) {
                    index_1: "1.0, 2.0";
                    index_2: "1.0, 2.0, 3.0";
                    values (
                        "1.0, 1.1, 1.2", \
                        "1.1, 1.3, 1.5"
                    );
                }
                cell_fall(delay_template_2x3_swapped_vars) { // Use other variable ordering!
                    index_1: "1.0, 2.0, 3.0";
                    index_2: "1.0, 2.0";
                    values (
                        "1.0, 1.1", \
                        "1.1, 1.3", \
                        "1.2, 1.5"
                    );
                }
            }
        }
      }
    }
    "#;

    let result = liberty_io::read_liberty_chars(data.chars());
    let library = result.unwrap();

    // Load the timing library structure.

    let timing_library = LibertyTimingLibrary::new(&library).unwrap();

    let arc_a_y = timing_library.get_delay_arc("INVX1", "Y", "A").unwrap();

    let cell_rise = arc_a_y.cell_rise.as_ref().unwrap();
    let cell_fall = arc_a_y.cell_fall.as_ref().unwrap();

    use uom::si::{capacitance::picofarad, time::nanosecond};
    let ns = Time::new::<nanosecond>;
    let pf = Capacitance::new::<picofarad>;

    assert!((cell_rise.eval2d((pf(2.0), ns(3.0))) - ns(1.5)).abs() < ns(1e-6));
    assert!((cell_rise.eval2d((pf(3.0), ns(2.0))) - ns(1.5)).abs() < ns(1e-6)); // Swapped variables
}