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
//! SDF `LABEL` annotation of specparams (IEEE 1800-2023 32.4.3; SD-C / T28,
//! `docs/superpowers/plans/2026-10-03-sdf.md`).
//!
//! LRM 32.4.3: "The SDF LABEL construct annotates to specparams. Any expression containing one
//! or more specparams is reevaluated when annotated to from an SDF file." The standard's two
//! examples are the clock module (`#dhigh clk = 1; #dlow clk = 0;`, delays that ARE specparams)
//! and a path delay `specify (A => Z) = 1.4 * cap + 0.7; endspecify` whose `cap` is annotated.
//!
//! **How it works.** Planning ([`collect`]) records, per instance, every specparam (name, run-time
//! key, source value) and every expression that reads one and that annotation must re-evaluate:
//! the delay list of a module path ([`PathDep`]) and the limits of a system timing check
//! ([`LimitDep`]), each as the source text of the expression. A `LABEL` ([`InstLabels::annotate`])
//! replaces (`ABSOLUTE`) or adds to (`INCREMENT`) the specparam's value; the dependent path
//! delays and check limits are then evaluated again from their text in a scratch script session
//! ([`InstLabels::evaluate`]) in which the instance's parameters and specparams (the annotated
//! ones with their new values) are declared, and written to the live tables
//! (`crate::sdf_apply`). A specparam read in procedural code, a `#delay` or any other expression
//! the kernels compile is a run-time read of the annotated value
//! (`vj_runtime::specparam`, `vj_codegen::timescale::lower_specparam_read`).
//!
//! **Implementation-defined choices** (the LRM leaves them open):
//! - A `LABEL` value is a time in the SDF file's `TIMESCALE`, converted to the time unit of the
//!   module the specparam lives in (an annotated specparam holds module time units, which is
//!   what `#dhigh` and a path delay expect). The LRM example's `(dhigh 60)` is 60 of the SDF
//!   file's unit.
//! - An annotated specparam holds a real number whatever its declared type: a delay that IS a
//!   specparam (`#dhigh`) keeps the fraction (`60.5` waits 60.5 units), and a path delay or limit
//!   is re-evaluated with the annotated value as a real. A read of an annotated specparam in an
//!   integral context (`$display(dhigh)`, `#(dhigh + 1)`) rounds it to the declared type.
//! - A re-evaluation replaces the delay (or limit) outright, so a `LABEL` that reaches a path
//!   discards an earlier `IOPATH` / `TIMINGCHECK` annotation of it, and a later one replaces the
//!   `LABEL`'s (annotation is ordered, LRM 32.5). The path's pulse limits follow its delays only
//!   while they were still the default (equal to the delays, LRM 30.7).
//! - A path delay below zero is zero (LRM 30.5.1); a limit keeps its sign.
//!
//! **What is not re-evaluated** (each reported as a warning when a `LABEL` reaches it, never
//! skipped silently): a specparam read in a gate, continuous-assignment or net delay or in a
//! path or timing-check condition (all fixed when the design is planned); the threshold of a
//! `$width`; a `PATHPULSE$` specparam; and another specparam's initializer. A specparam that is
//! not a number of at most 64 bits (a string, or one with `x`/`z` bits) cannot be annotated.
//! A design compiled ahead of time (`vj aot`) has no annotator, so its specparams keep
//! their source values.

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

use sv_lang::kinds::{ExpressionKind, SymbolKind};
use sv_lang::{ConstantValue, EvalSession, Expression, ScriptSession, Symbol, SyntaxTree};
use vj_sdf::ast::DeltaMode;
use vj_sim::netlist::InstanceId;
use vj_sim::netlist::specify::{CheckArgs, TimingModel};
use vj_sim::symid::{SymbolId, SymbolUid};

/// A specparam's value before any `LABEL`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Source {
    Real(f64),
    Integer(i64),
}

impl Source {
    fn as_f64(self) -> f64 {
        match self {
            Source::Real(f) => f,
            Source::Integer(i) => i as f64,
        }
    }
}

/// One specparam of an instance.
#[derive(Clone, Debug)]
pub(crate) struct Specparam {
    pub(crate) name: String,
    pub(crate) uid: SymbolId,
    /// The key the run-time read looks it up by (`vj_codegen::timescale::specparam_key`).
    key: Option<String>,
    source: Source,
    /// Why a `LABEL` cannot annotate it, when one cannot.
    refused: Option<String>,
    /// The value an SDF `LABEL` gave it, in the module's time unit.
    annotated: Option<f64>,
    /// The other specparams its initializer reads.
    derived_from: Vec<String>,
}

impl Specparam {
    /// The value as it stands now, in the module's time unit.
    pub(crate) fn current(&self) -> f64 {
        self.annotated.unwrap_or_else(|| self.source.as_f64())
    }

    /// Gives it `value` (`ABSOLUTE`) or adds `value` to it (`INCREMENT`), in the module's time
    /// unit, and publishes the result to the kernels. Returns the new value.
    pub(crate) fn annotate(&mut self, mode: DeltaMode, value: f64) -> Result<f64, String> {
        if let Some(why) = &self.refused {
            return Err(format!("`{}` {why}", self.name));
        }
        let new = match mode {
            DeltaMode::Absolute => value,
            DeltaMode::Increment => self.current() + value,
        };
        if !new.is_finite() {
            return Err(format!(
                "`{}` would become {new}, which is not finite",
                self.name
            ));
        }
        // `refused` covers a missing key, so it is present here.
        let key = self
            .key
            .as_deref()
            .ok_or_else(|| format!("`{}` has no run-time key (internal)", self.name))?;
        vj_runtime::specparam::set(key, new);
        self.annotated = Some(new);
        Ok(new)
    }

    /// The specparam's identity, as a path condition names it (`CondNode::Specparam`).
    pub(crate) fn uid(&self) -> &SymbolId {
        &self.uid
    }

    /// The names of the other specparams this one's initializer reads.
    pub(crate) fn derived_from(&self) -> &[String] {
        &self.derived_from
    }

    /// The declaration that gives a scratch session this specparam's value. An annotated one is
    /// a `real`; an unannotated one keeps its declared kind (an integral specparam is a
    /// `longint` there, as in `crate::specify`'s `PATHPULSE$` evaluation).
    fn declaration(&self) -> Option<String> {
        if let Some(f) = self.annotated {
            return real_declaration(&self.name, f);
        }
        match self.source {
            Source::Real(f) => real_declaration(&self.name, f),
            Source::Integer(i) => Some(integer_declaration(&self.name, i)),
        }
    }
}

fn real_declaration(name: &str, f: f64) -> Option<String> {
    f.is_finite().then(|| format!("real {name} = {f:?};"))
}

/// A sized signed hex literal, so every `i64` (`i64::MIN` has no positive decimal literal)
/// round-trips bit-exactly.
fn integer_declaration(name: &str, i: i64) -> String {
    format!("longint {name} = 64'sh{:x};", i as u64)
}

/// An expression that reads specparams, and so is re-evaluated when one is annotated.
#[derive(Clone, Debug)]
pub(crate) struct Dependent {
    /// The source text of each expression (`Err`: the expression has no source text to
    /// evaluate again).
    pub(crate) texts: Result<Vec<String>, String>,
    /// The specparams the expressions read, by name.
    pub(crate) refs: Vec<String>,
}

impl Dependent {
    pub(crate) fn reads_any(&self, names: &[String]) -> bool {
        self.refs.iter().any(|r| names.contains(r))
    }
}

/// A module path whose delay list reads specparams: the `TimingModel::paths` entries it
/// desugars to (one per input/output terminal pair) and the list.
#[derive(Clone, Debug)]
pub(crate) struct PathDep {
    pub(crate) indices: Vec<usize>,
    pub(crate) dep: Dependent,
}

/// One limit of a system timing check that reads specparams.
#[derive(Clone, Debug)]
pub(crate) struct LimitDep {
    /// The `TimingModel::timing_checks` entry.
    pub(crate) entry: usize,
    /// The limit's slot in `LiveChecks` (`None`: a limit no annotation reaches, the threshold
    /// of a `$width`).
    pub(crate) slot: Option<usize>,
    pub(crate) dep: Dependent,
}

/// Everything a `LABEL` needs to know about one instance.
#[derive(Clone, Debug)]
pub(crate) struct InstLabels {
    /// The module's time unit exponent: what a `LABEL` value is converted to.
    pub(crate) unit_exp: i32,
    params: Vec<(String, ConstantValue)>,
    pub(crate) specparams: Vec<Specparam>,
    pub(crate) paths: Vec<PathDep>,
    pub(crate) limits: Vec<LimitDep>,
    /// Specparams read by a gate, continuous-assignment or net delay: fixed at planning.
    planned_reads: HashSet<String>,
}

impl InstLabels {
    /// The specparam called `name`, which a `LABEL` names.
    pub(crate) fn specparam_mut(&mut self, name: &str) -> Option<&mut Specparam> {
        self.specparams.iter_mut().find(|s| s.name == name)
    }

    /// Whether a gate, continuous-assignment or net delay reads `name` (planned once, so a
    /// `LABEL` does not reach it).
    pub(crate) fn read_by_planned_delay(&self, name: &str) -> bool {
        self.planned_reads.contains(name)
    }

    /// Evaluates `texts` (constant expressions over literals, parameters and specparams, in the
    /// module's time unit) with the specparams at their current values.
    #[cfg(test)]
    pub(crate) fn evaluate(&self, texts: &[String]) -> Result<Vec<f64>, String> {
        self.evaluate_all(&[texts])?.remove(0)
    }

    /// [`Self::evaluate`] for several lists of expressions in one scratch session (building one
    /// is the expensive part). `Err` is a session that cannot be built; each job has its own.
    pub(crate) fn evaluate_all(
        &self,
        jobs: &[&[String]],
    ) -> Result<Vec<Result<Vec<f64>, String>>, String> {
        let mut session = ScriptSession::new().map_err(|e| format!("{e:?}"))?;
        for (name, v) in &self.params {
            let decl = match v {
                ConstantValue::Real(f) => real_declaration(name, *f),
                other => other.as_i64().map(|i| integer_declaration(name, i)),
            };
            // A parameter that is not a number (a string) is left undeclared, so an expression
            // that reads it fails below, loudly.
            if let Some(decl) = decl {
                session.eval(&decl);
            }
        }
        for sp in &self.specparams {
            if let Some(decl) = sp.declaration() {
                session.eval(&decl);
            }
        }
        Ok(jobs
            .iter()
            .map(|texts| {
                texts
                    .iter()
                    .map(|text| {
                        // Parenthesised on its own lines, so a trailing `//` comment in the
                        // text cannot swallow the closing parenthesis.
                        let value = session.eval(&format!("(\n{text}\n)")).ok_or_else(|| {
                            format!(
                                "`{}` is not a constant expression over literals, \
                                     specparams and parameters",
                                text.trim()
                            )
                        })?;
                        match value {
                            ConstantValue::Real(f) => Ok(f),
                            other => other
                                .as_i64()
                                .map(|i| i as f64)
                                .ok_or_else(|| format!("`{}` is not a number", text.trim())),
                        }
                    })
                    .collect()
            })
            .collect())
    }
}

/// Every instance's [`InstLabels`].
#[derive(Default)]
pub(crate) struct LabelPlan {
    instances: HashMap<InstanceId, InstLabels>,
}

impl LabelPlan {
    pub(crate) fn get_mut(&mut self, id: InstanceId) -> Option<&mut InstLabels> {
        self.instances.get_mut(&id)
    }

    #[cfg(test)]
    pub(crate) fn insert(&mut self, id: InstanceId, labels: InstLabels) {
        self.instances.insert(id, labels);
    }
}

#[cfg(test)]
impl InstLabels {
    /// An instance with specparams `(name, value)` (all real) and nothing reading them, for
    /// tests that drive annotation without elaborating a design.
    pub(crate) fn for_test(unit_exp: i32, specparams: &[(&str, f64)]) -> InstLabels {
        InstLabels {
            unit_exp,
            params: Vec::new(),
            specparams: specparams
                .iter()
                .map(|&(name, v)| Specparam {
                    name: name.to_string(),
                    uid: SymbolId::synthetic(&format!("test.{name}")),
                    key: Some(format!("test.{name}")),
                    source: Source::Real(v),
                    refused: None,
                    annotated: None,
                    derived_from: Vec::new(),
                })
                .collect(),
            paths: Vec::new(),
            limits: Vec::new(),
            planned_reads: HashSet::new(),
        }
    }

    /// The identity of specparam `name`.
    pub(crate) fn specparam_uid(&self, name: &str) -> SymbolId {
        self.specparams
            .iter()
            .find(|s| s.name == name)
            .expect("a specparam of this instance")
            .uid
            .clone()
    }

    /// Makes `name` read by a gate, continuous-assignment or net delay.
    pub(crate) fn reading_in_planned_delay(mut self, name: &str) -> Self {
        self.planned_reads.insert(name.to_string());
        self
    }

    /// Makes the initializer of specparam `name` read `refs`.
    pub(crate) fn derived(mut self, name: &str, refs: &[&str]) -> Self {
        let sp = self
            .specparam_mut(name)
            .expect("a specparam of this instance");
        sp.derived_from = refs.iter().map(|r| r.to_string()).collect();
        self
    }

    /// Makes specparam `name` impossible to annotate, for `why`.
    pub(crate) fn refused(mut self, name: &str, why: &str) -> Self {
        let sp = self
            .specparam_mut(name)
            .expect("a specparam of this instance");
        sp.refused = Some(why.to_string());
        self
    }

    /// Re-keys every specparam under the instance path `prefix` (`prefix.name`).
    pub(crate) fn keyed(mut self, prefix: &str) -> Self {
        for sp in &mut self.specparams {
            sp.key = Some(format!("{prefix}.{}", sp.name));
        }
        self
    }

    pub(crate) fn with_path(mut self, indices: Vec<usize>, texts: &[&str], refs: &[&str]) -> Self {
        self.paths.push(PathDep {
            indices,
            dep: Dependent {
                texts: Ok(texts.iter().map(|t| t.to_string()).collect()),
                refs: refs.iter().map(|r| r.to_string()).collect(),
            },
        });
        self
    }

    pub(crate) fn with_limit(
        mut self,
        entry: usize,
        slot: Option<usize>,
        text: &str,
        refs: &[&str],
    ) -> Self {
        self.limits.push(LimitDep {
            entry,
            slot,
            dep: Dependent {
                texts: Ok(vec![text.to_string()]),
                refs: refs.iter().map(|r| r.to_string()).collect(),
            },
        });
        self
    }
}

/// The expression a delay or limit evaluates: `min:typ:max` takes the typical value, like every
/// other delay in the design.
fn typical<'d>(e: Expression<'d>) -> Option<Expression<'d>> {
    if e.kind() == ExpressionKind::MinTypMax {
        e.children()
            .into_iter()
            .filter_map(|n| n.as_expression())
            .nth(1)
    } else {
        Some(e)
    }
}

/// The [`Dependent`] of `exprs`, or `None` when none of them reads a specparam.
fn dependent<'d>(
    exprs: impl Iterator<Item = Expression<'d>>,
    trees: &[SyntaxTree],
) -> Option<Dependent> {
    let mut refs: Vec<String> = Vec::new();
    let mut texts: Result<Vec<String>, String> = Ok(Vec::new());
    for e in exprs {
        let Some(e) = typical(e) else {
            texts = Err("a min:typ:max value with no typical member".to_string());
            continue;
        };
        for sp in vj_codegen::timescale::specparam_refs(e) {
            if !refs.iter().any(|r| r == sp.name()) {
                refs.push(sp.name().to_string());
            }
        }
        let text = trees.iter().find_map(|t| e.syntax(t)).map(|n| n.text());
        match (&mut texts, text) {
            (Ok(v), Some(t)) => v.push(t),
            (Ok(_), None) => texts = Err("the expression has no source text".to_string()),
            (Err(_), _) => {}
        }
    }
    (!refs.is_empty()).then_some(Dependent { texts, refs })
}

/// A specparam's [`Source`], or why it cannot be annotated.
fn source_of(v: Option<ConstantValue>) -> Result<Source, String> {
    match v {
        Some(ConstantValue::Real(f)) if f.is_finite() => Ok(Source::Real(f)),
        Some(ConstantValue::Real(_)) => Err("is not a finite number".to_string()),
        Some(other) => match other.as_i64() {
            Some(i) => Ok(Source::Integer(i)),
            None => Err(
                "is not a number of at most 64 bits with no x or z (a string, a wide or a \
                 4-state specparam cannot be annotated)"
                    .to_string(),
            ),
        },
        None => Err("has no constant value".to_string()),
    }
}

/// Plans the `LABEL` annotation of every instance of `infos` (see the module doc). Never fails:
/// what cannot be re-evaluated is recorded as such and reported only if an SDF file reaches it,
/// so a design with exotic specparams that never calls `$sdf_annotate` is unaffected.
pub(crate) fn collect<'d>(
    eval: &EvalSession<'d>,
    infos: &[(InstanceId, Symbol<'d>)],
    model: &TimingModel,
) -> LabelPlan {
    let trees = eval.design().syntax_trees();
    let path_symbols = crate::specify::timing_path_symbols(infos);
    let check_symbols = crate::timingcheck::timing_check_symbols(infos);
    let mut instances = HashMap::new();
    for &(id, body) in infos {
        let mut params = Vec::new();
        let mut specparams: Vec<Specparam> = Vec::new();
        let mut planned_reads: HashSet<String> = HashSet::new();
        let note_specparam = |s: Symbol<'d>, specparams: &mut Vec<Specparam>| {
            let name = s.name().to_string();
            let key = vj_codegen::timescale::specparam_key(&s);
            let value = model
                .specparam(id, &s.uid())
                .cloned()
                .or_else(|| s.constant_value());
            let (source, mut refused) = match source_of(value) {
                Ok(src) => (src, None),
                Err(why) => (Source::Integer(0), Some(why)),
            };
            if name.starts_with("PATHPULSE$") {
                refused = Some(
                    "is a PATHPULSE$ specparam, whose pulse limits are not re-evaluated"
                        .to_string(),
                );
            } else if key.is_none() {
                refused = Some("is outside any module instance".to_string());
            }
            let mut derived_from = Vec::new();
            if let Some(init) = s.initializer() {
                derived_from.extend(
                    vj_codegen::timescale::specparam_refs(init)
                        .into_iter()
                        .map(|r| r.name().to_string()),
                );
            }
            specparams.push(Specparam {
                name,
                uid: s.uid(),
                key,
                source,
                refused,
                annotated: None,
                derived_from,
            });
        };
        for m in vj_sim::netlist::module_items(&body) {
            match m.kind() {
                SymbolKind::Specparam => note_specparam(m, &mut specparams),
                SymbolKind::SpecifyBlock => {
                    for inner in m.members() {
                        if inner.kind() == SymbolKind::Specparam {
                            note_specparam(inner, &mut specparams);
                        }
                    }
                }
                SymbolKind::Parameter => {
                    if let Some(v) = m.constant_value() {
                        params.push((m.name().to_string(), v));
                    }
                }
                SymbolKind::PrimitiveInstance => {
                    note_planned_reads(m.primitive_instance_delay(), &mut planned_reads)
                }
                SymbolKind::ContinuousAssign => {
                    note_planned_reads(m.continuous_assign_delay(), &mut planned_reads)
                }
                SymbolKind::Net => note_planned_reads(m.net_delay(), &mut planned_reads),
                _ => {}
            }
        }
        let mut paths = Vec::new();
        for &(pid, sym) in &path_symbols {
            if pid != id {
                continue;
            }
            let Some(dep) = dependent(sym.timing_path_delays(), &trees) else {
                continue;
            };
            let indices: Vec<usize> = model
                .paths
                .iter()
                .enumerate()
                .filter(|(_, p)| p.instance == id && p.path_uid == sym.uid())
                .map(|(k, _)| k)
                .collect();
            paths.push(PathDep { indices, dep });
        }
        let mut limits = Vec::new();
        for (entry, e) in model.timing_checks.iter().enumerate() {
            if e.instance != id {
                continue;
            }
            let Some(sym) = check_symbols.get(&e.check_uid) else {
                continue;
            };
            let args: Vec<_> = sym.system_timing_check_arguments().collect();
            let is_width = matches!(e.args, CheckArgs::Width(_));
            let mut owned = e.args.clone();
            for (k, limit) in owned.limits_mut().iter().enumerate() {
                let Some(expr) = args.get(limit.arg_index as usize).and_then(|a| a.expr) else {
                    continue;
                };
                if let Some(dep) = dependent(std::iter::once(expr), &trees) {
                    // A `$width` threshold is the one limit `LiveChecks` has no slot for.
                    let slot = (!(is_width && k == 1)).then_some(k);
                    limits.push(LimitDep { entry, slot, dep });
                }
            }
        }
        instances.insert(
            id,
            InstLabels {
                unit_exp: vj_codegen::timescale::unit_exp(&body),
                params,
                specparams,
                paths,
                limits,
                planned_reads,
            },
        );
    }
    LabelPlan { instances }
}

/// Notes every specparam the delay control `delay` reads.
fn note_planned_reads(delay: Option<sv_lang::SemNode<'_>>, out: &mut HashSet<String>) {
    let Some(tc) = delay.and_then(|d| d.as_timing_control()) else {
        return;
    };
    for e in tc.children().into_iter().filter_map(|n| n.as_expression()) {
        for sp in vj_codegen::timescale::specparam_refs(e) {
            out.insert(sp.name().to_string());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn labels(unit_exp: i32, sp: &[(&str, f64)]) -> InstLabels {
        InstLabels::for_test(unit_exp, sp)
    }

    #[test]
    fn absolute_replaces_and_increment_adds() {
        let mut l = labels(-9, &[("cap", 0.0)]);
        let sp = l.specparam_mut("cap").unwrap();
        assert_eq!(sp.annotate(DeltaMode::Absolute, 2.5).unwrap(), 2.5);
        assert_eq!(sp.annotate(DeltaMode::Increment, 0.5).unwrap(), 3.0);
        assert_eq!(sp.current(), 3.0);
        assert_eq!(sp.annotate(DeltaMode::Absolute, 1.0).unwrap(), 1.0);
        vj_runtime::specparam::clear();
    }

    #[test]
    fn annotation_is_published_to_the_kernels_under_the_key() {
        vj_runtime::specparam::clear();
        let mut l = labels(-9, &[("dhigh", 0.0)]);
        assert!(vj_runtime::specparam::get("test.dhigh").is_none());
        l.specparam_mut("dhigh")
            .unwrap()
            .annotate(DeltaMode::Absolute, 60.0)
            .unwrap();
        assert_eq!(vj_runtime::specparam::get("test.dhigh"), Some(60.0));
        vj_runtime::specparam::clear();
    }

    #[test]
    fn a_non_finite_result_is_refused_and_leaves_the_value() {
        let mut l = labels(-9, &[("a", 1.0)]);
        let sp = l.specparam_mut("a").unwrap();
        assert!(sp.annotate(DeltaMode::Absolute, f64::INFINITY).is_err());
        assert!(sp.annotate(DeltaMode::Increment, f64::MAX * 2.0).is_err());
        assert_eq!(sp.current(), 1.0);
    }

    #[test]
    fn a_refused_specparam_says_why() {
        let mut l = labels(-9, &[("a", 1.0)]);
        let sp = l.specparam_mut("a").unwrap();
        sp.refused = Some("is a string".to_string());
        let err = sp.annotate(DeltaMode::Absolute, 1.0).unwrap_err();
        assert!(err.contains("`a` is a string"), "{err}");
        assert_eq!(sp.current(), 1.0);
    }

    #[test]
    fn evaluation_sees_the_annotated_value() {
        let mut l = labels(-9, &[("cap", 0.0)]);
        assert_eq!(l.evaluate(&["1.4 * cap + 0.7".into()]).unwrap(), [0.7]);
        l.specparam_mut("cap")
            .unwrap()
            .annotate(DeltaMode::Absolute, 2.5)
            .unwrap();
        let v = l.evaluate(&["1.4 * cap + 0.7".into()]).unwrap();
        assert!((v[0] - 4.2).abs() < 1e-12, "{v:?}");
        vj_runtime::specparam::clear();
    }

    #[test]
    fn evaluation_declares_parameters_and_integral_specparams() {
        let mut l = labels(-9, &[]);
        l.params.push(("P".into(), ConstantValue::Real(2.0)));
        l.specparams.push(Specparam {
            name: "n".into(),
            uid: SymbolId::synthetic("test.n"),
            key: Some("test.n".into()),
            source: Source::Integer(7),
            refused: None,
            annotated: None,
            derived_from: Vec::new(),
        });
        // An unannotated integral specparam keeps integer arithmetic (7 / 2 is 3).
        assert_eq!(l.evaluate(&["P * (n / 2)".into()]).unwrap(), [6.0]);
    }

    #[test]
    fn a_trailing_comment_cannot_swallow_the_closing_parenthesis() {
        let l = labels(-9, &[("a", 3.0)]);
        assert_eq!(l.evaluate(&["a + 1 // note".into()]).unwrap(), [4.0]);
    }

    #[test]
    fn evaluation_failure_names_the_expression() {
        let l = labels(-9, &[("a", 3.0)]);
        let err = l.evaluate(&["a + undeclared".into()]).unwrap_err();
        assert!(err.contains("a + undeclared"), "{err}");
    }

    #[test]
    fn declarations_round_trip_every_i64() {
        let l = labels(-9, &[]);
        for n in [i64::MIN, -1, 0, 1, 3_000_000_000, i64::MAX] {
            let mut sp = labels(-9, &[("x", 0.0)]).specparams.remove(0);
            sp.source = Source::Integer(n);
            let mut l2 = l.clone();
            l2.specparams.push(sp);
            let got = l2.evaluate(&["x".into()]).unwrap()[0];
            assert_eq!(got, n as f64, "{n}");
        }
    }
}