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
//! # koto_bytecode
//!
//! Contains Koto's compiler and its bytecode operations

use {
    koto_parser::{ConstantPool, Span},
    std::{path::PathBuf, sync::Arc},
};

mod compile;
mod instruction_reader;
mod loader;

pub use {compile::*, instruction_reader::*, loader::*};

/// The operation identifiers used in Koto bytecode
///
/// See [InstructionReader]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum Op {
    Copy,             // target, source
    DeepCopy,         // target, source
    SetEmpty,         // register
    SetFalse,         // register
    SetTrue,          // register
    Set0,             // register
    Set1,             // register
    SetNumberU8,      // register, number
    LoadNumber,       // register, constant
    LoadNumberLong,   // register, constant[4]
    LoadString,       // register, constant
    LoadStringLong,   // register, constant[4]
    LoadGlobal,       // register, constant
    LoadGlobalLong,   // register, constant[4]
    SetGlobal,        // global, source
    SetGlobalLong,    // global[4], source
    Import,           // register, constant
    ImportLong,       // register, constant[4]
    MakeTuple,        // register, start register, count
    MakeTempTuple,    // register, start register, count
    MakeList,         // register, size hint
    MakeListLong,     // register, size hint[4]
    MakeMap,          // register, size hint
    MakeMapLong,      // register, size hint[4]
    MakeNum2,         // register, element count, first element
    MakeNum4,         // register, element count, first element
    MakeIterator,     // register, range
    Function,         // register, arg count, capture count, flags, size[2]
    Capture,          // function, target, source
    LoadCapture,      // register, capture
    SetCapture,       // capture, source
    Range,            // register, start, end
    RangeInclusive,   // register, start, end
    RangeTo,          // register, end
    RangeToInclusive, // register, end
    RangeFrom,        // register, start
    RangeFull,        // register
    Negate,           // register, source
    Add,              // result, lhs, rhs
    Subtract,         // result, lhs, rhs
    Multiply,         // result, lhs, rhs
    Divide,           // result, lhs, rhs
    Modulo,           // result, lhs, rhs
    Less,             // result, lhs, rhs
    LessOrEqual,      // result, lhs, rhs
    Greater,          // result, lhs, rhs
    GreaterOrEqual,   // result, lhs, rhs
    Equal,            // result, lhs, rhs
    NotEqual,         // result, lhs, rhs
    Jump,             // offset[2]
    JumpTrue,         // condition, offset[2]
    JumpFalse,        // condition, offset[2]
    JumpBack,         // offset[2]
    JumpBackFalse,    // offset[2]
    Call,             // result, function, arg register, arg count
    CallChild,        // result, function, arg register, arg count, parent
    Return,           // register
    Yield,            // register
    IterNext,         // output, iterator, jump offset[2]
    IterNextTemp,     // output, iterator, jump offset[2]
    IterNextQuiet,    // iterator, jump offset[2]
    ValueIndex,       // result, value register, signed index
    SliceFrom,        // result, value register, signed index
    SliceTo,          // result, value register, signed index
    ListPushValue,    // list, value
    ListPushValues,   // list, start register, count
    ListUpdate,       // list, index, value
    Index,            // result, list register, index register
    MapInsert,        // map register, value register, key constant
    MapInsertLong,    // map register, value register, key constant[4]
    Access,           // register, value register, key
    AccessLong,       // register, value register, key[4]
    IsList,           // register, value
    IsTuple,          // register, value
    Size,             // register, value
    TryStart,         // catch arg register, catch body offset[2]
    TryEnd,           //
    Debug,            // register, constant[4]
    Unused78,
    Unused79,
    Unused80,
    Unused81,
    Unused82,
    Unused83,
    Unused84,
    Unused85,
    Unused86,
    Unused87,
    Unused88,
    Unused89,
    Unused90,
    Unused91,
    Unused92,
    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) }
    }
}

struct FunctionFlags {
    instance_function: bool,
    variadic: bool,
    generator: bool,
}

impl FunctionFlags {
    pub const INSTANCE: u8 = 0b0000001;
    pub const VARIADIC: u8 = 0b0000010;
    pub const GENERATOR: u8 = 0b0000100;

    pub fn from_byte(byte: u8) -> Self {
        Self {
            instance_function: byte & Self::INSTANCE == Self::INSTANCE,
            variadic: byte & Self::VARIADIC == Self::VARIADIC,
            generator: byte & Self::GENERATOR == Self::GENERATOR,
        }
    }

    pub fn as_byte(&self) -> u8 {
        let mut result = 0;
        if self.instance_function {
            result |= Self::INSTANCE;
        }
        if self.variadic {
            result |= Self::VARIADIC;
        }
        if self.generator {
            result |= Self::GENERATOR;
        }
        result
    }
}

/// Debug information for a Koto program
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DebugInfo {
    source_map: Vec<(usize, Span)>,
    /// The source of the program that the debug info was derived from
    pub source: String,
}

impl DebugInfo {
    fn push(&mut self, ip: usize, span: Span) {
        if let Some(entry) = self.source_map.last() {
            if entry.1 == span {
                // Don't add entries with matching spans, a search is performed in
                // get_source_span which will find the correct span
                // for intermediate ips.
                return;
            }
        }
        self.source_map.push((ip, span));
    }

    /// Returns a source span for a given instruction pointer
    pub fn get_source_span(&self, ip: usize) -> Option<Span> {
        // Find the last entry with an ip less than or equal to the input
        // an upper_bound would nice here, but this isn't currently a performance sensitive function
        // so a scan through the entries will do.
        let mut result = None;
        for entry in self.source_map.iter() {
            if entry.0 <= ip {
                result = Some(entry.1);
            } else {
                break;
            }
        }
        result
    }
}

/// A compiled chunk of bytecode, along with its associated constants and metadata
#[derive(Clone, Debug, PartialEq)]
pub struct Chunk {
    /// The bytes representing the chunk's bytecode
    pub bytes: Vec<u8>,
    /// The constant data associated with the chunk's bytecode
    pub constants: ConstantPool,
    /// The constant string data associated with the chunk's bytecode
    pub string_constants_arc: Arc<str>,
    /// The path of the program's source file
    pub source_path: Option<PathBuf>,
    /// Debug information associated with the chunk's bytecode
    pub debug_info: DebugInfo,
}

impl Default for Chunk {
    fn default() -> Self {
        Self {
            bytes: vec![],
            constants: ConstantPool::default(),
            string_constants_arc: String::default().into(),
            source_path: None,
            debug_info: DebugInfo::default(),
        }
    }
}

impl Chunk {
    pub fn new(
        bytes: Vec<u8>,
        constants: ConstantPool,
        source_path: Option<PathBuf>,
        debug_info: DebugInfo,
    ) -> Self {
        Self {
            bytes,
            string_constants_arc: constants.string_data().into(),
            constants,
            source_path,
            debug_info,
        }
    }
}

/// Returns a [String] displaying the instructions contained in the compiled [Chunk]
pub fn chunk_to_string(chunk: Arc<Chunk>) -> String {
    let mut result = String::new();
    let mut reader = InstructionReader::new(chunk);
    let mut ip = reader.ip;

    while let Some(instruction) = reader.next() {
        result += &format!("{}\t{}\n", ip, &instruction.to_string());
        ip = reader.ip;
    }

    result
}

/// Returns a [String] displaying the annotated instructions contained in the compiled [Chunk]
pub fn chunk_to_string_annotated(chunk: Arc<Chunk>, source_lines: &[&str]) -> String {
    let mut result = String::new();
    let mut reader = InstructionReader::new(chunk);
    let mut ip = reader.ip;
    let mut span: Option<Span> = None;
    let mut first = true;

    while let Some(instruction) = reader.next() {
        let instruction_span = reader
            .chunk
            .debug_info
            .get_source_span(ip)
            .expect("Missing source span");

        let print_source_lines = if let Some(span) = span {
            instruction_span.start.line != span.start.line
        } else {
            true
        };

        if print_source_lines && !source_lines.is_empty() {
            if !first {
                result += "\n";
            }
            first = false;

            let line = instruction_span
                .start
                .line
                .min(source_lines.len() as u32)
                .max(1) as usize;
            result += &format!("|{}| {}\n", line.to_string(), source_lines[line - 1]);
            span = Some(instruction_span);
        }

        result += &format!("{}\t{:?}\n", ip, &instruction);
        ip = reader.ip;
    }

    result
}