vj-sim 0.3.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
//! The set of covergroup types and instances of one simulation run, and the
//! type-level coverage queries (IEEE 1800-2023 19.8, 19.11.3, 19.9).
//!
//! An instance is named by a 64-bit handle: `index + 1`, so 0 is the null
//! handle a covergroup variable holds before `new`. Instances are never freed:
//! the cumulative (type) coverage keeps counting what a discarded instance saw.

use std::collections::HashSet;

use super::compute::{Score, empty_score, item_score, merge_bins, weighted_score};
use super::coverpoint::CovEvent;
use super::db::{Db, DbItem, DbType, ItemKind};
use super::decl::CovGroupDecl;
use super::instance::{CovInstance, ItemRef};
use super::options::{Level, TypeOptions};
use super::value::{CovError, Eval, Val};

pub type TypeId = usize;

/// Type options that 19.7.1 lets only the covergroup definition set.
const TYPE_DEFINITION_ONLY: [&str; 2] = ["strobe", "real_interval"];

#[derive(Debug)]
pub struct CovType {
    pub name: String,
    decl: CovGroupDecl,
    /// `type_option.*` of the covergroup.
    pub options: TypeOptions,
    cp_options: Vec<TypeOptions>,
    cross_options: Vec<TypeOptions>,
    instances: Vec<usize>,
}

impl CovType {
    pub fn decl(&self) -> &CovGroupDecl {
        &self.decl
    }

    /// The coverpoint or cross called `name`.
    pub fn find_item(&self, name: &str) -> Option<ItemRef> {
        if let Some(i) = self.decl.coverpoints.iter().position(|c| c.name == name) {
            return Some(ItemRef::Coverpoint(i));
        }
        self.decl
            .crosses
            .iter()
            .position(|c| c.name == name)
            .map(ItemRef::Cross)
    }

    fn check(&self, item: ItemRef) -> Result<(), CovError> {
        let ok = match item {
            ItemRef::Group => true,
            ItemRef::Coverpoint(i) => i < self.cp_options.len(),
            ItemRef::Cross(i) => i < self.cross_options.len(),
        };
        if ok {
            Ok(())
        } else {
            Err(CovError::UnknownItem {
                group: self.name.clone(),
                item: format!("{item:?}"),
            })
        }
    }

    /// The `type_option.*` of a covergroup, coverpoint or cross.
    pub fn type_options(&self, item: ItemRef) -> Result<&TypeOptions, CovError> {
        self.check(item)?;
        Ok(match item {
            ItemRef::Group => &self.options,
            ItemRef::Coverpoint(i) => &self.cp_options[i],
            ItemRef::Cross(i) => &self.cross_options[i],
        })
    }
}

/// What `$load_coverage_db` did with a database (19.9).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LoadSummary {
    /// Coverpoints and crosses (`type::item`) whose counts were taken.
    pub merged: Vec<String>,
    /// Covergroup types the database names that this design does not have.
    pub ignored_types: Vec<String>,
    /// `type::item` entries the covergroup type does not declare.
    pub ignored_items: Vec<String>,
}

#[derive(Debug, Default)]
pub struct Registry {
    types: Vec<CovType>,
    /// Every instance with the type it was made from.
    insts: Vec<(TypeId, CovInstance)>,
    /// Cumulative coverage of earlier runs, loaded by `$load_coverage_db`. It
    /// counts as one more instance of its type (see [`Registry::type_score`]);
    /// bins no instance has are left out of the computation.
    baseline: Db,
    /// The file `$set_coverage_db_name` chose.
    db_name: Option<String>,
}

impl Registry {
    pub fn new() -> Registry {
        Registry::default()
    }

    /// Forgets every type, instance and loaded database (a new simulation run).
    pub fn reset(&mut self) {
        self.types.clear();
        self.insts.clear();
        self.baseline = Db::default();
        self.db_name = None;
    }

    /// `$set_coverage_db_name(name)` (19.9).
    pub fn set_db_name(&mut self, name: &str) {
        self.db_name = Some(name.to_string());
    }

    pub fn db_name(&self) -> Option<&str> {
        self.db_name.as_deref()
    }

    /// The cumulative coverage of every type that has instances, plus whatever
    /// was loaded: bin hit counts of equally named bins add up across
    /// instances (19.11.3), the largest `at_least` and `weight` are kept.
    pub fn snapshot_db(&self) -> Result<Db, CovError> {
        let mut db = Db::default();
        for t in &self.types {
            if t.instances.is_empty() {
                continue;
            }
            let mut dt = DbType {
                name: t.name.clone(),
                items: Vec::new(),
            };
            for &i in &t.instances {
                let inst = &self.insts[i].1;
                let mut one = DbType {
                    name: t.name.clone(),
                    items: Vec::new(),
                };
                for (k, c) in inst.coverpoints().iter().enumerate() {
                    one.items.push(db_item(
                        inst,
                        ItemKind::Coverpoint,
                        &c.name,
                        ItemRef::Coverpoint(k),
                    )?);
                }
                for (k, x) in inst.crosses().iter().enumerate() {
                    one.items
                        .push(db_item(inst, ItemKind::Cross, &x.name, ItemRef::Cross(k))?);
                }
                dt.merge(&one);
            }
            db.types.push(dt);
        }
        db.merge(&self.baseline);
        Ok(db)
    }

    /// `$load_coverage_db(text)` (19.9): adds the hit counts of the database to
    /// the matching covergroup types. Types and coverpoints/crosses this design
    /// does not declare are ignored (reported in the summary); a database that
    /// does not parse changes nothing.
    pub fn load_db(&mut self, text: &str) -> Result<LoadSummary, CovError> {
        let db = Db::parse(text)?;
        let mut keep = Db::default();
        let mut summary = LoadSummary::default();
        for dt in db.types {
            let Some(t) = self.types.iter().find(|t| t.name == dt.name) else {
                summary.ignored_types.push(dt.name);
                continue;
            };
            let mut kept = DbType {
                name: dt.name.clone(),
                items: Vec::new(),
            };
            for item in dt.items {
                let declared = match item.kind {
                    ItemKind::Coverpoint => t.decl.coverpoints.iter().any(|c| c.name == item.name),
                    ItemKind::Cross => t.decl.crosses.iter().any(|c| c.name == item.name),
                };
                let label = format!("{}::{}", dt.name, item.name);
                if declared {
                    summary.merged.push(label);
                    kept.items.push(item);
                } else {
                    summary.ignored_items.push(label);
                }
            }
            keep.types.push(kept);
        }
        self.baseline.merge(&keep);
        Ok(summary)
    }

    /// The loaded database's entry for `item` of `t`, restricted to the bins
    /// some instance of the type has (a bin name the design does not have is
    /// ignored, 19.9).
    fn baseline_view(
        &self,
        t: &CovType,
        insts: &[&CovInstance],
        item: ItemRef,
    ) -> Result<Option<DbItem>, CovError> {
        let (kind, name) = match item {
            ItemRef::Group => return Ok(None),
            ItemRef::Coverpoint(i) => (ItemKind::Coverpoint, &t.decl.coverpoints[i].name),
            ItemRef::Cross(i) => (ItemKind::Cross, &t.decl.crosses[i].name),
        };
        let Some(b) = self.baseline.ty(&t.name).and_then(|d| d.item(kind, name)) else {
            return Ok(None);
        };
        let mut names = HashSet::new();
        for i in insts {
            for (n, _) in i.item_bins(item)? {
                names.insert(n);
            }
        }
        let mut view = b.clone();
        view.bins.retain(|(n, _)| names.contains(n));
        Ok(Some(view))
    }

    /// Registers a covergroup type: its `type_option` assignments are
    /// constant, so they are evaluated here, once (19.7.1).
    pub fn define(&mut self, decl: CovGroupDecl, ev: &mut dyn Eval) -> Result<TypeId, CovError> {
        let mut seen = HashSet::new();
        let names = decl
            .coverpoints
            .iter()
            .map(|c| &c.name)
            .chain(decl.crosses.iter().map(|c| &c.name));
        for n in names {
            if !seen.insert(n.as_str()) {
                return Err(CovError::DuplicateItem {
                    group: decl.name.clone(),
                    item: n.clone(),
                });
            }
        }
        let mut options = TypeOptions::default();
        for (n, e) in &decl.type_options {
            options.set(Level::Covergroup, n, &e.eval(ev, &[])?)?;
        }
        let mut cp_options = Vec::with_capacity(decl.coverpoints.len());
        for c in &decl.coverpoints {
            let mut o = options.inherit();
            for (n, e) in &c.type_options {
                o.set(Level::Coverpoint, n, &e.eval(ev, &[])?)?;
            }
            cp_options.push(o);
        }
        let mut cross_options = Vec::with_capacity(decl.crosses.len());
        for c in &decl.crosses {
            let mut o = options.inherit();
            for (n, e) in &c.type_options {
                o.set(Level::Cross, n, &e.eval(ev, &[])?)?;
            }
            cross_options.push(o);
        }
        self.types.push(CovType {
            name: decl.name.clone(),
            decl,
            options,
            cp_options,
            cross_options,
            instances: Vec::new(),
        });
        Ok(self.types.len() - 1)
    }

    pub fn types(&self) -> &[CovType] {
        &self.types
    }

    pub fn type_id(&self, name: &str) -> Option<TypeId> {
        self.types.iter().position(|t| t.name == name)
    }

    pub fn ty(&self, ty: TypeId) -> Result<&CovType, CovError> {
        self.types.get(ty).ok_or(CovError::BadHandle(ty as u64))
    }

    /// `new`: instantiates covergroup type `ty` with constructor arguments
    /// `ctor`. Returns the instance's handle and the bins' warnings.
    pub fn instantiate(
        &mut self,
        ty: TypeId,
        ctor: &[Val],
        ev: &mut dyn Eval,
    ) -> Result<(u64, Vec<String>), CovError> {
        let t = self.ty(ty)?;
        let auto_name = format!("{}#{}", t.name, t.instances.len());
        let (inst, warnings) = CovInstance::new(&t.decl, &t.options, auto_name, ev, ctor)?;
        let index = self.insts.len();
        self.insts.push((ty, inst));
        self.types[ty].instances.push(index);
        Ok((index as u64 + 1, warnings))
    }

    fn index(&self, h: u64) -> Result<usize, CovError> {
        let i = h.checked_sub(1).ok_or(CovError::BadHandle(h))?;
        match usize::try_from(i) {
            Ok(i) if i < self.insts.len() => Ok(i),
            _ => Err(CovError::BadHandle(h)),
        }
    }

    pub fn instance(&self, h: u64) -> Result<&CovInstance, CovError> {
        Ok(&self.insts[self.index(h)?].1)
    }

    pub fn instance_mut(&mut self, h: u64) -> Result<&mut CovInstance, CovError> {
        let i = self.index(h)?;
        Ok(&mut self.insts[i].1)
    }

    /// The type an instance was made from.
    pub fn type_of(&self, h: u64) -> Result<TypeId, CovError> {
        Ok(self.insts[self.index(h)?].0)
    }

    /// The handles of the instances of `ty`, in creation order.
    pub fn instances_of(&self, ty: TypeId) -> Result<Vec<u64>, CovError> {
        Ok(self
            .ty(ty)?
            .instances
            .iter()
            .map(|&i| i as u64 + 1)
            .collect())
    }

    pub fn sample(
        &mut self,
        h: u64,
        ev: &mut dyn Eval,
        sargs: &[Val],
    ) -> Result<Vec<CovEvent>, CovError> {
        self.instance_mut(h)?.sample(ev, sargs)
    }

    /// `type_option.<name> = v` executed procedurally (19.7.1) on a covergroup
    /// type, or one of its coverpoints or crosses.
    pub fn set_type_option(
        &mut self,
        ty: TypeId,
        item: ItemRef,
        name: &str,
        v: &Val,
    ) -> Result<(), CovError> {
        self.ty(ty)?.check(item)?;
        let t = &mut self.types[ty];
        let (opts, level) = match item {
            ItemRef::Group => (&mut t.options, Level::Covergroup),
            ItemRef::Coverpoint(i) => (&mut t.cp_options[i], Level::Coverpoint),
            ItemRef::Cross(i) => (&mut t.cross_options[i], Level::Cross),
        };
        let mut next = opts.clone();
        next.set(level, name, v)?;
        if TYPE_DEFINITION_ONLY.contains(&name) {
            return Err(CovError::DefinitionOnlyOption {
                option: name.to_string(),
            });
        }
        *opts = next;
        Ok(())
    }

    pub fn get_type_option(&self, ty: TypeId, item: ItemRef, name: &str) -> Result<Val, CovError> {
        let level = match item {
            ItemRef::Group => Level::Covergroup,
            ItemRef::Coverpoint(_) => Level::Coverpoint,
            ItemRef::Cross(_) => Level::Cross,
        };
        self.ty(ty)?.type_options(item)?.get(level, name)
    }

    /// `get_coverage()` on a covergroup type, or on one of its coverpoints or
    /// crosses (`cg::cp::get_coverage()`): the cumulative coverage over every
    /// instance (19.11, 19.11.3).
    pub fn type_score(&self, ty: TypeId, item: ItemRef) -> Result<Score, CovError> {
        let t = self.ty(ty)?;
        t.check(item)?;
        let weight = t.type_options(item)?.weight;
        let insts: Vec<&CovInstance> = t.instances.iter().map(|&i| &self.insts[i].1).collect();
        if !t.options.merge_instances {
            // 19.11.3: the weighted average of the instances' own coverage,
            // each instance weighted by its `option.weight`; a loaded
            // database is one more instance
            let loaded = |item: ItemRef| -> Result<Option<(i64, Score)>, CovError> {
                Ok(self.baseline_view(t, &insts, item)?.map(|b| {
                    (
                        b.weight,
                        item_score(b.weight, merge_bins(&[(b.at_least, b.bins)])),
                    )
                }))
            };
            let mut parts = Vec::with_capacity(insts.len() + 1);
            for i in &insts {
                parts.push((i.weight(item)?, i.own_score(item)?));
            }
            match item {
                ItemRef::Group => {
                    let mut items = Vec::new();
                    for i in 0..t.cp_options.len() {
                        items.extend(loaded(ItemRef::Coverpoint(i))?);
                    }
                    for i in 0..t.cross_options.len() {
                        items.extend(loaded(ItemRef::Cross(i))?);
                    }
                    parts.push((1, weighted_score(1, &items)));
                }
                _ => parts.extend(loaded(item)?),
            }
            return Ok(weighted_score(weight, &parts));
        }
        // 19.11.3: as if every instance were merged into the type; a loaded
        // database adds its hits to the bins of the same name
        let merged = |item: ItemRef| -> Result<Score, CovError> {
            let mut views = Vec::with_capacity(insts.len() + 1);
            for i in &insts {
                views.push((i.at_least(item)?, i.item_bins(item)?));
            }
            if let Some(b) = self.baseline_view(t, &insts, item)? {
                views.push((b.at_least, b.bins));
            }
            Ok(item_score(t.type_options(item)?.weight, merge_bins(&views)))
        };
        match item {
            ItemRef::Group => {
                let mut parts = Vec::new();
                for i in 0..t.cp_options.len() {
                    let it = ItemRef::Coverpoint(i);
                    parts.push((t.type_options(it)?.weight, merged(it)?));
                }
                for i in 0..t.cross_options.len() {
                    let it = ItemRef::Cross(i);
                    parts.push((t.type_options(it)?.weight, merged(it)?));
                }
                Ok(weighted_score(weight, &parts))
            }
            _ => merged(item),
        }
    }

    /// `get_inst_coverage()` on an instance or one of its items (19.8). With
    /// `type_option.merge_instances` set and `option.get_inst_coverage` clear it
    /// equals `get_coverage()` (Table 19-1).
    pub fn inst_score(&self, h: u64, item: ItemRef) -> Result<Score, CovError> {
        let (ty, inst) = &self.insts[self.index(h)?];
        if self.types[*ty].options.merge_instances && !inst.options.get_inst_coverage {
            return self.type_score(*ty, item);
        }
        inst.own_score(item)
    }

    /// `$get_coverage` (19.9, 19.11): the weighted average over the covergroup
    /// types (by `type_option.weight`) of their type coverage; 100.0 when no
    /// type contributes, which is the case with no instances or only zero
    /// weights.
    pub fn global_coverage(&self) -> Result<f64, CovError> {
        let mut parts = Vec::with_capacity(self.types.len());
        for (ty, t) in self.types.iter().enumerate() {
            parts.push((t.options.weight, self.type_score(ty, ItemRef::Group)?));
        }
        let s = weighted_score(1, &parts);
        Ok(if s.contributes {
            s.percent
        } else {
            empty_score(0).percent
        })
    }
}

fn db_item(
    inst: &CovInstance,
    kind: ItemKind,
    name: &str,
    item: ItemRef,
) -> Result<DbItem, CovError> {
    Ok(DbItem {
        kind,
        name: name.to_string(),
        at_least: inst.at_least(item)?,
        weight: inst.weight(item)?,
        bins: inst.item_bins(item)?,
    })
}