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
//! One coverpoint instance: bins, sampling and its coverage (IEEE 1800-2023
//! 19.5, 19.11).

use std::collections::{HashMap, VecDeque};

use super::bins::{Bin, Matcher, build_bins, fmt_real};
use super::decl::{BinKind, CoverpointDecl};
use super::options::{Level, Options, TypeOptions};
use super::value::{CovError, Eval, Expr, TypeInfo, Val};

/// `covered` bins out of `total` bins (the numerator and denominator the
/// `get_coverage(ref int covered, ref int total)` overload reports, 19.8).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Coverage {
    pub covered: u64,
    pub total: u64,
}

impl Coverage {
    /// `100 * covered / total`; `None` when there is nothing to cover, which
    /// the callers resolve per 19.11 (the item then does not contribute).
    pub fn percent(&self) -> Option<f64> {
        (self.total != 0).then(|| 100.0 * self.covered as f64 / self.total as f64)
    }
}

/// Something a sample did besides counting.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CovEvent {
    /// A value hit an `illegal_bins` bin: a run-time error (19.5.6).
    IllegalBin {
        coverpoint: String,
        bin: String,
        value: String,
    },
}

#[derive(Debug)]
pub struct Coverpoint {
    pub name: String,
    pub ty: TypeInfo,
    pub options: Options,
    pub type_options: TypeOptions,
    expr: Expr,
    iff: Option<Expr>,
    ctor: Vec<Val>,
    pub bins: Vec<Bin>,
    /// Non-default bins matching exactly one integral value.
    singles: HashMap<i128, Vec<usize>>,
    /// Every other non-default, non-empty-set bin.
    multi: Vec<usize>,
    /// Transition bins (19.5.2), in declaration order.
    trans: Vec<usize>,
    /// `default sequence` bins.
    default_seqs: Vec<usize>,
    /// A previous sample exists, so this sample completes a transition.
    has_prev: bool,
    /// The latest sampled values, for illegal-transition reports.
    recent: VecDeque<i128>,
    recent_cap: usize,
    /// How many times the coverpoint was sampled (its `iff` held).
    pub samples: u64,
    /// The last sample produced a value that a bin could take (its `iff` held
    /// and the value was not x/z): a cross can form a tuple from it.
    last_sampled: bool,
    /// Ascending indices of the normal bins the last sample counted, for the
    /// crosses over this coverpoint (19.6). Empty when the value was ignored,
    /// illegal or only in the default bin: those make no cross products.
    last_hits: Vec<usize>,
}

/// A sampled value normalised to the coverpoint type.
#[derive(Clone, Copy)]
enum Sample {
    Int(i128),
    Real(f64),
}

pub(super) fn truthy(v: Val, what: &str) -> Result<bool, CovError> {
    match v {
        Val::Int(i) => Ok(i != 0),
        Val::Real(r) => Ok(r != 0.0),
        // an x/z condition is false (12.4)
        Val::Unknown | Val::Pat { .. } => Ok(false),
        other => Err(CovError::BadValue {
            ctx: what.to_string(),
            got: format!("{other:?}"),
        }),
    }
}

impl Coverpoint {
    /// Instantiates `decl` for a covergroup whose options are `cg_opts` /
    /// `cg_topts`, constructed with `ctor` arguments. All construction-time
    /// expressions are evaluated through `ev` now.
    pub fn new(
        decl: &CoverpointDecl,
        cg_opts: &Options,
        cg_topts: &TypeOptions,
        ev: &mut dyn Eval,
        ctor: &[Val],
    ) -> Result<(Coverpoint, Vec<String>), CovError> {
        let mut options = cg_opts.inherit();
        for (n, e) in &decl.options {
            let v = e.eval(ev, ctor)?;
            options.set(Level::Coverpoint, n, &v)?;
        }
        let mut type_options = cg_topts.inherit();
        // Table 19-4 makes `distribute_first` a covergroup-only option, but it
        // governs how the bins of every coverpoint in the group are built
        // (19.5.1.1), so the coverpoint carries the group's value.
        type_options.distribute_first = cg_topts.distribute_first;
        for (n, e) in &decl.type_options {
            let v = e.eval(ev, ctor)?;
            type_options.set(Level::Coverpoint, n, &v)?;
        }
        let (bins, warnings) = build_bins(decl, &options, &type_options, ev, ctor)?;
        let mut singles: HashMap<i128, Vec<usize>> = HashMap::new();
        let mut multi = Vec::new();
        let mut trans = Vec::new();
        let mut default_seqs = Vec::new();
        let mut recent_cap = 0usize;
        for (i, b) in bins.iter().enumerate() {
            match &b.matcher {
                Matcher::Default => {}
                Matcher::Trans(t) => {
                    trans.push(i);
                    if b.kind == BinKind::Illegal {
                        recent_cap = recent_cap.max(t.max_len);
                    }
                }
                Matcher::DefaultSeq => {
                    default_seqs.push(i);
                    if b.kind == BinKind::Illegal {
                        recent_cap = recent_cap.max(2);
                    }
                }
                Matcher::Ints(s) if s.is_empty() => {}
                Matcher::Ints(s) if s.count() == 1 => {
                    singles.entry(s.intervals()[0].0).or_default().push(i)
                }
                _ => multi.push(i),
            }
        }
        Ok((
            Coverpoint {
                name: decl.name.clone(),
                ty: decl.ty,
                options,
                type_options,
                expr: decl.expr.clone(),
                iff: decl.iff.clone(),
                ctor: ctor.to_vec(),
                bins,
                singles,
                multi,
                trans,
                default_seqs,
                has_prev: false,
                recent: VecDeque::new(),
                recent_cap,
                samples: 0,
                last_sampled: false,
                last_hits: Vec::new(),
            },
            warnings,
        ))
    }

    fn args(&self, sargs: &[Val]) -> Vec<Val> {
        let mut a = self.ctor.clone();
        a.extend_from_slice(sargs);
        a
    }

    /// Samples the coverpoint: evaluates its `iff` and expression with
    /// `sargs` (the `sample()` arguments) and counts the value.
    pub fn sample(&mut self, ev: &mut dyn Eval, sargs: &[Val]) -> Result<Vec<CovEvent>, CovError> {
        self.last_sampled = false;
        self.last_hits.clear();
        let args = self.args(sargs);
        if let Some(iff) = &self.iff
            && !truthy(iff.eval(ev, &args)?, "coverpoint iff")?
        {
            return Ok(Vec::new());
        }
        let v = self.expr.eval(ev, &args)?;
        self.sample_value(&v, ev, sargs)
    }

    /// Counts an already-evaluated value (the coverpoint `iff` held).
    pub fn sample_value(
        &mut self,
        v: &Val,
        ev: &mut dyn Eval,
        sargs: &[Val],
    ) -> Result<Vec<CovEvent>, CovError> {
        self.last_sampled = false;
        self.last_hits.clear();
        self.samples += 1;
        let s = match (v, self.ty.real) {
            // an x/z value matches no bin, not even default (19.5.4, 19.5.7),
            // and no sequence continues through it
            (Val::Unknown | Val::Pat { .. }, _) => {
                self.break_trans();
                return Ok(Vec::new());
            }
            (Val::Int(i), false) => Sample::Int(self.ty.value_of(self.ty.bits_of(*i))),
            (Val::Int(i), true) => Sample::Real(*i as f64),
            (Val::Real(r), true) => Sample::Real(*r),
            (other, _) => {
                return Err(CovError::BadValue {
                    ctx: format!("coverpoint {} sample", self.name),
                    got: format!("{other:?}"),
                });
            }
        };
        let args = self.args(sargs);
        self.last_sampled = true;
        let mut events = self.count_value(s, ev, &args)?;
        if let Sample::Int(i) = s {
            events.extend(self.step_trans(i, ev, &args)?);
        }
        self.last_hits.sort_unstable();
        Ok(events)
    }

    /// Whether the last sample yielded a value the bins could take.
    pub fn last_sampled(&self) -> bool {
        self.last_sampled
    }

    /// Indices of the normal bins the last sample counted (see the field).
    pub fn last_hits(&self) -> &[usize] {
        &self.last_hits
    }

    /// Indices of the bins a cross over this coverpoint takes tuples from:
    /// normal, non-default, non-empty ones (19.6: "no cross coverage bins
    /// shall be created for coverpoint bins that are specified as default,
    /// ignored, or illegal bins").
    pub fn cross_bins(&self) -> Vec<usize> {
        self.bins
            .iter()
            .enumerate()
            .filter(|(_, b)| {
                b.kind == BinKind::Normal && !b.is_default() && !b.is_default_seq() && !b.empty
            })
            .map(|(i, _)| i)
            .collect()
    }

    /// Forgets every sequence in flight (a sample no bin can use).
    fn break_trans(&mut self) {
        self.has_prev = false;
        self.recent.clear();
        for &i in &self.trans {
            if let Matcher::Trans(t) = &mut self.bins[i].matcher {
                t.clear();
            }
        }
    }

    /// Advances every transition bin by the sampled value `v` (19.5.2).
    fn step_trans(
        &mut self,
        v: i128,
        ev: &mut dyn Eval,
        args: &[Val],
    ) -> Result<Vec<CovEvent>, CovError> {
        let mut events = Vec::new();
        if self.trans.is_empty() && self.default_seqs.is_empty() {
            return Ok(events);
        }
        if self.recent_cap > 0 {
            self.recent.push_back(v);
            while self.recent.len() > self.recent_cap {
                self.recent.pop_front();
            }
        }
        let mut matched = Vec::new();
        let mut pending = false;
        for k in 0..self.trans.len() {
            let i = self.trans[k];
            let Matcher::Trans(t) = &mut self.bins[i].matcher else {
                unreachable!("trans lists only transition bins");
            };
            let st = t.step(v);
            pending |= st.pending;
            if st.matched {
                matched.push(i);
            }
        }
        // 19.5.2: `default sequence` counts a transition that no other
        // transition bin took and no earlier attempt is still waiting on.
        let default_hit = self.has_prev && matched.is_empty() && !pending;
        self.has_prev = true;
        let text = self
            .recent
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>();
        let text = text.join("=>");
        let mut hit: Vec<usize> = matched;
        if default_hit {
            hit.extend(self.default_seqs.iter().copied());
        }
        for i in hit {
            if !self.bin_iff(i, ev, args)? {
                continue;
            }
            let bin = &mut self.bins[i];
            match bin.kind {
                // 19.5.5: an ignored sequence is not counted anywhere
                BinKind::Ignore => {}
                BinKind::Normal => {
                    bin.hits = bin.hits.saturating_add(1);
                    // `default sequence` makes no cross products (19.6)
                    if !bin.is_default_seq() {
                        self.last_hits.push(i);
                    }
                }
                BinKind::Illegal => {
                    bin.hits = bin.hits.saturating_add(1);
                    events.push(CovEvent::IllegalBin {
                        coverpoint: self.name.clone(),
                        bin: bin.name.clone(),
                        value: text.clone(),
                    });
                }
            }
        }
        Ok(events)
    }

    /// Counts a value in the value bins (19.5.1, 19.5.5-19.5.7).
    fn count_value(
        &mut self,
        s: Sample,
        ev: &mut dyn Eval,
        args: &[Val],
    ) -> Result<Vec<CovEvent>, CovError> {
        let matched = self.matching(s);
        let text = match s {
            Sample::Int(i) => i.to_string(),
            Sample::Real(r) => fmt_real(r),
        };
        let mut events = Vec::new();

        // 19.5.6: an illegal value is an error even if another bin holds it.
        let mut excluded = false;
        for &i in &matched {
            if self.bins[i].kind != BinKind::Illegal {
                continue;
            }
            excluded = true;
            if self.bin_iff(i, ev, args)? {
                self.bins[i].hits = self.bins[i].hits.saturating_add(1);
                events.push(CovEvent::IllegalBin {
                    coverpoint: self.name.clone(),
                    bin: self.bins[i].name.clone(),
                    value: text.clone(),
                });
            }
        }
        // 19.5.5: ignored values take no part in any other bin.
        excluded |= matched
            .iter()
            .any(|&i| self.bins[i].kind == BinKind::Ignore);
        if excluded {
            return Ok(events);
        }

        for &i in &matched {
            if self.bin_iff(i, ev, args)? {
                self.bins[i].hits = self.bins[i].hits.saturating_add(1);
                self.last_hits.push(i);
            }
        }
        // default: values of no defined bin (ignore/illegal bins are defined).
        if matched.is_empty() {
            for i in 0..self.bins.len() {
                if !self.bins[i].is_default() || !self.bin_iff(i, ev, args)? {
                    continue;
                }
                let bin = &mut self.bins[i];
                bin.hits = bin.hits.saturating_add(1);
                if bin.default_array
                    && let Sample::Int(v) = s
                {
                    let c = bin.default_values.entry(v).or_insert(0);
                    *c = c.saturating_add(1);
                }
                if bin.kind == BinKind::Illegal {
                    events.push(CovEvent::IllegalBin {
                        coverpoint: self.name.clone(),
                        bin: bin.name.clone(),
                        value: text.clone(),
                    });
                }
            }
        }
        Ok(events)
    }

    fn bin_iff(&self, i: usize, ev: &mut dyn Eval, args: &[Val]) -> Result<bool, CovError> {
        match &self.bins[i].iff {
            None => Ok(true),
            Some(e) => truthy(e.eval(ev, args)?, "bin iff"),
        }
    }

    /// Indices (ascending) of the non-default bins holding the value.
    fn matching(&self, s: Sample) -> Vec<usize> {
        let mut out = Vec::new();
        match s {
            Sample::Int(v) => {
                if let Some(ix) = self.singles.get(&v) {
                    out.extend(ix.iter().copied());
                }
                for &i in &self.multi {
                    let hit = match &self.bins[i].matcher {
                        Matcher::Ints(set) => set.contains(v),
                        Matcher::Pats(pats) => {
                            let bits = self.ty.bits_of(v);
                            pats.iter().any(|&(pb, care)| (bits ^ pb) & care == 0)
                        }
                        Matcher::Reals(_)
                        | Matcher::Default
                        | Matcher::Trans(_)
                        | Matcher::DefaultSeq => false,
                    };
                    if hit {
                        out.push(i);
                    }
                }
            }
            Sample::Real(r) => {
                for &i in &self.multi {
                    if let Matcher::Reals(items) = &self.bins[i].matcher
                        && items.iter().any(|it| it.contains(r))
                    {
                        out.push(i);
                    }
                }
            }
        }
        out.sort_unstable();
        out
    }

    /// The coverpoint's coverage: covered / total over the non-default,
    /// non-empty `bins` bins (19.11). Default, ignore and illegal bins and
    /// empty bins are excluded.
    pub fn coverage(&self) -> Coverage {
        let mut c = Coverage::default();
        for b in &self.bins {
            if b.kind != BinKind::Normal || b.is_default() || b.is_default_seq() || b.empty {
                continue;
            }
            c.total += 1;
            if b.hits >= self.options.at_least {
                c.covered += 1;
            }
        }
        c
    }

    /// The bins the coverage is measured over, with their hit counts, in
    /// declaration order: what a merged (type) coverage unions by name
    /// (19.11.3).
    pub fn coverage_bins(&self) -> Vec<(String, u64)> {
        self.bins
            .iter()
            .filter(|b| {
                b.kind == BinKind::Normal && !b.is_default() && !b.is_default_seq() && !b.empty
            })
            .map(|b| (b.name.clone(), b.hits))
            .collect()
    }

    /// A sample event this coverpoint did not take part in (it is stopped, 19.8):
    /// no cross tuple comes from it and every sequence in flight is dropped,
    /// because a gap in sampling breaks consecutiveness.
    pub fn skip(&mut self) {
        self.last_sampled = false;
        self.last_hits.clear();
        self.break_trans();
    }

    /// Hit count of the bin called `name`.
    pub fn hits(&self, name: &str) -> Option<u64> {
        self.bins.iter().find(|b| b.name == name).map(|b| b.hits)
    }

    /// Zeroes every bin (a covergroup `stop`/re-arm is not a reset; this is
    /// for `$set_coverage`-style clears and tests).
    pub fn reset(&mut self) {
        self.samples = 0;
        self.last_sampled = false;
        self.last_hits.clear();
        self.break_trans();
        for b in &mut self.bins {
            b.hits = 0;
            b.default_values.clear();
        }
    }
}