brink-ir 0.0.17

Intermediate representations for inkle's ink narrative scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Per-scope LIR chunks with chunk-local (symbolic) name references (FG-4c,
//! #817 — `docs/fine-grained-salsa-proposal.md` §5 + the
//! three-resolution-moments appendix).
//!
//! Lowering no longer threads a single shared
//! [`NameTable`](super::context::NameTable) through the whole container tree.
//! Instead each top-level scope (one file's root-level content, or a whole
//! knot subtree) is lowered against its **own** fresh `NameTable`, producing
//! a self-contained
//! [`ScopeChunk`]: a slice of the container tree whose `NameId`s index the
//! chunk's *own* owned `local_names` table rather than a project-wide one.
//!
//! A chunk is therefore the LIR analogue of FG-4b's `ContainerChunk`: its
//! name references are symbolic (the strings are owned by the chunk, the
//! content *is* the address) and it depends on no shared mutable state, so it
//! is memoizable in isolation (the FG-4d win this representation exists to
//! unlock). The whole-project **assembly** step ([`assemble_scopes`]) is the
//! LIR analogue of FG-4b's link phase: it merges every chunk's local names
//! into the project name table in deterministic walk order and *relocates*
//! each chunk's local `NameId`s to their assembled positions
//! ([`remap_container`] / [`remap_stmts`]), yielding today's whole-project
//! [`lir::Container`](super::lir::Container). The relocation erases itself —
//! a merged name table built in the fixed decls-then-walk order is
//! byte-identical to the one the old shared-table walk produced.
//!
//! History-independence (the FG-4d gate): a chunk's local table lists the
//! strings it references in first-occurrence walk order, and the merge is a
//! pure dedup over that order — both content-derived, never allocation-history
//! derived. Assembling the chunks in the same order the tree is walked
//! reproduces the project name table exactly whether a chunk was freshly
//! lowered or (in a future incremental world) reused from cache.

use brink_format::NameId;

use super::context::NameTable;
use super::lir;

/// One lowered top-level scope, self-contained w.r.t. names.
///
/// `body`/`children` carry `NameId`s that index this chunk's own
/// [`local_names`](Self::local_names), *not* the assembled project name
/// table. [`assemble_scopes`] relocates them.
///
/// A **root-content** chunk (one file's top-level content) carries that
/// file's top-level `body` statements and its inline `children`
/// (sequence/choice/gather containers created while lowering that body). A
/// **knot** chunk carries an empty `body` and a single-element `children`
/// holding the knot container (with its stitches and inline children nested
/// inside). Both shapes flatten into the root container by the assembler in
/// exactly the order the old `lower_root` appended them.
#[derive(Clone, Default)]
pub struct ScopeChunk {
    pub body: Vec<lir::Stmt>,
    pub children: Vec<lir::Container>,
    /// The chunk's owned name strings, in first-occurrence walk order. Local
    /// `NameId(i)` refers to `local_names[i]`.
    pub local_names: Vec<String>,
}

impl ScopeChunk {
    /// A root-content chunk: a file's top-level `body` + its inline
    /// `children`, plus the local names collected while lowering them.
    pub fn root_content(
        body: Vec<lir::Stmt>,
        children: Vec<lir::Container>,
        local_names: Vec<String>,
    ) -> Self {
        Self {
            body,
            children,
            local_names,
        }
    }

    /// A knot chunk: the lowered knot container (stitches + inline children
    /// nested) plus the names collected while lowering the whole subtree.
    ///
    /// `lifted` carries the lambda-lifted function containers synthesized
    /// while lowering that subtree (issue #1709). They are *siblings* of the
    /// knot, not children of it — a lifted function is entered only through
    /// its own fn value, so it belongs at top level next to the project's
    /// function knots (see `lower::lambda`'s module doc). Appending them
    /// after the knot leaves the assembled root-children order for every
    /// lambda-free project byte-identical.
    pub fn knot(
        container: lir::Container,
        lifted: Vec<lir::Container>,
        local_names: Vec<String>,
    ) -> Self {
        let mut children = Vec::with_capacity(1 + lifted.len());
        children.push(container);
        children.extend(lifted);
        Self {
            body: Vec::new(),
            children,
            local_names,
        }
    }
}

/// Merge every chunk's `local_names` into `names` (the project table, already
/// seeded with declaration/struct names) in walk order, relocate each chunk's
/// local `NameId`s to their assembled positions, and flatten the chunks into
/// the root container's `body`/`children`.
///
/// The merge is a pure first-occurrence dedup, so a string a chunk references
/// that was already interned (by decls, structs, or an earlier chunk) keeps
/// its earlier assembled id — exactly what the old single shared-table walk
/// did, hence byte-identical.
pub(super) fn assemble_scopes(
    chunks: Vec<ScopeChunk>,
    names: &mut NameTable,
) -> (Vec<lir::Stmt>, Vec<lir::Container>) {
    let mut body = Vec::new();
    let mut children = Vec::new();

    for mut chunk in chunks {
        // Relocation table: local NameId -> assembled NameId.
        let map: Vec<NameId> = chunk.local_names.iter().map(|s| names.intern(s)).collect();

        remap_stmts(&mut chunk.body, &map);
        for c in &mut chunk.children {
            remap_container(c, &map);
        }

        body.extend(chunk.body);
        children.append(&mut chunk.children);
    }

    (body, children)
}

// ─── Name-id relocation visitor ─────────────────────────────────────
//
// Every `NameId` reachable from a chunk's subtree is a chunk-local index and
// must be relocated to its assembled position via `map`. The matches below
// are deliberately **exhaustive** (no `_ =>` arms on the name-bearing enums):
// a new `NameId`-carrying LIR variant will fail to compile here until it is
// handled, so this pass can never silently drop a name reference (the
// silent-data-drop hazard the project guards against).

fn relocate(id: &mut NameId, map: &[NameId]) {
    if let Some(assembled) = map.get(id.0 as usize) {
        *id = *assembled;
    }
}

fn remap_container(c: &mut lir::Container, map: &[NameId]) {
    for p in &mut c.params {
        relocate(&mut p.name, map);
    }
    remap_stmts(&mut c.body, map);
    for child in &mut c.children {
        remap_container(child, map);
    }
}

fn remap_stmts(stmts: &mut [lir::Stmt], map: &[NameId]) {
    for s in stmts {
        remap_stmt(s, map);
    }
}

fn remap_stmt(stmt: &mut lir::Stmt, map: &[NameId]) {
    use lir::StmtKind;
    match &mut stmt.kind {
        StmtKind::EmitContent(content) => remap_content(content, map),
        StmtKind::EmitLine(emission) | StmtKind::EvalLine(emission) => {
            remap_emission(emission, map);
        }
        StmtKind::EmitLineVariants(v) => {
            for emission in &mut v.variants {
                remap_emission(emission, map);
            }
        }
        StmtKind::ChoiceOutput { content, emission } => {
            remap_content(content, map);
            if let Some(e) = emission {
                remap_emission(e, map);
            }
        }
        StmtKind::Divert(d) => remap_divert(d, map),
        StmtKind::TunnelCall(t) => {
            for target in &mut t.targets {
                remap_divert_target(&mut target.target, map);
                remap_call_args(&mut target.args, map);
            }
        }
        StmtKind::ThreadStart(t) => {
            remap_divert_target(&mut t.target, map);
            remap_call_args(&mut t.args, map);
        }
        StmtKind::DeclareTemp {
            slot: _,
            name,
            value,
            synthetic: _,
        } => {
            relocate(name, map);
            if let Some(v) = value {
                remap_expr(v, map);
            }
        }
        StmtKind::Assign {
            target,
            op: _,
            value,
        } => {
            remap_assign_target(target, map);
            remap_expr(value, map);
        }
        StmtKind::Return {
            value,
            is_tunnel: _,
            args,
        } => {
            if let Some(v) = value {
                remap_expr(v, map);
            }
            remap_call_args(args, map);
        }
        StmtKind::ChoiceSet(cs) => {
            for choice in &mut cs.choices {
                remap_choice(choice, map);
            }
        }
        StmtKind::Conditional(cond) => remap_conditional(cond, map),
        StmtKind::Sequence(seq) => remap_sequence(seq, map),
        StmtKind::ExprStmt(e) | StmtKind::AttachElement(e) => remap_expr(e, map),
        StmtKind::LogicWhile(w) => {
            remap_expr(&mut w.condition, map);
            remap_stmts(&mut w.body, map);
            remap_stmts(&mut w.post, map);
        }
        // No name references.
        StmtKind::EnterContainer(_)
        | StmtKind::EndOfLine
        | StmtKind::LogicBreak
        | StmtKind::LogicContinue
        | StmtKind::EndElementRun => {}
    }
}

fn remap_divert(d: &mut lir::Divert, map: &[NameId]) {
    remap_divert_target(&mut d.target, map);
    remap_call_args(&mut d.args, map);
}

fn remap_divert_target(t: &mut lir::DivertTarget, map: &[NameId]) {
    use lir::DivertTarget;
    match t {
        DivertTarget::VariableTemp(_, name) => relocate(name, map),
        DivertTarget::Address(_)
        | DivertTarget::Variable(_)
        | DivertTarget::Done
        | DivertTarget::End => {}
    }
}

fn remap_call_args(args: &mut [lir::CallArg], map: &[NameId]) {
    use lir::CallArg;
    for arg in args {
        match arg {
            CallArg::Value(e) => remap_expr(e, map),
            CallArg::RefTemp(_, name) => relocate(name, map),
            CallArg::RefGlobal(_) => {}
            // T1e: segment expressions can reference temps (e.g. `ref
            // party[idx]`), same remap need as an ordinary `Value` arg. The
            // root is always a global `DefinitionId`, never remapped (same
            // as `RefGlobal`).
            CallArg::RefProjection { segments, .. } => {
                for seg in segments {
                    remap_expr(seg, map);
                }
            }
        }
    }
}

fn remap_assign_target(t: &mut lir::AssignTarget, map: &[NameId]) {
    use lir::AssignTarget;
    match t {
        AssignTarget::Temp(_, name) => relocate(name, map),
        AssignTarget::Global(_) => {}
    }
}

fn remap_choice(choice: &mut lir::Choice, map: &[NameId]) {
    if let Some(c) = &mut choice.condition {
        remap_expr(c, map);
    }
    for content in [
        &mut choice.start_content,
        &mut choice.choice_only_content,
        &mut choice.inner_content,
    ]
    .into_iter()
    .flatten()
    {
        remap_content(content, map);
    }
    if let Some(e) = &mut choice.display_emission {
        remap_emission(e, map);
    }
    if let Some(e) = &mut choice.output_emission {
        remap_emission(e, map);
    }
    remap_tags(&mut choice.tags, map);
}

fn remap_conditional(cond: &mut lir::Conditional, map: &[NameId]) {
    if let lir::CondKind::Switch(e) = &mut cond.kind {
        remap_expr(e, map);
    }
    for branch in &mut cond.branches {
        if let Some(c) = &mut branch.condition {
            remap_expr(c, map);
        }
        remap_stmts(&mut branch.body, map);
    }
}

fn remap_sequence(seq: &mut lir::Sequence, map: &[NameId]) {
    for branch in &mut seq.branches {
        remap_stmts(branch, map);
    }
}

fn remap_emission(emission: &mut lir::ContentEmission, map: &[NameId]) {
    if let lir::RecognizedLine::Template { slot_exprs, .. } = &mut emission.line {
        for e in slot_exprs {
            remap_expr(e, map);
        }
    }
    remap_tags(&mut emission.tags, map);
}

fn remap_content(content: &mut lir::Content, map: &[NameId]) {
    remap_content_parts(&mut content.parts, map);
    remap_tags(&mut content.tags, map);
}

fn remap_tags(tags: &mut [Vec<lir::ContentPart>], map: &[NameId]) {
    for tag in tags {
        remap_content_parts(tag, map);
    }
}

fn remap_content_parts(parts: &mut [lir::ContentPart], map: &[NameId]) {
    use lir::ContentPart;
    for part in parts {
        match part {
            ContentPart::Interpolation(e) => remap_expr(e, map),
            ContentPart::InlineConditional(cond) => remap_conditional(cond, map),
            ContentPart::InlineSequence(seq) => remap_sequence(seq, map),
            ContentPart::Text(_)
            | ContentPart::Glue
            | ContentPart::Spring
            | ContentPart::EnterSequence(_) => {}
        }
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "exhaustive per-variant Expr walk — one arm per variant is the point"
)]
fn remap_expr(expr: &mut lir::Expr, map: &[NameId]) {
    use lir::ExprKind as Expr;
    match &mut expr.kind {
        Expr::GetTemp(_, name) | Expr::TakeTemp(_, name) => relocate(name, map),
        Expr::String(s) => remap_string(s, map),
        // Single-subexpression walks (incl. the NS-A1 one-arg Option verbs).
        Expr::Prefix(_, e)
        | Expr::Postfix(e, _)
        | Expr::OptionSome(e)
        | Expr::SeqMin(e)
        | Expr::SeqMax(e)
        | Expr::SeqFirst(e)
        | Expr::SeqLast(e)
        | Expr::MapClear(e)
        | Expr::RandChance(e)
        | Expr::RandPick(e)
        | Expr::RandShuffle(e)
        | Expr::SeqSorted(e)
        | Expr::RangeNonEmpty(e)
        | Expr::RandRoll(e)
        | Expr::HeapPeek(e) => remap_expr(e, map),

        // Two-subexpression seq walks: the NS-A4 comparator verb, NS-A7's
        // heap entry, and the fn-value verbs' `(array, callback)` pair
        // (#1679, both the pure quartet and the effectful pair).
        Expr::SeqSortedBy { seq, cmp: second }
        | Expr::HeapPush { seq, value: second }
        | Expr::SeqMap { seq, f: second }
        | Expr::SeqFilter { seq, pred: second }
        | Expr::SeqFilterMap { seq, f: second }
        | Expr::SeqEach { seq, f: second }
        | Expr::SeqMapEach { seq, f: second } => {
            remap_expr(seq, map);
            remap_expr(second, map);
        }
        Expr::SeqFold { seq, init, f } => {
            remap_expr(seq, map);
            remap_expr(init, map);
            remap_expr(f, map);
        }
        Expr::RangeMake { start, end, .. } => {
            remap_expr(start, map);
            remap_expr(end, map);
        }
        // B1 `or`-coalescing (#1471) is a dedicated variant, not generic
        // `Infix` — same two-subexpression walk; `shape` carries no
        // `NameId` to remap.
        Expr::Infix(l, _, r)
        | Expr::Coalesce {
            lhs: l,
            rhs: r,
            shape: _,
        } => {
            remap_expr(l, map);
            remap_expr(r, map);
        }
        Expr::Call { target: _, args }
        | Expr::CallVariable { target: _, args }
        | Expr::CallExternal {
            target: _, args, ..
        } => remap_call_args(args, map),
        Expr::CallVariableTemp {
            slot: _,
            name,
            args,
        } => {
            relocate(name, map);
            remap_call_args(args, map);
        }
        // The NS-A8 tower family shares CallBuiltin's plain arg-list walk.
        Expr::CallBuiltin { builtin: _, args } | Expr::Tower { op: _, args } => {
            for e in args {
                remap_expr(e, map);
            }
        }
        Expr::MakeFnValue { target: _, bound } => remap_call_args(bound, map),
        Expr::CallValue { callee, args } | Expr::BindValue { callee, args } => {
            remap_expr(callee, map);
            for e in args {
                remap_expr(e, map);
            }
        }
        Expr::ArrayNew(elems) => {
            for e in elems {
                remap_expr(e, map);
            }
        }
        // NS-A7 `weighted(…)` shares MapNew's pair walk (weights/keys
        // then values).
        Expr::MapNew(pairs) | Expr::WeightedNew { pairs } => {
            for (k, v) in pairs {
                remap_expr(k, map);
                remap_expr(v, map);
            }
        }
        Expr::Index { base, index } | Expr::SeqRemoveAt { base, index } => {
            remap_expr(base, map);
            remap_expr(index, map);
        }
        // B1b (issue #1475): the `as` binding's own name is a temp name
        // like any other `GetTemp`/`TakeTemp` name and relocates with them.
        Expr::OptionBind { value, name, .. } => {
            remap_expr(value, map);
            relocate(name, map);
        }
        Expr::IndexSet { base, index, value } => {
            remap_expr(base, map);
            remap_expr(index, map);
            remap_expr(value, map);
        }
        Expr::CollectionLen(e)
        | Expr::CollectionKeys(e)
        | Expr::CollectionValues(e)
        | Expr::ConvertInt(e)
        | Expr::ConvertFloat(e)
        | Expr::ConvertString(e) => {
            remap_expr(e, map);
        }
        Expr::CollectionContains { container, needle } => {
            remap_expr(container, map);
            remap_expr(needle, map);
        }
        Expr::CollectionInsert { base, key, value } => {
            remap_expr(base, map);
            remap_expr(key, map);
            remap_expr(value, map);
        }
        Expr::CollectionRemove { base, key } => {
            remap_expr(base, map);
            remap_expr(key, map);
        }
        Expr::CharAt { s, index } => {
            remap_expr(s, map);
            remap_expr(index, map);
        }
        // NS-A1 Option verbs (issue #1107); the one-arg forms are merged
        // into the single-subexpression arm above.
        Expr::StrFind { s, sub } => {
            remap_expr(s, map);
            remap_expr(sub, map);
        }
        Expr::SeqIndexOf { seq, needle } => {
            remap_expr(seq, map);
            remap_expr(needle, map);
        }
        Expr::MapGetOpt { map: m, key } => {
            remap_expr(m, map);
            remap_expr(key, map);
        }
        Expr::MapContainsValue { map: m, value } => {
            remap_expr(m, map);
            remap_expr(value, map);
        }
        // `pop`'s receiver is an `AssignTarget` — its `Temp` leg carries a
        // NameId, remapped exactly like a `Stmt::Assign` target.
        // `heap_pop` shares `pop`'s AssignTarget-receiver shape.
        Expr::SeqPop { root } | Expr::HeapPop { root } => remap_assign_target(root, map),
        Expr::RecordNew {
            shape_id: _,
            fields,
            prelude,
        } => {
            for e in fields {
                remap_expr(e, map);
            }
            for (_slot, name, e) in prelude {
                relocate(name, map);
                remap_expr(e, map);
            }
        }
        Expr::RecordGet {
            base,
            field,
            static_offset: _,
        } => {
            remap_expr(base, map);
            relocate(field, map);
        }
        Expr::RecordSet {
            base,
            field,
            static_offset: _,
            value,
        } => {
            remap_expr(base, map);
            relocate(field, map);
            remap_expr(value, map);
        }
        // Block capture (issue #1839): the captured statements are lowered
        // within this same chunk, so any `GetTemp`/`TakeTemp` they
        // reference needs the identical relocation everything else in the
        // chunk gets.
        Expr::Fragment(stmts) => remap_stmts(stmts, map),
        // No name references.
        Expr::Int(_)
        | Expr::Float(_)
        | Expr::Bool(_)
        | Expr::Null
        | Expr::GetGlobal(_)
        | Expr::TakeGlobal(_)
        | Expr::VisitCount(_)
        | Expr::DivertTarget(_)
        | Expr::ListLiteral { .. }
        | Expr::ConstLiteral(_)
        | Expr::OptionNone
        | Expr::RandFloat => {}
    }
}

fn remap_string(s: &mut lir::StringExpr, map: &[NameId]) {
    for part in &mut s.parts {
        if let lir::StringPart::Interpolation(e) = part {
            remap_expr(e, map);
        }
    }
}

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

    /// A placeholder `Provenance` for fixture `lir::Stmt`s in this module's
    /// tests — the remap machinery under test never reads it, only the
    /// `NameId`s it relocates.
    fn test_provenance() -> crate::Provenance {
        crate::Provenance::synthetic(crate::NodeClass::Stmt, rowan::TextRange::empty(0.into()))
    }

    #[test]
    fn relocate_maps_local_to_assembled() {
        let map = vec![NameId(5), NameId(2), NameId(9)];
        let mut id = NameId(1);
        relocate(&mut id, &map);
        assert_eq!(id, NameId(2));
    }

    #[test]
    fn remap_rewrites_nested_name_ids() {
        // Local names [greeting, field] -> assembled [7, 3].
        let map = vec![NameId(7), NameId(3)];
        let mut expr = lir::ExprKind::Infix(
            Box::new(lir::ExprKind::GetTemp(0, NameId(0)).at(test_provenance())),
            crate::InfixOp::Add,
            Box::new(
                lir::ExprKind::RecordGet {
                    base: Box::new(lir::ExprKind::GetTemp(1, NameId(0)).at(test_provenance())),
                    field: NameId(1),
                    static_offset: None,
                }
                .at(test_provenance()),
            ),
        )
        .at(test_provenance());
        remap_expr(&mut expr, &map);
        let (l, r) = match &expr.kind {
            lir::ExprKind::Infix(l, _, r) => Some((l, r)),
            _ => None,
        }
        .expect("expected infix");
        assert!(matches!(l.kind, lir::ExprKind::GetTemp(0, NameId(7))));
        let (base, field) = match &r.kind {
            lir::ExprKind::RecordGet { base, field, .. } => Some((base, field)),
            _ => None,
        }
        .expect("expected record get");
        assert!(matches!(base.kind, lir::ExprKind::GetTemp(1, NameId(7))));
        assert_eq!(*field, NameId(3));
    }

    #[test]
    fn assemble_dedups_against_existing_table() {
        let mut names = NameTable::new();
        let pre = names.intern("existing"); // NameId(0)

        let chunk = ScopeChunk::root_content(
            vec![lir::Stmt::new(
                lir::StmtKind::DeclareTemp {
                    slot: 0,
                    name: NameId(1), // local -> "fresh"
                    value: Some(lir::ExprKind::GetTemp(0, NameId(0)).at(test_provenance())), // local -> "existing"
                    synthetic: false,
                },
                test_provenance(),
            )],
            Vec::new(),
            vec!["existing".to_string(), "fresh".to_string()],
        );

        let (mut body, children) = assemble_scopes(vec![chunk], &mut names);
        assert!(children.is_empty());

        // "existing" deduped to its prior id; "fresh" got a new one after it.
        let entries = names.into_entries();
        assert_eq!(entries, vec!["existing".to_string(), "fresh".to_string()]);
        assert_eq!(pre, NameId(0));

        let (name, value) = match body.remove(0).kind {
            lir::StmtKind::DeclareTemp { name, value, .. } => Some((name, value)),
            _ => None,
        }
        .expect("expected declare temp");
        assert_eq!(name, NameId(1)); // "fresh"
        assert!(matches!(
            value.map(|v| v.kind),
            Some(lir::ExprKind::GetTemp(0, NameId(0)))
        )); // "existing"
    }
}