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
use std::mem;

use crate::common::number::build_number;
use crate::common::data::Data;
use crate::common::opcode::Opcode;
use crate::vm::trace::Trace;
use crate::vm::tag::Tagged;
use crate::vm::stack::{Item, Stack};
use crate::vm::local::Local;
use crate::compiler::gen::Chunk; // TODO: Move chunk to a better spot?

/// A `VM` executes bytecode chunks.
/// Each VM's state is self-contained,
/// So more than one can be spawned if needed.
#[derive(Debug)]
pub struct VM {
    chunk: Chunk,
    stack: Stack,
    ip:    usize,
}

// NOTE: use Opcode::same and Opcode.to_byte() rather than actual bytes
// Don't worry, the compiler *should* get rid of this overhead and just use bytes

// this impl contains initialization, helper functions, and the core interpreter loop
// the next impl contains opcode implementations
impl VM {
    /// Initialize a new VM.
    /// To run the VM, a chunk must be passed to it through `run`.
    pub fn init() -> VM {
        VM {
            chunk: Chunk::empty(),
            stack: vec![Item::Frame],
            ip:    0,
        }
    }


    fn next(&mut self)                           { self.ip += 1; }
    fn terminate(&mut self) -> Result<(), Trace> { self.ip = self.chunk.code.len(); Ok(()) }
    fn done(&mut self)      -> Result<(), Trace> { self.next(); Ok(()) }
    fn peek_byte(&mut self) -> u8                { self.chunk.code[self.ip] }
    fn next_byte(&mut self) -> u8                { self.done().unwrap(); self.peek_byte() }

    /// Builds the next number in the bytecode stream.
    /// See `utils::number` for more.
    fn next_number(&mut self) -> usize {
        self.next();
        let remaining      = self.chunk.code[self.ip..].to_vec();
        let (index, eaten) = build_number(remaining);
        self.ip += eaten - 1; // ip left on next op
        println!("{}", index);
        return index;
    }

    /// Finds a local on stack.
    /// Note that in the future, locals should be pre-indexed when the AST is walked
    /// so this function won't be necessary then.
    fn find_local(&mut self, local: &Local) -> Option<usize> {
        for (index, item) in self.stack.iter().enumerate().rev() {
            match item {
                Item::Local { local: l, .. } => if local == l { return Some(index); },
                Item::Frame                  => break,
                Item::Data(_)                => (),
            }
        }

        return None;
    }

    /// finds the index of the local on the stack indicated by the bytecode.
    fn local_index(&mut self) -> (Local, Option<usize>) {
        let local_index = self.next_number();
        let local       = self.chunk.locals[local_index].clone();
        let index       = self.find_local(&local);

        return (local, index);
    }

    // core interpreter loop

    /// Dissasembles and interprets a single (potentially fallible) bytecode op.
    /// The op definitions follow in the proceeding impl block.
    /// To see what each op does, check `pipeline::bytecode.rs`
    fn step(&mut self) -> Result<(), Trace> {
        let op_code = Opcode::from_byte(self.peek_byte());

        match op_code {
            Opcode::Con    => self.con(),
            Opcode::Save   => self.save(),
            Opcode::Load   => self.load(),
            Opcode::Clear  => self.clear(),
            Opcode::Call   => self.call(),
            Opcode::Return => self.return_val(),
        }
    }

    /// Suspends the current chunk and runs a new one on the VM.
    /// Runs until either success, in which it restores the state of the previous chunk,
    /// Or failure, in which it returns the runtime error.
    /// In the future, fibers will allow for error handling -
    /// right now, error in Passerine are practically panics.
    fn run(&mut self, chunk: Chunk) -> Result<(), Trace> {
        // cache current state, load new bytecode
        let old_chunk = mem::replace(&mut self.chunk, chunk);
        let old_ip    = mem::replace(&mut self.ip,    0);
        // TODO: should chunks store their own ip?

        while self.ip < self.chunk.code.len() {
            println!("before: {:?}", self.stack);
            println!("executing: {:?}", Opcode::from_byte(self.peek_byte()));
            println!("---");
            self.step()?;
        }

        // return current state
        mem::drop(mem::replace(&mut self.chunk, old_chunk));
        self.ip = old_ip;

        // nothing went wrong!
        return Result::Ok(());
    }
}

// TODO: there are a lot of optimizations that can be made
// I'll list a few here:
// - searching the stack for variables
//   A global Hash-table has significantly less overhead for function calls
// - cloning the heck out of everything - useless copies
//   instead, lifetime analysis during compilation
// - replace some panics with Result<()>s
impl VM {
    /// Load a constant and push it onto the stack.
    fn con(&mut self) -> Result<(), Trace> {
        // get the constant index
        let index = self.next_number();

        self.stack.push(Item::Data(Tagged::new(self.chunk.constants[index].clone())));
        self.done()
    }

    /// Save the topmost value on the stack into a variable.
    fn save(&mut self) -> Result<(), Trace> {
        let data = match self.stack.pop() { Some(Item::Data(d)) => d.data(), _ => panic!("Expected data") };
        let (local, index) = self.local_index();

        // NOTE: Does it make a copy or does it make a reference?
        // It makes a copy of the data
        match index {
            // It's been declared
            Some(i) => mem::drop(
                mem::replace(
                    &mut self.stack[i],
                    Item::Local { local, data },
                )
            ),
            // It hasn't been declared
            None => self.stack.push(Item::Local { local, data }),
        }

        // TODO: make separate byte code op?
        self.stack.push(Item::Data(Tagged::new(Data::Unit)));

        self.done()
    }

    /// Push a copy of a variable's value onto the stack.
    fn load(&mut self) -> Result<(), Trace> {
        let (_, index) = self.local_index();

        match index {
            Some(i) => {
                if let Item::Local { data, .. } = &self.stack[i] {
                    let data = Item::Data(Tagged::new(data.clone()));
                    self.stack.push(data);
                }
            },
            None => panic!("Local not found on stack!"), // TODO: make it a Passerine error
        }

        self.done()
    }

    /// Clear all data off the stack.
    fn clear(&mut self) -> Result<(), Trace> {
        loop {
            match self.stack.pop() {
                Some(Item::Data(_)) => (),
                Some(l)             => { self.stack.push(l); break; },
                None                => panic!("There wasn't a frame on the stack.")
            }
        }

        self.done()
    }

    /// Call a function on the top of the stack, passing the next value as an argument.
    fn call(&mut self) -> Result<(), Trace> {
        let fun = match self.stack.pop() {
            Some(Item::Data(d)) => match d.data() {
                Data::Lambda(l) => l,
                _               => unreachable!(),
            }
            _ => unreachable!(),
        };
        let arg = match self.stack.pop() {
            Some(Item::Data(d)) => d,
            _                   => unreachable!(),
        };

        self.stack.push(Item::Frame);
        self.stack.push(Item::Data(arg));
        println!("entering...");
        self.run(fun)?;
        println!("exiting...");

        self.done()
    }

    /// Return a value from a function.
    /// End the execution of the current chunk.
    /// Relpaces the last frame with the value on the top of the stack.
    fn return_val(&mut self) -> Result<(), Trace> {
        let val = match self.stack.pop() {
            Some(Item::Data(d)) => d,
            _                   => unreachable!(),
        };

        loop {
            match self.stack.pop() {
                Some(Item::Frame) => break,
                None              => unreachable!("There should never not be a frame on the stack"),
                _                 => (),
            }
        }

        self.stack.push(Item::Data(val));
        self.terminate()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::compiler::{
        parse::parse,
        lex::lex,
        gen::gen,
    };
    use crate::common::source::Source;

    #[test]
    fn init_run() {
        // TODO: check @ each step, write more tests
        let chunk = gen(parse(lex(
            Source::source("boop = 37.201; true; dhuiew = true; boop")
        ).unwrap()).unwrap());

        let mut vm = VM::init();

        match vm.run(chunk) {
            Ok(_)  => (),
            Err(e) => eprintln!("{}", e),
        }
    }

    #[test]
    fn block_expression() {
        let chunk = gen(parse(lex(
            Source::source("boop = true; heck = { x = boop; x }; heck")
        ).unwrap()).unwrap());

        let mut vm = VM::init();

        match vm.run(chunk) {
            Ok(_)  => (),
            Err(e) => eprintln!("{}", e),
        }

        if let Some(Item::Data(t)) = vm.stack.pop() {
            match t.data() {
                Data::Boolean(true) => (),
                _                   => panic!("Expected true value"),
            }
        } else {
            panic!("Expected data on top of stack");
        }
    }

    #[test]
    fn functions() {
        let chunk = gen(parse(lex(
            Source::source("iden = x -> x; y = true; iden ((iden iden) (iden y))")
        ).unwrap()).unwrap());

        let mut vm = VM::init();
        match vm.run(chunk) {
            Ok(_)  => (),
            Err(e) => eprintln!("{}", e),
        }

        if let Some(Item::Data(t)) = vm.stack.pop() {
            assert_eq!(t.data(), Data::Boolean(true));
        } else {
            panic!("Expected float on top of stack");
        }
    }

    #[test]
    fn fun_scope() {
        let chunk = gen(parse(lex(
            Source::source("y = (x -> { z = x; z }) 7.0; y")
        ).unwrap().into()).unwrap());

        println!("{:#?}", chunk);

        let out_of_scope = Local::new("z".to_string());

        let mut vm = VM::init();
        match vm.run(chunk) {
            Ok(_)  => (),
            Err(e) => eprintln!("{}", e),
        }

        // check that z has been dealloced
        assert_eq!(vm.find_local(&out_of_scope), None);

        // check that y is in fact 7
        if let Some(Item::Data(t)) = vm.stack.pop() {
            assert_eq!(t.data(), Data::Real(7.0));
        } else {
            panic!("Expected 7.0 on top of stack");
        }
    }
}