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
//! The run-wide timing options (IEEE 1800-2023 clauses 30-32's "simulators may provide an
//! option" text), as set on the `vj run` command line and threaded through
//! [`crate::run::run_design_with_options`] to every consumer.
//!
//! **Precedence (SD-C / T31, `docs/superpowers/plans/2026-10-03-sdf.md` decision 9).** The pulse
//! controls fall in two groups with opposite orders.
//!
//! The pulse LIMITS (reject / error): the first present of
//!
//! 1. an SDF annotation (`$sdf_annotate`: a `((d) (r) (e))` pulse form, `PATHPULSE`,
//!    `PATHPULSEPERCENT`; LRM 32.7);
//! 2. the design's own `PATHPULSE$` declaration (LRM 30.7.1);
//! 3. the global percentage options (this module; LRM 30.7.2);
//! 4. the built-in default (limits equal to the delay).
//!
//! The pulse STYLE and `showcancelled` mode: the LRM states the order itself. 30.7.4.1: "The pulse
//! style invocation options take precedence over pulse style specify block declarations"; 30.7.4.2:
//! "The showcancelled invocation options take precedence over the showcancelled specify block
//! declarations". So a given `--pulse-style` / `--showcancelled` / `--noshowcancelled` overrides
//! every `pulsestyle_*` / `showcancelled` / `noshowcancelled` declaration (on its own axis), and
//! only when the option is absent do the declarations, then the built-in default (on-event,
//! `noshowcancelled`), decide. SDF has no style or showcancelled construct.
//!
//! An SDF annotation that names only a delay still sets that path's limits, to the invocation
//! option's percentage of the new delay (LRM 32.7: "by default, these limits are 100%, but they
//! can be modified through invocation options").

use vj_sim::netlist::specify::PulseStyle;

/// What LRM Table 32-5's `TOOL_CONTROL` (the `mtm_spec` default: "annotates the value as selected
/// by the simulator") means in this run: which member of every min:typ:max triple is annotated.
/// `--sdf-mtm` on the command line; typical when unset (the LRM leaves the default open).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SdfMtm {
    /// The minimum value of each triple.
    Minimum,
    /// The typical value of each triple.
    #[default]
    Typical,
    /// The maximum value of each triple.
    Maximum,
}

/// Run-wide options of the timing checks and of timing annotation. Threaded from the command
/// line (`main.rs`) through [`crate::run::run_design_with_options`]; `Default` is the LRM's own
/// default behaviour, so every caller that names no option gets it.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TimingOptions {
    /// LRM 31.8: "Simulators may provide an option causing vectors in timing checks to
    /// result in the creation of multiple single-bit timing checks." Off (the default),
    /// a vector terminal is ONE event (any bit changing) of ONE check; on, [`crate::timingcheck`]'s
    /// `plan` makes `M*N` single-bit checks for a two-signal check and `N` for `$width` /
    /// `$period`, all sharing the notifier. `--timing-check-per-bit` on the command line.
    pub per_bit_vectors: bool,
    /// LRM 31.9.4: "the ability of simulators to handle negative values in `$setuphold` and
    /// `$recrem` timing checks shall be enabled with an invocation option". Off (the default),
    /// the `delayed_reference` / `delayed_data` signals are plain copies of the originals (no
    /// delay is solved, no module path is raised, no signal is implicitly delayed) and a
    /// negative limit behaves as the positive-limit check does with a limit of 0 -- the same
    /// planning with every delay at 0. On, `negative_timing` solves the delays (31.9.1) and
    /// the conditions follow them (31.9.2). `--enable-negative-timing-checks` on the command
    /// line.
    pub negative_timing_checks: bool,
    /// LRM 30.7.2 / 32.7: the default reject limit of a module path or annotated delay, as a
    /// percentage (0 to 100) of the delay. `None` is the LRM's 100%.
    /// `--timing-reject-limit-pct=N` on the command line.
    pub reject_limit_pct: Option<f64>,
    /// LRM 30.7.2 / 32.7: the default error limit, the same way. An error limit below the reject
    /// limit is raised to it. `--timing-error-limit-pct=N` on the command line.
    pub error_limit_pct: Option<f64>,
    /// LRM 30.7.4.1: the pulse style of every output, overriding any `pulsestyle_*` declaration
    /// ("The pulse style invocation options take precedence"). `None`: no option given, so the
    /// declarations (then on-event) decide. `--pulse-style=on-event|on-detect` on the command line.
    pub pulse_style: Option<PulseStyle>,
    /// LRM 30.7.4.2: whether every output shows a negative pulse as `x`, overriding any
    /// `showcancelled`/`noshowcancelled` declaration ("The showcancelled invocation options take
    /// precedence"). `None`: no option given, so the declarations (then `noshowcancelled`) decide.
    /// `--showcancelled` / `--noshowcancelled` on the command line.
    pub showcancelled: Option<bool>,
    /// LRM Table 32-5: what `TOOL_CONTROL` selects, which is both what an elided `mtm_spec`
    /// and an explicit `"TOOL_CONTROL"` mean. `--sdf-mtm=minimum|typical|maximum`.
    pub sdf_mtm: Option<SdfMtm>,
}

impl TimingOptions {
    /// The reject percentage in force (LRM 32.7's default is 100).
    pub fn reject_pct(&self) -> f64 {
        self.reject_limit_pct.unwrap_or(100.0)
    }

    /// The error percentage in force (LRM 32.7's default is 100).
    pub fn error_pct(&self) -> f64 {
        self.error_limit_pct.unwrap_or(100.0)
    }

    /// The pulse style the option selects where no declaration can intervene (the interconnect
    /// delay lines have none): on-event when no option was given.
    pub fn default_pulse_style(&self) -> PulseStyle {
        self.pulse_style.unwrap_or_default()
    }

    /// Whether the option selects `showcancelled` where no declaration can intervene (off when no
    /// option was given).
    pub fn default_showcancelled(&self) -> bool {
        self.showcancelled.unwrap_or(false)
    }

    /// What `TOOL_CONTROL` selects in this run (typical when `--sdf-mtm` was not given).
    pub fn tool_control(&self) -> SdfMtm {
        self.sdf_mtm.unwrap_or_default()
    }

    /// Reads one `vj run` argument. `Ok(true)`: it was one of the timing options and is
    /// recorded; `Ok(false)`: it is not a timing option (the caller handles it); `Err`: it is
    /// one, but malformed -- a missing or bad value, or a repeat that contradicts an earlier
    /// occurrence (a repeat that agrees is harmless).
    pub fn parse_arg(&mut self, arg: &str) -> Result<bool, String> {
        let (name, value) = match arg.split_once('=') {
            Some((n, v)) => (n, Some(v)),
            None => (arg, None),
        };
        match name {
            "--timing-check-per-bit" => {
                no_value(name, value)?;
                self.per_bit_vectors = true;
            }
            "--enable-negative-timing-checks" => {
                no_value(name, value)?;
                self.negative_timing_checks = true;
            }
            "--timing-reject-limit-pct" => {
                set_once(name, &mut self.reject_limit_pct, percent(name, value)?)?;
            }
            "--timing-error-limit-pct" => {
                set_once(name, &mut self.error_limit_pct, percent(name, value)?)?;
            }
            "--pulse-style" => {
                let style = match required(name, value)? {
                    "on-event" => PulseStyle::OnEvent,
                    "on-detect" => PulseStyle::OnDetect,
                    other => {
                        return Err(format!(
                            "{name}={other}: expected on-event or on-detect (LRM 30.7.4.1)"
                        ));
                    }
                };
                set_once(name, &mut self.pulse_style, style)?;
            }
            "--showcancelled" => {
                no_value(name, value)?;
                set_once(name, &mut self.showcancelled, true)?;
            }
            "--noshowcancelled" => {
                no_value(name, value)?;
                set_once(name, &mut self.showcancelled, false)?;
            }
            "--sdf-mtm" => {
                let mtm = match required(name, value)?.to_ascii_lowercase().as_str() {
                    "minimum" => SdfMtm::Minimum,
                    "typical" => SdfMtm::Typical,
                    "maximum" => SdfMtm::Maximum,
                    other => {
                        return Err(format!(
                            "{name}={other}: expected minimum, typical or maximum (LRM Table 32-5)"
                        ));
                    }
                };
                set_once(name, &mut self.sdf_mtm, mtm)?;
            }
            _ => return Ok(false),
        }
        Ok(true)
    }
}

impl TimingOptions {
    /// This run's options, as `vj build-aot`'s own image header records
    /// them (`vj_sim::image::TimingOptionsImage`): a lossless, plain
    /// encoding of every field above (a percentage's IEEE bits, a
    /// style/corner's own small ordinal) -- `Self::conflicts_with`'s own
    /// counterpart, read back by `vj run-aot`.
    pub fn to_image(&self) -> vj_sim::image::TimingOptionsImage {
        vj_sim::image::TimingOptionsImage {
            per_bit_vectors: self.per_bit_vectors,
            negative_timing_checks: self.negative_timing_checks,
            reject_limit_pct: self.reject_limit_pct.map(f64::to_bits),
            error_limit_pct: self.error_limit_pct.map(f64::to_bits),
            pulse_style: self.pulse_style.map(pulse_style_ordinal),
            showcancelled: self.showcancelled,
            sdf_mtm: self.sdf_mtm.map(sdf_mtm_ordinal),
        }
    }

    /// Every flag `self` was explicitly given (a `parse_arg` call that
    /// returned `Ok(true)`, never a default) that disagrees with `built`
    /// (`Self::to_image`'s own output, decoded from a `build-aot` library's
    /// embedded image) -- named, human-readable conflicts for `vj
    /// run-aot` to refuse with. The library was already compiled under its
    /// own choice (LRM 30.7.2/30.7.4/32: these options are baked into the
    /// planned pulse widths, path delays and `TOOL_CONTROL` selection), so a
    /// disagreeing flag at run time can only be wrong, never newly honored;
    /// a flag `self` never mentions (every `None`/`false` field, the "no
    /// option given" default) never conflicts, whatever the library used --
    /// exactly `parse_arg`'s own "an absent option leaves the declarations
    /// [here: the build's own choice] alone" rule, one level up.
    pub fn conflicts_with(&self, built: &vj_sim::image::TimingOptionsImage) -> Vec<String> {
        let mut out = Vec::new();
        if self.per_bit_vectors && !built.per_bit_vectors {
            out.push("--timing-check-per-bit: the library was built without it".to_string());
        }
        if self.negative_timing_checks && !built.negative_timing_checks {
            out.push(
                "--enable-negative-timing-checks: the library was built without it".to_string(),
            );
        }
        if let Some(pct) = self.reject_limit_pct {
            let got = built.reject_limit_pct.map(f64::from_bits).unwrap_or(100.0);
            if pct != got {
                out.push(format!(
                    "--timing-reject-limit-pct={pct}: the library was built with {got}"
                ));
            }
        }
        if let Some(pct) = self.error_limit_pct {
            let got = built.error_limit_pct.map(f64::from_bits).unwrap_or(100.0);
            if pct != got {
                out.push(format!(
                    "--timing-error-limit-pct={pct}: the library was built with {got}"
                ));
            }
        }
        if let Some(style) = self.pulse_style {
            let want = pulse_style_ordinal(style);
            let got = built.pulse_style.unwrap_or(0);
            if want != got {
                out.push(format!(
                    "--pulse-style={}: the library was built with --pulse-style={}",
                    pulse_style_name(want),
                    pulse_style_name(got)
                ));
            }
        }
        if let Some(sc) = self.showcancelled {
            let got = built.showcancelled.unwrap_or(false);
            if sc != got {
                out.push(format!(
                    "--{}showcancelled: the library was built with --{}showcancelled",
                    if sc { "" } else { "no" },
                    if got { "" } else { "no" },
                ));
            }
        }
        if let Some(mtm) = self.sdf_mtm {
            let want = sdf_mtm_ordinal(mtm);
            let got = built.sdf_mtm.unwrap_or(1);
            if want != got {
                out.push(format!(
                    "--sdf-mtm={}: the library was built with --sdf-mtm={}",
                    sdf_mtm_name(want),
                    sdf_mtm_name(got)
                ));
            }
        }
        out
    }
}

fn pulse_style_ordinal(s: PulseStyle) -> u8 {
    match s {
        PulseStyle::OnEvent => 0,
        PulseStyle::OnDetect => 1,
    }
}

fn pulse_style_name(v: u8) -> &'static str {
    if v == 0 { "on-event" } else { "on-detect" }
}

fn sdf_mtm_ordinal(m: SdfMtm) -> u8 {
    match m {
        SdfMtm::Minimum => 0,
        SdfMtm::Typical => 1,
        SdfMtm::Maximum => 2,
    }
}

fn sdf_mtm_name(v: u8) -> &'static str {
    match v {
        0 => "minimum",
        2 => "maximum",
        _ => "typical",
    }
}

/// `value` of an option that takes none.
fn no_value(name: &str, value: Option<&str>) -> Result<(), String> {
    match value {
        None => Ok(()),
        Some(_) => Err(format!("{name} takes no value")),
    }
}

/// `value` of an option that needs one.
fn required<'a>(name: &str, value: Option<&'a str>) -> Result<&'a str, String> {
    value.ok_or_else(|| format!("{name} needs a value: {name}=VALUE"))
}

/// A percentage: a finite number from 0 to 100 (LRM 30.7.2, 32.7: the limits are a percentage of
/// the delay, and a limit above the delay would never be reached).
fn percent(name: &str, value: Option<&str>) -> Result<f64, String> {
    let text = required(name, value)?;
    let pct: f64 = text
        .parse()
        .map_err(|_| format!("{name}={text}: not a number"))?;
    if !pct.is_finite() || !(0.0..=100.0).contains(&pct) {
        return Err(format!(
            "{name}={text}: a percentage from 0 to 100 is required"
        ));
    }
    Ok(pct)
}

/// Records `new` in `slot`; a second, different value for the same option is a contradiction
/// (implementation-defined: an error rather than a silent "last one wins").
fn set_once<T: PartialEq>(name: &str, slot: &mut Option<T>, new: T) -> Result<(), String> {
    match slot {
        Some(old) if *old != new => Err(format!(
            "{name} (or its opposite) was given twice with different settings"
        )),
        _ => {
            *slot = Some(new);
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parsed(args: &[&str]) -> Result<TimingOptions, String> {
        let mut o = TimingOptions::default();
        for a in args {
            assert!(o.parse_arg(a)?, "{a} should be a timing option");
        }
        Ok(o)
    }

    #[test]
    fn default_is_the_lrm_behaviour() {
        let o = TimingOptions::default();
        assert_eq!((o.reject_pct(), o.error_pct()), (100.0, 100.0));
        assert_eq!(o.default_pulse_style(), PulseStyle::OnEvent);
        assert!(!o.default_showcancelled());
        assert_eq!(o.tool_control(), SdfMtm::Typical);
        assert!(!o.per_bit_vectors && !o.negative_timing_checks);
    }

    #[test]
    fn every_flag_parses_into_its_own_field() {
        let o = parsed(&["--timing-check-per-bit"]).unwrap();
        assert!(o.per_bit_vectors);
        let o = parsed(&["--enable-negative-timing-checks"]).unwrap();
        assert!(o.negative_timing_checks);
        let o = parsed(&["--timing-reject-limit-pct=40"]).unwrap();
        assert_eq!((o.reject_pct(), o.error_pct()), (40.0, 100.0));
        let o = parsed(&["--timing-error-limit-pct=12.5"]).unwrap();
        assert_eq!((o.reject_pct(), o.error_pct()), (100.0, 12.5));
        let o = parsed(&["--pulse-style=on-detect"]).unwrap();
        assert_eq!(o.default_pulse_style(), PulseStyle::OnDetect);
        let o = parsed(&["--pulse-style=on-event"]).unwrap();
        assert_eq!(o.pulse_style, Some(PulseStyle::OnEvent));
        let o = parsed(&["--showcancelled"]).unwrap();
        assert_eq!(o.showcancelled, Some(true));
        let o = parsed(&["--noshowcancelled"]).unwrap();
        assert_eq!(o.showcancelled, Some(false));
        for (text, want) in [
            ("minimum", SdfMtm::Minimum),
            ("TYPICAL", SdfMtm::Typical),
            ("Maximum", SdfMtm::Maximum),
        ] {
            let o = parsed(&[&format!("--sdf-mtm={text}")]).unwrap();
            assert_eq!(o.tool_control(), want, "{text}");
        }
    }

    #[test]
    fn percentages_accept_the_closed_range_and_nothing_else() {
        assert_eq!(
            parsed(&["--timing-reject-limit-pct=0"])
                .unwrap()
                .reject_pct(),
            0.0
        );
        assert_eq!(
            parsed(&["--timing-error-limit-pct=100"])
                .unwrap()
                .error_pct(),
            100.0
        );
        for bad in [
            "--timing-reject-limit-pct=-1",
            "--timing-reject-limit-pct=100.5",
            "--timing-error-limit-pct=nan",
            "--timing-error-limit-pct=inf",
            "--timing-error-limit-pct=abc",
            "--timing-error-limit-pct=",
        ] {
            assert!(parsed(&[bad]).is_err(), "{bad} must be refused");
        }
    }

    #[test]
    fn a_missing_or_unwanted_value_is_an_error() {
        for bad in [
            "--timing-reject-limit-pct",
            "--timing-error-limit-pct",
            "--pulse-style",
            "--sdf-mtm",
            "--showcancelled=1",
            "--noshowcancelled=1",
            "--timing-check-per-bit=1",
            "--enable-negative-timing-checks=1",
            "--pulse-style=ondetect",
            "--sdf-mtm=tool_control",
            "--sdf-mtm=fast",
        ] {
            assert!(parsed(&[bad]).is_err(), "{bad} must be refused");
        }
    }

    #[test]
    fn contradictory_repeats_are_errors_and_agreeing_repeats_are_fine() {
        assert!(parsed(&["--showcancelled", "--noshowcancelled"]).is_err());
        assert!(parsed(&["--pulse-style=on-event", "--pulse-style=on-detect"]).is_err());
        assert!(
            parsed(&[
                "--timing-reject-limit-pct=10",
                "--timing-reject-limit-pct=20"
            ])
            .is_err()
        );
        assert!(parsed(&["--sdf-mtm=minimum", "--sdf-mtm=maximum"]).is_err());
        let o = parsed(&["--showcancelled", "--showcancelled"]).unwrap();
        assert_eq!(o.showcancelled, Some(true));
    }

    #[test]
    fn to_image_round_trips_every_field() {
        let o = parsed(&[
            "--timing-check-per-bit",
            "--enable-negative-timing-checks",
            "--timing-reject-limit-pct=40",
            "--timing-error-limit-pct=60",
            "--pulse-style=on-detect",
            "--showcancelled",
            "--sdf-mtm=minimum",
        ])
        .unwrap();
        let img = o.to_image();
        assert!(img.per_bit_vectors && img.negative_timing_checks);
        assert_eq!(img.reject_limit_pct, Some(40.0f64.to_bits()));
        assert_eq!(img.error_limit_pct, Some(60.0f64.to_bits()));
        assert_eq!(img.pulse_style, Some(1));
        assert_eq!(img.showcancelled, Some(true));
        assert_eq!(img.sdf_mtm, Some(0));
    }

    #[test]
    fn default_options_never_conflict_with_a_non_default_image() {
        let built = TimingOptions::default().to_image();
        assert!(TimingOptions::default().conflicts_with(&built).is_empty());
        let non_default = parsed(&["--pulse-style=on-detect", "--sdf-mtm=minimum"])
            .unwrap()
            .to_image();
        assert!(
            TimingOptions::default()
                .conflicts_with(&non_default)
                .is_empty(),
            "an unmentioned flag never conflicts, whatever the build used"
        );
    }

    #[test]
    fn an_agreeing_flag_never_conflicts() {
        let built = parsed(&["--pulse-style=on-detect"]).unwrap().to_image();
        let asked = parsed(&["--pulse-style=on-detect"]).unwrap();
        assert!(asked.conflicts_with(&built).is_empty());
    }

    #[test]
    fn a_disagreeing_flag_names_both_values() {
        let built = parsed(&["--pulse-style=on-event"]).unwrap().to_image();
        let asked = parsed(&["--pulse-style=on-detect"]).unwrap();
        let conflicts = asked.conflicts_with(&built);
        assert_eq!(conflicts.len(), 1);
        assert!(conflicts[0].contains("--pulse-style"));
        assert!(conflicts[0].contains("on-event"));
        assert!(conflicts[0].contains("on-detect"));

        let built = parsed(&["--sdf-mtm=minimum"]).unwrap().to_image();
        let asked = parsed(&["--sdf-mtm=maximum"]).unwrap();
        let conflicts = asked.conflicts_with(&built);
        assert_eq!(conflicts.len(), 1);
        assert!(conflicts[0].contains("minimum") && conflicts[0].contains("maximum"));

        let built = TimingOptions::default().to_image();
        let asked = parsed(&["--enable-negative-timing-checks"]).unwrap();
        let conflicts = asked.conflicts_with(&built);
        assert_eq!(conflicts.len(), 1);
        assert!(conflicts[0].contains("--enable-negative-timing-checks"));
    }

    #[test]
    fn an_argument_that_is_not_a_timing_option_is_left_to_the_caller() {
        let mut o = TimingOptions::default();
        assert_eq!(o.parse_arg("+plusarg"), Ok(false));
        assert_eq!(o.parse_arg("--sv-lib"), Ok(false));
        assert_eq!(o.parse_arg("design.c"), Ok(false));
        assert_eq!(o, TimingOptions::default());
    }
}