brink-codegen-inkb 0.0.17

Bytecode codegen backend: LIR → StoryData (inkb format)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! Expression compilation: LIR `Expr` → opcodes.

use brink_format::{ListValue, Opcode, SeqVerbOp};
use brink_ir::lir;

use crate::ContainerEmitter;

impl ContainerEmitter<'_> {
    /// Emit an expression. When `display` is true, function calls are
    /// wrapped in `BeginFragment`/`EndFragment` so their output is captured
    /// structurally for locale re-rendering.
    #[expect(
        clippy::too_many_lines,
        reason = "one match arm per LIR Expr variant; splitting would obscure the dispatch"
    )]
    pub(super) fn emit_expr(&mut self, expr: &lir::Expr, display: bool) {
        match &expr.kind {
            lir::ExprKind::Int(n) => self.emit(Opcode::PushInt(*n)),
            lir::ExprKind::Float(f) => self.emit(Opcode::PushFloat(*f)),
            lir::ExprKind::Bool(b) => self.emit(Opcode::PushBool(*b)),
            lir::ExprKind::Null => self.emit(Opcode::PushNull),

            lir::ExprKind::String(s) => self.emit_string_expr(s),

            lir::ExprKind::GetGlobal(id) => self.emit(Opcode::GetGlobal(*id)),
            lir::ExprKind::GetTemp(slot, _) => self.emit(Opcode::GetTemp(*slot)),
            lir::ExprKind::TakeGlobal(id) => self.emit(Opcode::TakeGlobal(*id)),
            lir::ExprKind::TakeTemp(slot, _) => self.emit(Opcode::TakeTemp(*slot)),

            lir::ExprKind::VisitCount(id) => {
                self.emit(Opcode::PushDivertTarget(*id));
                self.emit(Opcode::VisitCount);
            }

            lir::ExprKind::DivertTarget(id) => self.emit(Opcode::PushDivertTarget(*id)),

            lir::ExprKind::ListLiteral { items, origins } => {
                let lv = ListValue {
                    items: items.clone(),
                    origins: origins.clone(),
                };
                let idx = self.list_literals.len();
                self.list_literals.push(lv);
                #[expect(clippy::cast_possible_truncation)]
                self.emit(Opcode::PushList(idx as u16));
            }

            lir::ExprKind::Prefix(op, inner) => {
                self.emit_expr(inner, false);
                match op {
                    brink_ir::PrefixOp::Negate => self.emit(Opcode::Negate),
                    brink_ir::PrefixOp::Not => self.emit(Opcode::Not),
                }
            }

            lir::ExprKind::Infix(lhs, op, rhs) => {
                self.emit_expr(lhs, false);
                self.emit_expr(rhs, false);
                self.emit(infix_op_to_opcode(*op));
            }

            // B1 `or`-coalescing, short-circuited (issue #1471) — a real
            // branch, not a binary opcode, so `rhs`'s bytecode is only on
            // the path that actually reaches it (the `none` fall-through).
            // See `lir::ExprKind::Coalesce`'s own doc for the full shape.
            lir::ExprKind::Coalesce { lhs, rhs, shape } => {
                self.emit_expr(lhs, false);
                // Pops `lhs`; `some(v)` pushes the unwrapped `v` and jumps
                // to `some_site` below; `none` pushes nothing and falls
                // through into the `rhs` evaluation right here.
                let some_site = self.emit_jump_placeholder(Opcode::CoalesceSome(0));
                self.emit_expr(rhs, false);
                let end_site = self.emit_jump_placeholder(Opcode::Jump(0));
                self.patch_jump(some_site);
                // Only reached via the `some(v)` jump, with the unwrapped
                // `v` on top — re-wrap when the analyzer's recorded typing
                // says this step keeps its `Option`, so both branches agree
                // on shape at the join below.
                if matches!(shape, brink_ir::lir::CoalesceShape::PreserveOption) {
                    self.emit(Opcode::MakeSome);
                }
                self.patch_jump(end_site);
            }

            lir::ExprKind::Postfix(inner, op) => {
                self.emit_expr(inner, false);
                match op {
                    brink_ir::PostfixOp::Increment => {
                        self.emit(Opcode::PushInt(1));
                        self.emit(Opcode::Add);
                    }
                    brink_ir::PostfixOp::Decrement => {
                        self.emit(Opcode::PushInt(1));
                        self.emit(Opcode::Subtract);
                    }
                }
            }

            lir::ExprKind::Call { target, args } => {
                for arg in args {
                    self.emit_call_arg(arg);
                }
                self.emit_fragment_wrapped(display, Opcode::Call(*target));
            }

            lir::ExprKind::CallExternal {
                target,
                args,
                arg_count,
            } => {
                for arg in args {
                    self.emit_call_arg(arg);
                }
                self.emit_fragment_wrapped(display, Opcode::CallExternal(*target, *arg_count));
            }

            lir::ExprKind::CallVariable { target, args } => {
                for arg in args {
                    self.emit_call_arg(arg);
                }
                self.emit(Opcode::GetGlobal(*target));
                self.emit_fragment_wrapped(
                    display,
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a call supplies <=255 args"
                    )]
                    Opcode::CallVariable(args.len() as u8),
                );
            }

            lir::ExprKind::CallVariableTemp { slot, args, .. } => {
                for arg in args {
                    self.emit_call_arg(arg);
                }
                self.emit(Opcode::GetTemp(*slot));
                self.emit_fragment_wrapped(
                    display,
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a call supplies <=255 args"
                    )]
                    Opcode::CallVariable(args.len() as u8),
                );
            }

            lir::ExprKind::CallBuiltin { builtin, args } => {
                self.emit_builtin(*builtin, args);
            }

            // ── Function values (T1c, #700) ──────────────────────────
            lir::ExprKind::MakeFnValue { target, bound } => {
                for arg in bound {
                    self.emit_call_arg(arg);
                }
                if bound.is_empty() {
                    self.emit(Opcode::PushFnRef(*target));
                } else {
                    self.emit(Opcode::MakeClosure {
                        target: *target,
                        #[expect(
                            clippy::cast_possible_truncation,
                            reason = "a #fn binds <=255 args (E081 caps at the declared row)"
                        )]
                        bound_count: bound.len() as u8,
                    });
                }
            }

            lir::ExprKind::CallValue { callee, args } => {
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit_expr(callee, false);
                self.emit_fragment_wrapped(
                    display,
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a call supplies <=255 args"
                    )]
                    Opcode::CallValue(args.len() as u8),
                );
            }

            lir::ExprKind::BindValue { callee, args } => {
                // Same stack shape as `CallValue`: push the supplied args
                // (bottom), then the callee (top). `BindValue` returns a new
                // function value rather than entering the target, so it never
                // produces localized output — no fragment wrapping needed.
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit_expr(callee, false);
                self.emit(
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a bind supplies <=255 args"
                    )]
                    Opcode::BindValue(args.len() as u8),
                );
            }

            // ── Collections (T1b) ────────────────────────────────────
            lir::ExprKind::ConstLiteral(v) => self.emit_literal_pool_push(v),

            #[expect(
                clippy::cast_possible_truncation,
                reason = "collection literals stay well under u32::MAX elements"
            )]
            lir::ExprKind::ArrayNew(elements) => {
                for e in elements {
                    self.emit_expr(e, false);
                }
                self.emit(Opcode::ArrayNew(elements.len() as u32));
            }

            #[expect(
                clippy::cast_possible_truncation,
                reason = "collection literals stay well under u32::MAX entries"
            )]
            lir::ExprKind::MapNew(entries) => {
                for (k, v) in entries {
                    self.emit_expr(k, false);
                    self.emit_expr(v, false);
                }
                self.emit(Opcode::MapNew(entries.len() as u32));
            }

            lir::ExprKind::Index { base, index } => {
                self.emit_expr(base, false);
                self.emit_expr(index, false);
                self.emit(Opcode::IndexGet);
            }

            lir::ExprKind::IndexSet { base, index, value } => {
                self.emit_expr(base, false);
                self.emit_expr(index, false);
                self.emit_expr(value, false);
                self.emit(Opcode::IndexSet);
            }

            lir::ExprKind::CollectionLen(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::CollectionLen);
            }

            lir::ExprKind::CollectionKeys(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::CollectionKeys);
            }

            lir::ExprKind::CollectionValues(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::CollectionValues);
            }

            lir::ExprKind::CollectionContains { container, needle } => {
                self.emit_expr(container, false);
                self.emit_expr(needle, false);
                self.emit(Opcode::MapContains);
            }

            lir::ExprKind::CollectionInsert { base, key, value } => {
                self.emit_expr(base, false);
                self.emit_expr(key, false);
                self.emit_expr(value, false);
                self.emit(Opcode::MapInsert);
            }

            lir::ExprKind::CollectionRemove { base, key } => {
                self.emit_expr(base, false);
                self.emit_expr(key, false);
                self.emit(Opcode::MapRemove);
            }

            lir::ExprKind::SeqRemoveAt { base, index } => {
                self.emit_expr(base, false);
                self.emit_expr(index, false);
                self.emit(Opcode::SeqRemoveAt);
            }

            lir::ExprKind::CharAt { s, index } => {
                self.emit_expr(s, false);
                self.emit_expr(index, false);
                self.emit(Opcode::CharAt);
            }

            // ── NS-A1: Option[T] + the ruled stdlib flips (#1107) ────
            lir::ExprKind::OptionNone => self.emit(Opcode::PushNone),

            lir::ExprKind::OptionSome(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::MakeSome);
            }

            // ── B1b: the `as` binding (issue #1475) ──────────────────
            // The bind is fused into the condition's own evaluation: push
            // the `Option[T]`, then one op both tests it and (on `some`)
            // writes the unwrapped payload to the binding's slot. `name`
            // is lowering-time provenance only — the slot is what the VM
            // addresses, exactly as for `GetTemp`/`SetTemp`.
            lir::ExprKind::OptionBind { value, slot, .. } => {
                self.emit_expr(value, false);
                self.emit(Opcode::OptionBind(*slot));
            }

            lir::ExprKind::StrFind { s, sub } => {
                self.emit_expr(s, false);
                self.emit_expr(sub, false);
                self.emit(Opcode::StrFind);
            }

            lir::ExprKind::SeqIndexOf { seq, needle } => {
                self.emit_expr(seq, false);
                self.emit_expr(needle, false);
                self.emit(Opcode::SeqIndexOf);
            }

            lir::ExprKind::SeqMin(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::SeqMin);
            }

            lir::ExprKind::SeqMax(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::SeqMax);
            }

            lir::ExprKind::SeqFirst(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::SeqFirst);
            }

            lir::ExprKind::SeqLast(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::SeqLast);
            }

            // `pop(a)`: the take → `SeqPop` → store-back bracket against
            // the receiver's root cell. `SeqPop` pushes the Option result
            // *under* the shrunk array, so the trailing store (which pops
            // the array) leaves the Option on top as the expression value.
            // Take/Set auto-deref temp-held pointers, so a `ref`-bound
            // param receiver writes through to its target cell for free.
            lir::ExprKind::SeqPop { root } => {
                match root {
                    lir::AssignTarget::Global(id) => self.emit(Opcode::TakeGlobal(*id)),
                    lir::AssignTarget::Temp(slot, _) => self.emit(Opcode::TakeTemp(*slot)),
                }
                self.emit(Opcode::SeqPop);
                match root {
                    lir::AssignTarget::Global(id) => self.emit(Opcode::SetGlobal(*id)),
                    lir::AssignTarget::Temp(slot, _) => self.emit(Opcode::SetTemp(*slot)),
                }
            }

            lir::ExprKind::MapGetOpt { map, key } => {
                self.emit_expr(map, false);
                self.emit_expr(key, false);
                self.emit(Opcode::MapGetOpt);
            }

            lir::ExprKind::MapContainsValue { map, value } => {
                self.emit_expr(map, false);
                self.emit_expr(value, false);
                self.emit(Opcode::MapContainsValue);
            }

            // ── NS-A6: the `std::rand` draw verbs (#1112) ────────────
            lir::ExprKind::RandFloat => self.emit(Opcode::RandFloat),

            lir::ExprKind::RandChance(p) => {
                self.emit_expr(p, false);
                self.emit(Opcode::RandChance);
            }

            lir::ExprKind::RandPick(coll) => {
                self.emit_expr(coll, false);
                self.emit(Opcode::RandPick);
            }

            lir::ExprKind::RandShuffle(arr) => {
                self.emit_expr(arr, false);
                self.emit(Opcode::RandShuffle);
            }

            // ── NS-A4: the ordering verbs (#1110, stdlib-spec §4b) ───
            lir::ExprKind::SeqSorted(arr) => {
                self.emit_expr(arr, false);
                self.emit(Opcode::SeqSorted);
            }

            lir::ExprKind::SeqSortedBy { seq, cmp } => {
                self.emit_expr(seq, false);
                self.emit_expr(cmp, false);
                self.emit(Opcode::SeqSortedBy);
            }

            // ── The fn-value verbs (#1679, stdlib-spec §4) ───────────
            // Operands in source order, callback last — the `SeqSortedBy`
            // stack shape, so the VM pops callback-first.
            lir::ExprKind::SeqMap { seq, f } => {
                self.emit_expr(seq, false);
                self.emit_expr(f, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::Map));
            }
            lir::ExprKind::SeqFilter { seq, pred } => {
                self.emit_expr(seq, false);
                self.emit_expr(pred, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::Filter));
            }
            lir::ExprKind::SeqFold { seq, init, f } => {
                self.emit_expr(seq, false);
                self.emit_expr(init, false);
                self.emit_expr(f, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::Fold));
            }
            // Slice 2 (issue #1679): `filter_map` stays pure (the same
            // stack shape as `map`/`filter`); `each`/`map_each` are the
            // effectful spellings — same codegen shape, the runtime op is
            // what changes their contract.
            lir::ExprKind::SeqFilterMap { seq, f } => {
                self.emit_expr(seq, false);
                self.emit_expr(f, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::FilterMap));
            }
            lir::ExprKind::SeqEach { seq, f } => {
                self.emit_expr(seq, false);
                self.emit_expr(f, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::Each));
            }
            lir::ExprKind::SeqMapEach { seq, f } => {
                self.emit_expr(seq, false);
                self.emit_expr(f, false);
                self.emit(Opcode::SeqVerb(SeqVerbOp::MapEach));
            }

            // ── NS-A5: range values (#1111) ──────────────────────────
            lir::ExprKind::RangeMake {
                start,
                end,
                inclusive,
            } => {
                self.emit_expr(start, false);
                self.emit_expr(end, false);
                self.emit(if *inclusive {
                    Opcode::RangeMakeIncl
                } else {
                    Opcode::RangeMakeExcl
                });
            }

            lir::ExprKind::RangeNonEmpty(r) => {
                self.emit_expr(r, false);
                self.emit(Opcode::RangeNonEmpty);
            }

            lir::ExprKind::MapClear(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::MapClear);
            }

            // ── NS-A8: the numeric tower (#1114) — args pushed
            // left-to-right, then the one family opcode with its kind
            // immediate. ─────────────────────────────────────────────
            // ── NS-A7 collections+ (issue #1113, `docs/stdlib-spec.md`
            // §8) ────────────────────────────────────────────────────────
            // `weighted(…)`: push the flattened pair row (weight then
            // value, construction order), gather it with `ArrayNew(2n)` (a
            // transient artifact the `WeightedNew` op immediately
            // consumes), then build the table.
            lir::ExprKind::WeightedNew { pairs } => {
                for (w, v) in pairs {
                    self.emit_expr(w, false);
                    self.emit_expr(v, false);
                }
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "pair count is bounded by source arity; 2n fits u32"
                )]
                self.emit(Opcode::ArrayNew(2 * pairs.len() as u32));
                self.emit(Opcode::Collect(brink_format::CollectOp::WeightedNew));
            }
            lir::ExprKind::RandRoll(table) => {
                self.emit_expr(table, false);
                self.emit(Opcode::Collect(brink_format::CollectOp::RandRoll));
            }
            lir::ExprKind::HeapPush { seq, value } => {
                self.emit_expr(seq, false);
                self.emit_expr(value, false);
                self.emit(Opcode::Collect(brink_format::CollectOp::HeapPush));
            }
            // `heap_pop(a)`: the take → `Collect(HeapPop)` → store-back
            // bracket against the receiver's root cell — `SeqPop`'s shape
            // exactly (the op pushes the Option *under* the re-heapified
            // array, so the trailing store leaves the Option on top as the
            // expression value).
            lir::ExprKind::HeapPop { root } => {
                match root {
                    lir::AssignTarget::Global(id) => self.emit(Opcode::TakeGlobal(*id)),
                    lir::AssignTarget::Temp(slot, _) => self.emit(Opcode::TakeTemp(*slot)),
                }
                self.emit(Opcode::Collect(brink_format::CollectOp::HeapPop));
                match root {
                    lir::AssignTarget::Global(id) => self.emit(Opcode::SetGlobal(*id)),
                    lir::AssignTarget::Temp(slot, _) => self.emit(Opcode::SetTemp(*slot)),
                }
            }
            lir::ExprKind::HeapPeek(seq) => {
                self.emit_expr(seq, false);
                self.emit(Opcode::Collect(brink_format::CollectOp::HeapPeek));
            }

            lir::ExprKind::Tower { op, args } => {
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit(Opcode::Tower(*op));
            }

            // ── Records (TM-4c) ──────────────────────────────────────
            lir::ExprKind::RecordNew {
                shape_id,
                fields,
                prelude,
            } => {
                // Stage every initializer in source order first (issue
                // #676) — each pop-then-store is stack-neutral, so this
                // adds no net stack growth before `fields` is pushed.
                for (slot, _name, expr) in prelude {
                    self.emit_expr(expr, false);
                    self.emit(Opcode::DeclareTemp(*slot));
                }
                for f in fields {
                    self.emit_expr(f, false);
                }
                self.emit(Opcode::RecordNew(*shape_id));
            }

            lir::ExprKind::RecordGet {
                base,
                field,
                static_offset,
            } => {
                self.emit_expr(base, false);
                if let Some(offset) = static_offset {
                    self.emit(Opcode::RecordGet(*offset));
                } else {
                    self.emit(Opcode::RecordGetDyn(field.0));
                }
            }

            lir::ExprKind::RecordSet {
                base,
                field,
                static_offset,
                value,
            } => {
                self.emit_expr(base, false);
                self.emit_expr(value, false);
                if let Some(offset) = static_offset {
                    self.emit(Opcode::RecordSet(*offset));
                } else {
                    self.emit(Opcode::RecordSetDyn(field.0));
                }
            }

            // ── Conversion intrinsics (TM-3 completion, #659) ─────────
            lir::ExprKind::ConvertInt(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::ConvertInt);
            }

            lir::ExprKind::ConvertFloat(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::ConvertFloat);
            }

            lir::ExprKind::ConvertString(inner) => {
                self.emit_expr(inner, false);
                self.emit(Opcode::ConvertString);
            }

            // Block capture (issue #1839): identical bracket to
            // `emit_slot_expr`'s call-composition case, holding an
            // arbitrary captured statement run instead of one call's
            // output — `emit_body` lowers each statement through the
            // normal per-statement path, so a recognized line inside stays
            // a real line-table entry.
            lir::ExprKind::Fragment(stmts) => {
                self.emit(Opcode::BeginFragment);
                self.emit_body(stmts);
                self.emit(Opcode::EndFragment);
            }
        }
    }

    /// Push a T1b constant collection literal via the literal pool
    /// (`PushLiteral(idx)`), deduplicating by structural equality against
    /// entries already in the pool (`docs/format-v4-rfc.md` §2).
    #[expect(
        clippy::cast_possible_truncation,
        reason = "literal pools stay well under u32::MAX entries"
    )]
    fn emit_literal_pool_push(&mut self, v: &lir::ConstValue) {
        let value = crate::const_to_value(v, self.state_name_table, self.state_name_index);
        let idx = self
            .literal_pool
            .iter()
            .position(|existing| *existing == value)
            .unwrap_or_else(|| {
                self.literal_pool.push(value);
                self.literal_pool.len() - 1
            });
        self.emit(Opcode::PushLiteral(idx as u32));
    }

    /// Emit a call opcode. The runtime no longer implicitly captures
    /// function output — the compiler emits explicit `BeginFragment`/
    /// `EndFragment` around calls when capture is needed (e.g. template
    /// slot composition in `emit_recognized_line`).
    fn emit_fragment_wrapped(&mut self, _display: bool, op: Opcode) {
        self.emit(op);
    }

    pub(super) fn emit_call_arg(&mut self, arg: &lir::CallArg) {
        match arg {
            lir::CallArg::Value(expr) => self.emit_expr(expr, false),
            lir::CallArg::RefGlobal(id) => self.emit(Opcode::PushVarPointer(*id)),
            lir::CallArg::RefTemp(slot, _) => self.emit(Opcode::PushTempPointer(*slot)),
            // T1e-2 (docs/t1e-spec.md §3): a real path-projection ref
            // argument — first emission of `MakeProjection`. Segment
            // expressions push in source order; the VM's `MakeProjection`
            // handler pops them (LIFO) into reverse-push order, then
            // reverses that collected `Vec` once to restore source order —
            // the same "push in order, pop-then-reverse" shape
            // `MakeClosure`'s bound-arg row already establishes.
            lir::CallArg::RefProjection { root, segments } => {
                for seg in segments {
                    self.emit_expr(seg, false);
                }
                self.emit(Opcode::MakeProjection {
                    root: *root,
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "a ref-argument path has far fewer than 255 segments"
                    )]
                    segment_count: segments.len() as u8,
                });
            }
        }
    }

    fn emit_string_expr(&mut self, s: &lir::StringExpr) {
        // Single literal → intern as PushString
        if s.parts.len() == 1
            && let lir::StringPart::Literal(text) = &s.parts[0]
        {
            // FG-4b: leave the operand symbolic; the link phase resolves it.
            self.emit_push_string(text);
            return;
        }

        // Mixed parts → BeginStringEval + parts + EndStringEval
        self.emit(Opcode::BeginStringEval);
        for part in &s.parts {
            match part {
                lir::StringPart::Literal(text) => {
                    // No location here, and genuinely not yet threadable
                    // (issue #3181): unlike `hir::Content::ptr` (the
                    // `content.rs:172` fix), `hir::StringPart::Literal`
                    // carries no span at all today — `hir::expr_span`'s own
                    // `Expr::String` arm unions only interpolation
                    // sub-expression spans, treating literal text as a
                    // "nothing to cover" leaf by design (`hir/spans.rs`).
                    // The raw token range *is* available one layer up, in
                    // `lower_string_lit` (each literal piece is walked off
                    // a real rowan token with its own `text_range()`), so
                    // this is a real, fixable gap — but fixing it means
                    // adding a provenance field to `StringExpr`/`StringPart`
                    // at both the HIR and LIR levels (mirroring the
                    // `Container`/`Stmt` work issue #3183 did), not a
                    // one-line thread-through here. Tracked as follow-up
                    // scope rather than folded into this fix.
                    let idx = self.add_line(text, None);
                    self.emit(Opcode::EmitLine(idx, 0));
                }
                lir::StringPart::Interpolation(expr) => {
                    self.emit_expr(expr, false);
                    self.emit(Opcode::EmitValue);
                }
            }
        }
        self.emit(Opcode::EndStringEval);
    }

    fn emit_builtin(&mut self, builtin: lir::BuiltinFn, args: &[lir::Expr]) {
        match builtin {
            lir::BuiltinFn::ChoiceCount => self.emit(Opcode::ChoiceCount),
            lir::BuiltinFn::Turns => self.emit(Opcode::TurnIndex),
            lir::BuiltinFn::TurnsSince => {
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit(Opcode::TurnsSince);
            }
            lir::BuiltinFn::ReadCount => {
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit(Opcode::VisitCount);
            }
            _ => {
                for arg in args {
                    self.emit_expr(arg, false);
                }
                self.emit(builtin_to_opcode(builtin));
            }
        }
    }
}

fn infix_op_to_opcode(op: brink_ir::InfixOp) -> Opcode {
    match op {
        brink_ir::InfixOp::Add => Opcode::Add,
        brink_ir::InfixOp::Sub => Opcode::Subtract,
        brink_ir::InfixOp::Mul => Opcode::Multiply,
        brink_ir::InfixOp::Div => Opcode::Divide,
        brink_ir::InfixOp::Mod => Opcode::Modulo,
        brink_ir::InfixOp::Intersect => Opcode::ListIntersect,
        brink_ir::InfixOp::Eq => Opcode::Equal,
        brink_ir::InfixOp::NotEq => Opcode::NotEqual,
        brink_ir::InfixOp::Lt => Opcode::Less,
        brink_ir::InfixOp::Gt => Opcode::Greater,
        brink_ir::InfixOp::LtEq => Opcode::LessOrEqual,
        brink_ir::InfixOp::GtEq => Opcode::GreaterOrEqual,
        brink_ir::InfixOp::And => Opcode::And,
        brink_ir::InfixOp::Or => Opcode::Or,
        brink_ir::InfixOp::Has => Opcode::ListContains,
        brink_ir::InfixOp::HasNot => Opcode::ListNotContains,
        // Structurally unreachable: `lir::lower::expr::lower_expr`
        // special-cases `InfixOp::Coalesce` into `lir::ExprKind::Coalesce`
        // (issue #1471's short-circuit branch) before it can ever become a
        // generic `lir::ExprKind::Infix` — the only shape that reaches this
        // function. See `lir::ExprKind::Coalesce`'s own doc.
        brink_ir::InfixOp::Coalesce => {
            unreachable!("InfixOp::Coalesce lowers to lir::ExprKind::Coalesce, never generic Infix")
        }
    }
}

fn builtin_to_opcode(b: lir::BuiltinFn) -> Opcode {
    match b {
        lir::BuiltinFn::TurnsSince => Opcode::TurnsSince,
        lir::BuiltinFn::ReadCount => Opcode::VisitCount,
        lir::BuiltinFn::ChoiceCount => Opcode::ChoiceCount,
        lir::BuiltinFn::Turns => Opcode::TurnIndex,
        lir::BuiltinFn::Random => Opcode::Random,
        lir::BuiltinFn::SeedRandom => Opcode::SeedRandom,
        lir::BuiltinFn::CastToInt => Opcode::CastToInt,
        lir::BuiltinFn::CastToFloat => Opcode::CastToFloat,
        lir::BuiltinFn::Floor => Opcode::Floor,
        lir::BuiltinFn::Ceiling => Opcode::Ceiling,
        lir::BuiltinFn::Pow => Opcode::Pow,
        lir::BuiltinFn::Min => Opcode::Min,
        lir::BuiltinFn::Max => Opcode::Max,
        lir::BuiltinFn::ListCount => Opcode::ListCount,
        lir::BuiltinFn::ListMin => Opcode::ListMin,
        lir::BuiltinFn::ListMax => Opcode::ListMax,
        lir::BuiltinFn::ListAll => Opcode::ListAll,
        lir::BuiltinFn::ListInvert => Opcode::ListInvert,
        lir::BuiltinFn::ListRange => Opcode::ListRange,
        lir::BuiltinFn::ListRandom => Opcode::ListRandom,
        lir::BuiltinFn::ListValue => Opcode::ListValue,
        lir::BuiltinFn::ListFromInt => Opcode::ListFromInt,
    }
}