koto_bytecode 0.16.1

The bytecode compiler used by the Koto programming language
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
/// The operations used in Koto bytecode
///
/// Each operation is made up of a byte, followed by N additional bytes (where N is at least 1)
/// that define its behaviour.
///
/// The combined operation bytes are interpreted as an [Instruction](crate::Instruction) by the
/// [InstructionReader](crate::InstructionReader).
///
/// In the comments for each operation, the additional bytes are specified inside square brackets.
/// Byte prefixes:
///     * - Shows that the byte is referring to a register.
///     @ - Indicates a variable-sized integer.
///         - The 7 least significant bits are included in the integer.
///         - The 8th bit in a byte is a continuation flag.
///         - Continuation bits are shifted by N*7 and included in the resulting integer.
///         - Currently only (up to) 32 bits are used, and integers are unsigned.
///     ? - Used for optional values, the presence of which will be indicated by previous flags
///         in the instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
#[allow(missing_docs)] // Allowed for the UnusedX ops
pub enum Op {
    /// Marks the start of a new frame
    ///
    /// The VM will reserve space for the given number of registers used by the frame.
    ///
    /// `[registers]`
    NewFrame,

    /// Copies the source value to the target register
    ///
    /// `[*target, *source]`
    Copy,

    /// Sets a register to contain Null
    ///
    /// `[*target]`
    SetNull,

    /// Sets a register to contain Bool(false)
    ///
    /// `[*target]`
    SetFalse,

    /// Sets a register to contain Bool(true)
    ///
    /// `[*target]`
    SetTrue,

    /// Sets a register to contain Int(0)
    ///
    /// `[*target]`
    Set0,

    /// Sets a register to contain Int(1)
    ///
    /// `[*target]`
    Set1,

    /// Sets a register to contain Int(n)
    ///
    /// `[*target, n]`
    SetNumberU8,

    /// Sets a register to contain Int(-n)
    ///
    /// `[*target, n]`
    SetNumberNegU8,

    /// Loads an f64 constant into a register
    ///
    /// `[*target, @constant]`
    LoadFloat,

    /// Loads an i64 constant into a register
    ///
    /// `[*target, @constant]`
    LoadInt,

    /// Loads a string constant into a register
    ///
    /// `[*target, @constant]`
    LoadString,

    /// Loads a non-local value into a register
    ///
    /// `[*target, @constant]`
    LoadNonLocal,

    /// Imports a value
    ///
    /// The name of the module to be imported will be placed in the register before running this op,
    /// the imported module will then be placed in the same register.
    ///
    /// `[*register]`
    Import,

    /// Imports all items from a value
    ///
    /// The name of the module to be imported will be placed in the register before running this op,
    /// the imported module will then be made available for non-local access within the module.
    ///
    /// `[*register]`
    ImportAll,

    /// Makes a temporary tuple out of values stored in consecutive registers
    ///
    /// Used when a tuple is made which won't be assigned to a value,
    /// e.g. in match expressions: `match a, b, c`
    ///
    /// `[*target, *start, value count]`
    MakeTempTuple,

    /// Converts a temporary tuple into a regular Tuple
    ///
    /// Used when the result of an expression that uses a temporary tuple is needed.
    /// e.g. in multi-assignment in a return position: `return x, y, z = 1, 2, 3`
    ///
    /// `[*target, *source]`
    TempTupleToTuple,

    /// Makes an empty map with the given size hint
    ///
    /// `[*target, @size hint]`
    MakeMap,

    /// Makes an Iterator out of an iterable value
    ///
    /// `[*target, *iterable]`
    MakeIterator,

    /// Starts a new sequence with the given size hint
    ///
    /// `[@size hint]`
    SequenceStart,

    /// Pushes a single value to the end of the current sequence
    ///
    /// `[*value]`
    SequencePush,

    /// Pushes values from consecutive registers to the end of the current sequence
    ///
    /// `[*start, value count]`
    SequencePushN,

    /// Converts the current sequence into a List
    ///
    /// `[*register]`
    SequenceToList,

    /// Converts the current sequence into a Tuple
    ///
    /// `[*register]`
    SequenceToTuple,

    /// Starts the construction of a new string with a given size hint
    ///
    /// `[@size hint]`
    StringStart,

    /// Pushes a value to the end of the current string
    ///
    /// Values will be rendered and then formatted according to the specified format flags.
    ///
    /// See [`StringFormatFlags`](crate::StringFormatFlags) for a description of the format flags.
    ///
    /// `[*value, format_flags, ?@min_width, ?@precision, ?@fill_character, ?style]`
    StringPush,

    /// Places the finished string in the target register
    ///
    /// `[*target]`
    StringFinish,

    /// Makes a Function
    ///
    /// The flags are a bitfield constructed from [`FunctionFlags`](crate::FunctionFlags).
    /// The bytes following this instruction make up the body of the function.
    ///
    /// `[*target, arg count, optional arg count, capture count, flags, function size[2]]`
    Function,

    /// Captures a value for a Function
    ///
    /// The value gets cloned to the Function's captures list at the given index.
    ///
    /// `[*function, capture index, *value]`
    Capture,

    /// Makes a Range with defined start and end values
    ///
    /// `[*target, *start, *end]`
    Range,

    /// Makes an inclusive Range with defined start and end values
    ///
    /// `[*target, *start, *end]`
    RangeInclusive,

    /// Makes a Range with a defined end value and no start
    ///
    /// `[*target, *end]`
    RangeTo,

    /// Makes an inclusive Range with a defined end value and no start
    ///
    /// `[*target, *end]`
    RangeToInclusive,

    /// Makes a Range with a defined start value and no end
    ///
    /// `[*target, *start]`
    RangeFrom,

    /// Makes a full Range with undefined start and end
    ///
    /// `[*target]`
    RangeFull,

    /// Negates a value
    ///
    /// Used for the unary negation operator, i.e. `x = -y`
    ///
    /// `[*target, *source]`
    Negate,

    /// Flips the value of a boolean
    ///
    /// `[*target, *source]`
    Not,

    /// Adds lhs and rhs together
    ///
    /// `[*result, *lhs, *rhs]`
    Add,

    /// Subtracts rhs from lhs
    ///
    /// `[*result, *lhs, *rhs]`
    Subtract,

    /// Multiplies lhs and rhs together
    ///
    /// `[*result, *lhs, *rhs]`
    Multiply,

    /// Divides lhs by rhs
    ///
    /// `[*result, *lhs, *rhs]`
    Divide,

    /// Performs the remainder operation with lhs and rhs
    ///
    /// `[*result, *lhs, *rhs]`
    Remainder,

    /// Performs the power operation with lhs and rhs
    ///
    /// `[*result, *lhs, *rhs]`
    Power,

    /// lhs += rhs
    ///
    /// `[*lhs, *rhs]`
    AddAssign,

    /// lhs -= rhs
    ///
    /// `[*lhs, *rhs]`
    SubtractAssign,

    /// lhs *= rhs
    ///
    /// `[*lhs, *rhs]`
    MultiplyAssign,

    /// lhs /= rhs
    ///
    /// `[*lhs, *rhs]`
    DivideAssign,

    /// lhs %= rhs
    ///
    /// `[*lhs, *rhs]`
    RemainderAssign,

    /// lhs ^= rhs
    ///
    /// `[*lhs, *rhs]`
    PowerAssign,

    /// Compares lhs and rhs using the '<' operator
    ///
    /// `[*result, *lhs, *rhs]`
    Less,

    /// Compares lhs and rhs using the '<=' operator
    ///
    /// `[*result, *lhs, *rhs]`
    LessOrEqual,

    /// Compares lhs and rhs using the '>' operator
    ///
    /// `[*result, *lhs, *rhs]`
    Greater,

    /// Compares lhs and rhs using the '>=' operator
    ///
    /// `[*result, *lhs, *rhs]`
    GreaterOrEqual,

    /// Compares lhs and rhs using the '==' operator
    ///
    /// `[*result, *lhs, *rhs]`
    Equal,

    /// Compares lhs and rhs using the '!=' operator
    ///
    /// `[*result, *lhs, *rhs]`
    NotEqual,

    /// Causes the instruction pointer to jump forward by a number of bytes
    ///
    /// `[offset[2]]`
    Jump,

    /// Causes the instruction pointer to jump back by a number of bytes
    ///
    /// `[offset[2]]`
    JumpBack,

    /// Jumps the instruction pointer forward if a value is `false` or `null`
    ///
    /// `[*value, offset[2]]`
    JumpIfFalse,

    /// Jumps the instruction pointer forward if a value is neither `false` or `null`
    ///
    /// `[*value, offset[2]]`
    JumpIfTrue,

    /// Jumps the instruction pointer forward if a value is `null`
    ///
    /// `[*value, offset[2]]`
    JumpIfNull,

    /// Calls a standalone function
    ///
    /// The frame base register (which contains the instance during a method call) will be set to
    /// Null by the runtime before the function is called.
    ///
    /// If the result can be ignored then it will be placed in the frame base at the end of the
    /// call, which will result in it being discarded.
    ///
    /// Arguments are placed in the registers following the frame base.
    /// If there are any arguments to unpack, their indices are placed in the registers following
    /// the arguments, and the runtime will unpack them in place, shifting later arguments if
    /// necessary.
    ///
    /// `[*result, *function, *frame base, arg count, packed arg count]`
    Call,

    /// Calls an instance function
    ///
    /// The instance will be copied into the frame base register by the runtime if necessary.
    ///
    /// If the result can be ignored then it will be placed in the frame base at the end of the
    /// call, which will result in it being discarded.
    ///
    /// Arguments are placed in the registers following the frame base.
    /// If there are any arguments to unpack, their indices are placed in the registers following
    /// the arguments, and the runtime will unpack them in place, shifting later arguments if
    /// necessary.
    ///
    /// `[*result, *function, *instance, *frame base, arg count, packed arg count]`
    CallInstance,

    /// Returns from the current frame with the given result
    ///
    /// `[*result]`
    Return,

    /// Yields a value from the current generator
    ///
    /// `[*value]`
    Yield,

    /// Throws an error
    ///
    /// `[*error]`
    Throw,

    /// Gets the next value from an Iterator
    ///
    /// The output from the iterator is placed in the output register.
    /// If the iterator is finished then the instruction jumps forward by the given offset.
    ///
    /// `[*output, *iterator, offset[2]]`
    IterNext,

    /// Gets the next value from an Iterator, used when the output is treated as temporary
    ///
    /// The output from the iterator is placed in the output register, and is treated as temporary,
    /// with assigned values being unpacked from the output.
    ///
    /// e.g. `for key, value in map`
    ///
    /// If the iterator is finished then the instruction jumps forward by the given offset.
    ///
    /// `[*output, *iterator, offset[2]]`
    IterNextTemp,

    /// Gets the next value from an Iterator, used when the output can be ignored
    ///
    /// If the iterator is finished then the instruction jumps forward by the given offset.
    ///
    /// `[*iterator, offset[2]]`
    IterNextQuiet,

    /// Gets the next value from an Iterator, used during value unpacking
    ///
    /// If the iterator is finished then null is assigned to the target register.
    ///
    /// `[*output, *iterator]`
    IterUnpack,

    /// Accesses a contained value from a temporary value using a u8 index
    ///
    /// This is used for internal indexing operations.
    /// e.g. when unpacking a temporary value in multi-assignment
    ///
    /// `[*result, *value, index]`
    TempIndex,

    /// Takes a slice from the end of a given List or Tuple, starting from a u8 index
    ///
    /// Used in unpacking expressions, e.g. in a match arm
    ///
    /// `[*result, *value, index]`
    SliceFrom,

    /// Takes a slice from the start of a given List or Tuple, ending at a u8 index
    ///
    /// Used in unpacking expressions, e.g. in a match arm
    ///
    /// `[*result, *value, index]`
    SliceTo,

    /// Accesses a contained value via index
    ///
    /// `[*result, *indexable, *index]`
    Index,

    /// Sets a contained value via index
    ///
    /// `[*indexable, *value, *index]`
    IndexMut,

    /// Inserts a key/value entry into a map
    ///
    /// `[*map, *key, *value]`
    MapInsert,

    /// Inserts a key/value entry into a map's metamap
    ///
    /// `[*map, *key, *value]`
    MetaInsert,

    /// Inserts a named key/value entry into a map's metamap
    ///
    /// Used for meta keys that take a name as part of the key, like @test or @meta
    ///
    /// `[*map, *key, *name, *value]`
    MetaInsertNamed,

    /// Adds a key/value entry into the module's exported metamap
    ///
    /// Used for expressions like `@tests = ...`
    ///
    /// `[*key, *value]`
    MetaExport,

    /// Adds a named key/value entry into the module's exported metamap
    ///
    /// Used for expressions like `@tests = ...`
    ///
    /// `[*key, *name, *value]`
    MetaExportNamed,

    /// Exports a key/value pair by adding it to the module's exports map
    ///
    /// Used for expressions like `export foo = ...`
    ///
    /// `[*key, *value]`
    ExportValue,

    /// Exports an entry by adding it to the module's exports map
    ///
    /// - If the entry is a tuple, then it's assumed to be a key/value pair.
    /// - If the entry is an iterator, then it's unpacked into a key/value pair.
    /// - Otherwise an error will be thrown.
    ///
    /// `[*entry]`
    ExportEntry,

    /// Accesses a contained value via a constant key
    ///
    /// `[*target, @constant]`
    Access,

    /// Access a contained value via a string key
    ///
    /// Used in '.' access operations that use a quoted string, e.g. `foo."bar"`.
    ///
    /// `[*result, *value, *key]`
    AccessString,

    /// Gets the size of a value
    ///
    /// `[*result, *value]`
    Size,

    /// Starts a try block
    ///
    /// If an error is thrown in the try block then the error will be placed in the error register
    /// and the instruction pointer will be jumped forward to the location referred to by the catch
    /// offset.
    ///
    /// `[*error, catch offset[2]]`
    TryStart,

    /// Ends a try block
    ///
    /// A placeholder is used here to ensure that each op has at least one byte following it.
    ///
    /// `[placeholder]`
    TryEnd,

    /// Displays the contents of a value along with the source expression that produced it
    ///
    /// `[*value, @expression constant]`
    Debug,

    /// Throws an error if the value doesn't match the expected size
    ///
    /// Used when matching function arguments.
    ///
    /// `[*value, size]`
    CheckSizeEqual,

    /// Throws an error if the value isn't at least the expected size
    ///
    /// Used when matching function arguments.
    ///
    /// `[*value, size]`
    CheckSizeMin,

    /// Throws an error if the value doesn't match the provided type
    ///
    /// This is used for type hints on variable declarations, and can be disabled via the
    /// compiler's `enable_type_checks` flag.
    ///
    /// `[*value, @type constant]`
    AssertType,

    /// Throws an error if the value doesn't match the provided type
    ///
    /// This is used for type hints on variable declarations, and can be disabled via the
    /// compiler's `enable_type_checks` flag.
    ///
    /// `[*value, @type constant]`
    AssertOptionalType,

    /// Checks if the value matches the provided type
    ///
    /// If the value doesn't match the type then the instruction pointer will be jumped forward to
    /// the location referred to by the jump offset.
    ///
    /// This is used for type hints that can affect conditional logic, like match patterns.
    ///
    /// `[*value, @type constant, jump_offset[2]]`
    CheckType,

    /// Checks if the value matches the provided type
    ///
    /// If the value doesn't match the type then the instruction pointer will be jumped forward to
    /// the location referred to by the jump offset.
    ///
    /// This is used for type hints that can affect conditional logic, like match patterns.
    ///
    /// `[*value, @type constant, jump_offset[2]]`
    CheckOptionalType,

    // Unused opcodes, allowing for a direct transmutation from a byte to an Op.
    Unused93,
    Unused94,
    Unused95,
    Unused96,
    Unused97,
    Unused98,
    Unused99,
    Unused100,
    Unused101,
    Unused102,
    Unused103,
    Unused104,
    Unused105,
    Unused106,
    Unused107,
    Unused108,
    Unused109,
    Unused110,
    Unused111,
    Unused112,
    Unused113,
    Unused114,
    Unused115,
    Unused116,
    Unused117,
    Unused118,
    Unused119,
    Unused120,
    Unused121,
    Unused122,
    Unused123,
    Unused124,
    Unused125,
    Unused126,
    Unused127,
    Unused128,
    Unused129,
    Unused130,
    Unused131,
    Unused132,
    Unused133,
    Unused134,
    Unused135,
    Unused136,
    Unused137,
    Unused138,
    Unused139,
    Unused140,
    Unused141,
    Unused142,
    Unused143,
    Unused144,
    Unused145,
    Unused146,
    Unused147,
    Unused148,
    Unused149,
    Unused150,
    Unused151,
    Unused152,
    Unused153,
    Unused154,
    Unused155,
    Unused156,
    Unused157,
    Unused158,
    Unused159,
    Unused160,
    Unused161,
    Unused162,
    Unused163,
    Unused164,
    Unused165,
    Unused166,
    Unused167,
    Unused168,
    Unused169,
    Unused170,
    Unused171,
    Unused172,
    Unused173,
    Unused174,
    Unused175,
    Unused176,
    Unused177,
    Unused178,
    Unused179,
    Unused180,
    Unused181,
    Unused182,
    Unused183,
    Unused184,
    Unused185,
    Unused186,
    Unused187,
    Unused188,
    Unused189,
    Unused190,
    Unused191,
    Unused192,
    Unused193,
    Unused194,
    Unused195,
    Unused196,
    Unused197,
    Unused198,
    Unused199,
    Unused200,
    Unused201,
    Unused202,
    Unused203,
    Unused204,
    Unused205,
    Unused206,
    Unused207,
    Unused208,
    Unused209,
    Unused210,
    Unused211,
    Unused212,
    Unused213,
    Unused214,
    Unused215,
    Unused216,
    Unused217,
    Unused218,
    Unused219,
    Unused220,
    Unused221,
    Unused222,
    Unused223,
    Unused224,
    Unused225,
    Unused226,
    Unused227,
    Unused228,
    Unused229,
    Unused230,
    Unused231,
    Unused232,
    Unused233,
    Unused234,
    Unused235,
    Unused236,
    Unused237,
    Unused238,
    Unused239,
    Unused240,
    Unused241,
    Unused242,
    Unused243,
    Unused244,
    Unused245,
    Unused246,
    Unused247,
    Unused248,
    Unused249,
    Unused250,
    Unused251,
    Unused252,
    Unused253,
    Unused254,
    Unused255,
}

impl From<u8> for Op {
    fn from(op: u8) -> Op {
        // Safety:
        //  - Op is repr(u8)
        //  - All 256 possible values are represented in the enum
        unsafe { std::mem::transmute(op) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_op_count() {
        assert_eq!(
            Op::Unused255 as u8,
            255,
            "Op should have 256 entries (see impl From<u8> for Op)"
        );
    }
}