vj-sim 0.1.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
Documentation
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
//! Task 6 (sva T6): procedural clock inference, LRM 1800-2023 16.14.6
//! conditions (a)/(b)/(c) -- "A clock shall be inferred for the context of
//! an always or initial procedure that satisfies the following
//! requirements: (a) There is no blocking timing control in the
//! procedure. (b) There is exactly one event control in the procedure.
//! (c) One and only one event expression within the event control of the
//! procedure satisfies both [... two conditions ...]."
//!
//! **Deviation from the plan's §1.6 claim ("new static-analysis work with
//! no slang accessor -- `AnalyzedProcedure` doesn't expose this"), recorded
//! here as binding for this module.** `sv_lang::AnalyzedProcedure::
//! inferred_clock()` (`slang::analysis::AnalyzedProcedure::getInferredClock`,
//! backed by `DFAResults::inferClock` in the vendored C++,
//! `vendor/source/analysis/DFAResults.cpp`) turns out to implement
//! 16.14.6(a)-(c) **verbatim** -- its own source comments literally quote
//! "16.14.6: There must be no blocking timing controls and exactly one
//! event control" and then 16.14.6's two numbered sub-conditions word for
//! word. This was not assumed from the doc comment: this task compiled
//! all four of 16.14.6's own worked examples (the LRM's `r1`/`r2`/`r3`/`r4`
//! fragments, reproduced verbatim as this module's probe-corpus-style unit
//! tests below) through a live `Design`/`Analysis` and confirmed
//! `inferred_clock()` reproduces the LRM's own stated answer in all four
//! cases, including the one case (`r2`) where the LRM's answer is the
//! *qualified* event `posedge clock iff reset == 0`, not the simpler
//! `posedge reset` alternative, and the two cases (`r3`, `r4`) where the
//! LRM states no clock can be inferred at all.
//!
//! (`infer_structural_clock` below is the one documented exception: slang
//! analyzes no scope for a procedural checker instance's body, so it has
//! nothing to ask.)
//!
//! Given that, this module is a thin, typed wrapper around the existing
//! accessor -- never a second, independently-reasoned reimplementation of
//! the dataflow walk the plan's prose describes -- for the same reason
//! §1.1/§1.6 already give for reusing `AnalyzedAssertion::clock()` instead
//! of reimplementing 16.13.3's clock-flow algorithm: slang has already
//! done this analysis correctly, and a hand-rolled second copy could only
//! diverge from it, never improve on it.
//!
//! `inferred_clock()` itself only runs "if the procedure contains at least
//! one concurrent assertion" (its own doc comment) -- i.e. it is computed
//! lazily, exactly when 16.14.6 is actually relevant (a procedure with no
//! assertion needing an inferred clock has nothing for this function to
//! answer), so that gate is not a scoping gap for this task's purpose.
//!
//! **Correction (sva T6 review r1): the wrapped accessor is NOT a pure
//! (a)/(b)/(c) signal, and this module cannot make it one.** The paragraph
//! above establishes that `DFAResults::inferClock` -- called first --
//! implements (a)-(c) verbatim. But `AnalyzedProcedure`'s constructor
//! (`vendor/source/analysis/AnalyzedProcedure.cpp`, ~lines 54-66) does not
//! stop there: when `inferClock` returns null it unconditionally falls
//! through to `scope->getCompilation().getDefaultClocking(*scope)` and
//! assigns *that* to the same `inferredClock` field `getInferredClock()`
//! later returns. That is LRM 16.15's default-clocking fallback ("If no
//! clock can be inferred from the procedural context, then the clocks
//! shall be inferred from the default clocking"), folded into the exact
//! same return value as the (a)-(c) result, with nothing in the C++ or the
//! Rust `inferred_clock()` surface that says which path produced it.
//!
//! This was verified live, not just read off the C++: an LRM `r3`-shaped
//! procedure (16.14.6(a)-(c) fails -- the qualifying edge expression has no
//! edge identifier) placed in a module that also declares `default
//! clocking cb @(posedge other_sig); endclocking` makes
//! `infer_procedural_clock` return `Ok(Some(_))` referencing `other_sig`,
//! not `Ok(None)` -- see
//! `tests::default_clocking_fallback_is_indistinguishable_from_abc` below.
//!
//! sv-lang 0.1.9 exposes no lower-level accessor that would let this module
//! split the two apart: there is no bound
//! `Compilation::getDefaultClocking`, and `ClockingBlockSymbol::isDefault`
//! (present on the C++ struct) has no FFI accessor either, so this module
//! cannot independently ask "does a default clocking block apply to this
//! scope" and subtract that case out. Reimplementing 16.14.6(a)-(c) by hand
//! to get a value `inferred_clock()` doesn't provide would be exactly the
//! second, independently-reasoned reimplementation this module's whole
//! design (the paragraph above) exists to avoid -- and sv-lang itself is a
//! pinned dependency this task does not modify.
//!
//! The documented, honest contract is therefore: `infer_procedural_clock`
//! returns the procedure's *effective* inferred clock -- 16.14.6(a)-(c)
//! when that succeeds, otherwise silently 16.15's default-clocking
//! fallback when one applies, otherwise `None` -- and a caller cannot tell
//! which of the two non-`None` cases produced a `Some` from the return
//! value alone. Any future caller that specifically needs the pure
//! (a)-(c) signal (e.g. a diagnostic that must say "no clock could be
//! inferred from the procedural context" per 16.14.6, distinct from "no
//! default clocking either") cannot get it from this function and must
//! say so explicitly rather than assume otherwise.

use std::collections::HashSet;

use sv_lang::kinds::{StatementKind, SymbolKind, TimingControlKind};
use sv_lang::{AnalyzedProcedure, EdgeKind, SemNode, Symbol, TimingControl};

use super::AnalysisError;
use crate::symid::{SymbolId, SymbolUid, is_value_name};

/// LRM 16.14.6 (a)/(b)/(c) for a procedure that slang's analysis does not list:
/// one inside a *procedural* checker instance's body (17.3). slang analyzes such
/// a body as a side effect of analyzing the enclosing procedure and files no scope
/// result for it, so [`infer_procedural_clock`] has no `AnalyzedProcedure` to ask
/// (and an `AnalyzedAssertion::procedure` handle into that scope is not safe to
/// follow: slang keeps the procedures in a `std::vector` and the assertions point
/// into it before it has finished growing). This is therefore the one place the
/// three conditions are decided here rather than by slang, mirroring
/// `DFAResults::inferClock` for the shapes a checker's procedure can take:
///
/// - (a) no blocking timing control: a delay, `wait`, or a timing control on
///   anything but a statement makes the answer `None` (the last is an error here
///   instead, since `a = #1 b` is not modelled by this walk);
/// - (b) exactly one event control (a nonblocking assignment's does not count);
/// - (c) exactly one `edge expr [iff cond]` event of it none of whose terms is
///   referenced anywhere else in the procedure other than inside assertion
///   statements or as a clocking event.
///
/// An event control that is not of the `edge expr` form (an event variable, a
/// clocking block name, `@*`) is an error rather than a guess, since that path
/// would need the event-variable and clocking-block rules of (c) as well.
///
/// Unlike [`infer_procedural_clock`], a `None` means only that the procedure
/// itself yields no clock; the default clocking (16.15) is for the caller.
pub fn infer_structural_clock<'d>(
    block: &Symbol<'d>,
) -> Result<Option<TimingControl<'d>>, AnalysisError> {
    let unsupported = |what: &str| {
        AnalysisError::Unsupported(format!(
            "clock inference for procedure `{}` of a procedural checker instance: {what}",
            block.hierarchical_path()
        ))
    };
    let Some(body) = crate::process::cfg::proc_body(block) else {
        return Ok(None);
    };
    let mut referenced: HashSet<SymbolId> = HashSet::new();
    let mut events: Vec<TimingControl<'d>> = Vec::new();
    let mut stack: Vec<SemNode<'d>> = vec![body.as_sem_node()];
    while let Some(n) = stack.pop() {
        if n.as_timing_control().is_some() {
            return Err(unsupported(
                "a timing control that is not on a statement (an intra-assignment delay) is not \
                 modelled",
            ));
        }
        if let Some(e) = n.as_expression() {
            if is_value_name(e.kind()) {
                if let Some(sym) = e.referenced_symbol() {
                    referenced.insert(sym.uid());
                }
                continue;
            }
        } else if let Some(stmt) = n.as_statement() {
            let kind = stmt.kind();
            if kind == StatementKind::ConcurrentAssertion {
                // 16.14.6(c): a use inside an assertion statement does not count.
                continue;
            }
            if kind == StatementKind::Wait
                || kind == StatementKind::WaitFork
                || kind == StatementKind::WaitOrder
            {
                return Ok(None);
            }
            if kind == StatementKind::Timed {
                let tc = stmt
                    .timing_control()
                    .ok_or_else(|| unsupported("a timed statement with no timing control"))?;
                if tc.kind() == TimingControlKind::SignalEvent
                    || tc.kind() == TimingControlKind::EventList
                {
                    events.push(tc);
                } else {
                    return Ok(None);
                }
                // The timing control is inspected above; only the statement it
                // guards is walked for further uses.
                stack.extend(
                    n.children()
                        .into_iter()
                        .filter(|c| c.as_timing_control().is_none()),
                );
                continue;
            }
        }
        stack.extend(n.children());
    }
    let [control] = events.as_slice() else {
        return Ok(None);
    };
    let candidates: Vec<TimingControl<'d>> = if control.kind() == TimingControlKind::EventList {
        let mut out = Vec::new();
        for c in control.children() {
            let Some(tc) = c
                .as_timing_control()
                .filter(|t| t.kind() == TimingControlKind::SignalEvent)
            else {
                return Err(unsupported(
                    "an event list with a member that is not a signal event",
                ));
            };
            out.push(tc);
        }
        out
    } else {
        vec![*control]
    };
    let mut found: Option<TimingControl<'d>> = None;
    for cand in candidates {
        let Some(expr) = cand.children().first().and_then(|c| c.as_expression()) else {
            return Err(unsupported("an event with no signal expression"));
        };
        if cand.edge() == EdgeKind::None {
            let is_event_or_clocking = expr.referenced_symbol().is_some_and(|s| {
                s.kind() == SymbolKind::ClockingBlock
                    || expr.expr_type().is_some_and(|t| t.is_event())
            });
            if is_event_or_clocking && cand.children().len() == 1 {
                return Err(unsupported(
                    "an event variable or clocking block as the clocking event is not modelled",
                ));
            }
            continue;
        }
        let mut shared = false;
        let mut terms: Vec<SemNode<'d>> = vec![expr.as_sem_node()];
        while let Some(t) = terms.pop() {
            if let Some(e) = t.as_expression()
                && is_value_name(e.kind())
            {
                shared |= e
                    .referenced_symbol()
                    .is_some_and(|s| referenced.contains(&s.uid()));
                continue;
            }
            terms.extend(t.children());
        }
        if !shared {
            if found.is_some() {
                return Ok(None);
            }
            found = Some(cand);
        }
    }
    Ok(found)
}

/// The procedure's *effective* inferred clock: LRM 16.14.6 (a)/(b)/(c) when
/// those three conditions are jointly satisfied, otherwise LRM 16.15's
/// default-clocking fallback when a default clocking block applies to
/// `proc`'s scope, otherwise `Ok(None)`. See the module doc's "Correction"
/// section for why these two sources cannot be told apart from this
/// return value, and why this module cannot change that given sv-lang
/// 0.1.9's exposed surface.
///
/// `Err` only if slang's analysis reports an inferred clock whose
/// `SemNode` is not itself a `TimingControl` -- an API-shape precondition
/// this function depends on (every real `inferred_clock()` result observed
/// in this task's own testing, and by the C++ header's own return type
/// `const ast::TimingControl*`, is one); surfaced as a loud, typed
/// `AnalysisError` rather than silently treated as "no clock inferred" if
/// a future `sv-lang` upgrade ever violates it.
pub fn infer_procedural_clock<'d>(
    proc: &AnalyzedProcedure<'d>,
) -> Result<Option<TimingControl<'d>>, AnalysisError> {
    match proc.inferred_clock() {
        None => Ok(None),
        Some(node) => node.as_timing_control().map(Some).ok_or_else(|| {
            AnalysisError::Unsupported(format!(
                "AnalyzedProcedure::inferred_clock() for procedure `{}` returned a SemNode of \
                 kind `{}` that is not a TimingControl -- sv-lang API shape assumption violated",
                proc.symbol().hierarchical_path(),
                node.kind_name(),
            ))
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sv_lang::kinds::TimingControlKind;
    use sv_lang::{AnalysisFlags, BinaryOp, Compilation, EdgeKind, Session};

    fn compile(src: &str) -> sv_lang::Design {
        let session = Session::new();
        let mut comp = Compilation::new(&session).expect("session");
        comp.add_source(src).expect("add_source");
        comp.compile().expect("compiles")
    }

    /// The design's one top-level module's one analyzed procedure (every
    /// fixture below has exactly one `always`/`always_ff` block).
    fn the_one_procedure<'d>(
        design: &'d sv_lang::Design,
        analysis: &'d sv_lang::Analysis<'d>,
    ) -> AnalyzedProcedure<'d> {
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance body");
        let mut procs: Vec<_> = analysis.procedures(body).collect();
        assert_eq!(procs.len(), 1, "fixture has exactly one procedure");
        procs.remove(0)
    }

    /// LRM 16.14.6, the `r1` example: `always @(posedge mclk) begin q <=
    /// d1; r1_p1: assert property (r1); r1_p2: assert property (@(posedge
    /// scanclk) r1); end` -- "the clocking event @(posedge mclk) is
    /// inferred as the clocking event of r1_p1" (r1_p2 carries its own
    /// explicit clock and is irrelevant to the *procedure's* inferred
    /// clock, which this function reports once per procedure).
    #[test]
    fn r1_p1_infers_posedge_mclk() {
        let design = compile(
            "module m;\n\
             logic mclk, scanclk, q, d, d1;\n\
             property r1; q != d; endproperty\n\
             always @(posedge mclk) begin\n\
                q <= d1;\n\
                r1_p1: assert property (r1);\n\
                r1_p2: assert property (@(posedge scanclk) r1);\n\
             end\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);

        let tc = infer_procedural_clock(&proc)
            .expect("no API-shape error")
            .expect("r1_p1's clock is inferred");
        assert_eq!(tc.kind(), TimingControlKind::SignalEvent);
        assert_eq!(tc.edge(), EdgeKind::PosEdge);
        let children = tc.children();
        assert_eq!(
            children.len(),
            1,
            "no `iff` qualifier on r1's inferred clock"
        );
        let signal = children[0].as_expression().expect("event expression");
        assert_eq!(
            signal.referenced_symbol().map(|s| s.name().to_string()),
            Some("mclk".to_string())
        );
    }

    /// LRM 16.14.6, the `r2` example: `always_ff @(posedge clock iff reset
    /// == 0 or posedge reset) begin cnt <= reset ? 0 : cnt + 1; q <=
    /// $past(d1); r2_p: assert property (r2); end` -- "the inferred clock
    /// is posedge clock iff reset == 0. The inferred clock is not posedge
    /// clock because posedge clock is a proper subexpression" and `reset`
    /// is disqualified from being its own candidate because it is read
    /// outside the clocking event (`cnt <= reset ? ...`).
    #[test]
    fn r2_infers_posedge_clock_iff_reset_eq_0() {
        let design = compile(
            "module m;\n\
             logic clock, reset, cnt, q, d1;\n\
             property r2; q != d1; endproperty\n\
             always_ff @(posedge clock iff reset == 0 or posedge reset) begin\n\
                cnt <= reset ? 0 : cnt + 1;\n\
                q <= $past(d1);\n\
                r2_p: assert property (r2);\n\
             end\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);

        let tc = infer_procedural_clock(&proc)
            .expect("no API-shape error")
            .expect("r2's clock is inferred");
        assert_eq!(tc.kind(), TimingControlKind::SignalEvent);
        assert_eq!(tc.edge(), EdgeKind::PosEdge);
        let children = tc.children();
        assert_eq!(
            children.len(),
            2,
            "r2's inferred clock keeps its `iff reset == 0` qualifier"
        );
        let signal = children[0].as_expression().expect("event expression");
        assert_eq!(
            signal.referenced_symbol().map(|s| s.name().to_string()),
            Some("clock".to_string())
        );
        let iff = children[1].as_expression().expect("iff condition");
        assert_eq!(iff.binary_op(), Some(BinaryOp::Equality));
        let lhs = iff.left().expect("iff lhs");
        assert_eq!(
            lhs.referenced_symbol().map(|s| s.name().to_string()),
            Some("reset".to_string()),
            "the iff condition is `reset == 0`, not `posedge reset`'s own term"
        );
    }

    /// LRM 16.14.6, the `r3` example: `always_ff @(clock iff reset == 0 or
    /// posedge reset) begin ... end` -- "no clock is inferred for the
    /// context of the always_ff ... The edge expression posedge reset
    /// cannot be inferred because reset is referenced within the
    /// procedure, and the expression clock iff reset == 0 cannot be
    /// inferred because it does not have an edge identifier."
    #[test]
    fn r3_infers_nothing_edge_identifier_missing() {
        let design = compile(
            "module m;\n\
             logic clock, reset, cnt, q, d1;\n\
             property r3; q != d1; endproperty\n\
             always_ff @(clock iff reset == 0 or posedge reset) begin\n\
                cnt <= reset ? 0 : cnt + 1;\n\
                q <= $past(d1);\n\
                r3_p: assert property (r3);\n\
             end\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);

        let inferred = infer_procedural_clock(&proc).expect("no API-shape error");
        assert!(
            inferred.is_none(),
            "r3: no clock inferred, per the LRM's own text"
        );
    }

    /// Pins down the module doc's "Correction" section: an LRM `r3`-shaped
    /// procedure (16.14.6(a)-(c) fails because `clock iff reset == 0`'s
    /// qualifying edge expression has no edge identifier -- same body as
    /// `r3_infers_nothing_edge_identifier_missing` above) placed in a
    /// module that *also* declares a default clocking block. Per 16.14.6
    /// alone this procedure has no inferable clock (exactly as `r3`
    /// proves above with no default clocking in scope); but because
    /// `AnalyzedProcedure::inferred_clock()` unconditionally folds in
    /// 16.15's default-clocking fallback, `infer_procedural_clock` returns
    /// `Some` here, referencing the default clocking block's own event
    /// (`other_sig`) rather than anything from the procedure's own event
    /// control. This is the behavior the module doc documents as the
    /// honest contract, not a bug this task's function can fix (see the
    /// module doc for why) -- the test exists so that a future `sv-lang`
    /// upgrade that changes this merge, or a future refactor of this
    /// function that silently reintroduces the false "pure (a)-(c)" claim
    /// this module used to make, breaks loudly here instead of going
    /// unnoticed.
    #[test]
    fn default_clocking_fallback_is_indistinguishable_from_abc() {
        let design = compile(
            "module m;\n\
             logic clock, reset, cnt, q, d1, other_sig;\n\
             property r3; q != d1; endproperty\n\
             clocking cb @(posedge other_sig);\n\
             endclocking\n\
             default clocking cb;\n\
             always_ff @(clock iff reset == 0 or posedge reset) begin\n\
                cnt <= reset ? 0 : cnt + 1;\n\
                q <= $past(d1);\n\
                r3_p: assert property (r3);\n\
             end\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);

        let tc = infer_procedural_clock(&proc)
            .expect("no API-shape error")
            .expect(
                "the default-clocking fallback fires even though 16.14.6(a)-(c) fails exactly \
                 as it does in r3_infers_nothing_edge_identifier_missing",
            );
        assert_eq!(tc.kind(), TimingControlKind::SignalEvent);
        assert_eq!(tc.edge(), EdgeKind::PosEdge);
        let children = tc.children();
        assert_eq!(
            children.len(),
            1,
            "the default clocking block's own event carries no `iff` qualifier"
        );
        let signal = children[0].as_expression().expect("event expression");
        assert_eq!(
            signal.referenced_symbol().map(|s| s.name().to_string()),
            Some("other_sig".to_string()),
            "the returned clock is the DEFAULT CLOCKING's event, not derived from the \
             procedure's own (a)-(c)-failing event control -- confirming the two sources are \
             folded together and cannot be told apart from this function's return value"
        );
    }

    /// A procedure with a sampled value function and NO concurrent assertion
    /// still gets its clock (LRM 16.9.3's "inferred from the procedural
    /// context"): `$past`/`$rose` in `always @(posedge clk)`.
    #[test]
    fn a_procedure_with_only_a_sampled_call_infers_its_clock() {
        let design = compile(
            "module m;\n\
             logic clk, b, r;\n\
             always @(posedge clk) r <= $rose(b);\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);
        let tc = infer_procedural_clock(&proc)
            .expect("no API-shape error")
            .expect("the always block's clock is inferred");
        assert_eq!(tc.edge(), EdgeKind::PosEdge);
    }

    /// LRM 16.14.6, the `r4` example: `always @(posedge mclk) begin #10 q
    /// <= d1; @(negedge mclk) #10 q1 <= !d1; r4_p: assert property (r4);
    /// end` -- "no clock is inferred due to multiple event controls and
    /// delays in the always procedure."
    #[test]
    fn r4_infers_nothing_multiple_event_controls_and_delays() {
        let design = compile(
            "module m;\n\
             logic mclk, q, q1, d1;\n\
             property r4; q != d1; endproperty\n\
             always @(posedge mclk) begin\n\
                #10 q <= d1;\n\
                @(negedge mclk)\n\
                #10 q1 <= !d1;\n\
                r4_p: assert property (r4);\n\
             end\n\
             endmodule\n",
        );
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);

        let inferred = infer_procedural_clock(&proc).expect("no API-shape error");
        assert!(
            inferred.is_none(),
            "r4: no clock inferred, per the LRM's own text"
        );
    }

    /// `infer_structural_clock` is run on the one procedure of a module here;
    /// the function itself only looks at the procedure's own statements, so a
    /// module procedure exercises the same walk as a procedural checker's.
    fn structural(src: &str) -> Result<Option<(EdgeKind, String)>, AnalysisError> {
        let design = compile(src);
        let analysis = design.analyze(AnalysisFlags::NONE, 1).expect("analysis");
        let proc = the_one_procedure(&design, &analysis);
        let block = proc.symbol();
        Ok(infer_structural_clock(&block)?.map(|tc| {
            let signal = tc.children()[0].as_expression().expect("event expression");
            let name = signal
                .referenced_symbol()
                .map(|s| s.name().to_string())
                .expect("a named clock");
            (tc.edge(), name)
        }))
    }

    /// 16.14.6, the `r1` shape: one edge event control, its signal read nowhere
    /// else, an assertion that does not count as a use of it.
    #[test]
    fn structural_clock_is_the_single_edge_event() {
        let inferred = structural(
            "module m;\n\
             logic mclk, q, d;\n\
             always @(posedge mclk) begin\n\
                q <= d;\n\
                p: assert property (q != d);\n\
             end\n\
             endmodule\n",
        )
        .expect("no error");
        assert_eq!(inferred, Some((EdgeKind::PosEdge, "mclk".to_string())));
    }

    /// 16.14.6(c): the clock term must not be referenced elsewhere in the
    /// procedure, so `q <= clk` disqualifies `posedge clk`.
    #[test]
    fn structural_clock_term_read_in_the_body_is_not_a_clock() {
        let inferred = structural(
            "module m;\n\
             logic clk, q;\n\
             always @(posedge clk) q <= clk;\n\
             endmodule\n",
        )
        .expect("no error");
        assert_eq!(inferred, None);
    }

    /// 16.14.6(a): a blocking delay in the procedure means no inferred clock.
    #[test]
    fn structural_clock_blocking_delay_infers_nothing() {
        let inferred = structural(
            "module m;\n\
             logic clk, q, d;\n\
             always @(posedge clk) begin #1 q <= d; end\n\
             endmodule\n",
        )
        .expect("no error");
        assert_eq!(inferred, None);
    }

    /// 16.14.6(b): two event controls (the r4 shape) mean no inferred clock.
    #[test]
    fn structural_clock_two_event_controls_infer_nothing() {
        let inferred = structural(
            "module m;\n\
             logic mclk, q, q1, d1;\n\
             always @(posedge mclk) begin\n\
                @(negedge mclk) q1 <= !d1;\n\
                q <= d1;\n\
             end\n\
             endmodule\n",
        )
        .expect("no error");
        assert_eq!(inferred, None);
    }

    /// An event variable as the clocking event is the (c) case this walk does not
    /// model, so it is an error rather than a guess.
    #[test]
    fn structural_clock_event_variable_is_a_loud_error() {
        let err = structural(
            "module m;\n\
             event e;\n\
             logic q, d;\n\
             always @(e) q <= d;\n\
             endmodule\n",
        )
        .expect_err("an event-variable clock is refused");
        assert!(
            err.to_string().contains("event variable or clocking block"),
            "{err}"
        );
    }

    /// A timing control that is not on a statement (`q = #1 d`) is refused too.
    #[test]
    fn structural_clock_intra_assignment_delay_is_a_loud_error() {
        let err = structural(
            "module m;\n\
             logic clk, q, d;\n\
             always @(posedge clk) q = #1 d;\n\
             endmodule\n",
        )
        .expect_err("an intra-assignment delay is refused");
        assert!(err.to_string().contains("intra-assignment delay"), "{err}");
    }
}