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
//! Classes plan (`docs/superpowers/plans/2026-10-03-classes.md`), Task 2:
//! class template dedup (`ClassTemplateId`/`ClassTemplateKey`) and member
//! classification (`ClassMembers`) — LRM 8.4, 8.5, 8.9 (classification
//! only; `fields`/`methods` are not yet lowered into any storage/codegen
//! shape, that starts Task 5). Pure data, no codegen dependency yet (this
//! task's own acceptance text): nothing in `elaborate.rs`'s `Netlist`/
//! `Template` pipeline calls into this module yet, so `Template`'s already-
//! "stable from here on" shape (`template.rs`'s own doc comment) is left
//! untouched.
//!
//! **`ClassTemplateId`/`ClassTemplateKey` vs. `TemplateId`/`TemplateKey`**
//! (`dedup.rs`, `mod.rs`): structurally parallel (same two-field key shape,
//! same hash-then-verify dedup discipline, ARCHITECTURE §7 item 7), but the
//! *ground truth* half of "hash-then-verify" is different, for a reason
//! specific to classes rather than modules:
//!
//! - A module/interface/program `InstanceBody` is dedup'd the hard way
//!   (`dedup.rs::merge_groups_within_bucket`, `Symbol::instance_body_has_same_type`)
//!   because `Design::compile()` forces `DisableInstanceCaching` — `sv-lang`
//!   itself never pointer-shares two instance bodies, even syntactically
//!   identical ones (verified live in `netlist_dedup.rs`'s
//!   `disable_instance_caching_means_no_pointer_sharing_before_our_own_dedup`).
//! - A class specialization is the opposite: `GenericClassDefSymbol` caches
//!   every specialization it ever builds, keyed by its resolved parameter
//!   binding (`vendor/include/slang/ast/symbols/ClassSymbols.h`'s own
//!   `specMap`/`uninstantiatedSpecMap`, `vendor/source/ast/symbols/ClassSymbols.cpp`),
//!   so two `new Box#(int)` (or `Box#(int)`-typed) references anywhere in one
//!   `Compilation` resolve to the LITERAL SAME `ClassType` symbol —
//!   `Symbol`'s own pointer-identity `PartialEq` (`ast.rs`'s
//!   `self.raw.ptr == other.raw.ptr`), not merely a structurally-equivalent
//!   one. Verified live in `netlist_classes.rs`'s
//!   `same_specialization_is_pointer_identical_not_merely_structurally_equal`
//!   test.
//!
//! So this module's "verify" ground truth ([`same_specialization`]) is
//! symbol-identity, never a re-derived member-by-member structural
//! comparison — it is *stronger* than `instance_body_has_same_type` (exact
//! identity, not "same shape"), and it is exactly as cheap as the `==` it
//! is. `params_hash` is still only a candidate-bucketing FILTER, never
//! trusted alone: a 64-bit `DefaultHasher` digest of two DIFFERENT
//! parameter bindings could in principle collide (ARCHITECTURE §7 item 7's
//! own rationale for `TemplateKey.params_hash`), and
//! [`same_specialization`] is what catches that without ever trusting the
//! hash — see `netlist_classes.rs`'s
//! `hash_bucket_collision_between_different_specializations_is_rejected`.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};

use sv_lang_kinds::SymbolKind;

use crate::netlist::{ClassTemplateId, ClassTemplateKey, ElabError, hash_then_verify_dedup};
use crate::symid::SymbolId;

// `ClassTemplateId`/`ClassTemplateKey` themselves now live, unconditionally,
// in `netlist/mod.rs` alongside `TemplateId`/`TemplateKey` (Task 3 deviation:
// see that module's doc comment on `ClassTemplateId` for why) — this module
// keeps their sv-lang-backed construction (`class_template_key_of`,
// `same_specialization`, dedup) and documents their shape here as before.
//
// `ClassTemplateKey` is the candidate-bucketing key for class-template dedup
// (the FILTER half of hash-then-verify — see this module's doc comment
// above). `definition` is a dense id for the class's OWN definition
// identity: for a specialization of a generic class, the generic class's
// `GenericClassDef` symbol (`Type::class_generic_class()`) — shared by every
// specialization of that one generic class, so two different specializations
// of `Box#(T)` get the SAME `definition` and are told apart only by
// `params_hash`; for a plain (non-generic) class, the class's own `ClassType`
// symbol itself (every textually distinct `class Foo; endclass` is its own
// definition, exactly like a module's `Definition`).

/// Interns a class/generic-class DEFINITION symbol to a stable dense id,
/// keyed by [`crate::symid::SymbolUid::uid`] — the same stable-key discipline
/// [`super::dedup::DefinitionTable`] uses for module `Definition`s, kept as
/// its own small table rather than shared with that one because the two
/// intern different symbol kinds (`Definition` there, `ClassType`/
/// `GenericClassDef` here) and nothing requires their dense ids to share one
/// namespace.
#[derive(Default)]
pub struct ClassDefinitionTable {
    by_id: HashMap<SymbolId, u32>,
}

impl ClassDefinitionTable {
    pub fn intern(&mut self, def: sv_lang::Symbol<'_>) -> u32 {
        use crate::symid::SymbolUid;
        let next_id = self.by_id.len() as u32;
        *self.by_id.entry(def.uid()).or_insert(next_id)
    }
}

/// The definition-identity half of a [`ClassTemplateKey`]: the generic
/// class's own symbol for a specialization, or the class's own symbol for a
/// plain (non-generic) class — see [`ClassTemplateKey::definition`]'s doc
/// comment.
fn class_definition_symbol<'d>(ty: sv_lang::Type<'d>) -> sv_lang::Symbol<'d> {
    let ty = ty.canonical();
    match ty.class_generic_class() {
        Some(generic) => generic,
        None => ty.as_symbol(),
    }
}

/// Task 2's `class_param_binding_hash` (parallel to
/// `vj-codegen::mangle::param_binding_hash`, which this cannot literally
/// reuse: that function reads `sym.parameters()`, whose own doc/SAFETY
/// comment — quoted in `dedup.rs::template_key_of` — says its count "is 0
/// for non-instances", so it is populated only on an `Instance`-kind symbol,
/// never a `ClassType`). A specialized class's bound parameters are instead
/// real `Parameter`/`TypeParameter` members of the class's OWN scope
/// (`slang::ast::ParameterBuilder::createParam` adds them there at
/// specialization time, verified against
/// `vendor/source/ast/symbols/ClassSymbols.cpp`), so this walks
/// `class_sym.members()` directly and hashes each one's `(name(),
/// parameter_value())` — `parameter_value()` is documented to print "its
/// value or target type", which is exactly what distinguishes a `parameter
/// int W = 8` binding from a `parameter type T = int` one without this
/// function needing two different code paths for value vs. type parameters.
/// A plain (non-generic) class has no `Parameter`/`TypeParameter` members at
/// all, so this returns the same fixed empty-input hash for every one of
/// them — harmless, since `ClassTemplateKey.definition` already tells two
/// different plain classes apart on its own.
///
/// Deterministic (fixed-key `DefaultHasher`, not `HashMap`'s per-process-
/// randomized `RandomState`) for the same reason `template_key_of` is: a
/// candidate-bucketing filter must hash the same input to the same output
/// across independent `elaborate()`-style runs.
pub fn class_param_binding_hash(class_sym: &sv_lang::Symbol<'_>) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for member in class_sym.members() {
        if matches!(
            member.kind(),
            SymbolKind::Parameter | SymbolKind::TypeParameter
        ) {
            member.name().hash(&mut hasher);
            member.parameter_value().hash(&mut hasher);
        }
    }
    hasher.finish()
}

/// Builds one specialization's [`ClassTemplateKey`] — the definition half
/// via [`class_definition_symbol`]/[`ClassDefinitionTable::intern`], the
/// parameter-binding half via [`class_param_binding_hash`].
pub fn class_template_key_of(
    defs: &mut ClassDefinitionTable,
    ty: sv_lang::Type<'_>,
) -> ClassTemplateKey {
    let ty = ty.canonical();
    let definition = defs.intern(class_definition_symbol(ty));
    let params_hash = class_param_binding_hash(&ty.as_symbol());
    ClassTemplateKey {
        definition,
        params_hash,
    }
}

/// Classes plan Task 9 (LRM 8.25): a string that is equal for two class
/// types iff they are the same specialization of the same class, and that
/// is stable across everything a `Symbol` is not -- `sv-lang` 0.1.9 exposes
/// no pointer, `Hash` or `Ord` on a `Symbol` (so a registry keyed by the
/// specialization itself, never just by its generic's [`SymbolUid::uid`],
/// cannot be a plain map), and every specialization of one generic class
/// shares that one `uid` (as do their corresponding members), which is
/// exactly the ambiguity this key resolves. Composed of:
///
/// - the ENCLOSING class's own key, if `ty` is declared inside another class
///   (8.25's nested classes): `Outer#(int)::Inner` and `Outer#(string)::
///   Inner` are different classes with the same `Inner` uid;
/// - `ty`'s own definition uid (the generic class's, for a specialization);
/// - every bound `Parameter`/`TypeParameter` (the same members
///   [`class_param_binding_hash`] hashes) as `name=value`. A value
///   parameter prints through `parameter_value()`; a TYPE parameter
///   recurses into this function when its target is itself a class (so
///   `Box#(Outer1::Inner)` and `Box#(Outer2::Inner)`, whose target types
///   both PRINT as `Inner`, stay distinct) and otherwise uses the target's
///   canonical SV spelling.
///
/// Unlike [`class_param_binding_hash`] this is exact, not a bucketing
/// filter: it is what the codegen registry and the symbol mangler key on.
/// A residual ambiguity (two different types that print identically) is
/// caught loudly by the registry's own collision check, never silently
/// merged.
pub fn class_specialization_key(ty: sv_lang::Type<'_>) -> String {
    let mut out = String::new();
    push_class_key(ty.canonical().as_symbol(), &mut out);
    out
}

fn push_class_key(class_sym: sv_lang::Symbol<'_>, out: &mut String) {
    use crate::symid::SymbolUid;
    use std::fmt::Write as _;

    if let Some(parent) = class_sym.parent()
        && parent.kind() == SymbolKind::ClassType
    {
        push_class_key(parent, out);
        out.push('/');
    }
    let ty = class_sym.as_type();
    let definition = match ty.and_then(|t| t.class_generic_class()) {
        Some(generic) => generic,
        None => class_sym,
    };
    let _ = write!(out, "{:?}", definition.uid());
    for member in class_sym.members() {
        // Only a specialization's bound parameters take part in its
        // identity; every other member kind is the class's body. (`if`,
        // not a `match` with a wildcard: a membership test, not a
        // classification of `SymbolKind` -- `xtask lint-unimplemented`.)
        if member.kind() == SymbolKind::Parameter {
            let _ = write!(
                out,
                "#{}={}",
                member.name(),
                member.parameter_value().unwrap_or_default()
            );
        } else if member.kind() == SymbolKind::TypeParameter {
            let _ = write!(out, "#{}=", member.name());
            match member.declared_type().map(|t| t.canonical()) {
                Some(target) if target.is_class() => {
                    out.push('<');
                    push_class_key(target.as_symbol(), out);
                    out.push('>');
                }
                Some(target) => out.push_str(&target.to_sv_string()),
                None => out.push_str(&member.parameter_value().unwrap_or_default()),
            }
        }
    }
}

/// The VERIFY ground truth for class-template dedup (this module's doc
/// comment): two specializations are the same template iff they are
/// literally the same `ClassType` symbol. Never a structural re-derivation
/// (unlike `dedup.rs`'s `instance_body_has_same_type`) — slang's own
/// specialization cache already guarantees pointer identity for a genuinely
/// matching binding, so re-deriving "same shape" here would be strictly
/// weaker, not stronger, than just comparing identity directly. Exposed
/// (not just an internal helper of [`assign_class_template_ids`]) so a test
/// can drive [`hash_then_verify_dedup`] directly with a forced, fabricated
/// [`ClassTemplateKey`] collision between two genuinely different classes —
/// the same "bypass the real hash, exercise only the verify step" shape
/// `netlist_dedup.rs`'s own
/// `hash_bucket_collision_between_different_modules_is_rejected_by_pairwise_oracle`
/// uses for module `Template`s.
pub fn same_specialization(a: sv_lang::Type<'_>, b: sv_lang::Type<'_>) -> bool {
    a.canonical().as_symbol() == b.canonical().as_symbol()
}

/// Task 2 step 5: hash-then-verify dedup over a caller-supplied slice of
/// resolved class `Type`s (every element some specialization's or plain
/// class's own `ClassType`), returning one [`ClassTemplateId`] per input
/// element, index-aligned with `types` — two elements get the same id iff
/// [`same_specialization`] confirms they are the one underlying symbol.
/// Built directly on [`hash_then_verify_dedup`] (`dedup_algorithm.rs`'s
/// already-tested, generic, sv-lang-free algorithm) rather than a
/// re-implementation of its bucket/merge loop, tagging each `Type` with its
/// own [`ClassTemplateKey`] up front (a plain, non-`Fn`-constrained loop,
/// since building that key needs `&mut ClassDefinitionTable`) exactly the
/// way `dedup.rs::merge_groups_within_bucket` tags each module body with its
/// own `TemplateKey` before bucketing.
pub fn assign_class_template_ids(types: &[sv_lang::Type<'_>]) -> Vec<ClassTemplateId> {
    let mut defs = ClassDefinitionTable::default();
    let tagged: Vec<(ClassTemplateKey, sv_lang::Type<'_>)> = types
        .iter()
        .map(|ty| (class_template_key_of(&mut defs, *ty), *ty))
        .collect();

    let groups = hash_then_verify_dedup(
        &tagged,
        |(key, _ty)| *key,
        |(_, a), (_, b)| same_specialization(*a, *b),
    );

    let mut ids = vec![ClassTemplateId(0); types.len()];
    for (group_index, indices) in groups.into_iter().enumerate() {
        for i in indices {
            ids[i] = ClassTemplateId(group_index as u32);
        }
    }
    ids
}

/// Task 2 step 5's discovery mechanism, named explicitly in the plan: "walks
/// every instantiated specialization (every `new()` call site's resolved
/// type), not just syntactic class declarations". This is the only way a
/// generic class specialization becomes reachable at all when it is
/// otherwise never a direct scope member anywhere in `design.root()`'s own
/// symbol tree — `GenericClassDefSymbol`'s `specMap` (this module's own doc
/// comment) is a private cache, not a scope, so a specialization that is
/// only ever reached through a `new Box#(int)` expression has no OTHER
/// discoverable home in the AST.
///
/// Visits every symbol in `eval`'s design (`Symbol::visit`, the same
/// design-wide walk `check_no_class_declarations`/`discover_processes`
/// already use elsewhere in this workspace) and, at each one, walks its
/// `initializer()` (a variable/property's `= expr`) and `body()` (a
/// procedural block's or subroutine's — including a class method's and the
/// constructor's — root statement) generically via [`sv_lang::SemNode::children`]
/// — the one tree accessor that already spans every AST domain (expression,
/// statement, timing control, …) — checking only
/// `ExpressionKind::NewClass` and otherwise recursing unconditionally. This
/// is a "collect one kind, visit everything the same way" walk, not a
/// classification match, so it carries none of ARCHITECTURE §7 item 9's
/// exhaustive-kind-match obligation: it never branches on, nor chooses
/// different behavior for, any other node kind.
///
/// **Scope boundary, stated rather than silently narrowed**: this walk finds
/// a specialization only where a `new(...)` expression names it. A
/// specialization referenced ONLY through a declared variable's type with no
/// `new()` anywhere in the design (e.g. a bare `Box#(int) handle;`, always
/// `null`, never allocated) is not discovered by this function — exactly the
/// plan's own literal text for this step, and consistent with this task's
/// job being "the identity a `new()`-allocated object's `ObjEntry.template`
/// field will need" (Task 5), not a bare declared type's set of reachable
/// specializations. Task 9 (parameterized classes) revisits specialization
/// discovery as real codegen consumes it.
pub fn collect_new_class_types<'d>(eval: &'d sv_lang::EvalSession<'d>) -> Vec<sv_lang::Type<'d>> {
    discover_classes(eval).0
}

/// Every class a static property of which is initialized by a NON-constant
/// expression (`static bit m__initialized = __deferred_init();`) that the
/// design names anywhere -- a `new`, a variable's or typedef's declared type,
/// a base class, or a declaration -- not only a `new` site. LRM 6.21 / 8.9:
/// a static property is initialized once, before time zero, whether or not
/// anything ever touches it (UVM registers every `uvm_*_utils` type this
/// way), so each such class needs a time-zero initializer.
pub fn classes_with_dynamic_static_init<'d>(
    eval: &'d sv_lang::EvalSession<'d>,
) -> Vec<sv_lang::Symbol<'d>> {
    let (_, scanned) = discover_classes(eval);
    scanned
        .into_iter()
        .filter(|cls| {
            classify_members(*cls).is_ok_and(|m| {
                m.statics.iter().any(|s| {
                    s.initializer()
                        .is_some_and(|init| init.constant_value().is_none())
                })
            })
        })
        .collect()
}

/// Every method and constructor of every class the design names (each class
/// once, discovery order): the code a class-handle call may run.
pub fn class_method_symbols<'d>(eval: &'d sv_lang::EvalSession<'d>) -> Vec<sv_lang::Symbol<'d>> {
    let (_, scanned) = discover_classes(eval);
    scanned
        .into_iter()
        .filter_map(|cls| classify_members(cls).ok())
        .flat_map(|m| m.methods.into_iter().chain(m.ctor))
        .collect()
}

/// [`collect_new_class_types`]'s walk, also returning every class symbol it
/// scanned (each exactly once, in discovery order).
fn discover_classes<'d>(
    eval: &'d sv_lang::EvalSession<'d>,
) -> (Vec<sv_lang::Type<'d>>, Vec<sv_lang::Symbol<'d>>) {
    let mut out = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut pending = Vec::new();
    let mut scanned = Vec::new();
    scan_new_class_types(
        eval.design().root(),
        &mut out,
        &mut seen,
        &mut pending,
        &mut scanned,
    );
    // A specialization is scanned once, when first named; scanning it can
    // name more (a `new` of another one, a base class).
    let mut done = 0;
    loop {
        while done < out.len() {
            let ty = out[done];
            done += 1;
            pending.push(ty.as_symbol());
            pending.extend(base_chain(ty).into_iter().map(|b| b.as_symbol()));
        }
        let Some(cls) = pending.pop() else { break };
        if seen.insert(cls.hierarchical_path().to_string()) {
            scanned.push(cls);
            scan_new_class_types(cls, &mut out, &mut seen, &mut pending, &mut scanned);
        }
    }
    (out, scanned)
}

/// One [`collect_new_class_types`] walk of the symbol tree under `root`.
///
/// A class specialization that nothing in the tree DECLARES -- only a type
/// alias (`typedef uvm_object_registry#(T, "T") type_id;`, whose `get()` is
/// reached through `type_id::get()`), a variable's declared type or a `new`
/// names it -- is not a child of any scope the walk descends, so its
/// methods' `new` sites would be missed. Every class a symbol's declared
/// type names is therefore queued in `pending` for the same scan (once per
/// specialization, keyed by its hierarchical path).
fn scan_new_class_types<'d>(
    root: sv_lang::Symbol<'d>,
    out: &mut Vec<sv_lang::Type<'d>>,
    seen: &mut std::collections::HashSet<String>,
    pending: &mut Vec<sv_lang::Symbol<'d>>,
    scanned: &mut Vec<sv_lang::Symbol<'d>>,
) {
    root.visit(|sym| {
        // A module elaborated only as an uninstantiated definition (not a
        // top, never instantiated) or a generate branch not taken runs no
        // code: its `new` sites -- whose class parameters may be error types
        // there -- are not the design's.
        if crate::netlist::is_uninstantiated_scope(&sym) {
            return sv_lang::Walk::Skip;
        }
        if sym.kind() == SymbolKind::ClassType && seen.insert(sym.hierarchical_path().to_string()) {
            scanned.push(sym);
        }
        if let Some(ty) = sym.declared_type()
            && ty.canonical().is_class()
        {
            pending.push(ty.canonical().as_symbol());
        }
        if let Some(init) = sym.initializer() {
            collect_new_class_types_from(init.as_sem_node(), out, pending);
        }
        if let Some(body) = crate::process::cfg::proc_body(&sym) {
            collect_new_class_types_from(body.as_sem_node(), out, pending);
        }
        // LRM 8.24: an out-of-block method (`extern function f(); ... function
        // C::f();`) is a member of the class only as a `MethodPrototype`; its
        // body symbol is reached through the prototype, not by the walk.
        if sym.kind() == SymbolKind::MethodPrototype
            && let Some(imp) = sym.method_prototype_subroutine()
        {
            // Walk the whole out-of-block subroutine symbol, not only its body
            // statement: its locals (`static T x = new;`) carry initializers.
            scan_new_class_types(imp, out, seen, pending, scanned);
        }
        sv_lang::Walk::Continue
    });
}

fn collect_new_class_types_from<'d>(
    node: sv_lang::SemNode<'d>,
    out: &mut Vec<sv_lang::Type<'d>>,
    pending: &mut Vec<sv_lang::Symbol<'d>>,
) {
    if let Some(expr) = node.as_expression() {
        if expr.kind() == sv_lang_kinds::ExpressionKind::NewClass
            && let Some(ty) = expr.expr_type()
        {
            // LRM 8.25: `typedef vector#(4) Vfour; Vfour f = new;` types the
            // `new` as the TypeAlias; every consumer keys on the class symbol.
            out.push(ty.canonical());
        }
        // A static method called through its class (`uvm_typeid#(T)::get()`)
        // names that specialization without any declaration: scan it too.
        if expr.kind() == sv_lang_kinds::ExpressionKind::Call
            && expr.is_system_call() != Some(true)
            && let Some(cls) = expr
                .call_subroutine()
                .and_then(|s| s.parent())
                .filter(|p| p.kind() == SymbolKind::ClassType)
        {
            pending.push(cls);
        }
    }
    for child in crate::process::cfg::live_children(&node) {
        collect_new_class_types_from(child, out, pending);
    }
}

/// Task 2 step 1's `base_chain`: `ty`'s own ancestors, root (outermost) base
/// first, `ty` itself NOT included — `ObjectLayout::for_template` (Task 6)
/// concatenates this with `ty`'s own declared properties afterward, so
/// including `ty` here would double it. Repeats `Type::class_base()` until
/// it returns `None` (a root class with no `extends` clause).
pub fn base_chain<'d>(ty: sv_lang::Type<'d>) -> Vec<sv_lang::Type<'d>> {
    let mut chain = Vec::new();
    let mut cur = ty.class_base();
    while let Some(base) = cur {
        cur = base.class_base();
        chain.push(base);
    }
    chain.reverse();
    chain
}

/// Task 2 step 1's `flattened_interfaces`: a thin wrapper over
/// `Type::class_implemented_interfaces()`, which slang itself already
/// returns pre-flattened through another implemented interface's own
/// `extends` chain (confirmed live, Task 8: `interface class ic2 extends
/// ic1; class x implements ic2;` makes `x`'s own call return BOTH `ic2`
/// and `ic1`).
///
/// Correction (Task 8, found running its own `interface_class_via_base_
/// deferred_impl.sv` fixture -- this module's own earlier doc comment
/// claimed `ty.class_implemented_interfaces()` was ALSO already flattened
/// "transitively ... through a base class", which is false): `ty`'s own
/// call reflects only `ty`'s OWN `implements` clause (`ClassType::
/// implementsIfaces` is populated solely by `handleImplements`, which runs
/// only when `ty` itself declares one) -- a `Derived extends Base` with no
/// `implements` clause of its own, whose `Base` directly `implements
/// IFoo`, has an EMPTY `flattened_interfaces(derived_ty)` even though LRM
/// 8.26's own text ("a subclass implicitly implements all of the interface
/// classes implemented by its superclass") makes `Derived` an `IFoo` too.
/// A caller that needs the FULL transitive set across a base chain must
/// call this once per level and union the results -- `VtableLayout::
/// for_template`'s own Task 8 section does exactly that; this function
/// itself stays the same thin, one-level wrapper `base_chain`'s own shape
/// expects so Task 8 (interface classes) has one stable name to call.
pub fn flattened_interfaces<'d>(ty: sv_lang::Type<'d>) -> Vec<sv_lang::Type<'d>> {
    ty.class_implemented_interfaces().collect()
}

/// Task 2 step 2's `ClassMembers`: one class's own (non-inherited) members,
/// split by role. `statics`/`fields` are `ClassProperty` members split by
/// `variable_lifetime()` (8.9: a `static` property has one copy for the
/// whole simulation; an ordinary, "automatic"-lifetime one is per-object);
/// `methods` is every USER-declared `Subroutine`/`MethodPrototype` member
/// that is not the constructor; `ctor` is the `Subroutine` member flagged
/// `MethodFlags::CONSTRUCTOR` (8.7), if this class declares one. All four
/// are in `members()`'s own declaration order — this task's own tests rely
/// on that order, and no later task may re-sort them.
///
/// "USER-declared" is load-bearing: `slang` adds 8 implicit, bodied
/// `Subroutine` members to EVERY class — `randomize`, `pre_randomize`,
/// `post_randomize`, `get_randstate`, `set_randstate`, `srandom`,
/// `rand_mode`, `constraint_mode` (LRM 18.6/18.12–18.14's "every class
/// ... shall have the following built-in methods") — each flagged
/// `MethodFlags::BUILT_IN`, verified live against a plain `class Base; int
/// a; function void bump(); endclass` fixture
/// (`netlist_classes.rs`'s own regression: `class_sym.members()` for that
/// class yields `bump` PLUS all 8 of these, not `bump` alone). `classify_members`
/// excludes them from `methods` — this plan's own header is explicit that
/// `randomize()`/constraint solving (18.1–18.12/18.16–18.17) is the sibling
/// constraints plan's job, not this one's, and dumping these 8 into
/// `methods` would make Task 7's vtable-slot assignment try to mangle/lower
/// them as if they were ordinary user methods.
#[derive(Debug, Clone)]
pub struct ClassMembers<'d> {
    pub statics: Vec<sv_lang::Symbol<'d>>,
    pub fields: Vec<sv_lang::Symbol<'d>>,
    pub methods: Vec<sv_lang::Symbol<'d>>,
    pub ctor: Option<sv_lang::Symbol<'d>>,
}

/// IEEE 1800-2023 18.5.1 checks on one constraint block of a class: an
/// explicit `extern constraint p;` with no external block is an error, and
/// "it shall be an error if a constraint block of the same name as a
/// prototype appears in the same class declaration". slang only warns
/// (MemberImplNotFound) and accepts the duplicate, so this catches both once
/// per class, whether or not anything ever instantiates or randomizes it.
fn check_constraint_member<'d>(
    class_sym: sv_lang::Symbol<'d>,
    member: sv_lang::Symbol<'d>,
    seen: &mut std::collections::HashSet<String>,
) -> Result<(), ElabError> {
    if !seen.insert(member.name().to_string()) {
        return Err(ElabError::Frontend(format!(
            "class `{}` declares the constraint block `{}` more than once \
             (IEEE 1800-2023 18.5.1)",
            class_sym.name(),
            member.name()
        )));
    }
    let flags = member.constraint_block_flags();
    if flags.contains(sv_lang::ConstraintBlockFlags::EXPLICIT_EXTERN)
        && !flags.contains(sv_lang::ConstraintBlockFlags::PURE)
        && member
            .constraint_block_constraints()
            .and_then(|c| c.as_constraint())
            .is_none_or(|c| c.kind() == sv_lang::kinds::ConstraintKind::Invalid)
    {
        return Err(ElabError::Frontend(format!(
            "`extern constraint {};` in class `{}` has no external constraint \
             block (IEEE 1800-2023 18.5.1)",
            member.name(),
            class_sym.name()
        )));
    }
    Ok(())
}

/// Runs the 18.5.1 constraint-prototype checks over `class_sym` without
/// classifying the rest of the class, so a declared-but-unused class is still
/// diagnosed.
pub fn check_class_constraints(class_sym: sv_lang::Symbol<'_>) -> Result<(), ElabError> {
    let mut seen = std::collections::HashSet::new();
    for member in class_sym.members() {
        if member.kind() == SymbolKind::ConstraintBlock {
            check_constraint_member(class_sym, member, &mut seen)?;
        }
    }
    Ok(())
}

/// Task 2 step 2: one pass over `class_sym.members()`, classifying every
/// member into [`ClassMembers`]. Every `SymbolKind` a `ClassType`'s own
/// scope can legitimately contain is explicitly listed — never a blanket
/// `_` — so a genuinely unrecognized kind still falls to the typed-error arm
/// below (ARCHITECTURE §7 item 9), matching `template.rs::build_members`'s
/// own "known-benign, not a blanket `_`" pattern for the kinds this task
/// does not itself classify: `Parameter`/`TypeParameter` (a specialization's
/// own bound parameters — contribute to [`class_param_binding_hash`], not
/// here), `ClassType`/`GenericClassDef` (a nested class declaration — Task
/// 9's job, its own independent `ClassTemplateId` if ever specialized/`new`'d,
/// not a member of ITS enclosing class's `ClassMembers`), `ConstraintBlock`/
/// `CovergroupType` (this plan's own header: `randomize()`/constraint
/// solving and coverage are explicitly the sibling constraints/coverage
/// plans' job, not this one's), and the usual scope noise every symbol table
/// in this workspace already treats as contributing nothing
/// (`TypeAlias`/`ForwardingTypedef`/`EmptyMember`/`TransparentMember`/
/// `DeferredMember`/`Attribute`/`WildcardImport`/`ExplicitImport`/`LetDecl`).
pub fn classify_members<'d>(class_sym: sv_lang::Symbol<'d>) -> Result<ClassMembers<'d>, ElabError> {
    use sv_lang::{MethodFlags, VariableLifetime};

    let mut statics = Vec::new();
    let mut fields = Vec::new();
    let mut methods = Vec::new();
    let mut ctor = None;
    let mut constraint_names = std::collections::HashSet::new();

    for member in class_sym.members() {
        match member.kind() {
            SymbolKind::ClassProperty => match member.variable_lifetime() {
                VariableLifetime::Static => statics.push(member),
                VariableLifetime::Automatic => fields.push(member),
            },
            SymbolKind::Subroutine => {
                let flags = member.subroutine_flags();
                if flags.contains(MethodFlags::CONSTRUCTOR) {
                    ctor = Some(member);
                } else if !flags.contains(MethodFlags::BUILT_IN) {
                    // `MethodFlags::BUILT_IN` excludes slang's 8 implicit
                    // randomize-family methods every class carries — see
                    // this function's own doc comment above.
                    methods.push(member);
                }
            }
            SymbolKind::MethodPrototype => {
                if !member
                    .method_prototype_flags()
                    .contains(MethodFlags::BUILT_IN)
                {
                    methods.push(member);
                }
            }
            SymbolKind::ConstraintBlock => {
                check_constraint_member(class_sym, member, &mut constraint_names)?;
            }
            SymbolKind::Parameter
            | SymbolKind::TypeParameter
            | SymbolKind::ClassType
            | SymbolKind::GenericClassDef
            | SymbolKind::CovergroupType
            | SymbolKind::TypeAlias
            | SymbolKind::ForwardingTypedef
            | SymbolKind::EmptyMember
            | SymbolKind::TransparentMember
            | SymbolKind::DeferredMember
            | SymbolKind::Attribute
            | SymbolKind::WildcardImport
            | SymbolKind::ExplicitImport
            | SymbolKind::LetDecl => {}
            other => {
                return Err(ElabError::UnsupportedConstruct {
                    hier_path: member.hierarchical_path(),
                    detail: format!(
                        "{other:?} class member not yet classified by this elaboration pass"
                    ),
                });
            }
        }
    }

    Ok(ClassMembers {
        statics,
        fields,
        methods,
        ctor,
    })
}

/// Task 4 (`docs/superpowers/plans/2026-10-03-classes.md`, LRM 8.9): every
/// distinct class template reachable from `eval`'s design (via
/// [`collect_new_class_types`]/[`assign_class_template_ids`] — the same
/// `new()`-site discovery Task 2 already built; see that function's own
/// doc comment for the scope boundary this inherits: a specialization
/// referenced only through a declared variable's type, with no `new()`
/// anywhere in the design, is not discovered) that declares at least one
/// `static` property — paired with one representative `Symbol` for that
/// template. "Representative" is not a choice between distinct symbols:
/// any two class `Type`s sharing a `ClassTemplateId` are, by
/// [`same_specialization`]'s own pointer-identity ground truth, the
/// literal same `ClassType`/specialized symbol.
///
/// A class with no `static` member (per [`classify_members`]) contributes
/// no entry: it needs no singleton segment at all. This function is the
/// one place that decides "needs a segment" — never re-derived at a call
/// site (`state::instance::StateEngine::allocate_class_static_singletons`'s
/// own caller is expected to build its `layouts` argument from exactly this
/// list, never from a separately-filtered one).
///
/// Deduplicated and returned in ascending [`ClassTemplateId`] order —
/// deterministic across repeat calls on the same `eval`, like every other
/// query this module exposes.
pub fn class_templates_with_statics<'d>(
    eval: &'d sv_lang::EvalSession<'d>,
) -> Result<Vec<(crate::netlist::ClassTemplateId, sv_lang::Symbol<'d>)>, ElabError> {
    let types = collect_new_class_types(eval);
    let ids = assign_class_template_ids(&types);

    let mut by_id: HashMap<crate::netlist::ClassTemplateId, sv_lang::Symbol<'d>> = HashMap::new();
    for (ty, id) in types.iter().zip(ids.iter()) {
        by_id.entry(*id).or_insert_with(|| ty.as_symbol());
    }

    let mut ids_sorted: Vec<u32> = by_id.keys().map(|id| id.0).collect();
    ids_sorted.sort_unstable();

    let mut out = Vec::new();
    for raw in ids_sorted {
        let id = crate::netlist::ClassTemplateId(raw);
        let sym = by_id[&id];
        let members = classify_members(sym)?;
        if !members.statics.is_empty() {
            out.push((id, sym));
        }
    }
    Ok(out)
}