endbasic-core 0.13.0

The EndBASIC programming language - core
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
// EndBASIC
// Copyright 2026 Julio Merino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Virtual processor for EndBASIC execution.

use crate::ExprType;
use crate::Scope;
use crate::bytecode::{
    self, ErrorHandlerMode, ExitCode, Opcode, Register, TaggedRegisterRef, opcode_of,
};
use crate::image::Image;
use crate::mem::{ArrayData, ConstantDatum, DatumPtr, Heap, HeapDatum};
use crate::num::unchecked_usize_as_u8;
use crate::reader::LineCol;

/// Default max call stack.
const DEFAULT_MAX_CALL_STACK: usize = 4096;

const CALL_STACK_OVERFLOW_MSG: &str = "Out of call stack space";

/// Alias for the type representing a program address.
type Address = usize;

/// Internal representation of a `StopReason` that requires further annotation by the caller.
pub(super) enum InternalStopReason {
    /// Execution terminated due to an `END` instruction.
    End(ExitCode),

    /// Execution terminated due to natural fallthrough.
    Eof,

    /// Execution stopped due to an instruction-level exception.
    Exception(Address, String),

    /// Execution stopped due to an upcall that requires service from the caller.
    ///
    /// The fields are: upcall index, first argument register, and the PC of the UPCALL instruction.
    Upcall(u16, Register, Address),

    /// The fields are: upcall index, first argument register, and the PC of the UPCALLA instruction.
    UpcallAsync(u16, Register, Address),

    /// Execution stopped to yield control back to the caller.
    Yield,
}

/// Error handler configuration set by `ON ERROR`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ErrorHandler {
    /// Errors are not handled.
    None,

    /// Errors jump to a handler address.
    ///
    /// TODO(jmmv): Revisit how `active` is cleared once we implement the `RESUME` statement.
    /// For now, a jump handler must be explicitly re-armed with another `ON ERROR` statement
    /// after it handles an exception.
    Jump { active: bool, addr: Address },

    /// Errors resume execution at the next statement.
    ResumeNext,
}

/// Represents a call frame in the stack.
struct Frame {
    /// Program counter of the instruction that caused the call.
    old_pc: Address,

    /// Frame pointer of the previous frame.
    old_fp: usize,

    /// Register to store the return value of the call, if any.
    ret_reg: Option<Register>,
}

/// Custom implementation of checked integer additions for error reporting purposes.
#[inline(always)]
fn checked_add_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    lhs.checked_add(rhs).ok_or("Integer overflow")
}

/// Custom implementation of checked bitwise AND for error reporting purposes.
#[inline(always)]
fn checked_and_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    Ok(lhs & rhs)
}

/// Custom implementation of checked integer divisions for error reporting purposes.
#[inline(always)]
fn checked_div_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    if rhs == 0 { Err("Division by zero") } else { lhs.checked_div(rhs).ok_or("Integer underflow") }
}

/// Custom implementation of checked integer modulos for error reporting purposes.
#[inline(always)]
fn checked_mod_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    if rhs == 0 { Err("Modulo by zero") } else { lhs.checked_rem(rhs).ok_or("Integer underflow") }
}

/// Custom implementation of checked integer multiplications for error reporting purposes.
#[inline(always)]
fn checked_mul_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    lhs.checked_mul(rhs).ok_or("Integer overflow")
}

/// Custom implementation of checked bitwise OR for error reporting purposes.
#[inline(always)]
fn checked_or_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    Ok(lhs | rhs)
}

/// Custom implementation of checked integer powers for error reporting purposes.
#[inline(always)]
fn checked_pow_integer(lhs: i32, exp: u32) -> Result<i32, &'static str> {
    lhs.checked_pow(exp).ok_or("Integer overflow")
}

/// Custom implementation of checked left shift for error reporting purposes.
#[inline(always)]
fn checked_shl_integer(lhs: i32, rhs: i32) -> Result<i32, String> {
    match u32::try_from(rhs) {
        Err(_) => Err(format!("Number of bits to << ({}) must be positive", rhs)),
        Ok(bits) => Ok(lhs.checked_shl(bits).unwrap_or(0)),
    }
}

/// Custom implementation of checked right shift for error reporting purposes.
#[inline(always)]
fn checked_shr_integer(lhs: i32, rhs: i32) -> Result<i32, String> {
    match u32::try_from(rhs) {
        Err(_) => Err(format!("Number of bits to >> ({}) must be positive", rhs)),
        Ok(bits) => Ok(match lhs.checked_shr(bits) {
            Some(i) => i,
            None if lhs < 0 => -1,
            None => 0,
        }),
    }
}
/// Custom implementation of checked integer subtractions for error reporting purposes.
#[inline(always)]
fn checked_sub_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    lhs.checked_sub(rhs).ok_or("Integer underflow")
}

/// Custom implementation of checked bitwise XOR for error reporting purposes.
#[inline(always)]
fn checked_xor_integer(lhs: i32, rhs: i32) -> Result<i32, &'static str> {
    Ok(lhs ^ rhs)
}

/// Execution context for the virtual machine.
///
/// This roughly corresponds to the concept of a "processor", making the VM the container of
/// various objects and the context the representation of the execution.
pub(super) struct Context {
    /// Program counter.
    pc: Address,

    /// Frame pointer.  Contains the offset of the first local register for the current
    /// scope.
    fp: usize,

    /// Stop signal.  If set, indicates why the execution stopped during instruction processing.
    stop: Option<InternalStopReason>,

    /// Current error handler configuration.
    err_handler: ErrorHandler,

    /// Register values.  The first N registers hold global variables.  After those, we find
    /// the registers for all local variables and for all scopes.
    regs: Vec<u64>,

    /// Stack of call frames for tracking subroutine and function calls.
    call_stack: Vec<Frame>,

    /// Maximum number of frames the call stack can contain.
    max_call_stack: usize,

    /// Indicates whether execution should yield once we hit the next statement boundary.
    yield_pending: bool,
}

impl Default for Context {
    fn default() -> Self {
        Self::new(DEFAULT_MAX_CALL_STACK)
    }
}

impl Context {
    /// Creates a new execution context with the given call stack limit.
    pub(super) fn new(max_call_stack: usize) -> Self {
        Self {
            pc: 0,
            fp: usize::from(Register::MAX_GLOBAL),
            stop: None,
            err_handler: ErrorHandler::None,
            regs: vec![0; usize::from(Register::MAX)],
            call_stack: vec![],
            max_call_stack,
            yield_pending: false,
        }
    }
}

impl Context {
    /// Computes the absolute index in `regs` for `reg`.
    fn reg_index(&self, reg: Register) -> usize {
        let (is_global, index) = reg.to_parts();
        let mut index = usize::from(index);
        if !is_global {
            index += self.fp;
        }
        index
    }

    /// Gets the value of register `reg`.
    ///
    /// Panics if the register is invalid.
    fn get_reg(&self, reg: Register) -> u64 {
        let index = self.reg_index(reg);
        self.regs.get(index).copied().unwrap_or(0)
    }

    /// Sets the value of register `reg` to `value`.
    ///
    /// Panics if the register is invalid.
    fn set_reg(&mut self, reg: Register, value: u64) {
        let index = self.reg_index(reg);
        if index >= self.regs.len() {
            self.regs.resize(index + 1, 0);
        }
        self.regs[index] = value;
    }

    /// Sets the program counter to `pc`.
    pub(super) fn set_pc(&mut self, pc: Address) {
        self.pc = pc;
    }

    /// Returns the current error handler configuration.
    pub(super) fn error_handler(&self) -> ErrorHandler {
        self.err_handler
    }

    /// Clears the current error handler configuration.
    pub(super) fn clear_error_handler(&mut self) {
        self.err_handler = ErrorHandler::None;
    }

    /// Marks the current jump-based error handler as active.
    pub(super) fn set_error_handler_active(&mut self) {
        self.err_handler = match self.err_handler {
            ErrorHandler::Jump { active: false, addr } => ErrorHandler::Jump { active: true, addr },
            _ => unreachable!("Only inactive jump handlers can be activated"),
        };
    }

    /// Dereferences a pointer register as a string.
    fn deref_string<'b>(
        &self,
        reg: Register,
        constants: &'b [ConstantDatum],
        heap: &'b Heap,
    ) -> &'b str {
        let raw_addr = self.get_reg(reg);
        DatumPtr::from(raw_addr).resolve_string(constants, heap)
    }

    /// Returns the raw `u64` value stored in global register `index`.
    ///
    /// Used by the VM's `get_global_*` methods to read global variable values after execution.
    pub(super) fn get_global_reg_raw(&self, index: u8) -> u64 {
        self.regs[usize::from(index)]
    }

    /// Returns the raw `u64` value stored in program-scope register `index`.
    ///
    /// Program-scope variables live in local registers in the outer frame.  Their absolute
    /// positions in the register file start at `Register::MAX_GLOBAL`.
    pub(super) fn get_program_reg_raw(&self, index: u8) -> u64 {
        self.regs[usize::from(Register::MAX_GLOBAL) + usize::from(index)]
    }

    /// Resolves array subscripts and computes the flat index for `arr_reg` with subscripts read
    /// from registers starting at `first_sub_reg`.
    ///
    /// Returns `Some((heap_idx, flat_idx))` on success, or `None` if an exception was set.
    fn resolve_array_index(
        &mut self,
        arr_reg: Register,
        first_sub_reg: Register,
        heap: &Heap,
    ) -> Option<(usize, usize)> {
        let arr_ptr = DatumPtr::from(self.get_reg(arr_reg));
        let heap_idx = arr_ptr.heap_index();
        let array = match heap.get(heap_idx) {
            HeapDatum::Array(a) => a,
            _ => unreachable!("Register must point to an array"),
        };

        let ndims = array.dimensions.len();
        let (_, first_idx) = first_sub_reg.to_parts();
        let mut subscripts = Vec::with_capacity(ndims);
        for i in 0..unchecked_usize_as_u8(ndims) {
            let sub_reg = Register::local(first_idx + i).unwrap();
            subscripts.push(self.get_reg(sub_reg) as i32);
        }

        match array.flat_index(&subscripts) {
            Ok(flat_idx) => Some((heap_idx, flat_idx)),
            Err(e) => {
                self.set_exception(e);
                None
            }
        }
    }

    /// Registers that the instruction being processed threw an exception `message`.
    ///
    /// It's the responsibility of the execution loop to check for the presence of exceptions and
    /// to stop execution if needed.
    fn set_exception<S: Into<String>>(&mut self, message: S) {
        self.stop = Some(InternalStopReason::Exception(self.pc, message.into()));
    }

    fn push_frame(&mut self, frame: Frame) -> bool {
        if self.call_stack.len() >= self.max_call_stack {
            self.set_exception(CALL_STACK_OVERFLOW_MSG);
            false
        } else {
            self.call_stack.push(frame);
            true
        }
    }

    /// Constructs a `Scope` for an upcall with arguments starting at `reg`.
    ///
    /// When `is_function` is true, the first register slot is reserved for the return value and
    /// `arg_offset` is set to 1 so that `get_*` method indices are zero-based on the first
    /// argument.  When false, `arg_offset` is 0.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn upcall_scope<'a>(
        &'a mut self,
        reg: Register,
        is_function: bool,
        constants: &'a [ConstantDatum],
        heap: &'a mut Heap,
        arg_linecols: &'a [LineCol],
        last_error: &'a Option<(LineCol, String)>,
        data: &'a [Option<ConstantDatum>],
    ) -> Scope<'a> {
        let (is_global, index) = reg.to_parts();
        assert!(!is_global);
        let index = usize::from(index);

        Scope {
            regs: &mut self.regs,
            constants,
            heap,
            fp: self.fp + index,
            arg_offset: if is_function { 1 } else { 0 },
            arg_linecols,
            last_error,
            data,
        }
    }

    /// Resets all runtime state (registers, frame pointer, call stack, error handler,
    /// and program counter) to their initial values.
    ///
    /// This completely wipes execution context.  Callers that want to preserve the program counter
    /// (e.g. to continue executing the same image after resetting variables) must save and restore
    /// it themselves.
    pub(super) fn clear_runtime_state(&mut self) {
        self.pc = 0;
        self.regs.fill(0);
        self.fp = usize::from(Register::MAX_GLOBAL);
        self.stop = None;
        self.err_handler = ErrorHandler::None;
        self.call_stack.clear();
        self.yield_pending = false;
    }

    /// Starts or resumes execution of `image`.
    ///
    /// Panics if the processor state is out of sync with `image` or if the contents of `image`
    /// are invalid.  We assume that the image comes from the result of an in-process compilation
    /// (not stored bytecode) and that the compiler guarantees that the image is valid.
    pub(super) fn exec(&mut self, image: &Image, heap: &mut Heap) -> InternalStopReason {
        while self.stop.is_none() {
            if self.yield_pending && image.debug_info.instrs[self.pc].is_stmt_start {
                self.yield_pending = false;
                self.stop = Some(InternalStopReason::Yield);
                continue;
            }

            let instr = image.code[self.pc];

            match opcode_of(instr) {
                Opcode::AddDouble => self.do_add_double(instr),
                Opcode::AddInteger => self.do_add_integer(instr),
                Opcode::Alloc => self.do_alloc(instr, heap),
                Opcode::AllocArray => self.do_alloc_array(instr, heap),
                Opcode::BitwiseAnd => self.do_bitwise_and(instr),
                Opcode::BitwiseNot => self.do_bitwise_not(instr),
                Opcode::BitwiseOr => self.do_bitwise_or(instr),
                Opcode::BitwiseXor => self.do_bitwise_xor(instr),
                Opcode::Call => self.do_call(instr),
                Opcode::Concat => self.do_concat(instr, &image.constants, heap),
                Opcode::DivideDouble => self.do_divide_double(instr),
                Opcode::DivideInteger => self.do_divide_integer(instr),
                Opcode::DoubleToInteger => self.do_double_to_integer(instr),
                Opcode::EqualBoolean => self.do_equal_boolean(instr),
                Opcode::EqualDouble => self.do_equal_double(instr),
                Opcode::EqualInteger => self.do_equal_integer(instr),
                Opcode::EqualText => self.do_equal_text(instr, &image.constants, heap),
                Opcode::End => self.do_end(instr),
                Opcode::Eof => self.do_eof(instr),
                Opcode::Gosub => self.do_gosub(instr),
                Opcode::GreaterDouble => self.do_greater_double(instr),
                Opcode::GreaterEqualDouble => self.do_greater_equal_double(instr),
                Opcode::GreaterEqualInteger => self.do_greater_equal_integer(instr),
                Opcode::GreaterEqualText => {
                    self.do_greater_equal_text(instr, &image.constants, heap)
                }
                Opcode::GreaterInteger => self.do_greater_integer(instr),
                Opcode::GreaterText => self.do_greater_text(instr, &image.constants, heap),
                Opcode::IntegerToDouble => self.do_integer_to_double(instr),
                Opcode::Jump => self.do_jump(instr),
                Opcode::JumpIfFalse => self.do_jump_if_false(instr),
                Opcode::LessDouble => self.do_less_double(instr),
                Opcode::LessEqualDouble => self.do_less_equal_double(instr),
                Opcode::LessEqualInteger => self.do_less_equal_integer(instr),
                Opcode::LessEqualText => self.do_less_equal_text(instr, &image.constants, heap),
                Opcode::LessInteger => self.do_less_integer(instr),
                Opcode::LessText => self.do_less_text(instr, &image.constants, heap),
                Opcode::LoadArray => self.do_load_array(instr, heap),
                Opcode::LoadConstant => self.do_load_constant(instr, &image.constants),
                Opcode::LoadInteger => self.do_load_integer(instr),
                Opcode::LoadRegisterPointer => self.do_load_register_ptr(instr),
                Opcode::ModuloDouble => self.do_modulo_double(instr),
                Opcode::ModuloInteger => self.do_modulo_integer(instr),
                Opcode::Move => self.do_move(instr),
                Opcode::MultiplyDouble => self.do_multiply_double(instr),
                Opcode::MultiplyInteger => self.do_multiply_integer(instr),
                Opcode::NegateDouble => self.do_negate_double(instr),
                Opcode::NegateInteger => self.do_negate_integer(instr),
                Opcode::NotEqualBoolean => self.do_not_equal_boolean(instr),
                Opcode::NotEqualDouble => self.do_not_equal_double(instr),
                Opcode::NotEqualInteger => self.do_not_equal_integer(instr),
                Opcode::NotEqualText => self.do_not_equal_text(instr, &image.constants, heap),
                Opcode::Nop => self.do_nop(instr),
                Opcode::PowerDouble => self.do_power_double(instr),
                Opcode::PowerInteger => self.do_power_integer(instr),
                Opcode::Return => self.do_return(instr),
                Opcode::SetErrorHandler => self.do_set_error_handler(instr),
                Opcode::ShiftLeft => self.do_shift_left(instr),
                Opcode::ShiftRight => self.do_shift_right(instr),
                Opcode::StoreArray => self.do_store_array(instr, heap),
                Opcode::SubtractDouble => self.do_subtract_double(instr),
                Opcode::SubtractInteger => self.do_subtract_integer(instr),
                Opcode::Upcall => self.do_upcall(instr),
                Opcode::UpcallAsync => self.do_upcall_async(instr),
            }
        }
        self.stop.take().expect("The loop above can only exit when there is a stop reason")
    }
}

impl Context {
    /// Applies a binary double operation using `parse` to decode the instruction and `op` to
    /// compute the result.
    fn do_binary_double_op<F>(
        &mut self,
        instr: u32,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(f64, f64) -> f64,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = f64::from_bits(self.get_reg(src1));
        let rhs = f64::from_bits(self.get_reg(src2));
        self.set_reg(dest, op(lhs, rhs).to_bits());
        self.pc += 1;
    }

    /// Applies a binary double predicate using `parse` to decode the instruction and `op` to
    /// compute the result.
    fn do_binary_double_predicate_op<F>(
        &mut self,
        instr: u32,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(f64, f64) -> bool,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = f64::from_bits(self.get_reg(src1));
        let rhs = f64::from_bits(self.get_reg(src2));
        self.set_reg(dest, if op(lhs, rhs) { 1 } else { 0 });
        self.pc += 1;
    }

    /// Applies a binary integer operation using `parse` to decode the instruction and `op` to
    /// compute the result.  `op` returns `Err` with a message on failure.
    fn do_binary_integer_op<F, E>(
        &mut self,
        instr: u32,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(i32, i32) -> Result<i32, E>,
        E: ToString,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = self.get_reg(src1) as i32;
        let rhs = self.get_reg(src2) as i32;
        match op(lhs, rhs) {
            Ok(result) => {
                self.set_reg(dest, result as u64);
                self.pc += 1;
            }
            Err(msg) => {
                self.set_exception(msg.to_string());
            }
        }
    }

    /// Applies a binary integer predicate using `parse` to decode the instruction and `op` to
    /// compute the result.
    fn do_binary_integer_predicate_op<F>(
        &mut self,
        instr: u32,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(i32, i32) -> bool,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = self.get_reg(src1) as i32;
        let rhs = self.get_reg(src2) as i32;
        self.set_reg(dest, if op(lhs, rhs) { 1 } else { 0 });
        self.pc += 1;
    }

    /// Applies a binary boolean operation using `parse` to decode the instruction and `op` to
    /// compute the result.
    fn do_binary_boolean_op<F>(
        &mut self,
        instr: u32,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(bool, bool) -> bool,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = self.get_reg(src1) != 0;
        let rhs = self.get_reg(src2) != 0;
        self.set_reg(dest, if op(lhs, rhs) { 1 } else { 0 });
        self.pc += 1;
    }

    /// Applies a binary text operation using `parse` to decode the instruction and `op` to
    /// compute the result.
    fn do_binary_text_op<F>(
        &mut self,
        instr: u32,
        constants: &[ConstantDatum],
        heap: &Heap,
        parse: fn(u32) -> (Register, Register, Register),
        op: F,
    ) where
        F: Fn(&str, &str) -> bool,
    {
        let (dest, src1, src2) = parse(instr);
        let lhs = self.deref_string(src1, constants, heap);
        let rhs = self.deref_string(src2, constants, heap);
        self.set_reg(dest, if op(lhs, rhs) { 1 } else { 0 });
        self.pc += 1;
    }

    /// Implements the `AddDouble` opcode.
    pub(super) fn do_add_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_add_double, |l, r| l + r);
    }

    /// Implements the `AddInteger` opcode.
    pub(super) fn do_add_integer(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_add_integer, checked_add_integer);
    }

    /// Implements the `Alloc` opcode.
    pub(super) fn do_alloc(&mut self, instr: u32, heap: &mut Heap) {
        let (dest, etype) = bytecode::parse_alloc(instr);
        debug_assert_eq!(ExprType::Text, etype, "Alloc is only emitted for strings right now");
        self.set_reg(dest, heap.empty_text_ptr());
        self.pc += 1;
    }

    /// Implements the `AllocArray` opcode.
    pub(super) fn do_alloc_array(&mut self, instr: u32, heap: &mut Heap) {
        let (dest, packed, first_dim_reg) = bytecode::parse_alloc_array(instr);
        let subtype = packed.subtype();
        let ndims = usize::from(packed.ndims());

        let (_, first_idx) = first_dim_reg.to_parts();
        let mut dimensions = Vec::with_capacity(ndims);
        let mut total: usize = 1;
        for i in 0..ndims {
            let dim_reg = Register::local(first_idx + i as u8).unwrap();
            let dim = match usize::try_from(self.get_reg(dim_reg) as i32) {
                Ok(0) | Err(_) => {
                    self.set_exception(format!("Dimension {} must be positive", i));
                    return;
                }
                Ok(n) => n,
            };
            dimensions.push(dim);
            total *= dim;
        }

        let values = match subtype {
            ExprType::Boolean | ExprType::Double | ExprType::Integer => {
                vec![0; total]
            }
            ExprType::Text => vec![heap.empty_text_ptr(); total],
        };
        let array = ArrayData { dimensions, values };
        let ptr = match heap.push(HeapDatum::Array(array)) {
            Ok(ptr) => ptr,
            Err(e) => {
                self.set_exception(e.to_string());
                return;
            }
        };
        self.set_reg(dest, ptr);
        self.pc += 1;
    }

    /// Implements the `BitwiseAnd` opcode.
    pub(super) fn do_bitwise_and(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_bitwise_and, checked_and_integer);
    }

    /// Implements the `BitwiseNot` opcode.
    pub(super) fn do_bitwise_not(&mut self, instr: u32) {
        let reg = bytecode::parse_bitwise_not(instr);
        let value = self.get_reg(reg) as i32;
        self.set_reg(reg, (!value) as u64);
        self.pc += 1;
    }

    /// Implements the `BitwiseOr` opcode.
    pub(super) fn do_bitwise_or(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_bitwise_or, checked_or_integer);
    }

    /// Implements the `BitwiseXor` opcode.
    pub(super) fn do_bitwise_xor(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_bitwise_xor, checked_xor_integer);
    }

    /// Implements the `Call` opcode.
    pub(super) fn do_call(&mut self, instr: u32) {
        let (reg, offset) = bytecode::parse_call(instr);
        if !self.push_frame(Frame { old_pc: self.pc, old_fp: self.fp, ret_reg: Some(reg) }) {
            return;
        }
        self.pc = Address::from(offset);
        let (is_global, index) = reg.to_parts();
        debug_assert!(!is_global, "Function results are always stored to a temp register");
        self.fp += usize::from(index);
    }

    /// Implements the `Concat` opcode.
    pub(super) fn do_concat(&mut self, instr: u32, constants: &[ConstantDatum], heap: &mut Heap) {
        let (dest, src1, src2) = bytecode::parse_concat(instr);
        let lhs = self.deref_string(src1, constants, heap).to_owned();
        let rhs = self.deref_string(src2, constants, heap);
        let result = lhs + rhs;
        let ptr = match heap.push(HeapDatum::Text(result)) {
            Ok(ptr) => ptr,
            Err(e) => {
                self.set_exception(e.to_string());
                return;
            }
        };
        self.set_reg(dest, ptr);
        self.pc += 1;
    }

    /// Implements the `DivideDouble` opcode.
    pub(super) fn do_divide_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_divide_double, |l, r| l / r);
    }

    /// Implements the `DivideInteger` opcode.
    pub(super) fn do_divide_integer(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_divide_integer, checked_div_integer);
    }

    /// Implements the `DoubleToInteger` opcode.
    pub(super) fn do_double_to_integer(&mut self, instr: u32) {
        let reg = bytecode::parse_double_to_integer(instr);
        let dvalue = f64::from_bits(self.get_reg(reg)).round();
        if dvalue.is_finite() && dvalue >= (i32::MIN as f64) && dvalue <= (i32::MAX as f64) {
            self.set_reg(reg, (dvalue as i32) as u64);
        } else {
            self.set_exception(format!("Cannot cast {} to integer due to overflow", dvalue));
            return;
        }
        self.pc += 1;
    }

    /// Implements the `EqualBoolean` opcode.
    pub(super) fn do_equal_boolean(&mut self, instr: u32) {
        self.do_binary_boolean_op(instr, bytecode::parse_equal_boolean, |l, r| l == r);
    }

    /// Implements the `EqualDouble` opcode.
    pub(super) fn do_equal_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_equal_double, |l, r| l == r);
    }

    /// Implements the `EqualInteger` opcode.
    pub(super) fn do_equal_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(instr, bytecode::parse_equal_integer, |l, r| l == r);
    }

    /// Implements the `EqualText` opcode.
    pub(super) fn do_equal_text(&mut self, instr: u32, constants: &[ConstantDatum], heap: &Heap) {
        self.do_binary_text_op(instr, constants, heap, bytecode::parse_equal_text, |l, r| l == r);
    }

    /// Implements the `End` opcode.
    pub(super) fn do_end(&mut self, instr: u32) {
        let reg = bytecode::parse_end(instr);
        let code = self.get_reg(reg) as i32;
        let code = match ExitCode::try_from(code) {
            Ok(code) => code,
            Err(e) => {
                self.set_exception(e.to_string());
                return;
            }
        };
        self.stop = Some(InternalStopReason::End(code));
    }

    /// Implements the `Eof` opcode.
    pub(super) fn do_eof(&mut self, instr: u32) {
        bytecode::parse_eof(instr);
        self.stop = Some(InternalStopReason::Eof);
    }

    /// Implements the `Gosub` opcode.
    pub(super) fn do_gosub(&mut self, instr: u32) {
        let offset = bytecode::parse_gosub(instr);
        if !self.push_frame(Frame { old_pc: self.pc, old_fp: self.fp, ret_reg: None }) {
            return;
        }
        self.pc = Address::from(offset);
    }

    /// Implements the `GreaterDouble` opcode.
    pub(super) fn do_greater_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_greater_double, |l, r| l > r);
    }

    /// Implements the `GreaterEqualDouble` opcode.
    pub(super) fn do_greater_equal_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_greater_equal_double, |l, r| {
            l >= r
        });
    }

    /// Implements the `GreaterEqualInteger` opcode.
    pub(super) fn do_greater_equal_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(
            instr,
            bytecode::parse_greater_equal_integer,
            |l, r| l >= r,
        );
    }

    /// Implements the `GreaterEqualText` opcode.
    pub(super) fn do_greater_equal_text(
        &mut self,
        instr: u32,
        constants: &[ConstantDatum],
        heap: &Heap,
    ) {
        self.do_binary_text_op(
            instr,
            constants,
            heap,
            bytecode::parse_greater_equal_text,
            |l, r| l >= r,
        );
    }

    /// Implements the `GreaterInteger` opcode.
    pub(super) fn do_greater_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(instr, bytecode::parse_greater_integer, |l, r| l > r);
    }

    /// Implements the `GreaterText` opcode.
    pub(super) fn do_greater_text(&mut self, instr: u32, constants: &[ConstantDatum], heap: &Heap) {
        self.do_binary_text_op(instr, constants, heap, bytecode::parse_greater_text, |l, r| l > r);
    }

    /// Implements the `IntegerToDouble` opcode.
    pub(super) fn do_integer_to_double(&mut self, instr: u32) {
        let reg = bytecode::parse_integer_to_double(instr);
        let ivalue = self.get_reg(reg) as i32;
        self.set_reg(reg, (ivalue as f64).to_bits());
        self.pc += 1;
    }

    /// Implements the `Jump` opcode.
    pub(super) fn do_jump(&mut self, instr: u32) {
        let old_pc = self.pc;
        let offset = bytecode::parse_jump(instr);
        self.pc = Address::from(offset);
        if self.pc <= old_pc {
            self.yield_pending = true;
        }
    }

    /// Implements the `JumpIfFalse` opcode.
    pub(super) fn do_jump_if_false(&mut self, instr: u32) {
        let (cond_reg, target) = bytecode::parse_jump_if_false(instr);
        if self.get_reg(cond_reg) != 0 {
            self.pc += 1;
        } else {
            let old_pc = self.pc;
            self.pc = Address::from(target);
            if self.pc <= old_pc {
                self.yield_pending = true;
            }
        }
    }

    /// Implements the `LessDouble` opcode.
    pub(super) fn do_less_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_less_double, |l, r| l < r);
    }

    /// Implements the `LessEqualDouble` opcode.
    pub(super) fn do_less_equal_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_less_equal_double, |l, r| l <= r);
    }

    /// Implements the `LessEqualInteger` opcode.
    pub(super) fn do_less_equal_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(instr, bytecode::parse_less_equal_integer, |l, r| {
            l <= r
        });
    }

    /// Implements the `LessEqualText` opcode.
    pub(super) fn do_less_equal_text(
        &mut self,
        instr: u32,
        constants: &[ConstantDatum],
        heap: &Heap,
    ) {
        self.do_binary_text_op(instr, constants, heap, bytecode::parse_less_equal_text, |l, r| {
            l <= r
        });
    }

    /// Implements the `LessInteger` opcode.
    pub(super) fn do_less_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(instr, bytecode::parse_less_integer, |l, r| l < r);
    }

    /// Implements the `LessText` opcode.
    pub(super) fn do_less_text(&mut self, instr: u32, constants: &[ConstantDatum], heap: &Heap) {
        self.do_binary_text_op(instr, constants, heap, bytecode::parse_less_text, |l, r| l < r);
    }

    /// Implements the `LoadArray` opcode.
    pub(super) fn do_load_array(&mut self, instr: u32, heap: &Heap) {
        let (dest, arr_reg, first_sub_reg) = bytecode::parse_load_array(instr);

        if let Some((heap_idx, flat_idx)) = self.resolve_array_index(arr_reg, first_sub_reg, heap) {
            let array = match heap.get(heap_idx) {
                HeapDatum::Array(a) => a,
                _ => unreachable!("Register must point to an array"),
            };
            self.set_reg(dest, array.values[flat_idx]);
            self.pc += 1;
        }
    }

    /// Implements the `LoadConstant` opcode.
    pub(super) fn do_load_constant(&mut self, instr: u32, constants: &[ConstantDatum]) {
        let (register, i) = bytecode::parse_load_constant(instr);
        match &constants[usize::from(i)] {
            ConstantDatum::Boolean(_) => unreachable!("Booleans are always immediates"),
            ConstantDatum::Double(d) => self.set_reg(register, d.to_bits()),
            ConstantDatum::Integer(i) => self.set_reg(register, *i as u64),
            ConstantDatum::Text(_) => unreachable!("Strings cannot be loaded into registers"),
        }
        self.pc += 1;
    }

    /// Implements the `LoadInteger` opcode.
    pub(super) fn do_load_integer(&mut self, instr: u32) {
        let (register, i) = bytecode::parse_load_integer(instr);
        self.set_reg(register, i as u64);
        self.pc += 1;
    }

    /// Implements the `LoadRegisterPointer` opcode.
    pub(super) fn do_load_register_ptr(&mut self, instr: u32) {
        let (dest, vtype, src) = bytecode::parse_load_register_ptr(instr);
        let tagged_ref = TaggedRegisterRef::new(src, self.fp, vtype);
        self.set_reg(dest, tagged_ref.as_u64());
        self.pc += 1;
    }

    /// Implements the `ModuloDouble` opcode.
    pub(super) fn do_modulo_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_modulo_double, |l, r| l % r);
    }

    /// Implements the `ModuloInteger` opcode.
    pub(super) fn do_modulo_integer(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_modulo_integer, checked_mod_integer);
    }

    /// Implements the `Move` opcode.
    pub(super) fn do_move(&mut self, instr: u32) {
        let (dest, src) = bytecode::parse_move(instr);
        let value = self.get_reg(src);
        self.set_reg(dest, value);
        self.pc += 1;
    }

    /// Implements the `MultiplyDouble` opcode.
    pub(super) fn do_multiply_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_multiply_double, |l, r| l * r);
    }

    /// Implements the `MultiplyInteger` opcode.
    pub(super) fn do_multiply_integer(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_multiply_integer, checked_mul_integer);
    }

    /// Implements the `NegateDouble` opcode.
    pub(super) fn do_negate_double(&mut self, instr: u32) {
        let reg = bytecode::parse_negate_double(instr);
        let value = f64::from_bits(self.get_reg(reg));
        self.set_reg(reg, (-value).to_bits());
        self.pc += 1;
    }

    /// Implements the `NegateInteger` opcode.
    pub(super) fn do_negate_integer(&mut self, instr: u32) {
        let reg = bytecode::parse_negate_integer(instr);
        let value = self.get_reg(reg) as i32;
        match value.checked_neg() {
            Some(result) => {
                self.set_reg(reg, result as u64);
                self.pc += 1;
            }
            None => {
                self.set_exception("Integer overflow");
            }
        }
    }

    /// Implements the `NotEqualBoolean` opcode.
    pub(super) fn do_not_equal_boolean(&mut self, instr: u32) {
        self.do_binary_boolean_op(instr, bytecode::parse_not_equal_boolean, |l, r| l != r);
    }

    /// Implements the `NotEqualDouble` opcode.
    pub(super) fn do_not_equal_double(&mut self, instr: u32) {
        self.do_binary_double_predicate_op(instr, bytecode::parse_not_equal_double, |l, r| l != r);
    }

    /// Implements the `NotEqualInteger` opcode.
    pub(super) fn do_not_equal_integer(&mut self, instr: u32) {
        self.do_binary_integer_predicate_op(instr, bytecode::parse_not_equal_integer, |l, r| {
            l != r
        });
    }

    /// Implements the `NotEqualText` opcode.
    pub(super) fn do_not_equal_text(
        &mut self,
        instr: u32,
        constants: &[ConstantDatum],
        heap: &Heap,
    ) {
        self.do_binary_text_op(instr, constants, heap, bytecode::parse_not_equal_text, |l, r| {
            l != r
        });
    }

    /// Implements the `Nop` opcode.
    pub(super) fn do_nop(&mut self, instr: u32) {
        bytecode::parse_nop(instr);
        self.pc += 1;
    }

    /// Implements the `PowerDouble` opcode.
    pub(super) fn do_power_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_power_double, |l, r| l.powf(r));
    }

    /// Implements the `PowerInteger` opcode.
    pub(super) fn do_power_integer(&mut self, instr: u32) {
        let (dest, src1, src2) = bytecode::parse_power_integer(instr);
        let lhs = self.get_reg(src1) as i32;
        let rhs = self.get_reg(src2) as i32;
        let exp = match u32::try_from(rhs) {
            Ok(exp) => exp,
            Err(_) => {
                self.set_exception(format!("Exponent {} cannot be negative", rhs));
                return;
            }
        };
        match checked_pow_integer(lhs, exp) {
            Ok(result) => {
                self.set_reg(dest, result as u64);
                self.pc += 1;
            }
            Err(msg) => {
                self.set_exception(msg);
            }
        }
    }

    /// Implements the `Return` opcode.
    pub(super) fn do_return(&mut self, instr: u32) {
        bytecode::parse_return(instr);
        let frame = match self.call_stack.pop() {
            Some(frame) => frame,
            None => {
                self.set_exception("RETURN without GOSUB or FUNCTION call");
                return;
            }
        };
        if let Some(ret_reg) = frame.ret_reg {
            let return_value = self.get_reg(Register::local(0).unwrap());
            self.pc = frame.old_pc + 1;
            self.fp = frame.old_fp;
            self.set_reg(ret_reg, return_value);
        } else {
            self.pc = frame.old_pc + 1;
            self.fp = frame.old_fp;
            self.yield_pending = true;
        }
    }

    /// Implements the `SetErrorHandler` opcode.
    pub(super) fn do_set_error_handler(&mut self, instr: u32) {
        let (mode, target) = bytecode::parse_set_error_handler(instr);
        self.err_handler = match mode {
            ErrorHandlerMode::None => ErrorHandler::None,
            ErrorHandlerMode::Jump => {
                ErrorHandler::Jump { active: false, addr: usize::from(target) }
            }
            ErrorHandlerMode::ResumeNext => ErrorHandler::ResumeNext,
        };
        self.pc += 1;
    }

    /// Implements the `ShiftLeft` opcode.
    pub(super) fn do_shift_left(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_shift_left, checked_shl_integer);
    }

    /// Implements the `ShiftRight` opcode.
    pub(super) fn do_shift_right(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_shift_right, checked_shr_integer);
    }

    /// Implements the `StoreArray` opcode.
    pub(super) fn do_store_array(&mut self, instr: u32, heap: &mut Heap) {
        let (arr_reg, val_reg, first_sub_reg) = bytecode::parse_store_array(instr);

        let value = self.get_reg(val_reg);
        if let Some((heap_idx, flat_idx)) = self.resolve_array_index(arr_reg, first_sub_reg, heap) {
            let array = match heap.get_mut(heap_idx) {
                HeapDatum::Array(a) => a,
                _ => unreachable!("Register must point to an array"),
            };
            array.values[flat_idx] = value;
            self.pc += 1;
        }
    }

    /// Implements the `SubtractDouble` opcode.
    pub(super) fn do_subtract_double(&mut self, instr: u32) {
        self.do_binary_double_op(instr, bytecode::parse_subtract_double, |l, r| l - r);
    }

    /// Implements the `SubtractInteger` opcode.
    pub(super) fn do_subtract_integer(&mut self, instr: u32) {
        self.do_binary_integer_op(instr, bytecode::parse_subtract_integer, checked_sub_integer);
    }

    /// Implements the `Upcall` opcode.
    pub(super) fn do_upcall(&mut self, instr: u32) {
        let (index, first_reg) = bytecode::parse_upcall(instr);
        let upcall_pc = self.pc;
        self.pc += 1;
        self.stop = Some(InternalStopReason::Upcall(index, first_reg, upcall_pc));
    }

    /// Implements the `UpcallAsync` opcode.
    pub(super) fn do_upcall_async(&mut self, instr: u32) {
        let (index, first_reg) = bytecode::parse_upcall_async(instr);
        let upcall_pc = self.pc;
        self.pc += 1;
        self.stop = Some(InternalStopReason::UpcallAsync(index, first_reg, upcall_pc));
    }
}