tclrs 0.2.0

Tcl as a fusevm frontend: a parser and compiler to fusevm::Chunk, with no bespoke VM or JIT
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
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
//! Lowering: [`parser::Script`] → `fusevm::Chunk`.
//!
//! Every command leaves exactly one value on the stack — its result — because
//! a Tcl script's value is the value of its last command, and command
//! substitution needs the same thing from a nested script. The compiler tracks
//! that depth statically, which is what lets `break` and `continue` unwind to a
//! balanced stack with a known number of pops instead of a runtime unwinder.
//!
//! Operations whose Tcl semantics differ from the VM's generic ones — integer
//! division and remainder floor toward negative infinity, `**` stays integral
//! for integral operands — are frontend extension ops rather than the VM's
//! `Div`/`Mod`/`Pow`, as fusevm's own documentation directs for frontends whose
//! arithmetic differs. Everything else lowers to native ops so the JIT can see
//! it.
//!
//! Loops are emitted rotated — entered at the test, closed by a conditional
//! backward branch — because that is the one shape fusevm's tracing JIT installs
//! a trace for. [`Compiler::rotated_loop`] is the single emitter every loop in
//! this crate goes through; `while`, `for`, `foreach` and `dict for` differ only
//! in what they hand it.

use fusevm::{ChunkBuilder, Op, Value};
use std::collections::{HashMap, HashSet};
use std::fmt;

use crate::assoc::{self, ArrayNames, Target};
use crate::expr::{self, BinOp, Expr, UnOp};
use crate::parser::{Command, Part, Script, Word};
use crate::procs::Signature;

/// Extension opcode ids owned by this frontend.
pub mod ext {
    pub const DIV: u16 = 0;
    pub const MOD: u16 = 1;
    pub const POW: u16 = 2;
    pub const IN: u16 = 3;
    pub const NI: u16 = 4;
    /// Convert a VM-native result into its Tcl value: booleans become 1 or 0,
    /// doubles take Tcl's formatting.
    pub const NORM: u16 = 5;
    /// `eval`: `[arg, …]` with the count in the inline operand → the value of
    /// the script they concatenate to. The only op whose operand is a script
    /// that is not known until it runs; the handler lives in
    /// [`crate::runtime`], which owns the state the script runs against.
    pub const EVAL: u16 = 6;

    // Procedures and control flow (`procs`, `control`).

    /// Pop a pattern and a subject and push 1 or 0. `arg` is 0 for `switch
    /// -exact` and 1 for `switch -glob`.
    pub const MATCH: u16 = 7;
    /// Raise the Tcl error whose message is on top of the stack.
    pub const ERROR: u16 = 8;
    /// Leave the `catch` region entered by [`ext_wide::CATCH`], having reached
    /// its end without an error.
    pub const CATCH_END: u16 = 9;

    // Coroutines (`coro`). Every one but [`CORO_INFO`] parks the VM with a
    // request the driver in [`crate::runtime`] services; see [`crate::coro`].

    /// `[arg …, name, command]` with `arg` actual arguments — create the
    /// coroutine `name` running `command`, and enter it.
    pub const CORO_CREATE: u16 = 10;
    /// `[arg …, name]` with `arg` actual arguments — resume the coroutine.
    pub const CORO_RESUME: u16 = 11;
    /// `[value]` — suspend this coroutine, handing `value` to its resumer.
    pub const CORO_YIELD: u16 = 12;
    /// `[name, arg …]` with `arg` actual arguments — suspend this coroutine and
    /// enter the coroutine `name`, which inherits this one's resumer.
    pub const CORO_YIELDTO: u16 = 13;
    /// `info coroutine`: the running coroutine's qualified name, or `""`.
    pub const CORO_INFO: u16 = 14;

    /// `[name, arg …]` with the count in the inline operand — call the function
    /// an inline `rust { ... }` block exported. Emitted only for a name
    /// [`crate::rust_ffi::is_exported`] answered for while compiling.
    pub const FFI_CALL: u16 = 63;

    /// Pop a value and push Tcl's boolean reading of it — 1 or 0 — or refuse it.
    /// `arg` is 0 for a condition and 1 for `!`, which differ in how they word
    /// the refusal. Emitted only where the value could be a string, so the
    /// arithmetic a condition is usually made of stays native and traceable;
    /// [`super::Compiler::yields_number`] is the test.
    pub const BOOL: u16 = 15;

    /// Where the list commands' ops begin. Everything at or above this id is
    /// dispatched to [`crate::cmd_list`]; the inline operand is the number of
    /// stack values the op consumes.
    pub const LIST_BASE: u16 = 16;
    pub const LIST: u16 = 16;
    pub const LLENGTH: u16 = 17;
    pub const LINDEX: u16 = 18;
    pub const LAPPEND: u16 = 19;
    pub const LRANGE: u16 = 20;
    pub const LREVERSE: u16 = 21;
    pub const LINSERT: u16 = 22;
    pub const LREPLACE: u16 = 23;
    pub const LSEARCH: u16 = 24;
    pub const LSORT: u16 = 25;
    pub const JOIN: u16 = 26;
    pub const SPLIT: u16 = 27;
    pub const CONCAT: u16 = 28;

    /// `foreach`'s four steps. `INIT` builds the loop state from the value
    /// lists, `MORE` asks whether an iteration remains, `TAKE` pushes one
    /// iteration's values, and `ADVANCE` moves to the next.
    pub const FOREACH_INIT: u16 = 29;
    pub const FOREACH_MORE: u16 = 30;
    pub const FOREACH_TAKE: u16 = 31;
    pub const FOREACH_ADVANCE: u16 = 32;
    // Associative data (`assoc`). The operand order in each comment is the
    // order the compiler pushes them, so the handler pops them in reverse.

    /// Where the associative commands' ops begin — array elements, `array`
    /// and `dict` — dispatched to [`crate::assoc`].
    pub const ASSOC_BASE: u16 = 64;
    /// `[name, value]` → `value`, refusing an array. `arg` 1 assigns instead of
    /// reading and leaves nothing behind.
    pub const SCALAR: u16 = ASSOC_BASE;
    /// `[name, index, slot]` → the element's value.
    pub const ELEM_GET: u16 = ASSOC_BASE + 1;
    /// `[name, index, value, slot]` → `value`, stored.
    pub const ELEM_SET: u16 = ASSOC_BASE + 2;
    /// `[name, index, increment, slot]` → the incremented element.
    pub const ELEM_INCR: u16 = ASSOC_BASE + 3;
    /// `[name, index, slot, complain]`, leaving nothing.
    pub const UNSET_ELEM: u16 = ASSOC_BASE + 4;
    /// `[name, slot, complain]`, leaving nothing.
    pub const UNSET_VAR: u16 = ASSOC_BASE + 5;
    /// `[slot]` → 1 when the variable holds an array.
    pub const ARR_EXISTS: u16 = ASSOC_BASE + 6;
    /// `[slot]` → the element count.
    pub const ARR_SIZE: u16 = ASSOC_BASE + 7;
    /// `[mode, pattern, given, slot]` → the matching element names, as a list.
    pub const ARR_NAMES: u16 = ASSOC_BASE + 8;
    /// `[mode, pattern, given, slot]` → matching name/value pairs, as a list.
    pub const ARR_GET: u16 = ASSOC_BASE + 9;
    /// `[mode, pattern, given, slot]` → `""`, having removed the matches.
    pub const ARR_UNSET: u16 = ASSOC_BASE + 10;
    /// `[name, list, slot]` → `""`, having merged the list into the array.
    pub const ARR_SET: u16 = ASSOC_BASE + 11;
    /// `[k, v, …, count]` → a dict.
    pub const DICT_CREATE: u16 = ASSOC_BASE + 12;
    /// `[dict, key, …, count]` → the value at the key path.
    pub const DICT_GET: u16 = ASSOC_BASE + 13;
    /// `[dict, key, …, count]` → 1 when the key path resolves.
    pub const DICT_EXISTS: u16 = ASSOC_BASE + 14;
    /// `[dict, key, …, count]` → the dict without those keys.
    pub const DICT_REMOVE: u16 = ASSOC_BASE + 15;
    /// `[dict, …, count]` → the dicts combined left to right.
    pub const DICT_MERGE: u16 = ASSOC_BASE + 16;
    /// `[dict, mode, pattern, given]` → the matching keys, as a list.
    pub const DICT_KEYS: u16 = ASSOC_BASE + 17;
    /// `[dict, mode, pattern, given]` → the matching values, as a list.
    pub const DICT_VALUES: u16 = ASSOC_BASE + 18;
    /// `[dict]` → the number of pairs.
    pub const DICT_SIZE: u16 = ASSOC_BASE + 19;
    /// `[name, current, key, …, value, count]` → the updated dict.
    pub const DICT_SET: u16 = ASSOC_BASE + 20;
    /// `[dict]` → a `Value::Array` of alternating keys and values, which
    /// `dict for` walks with the VM's own `ArrayLen` and `ArrayGet`.
    pub const DICT_PAIRS: u16 = ASSOC_BASE + 21;

    /// Where the string commands' ops begin — the `string` ensemble, `append`
    /// and `format` — dispatched to [`crate::cmd_string`], which names them.
    /// The inline operand is the number of stack values the op consumes.
    pub const STRING_BASE: u16 = 128;
}

/// Wide extension opcode ids, whose payload is a `usize` rather than a byte.
pub mod ext_wide {
    /// Enter a `catch` region. The payload is the op index of the region's
    /// error handler, which the driver in [`crate::runtime`] resumes at.
    pub const CATCH: u16 = 0;

    /// A command is about to run, and the payload is its line. Emitted only
    /// when [`super::Compiler::debug`] is set — a chunk compiled the ordinary
    /// way carries none of these, so nothing is paid for a debugger that is not
    /// attached.
    pub const DBG_LINE: u16 = 1;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileError {
    pub msg: String,
    pub line: usize,
}

impl fmt::Display for CompileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} (line {})", self.msg, self.line)
    }
}

impl std::error::Error for CompileError {}

/// Compile a parsed script into a chunk whose result is the script's value.
///
/// Two passes. Reading `$x` lowers to a bare `GetVar`, which cannot fail, but
/// reading a variable that holds an array must — and the `set a(i) v` that makes
/// it one may be compiled after the `$a` that reads it. The first pass records
/// every name used as an array; the second, knowing them, guards just those
/// names. Nothing else differs between the passes, so a script with no arrays
/// compiles exactly as it did before and pays nothing.
pub fn compile(script: &Script) -> Result<fusevm::Chunk, CompileError> {
    lower(script, false)
}

/// Lower a script with a line marker before every command, for the debug
/// adapter. The markers are the only difference: a debugger single-steps the
/// same bytecode a run executes, rather than a second lowering written for it.
pub fn compile_debug(script: &Script) -> Result<fusevm::Chunk, CompileError> {
    lower(script, true)
}

fn lower(script: &Script, debug: bool) -> Result<fusevm::Chunk, CompileError> {
    let first = Compiler::run(script, ArrayNames::new(), debug)?;
    let mut chunk = if first.seen_arrays.is_empty() {
        first.b.build()
    } else {
        Compiler::run(script, first.seen_arrays, debug)?.b.build()
    };
    // Tcl's integers are arbitrary-precision, and this frontend has no bignum:
    // an `i64` that overflows is an error, raised by the numeric hook. Native
    // codegen would wrap instead, so ask fusevm for the overflow-checked
    // lowering — `Add`/`Sub`/`Mul` stay native registers on the common path and
    // deopt into the hook when a result does not fit. Without this, the JIT and
    // the AOT compiler print -9223372036854775808 where the interpreter reports
    // "integer value too large to represent".
    chunk.int_overflow_deopt = true;
    Ok(chunk)
}

pub(crate) struct LoopCtx {
    /// Stack depth on entry, so an early exit knows how much to discard.
    pub(crate) depth: usize,
    /// `catch` regions open at the loop header. An exit from a deeper one
    /// would leave the driver's catch record behind, so it is refused.
    pub(crate) catch_depth: usize,
    pub(crate) breaks: Vec<usize>,
    pub(crate) continues: Vec<usize>,
}

/// The local variables of one procedure body.
///
/// A procedure's variables live in the call frame's slots, which fusevm
/// allocates per `Op::Call` — that is what keeps them off the globals and out
/// of a recursive call's way. Names listed by `global` are excluded and reach
/// the VM's global table through `Op::GetVar`/`Op::SetVar` instead.
#[derive(Default)]
pub(crate) struct Scope {
    pub locals: HashMap<String, u16>,
    pub globals: HashSet<String>,
    pub next_slot: u16,
}

pub(crate) struct Compiler {
    pub(crate) b: ChunkBuilder,
    pub(crate) depth: usize,
    pub(crate) loops: Vec<LoopCtx>,
    /// The line of the command being lowered, recorded against every op it
    /// emits so `--disasm` can attribute them. Inside a body this is relative to
    /// the body's own text, because a body is parsed as a script of its own.
    pub(crate) line: usize,
    /// The line of the script's own command that is being lowered — the line a
    /// failure is reported at. See [`Compiler::err`].
    pub(crate) command_line: usize,
    /// Names known to be used as arrays, from the previous pass.
    pub(crate) arrays: ArrayNames,
    /// Names found to be used as arrays during this pass.
    pub(crate) seen_arrays: ArrayNames,
    /// `Some` while compiling a procedure body.
    pub(crate) scope: Option<Scope>,
    /// Signatures of every procedure the script defines, keyed by name. The
    /// call site needs one to apply defaults and collect `args`.
    pub(crate) procs: HashMap<String, Signature>,
    /// Procedures whose body has been compiled, so a redefinition is caught.
    pub(crate) defined: HashSet<String>,
    /// Names the script's own `coroutine` commands create. A call to one of
    /// them resumes the coroutine instead of calling a procedure.
    pub(crate) coros: HashSet<String>,
    /// How many `catch` regions enclose the code being compiled.
    pub(crate) catch_depth: usize,
    /// How many re-parsed bodies enclose the code being compiled. Nonzero means
    /// the commands being lowered are numbered relative to a body's own text
    /// rather than to the script, so they must not move
    /// [`Compiler::command_line`].
    pub(crate) body_depth: usize,
    /// Whether the command being compiled is one of the script's own, rather
    /// than one inside a body or a command substitution.
    pub(crate) top_level: bool,
    /// Whether the command being compiled runs exactly once, at a position
    /// [`crate::coro::prescan`] also reaches: the script's own commands and the
    /// command substitutions inside them. A `coroutine` command may only appear
    /// there, since its name has to be known to every call site.
    pub(crate) static_ctx: bool,
    /// Emit a [`ext_wide::DBG_LINE`] marker before every command, which is what
    /// lets a debugger stop at one. Off for every ordinary compilation.
    pub(crate) debug: bool,
    /// How many command substitutions enclose the command being compiled. A
    /// debugger stops before a statement, and a substitution is part of one.
    pub(crate) subst_depth: usize,
}

impl Compiler {
    /// One compilation pass over the script, with the array names the previous
    /// pass discovered.
    fn run(script: &Script, arrays: ArrayNames, debug: bool) -> Result<Compiler, CompileError> {
        let mut c = Compiler {
            b: ChunkBuilder::new(),
            depth: 0,
            loops: Vec::new(),
            line: 1,
            command_line: 1,
            arrays,
            seen_arrays: ArrayNames::new(),
            scope: None,
            procs: HashMap::new(),
            defined: HashSet::new(),
            coros: HashSet::new(),
            catch_depth: 0,
            body_depth: 0,
            top_level: true,
            static_ctx: true,
            debug,
            subst_depth: 0,
        };
        // Signatures are collected before anything is emitted so a procedure
        // may call one that the script defines further down, which is legal in
        // Tcl as long as the call is not reached first.
        crate::procs::prescan(&mut c.procs, script);
        crate::coro::prescan(&mut c.coros, script);
        c.script_value(script)?;
        Ok(c)
    }

    pub(crate) fn emit(&mut self, op: Op, delta: i32) -> usize {
        let idx = self.b.emit(op, self.line as u32);
        self.depth = (self.depth as i32 + delta) as usize;
        idx
    }

    pub(crate) fn error<T>(&self, msg: impl Into<String>) -> Result<T, CompileError> {
        Err(self.err(msg))
    }

    /// A failure located where the reference interpreter locates one: at the
    /// script's own command, not at the position inside a body that a re-parse
    /// gave its own line numbers.
    ///
    /// A braced body is parsed as a script of its own, so its commands are
    /// numbered from 1 relative to the body's text — which is why an error
    /// inside `if {1} {f}` on line 3 used to be reported at line 1. tclsh's
    /// `(file "…" line N)` names the top-level command that was running
    /// (measured: `while {1} {\n incr\n}` reports `("while" body line 2)` for
    /// the position inside the body and `(file … line 1)` for the file), and
    /// that is the line this reports. [`Compiler::line`] keeps the per-op line
    /// the disassembler shows, so the two are tracked separately.
    pub(crate) fn err(&self, msg: impl Into<String>) -> CompileError {
        CompileError {
            msg: msg.into(),
            line: self.command_line,
        }
    }

    pub(crate) fn push_value(&mut self, v: Value) {
        let idx = self.b.add_constant(v);
        self.emit(Op::LoadConst(idx), 1);
    }

    pub(crate) fn push_empty(&mut self) {
        self.push_value(Value::Str(std::sync::Arc::new(String::new())));
    }

    /// Push a string constant verbatim, without the numeric canonicalisation
    /// [`Compiler::push_text`] applies. Operands the compiler synthesises — an
    /// option name, a variable name an op resolves at run time — go through
    /// here, since they are never numbers.
    pub(crate) fn push_str(&mut self, text: &str) {
        self.push_value(Value::Str(std::sync::Arc::new(text.to_string())));
    }

    /// Push a literal string as a value, canonicalising it the way a literal
    /// word is canonicalised.
    pub(crate) fn push_text(&mut self, text: &str) {
        let v = literal_value(text);
        self.push_value(v);
    }

    // ── variables ────────────────────────────────────────────────────────

    /// The frame slot holding `name`, allocating one if this is its first
    /// mention. `None` outside a procedure body, and for a name that `global`
    /// has bound to the global of the same name.
    fn slot_of(&mut self, name: &str) -> Option<u16> {
        let scope = self.scope.as_mut()?;
        if scope.globals.contains(name) {
            return None;
        }
        if let Some(slot) = scope.locals.get(name) {
            return Some(*slot);
        }
        let slot = scope.next_slot;
        scope.next_slot += 1;
        scope.locals.insert(name.to_string(), slot);
        Some(slot)
    }

    /// Whether `name` would resolve to a frame slot rather than to the VM's
    /// global table — true inside a procedure body for every name `global` has
    /// not bound. Unlike [`Compiler::slot_of`] this allocates nothing, so it is
    /// safe to ask about a name the emitted code may never touch.
    pub(crate) fn is_local(&self, name: &str) -> bool {
        self.scope
            .as_ref()
            .is_some_and(|s| !s.globals.contains(name))
    }

    /// Read a variable onto the stack.
    pub(crate) fn emit_get_var(&mut self, name: &str) {
        match self.slot_of(name) {
            Some(slot) => self.emit(Op::GetSlot(slot), 1),
            None => {
                let idx = self.b.add_name(name);
                self.emit(Op::GetVar(idx), 1)
            }
        };
    }

    /// Pop the top of the stack into a variable.
    pub(crate) fn emit_set_var(&mut self, name: &str) {
        match self.slot_of(name) {
            Some(slot) => self.emit(Op::SetSlot(slot), -1),
            None => {
                let idx = self.b.add_name(name);
                self.emit(Op::SetVar(idx), -1)
            }
        };
    }

    // ── scripts ──────────────────────────────────────────────────────────

    /// Emit a nested script — a body — for its value. Commands that may only
    /// appear at the script's own top level are refused inside one, and so are
    /// the ones that need a position the prescan reaches: a body may run any
    /// number of times, or not at all.
    pub(crate) fn nested_value(&mut self, script: &Script) -> Result<(), CompileError> {
        self.in_body(|c| c.script_value(script))
    }

    /// Emit a nested script for its effect, leaving the stack as it was found.
    pub(crate) fn nested_effect(&mut self, script: &Script) -> Result<(), CompileError> {
        self.in_body(|c| c.script_effect(script))
    }

    /// Run `emit` with the compiler inside a body: not the script's top level,
    /// not a position the prescan reaches, and numbered relative to the body's
    /// own text.
    fn in_body(
        &mut self,
        emit: impl FnOnce(&mut Self) -> Result<(), CompileError>,
    ) -> Result<(), CompileError> {
        let outer = std::mem::replace(&mut self.top_level, false);
        let outer_static = std::mem::replace(&mut self.static_ctx, false);
        self.body_depth += 1;
        let result = emit(self);
        self.body_depth -= 1;
        self.top_level = outer;
        self.static_ctx = outer_static;
        result
    }

    /// Emit a command substitution for its value. Unlike a body it runs exactly
    /// where it is written, once per evaluation of the command it belongs to,
    /// so a command the prescan needs to see may appear in one.
    fn subst_value(&mut self, script: &Script) -> Result<(), CompileError> {
        let outer = std::mem::replace(&mut self.top_level, false);
        // A command substitution is part of the command containing it, not a
        // command a debugger stops before: `set out [double 21]` is one step,
        // and its nested command carries the same line anyway.
        self.subst_depth += 1;
        let result = self.script_value(script);
        self.subst_depth -= 1;
        self.top_level = outer;
        result
    }

    /// Emit a script that leaves its value on the stack.
    pub(crate) fn script_value(&mut self, script: &Script) -> Result<(), CompileError> {
        if script.commands.is_empty() {
            self.push_empty();
            return Ok(());
        }
        for (i, cmd) in script.commands.iter().enumerate() {
            if i > 0 {
                self.emit(Op::Pop, -1);
            }
            self.command(cmd)?;
        }
        Ok(())
    }

    /// Emit a script for its effect, leaving the stack as it was found.
    pub(crate) fn script_effect(&mut self, script: &Script) -> Result<(), CompileError> {
        for cmd in &script.commands {
            self.command(cmd)?;
            self.emit(Op::Pop, -1);
        }
        Ok(())
    }

    // ── words ────────────────────────────────────────────────────────────

    /// Emit a word, leaving its value on the stack.
    pub(crate) fn word(&mut self, word: &Word) -> Result<(), CompileError> {
        if word.expand {
            return self.error("{*} argument expansion is not supported yet");
        }
        match word.parts.len() {
            0 => self.push_empty(),
            1 => self.part(&word.parts[0])?,
            _ => {
                self.part(&word.parts[0])?;
                for part in &word.parts[1..] {
                    self.part(part)?;
                    self.emit(Op::Concat, -1);
                }
            }
        }
        Ok(())
    }

    fn part(&mut self, part: &Part) -> Result<(), CompileError> {
        match part {
            Part::Lit(text) => {
                self.push_value(literal_value(text));
                Ok(())
            }
            Part::Var(name) => {
                self.scalar_get(name);
                Ok(())
            }
            Part::Elem { name, index } => self.elem_get(name, index),
            Part::Script(script) => self.subst_value(script),
        }
    }

    /// The literal text of a word, when the compiler needs it at compile time
    /// (a command name, a variable name, a braced body).
    pub(crate) fn literal_of<'w>(
        &self,
        word: &'w Word,
        what: &str,
    ) -> Result<&'w str, CompileError> {
        word.as_literal()
            .ok_or_else(|| self.err(format!("{what} must be a literal in this phase")))
    }

    /// What a variable-name word names. `a(i)` is an array element even though
    /// the parser hands it over as ordinary text — the parentheses are only
    /// syntax inside a `$` substitution, so the interpretation happens here.
    fn target_of(&self, word: &Word) -> Result<Target, CompileError> {
        assoc::target_of(word)
            .ok_or_else(|| self.err("variable name must be a literal in this phase".to_string()))
    }

    /// The plain name of a scalar variable, for the commands that take only
    /// one. An array element is refused here rather than silently treated as a
    /// variable whose name happens to contain parentheses.
    pub(crate) fn var_name_of(&self, word: &Word) -> Result<String, CompileError> {
        match self.target_of(word)? {
            Target::Scalar(name) => Ok(name),
            Target::Elem { .. } => self.error("this command does not take an array element yet"),
        }
    }

    // ── commands ─────────────────────────────────────────────────────────

    /// The command names [`Compiler::command`] matches before it consults
    /// `procs`. A procedure may not take one of these names: Tcl would let the
    /// definition replace the command, and here the built-in lowering would
    /// keep winning. The list commands are absent on purpose — they are
    /// dispatched after `procs`, so a procedure does replace one.
    pub const BUILTINS: &'static [&'static str] = &[
        "set",
        "eval",
        "puts",
        "expr",
        "incr",
        "if",
        "while",
        "for",
        "foreach",
        "switch",
        "string",
        "append",
        "format",
        "break",
        "continue",
        "proc",
        "return",
        "global",
        "catch",
        "error",
        "array",
        "dict",
        "unset",
        "coroutine",
        "yield",
        "yieldto",
        "info",
    ];

    fn command(&mut self, cmd: &Command) -> Result<(), CompileError> {
        self.line = cmd.line;
        // A command substitution is parsed from the script's own text, so its
        // commands carry absolute lines and may set this; a body is re-parsed
        // and carries lines of its own, so it may not. `top_level` is false in
        // both, which is why the two are told apart by `body_depth`.
        if self.body_depth == 0 {
            self.command_line = cmd.line;
        }
        // Before the command, so a stop reports the line about to run rather
        // than the one that just did. Emitted inside procedure bodies too,
        // which is what makes stepping work below the top level.
        if self.debug && self.subst_depth == 0 {
            self.emit(Op::ExtendedWide(ext_wide::DBG_LINE, cmd.line), 0);
        }
        let Some(first) = cmd.words.first() else {
            self.push_empty();
            return Ok(());
        };
        let name = self.literal_of(first, "command name")?.to_string();
        let args = &cmd.words[1..];

        match name.as_str() {
            "set" => self.cmd_set(args),
            "eval" => self.cmd_eval(args),
            "puts" => self.cmd_puts(args),
            "expr" => self.cmd_expr(args),
            "incr" => self.cmd_incr(args),
            "if" => self.cmd_if(args),
            "while" => self.cmd_while(args),
            "for" => self.cmd_for(args),
            "foreach" => self.cmd_foreach(args),
            "switch" => self.cmd_switch(args),
            "string" | "append" | "format" => self.cmd_string_family(&name, args),
            "break" => self.cmd_loop_exit(args, true),
            "continue" => self.cmd_loop_exit(args, false),
            "proc" => self.cmd_proc(args),
            "return" => self.cmd_return(args),
            "global" => self.cmd_global(args),
            "catch" => self.cmd_catch(args),
            "error" => self.cmd_error(args),
            "array" => self.cmd_array(args),
            "dict" => self.cmd_dict(args),
            "unset" => self.cmd_unset(args),
            "coroutine" => self.cmd_coroutine(args),
            "yield" => self.cmd_yield(args),
            "yieldto" => self.cmd_yieldto(args),
            "info" => self.cmd_info(args),
            // The command an inline `rust { ... }` block was rewritten into.
            name if name == crate::rust_ffi::COMPILE_COMMAND => self.cmd_rust_compile(args),
            // A coroutine's context command. Its name is refused to `proc`, so
            // there is never both a procedure and a coroutine to choose from.
            other if self.coros.contains(other) => self.call_coro(other, args),
            // A procedure the script defines shadows nothing built in: the
            // names above are refused to `proc` at its definition.
            other if self.procs.contains_key(other) => self.call_proc(other, args),
            // A function an inline `rust { ... }` block exported. Asked after
            // the procedures, so a Tcl procedure of the same name still wins —
            // a script's own definition is never shadowed by a library it
            // loaded.
            other if crate::rust_ffi::is_exported(other) => self.call_ffi(other, args),
            // The list commands own the tail of the dispatch, and report the
            // unknown-command error for anything no module claims.
            other => crate::cmd_list::compile(self, other, args),
        }
    }

    fn cmd_set(&mut self, args: &[Word]) -> Result<(), CompileError> {
        match args.len() {
            1 => match self.target_of(&args[0])? {
                Target::Scalar(name) => {
                    self.scalar_get(&name);
                    Ok(())
                }
                Target::Elem { name, index } => self.elem_get(&name, &index),
            },
            2 => match self.target_of(&args[0])? {
                Target::Scalar(name) => {
                    self.scalar_set_guard(&name);
                    self.word(&args[1])?;
                    // `set` yields the value it assigned.
                    self.emit(Op::Dup, 1);
                    self.emit_set_var(&name);
                    Ok(())
                }
                Target::Elem { name, index } => self.elem_set(&name, &index, &args[1]),
            },
            _ => self.error("wrong # args: should be \"set varName ?newValue?\""),
        }
    }

    /// `eval arg ?arg ...?`.
    ///
    /// Every other command's script is braced text this compiler can lower in
    /// place. `eval`'s is a value, so its arguments are compiled as ordinary
    /// words and the script they produce is compiled when the op runs — once
    /// per distinct text, since [`crate::cache`] keeps what it lowered.
    ///
    /// The nested script is a chunk of its own, and a chunk addresses variables
    /// through the interpreter's global table. A procedure's parameters and
    /// locals are frame slots instead, so a script compiled inside one could
    /// not see them: `eval` in a procedure body is refused rather than run
    /// against the wrong variables.
    fn cmd_eval(&mut self, args: &[Word]) -> Result<(), CompileError> {
        if args.is_empty() {
            return self.error("wrong # args: should be \"eval arg ?arg ...?\"");
        }
        if self.scope.is_some() {
            return self.error(
                "\"eval\" inside a procedure is not supported: the script it builds cannot \
                 reach the procedure's local variables",
            );
        }
        let count = u8::try_from(args.len())
            .map_err(|_| self.err("too many arguments for \"eval\"".to_string()))?;
        for arg in args {
            self.word(arg)?;
        }
        self.emit(Op::Extended(ext::EVAL, count), 1 - args.len() as i32);
        Ok(())
    }

    fn cmd_puts(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let (newline, value) = match args {
            [v] => (true, v),
            [flag, v] if flag.as_literal() == Some("-nonewline") => (false, v),
            _ => return self.error("wrong # args: should be \"puts ?-nonewline? string\""),
        };
        self.word(value)?;
        if newline {
            self.emit(Op::PrintLn(1), -1);
        } else {
            self.emit(Op::Print(1), -1);
        }
        self.push_empty();
        Ok(())
    }

    /// `expr` joins its arguments with spaces and evaluates the result. A single
    /// braced argument — the form that matters — is compiled straight from its
    /// text with no runtime parse.
    fn cmd_expr(&mut self, args: &[Word]) -> Result<(), CompileError> {
        if args.is_empty() {
            return self.error("wrong # args: should be \"expr arg ?arg ...?\"");
        }
        let mut text = String::new();
        for (i, w) in args.iter().enumerate() {
            let piece = self.literal_of(w, "expression")?;
            if i > 0 {
                text.push(' ');
            }
            text.push_str(piece);
        }
        let parsed = expr::parse(&text).map_err(|e| self.err(e.msg))?;
        self.expr(&parsed)?;
        self.emit(Op::Extended(ext::NORM, 0), 0);
        Ok(())
    }

    fn cmd_incr(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let (name, by) = match args {
            [n] => (n, None),
            [n, by] => (n, Some(by)),
            _ => return self.error("wrong # args: should be \"incr varName ?increment?\""),
        };
        // `incr` takes an integer, not an `expr` operand, and says so in its own
        // words. An increment the script wrote out is checked here, where the
        // check is free; see the note on the lowering below for the one it
        // cannot reach.
        if let Some(text) = by.and_then(|w| w.as_literal()) {
            if crate::runtime::tcl_int(&Value::Str(std::sync::Arc::new(text.to_string()))).is_err()
            {
                return self.error(format!(
                    "expected integer but got {}",
                    crate::runtime::named(text, 50)
                ));
            }
        }
        let name = match self.target_of(name)? {
            Target::Scalar(name) => name,
            Target::Elem { name, index } => return self.elem_incr(&name, &index, by),
        };
        self.scalar_get(&name);
        match by {
            Some(w) => self.word(w)?,
            None => {
                self.emit(Op::LoadInt(1), 1);
            }
        }
        // Native `Op::Add`, deliberately: an extension op here would put one
        // inside every loop that counts with `incr`, and fusevm's tracing tier
        // rejects `Op::Extended`, so `bench/counted_loop_proc.tcl` would stop
        // reaching native code. The cost is that a *variable* holding something
        // that is not an integer is refused by the numeric hook in `expr`'s
        // wording rather than `incr`'s — recorded in BUGS.md.
        self.emit(Op::Add, -1);
        self.emit(Op::Dup, 1);
        self.emit_set_var(&name);
        Ok(())
    }

    fn cmd_if(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let mut i = 0;
        let mut end_jumps = Vec::new();
        let branch_depth = self.depth;

        loop {
            let Some(cond) = args.get(i) else {
                return self.error("wrong # args: no expression after \"if\" argument");
            };
            self.expr_word(cond)?;
            let jump_false = self.emit(Op::JumpIfFalse(usize::MAX), -1);

            i += 1;
            if args.get(i).and_then(|w| w.as_literal()) == Some("then") {
                i += 1;
            }
            let Some(body) = args.get(i) else {
                return self.error("wrong # args: no script following \"if\" argument");
            };
            self.body(body)?;
            i += 1;

            end_jumps.push(self.emit(Op::Jump(usize::MAX), 0));
            let else_start = self.b.current_pos();
            self.b.patch_jump(jump_false, else_start);
            // Each branch is compiled at the same entry depth.
            self.depth = branch_depth;

            match args.get(i).and_then(|w| w.as_literal()) {
                Some("elseif") => {
                    i += 1;
                    continue;
                }
                Some("else") => {
                    i += 1;
                    let Some(body) = args.get(i) else {
                        return self.error("wrong # args: no script following \"else\" argument");
                    };
                    self.body(body)?;
                    i += 1;
                    break;
                }
                None if i == args.len() => {
                    // No else: the value of a taken-nowhere `if` is empty.
                    self.push_empty();
                    break;
                }
                Some(other) => {
                    return self.error(format!("expected \"elseif\" or \"else\", got \"{other}\""))
                }
                None => return self.error("non-literal clause after \"if\" body"),
            }
        }

        if i != args.len() {
            return self.error("wrong # args: extra arguments after \"if\" script");
        }
        let end = self.b.current_pos();
        for j in end_jumps {
            self.b.patch_jump(j, end);
        }
        Ok(())
    }

    fn cmd_while(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let [cond, body] = args else {
            return self.error("wrong # args: should be \"while test command\"");
        };
        let script = self.body_script(body)?;
        self.rotated_loop(
            |c| c.nested_effect(&script),
            |_| Ok(()),
            |c| c.expr_word(cond),
        )?;
        // A loop's own value is empty.
        self.push_empty();
        Ok(())
    }

    /// `foreach varList list ?varList list ...? body`.
    ///
    /// The loop's state — how far it has run and every variable's value for
    /// every iteration — is a single value carried on the stack beneath the
    /// body, so nothing is stashed in a variable the script could see. The
    /// iteration count is fixed before the first pass, as it is in the
    /// reference implementation: the longest list decides it, and shorter ones
    /// supply empty values once they run out.
    fn cmd_foreach(&mut self, args: &[Word]) -> Result<(), CompileError> {
        let Some((body, pairs)) = args.split_last() else {
            return self.error(
                "wrong # args: should be \"foreach varList list ?varList list ...? command\"",
            );
        };
        if pairs.is_empty() || pairs.len() % 2 != 0 {
            return self.error(
                "wrong # args: should be \"foreach varList list ?varList list ...? command\"",
            );
        }

        let mut names = Vec::new();
        for pair in pairs.chunks(2) {
            let text = self
                .literal_of(&pair[0], "foreach variable list")?
                .to_string();
            let vars = crate::list::split(&text).map_err(|msg| CompileError {
                msg,
                line: self.line,
            })?;
            if vars.is_empty() {
                return self.error("foreach varlist is empty");
            }
            let count = vars.len();
            for name in vars {
                if name.ends_with(')') && name.contains('(') {
                    return self.error("array variables are not supported yet");
                }
                names.push(name);
            }
            self.push_value(Value::Int(count as i64));
            self.word(&pair[1])?;
        }
        let lists = u8::try_from(pairs.len() / 2)
            .map_err(|_| self.err("too many lists for \"foreach\"".to_string()))?;
        let width = u8::try_from(names.len())
            .map_err(|_| self.err("too many variables for \"foreach\"".to_string()))?;
        self.emit(
            Op::Extended(ext::FOREACH_INIT, lists),
            1 - pairs.len() as i32,
        );

        // `MORE` and `TAKE` read the state where it lies instead of consuming
        // it, so there is no `Dup` here and no copy of the state per iteration.
        let script = self.body_script(body)?;
        let taken: Vec<String> = names.iter().rev().cloned().collect();
        self.rotated_loop(
            |c| {
                c.emit(Op::Extended(ext::FOREACH_TAKE, width), i32::from(width));
                for name in &taken {
                    c.emit_set_var(name);
                }
                c.nested_effect(&script)
            },
            |c| {
                c.emit(Op::Extended(ext::FOREACH_ADVANCE, 0), 0);
                Ok(())
            },
            |c| {
                c.emit(Op::Extended(ext::FOREACH_MORE, 0), 1);
                Ok(())
            },
        )?;
        self.emit(Op::Pop, -1);
        self.push_empty();
        Ok(())
    }

    fn cmd_loop_exit(&mut self, args: &[Word], is_break: bool) -> Result<(), CompileError> {
        let word = if is_break { "break" } else { "continue" };
        if !args.is_empty() {
            return self.error(format!("wrong # args: should be \"{word}\""));
        }
        let Some(ctx) = self.loops.last() else {
            return self.error(format!("invoked \"{word}\" outside of a loop"));
        };
        if ctx.catch_depth != self.catch_depth {
            // Tcl turns such an exit into the return code the enclosing
            // `catch` reports rather than letting it reach the loop, which
            // this frontend does not model.
            return self.error(format!(
                "\"{word}\" out of a \"catch\" script is not supported"
            ));
        }
        // Discard whatever this iteration pushed before jumping, so the exit
        // point sees the depth it was compiled for.
        let surplus = self.depth.saturating_sub(ctx.depth);
        for _ in 0..surplus {
            self.emit(Op::Pop, -1);
        }
        let jump = self.emit(Op::Jump(usize::MAX), 0);
        let ctx = self.loops.last_mut().expect("loop context");
        if is_break {
            ctx.breaks.push(jump);
        } else {
            ctx.continues.push(jump);
        }
        // The jump leaves; the value keeps the sequencer's arithmetic honest.
        self.push_empty();
        Ok(())
    }

    /// Emit a loop in the rotated — do-while — shape, which is the one shape
    /// fusevm's tracing JIT installs a trace for.
    ///
    /// ```text
    ///     Jump -> cond          ; enter at the test, so it still runs first
    ///   body:
    ///     <body>
    ///   step:
    ///     <step>
    ///   cond:
    ///     <cond>
    ///     JumpIfTrue -> body    ; conditional BACKWARD branch
    ///   end:
    /// ```
    ///
    /// fusevm's trace recorder arms at a backward branch and closes the
    /// recording when a branch lands back on the anchor. A `while`-shaped loop
    /// — a forward `JumpIfFalse` exit closed by an unconditional backward
    /// `Jump` — records an eligible op sequence that its trace compiler then
    /// declines, so the trace is aborted and nothing is ever installed. The
    /// rotated shape compiles. That is a fusevm property, reproducible against
    /// the same bytecode with no Tcl involved.
    ///
    /// `body` and `step` must leave the stack as they found it; `cond` must
    /// leave exactly one value, which the closing branch consumes. Because the
    /// next test is at the bottom, `continue` jumps to `step` and `break` to
    /// `end` — the loop's entry depth at both.
    pub(crate) fn rotated_loop<B, S, C>(
        &mut self,
        body: B,
        step: S,
        cond: C,
    ) -> Result<(), CompileError>
    where
        B: FnOnce(&mut Self) -> Result<(), CompileError>,
        S: FnOnce(&mut Self) -> Result<(), CompileError>,
        C: FnOnce(&mut Self) -> Result<(), CompileError>,
    {
        let entry = self.depth;
        let enter = self.emit(Op::Jump(usize::MAX), 0);
        let top = self.b.current_pos();

        self.loops.push(LoopCtx {
            depth: entry,
            catch_depth: self.catch_depth,
            breaks: Vec::new(),
            continues: Vec::new(),
        });
        // The step is compiled with the loop still open: `for(n)` gives a
        // `break` there the same meaning it has in the body.
        let emitted = body(self).and_then(|()| {
            let at = self.b.current_pos();
            step(self).map(|()| at)
        });
        let ctx = self.loops.pop().expect("loop context");
        let step_at = emitted?;

        let cond_at = self.b.current_pos();
        self.b.patch_jump(enter, cond_at);
        for j in ctx.continues {
            self.b.patch_jump(j, step_at);
        }
        // The body and the step are balanced, so the test is compiled at the
        // same depth the entry jump reached it with.
        debug_assert_eq!(self.depth, entry, "rotated loop body is unbalanced");
        cond(self)?;
        self.emit(Op::JumpIfTrue(top), -1);

        let end = self.b.current_pos();
        for j in ctx.breaks {
            self.b.patch_jump(j, end);
        }
        Ok(())
    }

    /// A control-flow body: braced text compiled in place.
    pub(crate) fn body(&mut self, word: &Word) -> Result<(), CompileError> {
        let script = self.body_script(word)?;
        self.nested_value(&script)
    }

    pub(crate) fn body_script(&mut self, word: &Word) -> Result<Script, CompileError> {
        let text = self.literal_of(word, "script body")?;
        crate::parser::parse(text).map_err(|e| self.err(e.msg))
    }

    /// A word used as a condition: its text is an expression, and its value has
    /// to be a Tcl boolean.
    pub(crate) fn expr_word(&mut self, word: &Word) -> Result<(), CompileError> {
        let text = self.literal_of(word, "condition")?.to_string();
        let parsed = expr::parse(&text).map_err(|e| self.err(e.msg))?;
        self.condition(&parsed)
    }

    /// Emit an expression whose value a branch will consume, as Tcl's rule for a
    /// condition rather than as the VM's truthiness: `if {"b"}` is
    /// `expected boolean value but got "b"`, not a taken branch.
    ///
    /// The conversion is an extension op, and an extension op inside a loop body
    /// makes the body ineligible for fusevm's tracing tier
    /// (`is_trace_op_allowed_at` rejects `Op::Extended`), so it is emitted only
    /// where it can change the answer — where the expression's value could be a
    /// string. An arithmetic or relational condition, which is what a counted
    /// loop's test is, already produces a number and keeps the loop traceable.
    pub(crate) fn condition(&mut self, e: &Expr) -> Result<(), CompileError> {
        self.expr(e)?;
        if !Self::yields_number(e) {
            self.emit(Op::Extended(ext::BOOL, 0), 0);
        }
        Ok(())
    }

    /// Whether this expression's value is necessarily a number, whatever the
    /// variables in it hold — which is what decides whether a condition needs
    /// [`ext::BOOL`] at all.
    ///
    /// Every operator lowers to an op that answers with an `Int`, a `Float` or a
    /// `Bool`; the exceptions are an operand that is substituted text
    /// ([`Expr::Subst`]) and unary `+`, which is the identity and so passes its
    /// operand's value straight through.
    fn yields_number(e: &Expr) -> bool {
        match e {
            Expr::Int(_) | Expr::Float(_) => true,
            Expr::Subst(_) => false,
            Expr::Unary(UnOp::Plus, operand) => Self::yields_number(operand),
            Expr::Unary(_, _) => true,
            Expr::Binary(_, _, _) => true,
            // Either arm may be the value, so both have to answer with a number.
            Expr::Ternary(_, then, other) => {
                Self::yields_number(then) && Self::yields_number(other)
            }
            // Refused when lowered; the answer here does not matter.
            Expr::Call(_, _) => true,
        }
    }

    // ── expressions ──────────────────────────────────────────────────────

    fn expr(&mut self, e: &Expr) -> Result<(), CompileError> {
        match e {
            Expr::Int(v) => {
                self.emit(Op::LoadInt(*v), 1);
                Ok(())
            }
            Expr::Float(v) => {
                self.emit(Op::LoadFloat(*v), 1);
                Ok(())
            }
            Expr::Subst(parts) => {
                let word = Word {
                    parts: parts.clone(),
                    ..Word::default()
                };
                self.word(&word)
            }
            // `!` wants a number or a boolean word, so a numeric operand is
            // `Op::LogNot` — whose truthiness agrees with Tcl's on every number
            // — and anything that could be a string goes through `ext::BOOL`.
            Expr::Unary(UnOp::Not, operand) if !Self::yields_number(operand) => {
                self.expr(operand)?;
                self.emit(Op::Extended(ext::BOOL, 1), 0);
                Ok(())
            }
            Expr::Unary(op, operand) => {
                self.expr(operand)?;
                match op {
                    UnOp::Neg => self.emit(Op::Negate, 0),
                    UnOp::Plus => 0, // identity, but still requires a number
                    UnOp::BitNot => self.emit(Op::BitNot, 0),
                    UnOp::Not => self.emit(Op::LogNot, 0),
                };
                Ok(())
            }
            Expr::Binary(BinOp::And, a, b) => self.short_circuit(a, b, false),
            Expr::Binary(BinOp::Or, a, b) => self.short_circuit(a, b, true),
            Expr::Binary(op, a, b) => {
                self.expr(a)?;
                self.expr(b)?;
                let native = match op {
                    BinOp::Add => Some(Op::Add),
                    BinOp::Sub => Some(Op::Sub),
                    BinOp::Mul => Some(Op::Mul),
                    BinOp::Shl => Some(Op::Shl),
                    BinOp::Shr => Some(Op::Shr),
                    BinOp::Lt => Some(Op::NumLt),
                    BinOp::Gt => Some(Op::NumGt),
                    BinOp::Le => Some(Op::NumLe),
                    BinOp::Ge => Some(Op::NumGe),
                    BinOp::Eq => Some(Op::NumEq),
                    BinOp::Ne => Some(Op::NumNe),
                    BinOp::StrLt => Some(Op::StrLt),
                    BinOp::StrGt => Some(Op::StrGt),
                    BinOp::StrLe => Some(Op::StrLe),
                    BinOp::StrGe => Some(Op::StrGe),
                    BinOp::StrEq => Some(Op::StrEq),
                    BinOp::StrNe => Some(Op::StrNe),
                    BinOp::BitAnd => Some(Op::BitAnd),
                    BinOp::BitOr => Some(Op::BitOr),
                    BinOp::BitXor => Some(Op::BitXor),
                    _ => None,
                };
                match native {
                    Some(op) => {
                        self.emit(op, -1);
                    }
                    None => {
                        let id = match op {
                            BinOp::Div => ext::DIV,
                            BinOp::Mod => ext::MOD,
                            BinOp::Pow => ext::POW,
                            BinOp::In => ext::IN,
                            BinOp::Ni => ext::NI,
                            _ => unreachable!("binary op {op:?} has no lowering"),
                        };
                        self.emit(Op::Extended(id, 2), -1);
                    }
                }
                Ok(())
            }
            Expr::Ternary(cond, then, other) => {
                self.condition(cond)?;
                let to_else = self.emit(Op::JumpIfFalse(usize::MAX), -1);
                let branch_depth = self.depth;
                self.expr(then)?;
                let to_end = self.emit(Op::Jump(usize::MAX), 0);
                let else_start = self.b.current_pos();
                self.b.patch_jump(to_else, else_start);
                self.depth = branch_depth;
                self.expr(other)?;
                let end = self.b.current_pos();
                self.b.patch_jump(to_end, end);
                Ok(())
            }
            Expr::Call(name, _) => {
                self.error(format!("math function \"{name}\" is not supported yet"))
            }
        }
    }

    /// `&&` and `||` evaluate their right operand only when the left does not
    /// decide the result.
    ///
    /// Both operands are conditions, so both are held to Tcl's boolean rule —
    /// and only the one that is evaluated is: `expr {0 && "b"}` is 0 in tclsh,
    /// not an error, because the left operand already decided it.
    fn short_circuit(&mut self, a: &Expr, b: &Expr, on_true: bool) -> Result<(), CompileError> {
        self.condition(a)?;
        let jump = if on_true {
            self.emit(Op::JumpIfTrueKeep(usize::MAX), 0)
        } else {
            self.emit(Op::JumpIfFalseKeep(usize::MAX), 0)
        };
        self.emit(Op::Pop, -1);
        self.condition(b)?;
        // Normalize both arms to a boolean, as Tcl's logical operators yield
        // 1 or 0 rather than the operand that decided the result.
        let end = self.b.current_pos();
        self.b.patch_jump(jump, end);
        self.emit(Op::Extended(ext::NORM, 1), 0);
        Ok(())
    }
}

/// A literal word's runtime value.
///
/// Tcl's first rule is that a value's string representation is what the script
/// wrote, so a literal is a string unless carrying it as a number cannot be
/// observed. That holds for an integer — `i64::to_string` is exactly the
/// spelling Tcl prints, and `05` fails the round-trip and stays a string — and
/// it does **not** hold for a double: a `Value::Float` reaching `puts` is
/// stringified by fusevm's `as_str_cow`, and only an `expr` result passes
/// through the `NORM` op that applies Tcl's formatting. `puts 3.0` printed `3`
/// for exactly that reason, so no literal is interned as a `Float`.
///
/// A double literal inside an `expr` still becomes `Op::LoadFloat`
/// ([`Compiler::expr`]), which is the arithmetic fast path this used to be
/// about; what it costs here is one parse of a literal double at run time.
pub(crate) fn literal_value(text: &str) -> Value {
    if let Ok(i) = text.parse::<i64>() {
        if i.to_string() == text {
            return Value::Int(i);
        }
    }
    Value::Str(std::sync::Arc::new(text.to_string()))
}