vj 0.2.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
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
//! The arithmetic half of `$sdf_annotate`'s DELAY mapping (IEEE 1800-2023 clause 32;
//! SD-B / T26, `docs/superpowers/plans/2026-10-03-sdf.md`): everything that turns the numbers
//! of an SDF construct into per-transition tick values and merges them into a module path's
//! delays and pulse limits. Pure -- no design, no scheduler -- so every rule of 32.5, 32.7,
//! 32.8 and Table 32-4 is pinned by a unit test here; [`crate::sdf_apply`] is the glue that
//! finds the specify paths a construct annotates.
//!
//! **Hold.** An SDF `()` leaves the annotated value as it is (32.5: "empty parentheses to
//! hold the current values"). A value that is held is `None` throughout this module, and an
//! [`SlotUpdate`] slot that is `None` leaves that transition untouched. Table 32-4's `min` /
//! `max` entries combine two of the given values: implementation-defined (the LRM defines the
//! table only for supplied values), a `min`/`max` with a held operand is itself held, so a
//! transition whose value depends on a value the file declined to give is never changed from
//! a guess.

use vj_sdf::ast::{DelVal, DeltaMode, PathPulse, Rvalue};
use vj_sim::netlist::specify::PathDelaySet;

pub(crate) use vj_exec::timing::sdf_update::{SlotUpdate, Slots, apply_update, merge_one};

// ---------------------------------------------------------------------------------------
// Table 32-4.
// ---------------------------------------------------------------------------------------

/// One cell of Table 32-4: a given SDF value (`V(1)` is `v1`) or the minimum / maximum of two.
#[derive(Clone, Copy)]
enum Cell {
    V(usize),
    Min(usize, usize),
    Max(usize, usize),
}

use Cell::{Max, Min, V};

/// The columns of Table 32-4: how many SDF delay values were provided.
const COLUMNS: [usize; 5] = [1, 2, 3, 6, 12];

/// IEEE 1800-2023 Table 32-4 ("SDF to SystemVerilog delay value mapping"), transcribed cell
/// for cell: one row per SystemVerilog transition in `TRANSITIONS` order (`0->1`, `1->0`,
/// `0->z`, `z->1`, `1->z`, `z->0`, `0->x`, `x->1`, `1->x`, `x->0`, `x->z`, `z->x`), one column
/// per entry of [`COLUMNS`]. This is a table of its own and not `PathDelaySet::from_list`:
/// that one takes already-resolved values and cannot carry a held (`None`) operand through
/// its `min`/`max`. (The two tables do give the same numbers, pinned by a test.)
#[rustfmt::skip]
const TABLE_32_4: [[Cell; 5]; 12] = [
    // 1 value   2 values      3 values       6 values       12 values
    [V(1), V(1),         V(1),          V(1),          V(1)],  // 0 -> 1
    [V(1), V(2),         V(2),          V(2),          V(2)],  // 1 -> 0
    [V(1), V(1),         V(3),          V(3),          V(3)],  // 0 -> z
    [V(1), V(1),         V(1),          V(4),          V(4)],  // z -> 1
    [V(1), V(2),         V(3),          V(5),          V(5)],  // 1 -> z
    [V(1), V(2),         V(2),          V(6),          V(6)],  // z -> 0
    [V(1), V(1),         Min(1, 3),     Min(1, 3),     V(7)],  // 0 -> x
    [V(1), V(1),         V(1),          Max(1, 4),     V(8)],  // x -> 1
    [V(1), V(2),         Min(2, 3),     Min(2, 5),     V(9)],  // 1 -> x
    [V(1), V(2),         V(2),          Max(2, 6),     V(10)], // x -> 0
    [V(1), Max(1, 2),    V(3),          Max(3, 5),     V(11)], // x -> z
    [V(1), Min(1, 2),    Min(1, 2),     Min(4, 6),     V(12)], // z -> x
];

/// Extends `v` (the values of one SDF delay list, `None` for a held one) to twelve transitions
/// by Table 32-4. An SDF list of any length other than 1, 2, 3, 6 or 12 has no column in the
/// table and is an error.
pub(crate) fn expand_table(v: &[Option<i64>]) -> Result<Slots, String> {
    let Some(col) = COLUMNS.iter().position(|&n| n == v.len()) else {
        return Err(format!(
            "an SDF delay list of {} values (LRM Table 32-4 defines only 1, 2, 3, 6 and 12)",
            v.len()
        ));
    };
    let mut out: Slots = [None; 12];
    for (slot, row) in out.iter_mut().zip(&TABLE_32_4) {
        *slot = match row[col] {
            V(a) => v[a - 1],
            Min(a, b) => v[a - 1].zip(v[b - 1]).map(|(x, y)| x.min(y)),
            Max(a, b) => v[a - 1].zip(v[b - 1]).map(|(x, y)| x.max(y)),
        };
    }
    Ok(out)
}

// ---------------------------------------------------------------------------------------
// $sdf_annotate's mtm_spec / scale_factors / scale_type (Tables 32-5, 32-6).
// ---------------------------------------------------------------------------------------

/// Which member of a min:typ:max triple is annotated (Table 32-5).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mtm {
    Min,
    Typ,
    Max,
}

impl Mtm {
    fn index(self) -> usize {
        match self {
            Mtm::Min => 0,
            Mtm::Typ => 1,
            Mtm::Max => 2,
        }
    }

    /// `mtm_spec` (absent = the default `TOOL_CONTROL`). Keywords are matched
    /// case-insensitively (lenient: the LRM prints them upper case).
    ///
    /// Implementation-defined: `TOOL_CONTROL` ("annotates the value as selected by the
    /// simulator") selects `tool_control`, which is the typical value unless the run was given
    /// `--sdf-mtm` (`TimingOptions::tool_control`). Both an elided `mtm_spec` and an explicit
    /// `"TOOL_CONTROL"` mean it (LRM Table 32-5: the elided default is `TOOL_CONTROL`).
    pub(crate) fn parse(spec: Option<&str>, tool_control: Mtm) -> Result<Mtm, String> {
        let Some(s) = spec else {
            return Ok(tool_control);
        };
        match s.to_ascii_uppercase().as_str() {
            "MINIMUM" => Ok(Mtm::Min),
            "MAXIMUM" => Ok(Mtm::Max),
            "TYPICAL" => Ok(Mtm::Typ),
            "TOOL_CONTROL" => Ok(tool_control),
            _ => Err(format!(
                "mtm_spec \"{s}\" is not MAXIMUM, MINIMUM, TYPICAL or TOOL_CONTROL (LRM Table 32-5)"
            )),
        }
    }
}

/// How `scale_factors` apply to a triple (Table 32-6).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ScaleType {
    Max,
    Min,
    Mtm,
    Typ,
}

/// `scale_factors` and `scale_type`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Scale {
    /// The min, typ and max factors.
    pub(crate) factors: [f64; 3],
    pub(crate) kind: ScaleType,
}

impl Scale {
    /// `1.0:1.0:1.0`, `FROM_MTM`: no scaling.
    pub(crate) const IDENTITY: Scale = Scale {
        factors: [1.0; 3],
        kind: ScaleType::Mtm,
    };

    /// The two options (each absent = its default). `scale_factors` is `"min:typ:max"`, three
    /// non-negative numbers; `scale_type` one of Table 32-6's keywords (case-insensitive).
    pub(crate) fn parse(factors: Option<&str>, kind: Option<&str>) -> Result<Scale, String> {
        let mut scale = Scale::IDENTITY;
        if let Some(f) = factors {
            let parts: Vec<&str> = f.split(':').collect();
            let [a, b, c] = parts.as_slice() else {
                return Err(format!(
                    "scale_factors \"{f}\" is not three colon-separated numbers (min:typ:max)"
                ));
            };
            for (slot, text) in scale.factors.iter_mut().zip([a, b, c]) {
                *slot = text
                    .trim()
                    .parse::<f64>()
                    .ok()
                    .filter(|v| v.is_finite() && *v >= 0.0)
                    .ok_or_else(|| {
                        format!("scale_factors \"{f}\": \"{text}\" is not a non-negative number")
                    })?;
            }
        }
        if let Some(k) = kind {
            scale.kind = match k.to_ascii_uppercase().as_str() {
                "FROM_MAXIMUM" => ScaleType::Max,
                "FROM_MINIMUM" => ScaleType::Min,
                "FROM_MTM" => ScaleType::Mtm,
                "FROM_TYPICAL" => ScaleType::Typ,
                _ => {
                    return Err(format!(
                        "scale_type \"{k}\" is not FROM_MAXIMUM, FROM_MINIMUM, FROM_MTM or \
                         FROM_TYPICAL (LRM Table 32-6)"
                    ));
                }
            };
        }
        Ok(scale)
    }
}

/// Reduces an SDF value slot to the one number annotated: the `mtm_spec` member of the triple,
/// scaled.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Selector {
    pub(crate) mtm: Mtm,
    pub(crate) scale: Scale,
}

impl Selector {
    /// `rv`'s annotated value in SDF time units, or `None` (held) for `()` and for a triple
    /// whose needed member is not written (`(1::3)` with `TYPICAL`).
    ///
    /// Table 32-6: `FROM_MTM` scales each member by its own factor; `FROM_MINIMUM`,
    /// `FROM_TYPICAL` and `FROM_MAXIMUM` scale that one member by each of the three factors in
    /// turn (so the min, typ and max results all derive from it). The `mtm_spec` member of the
    /// result is then taken.
    pub(crate) fn value(&self, rv: Rvalue) -> Option<f64> {
        let triple = match rv {
            Rvalue::Empty => return None,
            Rvalue::Single(v) => [Some(v); 3],
            Rvalue::Triple { min, typ, max } => [min, typ, max],
        };
        let want = self.mtm.index();
        let base = match self.scale.kind {
            ScaleType::Mtm => want,
            ScaleType::Min => 0,
            ScaleType::Typ => 1,
            ScaleType::Max => 2,
        };
        triple[base].map(|v| v * self.scale.factors[want])
    }
}

/// The reject / error percentages of an annotated delay (LRM 32.7: "by default, these limits
/// are 100%, but they can be modified through invocation options").
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PulsePercent {
    pub(crate) reject: f64,
    pub(crate) error: f64,
}

impl PulsePercent {
    pub(crate) const DEFAULT: PulsePercent = PulsePercent {
        reject: 100.0,
        error: 100.0,
    };
}

/// `v` SDF time units (of `10^sdf_unit_exp` seconds) as scheduler ticks (of `10^tick_exp`
/// seconds), rounded to the annotated instance's time precision (`10^precision_exp`, LRM
/// 3.14.2.2) first, exactly as `vj_codegen::timescale::delay_ticks` does for a source
/// delay. Signed: an INCREMENT may be negative.
pub(crate) fn to_ticks(v: f64, sdf_unit_exp: i32, precision_exp: i32, tick_exp: i32) -> i64 {
    let in_precision = (v * 10f64.powi(sdf_unit_exp - precision_exp)).round();
    // A saturating cast: a value beyond i64 is absurd for a delay and must not wrap.
    (in_precision * 10f64.powi(precision_exp - tick_exp)).round() as i64
}

// ---------------------------------------------------------------------------------------
// Building and applying updates.
// ---------------------------------------------------------------------------------------

fn percent_of(v: i64, pct: f64) -> i64 {
    (v as f64 * pct / 100.0).round() as i64
}

/// The update an `IOPATH` (or `DEVICE`) delay list makes (LRM 32.4.1, 32.7, 32.8): the delays by
/// Table 32-4; the pulse limits from the explicit `((d) (reject) (error))` forms the same way
/// (a held pulse value holds the limit); and, for a delay written without a pulse form, from
/// `pct` of that delay ("the default values annotated for pulse limits shall be calculated
/// using the percentage settings").
///
/// Implementation-defined: a no-pulse delay's default limit in INCREMENT mode is `pct` of the
/// INCREMENT, not of the new delay, so it adds to the limit exactly as the delay itself adds
/// to the delay (the two agree whenever the limits were the default ones).
pub(crate) fn iopath_update(
    delvals: &[DelVal],
    sel: &Selector,
    pct: PulsePercent,
    convert: &dyn Fn(f64) -> i64,
) -> Result<SlotUpdate, String> {
    let mut delays = Vec::with_capacity(delvals.len());
    let mut rejects = Vec::with_capacity(delvals.len());
    let mut errors = Vec::with_capacity(delvals.len());
    for dv in delvals {
        let delay = sel.value(dv.delay).map(convert);
        let (reject, error) = match dv.pulse {
            Some((r, e)) => (sel.value(r).map(convert), sel.value(e).map(convert)),
            None => (
                delay.map(|d| percent_of(d, pct.reject)),
                delay.map(|d| percent_of(d, pct.error)),
            ),
        };
        delays.push(delay);
        rejects.push(reject);
        errors.push(error);
    }
    Ok(SlotUpdate {
        delay: expand_table(&delays)?,
        reject: expand_table(&rejects)?,
        error: expand_table(&errors)?,
    })
}

/// The update a `PATHPULSE` / `PATHPULSEPERCENT` makes to one path (LRM 32.7: "they do not
/// affect the delay"): the same reject value for every transition, a held value holding. For
/// `PATHPULSEPERCENT` the values are percentages of `delays`, the path's delays as they stand
/// when the construct is reached (annotation is ordered, 32.5).
pub(crate) fn pathpulse_update(
    pp: &PathPulse,
    sel: &Selector,
    convert: &dyn Fn(f64) -> i64,
    delays: &PathDelaySet,
) -> SlotUpdate {
    let mut up = SlotUpdate::default();
    let current = delays.transitions();
    for (limit, rv) in [(&mut up.reject, pp.reject), (&mut up.error, pp.error)] {
        let Some(v) = sel.value(rv) else { continue };
        for (i, slot) in limit.iter_mut().enumerate() {
            *slot = Some(if pp.percent {
                percent_of(i64::try_from(current[i]).unwrap_or(i64::MAX), v)
            } else {
                convert(v)
            });
        }
    }
    up
}

/// `cur` (`[rise, fall, turn-off]`, a primitive's delays, LRM 28.16) with a `DEVICE` update
/// applied (LRM 32.4 Table 32-1: `DEVICE` annotates primitives when the module has no specify
/// path). A primitive has three delays where Table 32-4 has twelve transitions: rise is `0->1`,
/// fall is `1->0`, and turn-off is the smaller of the two transitions to `z` (`0->z`, `1->z`),
/// which for 1, 2 and 3 SDF values is exactly Table 28-9's own expansion of a gate's delay
/// list (one value: all three; two: turn-off is `min(rise, fall)`; three: the third) -- for 6
/// and 12 values the minimum is implementation-defined. A turn-off whose operand is held
/// (`()`) is itself held. INCREMENT adds, flooring at 0; the pulse limits of the construct
/// have no meaning on a primitive and are not read here.
pub(crate) fn device_delays(cur: [u64; 3], upd: &Slots, mode: DeltaMode) -> [u64; 3] {
    let off = upd[2].zip(upd[4]).map(|(a, b)| a.min(b));
    let mut out = cur;
    for (slot, u) in out.iter_mut().zip([upd[0], upd[1], off]) {
        *slot = merge_one(*slot, u, mode);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::specify::PathTimes;
    use vj_abi::bit4::Bit4;
    use vj_sdf::ast::{DelVal, DeltaMode, PathPulse, Rvalue};
    use vj_sim::netlist::specify::TRANSITIONS;

    fn some(v: &[i64]) -> Vec<Option<i64>> {
        v.iter().map(|&x| Some(x)).collect()
    }

    fn slots(v: [i64; 12]) -> Slots {
        v.map(Some)
    }

    // v1..v12, chosen so that every min / max of Table 32-4 has a visible winner.
    const V: [i64; 12] = [5, 3, 9, 2, 8, 6, 11, 4, 12, 1, 10, 7];

    // Order: 0->1 1->0 0->z z->1 1->z z->0 0->x x->1 1->x x->0 x->z z->x.
    #[test]
    fn table_32_4_one_value_column() {
        assert_eq!(expand_table(&some(&V[..1])).unwrap(), slots([5; 12]));
    }

    #[test]
    fn table_32_4_two_value_column() {
        // v1 = 5, v2 = 3.
        assert_eq!(
            expand_table(&some(&V[..2])).unwrap(),
            slots([
                5, 3, 5, 5, 3, 3, 5, 5, 3, 3, 5, /* max(v1,v2) */
                3  /* min(v1,v2) */
            ])
        );
    }

    #[test]
    fn table_32_4_three_value_column() {
        // v1 = 5, v2 = 3, v3 = 9.
        assert_eq!(
            expand_table(&some(&V[..3])).unwrap(),
            slots([
                5, 3, 9, 5, 9, 3, //
                5, /* min(v1,v3) */
                5, /* v1 */
                3, /* min(v2,v3) */
                3, /* v2 */
                9, /* v3 */
                3, /* min(v1,v2) */
            ])
        );
    }

    #[test]
    fn table_32_4_six_value_column() {
        // v1..v6 = 5, 3, 9, 2, 8, 6.
        assert_eq!(
            expand_table(&some(&V[..6])).unwrap(),
            slots([
                5, 3, 9, 2, 8, 6, //
                5, /* min(v1,v3) */
                5, /* max(v1,v4) */
                3, /* min(v2,v5) */
                6, /* max(v2,v6) */
                9, /* max(v3,v5) */
                2, /* min(v4,v6) */
            ])
        );
    }

    #[test]
    fn table_32_4_twelve_value_column_is_the_identity() {
        assert_eq!(expand_table(&some(&V)).unwrap(), slots(V));
    }

    #[test]
    fn table_32_4_agrees_with_the_source_side_table_30_2_and_30_3() {
        // Transcribing Table 32-4 cell for cell (rather than reusing `from_list`) is the
        // plan's requirement; as an independent cross-check, the two transcriptions must give
        // the same twelve values for every list length the source side also accepts.
        for n in [1usize, 2, 3, 6, 12] {
            let vals: Vec<u64> = V[..n].iter().map(|&v| v as u64).collect();
            let from_source = PathDelaySet::from_list(&vals).unwrap().transitions();
            let from_sdf = expand_table(&some(&V[..n])).unwrap();
            for (i, t) in TRANSITIONS.iter().enumerate() {
                assert_eq!(
                    from_sdf[i],
                    Some(from_source[i] as i64),
                    "{n} values, transition {t:?}"
                );
            }
        }
    }

    #[test]
    fn table_32_4_rejects_a_list_length_with_no_column() {
        for n in [0usize, 4, 5, 7, 11, 13] {
            let err = expand_table(&vec![Some(1); n]).unwrap_err();
            assert!(err.contains(&format!("{n} values")), "{err}");
        }
    }

    #[test]
    fn a_held_operand_holds_the_combined_transition() {
        // 2 values, v2 held: 1->0, 1->z, z->0, 1->x, x->0 all take v2 and hold;
        // x->z = max(v1, v2) and z->x = min(v1, v2) hold too.
        let out = expand_table(&[Some(5), None]).unwrap();
        let held: Vec<(Bit4, Bit4)> = TRANSITIONS
            .iter()
            .zip(out)
            .filter(|(_, v)| v.is_none())
            .map(|(t, _)| *t)
            .collect();
        assert_eq!(
            held,
            vec![
                (Bit4::One, Bit4::Zero),
                (Bit4::One, Bit4::Z),
                (Bit4::Z, Bit4::Zero),
                (Bit4::One, Bit4::X),
                (Bit4::X, Bit4::Zero),
                (Bit4::X, Bit4::Z),
                (Bit4::Z, Bit4::X),
            ]
        );
        assert_eq!(out[0], Some(5), "0->1 is v1");
    }

    fn sel(mtm: Mtm, factors: [f64; 3], kind: ScaleType) -> Selector {
        Selector {
            mtm,
            scale: Scale { factors, kind },
        }
    }

    const TRIPLE: Rvalue = Rvalue::Triple {
        min: Some(1.0),
        typ: Some(2.0),
        max: Some(4.0),
    };

    #[test]
    fn mtm_spec_picks_the_member() {
        let s = |m| sel(m, [1.0; 3], ScaleType::Mtm).value(TRIPLE);
        assert_eq!(s(Mtm::Min), Some(1.0));
        assert_eq!(s(Mtm::Typ), Some(2.0));
        assert_eq!(s(Mtm::Max), Some(4.0));
    }

    #[test]
    fn a_single_value_is_every_member_and_empty_holds() {
        let s = sel(Mtm::Max, [1.0; 3], ScaleType::Mtm);
        assert_eq!(s.value(Rvalue::Single(7.0)), Some(7.0));
        assert_eq!(s.value(Rvalue::Empty), None);
    }

    #[test]
    fn a_missing_selected_member_holds() {
        let s = sel(Mtm::Typ, [1.0; 3], ScaleType::Mtm);
        let rv = Rvalue::Triple {
            min: Some(1.0),
            typ: None,
            max: Some(3.0),
        };
        assert_eq!(s.value(rv), None);
        assert_eq!(sel(Mtm::Max, [1.0; 3], ScaleType::Mtm).value(rv), Some(3.0));
    }

    #[test]
    fn scale_types_follow_table_32_6() {
        // LRM 32.9: "1.6:1.4:1.2" -- min x1.6, typ x1.4, max x1.2.
        let f = [1.6, 1.4, 1.2];
        let near = |a: Option<f64>, b: f64| {
            let a = a.expect("a value");
            assert!((a - b).abs() < 1e-9, "{a} != {b}");
        };
        // FROM_MTM: each member by its own factor.
        near(sel(Mtm::Min, f, ScaleType::Mtm).value(TRIPLE), 1.0 * 1.6);
        near(sel(Mtm::Typ, f, ScaleType::Mtm).value(TRIPLE), 2.0 * 1.4);
        near(sel(Mtm::Max, f, ScaleType::Mtm).value(TRIPLE), 4.0 * 1.2);
        // FROM_MINIMUM / TYPICAL / MAXIMUM: that member, by each factor.
        near(sel(Mtm::Max, f, ScaleType::Min).value(TRIPLE), 1.0 * 1.2);
        near(sel(Mtm::Min, f, ScaleType::Typ).value(TRIPLE), 2.0 * 1.6);
        near(sel(Mtm::Typ, f, ScaleType::Max).value(TRIPLE), 4.0 * 1.4);
    }

    #[test]
    fn option_strings_parse_and_reject_garbage() {
        assert_eq!(Mtm::parse(None, Mtm::Typ).unwrap(), Mtm::Typ);
        assert_eq!(
            Mtm::parse(Some("TOOL_CONTROL"), Mtm::Typ).unwrap(),
            Mtm::Typ
        );
        assert_eq!(Mtm::parse(Some("minimum"), Mtm::Typ).unwrap(), Mtm::Min);
        assert!(
            Mtm::parse(Some("BEST"), Mtm::Typ)
                .unwrap_err()
                .contains("mtm_spec")
        );
    }

    /// T31 (LRM Table 32-5): `--sdf-mtm` defines what `TOOL_CONTROL` selects, both when the
    /// `mtm_spec` is elided and when it is written; the other keywords never follow it.
    #[test]
    fn tool_control_follows_the_invocation_option_and_nothing_else_does() {
        for tc in [Mtm::Min, Mtm::Typ, Mtm::Max] {
            assert_eq!(Mtm::parse(None, tc).unwrap(), tc);
            assert_eq!(Mtm::parse(Some("TOOL_CONTROL"), tc).unwrap(), tc);
            assert_eq!(Mtm::parse(Some("tool_control"), tc).unwrap(), tc);
            assert_eq!(Mtm::parse(Some("MINIMUM"), tc).unwrap(), Mtm::Min);
            assert_eq!(Mtm::parse(Some("TYPICAL"), tc).unwrap(), Mtm::Typ);
            assert_eq!(Mtm::parse(Some("MAXIMUM"), tc).unwrap(), Mtm::Max);
        }
    }

    #[test]
    fn scale_options_parse_and_reject_garbage() {
        let s = Scale::parse(Some("1.6:1.4:1.2"), Some("FROM_TYPICAL")).unwrap();
        assert_eq!(s.factors, [1.6, 1.4, 1.2]);
        assert_eq!(s.kind, ScaleType::Typ);
        assert_eq!(Scale::parse(None, None).unwrap(), Scale::IDENTITY);
        assert!(Scale::parse(Some("1:2"), None).is_err());
        assert!(Scale::parse(Some("1:x:3"), None).is_err());
        assert!(Scale::parse(Some("1:-2:3"), None).is_err());
        assert!(Scale::parse(None, Some("FROM_NOWHERE")).is_err());
    }

    #[test]
    fn ticks_round_to_the_precision_then_scale_to_the_tick() {
        // 3.5 ns, 1 ps tick, 1 ps precision.
        assert_eq!(to_ticks(3.5, -9, -12, -12), 3500);
        // Precision 1 ns first: 3.5 -> 4 (round half away), then 1000 ticks per ns.
        assert_eq!(to_ticks(3.5, -9, -9, -12), 4000);
        assert_eq!(to_ticks(-3.5, -9, -9, -12), -4000);
        // 1 ns SDF unit, 10 ns design tick is impossible (tick is the finest); equal tick:
        assert_eq!(to_ticks(2.0, -9, -9, -9), 2);
    }

    // -- the LRM's own worked examples ------------------------------------------------

    fn dv(delay: Rvalue) -> DelVal {
        DelVal { delay, pulse: None }
    }

    fn dvp(delay: Rvalue, r: Rvalue, e: Rvalue) -> DelVal {
        DelVal {
            delay,
            pulse: Some((r, e)),
        }
    }

    fn one(v: f64) -> Rvalue {
        Rvalue::Single(v)
    }

    // 1 SDF unit = 10 ticks, so the LRM's one-decimal values are exact.
    fn tens(v: f64) -> i64 {
        (v * 10.0).round() as i64
    }

    const SEL: Selector = Selector {
        mtm: Mtm::Typ,
        scale: Scale::IDENTITY,
    };

    fn times(delay: u64, reject: u64, error: u64) -> PathTimes {
        PathTimes {
            delays: PathDelaySet::uniform(delay),
            reject: PathDelaySet::uniform(reject),
            error: PathDelaySet::uniform(error),
            floor: 0,
        }
    }

    fn rise_fall(t: &PathTimes) -> ((u64, u64, u64), (u64, u64, u64)) {
        (
            t.limits(Bit4::Zero, Bit4::One),
            t.limits(Bit4::One, Bit4::Zero),
        )
    }

    fn pulse(reject: f64, error: f64) -> PathPulse {
        PathPulse {
            percent: false,
            input: None,
            output: None,
            reject: one(reject),
            error: one(error),
        }
    }

    fn io(delvals: &[DelVal], pct: PulsePercent) -> SlotUpdate {
        iopath_update(delvals, &SEL, pct, &tens).unwrap()
    }

    #[test]
    fn lrm_32_5_iopath_after_pathpulse_overwrites_the_limits() {
        // (PATHPULSE A Z (2.1) (3.4)) then (IOPATH A Z (3.5) (6.1)).
        let mut t = times(0, 0, 0);
        let pp = pathpulse_update(&pulse(2.1, 3.4), &SEL, &tens, &t.delays);
        apply_update(&mut t, &pp, DeltaMode::Absolute);
        assert_eq!(t.reject.transitions(), [21; 12]);
        assert_eq!(t.error.transitions(), [34; 12]);
        let up = io(&[dv(one(3.5)), dv(one(6.1))], PulsePercent::DEFAULT);
        apply_update(&mut t, &up, DeltaMode::Absolute);
        // Rise 3.5 with limits 3.5 (100%), fall 6.1 with limits 6.1: the 2.1 / 3.4 are gone.
        assert_eq!(rise_fall(&t), ((35, 35, 35), (61, 61, 61)));
    }

    #[test]
    fn lrm_32_5_empty_parentheses_hold_the_pulse_limits() {
        // (PATHPULSE A Z (2.1) (3.4)) then (IOPATH A Z ((3.5) () ()) ((6.1) () ())).
        let mut t = times(0, 0, 0);
        let pp = pathpulse_update(&pulse(2.1, 3.4), &SEL, &tens, &t.delays);
        apply_update(&mut t, &pp, DeltaMode::Absolute);
        let e = Rvalue::Empty;
        let up = io(
            &[dvp(one(3.5), e, e), dvp(one(6.1), e, e)],
            PulsePercent::DEFAULT,
        );
        apply_update(&mut t, &up, DeltaMode::Absolute);
        // The delays moved; the limits stayed 2.1 / 3.4 (read below the delay: 3.5 and 6.1
        // are above both).
        assert_eq!(t.delays.of(Bit4::Zero, Bit4::One), 35);
        assert_eq!(t.delays.of(Bit4::One, Bit4::Zero), 61);
        assert_eq!(rise_fall(&t), ((35, 21, 34), (61, 21, 34)));
    }

    #[test]
    fn lrm_32_5_the_combined_form_gives_the_same_result() {
        // (IOPATH A Z ((3.5) (2.1) (3.4)) ((6.1) (2.1) (3.4))).
        let mut t = times(0, 0, 0);
        let up = io(
            &[
                dvp(one(3.5), one(2.1), one(3.4)),
                dvp(one(6.1), one(2.1), one(3.4)),
            ],
            PulsePercent::DEFAULT,
        );
        apply_update(&mut t, &up, DeltaMode::Absolute);
        assert_eq!(rise_fall(&t), ((35, 21, 34), (61, 21, 34)));
    }

    #[test]
    fn lrm_32_7_default_limits_use_the_percentage_settings() {
        // Reject 40%, error 80%: (IOPATH A Z (5)) = delay 5, reject 2, error 4.
        let mut t = times(0, 0, 0);
        let pct = PulsePercent {
            reject: 40.0,
            error: 80.0,
        };
        apply_update(&mut t, &io(&[dv(one(5.0))], pct), DeltaMode::Absolute);
        assert_eq!(rise_fall(&t), ((50, 20, 40), (50, 20, 40)));
        // And at the default 100%: the limits are the delay.
        let mut t = times(0, 0, 0);
        apply_update(
            &mut t,
            &io(&[dv(one(5.0))], PulsePercent::DEFAULT),
            DeltaMode::Absolute,
        );
        assert_eq!(rise_fall(&t), ((50, 50, 50), (50, 50, 50)));
    }

    #[test]
    fn lrm_32_7_empty_pulse_values_on_a_zero_delay_give_zero_limits() {
        // The path was 0 / 0 / 0: ((5) () ()) -> delay 5, limits 0.
        let mut t = times(0, 0, 0);
        let e = Rvalue::Empty;
        apply_update(
            &mut t,
            &io(&[dvp(one(5.0), e, e)], PulsePercent::DEFAULT),
            DeltaMode::Absolute,
        );
        assert_eq!(rise_fall(&t), ((50, 0, 0), (50, 0, 0)));
    }

    #[test]
    fn lrm_32_7_increment_cannot_take_a_limit_below_zero() {
        // Limits 3 / 3, (IOPATH A Z (() (-4) (-5))) in INCREMENT: both become 0.
        let mut t = PathTimes {
            delays: PathDelaySet::uniform(100),
            reject: PathDelaySet::uniform(30),
            error: PathDelaySet::uniform(30),
            floor: 0,
        };
        let e = Rvalue::Empty;
        let up = io(&[dvp(e, one(-4.0), one(-5.0))], PulsePercent::DEFAULT);
        apply_update(&mut t, &up, DeltaMode::Increment);
        assert_eq!(
            t.delays.transitions(),
            [100; 12],
            "the held delay is untouched"
        );
        assert_eq!(t.reject.transitions(), [0; 12]);
        assert_eq!(t.error.transitions(), [0; 12]);
    }

    #[test]
    fn lrm_32_7_pathpulse_above_the_delay_acts_as_the_delay() {
        // Delay 3, PATHPULSE (5) (9): both limits read as 3, but are stored as given.
        let mut t = times(30, 30, 30);
        let pp = pathpulse_update(&pulse(5.0, 9.0), &SEL, &tens, &t.delays);
        apply_update(&mut t, &pp, DeltaMode::Absolute);
        assert_eq!(
            t.delays.transitions(),
            [30; 12],
            "PATHPULSE does not touch the delay"
        );
        assert_eq!(t.reject.transitions(), [50; 12]);
        assert_eq!(t.limits(Bit4::Zero, Bit4::One), (30, 30, 30));
        // A later INCREMENT of the delay makes the stored limits valid again.
        let up = io(&[dv(one(4.0))], PulsePercent::DEFAULT);
        apply_update(&mut t, &up, DeltaMode::Increment);
        // (the 100% default limit increments too: 50 + 40 and 90 + 40 -- but are stored
        // sums, so read against the new delay of 70)
        assert_eq!(t.delays.of(Bit4::Zero, Bit4::One), 70);
        assert_eq!(t.limits(Bit4::Zero, Bit4::One), (70, 70, 70));
    }

    #[test]
    fn pathpulse_percent_is_a_percentage_of_the_current_delay() {
        let mut t = times(50, 50, 50);
        let pp = PathPulse {
            percent: true,
            input: None,
            output: None,
            reject: one(40.0),
            error: one(80.0),
        };
        let up = pathpulse_update(&pp, &SEL, &tens, &t.delays);
        apply_update(&mut t, &up, DeltaMode::Absolute);
        assert_eq!(t.reject.transitions(), [20; 12]);
        assert_eq!(t.error.transitions(), [40; 12]);
        assert_eq!(t.delays.transitions(), [50; 12]);
    }

    #[test]
    fn a_held_pathpulse_value_changes_nothing() {
        let mut t = times(50, 11, 22);
        let pp = PathPulse {
            percent: false,
            input: None,
            output: None,
            reject: Rvalue::Empty,
            error: Rvalue::Empty,
        };
        let up = pathpulse_update(&pp, &SEL, &tens, &t.delays);
        apply_update(&mut t, &up, DeltaMode::Absolute);
        assert_eq!(t.reject.transitions(), [11; 12]);
        assert_eq!(t.error.transitions(), [22; 12]);
    }

    #[test]
    fn increment_adds_to_the_delay_and_a_negative_result_is_zero() {
        let mut t = times(20, 20, 20);
        apply_update(
            &mut t,
            &io(&[dv(one(1.0))], PulsePercent::DEFAULT),
            DeltaMode::Increment,
        );
        assert_eq!(t.delays.transitions(), [30; 12]);
        apply_update(
            &mut t,
            &io(&[dv(one(-9.0))], PulsePercent::DEFAULT),
            DeltaMode::Increment,
        );
        assert_eq!(t.delays.transitions(), [0; 12], "30 - 90 clamps at 0");
        assert_eq!(t.reject.transitions(), [0; 12]);
    }

    #[test]
    fn a_negative_absolute_delay_is_zero() {
        let mut t = times(20, 20, 20);
        apply_update(
            &mut t,
            &io(&[dv(one(-3.0))], PulsePercent::DEFAULT),
            DeltaMode::Absolute,
        );
        assert_eq!(t.delays.transitions(), [0; 12]);
    }

    #[test]
    fn the_negative_timing_floor_is_kept() {
        let mut t = times(20, 20, 20);
        t.floor = 40;
        apply_update(
            &mut t,
            &io(&[dv(one(1.0))], PulsePercent::DEFAULT),
            DeltaMode::Absolute,
        );
        assert_eq!(
            t.delays.transitions(),
            [40; 12],
            "raised to the floor, LRM 31.9.1"
        );
    }

    #[test]
    fn the_error_limit_is_never_below_the_reject_limit() {
        let mut t = times(100, 100, 100);
        let up = io(&[dvp(one(10.0), one(8.0), one(3.0))], PulsePercent::DEFAULT);
        apply_update(&mut t, &up, DeltaMode::Absolute);
        assert_eq!(t.reject.transitions(), [80; 12]);
        assert_eq!(t.error.transitions(), [80; 12]);
    }

    #[test]
    fn min_typ_max_values_go_through_mtm_spec_and_scaling() {
        let rv = Rvalue::Triple {
            min: Some(1.0),
            typ: Some(2.0),
            max: Some(3.0),
        };
        let sel = Selector {
            mtm: Mtm::Max,
            scale: Scale {
                factors: [1.0, 1.0, 2.0],
                kind: ScaleType::Mtm,
            },
        };
        let up = iopath_update(&[dv(rv)], &sel, PulsePercent::DEFAULT, &tens).unwrap();
        assert_eq!(up.delay, [Some(60); 12], "max 3 x2 = 6 units of 10 ticks");
    }

    #[test]
    fn an_iopath_with_a_bad_value_count_is_an_error() {
        let err = iopath_update(
            &[dv(one(1.0)), dv(one(2.0)), dv(one(3.0)), dv(one(4.0))],
            &SEL,
            PulsePercent::DEFAULT,
            &tens,
        )
        .unwrap_err();
        assert!(err.contains("4 values"), "{err}");
    }

    fn device(vals: &[f64], cur: [u64; 3], mode: DeltaMode) -> [u64; 3] {
        let dvs: Vec<DelVal> = vals.iter().map(|&v| dv(one(v))).collect();
        let up = iopath_update(&dvs, &SEL, PulsePercent::DEFAULT, &tens).unwrap();
        device_delays(cur, &up.delay, mode)
    }

    // A primitive's three delays from 1, 2 and 3 SDF values are Table 28-9's expansion of a
    // gate delay list: one value is all three, two give a turn-off of min(rise, fall).
    #[test]
    fn device_maps_one_two_and_three_values_onto_rise_fall_turn_off() {
        let abs = DeltaMode::Absolute;
        assert_eq!(device(&[2.0], [7, 7, 7], abs), [20, 20, 20]);
        assert_eq!(device(&[5.0, 3.0], [7, 7, 7], abs), [50, 30, 30]);
        assert_eq!(device(&[3.0, 5.0], [7, 7, 7], abs), [30, 50, 30]);
        assert_eq!(device(&[5.0, 3.0, 4.0], [7, 7, 7], abs), [50, 30, 40]);
    }

    #[test]
    fn device_increment_adds_to_each_delay_and_floors_at_zero() {
        let inc = DeltaMode::Increment;
        assert_eq!(device(&[1.0, 2.0, 3.0], [10, 20, 30], inc), [20, 40, 60]);
        assert_eq!(device(&[-5.0], [10, 20, 30], inc), [0, 0, 0]);
    }

    #[test]
    fn device_holds_a_delay_whose_value_is_empty_parentheses() {
        // `(5) () (4)`: the fall (and so the turn-off's `1->z` operand) is held, and a held
        // operand holds the turn-off.
        let up = iopath_update(
            &[dv(one(5.0)), dv(Rvalue::Empty), dv(one(4.0))],
            &SEL,
            PulsePercent::DEFAULT,
            &tens,
        )
        .unwrap();
        // 3 values: 0->z is v3 and 1->z is v3 as well, so the turn-off is v3 = 4 (not held);
        // the fall is v2 and holds.
        assert_eq!(
            device_delays([7, 8, 9], &up.delay, DeltaMode::Absolute),
            [50, 8, 40]
        );
        // Two values `(5) ()`: 1->z is v2 (held), so the turn-off is held too.
        let up = iopath_update(
            &[dv(one(5.0)), dv(Rvalue::Empty)],
            &SEL,
            PulsePercent::DEFAULT,
            &tens,
        )
        .unwrap();
        assert_eq!(
            device_delays([7, 8, 9], &up.delay, DeltaMode::Absolute),
            [50, 8, 9]
        );
    }
}