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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Unpacked struct and fixed-size unpacked array class properties for the
//! [`Builder`] (plan task C14; IEEE 1800-2023 18.4, 18.5.7, 18.8).
//!
//! An aggregate property is stored as one flat value (`state::storage`): a
//! struct's fields concatenated, an array's elements lowest index first. Its
//! *leaves* (an integral or real member or element) are the variables of the
//! solve. A leaf is a [`Window`] of the property's value: it has its own
//! [`VarInfo`] (or [`RealVarInfo`]), keyed by the property and the path of
//! [`Step`]s from it, and the registry reads and writes the leaf through that
//! window.
//!
//! * A leaf is random when the property is declared `rand`/`randc` (18.4: an
//!   array declared `rand` makes every element random; a `rand` unpacked
//!   struct solves every member concurrently) or when a struct member on its
//!   path is. A member's own qualifier overrides the one it would inherit, so a
//!   `randc` member of a `rand` struct is `randc` and a member that is not
//!   `rand` of a non-`rand` struct is a state variable (18.3).
//! * An unpacked union is never random; a `string` or `chandle` member has no
//!   solved value and is skipped. A class handle, queue, dynamic array or
//!   associative array *inside* a random aggregate is
//!   [`BuildError::Unsupported`]: such a leaf would be a random object or a
//!   random-size array nested in a flat value.
//! * `a[i]` with a constant index names one leaf. An index that is a state
//!   variable or loop variable names a *choice* among the leaves
//!   ([`ArrayNode::Pick`]) the registry resolves once the index is known; an
//!   index that is a random variable is [`BuildError::BadArray`] (18.5.7.1).
//!   An index outside the array is an error only if the constraint it is in
//!   is live: "users have to explicitly exclude these indices using
//!   predicates".
//! * `A.sum()` and the other reduction methods over a fixed-size array unroll
//!   over its elements (`arrays`); `foreach` over one unrolls too.

use super::arrays::{ArrayShape, array_shape, const_i64};
use super::real::{real_kind, state_ty, strip_conversions};
use super::*;
use crate::constraints::ir::{ArrayNode, Assignment, eval};
use crate::constraints::real_domain::{FloatKind as Fk, RealExpr};
use crate::state::storage::{field_slice, storage_width};

/// One step from an aggregate property to a leaf of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Step {
    /// The element at this declared index of a fixed-size array.
    Index(i64),
    /// The member at this position (declaration order) of an unpacked struct.
    Field(u32),
}

/// A leaf declared as a random variable, in the namespace it lives in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Declared {
    /// An integral leaf: an id of [`ConstraintSet::vars`].
    Int(u32),
    /// A `real`/`shortreal` leaf: an id of [`ConstraintSet::real_vars`].
    Real(u32),
    /// A dynamic array or queue leaf (`rand int a[3][]`, a `rand` queue member
    /// of a struct): an id of [`ConstraintSet::arrays`] whose handle sits at a
    /// window of the property.
    Array(u32),
}

/// One step of an expression naming a leaf, before indices are evaluated.
#[derive(Clone, Copy)]
pub(super) enum RawStep<'d> {
    /// `[expr]`, to be built.
    Index(Expression<'d>),
    /// `[constant]`.
    Const(i64),
    /// `.member`, by position.
    Field(u32),
}

/// An expression naming a leaf of an aggregate property of this class.
#[derive(Clone)]
pub(super) struct Chain<'d> {
    /// The class property.
    pub root: Symbol<'d>,
    /// The selects and member accesses from it, outermost first (none for the
    /// property itself).
    pub steps: Vec<RawStep<'d>>,
}

/// What `e` names, if it is a class property of this class or a member or
/// element of one: `s`, `this.s`, `s.m`, `a[i]`, `s.m[i].n`, ... (anything
/// reached through an object handle, a local or a union is `None`).
pub(super) fn aggregate_chain<'d>(
    e: Expression<'d>,
    forced: &HashSet<SymbolId>,
) -> Option<Chain<'d>> {
    let e = strip_conversions(e);
    let kind = e.kind();
    // Every other kind of expression names no leaf of a property: `None`.
    if kind == ExpressionKind::NamedValue {
        let sym = e.referenced_symbol()?;
        return (sym.kind() == SymbolKind::ClassProperty || forced.contains(&sym.uid())).then(
            || Chain {
                root: sym,
                steps: Vec::new(),
            },
        );
    }
    if kind == ExpressionKind::MemberAccess {
        let base = e.left()?;
        let member = e.member_symbol()?;
        let is_this = strip_conversions(base).kind() == ExpressionKind::NamedValue
            && strip_conversions(base)
                .referenced_symbol()
                .is_some_and(|s| s.name() == "this");
        if is_this {
            return (member.kind() == SymbolKind::ClassProperty).then(|| Chain {
                root: member,
                steps: Vec::new(),
            });
        }
        let bt = base.expr_type()?.canonical();
        if !bt.is_unpacked_struct() {
            return None;
        }
        let index = bt.fields().position(|f| f.name() == member.name())?;
        let mut chain = aggregate_chain(base, forced)?;
        chain.steps.push(RawStep::Field(u32::try_from(index).ok()?));
        return Some(chain);
    }
    if kind == ExpressionKind::ElementSelect {
        let base = e.select_value()?;
        if array_shape(base.expr_type()?) != Some(ArrayShape::Fixed) {
            return None;
        }
        let mut chain = aggregate_chain(base, forced)?;
        chain.steps.push(RawStep::Index(e.selector()?));
        return Some(chain);
    }
    None
}

/// Whether `t` is an unpacked struct or a fixed-size unpacked array: a type
/// whose leaves are variables ([`Builder::declare_rand_aggregate`]).
pub fn is_aggregate_type(t: Type<'_>) -> bool {
    let c = t.canonical();
    c.is_unpacked_struct() || array_shape(c) == Some(ArrayShape::Fixed)
}

/// Whether the class property `sym` has any random leaf: it is declared
/// `rand`/`randc`, or an unpacked-struct member at any depth is. Such a
/// property has a `rand_mode` (18.8) and is declared with
/// [`Builder::declare_rand_aggregate`] (or [`Builder::declare_rand`] when it is
/// not an aggregate).
pub fn property_is_random(sym: Symbol<'_>) -> bool {
    if sym.rand_mode() != RandMode::None {
        return true;
    }
    sym.value_type().is_some_and(has_random_member)
}

fn has_random_member(t: Type<'_>) -> bool {
    let c = t.canonical();
    if c.is_unpacked_struct() {
        return c.fields().any(|f| {
            f.field_rand_mode() != RandMode::None || f.value_type().is_some_and(has_random_member)
        });
    }
    array_shape(c) == Some(ArrayShape::Fixed) && c.element_type().is_some_and(has_random_member)
}

/// What kind of value a leaf is.
#[derive(Clone, Copy, Debug)]
pub(super) enum LeafKind {
    /// An integral leaf.
    Int(Ty),
    /// A `real` or `shortreal` leaf.
    Real(Fk),
    /// A virtual interface: never randomizable.
    Vif,
    /// A `string` or `chandle`: stored, but with no solved value.
    Skipped,
    /// A dynamic array or queue: an array of its own, stored as a handle.
    Collection,
    /// A class handle, associative array, or a union.
    Other,
}

/// A leaf of an aggregate property.
#[derive(Clone)]
pub(super) struct LeafRef<'d> {
    /// The property's key.
    pub root: SymbolId,
    /// `s.f[1]`: the property's name and the steps to the leaf.
    pub name: String,
    /// The steps from the property.
    pub path: Vec<Step>,
    /// Where the leaf sits in the property's value.
    pub window: Window,
    /// The effective `rand`/`randc` mode (none for a state leaf).
    pub mode: RandMode,
    /// The leaf's value kind.
    pub kind: LeafKind,
    /// The leaf's declared type.
    pub vt: Type<'d>,
}

impl LeafRef<'_> {
    pub(super) fn randc(&self) -> bool {
        self.mode == RandMode::RandC
    }
}

/// A resolved leaf expression: one leaf, or a run-time choice among several.
pub(super) enum Sel<'d> {
    Leaf(LeafRef<'d>),
    Pick {
        index: Expr,
        low: i64,
        elems: Vec<Sel<'d>>,
    },
}

/// A position inside an aggregate property while its steps are followed.
#[derive(Clone)]
struct Cursor<'d> {
    root: SymbolId,
    /// The whole property's width.
    whole: u64,
    ty: Type<'d>,
    mode: RandMode,
    path: Vec<Step>,
    name: String,
    /// The LSB of the current value within the property's value.
    bit: u64,
}

fn missing(what: impl Into<String>) -> BuildError {
    BuildError::Missing { what: what.into() }
}

impl<'d> Cursor<'d> {
    fn of(root: Symbol<'d>) -> Result<Cursor<'d>, BuildError> {
        let ty = root
            .value_type()
            .ok_or_else(|| missing(format!("value type for `{}`", root.name())))?;
        let whole = storage_width(&ty).ok_or_else(|| {
            missing(format!(
                "stored width of `{}` of type `{}`",
                root.name(),
                ty.to_sv_string()
            ))
        })?;
        Ok(Cursor {
            root: root.uid(),
            whole,
            ty,
            mode: root.rand_mode(),
            path: Vec::new(),
            name: root.name().to_string(),
            bit: 0,
        })
    }

    /// Member number `i` of the struct this is at.
    fn field(&self, i: u32) -> Result<Cursor<'d>, BuildError> {
        let t = self.ty.canonical();
        if !t.is_unpacked_struct() {
            return Err(missing(format!(
                "`{}` is not an unpacked struct",
                self.name
            )));
        }
        let f = t
            .fields()
            .nth(i as usize)
            .ok_or_else(|| missing(format!("member {i} of `{}`", self.name)))?;
        let (lsb, _) = field_slice(&t, i)
            .ok_or_else(|| missing(format!("stored position of member {i} of `{}`", self.name)))?;
        let ty = f
            .value_type()
            .ok_or_else(|| missing(format!("type of `{}.{}`", self.name, f.name())))?;
        let mut path = self.path.clone();
        path.push(Step::Field(i));
        Ok(Cursor {
            root: self.root.clone(),
            whole: self.whole,
            ty,
            // A member's own qualifier replaces the one it would inherit.
            mode: match f.field_rand_mode() {
                RandMode::None => self.mode,
                own => own,
            },
            path,
            name: format!("{}.{}", self.name, f.name()),
            bit: self.bit + lsb,
        })
    }

    /// The declared bounds `(lo, hi)` and the element type of the fixed-size
    /// array this is at.
    fn dim(&self) -> Result<(i64, i64, Type<'d>), BuildError> {
        let t = self.ty.canonical();
        match array_shape(t) {
            Some(ArrayShape::Fixed) => {}
            Some(ArrayShape::Collection | ArrayShape::Assoc) => {
                return Err(unsupported(
                    format!(
                        "`{}`, whose size is only known at run time (a dynamic array, queue or \
                         associative array), as an element of an aggregate",
                        self.name
                    ),
                    "C14",
                ));
            }
            None => {
                return Err(BuildError::OutOfRangeSelect {
                    what: format!("`{}` is not an array, so it has no elements", self.name),
                });
            }
        }
        let r = t.fixed_unpacked_array_range();
        let elem = t
            .element_type()
            .ok_or_else(|| missing(format!("element type of the array `{}`", self.name)))?;
        Ok((
            i64::from(r.left).min(i64::from(r.right)),
            i64::from(r.left).max(i64::from(r.right)),
            elem,
        ))
    }

    /// The element at declared index `i` of the array this is at.
    fn index(&self, i: i64) -> Result<Cursor<'d>, BuildError> {
        let (lo, hi, elem) = self.dim()?;
        if !(lo..=hi).contains(&i) {
            let r = self.ty.canonical().fixed_unpacked_array_range();
            return Err(BuildError::OutOfRangeSelect {
                what: format!("`{}` index {i} outside [{}:{}]", self.name, r.left, r.right),
            });
        }
        let ew = storage_width(&elem)
            .ok_or_else(|| missing(format!("stored width of an element of `{}`", self.name)))?;
        let mut path = self.path.clone();
        path.push(Step::Index(i));
        Ok(Cursor {
            root: self.root.clone(),
            whole: self.whole,
            ty: elem,
            mode: self.mode,
            path,
            name: format!("{}[{i}]", self.name),
            bit: self.bit + (i - lo) as u64 * ew,
        })
    }

    fn leaf(self) -> Result<LeafRef<'d>, BuildError> {
        let width = storage_width(&self.ty)
            .ok_or_else(|| missing(format!("stored width of `{}`", self.name)))?;
        let narrow = |v: u64| {
            u32::try_from(v).map_err(|_| {
                missing(format!(
                    "a window of `{}` within 32-bit offsets (the property is {} bits)",
                    self.name, self.whole
                ))
            })
        };
        let window = Window {
            bit: narrow(self.bit)?,
            width: narrow(width)?,
            field_width: narrow(self.whole)?,
        };
        let c = self.ty.canonical();
        let kind = if let Some(k) = real_kind(Some(self.ty)) {
            LeafKind::Real(k)
        } else if c.is_virtual_interface() {
            LeafKind::Vif
        } else if c.is_integral() {
            LeafKind::Int(ty_of(Some(self.ty), &format!("`{}`", self.name))?)
        } else if c.is_string() || c.is_chandle() {
            LeafKind::Skipped
        } else if array_shape(c) == Some(ArrayShape::Collection) {
            LeafKind::Collection
        } else {
            LeafKind::Other
        };
        Ok(LeafRef {
            root: self.root,
            name: self.name,
            path: self.path,
            window,
            mode: self.mode,
            kind,
            vt: self.ty,
        })
    }

    /// Every random leaf at or below this, in declaration order.
    fn random_leaves(self, out: &mut Vec<LeafRef<'d>>) -> Result<(), BuildError> {
        let t = self.ty.canonical();
        if t.is_unpacked_struct() {
            for i in 0..t.fields().count() {
                self.field(i as u32)?.random_leaves(out)?;
            }
            return Ok(());
        }
        if array_shape(t) == Some(ArrayShape::Fixed) {
            let (lo, hi, _) = self.dim()?;
            for i in lo..=hi {
                self.index(i)?.random_leaves(out)?;
            }
            return Ok(());
        }
        if self.mode == RandMode::None || t.is_unpacked_union() {
            return Ok(());
        }
        let leaf = self.leaf()?;
        match leaf.kind {
            LeafKind::Int(_) | LeafKind::Real(_) | LeafKind::Collection => out.push(leaf),
            LeafKind::Skipped => {}
            LeafKind::Vif => return Err(BuildError::VirtualInterfaceRand { name: leaf.name }),
            LeafKind::Other => {
                return Err(unsupported(
                    format!(
                        "the random member `{}` of type `{}` inside an unpacked struct or array \
                         (a class handle or associative array nested in a flat aggregate cannot \
                         be randomized)",
                        leaf.name,
                        leaf.vt.to_sv_string()
                    ),
                    "C14",
                ));
            }
        }
        Ok(())
    }
}

impl Builder<'_> {
    /// The cursor at the root of `sym`; a variable declared by
    /// [`Self::declare_aggregate_forced`] is random whatever its declaration.
    fn cursor_of<'d>(&self, sym: Symbol<'d>) -> Result<Cursor<'d>, BuildError> {
        let mut cur = Cursor::of(sym)?;
        if self.forced_roots.contains(&cur.root) {
            cur.mode = RandMode::Rand;
        }
        Ok(cur)
    }

    /// Declares every leaf of the unpacked-struct or fixed-size array variable
    /// `sym` random for this call whether or not it is declared `rand` (LRM
    /// 18.12: the arguments of `std::randomize` are random; 18.11 for a
    /// property), and returns their ids. A member's own `rand`/`randc`
    /// qualifier still decides its cyclic nature (18.4). The variable may then
    /// be named in the constraints like a property (`a[i]`, `a.sum()`,
    /// `foreach`, `s.m`).
    pub fn declare_aggregate_forced(
        &mut self,
        sym: Symbol<'_>,
    ) -> Result<Vec<Declared>, BuildError> {
        self.forced_roots.insert(sym.uid());
        self.declare_rand_aggregate(sym)
    }

    /// Declares every random leaf of the unpacked-struct or fixed-size
    /// unpacked-array property `sym` as a random variable, in declaration
    /// order, and returns their ids (idempotent). `sym` need not be `rand`
    /// itself: a struct with a `rand` member has random leaves (LRM 18.4).
    pub fn declare_rand_aggregate(&mut self, sym: Symbol<'_>) -> Result<Vec<Declared>, BuildError> {
        let cur = self.cursor_of(sym)?;
        if !is_aggregate_type(cur.ty) {
            return Err(missing(format!(
                "an unpacked struct or fixed-size array type for `{}` (use `declare_rand`)",
                sym.name()
            )));
        }
        let mut leaves = Vec::new();
        cur.random_leaves(&mut leaves)?;
        leaves.iter().map(|l| self.declare_leaf(l)).collect()
    }

    /// Declares element `idx` (declared indices, outermost dimension first) of
    /// the `rand` or `randc` unpacked-array property `array` as a random
    /// variable and returns its id (idempotent). It is named `a[2]` or `m[1][2]`.
    pub fn declare_rand_element(
        &mut self,
        array: Symbol<'_>,
        idx: &[i64],
    ) -> Result<u32, BuildError> {
        let mut cur = Cursor::of(array)?;
        for &i in idx {
            cur = cur.index(i)?;
        }
        if is_aggregate_type(cur.ty) {
            return Err(BuildError::OutOfRangeSelect {
                what: format!(
                    "`{}` is still an aggregate: name one index per unpacked dimension",
                    cur.name
                ),
            });
        }
        if cur.mode == RandMode::None {
            return Err(BuildError::NotRand { name: cur.name });
        }
        if idx.is_empty() {
            return Err(BuildError::OutOfRangeSelect {
                what: format!(
                    "`{}` is not an array element (use `declare_rand`)",
                    cur.name
                ),
            });
        }
        let leaf = cur.leaf()?;
        match self.declare_leaf(&leaf)? {
            Declared::Int(id) => Ok(id),
            Declared::Real(_) => Err(BuildError::RealConstraint {
                what: format!(
                    "`{}` is real: it is a real random variable, not an integral element",
                    leaf.name
                ),
            }),
            Declared::Array(_) => Err(BuildError::NonIntegral {
                what: format!("`{}` is an array, not an integral element", leaf.name),
            }),
        }
    }

    /// The key suffix of the array leaf at `path` of its property.
    pub(super) fn leaf_tag(path: &[Step]) -> String {
        let mut t = String::from("leaf");
        for st in path {
            match st {
                Step::Index(i) => t.push_str(&format!("[{i}]")),
                Step::Field(f) => t.push_str(&format!(".{f}")),
            }
        }
        t
    }

    /// Registers the dynamic array or queue `leaf` of an aggregate property as
    /// an array of its own (its handle sits at the leaf's window).
    pub(super) fn new_leaf_array(
        &mut self,
        leaf: &LeafRef<'_>,
        rand: bool,
    ) -> Result<u32, BuildError> {
        let mut info = self.array_info(leaf.root.clone(), leaf.name.clone(), leaf.vt, rand)?;
        if info.nested {
            return Err(unsupported(
                format!(
                    "`{}`: an array of arrays as an element or member of an aggregate",
                    leaf.name
                ),
                "C14",
            ));
        }
        info.window = Some(leaf.window);
        let id = self.arrays.len() as u32;
        self.arrays.push(info);
        Ok(id)
    }

    /// Declares the random leaf `leaf` (idempotent).
    fn declare_leaf(&mut self, leaf: &LeafRef<'_>) -> Result<Declared, BuildError> {
        let key = (leaf.root.clone(), leaf.path.clone());
        match leaf.kind {
            LeafKind::Int(_) => {
                if let Some(&id) = self.elem_ix.get(&key) {
                    return Ok(Declared::Int(id));
                }
                let id = self.new_rand_var(
                    leaf.root.clone(),
                    leaf.name.clone(),
                    leaf.vt,
                    leaf.randc(),
                    leaf.path.clone(),
                    Some(leaf.window),
                )?;
                self.elem_ix.insert(key, id);
                Ok(Declared::Int(id))
            }
            LeafKind::Real(kind) => {
                if let Some(&id) = self.real_leaf_ix.get(&key) {
                    return Ok(Declared::Real(id));
                }
                if leaf.randc() {
                    return Err(BuildError::RealConstraint {
                        what: format!(
                            "`randc` variable `{}` is real; `randc` is for integral types only \
                             (IEEE 1800-2023 18.4.2)",
                            leaf.name
                        ),
                    });
                }
                let id = self.real_vars.len() as u32;
                self.real_vars.push(RealVarInfo {
                    symbol: leaf.root.clone(),
                    name: leaf.name.clone(),
                    kind,
                    window: Some(leaf.window),
                });
                self.real_leaf_ix.insert(key, id);
                Ok(Declared::Real(id))
            }
            LeafKind::Collection => {
                let key = leaf.root.derive(&Self::leaf_tag(&leaf.path));
                if let Some(&id) = self.array_ix.get(&key) {
                    return Ok(Declared::Array(id));
                }
                if leaf.randc() {
                    return Err(unsupported(
                        format!("the `randc` array `{}`: per-element cycling", leaf.name),
                        "C14",
                    ));
                }
                let id = self.new_leaf_array(leaf, true)?;
                self.array_ix.insert(key, id);
                Ok(Declared::Array(id))
            }
            LeafKind::Vif | LeafKind::Skipped | LeafKind::Other => Err(missing(format!(
                "a randomizable value for `{}` of type `{}`",
                leaf.name,
                leaf.vt.to_sv_string()
            ))),
        }
    }

    /// Follows `chain` to its leaf, or to the run-time choice among leaves an
    /// index that is not a constant makes.
    pub(super) fn resolve_chain<'d>(&mut self, chain: &Chain<'d>) -> Result<Sel<'d>, BuildError> {
        let cur = self.cursor_of(chain.root)?;
        self.walk(cur, &chain.steps)
    }

    fn walk<'d>(&mut self, cur: Cursor<'d>, steps: &[RawStep<'d>]) -> Result<Sel<'d>, BuildError> {
        let Some((first, rest)) = steps.split_first() else {
            return Ok(Sel::Leaf(cur.leaf()?));
        };
        match *first {
            RawStep::Field(i) => self.walk(cur.field(i)?, rest),
            RawStep::Const(i) => self.walk(cur.index(i)?, rest),
            RawStep::Index(e) => {
                let ix = self.expr(e)?;
                if let Some(i) = Self::constant_index(&ix) {
                    let (lo, hi, _) = cur.dim()?;
                    if (lo..=hi).contains(&i) {
                        return self.walk(cur.index(i)?, rest);
                    }
                }
                self.not_in_function(
                    "an element of an unpacked array property at a computed index",
                )?;
                self.arrays_allowed("an element of an unpacked array property")?;
                let mut has_var = false;
                ix.for_each_var(&mut |_, _| has_var = true);
                if has_var {
                    return Err(BuildError::BadArray {
                        what: format!(
                            "a random variable in the index of the array `{}`: an index is a \
                             constant, a state variable, a loop variable or the size (IEEE \
                             1800-2023 18.5.7.1)",
                            cur.name
                        ),
                    });
                }
                // Every element is a candidate; the registry keeps the one the
                // index names (or reports an index outside the array if the
                // constraint is live).
                let (lo, hi, _) = cur.dim()?;
                let mut elems = Vec::new();
                for i in lo..=hi {
                    elems.push(self.walk(cur.index(i)?, rest)?);
                }
                Ok(Sel::Pick {
                    index: ix,
                    low: lo,
                    elems,
                })
            }
        }
    }

    /// The value of `ix` if it involves no variable, state or array node.
    pub(super) fn constant_index(ix: &Expr) -> Option<i64> {
        if ix.any_node(&mut |n| matches!(n, Expr::Var(..) | Expr::State(..) | Expr::Array(_))) {
            return None;
        }
        let v = eval(ix, &Assignment::default()).ok()?;
        const_i64(ix.ty(), &v)
    }

    /// The leaf `chain` names, and its id if it is a declared random variable;
    /// `what` names the construct for a run-time index.
    pub(super) fn declared_leaf<'d>(
        &mut self,
        chain: Chain<'d>,
        what: &str,
    ) -> Result<(LeafRef<'d>, Option<Declared>), BuildError> {
        let Sel::Leaf(leaf) = self.resolve_chain(&chain)? else {
            return Err(unsupported(
                format!("{what} that selects an element at a computed index"),
                "C14",
            ));
        };
        let key = (leaf.root.clone(), leaf.path.clone());
        let declared = match leaf.kind {
            LeafKind::Int(_) => self.elem_ix.get(&key).map(|&id| Declared::Int(id)),
            LeafKind::Real(_) => self.real_leaf_ix.get(&key).map(|&id| Declared::Real(id)),
            LeafKind::Vif | LeafKind::Skipped | LeafKind::Collection | LeafKind::Other => {
                return Err(BuildError::NonIntegral {
                    what: format!("`{}` of type `{}`", leaf.name, leaf.vt.to_sv_string()),
                });
            }
        };
        Ok((leaf, declared))
    }

    /// The error for a random leaf nobody declared.
    fn undeclared(leaf: &LeafRef<'_>) -> BuildError {
        unsupported(
            format!(
                "the random variable `{}`, a leaf of an aggregate property that was not declared \
                 random (`declare_rand_aggregate`)",
                leaf.name
            ),
            "C14",
        )
    }

    /// The state variable of the non-random leaf `leaf`, registered on first use.
    fn leaf_state(&mut self, leaf: &LeafRef<'_>, ty: Ty) -> Expr {
        let key = (leaf.root.clone(), leaf.path.clone());
        if let Some(&id) = self.leaf_state_ix.get(&key) {
            return Expr::State(id, self.states[id as usize].ty);
        }
        let id = self.states.len() as u32;
        self.states.push(StateInfo {
            root_bit: 0,
            symbol: leaf.root.clone(),
            name: leaf.name.clone(),
            ty,
            via: Vec::new(),
            window: Some(leaf.window),
            class_of: false,
        });
        self.leaf_state_ix.insert(key, id);
        Expr::State(id, ty)
    }

    /// The expression for one integral leaf: its random variable, or its state.
    fn leaf_expr(&mut self, leaf: &LeafRef<'_>) -> Result<Expr, BuildError> {
        let LeafKind::Int(ty) = leaf.kind else {
            return Err(BuildError::NonIntegral {
                what: format!("`{}` of type `{}`", leaf.name, leaf.vt.to_sv_string()),
            });
        };
        if leaf.mode == RandMode::None {
            return Ok(self.leaf_state(leaf, ty));
        }
        let key = (leaf.root.clone(), leaf.path.clone());
        let &id = self
            .elem_ix
            .get(&key)
            .ok_or_else(|| Self::undeclared(leaf))?;
        if self.frame.is_some() {
            return Err(self.rand_read_in_function(&leaf.name));
        }
        Ok(Expr::Var(id, self.vars[id as usize].ty))
    }

    fn sel_expr(&mut self, sel: Sel<'_>, ty: Ty) -> Result<Expr, BuildError> {
        match sel {
            Sel::Leaf(leaf) => {
                let x = self.leaf_expr(&leaf)?;
                Ok(if x.ty() == ty {
                    x
                } else {
                    Expr::Resize(Box::new(x), ty)
                })
            }
            Sel::Pick { index, low, elems } => {
                let elems = elems
                    .into_iter()
                    .map(|s| self.sel_expr(s, ty))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(Expr::Array(ArrayNode::Pick {
                    index: Box::new(index),
                    low,
                    elems,
                    ty,
                }))
            }
        }
    }

    /// The integral value `chain` names, of type `ty`.
    pub(super) fn aggregate_value(&mut self, chain: Chain<'_>, ty: Ty) -> Result<Expr, BuildError> {
        let sel = self.resolve_chain(&chain)?;
        self.sel_expr(sel, ty)
    }

    /// The bit-stream (LRM 6.24.3, 11.4.14) of the aggregate property `chain`
    /// names: its integral leaves concatenated, the first struct member or the
    /// array element at the left bound the most significant. A real, string or
    /// handle leaf is an error (no bit pattern is solved for it).
    pub(super) fn aggregate_bitstream(&mut self, chain: Chain<'_>) -> Result<Expr, BuildError> {
        let mut parts = Vec::new();
        let mut cur = self.cursor_of(chain.root)?;
        // Walk the chain's own steps first (constant steps only: a computed
        // index would pick among leaves, which a stream cannot).
        let mut rest: &[RawStep<'_>] = &chain.steps;
        while let Some((first, tail)) = rest.split_first() {
            cur = match *first {
                RawStep::Field(i) => cur.field(i)?,
                RawStep::Const(i) => cur.index(i)?,
                RawStep::Index(e) => {
                    let ix = self.expr(e)?;
                    let i = Self::constant_index(&ix).ok_or_else(|| {
                        unsupported("a bit-stream cast of an element at a computed index", "C2")
                    })?;
                    cur.index(i)?
                }
            };
            rest = tail;
        }
        self.stream_leaves(cur, &mut parts)?;
        let w = parts.iter().map(|p| p.ty().width).sum();
        Ok(Expr::Concat(parts, Ty::unsigned(w)))
    }

    fn stream_leaves(&mut self, cur: Cursor<'_>, out: &mut Vec<Expr>) -> Result<(), BuildError> {
        let t = cur.ty.canonical();
        if t.is_unpacked_struct() {
            for i in 0..t.fields().count() {
                self.stream_leaves(cur.field(i as u32)?, out)?;
            }
        } else if array_shape(t) == Some(ArrayShape::Fixed) {
            let r = t.fixed_unpacked_array_range();
            let (l, h) = (i64::from(r.left), i64::from(r.right));
            let idx: Vec<i64> = if l <= h {
                (l..=h).collect()
            } else {
                (h..=l).rev().collect()
            };
            for i in idx {
                self.stream_leaves(cur.index(i)?, out)?;
            }
        } else {
            let leaf = cur.leaf()?;
            let LeafKind::Int(ty) = leaf.kind else {
                return Err(BuildError::NonIntegral {
                    what: format!(
                        "`{}` of type `{}` in a bit-stream cast",
                        leaf.name,
                        leaf.vt.to_sv_string()
                    ),
                });
            };
            let x = self.leaf_expr(&leaf)?;
            out.push(Expr::Resize(Box::new(x), Ty::unsigned(ty.width)));
        }
        Ok(())
    }

    /// Element `i` (a declared index) of the fixed-size array `arr` names, of
    /// type `ty`.
    pub(super) fn aggregate_element(
        &mut self,
        arr: Expression<'_>,
        i: i64,
        ty: Ty,
    ) -> Result<Expr, BuildError> {
        let mut chain = aggregate_chain(arr, &self.forced_roots).ok_or_else(|| {
            unsupported(
                "a method over an unpacked array that is not a property (or a member of a struct \
                 property) of this class",
                "C14",
            )
        })?;
        chain.steps.push(RawStep::Const(i));
        self.aggregate_value(chain, ty)
    }

    /// The real value `chain` names, of grid type `kind`.
    pub(super) fn real_aggregate(
        &mut self,
        chain: Chain<'_>,
        kind: Fk,
    ) -> Result<RealExpr, BuildError> {
        let leaf = match self.resolve_chain(&chain)? {
            Sel::Leaf(leaf) => leaf,
            Sel::Pick { .. } => {
                return Err(BuildError::RealConstraint {
                    what: "a real element of an array at a computed index (only an integral \
                           element can be chosen by a state or loop variable)"
                        .into(),
                });
            }
        };
        if !matches!(leaf.kind, LeafKind::Real(_)) {
            return Err(missing(format!("a real value for `{}`", leaf.name)));
        }
        if leaf.mode == RandMode::None {
            let st = self.leaf_state(&leaf, state_ty(kind));
            return self.real_state(st, kind);
        }
        let key = (leaf.root.clone(), leaf.path.clone());
        let &id = self
            .real_leaf_ix
            .get(&key)
            .ok_or_else(|| Self::undeclared(&leaf))?;
        Ok(RealExpr::Var(id))
    }
}