summaryrefslogtreecommitdiff
path: root/src/runtime.rs
blob: dbb6222b88bac3e82642192153af51174deeafbd (plain)
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
use std::{collections::BTreeMap, cmp::Ordering, sync::Arc, iter::{Copied, Rev}};

use ion_rs::SymbolTable;
use tokio::sync::mpsc::{self, Sender};

use crate::ion::{IonReader, IonValue};




#[repr(u8)]
pub enum OpCode {

    Jump = 0x01,

    Dup = 0x02,
    Dup2 = 0x03,
    SwapPop = 0x04,

    /// Invoke a function
    /// operands: function id
    /// stack: [arguments...] -> [return value?]
    Invoke = 0x05,

    /// Invoke a function and gather all results into a list.
    /// operands: function id
    /// stack: [arguments...] -> [list of return values]
    InvokeGenerate = 0x06,

    /// Provide a return value.
    /// operands:
    /// stack: [value] -> []
    Yield = 0x07,

    /// Return control to the caller.
    /// operands:
    /// stack:
    Return = 0x08,

    /// Push a typed Ion value onto the stack.
    /// operands: T and L
    ///           length
    ///           repr
    /// stack: [] -> [representation, length, T and L]
    /// Note: lengths are reversed on the stack.
    ///       representations are not reversed.
    TypePush = 0x10,

    /// Pop a typed Ion value from the stack.
    /// operands:
    /// stack: [repr, length, T and L] -> []
    TypePop = 0x11,

    /// Load a typed Ion value from a variable onto the stack.
    /// operands: variableId (VarUInt)
    /// stack: [] -> [repr, length, T and L]
    TypeLoad = 0x12,

    /// Save a typed Ion value from the stack into a variable.
    /// operands: variableId (VarUInt)
    /// stack: [repr, length, T and L] -> []
    TypeStore = 0x13,

    /// Push the length of the type.
    /// operands: variableId (VarUInt)
    /// stack: [repr, length, T+L] -> [Int]
    TypeLength = 0x14,

    /// Append bytes onto the end of a typed sequence of bytes.
    /// This operation is valid with string, clob, and blob types.
    /// operands: variableId (VarUInt)
    ///           number of octets to push
    /// stack: [repr, length, T+L, bytes] -> [repr, bytes, length', T+L']
    BytesAppend = 0x15,

    /// Append a typed value onto the end of a list or sexp.
    /// operands: variableId (VarUInt)
    /// stack: [repr, length, T+L] ->  []
    ListAppend = 0x16,

    /// Push the element from a list or sexp onto the stack.
    /// operands: variableId (VarUInt)
    /// stack: [offset (Int)] -> [{next offset}, {value}]
    ListLoad = 0x17,

    /// Append a typed value onto the end of a struct.
    /// operands: variableId (VarUInt)
    /// stack: [{value}, {symbol}] ->  []
    FieldAppend = 0x18,

    /// Prepare an iterator an iterator over the variable.
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{next offset}]
    Iterator = 0x19,

    /// Move an iterator to the next value.
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{next offset}]
    Next = 0x1A,

    /// Move an iterator to a nested value.
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{offset}, {next end}, {next offset}]
    StepIn = 0x1B,

    /// Move an iterator out of a nested value.
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{next offset}]
    /// stack: [{{end}, {offset}] -> []
    StepOut = 0x1C,

    /// Copy a value onto the stack
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{offset}, {value}]
    LoadValue = 0x1D,

    /// Copy a struct field symbol onto the stack
    /// operands: variableId (VarUInt)
    /// stack: [{offset (UInt)}] -> [{offset}, {value}]
    StructField = 0x1E,


    /// Add two ints.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    IntAdd = 0x21,

    /// Subtract value2 from value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    IntSub = 0x22,

    /// Multiply value1 and value2.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    IntMul = 0x23,

    /// Divide value2 by value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    IntDiv = 0x24,


    /// Add two floats.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    FloatAdd = 0x41,

    /// Subtract value2 from value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    FloatSub = 0x42,

    /// Multiply value1 and value2.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    FloatMul = 0x43,

    /// Divide value2 by value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    FloatDiv = 0x44,


    /// Add two decimals.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    DecimalAdd = 0x51,

    /// Subtract value2 from value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    DecimalSub = 0x52,

    /// Multiply value1 and value2.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    DecimalMul = 0x53,

    /// Divide value2 by value1.
    /// operands:
    /// stack -> [{value1}, {value2} -> {result}]
    DecimalDiv = 0x54,


    /// Jump to the given instruction if value == 0.
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfEq = 0x30,

    /// Jump to the given instruction if values != 0.
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfNe = 0x31,

    /// Jump to the given instruction if value >= 0
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfGe = 0x32,

    /// Jump to the given instruction if value > 0.
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfGt = 0x33,

    /// Jump to the given instruction if value <= 0.
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfLe = 0x34,

    /// Jump to the given instruction if value < 0.
    /// operands: instruction (VarUInt)
    /// stack: [{value}] -> []
    IfLt = 0x35,


    /// Jump to the given instruction if two values are equal.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfEq2 = 0x36,

    /// Jump to the given instruction if two values are not equal.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfNe2 = 0x37,

    /// Jump to the given instruction if value2 >= value1.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfGe2 = 0x38,

    /// Jump to the given instruction if value2 > value1.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfGt2 = 0x39,

    /// Jump to the given instruction if value2 <= value1.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfLe2 = 0x3a,

    /// Jump to the given instruction if value2 < value1.
    /// operands: instruction (VarUInt)
    /// stack: [{value1}, {value2}] -> []
    IfLt2 = 0x3b,


    NewList = 0xB1,
    NewStruct = 0xD1,

}

impl OpCode {
    pub fn as_u8(&self) -> u8 {
        unsafe { *(self as *const Self as *const u8) }
    }
}

impl From<OpCode> for u8 {
    fn from(value: OpCode) -> Self {
        value.as_u8()
    }
}

#[derive(Clone)]
pub struct Runtime(Arc<RuntimeInner>);

pub struct RuntimeInner {
    symbols: SymbolTable,
    bytecode: Arc<ByteCode>,
    functions: BTreeMap<usize, Function>,
    channel_buffer_size: usize,
}

pub enum ExecutionState {
    Continue,
    Yield(IonValue),
    Halt,
}

#[derive(Copy, Clone)]
pub struct Function {
    pub(crate) name_symbol: usize,
    pub(crate) arguments: u16,
    pub(crate) variables: u16,
    pub(crate) pc: usize,
    pub(crate) expected_stack_depth: usize,
}

pub type ByteCode = Vec<u8>;

#[derive(Clone)]
struct Stack(Vec<u8>);

#[derive(Clone)]
pub struct StackFrame {
    runtime: Runtime,
    bytecode: Arc<ByteCode>,
    pc: usize,
    variables: Vec<IonValue>,
    stack: Stack,
    tx: Sender<IonValue>,
}

pub type ExecutionStream = mpsc::Receiver<IonValue>;


impl Runtime {
    pub fn new(symbols: SymbolTable, bytecode: ByteCode, functions: Vec<Function>) -> Runtime {
        Runtime(Arc::new(RuntimeInner {
            symbols,
            functions: functions.into_iter().map(|f| (f.name_symbol, f)).collect(),
            bytecode: bytecode.into(),
            channel_buffer_size: 1,
        }))
    }

    pub fn to_symbol_id<S>(&self, s: S) -> Option<usize>
    where S: AsRef<str>
    {
        self.0.symbols.sid_for(&s)
    }

    pub fn resolve_symbol(&self, id: usize) -> Option<&str> {
        self.0.symbols.text_for(id)
    }

    pub fn invoke(&mut self, fnref: usize, arguments: Vec<IonValue>) -> ExecutionStream {
        let (tx, rx) = mpsc::channel::<IonValue>(self.0.channel_buffer_size);
        let func = *self.0.functions.get(&fnref).expect("Undefined function");
        let frame = StackFrame::new(self.clone(), tx, &func, arguments);
        execute_frame(frame);
        rx
    }
}

fn execute_frame(mut frame: StackFrame) {
    tokio::spawn(async move {
        loop {
            match execute(&mut frame).await {
                ExecutionState::Continue => (),
                ExecutionState::Yield(value) => {
                    if frame.tx.send(value).await.is_err() {
                        break;
                    }
                },
                ExecutionState::Halt => {
                    break;
                },
            }
        }
    });
}

async fn execute(frame: &mut StackFrame) -> ExecutionState {
    if frame.eof() {
        return ExecutionState::Halt;
    }

    let op = frame.next_byte();

    #[cfg(debugger)]
    {
        for x in &frame.stack.0 {
            print!(" {x:02X}");
        }
        println!();
        println!("PC: {:02X}, OP: {:02X}", frame.pc - 1, op);
    }

    match op {
        0x01 => { // OpType::Jump
            let pc = frame.next_u32().try_into().unwrap();
            frame.jump(pc);
        },
        0x02 => { // OpType::Dup
            let value1 = frame.stack.pop_value();
            frame.stack.push_value(&value1);
            frame.stack.push_value(&value1);
        },
        0x03 => { // OpType::Dup2
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            frame.stack.push_value(&value2);
            frame.stack.push_value(&value1);
            frame.stack.push_value(&value2);
            frame.stack.push_value(&value1);
        },
        0x04 => { // OpType::SwapPop
            let value1 = frame.stack.pop_value();
            frame.stack.drop_value();
            frame.stack.push_value(&value1);
        },
        0x05 => { // OpType::Invoke
            let function_id = frame.next_varuint();
            let function = frame.runtime.0.functions.get(&function_id)
                .expect("Undefined function");
            let mut args = Vec::with_capacity(function.arguments as usize);
            for _ in 0..function.arguments {
                args.push(frame.stack.pop_value());
            }
            let mut rx = frame.runtime.invoke(function_id, args);
            let mut previous_ret = None;
            while let Some(ret) = rx.recv().await {
                if let Some(previous_ret) = previous_ret.take() {
                    let mut branch = frame.clone();
                    branch.stack.push_value(&previous_ret);
                    execute_frame(branch);
                }
                previous_ret = Some(ret);
            }
            if let Some(ret) = previous_ret.take() {
                frame.stack.push_value(&ret);
            }
        },
        0x06 => { // OpType::InvokeGenerator

        },
        0x07 => { // OpType::Yield
            return ExecutionState::Yield(frame.stack.pop_value());
        },
        0x08 => { // OpType::Return
            return ExecutionState::Halt;
        },
        0x10 => { // OpType::Push
            let buf = &frame.bytecode[frame.pc..];
            let mut reader = IonReader::new(buf.iter().copied(), 0);
            let value = reader.next_value();
            frame.pc += reader.offset();
            frame.stack.push_value(&value);
        },
        0x11 => { // OpCode::TypePop
            frame.stack.drop_value();
        },
        0x12 => { // OpCode::TypeLoad
            let var = frame.next_varuint();
            frame.stack.push_value(&frame.variables[var]);
        },
        0x13 => { // OpCode::TypeStore
            let var = frame.next_varuint();
            frame.variables[var] = frame.stack.pop_value();
        },
        0x14 => { // OpCode::TypeLength
            let var = frame.next_varuint();
            let buf = frame.variables.get(var).expect("Undefined variable");
            let len = buf.len();
            frame.stack.push_usize(len);
        },
        0x15 => todo!(), // OpCode::BytesAppend
        0x16 => todo!(), // OpCode::ListAppend
        0x17 => todo!(), // OpCode::ListLoad
        0x18 => todo!(), // OpCode::FieldAppend
        0x19 => { // OpCode::Iterate
            let (ion_type, end, pos) = {
                let mut reader = frame.stack.peek_reader();
                let (ion_type, end) = reader.step_in();
                let pos = reader.offset();
                (ion_type, end, pos)
            };

            frame.stack.push_usize(ion_type as usize);
            frame.stack.push_usize(end);
            frame.stack.push_usize(pos);

        },
        0x1A => { // OpCode::Next
            let pos = frame.stack.pop_value().to_usize();
            let len = frame.stack.pop_value().to_usize();
            let ion_type = frame.stack.pop_value().to_usize();

            let next = {
                let mut reader = if ion_type == 0x0D {
                    frame.stack.peek_struct_reader_at(pos)
                } else {
                    frame.stack.peek_reader_at(pos)
                };
                reader.skip_value();
                reader.offset()
            };

            frame.stack.push_usize(ion_type);          // TODO peek
            frame.stack.push_usize(len);               // TODO peek
            frame.stack.push_usize(next);
        },
        0x1B => { // OpCode::StepIn
            let pos = frame.stack.pop_value().to_usize();
            let len = frame.stack.pop_value().to_usize();
            let ion_type = frame.stack.pop_value().to_usize();

            let (next_type, next_end, next_pos) = {
                let mut reader = if ion_type == 0x0D {
                    frame.stack.peek_struct_reader_at(pos)
                } else {
                    frame.stack.peek_reader_at(pos)
                };
                let (next_type, next_end) = reader.step_in();
                let next_pos = reader.offset();
                (next_type, next_end, next_pos)
            };

            frame.stack.push_usize(ion_type);          // TODO peek
            frame.stack.push_usize(len);               // TODO peek
            frame.stack.push_usize(pos);               // TODO peek

            frame.stack.push_usize(next_type as usize);
            frame.stack.push_usize(next_end);
            frame.stack.push_usize(next_pos);
        },
        0x1C => { // OpCode::StepOut
            frame.stack.drop_value();
            frame.stack.drop_value();
            frame.stack.drop_value();
        },
        0x1D => { // OpCode::LoadValue
            let pos = frame.stack.pop_value().to_usize();
            let len = frame.stack.pop_value().to_usize();
            let ion_type = frame.stack.pop_value().to_usize();

            let next_value = {
                let mut reader = if ion_type == 0x0D {
                    frame.stack.peek_struct_reader_at(pos)
                } else {
                    frame.stack.peek_reader_at(pos)
                };
                reader.next_value()
            };

            frame.stack.push_usize(ion_type);          // TODO peek
            frame.stack.push_usize(len);               // TODO peek
            frame.stack.push_usize(pos);               // TODO peek

            frame.stack.push_value(&next_value);
        },
        0x1E => { // OpCode::StructField
            let pos = frame.stack.pop_value().to_usize();
            let len = frame.stack.pop_value().to_usize();
            let ion_type = frame.stack.pop_value().to_usize();

            let field_id = {
                let mut reader = if ion_type == 0x0D {
                    frame.stack.peek_struct_reader_at(pos)
                } else {
                    frame.stack.peek_reader_at(pos)
                };
                reader.skip_value();
                reader.field_id()
            };

            frame.stack.push_usize(ion_type);          // TODO peek
            frame.stack.push_usize(len);               // TODO peek
            frame.stack.push_usize(pos);               // TODO peek

            if let Some(field_id) = field_id {
                frame.stack.push_symbol(field_id);
            } else {
                panic!("Not a struct");
            }
        },
        0x21 => todo!(), // OpCode::IntAdd
        0x22 => todo!(), // OpCode::IntSub
        0x23 => todo!(), // OpCode::IntMul
        0x24 => todo!(), // OpCode::IntDiv
        0x41 => todo!(), // OpCode::FloatAdd
        0x42 => todo!(), // OpCode::FloatSub
        0x43 => todo!(), // OpCode::FloatMul
        0x44 => todo!(), // OpCode::FloatDiv
        0x51 => todo!(), // OpCode::DecimalAdd
        0x52 => todo!(), // OpCode::DecimalSub
        0x53 => todo!(), // OpCode::DecimalMul
        0x54 => todo!(), // OpCode::DecimalDiv
        0x30 => todo!(), // OpCode::IfEq
        0x31 => todo!(), // OpCode::IfNe
        0x32 => todo!(), // OpCode::IfGe
        0x33 => todo!(), // OpCode::IfGt
        0x34 => todo!(), // OpCode::IfLe
        0x35 => todo!(), // OpCode::IfLt
        0x36 => { // OpCode::IfEq2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 == value2 {
                frame.pc = next_pc;
            }
        },
        0x37 => { // OpCode::IfNe2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 != value2 {
                frame.pc = next_pc;
            }
        },
        0x38 => { // OpCode::IfGe2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 >= value2 {
                frame.pc = next_pc;
            }
        },
        0x39 => { // OpCode::IfGt2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 > value2 {
                frame.pc = next_pc;
            }
        },
        0x3A => { // OpCode::IfLe2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 <= value2 {
                frame.pc = next_pc;
            }
        },
        0x3B => { // OpCode::IfLt2
            let next_pc = frame.next_u32().try_into().unwrap();
            let value1 = frame.stack.pop_value();
            let value2 = frame.stack.pop_value();
            if value1 < value2 {
                frame.pc = next_pc;
            }
        },

        0xB1 => { // OpCode::NewList
            // TODO: Yuck
            let len = frame.stack.pop_usize();
            let mut list = Vec::new();
            let mut sz = 0;
            for _ in 0..len {
                let value = frame.stack.pop_value();
                sz += value.len();
                list.push(value);
            }
            for v in list {
                frame.stack.push_value(&v);
            }
            if sz >= 14 {
                frame.stack.push_varuint(sz);
                frame.stack.push_byte(0xBE);
            } else {
                frame.stack.push_byte(0xB0 | (sz as u8));
            }
        },

        0xD1 => { // OpCode::NewStruct
            // TODO: Yuck
            let len = frame.stack.pop_usize();
            let mut pairs = Vec::new();
            for _ in 0..len {
                let sym = frame.stack.pop_value();
                let value = frame.stack.pop_value();
                pairs.push((sym, value));
            }
            let mark = frame.stack.len();
            for (sym, v) in pairs {
                frame.stack.push_value(&v);
                frame.stack.push_varuint(sym.reader().next_symbol_id());
            }
            let sz = frame.stack.len() - mark;
            if sz >= 14 {
                frame.stack.push_varuint(sz);
                frame.stack.push_byte(0xDE);
            } else {
                frame.stack.push_byte(0xD0 | (sz as u8));
            }
        },

        _ => panic!("Invalid opcode {:02x} at {:02x}", op, frame.pc - 1),
    }

    ExecutionState::Continue
}

impl  StackFrame {
    pub fn new(runtime: Runtime, tx: Sender<IonValue>, func: &Function, arguments: Vec<IonValue>) -> StackFrame {
        let stack = Stack::new(func.expected_stack_depth);
        let mut frame = StackFrame {
            bytecode: runtime.0.bytecode.clone(),
            pc: func.pc,
            variables: arguments,
            stack,
            tx,
            runtime,
        };

        for _ in func.arguments..func.variables {
            frame.variables.push(IonValue::new_null());
        }

        frame
    }

    fn jump(&mut self, pc: usize) {
        self.pc = pc;
    }

    fn eof(&self) -> bool {
        self.pc >= self.bytecode.len()
    }

    fn next_byte(&mut self) -> u8 {
        let b = self.bytecode[self.pc];
        self.pc += 1;
        b
    }

    fn next_u32(&mut self) -> u32 {
        let mut v: u32 = 0;
        for _ in 0..4 {
            v <<= 8;
            v |= self.next_byte() as u32;
        }
        v
    }

    fn next_varuint(&mut self) -> usize {
        let mut b: usize = self.next_byte().into();
        let mut v = b & 0x7f;
        while (b & 0x80) == 0 {
            b = self.next_byte().into();
            v <<= 7;
            v |= b & 0x7f;
        }
        v
    }
}

impl Stack {
    pub fn new(expected_depth: usize) -> Stack {
        Stack(Vec::with_capacity(expected_depth))
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn peek_reader(&self) -> IonReader<impl DoubleEndedIterator<Item = u8> + '_> {
        IonReader::new(self.0.iter().copied().rev(), 0)
    }

    pub fn peek_reader_at(&self, offset: usize) -> IonReader<Rev<Copied<std::slice::Iter<'_, u8>>>> {
        let end = self.0.len() - offset;
        IonReader::new(self.0[..end].iter().copied().rev(), offset)
    }

    pub fn peek_struct_reader_at(&self, offset: usize) -> IonReader<Rev<Copied<std::slice::Iter<'_, u8>>>> {
        let end = self.0.len() - offset;
        IonReader::new_struct(self.0[..end].iter().copied().rev(), offset)
    }

    pub fn drop_value(&mut self) {
        let mut it = IonReader::new(self.0.iter().copied().rev(), 0);
        it.skip_value();
        let offset = it.offset();
        self.0.truncate(self.0.len() - offset);
    }

    pub fn pop_value(&mut self) -> IonValue {
        let mut it = IonReader::new(self.0.iter().copied().rev(), 0);
        let value = it.next_value();
        let offset = it.offset();
        self.0.truncate(self.0.len() - offset);
        value
    }

    pub fn pop_usize(&mut self) -> usize {
        let mut it = IonReader::new(self.0.iter().copied().rev(), 0);
        let value = it.next_usize();
        let offset = it.offset();
        self.0.truncate(self.0.len() - offset);
        value
    }

    #[inline]
    pub fn push_byte(&mut self, value: u8) {
        self.0.push(value);
    }

    pub fn push_varuint(&mut self, mut value: usize) {
        self.push_byte((value & 0x7F | 0x80) as u8);
        value >>= 7;
        while value != 0 {
            self.push_byte((value & 0x7F) as u8);
            value >>= 7;
        }
    }

    pub fn push_value(&mut self, value: &IonValue) {
        for byte in value.bytes().rev() {
            self.push_byte(byte);
        }
    }

    pub fn push_symbol(&mut self, value: usize) {
        match value.cmp(&0) {
            Ordering::Equal => self.push_byte(0x70),
            Ordering::Greater => {
                let mut v = value;
                let mut octets = 0;
                while v != 0 {
                    self.push_byte((v & 0xFF) as u8);
                    octets += 1;
                    v >>= 8;
                }
                let tl = 0x70 | octets;
                self.push_byte(tl);
            },
            Ordering::Less => (),
        }
    }

    pub fn push_usize(&mut self, value: usize) {
        match value.cmp(&0) {
            Ordering::Equal => self.push_byte(0x20),
            Ordering::Greater => {
                let mut v = value;
                let mut octets = 0;
                while v != 0 {
                    self.push_byte((v & 0xFF) as u8);
                    octets += 1;
                    v >>= 8;
                }
                let tl = 0x20 | octets;
                self.push_byte(tl);
            },
            Ordering::Less => (),
        }
    }

}