miruscriptx 1.11.0

MiruScriptX: a complete, general-purpose scripting language written from scratch in Rust.
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
//! The bytecode compiler: it walks the AST and emits a [`Chunk`] for the VM.
//!
//! Compiling happens once per program, so the work of resolving names to slots,
//! laying out control flow as jumps, and folding each construct into
//! instructions is paid a single time rather than on every evaluation.

use std::rc::Rc;

use crate::ast::{BinaryOp, Expr, ExprKind, LogicalOp, Pattern, Stmt, StmtKind, UnaryOp};
use crate::chunk::{Chunk, OpCode};
use crate::globals::{Globals, ModuleId, ROOT_MODULE};
use crate::value::{CompiledFunction, Value};
use crate::MiruError;

/// The message for exceeding the local slot cap. Shared so the two places that
/// can hit it word it the same way.
const TOO_MANY_LOCALS: &str = "too many local variables in scope";

/// A local variable in scope during compilation, at a known stack slot (its
/// index in the list) and the block depth where it was declared. `captured`
/// records whether a nested function closes over it, so it is closed rather than
/// simply popped when its scope ends.
struct Local {
    name: String,
    depth: usize,
    captured: bool,
}

/// How a closure captures one upvalue: from a local of the immediately enclosing
/// function (`is_local`), or from that function's own upvalue. `index` is the
/// slot or upvalue index accordingly.
#[derive(Clone, Copy, PartialEq)]
struct UpvalueSpec {
    is_local: bool,
    index: u16,
}

/// A function whose compilation is paused while a nested function inside it is
/// compiled. The nested function may reach back into these to capture upvalues.
struct FunctionState {
    chunk: Chunk,
    locals: Vec<Local>,
    scope_depth: usize,
    loops: Vec<LoopContext>,
    upvalues: Vec<UpvalueSpec>,
}

/// Bookkeeping for the loop currently being compiled, so `break` and `continue`
/// know where to jump and how many locals to discard first.
struct LoopContext {
    /// Where `continue` jumps back to (the condition check).
    start: usize,
    /// The scope depth of the loop body; locals at or below it are popped when
    /// `break` or `continue` leaves the current iteration.
    body_depth: usize,
    /// Offsets of `break` jumps to patch to the loop's exit.
    breaks: Vec<usize>,
}

/// Compiles an AST into a [`Chunk`]. The fields describe the function currently
/// being compiled; `enclosing` holds the functions paused around it.
pub struct Compiler<'g> {
    /// The shared global table, so a name gets the same slot across the
    /// separately compiled inputs of a session.
    globals: &'g mut Globals,
    /// Which module's names this compilation resolves against.
    module: ModuleId,
    chunk: Chunk,
    /// 0 at the top level (where variables are globals), higher inside blocks.
    scope_depth: usize,
    /// Locals currently in scope, in stack order.
    locals: Vec<Local>,
    /// The stack of loops enclosing the code being compiled.
    loops: Vec<LoopContext>,
    /// The upvalues the current function captures.
    upvalues: Vec<UpvalueSpec>,
    /// Functions whose compilation is paused while this one is compiled.
    enclosing: Vec<FunctionState>,
    /// The module every function compiled here belongs to, or `None` at the top
    /// level of the file being run.
    file: Option<Rc<String>>,
}

impl<'g> Compiler<'g> {
    fn new(globals: &'g mut Globals, module: ModuleId) -> Compiler<'g> {
        Compiler {
            globals,
            module,
            chunk: Chunk::new(),
            scope_depth: 0,
            locals: Vec::new(),
            loops: Vec::new(),
            upvalues: Vec::new(),
            enclosing: Vec::new(),
            file: None,
        }
    }

    /// Compile a whole program into a script function whose chunk ends in a
    /// `Return`. The value the VM returns is that of the program's final
    /// expression, which is what the REPL echoes.
    ///
    /// Compiles into the root module. A module of its own is what an imported
    /// file gets, through [`Compiler::compile_module`].
    pub fn compile(
        program: &[Stmt],
        globals: &'g mut Globals,
    ) -> Result<Rc<CompiledFunction>, MiruError> {
        Compiler::compile_module(program, globals, ROOT_MODULE)
    }

    /// Compile a program whose global names resolve against `module`.
    ///
    /// Two modules can define the same name without colliding, because a slot
    /// is handed out per module rather than per name. Slots stay globally
    /// unique, so nothing about running the result changes: `GetGlobal` is the
    /// same indexed read either way.
    pub fn compile_module(
        program: &[Stmt],
        globals: &'g mut Globals,
        module: ModuleId,
    ) -> Result<Rc<CompiledFunction>, MiruError> {
        Compiler::compile_file(program, globals, module, None)
    }

    /// Compile a module, recording the path every function in it came from.
    ///
    /// The path rides on each [`CompiledFunction`] rather than being looked up
    /// later, because a module's functions outlive the import that created
    /// them and nothing else still knows where they were written.
    pub fn compile_file(
        program: &[Stmt],
        globals: &'g mut Globals,
        module: ModuleId,
        file: Option<Rc<String>>,
    ) -> Result<Rc<CompiledFunction>, MiruError> {
        let mut compiler = Compiler::new(globals, module);
        compiler.file = file;
        compiler.program(program)?;
        let (line, column) = program.last().map(|stmt| (stmt.line, 1)).unwrap_or((0, 0));
        compiler.chunk.write_op(OpCode::Return, line, column);
        Ok(Rc::new(CompiledFunction {
            name: None,
            arity: 0,
            chunk: compiler.chunk,
            file: compiler.file,
        }))
    }

    fn program(&mut self, program: &[Stmt]) -> Result<(), MiruError> {
        let Some((last, rest)) = program.split_last() else {
            self.chunk.write_op(OpCode::Nil, 0, 0);
            return Ok(());
        };
        for stmt in rest {
            self.statement(stmt)?;
        }
        // The program's value is that of a trailing expression, or nil otherwise.
        if let StmtKind::Expr(expr) = &last.kind {
            self.expression(expr)?;
        } else {
            self.statement(last)?;
            self.chunk.write_op(OpCode::Nil, last.line, 1);
        }
        Ok(())
    }

    /// Compile a statement for its side effects, leaving the stack unchanged.
    fn statement(&mut self, stmt: &Stmt) -> Result<(), MiruError> {
        match &stmt.kind {
            // Imports are resolved before compilation, by whoever holds the
            // file path, so by the time the compiler sees one the alias already
            // has its value and there is nothing left to emit. The compiler
            // knows nothing about files, which is why the error for a program
            // that has none is raised where the path would have been.
            StmtKind::Import { .. } => {}
            StmtKind::Expr(expr) => {
                self.expression(expr)?;
                self.chunk.write_op(OpCode::Pop, stmt.line, 1);
            }
            StmtKind::Let { pattern, value } => {
                // Compile the value first, so a right-hand reference to the same
                // name resolves to the outer binding, not the one being declared.
                self.expression(value)?;
                let as_global = self.scope_depth == 0;
                // A pattern that does not fit reports against the value that
                // does not fit it, so the caret lands under the array rather
                // than under the word `let`. A plain name keeps the position it
                // has always had, so no existing caret moves.
                let (line, column) = match pattern {
                    Pattern::Array(_) => (value.line, value.column),
                    Pattern::Name(_) => (stmt.line, 1),
                };
                self.bind_pattern(pattern, as_global, line, column)?;
            }
            StmtKind::CompoundAssign { target, op, value } => {
                self.compound_assign(target, *op, value)?;
            }
            StmtKind::Assign { target, value } => {
                self.expression(value)?;
                match &target.kind {
                    ExprKind::Identifier(name) => {
                        if let Some(slot) = self.resolve_local(name) {
                            self.local_access(
                                OpCode::SetLocal,
                                OpCode::SetLocalLong,
                                slot,
                                target.line,
                                target.column,
                            );
                        } else if let Some(upvalue) =
                            self.resolve_upvalue(name, target.line, target.column)?
                        {
                            self.chunk
                                .write_op(OpCode::SetUpvalue, target.line, target.column);
                            self.chunk.write(upvalue as u8, target.line, target.column);
                        } else {
                            self.named_global(OpCode::SetGlobal, name, target.line, target.column)?;
                        }
                    }
                    ExprKind::Index {
                        target: object,
                        index,
                    } => {
                        // The value is already on the stack; push the target and
                        // index above it, then store through them.
                        self.expression(object)?;
                        self.expression(index)?;
                        self.chunk
                            .write_op(OpCode::SetIndex, index.line, index.column);
                        self.chunk.write(0, object.line, object.column);
                    }
                    ExprKind::Field {
                        target: object,
                        name,
                    } => {
                        // The same shape as an index assignment, with the name
                        // as an ordinary constant so it is not capped at 256.
                        self.expression(object)?;
                        self.constant(
                            Value::Str(Rc::new(name.clone())),
                            target.line,
                            target.column,
                        )?;
                        self.chunk
                            .write_op(OpCode::SetField, target.line, target.column);
                        self.chunk.write(0, object.line, object.column);
                    }
                    _ => {
                        return Err(MiruError::with_column(
                            target.line,
                            target.column,
                            "the bytecode VM does not support this assignment yet",
                        ));
                    }
                }
            }
            StmtKind::If {
                condition,
                then_branch,
                else_branch,
            } => self.if_statement(condition, then_branch, else_branch.as_deref())?,
            StmtKind::While { condition, body } => self.while_statement(condition, body)?,
            StmtKind::For {
                name,
                value,
                iterable,
                body,
            } => self.for_statement(name, value.as_ref(), iterable, body)?,
            StmtKind::Break => self.break_statement(stmt.line)?,
            StmtKind::Continue => self.continue_statement(stmt.line)?,
            StmtKind::Return(value) => {
                match value {
                    Some(expr) => self.expression(expr)?,
                    None => self.chunk.write_op(OpCode::Nil, stmt.line, 1),
                }
                // Return unwinds the whole call frame, so locals need no cleanup.
                self.chunk.write_op(OpCode::Return, stmt.line, 1);
            }
            StmtKind::Function { name, params, body } => {
                self.function(Some(name), params, body, stmt.line, 1)?;
                if self.scope_depth == 0 {
                    self.named_global(OpCode::DefineGlobal, name, stmt.line, 1)?;
                } else {
                    self.declare_local(name, stmt.line)?;
                }
            }
        }
        Ok(())
    }

    /// Compile a function's parameters and body into a nested [`CompiledFunction`]
    /// and emit a `Closure` in the current chunk that builds it at runtime, along
    /// with the specs for capturing its upvalues.
    fn function(
        &mut self,
        name: Option<&str>,
        params: &[String],
        body: &[Stmt],
        line: usize,
        column: usize,
    ) -> Result<(), MiruError> {
        self.begin_function();
        // Inside a function, declarations are local; parameters take the first
        // slots (0..arity), where the call places the arguments.
        self.scope_depth = 1;
        for param in params {
            self.declare_local(param, line)?;
        }
        for stmt in body {
            self.statement(stmt)?;
        }
        // A function that runs off the end returns nil.
        self.chunk.write_op(OpCode::Nil, line, column);
        self.chunk.write_op(OpCode::Return, line, column);
        let (chunk, upvalues) = self.end_function();

        let function = Rc::new(CompiledFunction {
            name: name.map(str::to_string),
            arity: params.len(),
            chunk,
            // Every function in a module belongs to that module, however deeply
            // nested, so this is the compiler's one file rather than anything
            // tracked per function.
            file: self.file.clone(),
        });
        let index = u16::try_from(self.chunk.add_function(function))
            .map_err(|_| MiruError::with_column(line, column, "too many functions in one chunk"))?;
        self.chunk.write_op(OpCode::Closure, line, column);
        self.write_u16(index, line, column);
        self.chunk.write(upvalues.len() as u8, line, column);
        for upvalue in upvalues {
            self.chunk.write(u8::from(upvalue.is_local), line, column);
            self.write_u16(upvalue.index, line, column);
        }
        Ok(())
    }

    /// Pause the current function and start a fresh one for a nested function.
    fn begin_function(&mut self) {
        let suspended = FunctionState {
            chunk: std::mem::take(&mut self.chunk),
            locals: std::mem::take(&mut self.locals),
            scope_depth: self.scope_depth,
            loops: std::mem::take(&mut self.loops),
            upvalues: std::mem::take(&mut self.upvalues),
        };
        self.enclosing.push(suspended);
        self.scope_depth = 0;
    }

    /// Finish the current function, returning its chunk and captured upvalues, and
    /// restore the enclosing function's state.
    fn end_function(&mut self) -> (Chunk, Vec<UpvalueSpec>) {
        let chunk = std::mem::take(&mut self.chunk);
        let upvalues = std::mem::take(&mut self.upvalues);
        let restored = self.enclosing.pop().expect("an enclosing function");
        self.chunk = restored.chunk;
        self.locals = restored.locals;
        self.scope_depth = restored.scope_depth;
        self.loops = restored.loops;
        self.upvalues = restored.upvalues;
        (chunk, upvalues)
    }

    /// Resolve `name` as an upvalue of the current function, capturing it through
    /// any functions in between. Returns `None` when `name` is not a local of any
    /// enclosing function, so the caller falls back to a global.
    fn resolve_upvalue(
        &mut self,
        name: &str,
        line: usize,
        column: usize,
    ) -> Result<Option<u16>, MiruError> {
        let mut found = None;
        for level in (0..self.enclosing.len()).rev() {
            if let Some(slot) = local_slot(&self.enclosing[level].locals, name) {
                found = Some((level, slot));
                break;
            }
        }
        let (level, slot) = match found {
            Some(pair) => pair,
            None => return Ok(None),
        };
        self.enclosing[level].locals[slot as usize].captured = true;
        // The function just inside the declaring one captures its local; each
        // function deeper in captures the previous one's upvalue.
        let mut index = self.add_upvalue(level + 1, true, slot, line, column)?;
        for deeper in (level + 2)..=self.enclosing.len() {
            index = self.add_upvalue(deeper, false, index, line, column)?;
        }
        Ok(Some(index))
    }

    /// Add (or reuse) an upvalue at function `level`, where `level` equal to the
    /// number of enclosing functions means the current one.
    fn add_upvalue(
        &mut self,
        level: usize,
        is_local: bool,
        index: u16,
        line: usize,
        column: usize,
    ) -> Result<u16, MiruError> {
        let spec = UpvalueSpec { is_local, index };
        let upvalues = if level == self.enclosing.len() {
            &mut self.upvalues
        } else {
            &mut self.enclosing[level].upvalues
        };
        if let Some(position) = upvalues.iter().position(|existing| *existing == spec) {
            return Ok(position as u16);
        }
        // GetUpvalue and SetUpvalue address an upvalue with one byte, so 255 is
        // the most that can be addressed. Unlike a local slot, this cap is not
        // worth lifting: a function closing over 255 distinct variables is not a
        // program anyone writes, and the emission sites below rely on the cast
        // being lossless.
        if upvalues.len() >= u8::MAX as usize {
            return Err(MiruError::with_column(
                line,
                column,
                "too many captured variables in one function",
            ));
        }
        upvalues.push(spec);
        Ok((upvalues.len() - 1) as u16)
    }

    /// Compile `while cond { .. }`. The condition is re-checked at the top of each
    /// iteration; `Loop` jumps back to it, and `break` jumps past the whole loop.
    fn while_statement(&mut self, condition: &Expr, body: &[Stmt]) -> Result<(), MiruError> {
        let line = condition.line;
        let column = condition.column;
        let loop_start = self.chunk.code.len();
        self.expression(condition)?;
        let exit_jump = self.emit_jump(OpCode::JumpIfFalse, line, column);
        self.chunk.write_op(OpCode::Pop, line, column);
        self.begin_scope();
        self.loops.push(LoopContext {
            start: loop_start,
            body_depth: self.scope_depth,
            breaks: Vec::new(),
        });
        for stmt in body {
            self.statement(stmt)?;
        }
        let context = self.loops.pop().expect("loop context");
        let (end_line, end_column) = body.last().map(|s| (s.line, 1)).unwrap_or((line, column));
        self.end_scope(end_line, end_column);
        self.emit_loop(loop_start, line, column)?;
        self.patch_jump(exit_jump, line, column)?;
        self.chunk.write_op(OpCode::Pop, line, column);
        for break_jump in context.breaks {
            self.patch_jump(break_jump, line, column)?;
        }
        Ok(())
    }

    /// Compile `for name in iterable { .. }`. The iterable is snapshotted into a
    /// hidden local, a hidden index walks it, and each iteration binds `name` to
    /// the next element in a fresh per-iteration scope.
    ///
    /// With a `value` pattern the snapshot holds pairs instead, and each
    /// iteration binds both halves of the pair it is given.
    fn for_statement(
        &mut self,
        name: &Pattern,
        value: Option<&Pattern>,
        iterable: &Expr,
        body: &[Stmt],
    ) -> Result<(), MiruError> {
        let line = iterable.line;
        let column = iterable.column;
        self.begin_scope();
        // The snapshot and index are hidden locals whose names cannot be written
        // in source ('$' is not a valid identifier), so they never clash.
        self.expression(iterable)?;
        self.chunk.write_op(OpCode::IterSnapshot, line, column);
        // 1 asks the snapshot for pairs, which is what a second loop variable
        // walks. A map with one variable reaches the refusal in the VM.
        self.chunk.write(u8::from(value.is_some()), line, column);
        let seq_slot = u16::try_from(self.locals.len())
            .map_err(|_| MiruError::with_column(line, column, TOO_MANY_LOCALS))?;
        self.declare_local("$seq", line)?;
        self.constant(Value::Int(0), line, column)?;
        self.declare_local("$idx", line)?;

        let loop_start = self.chunk.code.len();
        self.chunk.write_op(OpCode::ForNext, line, column);
        self.write_u16(seq_slot, line, column);
        self.chunk.write(0xff, line, column);
        self.chunk.write(0xff, line, column);
        let exit_jump = self.chunk.code.len() - 2;

        // The loop variable and body share one fresh scope per iteration.
        self.begin_scope();
        match value {
            // One variable takes the element `ForNext` pushed.
            None => self.bind_pattern(name, false, line, column)?,
            // Two variables take it apart. `ForNext` pushed the pair, which
            // becomes a hidden local, and each half is read out of it with the
            // ordinary index opcode -- no new instruction, and the same code a
            // program would write by hand.
            Some(value) => {
                let pair_slot = u16::try_from(self.locals.len())
                    .map_err(|_| MiruError::with_column(line, column, TOO_MANY_LOCALS))?;
                self.declare_local("$pair", line)?;
                for (half, bound) in [(0i64, name), (1, value)] {
                    self.element_of(pair_slot, half, line, column)?;
                    self.bind_pattern(bound, false, line, column)?;
                }
            }
        }
        self.loops.push(LoopContext {
            start: loop_start,
            body_depth: self.scope_depth,
            breaks: Vec::new(),
        });
        for stmt in body {
            self.statement(stmt)?;
        }
        let context = self.loops.pop().expect("loop context");
        let (end_line, end_column) = body.last().map(|s| (s.line, 1)).unwrap_or((line, column));
        self.end_scope(end_line, end_column);
        self.emit_loop(loop_start, line, column)?;

        self.patch_jump(exit_jump, line, column)?;
        for break_jump in context.breaks {
            self.patch_jump(break_jump, line, column)?;
        }
        self.end_scope(line, column);
        Ok(())
    }

    /// Bind the value on top of the stack to a pattern.
    ///
    /// `as_global` decides what a name becomes, and is decided once by the
    /// statement rather than read from `scope_depth` on the way down: a
    /// bracketed pattern declares a hidden local for the array it takes apart,
    /// and a nested pattern must not become a local merely because one exists.
    ///
    /// A name at global scope is defined and the value popped. A name in a
    /// block becomes a local, whose storage is the stack slot the value already
    /// occupies.
    ///
    /// A bracketed pattern checks the array, keeps it as a hidden local, and
    /// reads each element out with [`OpCode::Index`] -- the same code a program
    /// would write by hand. Nesting needs nothing more, because the element it
    /// reads is on top of the stack, which is where this started.
    ///
    /// **The hidden local stays for the rest of the block**, exactly as a `for`
    /// loop's `$seq` and `$idx` do. It costs one stack slot and no instruction;
    /// removing it would mean moving every local declared after it. At global
    /// scope every name was popped by its `DefineGlobal`, so the array is back
    /// on top and is popped here instead.
    fn bind_pattern(
        &mut self,
        pattern: &Pattern,
        as_global: bool,
        line: usize,
        column: usize,
    ) -> Result<(), MiruError> {
        match pattern {
            Pattern::Name(name) if as_global => {
                self.named_global(OpCode::DefineGlobal, name, line, column)
            }
            Pattern::Name(name) => self.declare_local(name, line),
            Pattern::Array(items) => {
                let expected = u16::try_from(items.len()).map_err(|_| {
                    MiruError::with_column(line, column, "too many names in one pattern")
                })?;
                self.chunk.write_op(OpCode::CheckUnpack, line, column);
                self.write_u16(expected, line, column);
                let slot = u16::try_from(self.locals.len())
                    .map_err(|_| MiruError::with_column(line, column, TOO_MANY_LOCALS))?;
                self.declare_local("$pattern", line)?;
                for (index, item) in items.iter().enumerate() {
                    self.element_of(slot, index as i64, line, column)?;
                    self.bind_pattern(item, as_global, line, column)?;
                }
                if as_global {
                    self.chunk.write_op(OpCode::Pop, line, column);
                    self.locals.pop();
                }
                Ok(())
            }
        }
    }

    /// Push `local[index]`, where `local` holds an array.
    fn element_of(
        &mut self,
        slot: u16,
        index: i64,
        line: usize,
        column: usize,
    ) -> Result<(), MiruError> {
        self.local_access(OpCode::GetLocal, OpCode::GetLocalLong, slot, line, column);
        self.constant(Value::Int(index), line, column)?;
        self.chunk.write_op(OpCode::Index, line, column);
        self.chunk.write(0, line, column);
        Ok(())
    }

    fn break_statement(&mut self, line: usize) -> Result<(), MiruError> {
        let Some(body_depth) = self.loops.last().map(|context| context.body_depth) else {
            return Err(MiruError::with_column(line, 1, "break outside of a loop"));
        };
        self.pop_locals_to_depth(body_depth, line, 1);
        let jump = self.emit_jump(OpCode::Jump, line, 1);
        self.loops
            .last_mut()
            .expect("loop context")
            .breaks
            .push(jump);
        Ok(())
    }

    fn continue_statement(&mut self, line: usize) -> Result<(), MiruError> {
        let Some((start, body_depth)) = self
            .loops
            .last()
            .map(|context| (context.start, context.body_depth))
        else {
            return Err(MiruError::with_column(
                line,
                1,
                "continue outside of a loop",
            ));
        };
        self.pop_locals_to_depth(body_depth, line, 1);
        self.emit_loop(start, line, 1)
    }

    /// Discard each local at or deeper than `min_depth` (popping, or closing a
    /// captured one) without removing them from the compiler's list, since later
    /// code in the same scope still sees them. Used by `break` and `continue`,
    /// which jump over the normal end-of-scope cleanup.
    fn pop_locals_to_depth(&mut self, min_depth: usize, line: usize, column: usize) {
        let ops: Vec<OpCode> = self
            .locals
            .iter()
            .rev()
            .take_while(|local| local.depth >= min_depth)
            .map(|local| {
                if local.captured {
                    OpCode::CloseUpvalue
                } else {
                    OpCode::Pop
                }
            })
            .collect();
        for op in ops {
            self.chunk.write_op(op, line, column);
        }
    }

    /// Compile a block of statements in a nested scope, popping any locals it
    /// declares off the stack when the scope ends.
    fn block(&mut self, statements: &[Stmt]) -> Result<(), MiruError> {
        self.begin_scope();
        for stmt in statements {
            self.statement(stmt)?;
        }
        let (line, column) = statements
            .last()
            .map(|stmt| (stmt.line, 1))
            .unwrap_or((0, 0));
        self.end_scope(line, column);
        Ok(())
    }

    fn begin_scope(&mut self) {
        self.scope_depth += 1;
    }

    /// Leave the current scope. Each local it declared is popped, or closed as an
    /// upvalue first if a nested function captured it.
    fn end_scope(&mut self, line: usize, column: usize) {
        self.scope_depth -= 1;
        while matches!(self.locals.last(), Some(local) if local.depth > self.scope_depth) {
            let captured = self.locals.last().expect("a local").captured;
            let op = if captured {
                OpCode::CloseUpvalue
            } else {
                OpCode::Pop
            };
            self.chunk.write_op(op, line, column);
            self.locals.pop();
        }
    }

    /// Record a new local at the current scope depth. Its slot is its position in
    /// the list, which is where its value already sits on the stack.
    fn declare_local(&mut self, name: &str, line: usize) -> Result<(), MiruError> {
        if self.locals.len() > u16::MAX as usize {
            return Err(MiruError::with_column(line, 1, TOO_MANY_LOCALS));
        }
        self.locals.push(Local {
            name: name.to_string(),
            depth: self.scope_depth,
            captured: false,
        });
        Ok(())
    }

    /// Find a local variable's stack slot by name, searching innermost first.
    fn resolve_local(&self, name: &str) -> Option<u16> {
        local_slot(&self.locals, name)
    }

    /// Compile `if cond { .. } else { .. }`. The condition is left on the stack
    /// for `JumpIfFalse` to test, then discarded on whichever branch runs.
    fn if_statement(
        &mut self,
        condition: &Expr,
        then_branch: &[Stmt],
        else_branch: Option<&[Stmt]>,
    ) -> Result<(), MiruError> {
        let line = condition.line;
        let column = condition.column;
        self.expression(condition)?;
        let else_jump = self.emit_jump(OpCode::JumpIfFalse, line, column);
        self.chunk.write_op(OpCode::Pop, line, column);
        self.block(then_branch)?;
        let end_jump = self.emit_jump(OpCode::Jump, line, column);
        self.patch_jump(else_jump, line, column)?;
        self.chunk.write_op(OpCode::Pop, line, column);
        if let Some(else_branch) = else_branch {
            self.block(else_branch)?;
        }
        self.patch_jump(end_jump, line, column)?;
        Ok(())
    }

    fn expression(&mut self, expr: &Expr) -> Result<(), MiruError> {
        let line = expr.line;
        let column = expr.column;
        // An operator applied to literals is computed here rather than every
        // time the program runs. Only compound expressions are worth folding: a
        // bare literal already compiles to a single instruction.
        if matches!(expr.kind, ExprKind::Unary { .. } | ExprKind::Binary { .. }) {
            if let Some(value) = fold(expr) {
                return self.emit_value(value, line, column);
            }
        }
        match &expr.kind {
            // The statement form's shape, with the two `Pop`s that discard each
            // arm's value removed: here each arm is the value, and both paths
            // leave exactly one on the stack.
            ExprKind::If {
                condition,
                then_value,
                else_value,
            } => {
                self.expression(condition)?;
                let else_jump = self.emit_jump(OpCode::JumpIfFalse, line, column);
                self.chunk.write_op(OpCode::Pop, line, column);
                self.expression(then_value)?;
                let end_jump = self.emit_jump(OpCode::Jump, line, column);
                self.patch_jump(else_jump, line, column)?;
                self.chunk.write_op(OpCode::Pop, line, column);
                self.expression(else_value)?;
                self.patch_jump(end_jump, line, column)?;
            }
            ExprKind::Try(inner) => {
                // Both ways out leave exactly one value where this expression's
                // result belongs: EndTry keeps what the expression produced, and
                // an error lands here with the error already pushed. So they
                // converge on the next instruction and the success path needs no
                // jump over anything.
                let handler = self.emit_jump(OpCode::BeginTry, line, column);
                self.expression(inner)?;
                self.chunk.write_op(OpCode::EndTry, line, column);
                self.patch_jump(handler, line, column)?;
            }
            ExprKind::Int(n) => self.constant(Value::Int(*n), line, column)?,
            ExprKind::Float(f) => self.constant(Value::Float(*f), line, column)?,
            ExprKind::Str(s) => self.constant(Value::Str(Rc::new(s.clone())), line, column)?,
            ExprKind::Bool(true) => self.chunk.write_op(OpCode::True, line, column),
            ExprKind::Bool(false) => self.chunk.write_op(OpCode::False, line, column),
            ExprKind::Nil => self.chunk.write_op(OpCode::Nil, line, column),
            ExprKind::Array(elements) => {
                let count = u16::try_from(elements.len()).map_err(|_| {
                    MiruError::with_column(line, column, "array literal has too many elements")
                })?;
                for element in elements {
                    self.expression(element)?;
                }
                self.chunk.write_op(OpCode::Array, line, column);
                self.write_u16(count, line, column);
            }
            ExprKind::Map(entries) => {
                let count = u16::try_from(entries.len()).map_err(|_| {
                    MiruError::with_column(line, column, "map literal has too many entries")
                })?;
                for (key, value) in entries {
                    self.expression(key)?;
                    self.expression(value)?;
                }
                self.chunk.write_op(OpCode::Map, line, column);
                self.write_u16(count, line, column);
            }
            ExprKind::Field { target, name } => {
                self.expression(target)?;
                // The name is an ordinary constant rather than an operand, so a
                // file with many distinct field names gets ConstantLong instead
                // of a cap at 256.
                self.constant(Value::Str(Rc::new(name.clone())), line, column)?;
                // The opcode carries the field's position and its operand byte
                // the target's, so a missing field points at the name and
                // "cannot read a field" points at the thing that has none.
                self.chunk.write_op(OpCode::GetField, line, column);
                self.chunk.write(0, target.line, target.column);
            }
            ExprKind::Index { target, index } => {
                self.expression(target)?;
                self.expression(index)?;
                // The opcode carries the index's position and its operand byte
                // the target's, so each index error points at the part at fault.
                self.chunk.write_op(OpCode::Index, index.line, index.column);
                self.chunk.write(0, target.line, target.column);
            }
            ExprKind::Identifier(name) => {
                if let Some(slot) = self.resolve_local(name) {
                    self.local_access(OpCode::GetLocal, OpCode::GetLocalLong, slot, line, column);
                } else if let Some(upvalue) = self.resolve_upvalue(name, line, column)? {
                    self.chunk.write_op(OpCode::GetUpvalue, line, column);
                    self.chunk.write(upvalue as u8, line, column);
                } else {
                    self.named_global(OpCode::GetGlobal, name, line, column)?;
                }
            }
            ExprKind::Unary { op, operand } => {
                self.expression(operand)?;
                let opcode = match op {
                    UnaryOp::Negate => OpCode::Negate,
                    UnaryOp::Not => OpCode::Not,
                };
                self.chunk.write_op(opcode, line, column);
            }
            // Expanded here rather than in the parser, so `miru fmt` still
            // sees an f-string and prints one back. The expansion is the
            // parser's `fstring_expr`, which is the single place that decides
            // what an f-string means.
            ExprKind::FString(parts) => {
                let expanded = crate::parser::fstring_expr(parts, line, column);
                self.expression(&expanded)?;
            }
            ExprKind::Binary { op, left, right } => {
                self.expression(left)?;
                // A constant on the right is the shape most operators in real
                // code have: `i < 20000`, `x + 1`, `n * 2`. Folding has already
                // dealt with the case where both sides are known, so what is
                // left is a computed value against a fixed one. Carrying that
                // constant as an operand of the operator costs the same three
                // bytes as loading it separately, but is one instruction rather
                // than two and never puts it on the stack.
                // BinaryConst carries the index in one byte. Past that the pair
                // is emitted unfused rather than widening the instruction for
                // every program that never reaches so many constants.
                let fused = match fold(right).filter(fusable_operand) {
                    Some(value) => {
                        let index = self.constant_index(value, line, column)?;
                        u8::try_from(index).ok()
                    }
                    None => None,
                };
                match fused {
                    Some(index) => {
                        self.chunk.write_op(OpCode::BinaryConst, line, column);
                        self.chunk.write(binary_opcode(*op) as u8, line, column);
                        self.chunk.write(index, line, column);
                    }
                    None => {
                        self.expression(right)?;
                        self.chunk.write_op(binary_opcode(*op), line, column);
                    }
                }
            }
            ExprKind::Logical { op, left, right } => {
                // MiruScriptX's && and || yield a bool, and short-circuit: the
                // right side is skipped when the left already decides the result.
                self.expression(left)?;
                self.chunk.write_op(OpCode::Truthy, line, column);
                let short_circuit = match op {
                    LogicalOp::And => OpCode::JumpIfFalse,
                    LogicalOp::Or => OpCode::JumpIfTrue,
                };
                let jump = self.emit_jump(short_circuit, line, column);
                self.chunk.write_op(OpCode::Pop, line, column);
                self.expression(right)?;
                self.chunk.write_op(OpCode::Truthy, line, column);
                self.patch_jump(jump, line, column)?;
            }
            ExprKind::Call { callee, arguments } => {
                self.expression(callee)?;
                let argcount = u8::try_from(arguments.len())
                    .map_err(|_| MiruError::with_column(line, column, "too many call arguments"))?;
                for argument in arguments {
                    self.expression(argument)?;
                }
                self.chunk.write_op(OpCode::Call, line, column);
                self.chunk.write(argcount, line, column);
            }
            ExprKind::Function { params, body } => {
                self.function(None, params, body, line, column)?;
            }
        }
        Ok(())
    }

    /// Add a value to the constant pool, returning its one-byte index. A chunk
    /// holds at most 256 constants, since the index is a single byte.
    fn constant_index(
        &mut self,
        value: Value,
        line: usize,
        column: usize,
    ) -> Result<u16, MiruError> {
        let index = self.chunk.add_constant(value);
        u16::try_from(index)
            .map_err(|_| MiruError::with_column(line, column, "too many constants in one chunk"))
    }

    /// Emit a jump instruction with a placeholder operand, returning the offset
    /// of that operand so it can be patched once the target is known.
    fn emit_jump(&mut self, op: OpCode, line: usize, column: usize) -> usize {
        self.chunk.write_op(op, line, column);
        self.chunk.write(0xff, line, column);
        self.chunk.write(0xff, line, column);
        self.chunk.code.len() - 2
    }

    /// Fill in a jump emitted earlier so it lands at the current end of the code.
    ///
    /// The position is the construct the jump belongs to, so that overflowing a
    /// jump distance reports a place in the source rather than nothing at all.
    fn patch_jump(&mut self, operand: usize, line: usize, column: usize) -> Result<(), MiruError> {
        let distance = self.chunk.code.len() - (operand + 2);
        let distance = u16::try_from(distance).map_err(|_| {
            MiruError::with_column(line, column, "the compiled body is too large to jump over")
        })?;
        self.chunk.code[operand] = (distance >> 8) as u8;
        self.chunk.code[operand + 1] = (distance & 0xff) as u8;
        Ok(())
    }

    /// Emit a backward `Loop` jump to `target` (an earlier code offset).
    fn emit_loop(&mut self, target: usize, line: usize, column: usize) -> Result<(), MiruError> {
        self.chunk.write_op(OpCode::Loop, line, column);
        let distance = self.chunk.code.len() + 2 - target;
        let distance = u16::try_from(distance).map_err(|_| {
            MiruError::with_column(line, column, "the loop body is too large to compile")
        })?;
        self.chunk.write((distance >> 8) as u8, line, column);
        self.chunk.write((distance & 0xff) as u8, line, column);
        Ok(())
    }

    /// Push a known value using the cheapest encoding: `true`, `false`, and
    /// `nil` have dedicated single-byte opcodes, so folding to one of those must
    /// not turn it into a two-byte constant load.
    fn emit_value(&mut self, value: Value, line: usize, column: usize) -> Result<(), MiruError> {
        match value {
            Value::Bool(true) => self.chunk.write_op(OpCode::True, line, column),
            Value::Bool(false) => self.chunk.write_op(OpCode::False, line, column),
            Value::Nil => self.chunk.write_op(OpCode::Nil, line, column),
            other => self.constant(other, line, column)?,
        }
        Ok(())
    }

    /// Emit a `Constant` instruction that pushes `value`.
    /// Emit an instruction that pushes `value`.
    ///
    /// Loading a constant is one of the hottest instructions in the language, so
    /// the one-byte form is used wherever the index fits and the wide one only
    /// past that. A program with few constants, which is nearly all of them,
    /// emits exactly the bytecode it did before this existed.
    fn constant(&mut self, value: Value, line: usize, column: usize) -> Result<(), MiruError> {
        let index = self.constant_index(value, line, column)?;
        match u8::try_from(index) {
            Ok(short) => {
                self.chunk.write_op(OpCode::Constant, line, column);
                self.chunk.write(short, line, column);
            }
            Err(_) => {
                self.chunk.write_op(OpCode::ConstantLong, line, column);
                self.write_u16(index, line, column);
            }
        }
        Ok(())
    }

    /// Emit a global instruction (`DefineGlobal`, `GetGlobal`, or `SetGlobal`),
    /// resolving the name to its slot in the shared table. Resolving here rather
    /// than at run time is the point: the VM indexes instead of hashing.
    fn named_global(
        &mut self,
        op: OpCode,
        name: &str,
        line: usize,
        column: usize,
    ) -> Result<(), MiruError> {
        // A declaration introduces the module's own name even when a builtin
        // has that name; everything else resolves normally, which finds the
        // declaration if there was one and the builtin otherwise.
        let slot = if matches!(op, OpCode::DefineGlobal) {
            self.globals.slot_for_declaration(self.module, name)
        } else {
            self.globals.slot_for(self.module, name)
        }
        .ok_or_else(|| {
            MiruError::with_column(line, column, "too many global variables in one program")
        })?;
        self.chunk.write_op(op, line, column);
        self.write_u16(slot, line, column);
        Ok(())
    }

    /// Emit a local read or write, picking the short or wide encoding.
    ///
    /// Locals are the most frequently touched thing in a function body, so the
    /// one-byte form is used wherever the slot fits. A function with more than
    /// 256 locals in scope pays an extra byte on the ones past that, and no
    /// other function pays anything.
    fn local_access(&mut self, short: OpCode, long: OpCode, slot: u16, line: usize, column: usize) {
        match u8::try_from(slot) {
            Ok(slot) => {
                self.chunk.write_op(short, line, column);
                self.chunk.write(slot, line, column);
            }
            Err(_) => {
                self.chunk.write_op(long, line, column);
                self.write_u16(slot, line, column);
            }
        }
    }

    /// Write a two-byte big-endian operand, the encoding every wide operand in a
    /// chunk uses.
    fn write_u16(&mut self, value: u16, line: usize, column: usize) {
        self.chunk.write((value >> 8) as u8, line, column);
        self.chunk.write((value & 0xff) as u8, line, column);
    }
}

/// Try to evaluate an expression at compile time.
///
/// Returns `None` when the expression is not made only of literals, and also
/// when evaluating it *fails*. That second case matters: `1 / 0` and an
/// overflowing sum have to stay runtime errors reported at their own position,
/// so a fold that would raise is abandoned and the instructions are emitted as
/// usual, leaving the error to happen where it always did.
fn fold(expr: &Expr) -> Option<Value> {
    match &expr.kind {
        ExprKind::Int(n) => Some(Value::Int(*n)),
        ExprKind::Float(f) => Some(Value::Float(*f)),
        ExprKind::Str(s) => Some(Value::Str(Rc::new(s.clone()))),
        ExprKind::Bool(b) => Some(Value::Bool(*b)),
        ExprKind::Nil => Some(Value::Nil),
        ExprKind::Unary { op, operand } => crate::ops::unary(*op, fold(operand)?).ok(),
        ExprKind::Binary { op, left, right } => {
            crate::ops::binary(*op, fold(left)?, fold(right)?).ok()
        }
        _ => None,
    }
}

/// Whether a known right-hand value is worth folding into the operator.
///
/// `true`, `false`, and `nil` are not. They already load in a single byte with
/// no constant pool entry, so fusing them would trade a byte of code and one of
/// the 256 constant slots for the one dispatch it saves, on comparisons that are
/// rare next to arithmetic against a number.
fn fusable_operand(value: &Value) -> bool {
    matches!(value, Value::Int(_) | Value::Float(_) | Value::Str(_))
}

/// Find a local's stack slot by name in a scope, searching innermost first.
fn local_slot(locals: &[Local], name: &str) -> Option<u16> {
    locals
        .iter()
        .rposition(|local| local.name == name)
        .map(|slot| slot as u16)
}

impl Compiler<'_> {
    /// Compile `target op= value`.
    ///
    /// **The parts of the target are evaluated once**, which is the whole
    /// reason this is not rewritten into `target = target op value` in the
    /// parser. `a[next()] += 1` calls `next` a single time; the rewrite would
    /// call it to read and again to store, and put the element back in a slot
    /// the program never asked for.
    ///
    /// A name has no parts to evaluate, so it needs no care: read it, apply,
    /// write it back.
    ///
    /// An index and a field have the same shape as each other, because
    /// `GetField` and `SetField` take the name from the stack exactly as
    /// `Index` and `SetIndex` take the index. So both compile to one sequence,
    /// with `DupTwo` making the copies to read through and `Rot3` putting the
    /// result underneath the pair that stores it.
    fn compound_assign(
        &mut self,
        target: &Expr,
        op: BinaryOp,
        value: &Expr,
    ) -> Result<(), MiruError> {
        let (line, column) = (target.line, target.column);
        match &target.kind {
            ExprKind::Identifier(_) => {
                // Reading and writing a name are each a single instruction, so
                // the plain expression path gives the read and the assignment
                // path gives the write.
                self.expression(target)?;
                self.expression(value)?;
                self.chunk.write_op(binary_opcode(op), line, column);
                self.store_name(target)?;
            }
            ExprKind::Index {
                target: object,
                index,
            } => {
                self.expression(object)?;
                self.expression(index)?;
                self.chunk.write_op(OpCode::DupTwo, line, column);
                self.chunk.write_op(OpCode::Index, index.line, index.column);
                self.chunk.write(0, object.line, object.column);
                self.expression(value)?;
                self.chunk.write_op(binary_opcode(op), line, column);
                self.chunk.write_op(OpCode::Rot3, line, column);
                self.chunk
                    .write_op(OpCode::SetIndex, index.line, index.column);
                self.chunk.write(0, object.line, object.column);
            }
            ExprKind::Field {
                target: object,
                name,
            } => {
                self.expression(object)?;
                self.constant(Value::Str(Rc::new(name.clone())), line, column)?;
                self.chunk.write_op(OpCode::DupTwo, line, column);
                self.chunk.write_op(OpCode::GetField, line, column);
                self.chunk.write(0, object.line, object.column);
                self.expression(value)?;
                self.chunk.write_op(binary_opcode(op), line, column);
                self.chunk.write_op(OpCode::Rot3, line, column);
                self.chunk.write_op(OpCode::SetField, line, column);
                self.chunk.write(0, object.line, object.column);
            }
            _ => {
                return Err(MiruError::with_column(
                    line,
                    column,
                    "invalid assignment target (only variables, elements, and fields can be assigned to)",
                ));
            }
        }
        Ok(())
    }

    /// Emit the write half of an assignment to a name.
    fn store_name(&mut self, target: &Expr) -> Result<(), MiruError> {
        let ExprKind::Identifier(name) = &target.kind else {
            unreachable!("store_name is only called for an identifier target");
        };
        if let Some(slot) = self.resolve_local(name) {
            self.local_access(
                OpCode::SetLocal,
                OpCode::SetLocalLong,
                slot,
                target.line,
                target.column,
            );
        } else if let Some(upvalue) = self.resolve_upvalue(name, target.line, target.column)? {
            self.chunk
                .write_op(OpCode::SetUpvalue, target.line, target.column);
            self.chunk.write(upvalue as u8, target.line, target.column);
        } else {
            self.named_global(OpCode::SetGlobal, name, target.line, target.column)?;
        }
        Ok(())
    }
}

fn binary_opcode(op: BinaryOp) -> OpCode {
    match op {
        BinaryOp::Add => OpCode::Add,
        BinaryOp::Subtract => OpCode::Subtract,
        BinaryOp::Multiply => OpCode::Multiply,
        BinaryOp::Divide => OpCode::Divide,
        BinaryOp::Modulo => OpCode::Modulo,
        BinaryOp::Equal => OpCode::Equal,
        BinaryOp::NotEqual => OpCode::NotEqual,
        BinaryOp::Less => OpCode::Less,
        BinaryOp::Greater => OpCode::Greater,
        BinaryOp::LessEqual => OpCode::LessEqual,
        BinaryOp::GreaterEqual => OpCode::GreaterEqual,
    }
}