vj 0.2.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
//! Gate, switch and pull primitives and user-defined primitives (LRM
//! 1800-2023 §28, §29), and the delay line that gives a continuous driver
//! its delay (§10.3.3, §28.16): the planning half.
//!
//! This module reads the elaborated design (slang side) and produces plain
//! data -- [`vj_exec::timing::PrimPlan`] and
//! [`vj_exec::timing::LinePlan`] -- which the slang-free half
//! (`vj_exec::timing::prim`) registers as native processes. The JIT and the
//! AOT runner register through the same code, so the semantics below live in
//! one place:
//!
//! Each primitive instance is a native process sensitive to its input
//! terminals: it reads them, evaluates the gate (or the UDP's table), and
//! writes each output terminal's bit -- into the net, or into its driver
//! contribution when the net is resolved (`crate::nets`). A terminal is a
//! signal (its least significant bit), a constant bit-select of one, or a
//! constant. Switches pass their data input's value but not its strength:
//! a driver's strength is fixed (`nmos`/`pmos`/`cmos` strong, the resistive
//! `r*` forms pull, `pullup`/`pulldown` pull unless given). The
//! bidirectional `tran` switches are not supported.
//!
//! A delayed driver writes a staging cell instead of its target, and a
//! delay line moves the staged value to the target once it has been stable
//! for the delay its transition calls for -- inertial delay: a newer value
//! cancels a pending one. The line is two processes sharing the pending
//! value: a recorder, woken by the staging cell, notes each new value and
//! when it is due and bumps a kick cell; a delayer, woken by the kick,
//! sleeps until the pending value is due and commits it. The delayer never
//! sleeps longer than the shortest delay, so a newer value due sooner (a
//! short fall after a long rise) is never late.

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};

use sv_lang::kinds::{ExpressionKind, SymbolKind, SyntaxKind};
use sv_lang::{EvalSession, Expression, SemNode, Symbol, SyntaxTree};
use vj_abi::bit4::Bit4;
use vj_codegen::process_lower::{SignalSlot, SignalSlotClass};
use vj_codegen::types::TypeWidth;
use vj_exec::timing::dyndelay::{ConvTo, DelayExpr, DelayOp, DelayTerm, DynDelay};
use vj_exec::timing::prim::{Field, Gate, LiveDelays, Row, TermLoc, Udp, can_be_ambiguous};
pub(crate) use vj_exec::timing::{Delays, Loc, LocClass, SlotRef};
pub(crate) use vj_exec::timing::{LinePlan, PrimPlan};
use vj_sim::netlist::InstanceId;
use vj_sim::symid::{SymbolId, SymbolUid};

use crate::nets::{DriverKey, Resolution};

/// `slot` as plain data (what a [`Loc`] carries).
pub(crate) fn slot_ref(slot: SignalSlot) -> SlotRef {
    SlotRef {
        slot: slot.slot,
        width: slot.width,
        signed: slot.signed,
        class: match slot.class {
            SignalSlotClass::Inline => LocClass::Inline,
            SignalSlotClass::Wide => LocClass::Wide,
            SignalSlotClass::Memory {
                num_rows,
                lower_index,
            } => LocClass::Memory {
                num_rows,
                lower_index,
            },
        },
    }
}

/// A bank slot's [`SignalSlot`].
pub(crate) fn bank_slot(slot: u32, width: u32) -> SignalSlot {
    SignalSlot {
        slot,
        width,
        signed: false,
        class: if width > 64 {
            SignalSlotClass::Wide
        } else {
            SignalSlotClass::Inline
        },
    }
}

/// A [`Loc`] of `slot` in `inst` (a bank pseudo-instance included).
pub(crate) fn loc_of(inst: InstanceId, slot: SignalSlot) -> Loc {
    Loc::new(inst, slot_ref(slot))
}

/// The built-in primitive `name` names, and whether it is a resistive
/// switch.
fn builtin(name: &str) -> Option<(Gate, bool)> {
    Some(match name {
        "and" => (Gate::And, false),
        "nand" => (Gate::Nand, false),
        "or" => (Gate::Or, false),
        "nor" => (Gate::Nor, false),
        "xor" => (Gate::Xor, false),
        "xnor" => (Gate::Xnor, false),
        "buf" => (Gate::Buf, false),
        "not" => (Gate::Not, false),
        "bufif0" => (Gate::Bufif0, false),
        "bufif1" => (Gate::Bufif1, false),
        "notif0" => (Gate::Notif0, false),
        "notif1" => (Gate::Notif1, false),
        "nmos" => (Gate::Nmos, false),
        "pmos" => (Gate::Pmos, false),
        "cmos" => (Gate::Cmos, false),
        "rnmos" => (Gate::Nmos, true),
        "rpmos" => (Gate::Pmos, true),
        "rcmos" => (Gate::Cmos, true),
        "pullup" => (Gate::Pullup, false),
        "pulldown" => (Gate::Pulldown, false),
        _ => return None,
    })
}

/// The primitive instances among `body`'s items (array elements included).
pub(crate) fn instances<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    fn walk<'d>(s: Symbol<'d>, out: &mut Vec<Symbol<'d>>) {
        if s.kind() == SymbolKind::PrimitiveInstance {
            out.push(s);
        } else if s.kind() == SymbolKind::InstanceArray {
            for e in s.instance_array_elements() {
                walk(e, out);
            }
        }
    }
    let mut out = Vec::new();
    for m in vj_sim::netlist::module_items(body) {
        walk(m, &mut out);
    }
    out
}

/// The name of the primitive `inst` instantiates (`and`, a UDP's name),
/// from its instantiation's syntax.
pub(crate) fn type_name(inst: &Symbol<'_>, trees: &[SyntaxTree]) -> Option<String> {
    // An array element has no syntax of its own; its array does.
    let mut sym = *inst;
    loop {
        for tree in trees {
            let Some(mut node) = sym.syntax(tree) else {
                continue;
            };
            loop {
                if node.kind() == SyntaxKind::PrimitiveInstantiation {
                    return <sv_lang::nodes::PrimitiveInstantiationSyntax as sv_lang::AstNode>::cast(
                        node,
                    )
                    .and_then(|n| n.r#type())
                    .map(|t| t.text().to_string());
                }
                if node.kind() == SyntaxKind::HierarchyInstantiation {
                    return <sv_lang::nodes::HierarchyInstantiationSyntax as sv_lang::AstNode>::cast(
                        node,
                    )
                    .and_then(|n| n.r#type())
                    .map(|t| t.text().to_string());
                }
                match node.parent() {
                    Some(p) => node = p,
                    None => break,
                }
            }
        }
        match sym.parent() {
            Some(p) if p.kind() == SymbolKind::InstanceArray => sym = p,
            _ => return None,
        }
    }
}

/// Whether `inst` is a bidirectional switch (`tran`, `tranif1`, ...),
/// realized by joining nets (`crate::nets`), not as a process.
pub(crate) fn is_switch(inst: &Symbol<'_>, trees: &[SyntaxTree]) -> bool {
    type_name(inst, trees).is_some_and(|n| n.starts_with("tran") || n.starts_with("rtran"))
}

/// How many of a primitive's `n` terminals are outputs (they come first).
fn output_count(gate: Gate, n: usize) -> usize {
    match gate {
        Gate::Buf | Gate::Not => n.saturating_sub(1),
        Gate::Pullup | Gate::Pulldown => n,
        _ => 1,
    }
}

/// The user-defined primitives of `inst`'s design, by name.
fn udps_of<'d>(inst: &Symbol<'d>) -> HashMap<String, Symbol<'d>> {
    let mut root = *inst;
    while let Some(p) = root.parent() {
        root = p;
    }
    let mut out = HashMap::new();
    for unit in root.members() {
        for m in unit.members() {
            if m.kind() == SymbolKind::Primitive {
                out.insert(m.name().to_string(), m);
            }
        }
    }
    out
}

/// A primitive instance's function, UDP table, and output terminals (the
/// left-hand sides of its output connections).
pub(crate) struct Shape<'d> {
    pub gate: Gate,
    pub resistive: bool,
    pub udp: Option<Udp>,
    pub outputs: Vec<Expression<'d>>,
    pub inputs: Vec<Expression<'d>>,
}

pub(crate) fn shape<'d>(inst: &Symbol<'d>, trees: &[SyntaxTree]) -> Result<Shape<'d>, String> {
    let name = type_name(inst, trees).ok_or_else(|| {
        format!(
            "primitive instance {}: no instantiation syntax",
            inst.name()
        )
    })?;
    let (gate, resistive, udp) = match builtin(&name) {
        Some((g, r)) => (g, r, None),
        None => {
            let def = udps_of(inst).remove(&name).ok_or_else(|| {
                format!("`{name}` is not a supported primitive (tran switches are not)")
            })?;
            (Gate::Udp, false, Some(udp_of(&def)?))
        }
    };
    let conns: Vec<Expression<'d>> = inst.primitive_instance_port_connections().collect();
    let n_out = output_count(gate, conns.len());
    let mut outputs = Vec::new();
    for c in &conns[..n_out] {
        let lhs = if c.kind() == ExpressionKind::Assignment {
            c.left()
        } else {
            Some(*c)
        };
        outputs.push(
            lhs.ok_or_else(|| format!("primitive {}: an output with no target", inst.name()))?,
        );
    }
    Ok(Shape {
        gate,
        resistive,
        udp,
        outputs,
        inputs: conns[n_out..].to_vec(),
    })
}

/// The strength a primitive drives with.
pub(crate) fn strength(
    inst: &Symbol<'_>,
    gate: Gate,
    resistive: bool,
) -> vj_sim::state::DriveStrengthPair {
    use vj_sim::state::DriveStrength;
    let given = inst.primitive_instance_drive_strength();
    let default = if resistive || matches!(gate, Gate::Pullup | Gate::Pulldown) {
        DriveStrength::Pull
    } else {
        DriveStrength::Strong
    };
    let one = |s: Option<sv_lang::DriveStrength>| match s {
        None => default,
        Some(sv_lang::DriveStrength::Strong) => DriveStrength::Strong,
        Some(sv_lang::DriveStrength::Supply) => DriveStrength::Supply,
        Some(sv_lang::DriveStrength::Pull) => DriveStrength::Pull,
        Some(sv_lang::DriveStrength::HighZ) => DriveStrength::HighZ,
        Some(_) => DriveStrength::Weak,
    };
    vj_sim::state::DriveStrengthPair {
        s0: one(given.strength0),
        s1: one(given.strength1),
    }
}

fn level_char(c: char) -> Option<u8> {
    Some(match c {
        '0' => 1,
        '1' => 2,
        'x' | 'X' => 4,
        '?' => 7,
        'b' | 'B' => 3,
        _ => return None,
    })
}

fn parse_fields(s: &str) -> Result<Vec<Field>, String> {
    let bad = || format!("unrecognized UDP table entry `{s}`");
    let mut out = Vec::new();
    let mut chars = s.chars().filter(|c| !c.is_whitespace());
    while let Some(c) = chars.next() {
        let field = match c {
            '(' => {
                let from = chars.next().and_then(level_char).ok_or_else(bad)?;
                let to = chars.next().and_then(level_char).ok_or_else(bad)?;
                if chars.next() != Some(')') {
                    return Err(bad());
                }
                Field::Edge(vec![(from, to)])
            }
            'r' | 'R' => Field::Edge(vec![(1, 2)]),
            'f' | 'F' => Field::Edge(vec![(2, 1)]),
            'p' | 'P' => Field::Edge(vec![(1, 2), (1, 4), (4, 2)]),
            'n' | 'N' => Field::Edge(vec![(2, 1), (2, 4), (4, 1)]),
            '*' => Field::Edge(vec![(7, 7)]),
            c => Field::Level(level_char(c).ok_or_else(bad)?),
        };
        out.push(field);
    }
    Ok(out)
}

/// The table of the user-defined primitive `def` (LRM §29).
fn udp_of(def: &Symbol<'_>) -> Result<Udp, String> {
    let mut rows = Vec::new();
    for (inputs, out, state) in def.primitive_table() {
        let out = match out.trim() {
            "0" => Some(Bit4::Zero),
            "1" => Some(Bit4::One),
            "x" | "X" => Some(Bit4::X),
            "-" => None,
            other => return Err(format!("unrecognized UDP output `{other}`")),
        };
        let state = if state.trim().is_empty() {
            7
        } else {
            level_char(state.trim().chars().next().unwrap_or('?'))
                .ok_or_else(|| format!("unrecognized UDP state `{state}`"))?
        };
        rows.push(Row {
            inputs: parse_fields(inputs)?,
            state,
            out,
        });
    }
    let init = match def.primitive_init_val().and_then(|v| v.as_i64()) {
        Some(0) => Bit4::Zero,
        Some(1) => Bit4::One,
        _ => Bit4::X,
    };
    Ok(Udp {
        sequential: def.primitive_is_sequential(),
        init,
        rows,
    })
}

// ---------------------------------------------------------------------------
// Terminals and cells.

/// A constant expression's value (folding what slang left unfolded).
fn constant_of(eval: &EvalSession<'_>, e: Expression<'_>) -> Option<sv_lang::ConstantValue> {
    e.constant_value().or_else(|| eval.eval_constant(e))
}

/// The declared value of a delay that IS a specparam (`assign #d q = a;`, LRM 30.4 / 32.4.3's
/// `#dhigh`): neither `constant_value()` nor `eval_constant` folds a specparam reference, so the
/// symbol's own initializer value is read. This is the SOURCE value, planned once: an SDF LABEL
/// cannot move it afterwards (`sdf_labels` warns when it annotates a specparam read here).
fn specparam_source_value(e: Expression<'_>) -> Option<sv_lang::ConstantValue> {
    let mut bare = e;
    while bare.kind() == ExpressionKind::Conversion
        && let Some(inner) = bare.conversion_operand()
    {
        bare = inner;
    }
    bare.referenced_symbol()
        .filter(|s| s.kind() == SymbolKind::Specparam)
        .and_then(|s| s.constant_value())
}

/// `e`'s bit offset inside `base` (a constant bit-select), from the base
/// type's declared range.
fn select_offset(
    eval: &EvalSession<'_>,
    base: Expression<'_>,
    index: Expression<'_>,
    width: u32,
) -> Option<u32> {
    let idx = constant_of(eval, index)?.as_i64()?;
    let (left, right) = match base.expr_type() {
        Some(t) if t.is_integral() && !t.is_struct() && !t.is_union() => {
            let r = t.bit_vector_range();
            (i64::from(r.left), i64::from(r.right))
        }
        _ => (i64::from(width) - 1, 0),
    };
    let off = if left >= right {
        idx - right
    } else {
        right - idx
    };
    (0..i64::from(width)).contains(&off).then_some(off as u32)
}

/// A constant simple part-select `net[a:b]` of a whole net, as
/// `(net, slot, (lowest bit offset, width))`.
fn signal_range<'d>(
    eval: &EvalSession<'_>,
    e: Expression<'d>,
    signals: &HashMap<SymbolId, SignalSlot>,
) -> Option<(Symbol<'d>, SignalSlot, (u32, u32))> {
    let base = e.select_value()?;
    if !vj_sim::symid::is_value_name(base.kind()) {
        return None;
    }
    let sym = base.referenced_symbol()?;
    let slot = *signals.get(&sym.uid())?;
    if matches!(slot.class, SignalSlotClass::Memory { .. }) {
        return None;
    }
    let a = select_offset(eval, base, e.range_left()?, slot.width)?;
    let b = select_offset(eval, base, e.range_right()?, slot.width)?;
    e.range_selection_kind().filter(|k| {
        vj_codegen::expr::classify_range_selection_kind(*k)
            == Ok(vj_codegen::expr::RangeSelectionKindClass::Simple)
    })?;
    Some((sym, slot, (a.min(b), a.abs_diff(b) + 1)))
}

/// A terminal expression as a signal bit: a signal (its bit 0), or a
/// constant bit-select of one, looked up in `signals`.
fn signal_bit<'d>(
    eval: &EvalSession<'_>,
    e: Expression<'d>,
    signals: &HashMap<SymbolId, SignalSlot>,
) -> Option<(Symbol<'d>, SignalSlot, u32)> {
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand()?
    } else {
        e
    };
    if vj_sim::symid::is_value_name(e.kind()) {
        let sym = e.referenced_symbol()?;
        let slot = *signals.get(&sym.uid())?;
        return (!matches!(slot.class, SignalSlotClass::Memory { .. })).then_some((sym, slot, 0));
    }
    if e.kind() == ExpressionKind::ElementSelect {
        let base = e.select_value()?;
        // One element of a primitive array whose terminal is a constant
        // part-select of a vector net (LRM 28.3.5, `pmos g[1:0](cd[2:1], ..)`):
        // slang indexes the part-select `cd[2:1]` itself, element 0 first.
        if base.kind() == ExpressionKind::RangeSelect {
            let (sym, slot, lo) = signal_range(eval, base, signals)?;
            let width = lo.1;
            let off = select_offset(eval, base, e.selector()?, width)?;
            return Some((sym, slot, lo.0 + off));
        }
        if !vj_sim::symid::is_value_name(base.kind()) {
            return None;
        }
        let sym = base.referenced_symbol()?;
        let slot = *signals.get(&sym.uid())?;
        if matches!(slot.class, SignalSlotClass::Memory { .. }) {
            return None;
        }
        let lo = select_offset(eval, base, e.selector()?, slot.width)?;
        return Some((sym, slot, lo));
    }
    None
}

// ---------------------------------------------------------------------------
// Delays.

/// `exprs`'s own values, each converted to scheduler ticks in `scope`'s own
/// timescale -- the shared core of [`delays_of`] (a `#d`/`#(r,f,z)` delay
/// control's children) and `crate::specify`'s own module-path delay-list
/// evaluation (`(a=>q)=(r,f,z);`, Task 4a): the SAME `min:typ:max`-unwrap-
/// then-evaluate-then-convert rule, just over a plain [`Expression`]
/// iterator instead of a timing-control node's children (`path.
/// timing_path_delays()` is already an `Expression` iterator, not a timing
/// control -- a `path_delay_value` is a different grammar production
/// entirely). Kept here, reused there, rather than a second copy that could
/// silently diverge from this one (this module's own doc comment: "no new
/// scheduling primitive is invented").
pub(crate) fn delay_values_of<'d>(
    eval: &EvalSession<'_>,
    exprs: impl Iterator<Item = Expression<'d>>,
    scope: &Symbol<'_>,
) -> Result<Vec<u64>, String> {
    let tick = vj_codegen::timescale::design_tick_exp(scope);
    let mut out = Vec::new();
    for e in exprs {
        // `min:typ:max` takes the typical value.
        let e = if e.kind() == ExpressionKind::MinTypMax {
            e.children()
                .into_iter()
                .filter_map(|n| n.as_expression())
                .nth(1)
                .ok_or_else(|| "a min:typ:max delay with no typical value".to_string())?
        } else {
            e
        };
        let v = match constant_of(eval, e).or_else(|| specparam_source_value(e)) {
            Some(sv_lang::ConstantValue::Real(f)) => f,
            Some(c) => c
                .as_i64()
                .ok_or_else(|| "a delay that is not a number".to_string())?
                as f64,
            None => return Err("a delay that is not a constant".to_string()),
        };
        out.push(vj_codegen::timescale::delay_ticks(v, scope, tick).map_err(|e| e.message)?);
    }
    Ok(out)
}

/// A delay control (`#d`, `#(r, f)`, `#(r, f, z)`, each maybe `min:typ:max`)
/// as [`Delays`] in scheduler ticks, in `scope`'s time unit.
pub(crate) fn delays_of(
    eval: &EvalSession<'_>,
    node: SemNode<'_>,
    scope: &Symbol<'_>,
) -> Result<Delays, String> {
    let tc = node
        .as_timing_control()
        .ok_or_else(|| "a delay that is not a timing control".to_string())?;
    let out = delay_values_of(
        eval,
        tc.children().into_iter().filter_map(|n| n.as_expression()),
        scope,
    )?;
    Ok(Delays::from_list(&out))
}

/// A delay control whose values may be expressions over signals (`#(period/3)`,
/// `#(rise, fall)`, LRM 28.16.2): the constant [`Delays`] when every value folds, otherwise
/// the zero [`Delays`] and the [`DynDelay`] a delay line evaluates each time its source
/// changes (10.3.3). Anything a delay line cannot evaluate is a named error.
fn delays_or_dynamic(
    eval: &EvalSession<'_>,
    node: SemNode<'_>,
    scope: &Symbol<'_>,
    inst: InstanceId,
    signals: &HashMap<SymbolId, SignalSlot>,
) -> Result<(Delays, Option<DynDelay<Loc>>), String> {
    match delays_of(eval, node, scope) {
        Err(e) if e == "a delay that is not a constant" => {}
        r => return r.map(|d| (d, None)),
    }
    let tc = node
        .as_timing_control()
        .ok_or_else(|| "a delay that is not a timing control".to_string())?;
    let (unit, precision) = vj_codegen::timescale::unit_and_precision(scope);
    let tick = vj_codegen::timescale::design_tick_exp(scope);
    let mut terms = Vec::new();
    for e in tc.children().into_iter().filter_map(|n| n.as_expression()) {
        // `min:typ:max` takes the typical value.
        let e = if e.kind() == ExpressionKind::MinTypMax {
            e.children()
                .into_iter()
                .filter_map(|n| n.as_expression())
                .nth(1)
                .ok_or_else(|| "a min:typ:max delay with no typical value".to_string())?
        } else {
            e
        };
        terms.push(DelayTerm {
            expr: delay_expr(eval, e, inst, signals)?,
            unit_to_precision: unit - precision,
            precision_to_tick: precision - tick,
        });
    }
    Ok((Delays::default(), Some(DynDelay { terms })))
}

/// `e` as a [`DelayExpr`]: constants fold, signals of at most 64 bits are read when the
/// delay is taken, and the arithmetic of 11.4.3 / 11.4.8 / 11.4.10 is evaluated.
fn delay_expr(
    eval: &EvalSession<'_>,
    e: Expression<'_>,
    inst: InstanceId,
    signals: &HashMap<SymbolId, SignalSlot>,
) -> Result<DelayExpr<Loc>, String> {
    let refuse = |what: &str| format!("a delay expression with {what}");
    if let Some(c) = constant_of(eval, e).or_else(|| specparam_source_value(e)) {
        return match c {
            sv_lang::ConstantValue::Real(f) => Ok(DelayExpr::Real(f.to_bits())),
            c => c
                .as_i64()
                .map(DelayExpr::Int)
                .ok_or_else(|| "a delay that is not a number".to_string()),
        };
    }
    let ty = e.expr_type();
    let real = ty.as_ref().is_some_and(|t| t.is_floating());
    let width = ty.as_ref().map_or(64, |t| t.bit_width() as u32);
    let signed = ty.as_ref().is_some_and(|t| t.is_signed());
    match e.kind() {
        ExpressionKind::Conversion => {
            let inner = e
                .conversion_operand()
                .ok_or_else(|| refuse("a conversion with no operand"))?;
            let to = if real {
                ConvTo::Real
            } else {
                ConvTo::Int { width, signed }
            };
            // A widening conversion extends by the operand's own signedness (11.8.2); the
            // wrap in `Int` keeps the operand's value, so only the target width matters.
            Ok(DelayExpr::Conv(
                to,
                Box::new(delay_expr(eval, inner, inst, signals)?),
            ))
        }
        k if vj_sim::symid::is_value_name(k) => {
            let sym = e
                .referenced_symbol()
                .ok_or_else(|| refuse("an unresolved name"))?;
            let slot = *signals
                .get(&sym.uid())
                .ok_or_else(|| refuse(&format!("`{}`, which is not a signal", sym.name())))?;
            if matches!(slot.class, SignalSlotClass::Memory { .. }) || slot.width > 64 {
                return Err(refuse(&format!(
                    "`{}`, an array or a signal wider than 64 bits",
                    sym.name()
                )));
            }
            Ok(DelayExpr::Sig {
                loc: loc_of(inst, slot),
                width,
                signed,
                real,
            })
        }
        ExpressionKind::UnaryOp => match e.unary_op() {
            Some(sv_lang::UnaryOp::Plus) => delay_expr(
                eval,
                e.operand()
                    .ok_or_else(|| refuse("a unary operator with no operand"))?,
                inst,
                signals,
            ),
            Some(sv_lang::UnaryOp::Minus) => Ok(DelayExpr::Neg(Box::new(delay_expr(
                eval,
                e.operand()
                    .ok_or_else(|| refuse("a unary operator with no operand"))?,
                inst,
                signals,
            )?))),
            op => Err(refuse(&format!("the unary operator {op:?}"))),
        },
        ExpressionKind::BinaryOp => {
            use sv_lang::BinaryOp as B;
            let op = match e.binary_op() {
                Some(B::Add) => DelayOp::Add,
                Some(B::Subtract) => DelayOp::Sub,
                Some(B::Multiply) => DelayOp::Mul,
                Some(B::Divide) => DelayOp::Div,
                Some(B::Mod) => DelayOp::Mod,
                Some(B::BinaryAnd) => DelayOp::And,
                Some(B::BinaryOr) => DelayOp::Or,
                Some(B::BinaryXor) => DelayOp::Xor,
                Some(B::LogicalShiftLeft | B::ArithmeticShiftLeft) => DelayOp::Shl,
                Some(B::LogicalShiftRight) => DelayOp::Shr,
                Some(B::ArithmeticShiftRight) => DelayOp::Ashr,
                op => return Err(refuse(&format!("the binary operator {op:?}"))),
            };
            let (Some(l), Some(r)) = (e.left(), e.right()) else {
                return Err(refuse("a binary operator with a missing operand"));
            };
            Ok(DelayExpr::Bin {
                op,
                width,
                signed,
                real,
                a: Box::new(delay_expr(eval, l, inst, signals)?),
                b: Box::new(delay_expr(eval, r, inst, signals)?),
            })
        }
        k => Err(refuse(&format!("a {k:?} operand"))),
    }
}

/// `net`'s own delay (`wire #d w;`), which adds to every driver's. A
/// `trireg`'s third value is its charge decay time, not a turn-off delay
/// (LRM 28.16.2, [`trireg_decays`]): its drivers turning off is a change to
/// the stored charge, taken after the shorter of the rise and fall delays.
fn net_delays(eval: &EvalSession<'_>, net: &Symbol<'_>) -> Result<Delays, String> {
    match net.net_delay() {
        Some(d) if net.kind() == SymbolKind::Net => {
            let mut delays = delays_of(eval, d, net)?;
            if is_trireg(eval, net) {
                delays.off = delays.rise.min(delays.fall);
            }
            Ok(delays)
        }
        _ => Ok(Delays::default()),
    }
}

fn is_trireg(eval: &EvalSession<'_>, net: &Symbol<'_>) -> bool {
    crate::nets::net_kind_of(net, &eval.design().syntax_trees()) == vj_sim::state::NetKind::TriReg
}

/// Each `trireg` net's charge decay time in ticks, for those whose delay has
/// a third value (`trireg #(r, f, decay) t;`, LRM 28.16.2): held charge
/// becomes `x` that long after the last driver turned off.
pub(crate) fn trireg_decays(
    eval: &EvalSession<'_>,
    bodies: &[(InstanceId, Symbol<'_>)],
) -> Result<HashMap<(InstanceId, SymbolId), u64>, String> {
    let mut out = HashMap::new();
    for (id, body) in bodies {
        for m in vj_sim::netlist::module_items(body) {
            if m.kind() != SymbolKind::Net || !is_trireg(eval, &m) {
                continue;
            }
            if let Some(d) = m.net_delay() {
                let delays = delays_of(eval, d, &m)?;
                if delays.off > 0 {
                    out.insert((*id, m.uid()), delays.off);
                }
            }
        }
    }
    Ok(out)
}

/// Each `trireg` net's charge strength as a `%v` code (LRM 28.16.1): 5 for
/// `(small)`, 6 for `(large)`; a net left at the `medium` default is omitted.
pub(crate) fn trireg_charges(
    eval: &EvalSession<'_>,
    bodies: &[(InstanceId, Symbol<'_>)],
) -> HashMap<(InstanceId, SymbolId), u8> {
    let trees = eval.design().syntax_trees();
    let mut out = HashMap::new();
    for (id, body) in bodies {
        for m in vj_sim::netlist::module_items(body) {
            if m.kind() != SymbolKind::Net || !is_trireg(eval, &m) {
                continue;
            }
            let code = crate::nets::charge_code_of(&m, &trees);
            if code != 4 {
                out.insert((*id, m.uid()), code);
            }
        }
    }
    out
}

/// Every primitive output that `$sdf_annotate`'s `DEVICE` can reach, keyed by (instance,
/// net): indices into [`Plans::device_init`] -- see [`Plans::device`].
pub(crate) type DeviceIndex = HashMap<(InstanceId, SymbolId), Vec<u32>>;

/// [`DeviceIndex`] bound to the live cells of a registered plan (what the annotator rewrites).
pub(crate) type DeviceDelays = HashMap<(InstanceId, SymbolId), Vec<Arc<Mutex<Delays>>>>;

/// Every primitive instance's outputs, by the instance's hierarchical path: its primitive name
/// (`and`, or a UDP's name; the SDF `CELLTYPE`) and the [`Plans::device_init`] indices of its
/// output lines -- see [`Plans::by_path`].
pub(crate) type PrimIndex = HashMap<String, (String, Vec<u32>)>;

/// [`PrimIndex`] bound to the live cells of a registered plan.
pub(crate) type PrimDelays = HashMap<String, (String, Vec<Arc<Mutex<Delays>>>)>;

/// `index`'s cells out of `live`.
pub(crate) fn prim_cells(index: &PrimIndex, live: &vj_exec::timing::TimingLive) -> PrimDelays {
    index
        .iter()
        .map(|(k, (ty, v))| {
            (
                k.clone(),
                (
                    ty.clone(),
                    v.iter()
                        .map(|&i| live.prim.device[i as usize].clone())
                        .collect(),
                ),
            )
        })
        .collect()
}

/// `index`'s cells out of `live`.
pub(crate) fn device_cells(
    index: &DeviceIndex,
    live: &vj_exec::timing::TimingLive,
) -> DeviceDelays {
    index
        .iter()
        .map(|(k, v)| {
            (
                k.clone(),
                v.iter()
                    .map(|&i| live.prim.device[i as usize].clone())
                    .collect(),
            )
        })
        .collect()
}

/// Whether any of `trees` calls `$sdf_annotate`: the design is then planned so that a
/// primitive driving a module output without a specify path can be re-delayed by `DEVICE`.
/// A token test on the syntax, so a mention in a comment or a string does not count.
pub(crate) fn calls_sdf_annotate(trees: &[SyntaxTree]) -> bool {
    let mut found = false;
    for tree in trees {
        tree.root().visit_with_tokens(|c| {
            if let sv_lang::Child::Token(t) = c
                && t.kind() == sv_lang::kinds::TokenKind::SystemIdentifier
                && t.text() == "$sdf_annotate"
            {
                found = true;
                return sv_lang::Walk::Break;
            }
            sv_lang::Walk::Continue
        });
        if found {
            return true;
        }
    }
    false
}

/// The module output ports (`output`/`inout`) of `body`, by their internal signal.
fn output_ports(body: &Symbol<'_>) -> HashSet<SymbolId> {
    body.members()
        .filter(|m| m.kind() == SymbolKind::Port)
        .filter(|m| {
            matches!(
                m.port_direction(),
                sv_lang::ArgumentDirection::Out | sv_lang::ArgumentDirection::InOut
            )
        })
        .map(|m| m.port_internal_symbol().unwrap_or(m).uid())
        .collect()
}

// ---------------------------------------------------------------------------
// Planning (before the instances exist) and registration.

/// A primitive input terminal that is an expression (LRM 28.3: `nand g(o, C,
/// ~D)`): a hidden continuously driven cell in the bank, written by a
/// continuous-assign kernel that `run.rs` lowers in `inst`
/// (`ContAssignLoweringSpec::hidden_target`) and read by the primitive.
pub(crate) struct HiddenTerm<'d> {
    pub(crate) inst: InstanceId,
    /// The primitive instance (the kernel's diagnostic anchor).
    pub(crate) prim: Symbol<'d>,
    pub(crate) expr: Expression<'d>,
    /// The bank slot of the cell (as wide as the expression).
    pub(crate) cell: u32,
}

/// Every primitive and delay line of a design, and the staging slot each
/// delayed continuous assignment writes instead of its target.
#[derive(Default)]
pub(crate) struct Plans<'d> {
    pub(crate) prims: Vec<PrimPlan>,
    /// Every primitive input terminal that is an expression (LRM 28.3).
    pub(crate) hidden: Vec<HiddenTerm<'d>>,
    pub(crate) lines: Vec<LinePlan>,
    /// A delayed continuous assignment's staging slot in the bank.
    pub staged: HashMap<DriverKey, u32>,
    /// Task 9 (LRM 30.6, `docs/superpowers/plans/2026-10-03-sdf.md`): a
    /// continuous-assign driver's own distributed delay (its `#delay`,
    /// combined with any net delay — the SAME `delays` this function would
    /// otherwise have built a [`LinePlan`] for), for every destination named
    /// in `specify_dests` — this module's own "committed behavior... must be
    /// byte-for-byte unaffected" for a design with no specify block at all
    /// (`specify_dests` is then empty, so this map stays empty and every
    /// `LinePlan` below is built exactly as before): rather than this module
    /// ALSO running its own `Recorder`/`Delayer` line writing the SAME
    /// destination net directly (which would race `crate::specify`'s own
    /// retimer, committing the natural value too early whenever the specify
    /// delay turns out to be the larger one — verified live against
    /// `iverilog -g2012 -gspecify` reproducing exactly this race when a
    /// destination's two delay sources are close enough together to
    /// interleave), this function SKIPS building its own `LinePlan` for a
    /// `specify_dests` member entirely and exposes the `Delays` it would
    /// have used here instead, so `crate::specify::plan`'s own retimer can
    /// fold it into one `max(natural, specify)` schedule per LRM 30.6's own
    /// text ("the larger of the two delays... shall be used") and own the
    /// destination's SOLE commit.
    pub(crate) natural: HashMap<(InstanceId, SymbolId), Delays>,
    /// A specify path destination a primitive drives (the standard-cell
    /// shape `buf (Y, A); specify (A => Y) = ...;`): the staging slot the
    /// gate writes instead of the net, which the path's retimer reads
    /// (`specify::plan`), by (instance, net).
    pub(crate) specify_staging: HashMap<(InstanceId, SymbolId), Loc>,
    /// SD-B / T26 (LRM 32.4 Table 32-1, `DEVICE`): in a design that calls `$sdf_annotate`, the
    /// own delays of every primitive driving a module output port that no specify path
    /// targets, by (instance, output net). Each such primitive output is given a delay line
    /// even if its source delay is zero, so an annotation arriving later has a line to
    /// delay; the line reads the cell on every transition. Empty for a design that never
    /// calls `$sdf_annotate`, so its planned processes are exactly as before.
    ///
    /// Implementation-defined: the zero-delay line commits its value one delta cycle after
    /// the primitive evaluates, where an unannotated primitive output commits in the same
    /// delta. Only the outputs `DEVICE` can reach are affected.
    pub(crate) device: DeviceIndex,
    /// The initial own delays of the cells [`Self::device`] indexes (`TimingPlan::device_init`).
    pub(crate) device_init: Vec<Delays>,
    /// A design that calls `$sdf_annotate` also gives EVERY primitive output a live delay
    /// line (an entry of [`Self::device_init`]), so an SDF `CELL` can name the primitive
    /// instance itself (`(CELLTYPE "and") (INSTANCE g1)`): its lines by hierarchical path.
    /// Empty when the design never calls `$sdf_annotate`.
    pub(crate) by_path: PrimIndex,
}

/// Plans every primitive instance and delayed continuous driver of
/// `insts` (`(id, body)`), allocating their staging and kick cells in
/// the bank (`bank`, whose slot widths are `res.bank_widths`).
///
/// `specify_dests` (Task 9): every `(instance, destination symbol)` any
/// module path targets (`vj_sim::netlist::specify::PathEntry::outputs`,
/// collected by `run.rs` BEFORE this call — `crate::specify::discover` has
/// no dependency on `res`/`bank` at all, so reordering it earlier costs
/// nothing) — see [`Plans::natural`]'s own doc comment for why this
/// function consults it rather than always building its own delay line.
///
/// SD-B / T26: when `trees` call `$sdf_annotate` ([`calls_sdf_annotate`]), every primitive
/// output on a module output port outside `specify_dests` gets a re-delayable line
/// ([`Plans::device`]).
pub(crate) fn plan<'d>(
    eval: &EvalSession<'_>,
    insts: &[(InstanceId, Symbol<'d>)],
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    trees: &[SyntaxTree],
    res: &mut Resolution,
    bank: InstanceId,
    specify_dests: &HashSet<(InstanceId, SymbolId)>,
) -> Result<Plans<'d>, String> {
    let device_lines = calls_sdf_annotate(trees);
    let shows_strength = crate::nets::shows_strength(trees);
    let mut plans = Plans::default();
    // Every `(instance, specify destination, bit)` a primitive drives into a staging cell.
    let mut staged_bits: HashSet<(InstanceId, SymbolId, u32)> = HashSet::new();
    let alloc = |res: &mut Resolution, width: u32| {
        let slot = res.bank_widths.len() as u32;
        res.bank_widths.push(width);
        loc_of(bank, bank_slot(slot, width))
    };
    for (id, body) in insts {
        let own = &signals[id];
        let ports = if device_lines {
            output_ports(body)
        } else {
            HashSet::new()
        };
        for inst in instances(body) {
            if is_switch(&inst, trees) {
                // A `tranif` with a turn-on/turn-off delay (LRM 28.16): its control's
                // delay line, from the written control to the cell the switch reads.
                let uid = inst.uid();
                let Some(dc) = res
                    .delayed_controls
                    .iter()
                    .find(|c| c.inst == *id && c.prim == uid)
                    .cloned()
                else {
                    continue;
                };
                let d = inst
                    .primitive_instance_delay()
                    .ok_or_else(|| "a delayed switch control with no delay".to_string())?;
                let (mut delays, mut dynamic) = delays_or_dynamic(eval, d, &inst, *id, own)?;
                // The first delay is the turn-on (LRM 28.8): the control becoming the
                // conducting value. A delay line's first value is its rise (to 1), which
                // is the turn-on of a `tranif1` and the turn-off of a `tranif0`.
                if !dc.on_is_one {
                    delays = Delays {
                        rise: delays.fall,
                        fall: delays.rise,
                        off: delays.off,
                    };
                    if let Some(dd) = dynamic.as_mut()
                        && dd.terms.len() >= 2
                    {
                        dd.terms.swap(0, 1);
                    }
                }
                let staging = loc_of(dc.source.0, dc.source.1);
                let kick = alloc(res, 32);
                plans.lines.push(LinePlan {
                    staging,
                    range: (dc.source.2, 1),
                    dst: loc_of(bank, bank_slot(dc.cell, 1)),
                    dst_lo: 0,
                    delays,
                    kick,
                    live: None,
                    dynamic,
                });
                continue;
            }
            let sh = shape(&inst, trees)?;
            let prim_name = type_name(&inst, trees).unwrap_or_default();
            let at = |what: &str| format!("primitive {}: {what}", inst.hierarchical_path());
            let mut inputs = Vec::new();
            for e in &sh.inputs {
                // An element of an interconnect array: a scalar wire
                // (LRM 23.3.3.7.2), read from the cell its resolver writes.
                if let Some((_, elem)) = crate::nets::ic_element(*e, *id)? {
                    let cell = *res
                        .ic_elem
                        .get(&elem)
                        .ok_or_else(|| at("an interconnect array element terminal with no wire"))?;
                    inputs.push(TermLoc::Bit(loc_of(bank, bank_slot(cell, 1)), 0));
                } else if let Some((_, slot, lo)) = signal_bit(eval, *e, own) {
                    inputs.push(TermLoc::Bit(loc_of(*id, slot), lo));
                } else if let Some((_, slot, (lo, _))) = signal_range(
                    eval,
                    if e.kind() == ExpressionKind::Conversion {
                        e.operand().unwrap_or(*e)
                    } else {
                        *e
                    },
                    own,
                ) {
                    // A multi-bit input terminal: the primitive reads the expression's
                    // least significant bit (LRM 28.3.2 reads one bit per input; Icarus
                    // and the other simulators take the LSB, ivtest gate_connect1). For a
                    // constant part-select that is its lowest-offset bit.
                    inputs.push(TermLoc::Bit(loc_of(*id, slot), lo));
                } else if let Some(c) = constant_of(eval, *e) {
                    let b = match c.as_i64() {
                        Some(v) if v & 1 == 1 => Bit4::One,
                        Some(_) => Bit4::Zero,
                        None => Bit4::X,
                    };
                    inputs.push(TermLoc::Const(b));
                } else {
                    // Any other expression: a hidden cell continuously
                    // driven with its value (LRM 28.3); the primitive reads
                    // its bit 0.
                    let ty = e.expr_type();
                    let width = ty.as_ref().map_or(0, |t| t.value_width());
                    if width == 0
                        || ty.as_ref().is_some_and(|t| t.is_floating())
                        || vj_codegen::huge::is_huge_width(width)
                    {
                        return Err(at(
                            "an input terminal expression that is real or wider than the \
                             inline value path",
                        ));
                    }
                    let cell = res.bank_widths.len() as u32;
                    res.bank_widths.push(width);
                    plans.hidden.push(HiddenTerm {
                        inst: *id,
                        prim: inst,
                        expr: *e,
                        cell,
                    });
                    inputs.push(TermLoc::Bit(loc_of(bank, bank_slot(cell, width)), 0));
                }
            }
            let (gate_delays, gate_dyn) = match inst.primitive_instance_delay() {
                Some(d) => delays_or_dynamic(eval, d, &inst, *id, own)?,
                None => (Delays::default(), None),
            };
            let mut outputs = Vec::new();
            for e in &sh.outputs {
                // An element of an interconnect array is a scalar wire
                // (LRM 23.3.3.7.2): driven through its contribution cell.
                let ic = crate::nets::ic_element(*e, *id)?;
                let (net, slot, lo) = match &ic {
                    Some((root, _)) => (*root, bank_slot(0, 1), 0),
                    None => signal_bit(eval, *e, own).ok_or_else(|| {
                        at("an output terminal that is not a net or a constant bit-select of one")
                    })?,
                };
                let net_extra = net_delays(eval, &net)?;
                let delays = gate_delays.plus(&net_extra);
                // A module output no specify path targets, in a design that calls
                // `$sdf_annotate`: `DEVICE` may re-delay this primitive (see `Plans::device`).
                let live = device_lines.then(|| {
                    let own = plans.device_init.len() as u32;
                    plans.device_init.push(gate_delays);
                    if ports.contains(&net.uid()) && !specify_dests.contains(&(*id, net.uid())) {
                        plans.device.entry((*id, net.uid())).or_default().push(own);
                    }
                    plans
                        .by_path
                        .entry(inst.hierarchical_path())
                        .or_insert_with(|| (prim_name.clone(), Vec::new()))
                        .1
                        .push(own);
                    LiveDelays {
                        own,
                        net: net_extra,
                    }
                });
                // Where a bit goes: straight to `dst`, or through a delay line.
                let mut route = |res: &mut Resolution, dst: Loc, lo: u32| {
                    if delays.is_zero() && live.is_none() && gate_dyn.is_none() {
                        return (dst, lo);
                    }
                    let staging = alloc(res, 1);
                    let kick = alloc(res, 32);
                    plans.lines.push(LinePlan {
                        staging,
                        range: (0, 1),
                        dst,
                        dst_lo: lo,
                        delays,
                        kick,
                        live,
                        dynamic: gate_dyn.clone(),
                    });
                    (staging, 0)
                };
                let key = match &ic {
                    Some((_, elem)) => {
                        DriverKey::PrimElem(*id, inst.uid(), net.uid(), elem.2.clone())
                    }
                    None => DriverKey::Prim(*id, inst.uid(), net.uid()),
                };
                // A specify path destination (LRM 30.4) the gate alone drives:
                // the output goes to a staging slot the path's retimer reads,
                // and the gate's own delay competes with the path's there
                // (30.6, `natural`), instead of a delay line of its own.
                //
                // A vector destination is driven bit by bit (`buf b[1:0] (a, x)`, one gate per
                // bit): every gate writes ITS bit of ONE net-wide staging cell, and `specify::plan`
                // retimes each bit from it. One bit driven by two gates is a contention, refused.
                if specify_dests.contains(&(*id, net.uid())) && res.slot(&key).is_none() {
                    if !staged_bits.insert((*id, net.uid(), lo)) {
                        return Err(at("a specify path destination driven by two primitives"));
                    }
                    let staging = match plans.specify_staging.get(&(*id, net.uid())) {
                        Some(s) => *s,
                        None => {
                            let s = alloc(res, slot.width);
                            plans.specify_staging.insert((*id, net.uid()), s);
                            s
                        }
                    };
                    if gate_dyn.is_some() {
                        return Err(at("a variable delay on a specify path destination"));
                    }
                    // `natural` is one delay per destination: gates of one vector with
                    // different delays would need one per bit.
                    let prior = plans
                        .natural
                        .get(&(*id, net.uid()))
                        .copied()
                        .unwrap_or_default();
                    let first = staged_bits
                        .iter()
                        .filter(|(i, n, _)| (*i, n) == (*id, &net.uid()))
                        .count()
                        == 1;
                    if !first && prior != delays {
                        return Err(at(
                            "primitives of one specify path destination with different delays",
                        ));
                    }
                    if !delays.is_zero() {
                        plans.natural.insert((*id, net.uid()), delays);
                    }
                    outputs.push((staging, lo, None));
                    continue;
                }
                // The net's driver contribution when it is resolved; a gate
                // that can drive a strength-ambiguous `L`/`H` also marks its
                // ambiguous bits there, for the resolver.
                let out = match res.slot(&key) {
                    Some(s) => {
                        let dst = loc_of(bank, bank_slot(s, slot.width));
                        // A MOS gate passes its data input's strength (LRM 28.4,
                        // Table 28-8), when the design prints `%v`.
                        if shows_strength
                            && matches!(sh.gate, Gate::Nmos | Gate::Pmos | Gate::Cmos)
                            && let Some((isym, _, ilo)) = signal_bit(eval, sh.inputs[0], own)
                            && let Some(gi) = res.groups.iter().position(|g| {
                                g.nets.contains(&(*id, isym.uid()))
                                    && g.user.is_none()
                                    && g.rows.is_empty()
                                    && g.cells.is_empty()
                            })
                        {
                            let tick = match res.strength_ticks.get(&gi) {
                                Some(&t) => t,
                                None => {
                                    let t = alloc(res, 32).slot.slot;
                                    res.strength_ticks.insert(gi, t);
                                    t
                                }
                            };
                            res.strength_src.insert(
                                s,
                                vj_sim::image::StrengthSrc {
                                    key: vj_runtime::fmt::strength_key(&isym.uid().key_string()),
                                    bit: ilo,
                                    out_bit: lo,
                                    resistive: sh.resistive,
                                    tick,
                                },
                            );
                        }
                        let amb = can_be_ambiguous(sh.gate).then(|| {
                            let a = alloc(res, slot.width);
                            res.ambiguous.insert(s, a.slot.slot);
                            route(res, a, lo)
                        });
                        let (d, l) = route(res, dst, lo);
                        (d, l, amb)
                    }
                    None => {
                        let (d, l) = route(res, loc_of(*id, slot), lo);
                        (d, l, None)
                    }
                };
                outputs.push(out);
            }
            plans.prims.push(PrimPlan {
                gate: sh.gate,
                udp: sh.udp,
                inputs,
                outputs,
                path: inst.hierarchical_path(),
            });
        }

        // Unconnected input ports under `unconnected_drive` (LRM 22.5.2):
        // a constant pull driver per bit, as a `pullup`/`pulldown` would be.
        // Planned once, with the first instance.
        for (pid, port, net, one) in std::mem::take(&mut res.open_pulls) {
            let slot = signals[&pid][&net];
            let key = DriverKey::Prim(pid, port, net);
            let mut outputs = Vec::new();
            for bit in 0..slot.width {
                let dst = match res.slot(&key) {
                    Some(s) => loc_of(bank, bank_slot(s, slot.width)),
                    None => loc_of(pid, slot),
                };
                outputs.push((dst, bit, None));
            }
            plans.prims.push(PrimPlan {
                gate: if one { Gate::Pullup } else { Gate::Pulldown },
                udp: None,
                inputs: Vec::new(),
                outputs,
                path: String::new(),
            });
        }

        // Delayed continuous assignments.
        for ca in vj_codegen::module::discover_cont_assigns(body).map_err(|e| e.message)? {
            let (own_delay, ca_dyn) = match ca.delay {
                Some(d) => delays_or_dynamic(eval, d, &ca.sym, *id, own)?,
                None => (Delays::default(), None),
            };
            let (root, lo, width) = match ca.net_target {
                Some(net) => {
                    let slot = *own
                        .get(&net.uid())
                        .ok_or_else(|| format!("net {} has no slot", net.name()))?;
                    (net, 0, slot.width)
                }
                None => {
                    let lhs = ca.assign_expr.left().ok_or("an assign with no target")?;
                    let roots = crate::nets::lvalue_roots(lhs);
                    let [root] = roots[..] else {
                        if own_delay.is_zero() && ca_dyn.is_none() {
                            continue;
                        }
                        return Err(format!(
                            "{}: a delayed continuous assignment to a concatenation",
                            ca.sym.hierarchical_path()
                        ));
                    };
                    let Some(slot) = own.get(&root.uid()).copied() else {
                        continue;
                    };
                    if vj_sim::symid::is_value_name(lhs.kind()) {
                        (root, 0, slot.width)
                    } else if let Some((_, _, bit)) = signal_bit(eval, lhs, own) {
                        (root, bit, 1)
                    } else if lhs.kind() == ExpressionKind::RangeSelect
                        && let Some(base) = lhs.select_value()
                        && let (Some(l), Some(r)) = (lhs.range_left(), lhs.range_right())
                        && let (Some(a), Some(b)) = (
                            select_offset(eval, base, l, slot.width),
                            select_offset(eval, base, r, slot.width),
                        )
                        && lhs.range_selection_kind().is_some_and(|k| {
                            vj_codegen::expr::classify_range_selection_kind(k)
                                == Ok(vj_codegen::expr::RangeSelectionKindClass::Simple)
                        })
                    {
                        (root, a.min(b), a.abs_diff(b) + 1)
                    } else {
                        if own_delay.is_zero()
                            && ca_dyn.is_none()
                            && net_delays(eval, &root)?.is_zero()
                        {
                            continue;
                        }
                        return Err(format!(
                            "{}: a delayed continuous assignment whose target is not a whole \
                             signal or a constant select of one",
                            ca.sym.hierarchical_path()
                        ));
                    }
                }
            };
            // A declaration assignment's delay is the net's own.
            let delays = if ca.net_target.is_some() {
                own_delay
            } else {
                own_delay.plus(&net_delays(eval, &root)?)
            };
            if delays.is_zero() && ca_dyn.is_none() {
                continue;
            }
            // Task 9 (LRM 30.6): this destination is ALSO a module-path
            // target -- expose `delays` for `crate::specify::plan`'s own
            // retimer to fold into its own `max(natural, specify)` schedule
            // instead of this module building a SECOND, independently-
            // committing delay line for the same destination (see
            // `Plans::natural`'s own doc comment for why that would race).
            if specify_dests.contains(&(*id, root.uid())) {
                if ca_dyn.is_some() {
                    return Err(format!(
                        "{}: a variable delay on a specify path destination",
                        ca.sym.hierarchical_path()
                    ));
                }
                plans.natural.insert((*id, root.uid()), delays);
                continue;
            }
            let slot = own[&root.uid()];
            let is_mem = matches!(slot.class, SignalSlotClass::Memory { .. });
            if is_mem && (lo != 0 || width != slot.width) {
                return Err(format!(
                    "{}: a delayed continuous assignment to part of an unpacked array (LRM 10.3.3)",
                    ca.sym.hierarchical_path()
                ));
            }
            let key = DriverKey::Assign(*id, ca.sym.uid(), root.uid());
            let dst = match res.slot(&key) {
                Some(s) if is_mem => loc_of(bank, SignalSlot { slot: s, ..slot }),
                Some(s) => loc_of(bank, bank_slot(s, slot.width)),
                None => loc_of(*id, slot),
            };
            let staging = alloc(res, slot.width);
            // An unpacked array stages row by row: its staging cell is a memory shaped like it.
            let staging = if is_mem {
                res.bank_mem.insert(staging.slot.slot, slot);
                loc_of(
                    bank,
                    SignalSlot {
                        slot: staging.slot.slot,
                        ..slot
                    },
                )
            } else {
                staging
            };
            let kick = alloc(res, 32);
            plans.staged.insert(key, staging.slot.slot);
            plans.lines.push(LinePlan {
                staging,
                range: (lo, width),
                dst,
                dst_lo: lo,
                delays,
                kick,
                live: None,
                dynamic: ca_dyn,
            });
        }
    }
    Ok(plans)
}