~cdv/loxen

ref: bba9ce3300c5bae29961fe8617fc0d173c430afe loxen/rs/src/vm.rs -rw-r--r-- 5.7 KiB
bba9ce33Chris Vittal [relox] Many changes, notably, strings. 1 year, 6 months ago
                                                                                
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
use std::{convert::TryFrom, fmt};

use byteorder::{ReadBytesExt, LE};

use crate::{chunk::*, object::*, value::Value, Error};

use Op::*;

#[derive(Default)]
pub struct VM {
    chunk: Box<Chunk>,
    stack: Vec<Value>,
    heap: Heap,
    ip: usize,
}

impl VM {
    pub fn interpret(&mut self, source: &str) -> Result<(), Error> {
        let chunk = crate::compiler::compile(source, &mut self.heap)?;
        self.interpret_chunk(chunk)
    }

    fn interpret_chunk(&mut self, mut chunk: Box<Chunk>) -> Result<(), Error> {
        std::mem::swap(&mut self.chunk, &mut chunk);
        self.ip = 0;
        self.stack.clear();

        self.run()
    }

    fn runtime_error(&self, err: fmt::Arguments) -> Result<(), Error> {
        eprintln!("{}", err);
        eprintln!("[line {}] in script", self.chunk.get_line(self.ip));
        Err(Error::Runtime)
    }

    fn concatenate(&mut self, sa: Oid, sb: Oid) {
        let new_s = match (&self.heap[sa], &self.heap[sb]) {
            (Obj::Str(ref a), Obj::Str(ref b)) => {
                let mut a = String::from(a.as_ref());
                a += &b;
                a
            }
            _ => unreachable!(),
        };
        self.pop();
        self.pop();
        let oid = self.heap.take_string(new_s);
        self.push(Value::Str(oid));
    }

    fn run(&mut self) -> Result<(), Error> {
        macro_rules! binary_op {
            ($op:tt) => {
                if !self.peek(0).is_num() || !self.peek(1).is_num() {
                    self.runtime_error(format_args!("Operands must be numbers"))?;
                }

                let b = self.pop();
                let a = self.pop();
                match (a, b) {
                    (Value::Num(a), Value::Num(b)) => self.push(a $op b),
                    _ => unreachable!()
                }
            }
        }
        #[cfg(debug_assertions)]
        let mut prev_line = u32::MAX;
        loop {
            let op = self.read_op();
            #[cfg(debug_assertions)]
            {
                if !self.stack.is_empty() {
                    print!("          ");
                }
                for v in &self.stack {
                    print!("[ {} ]", self.vfmt(v));
                }
                println!();
                op.disassemble(&self.chunk, self.ip - 1, &mut prev_line);
            }
            match op {
                Constant | ConstantLong => {
                    let v = self.read_constant(op);
                    self.push(v);
                }
                Nil => self.push(Value::Nil),
                True => self.push(true),
                False => self.push(false),
                Equal => {
                    let b = self.pop();
                    let a = self.pop();
                    self.push(a == b);
                }
                Greater => {
                    binary_op!(>);
                }
                Less => {
                    binary_op!(<);
                }
                Add => match (self.peek(1), self.peek(0)) {
                    (&Value::Str(sa), &Value::Str(sb)) => self.concatenate(sa, sb),
                    (&Value::Num(a), &Value::Num(b)) => {
                        self.pop();
                        self.pop();
                        self.push(a + b);
                    }
                    _ => todo!(),
                },
                Sub => {
                    binary_op!(-);
                }
                Mul => {
                    binary_op!(*);
                }
                Div => {
                    binary_op!(/);
                }
                Not => {
                    let v = self.pop();
                    self.push(v.is_falsey())
                }
                Negate => {
                    if !self.peek(0).is_num() {
                        self.runtime_error(format_args!("Operand must be a number"))?;
                    }

                    if let Value::Num(v) = self.pop() {
                        self.push(-v);
                    } else {
                        unreachable!();
                    }
                }
                Return => {
                    let v = self.pop();
                    println!("{}", self.vfmt(&v));
                    return Ok(());
                }
            }
        }
    }

    fn read_constant(&mut self, op: Op) -> Value {
        match op {
            Constant => {
                let cid = self.read_byte() as usize;
                self.chunk.constants[cid]
            }
            ConstantLong => {
                let nip = self.ip + 3;
                let mut cid_buf = &self.chunk[self.ip..nip];
                self.ip = nip;

                let cid = cid_buf.read_u24::<LE>().expect("cannot fail");
                self.chunk.constants[cid as usize]
            }
            _ => panic!("Invalid argument, {:?}", op),
        }
    }

    fn read_byte(&mut self) -> u8 {
        self.ip += 1;
        self.chunk[self.ip - 1]
    }

    fn read_op(&mut self) -> Op {
        Op::try_from(self.read_byte()).expect("Invalid Opcode")
    }

    fn push<V: Into<Value>>(&mut self, v: V) {
        self.stack.push(v.into());
    }

    fn pop(&mut self) -> Value {
        self.stack.pop().expect("Attempted to pop from empty stack")
    }

    fn peek(&self, dist: usize) -> &Value {
        &self.stack[self.stack.len() - dist - 1]
    }

    fn vfmt<'vm>(&'vm self, v: &'vm Value) -> VRef {
        VRef {
            heap: &self.heap,
            value: v,
        }
    }
}

struct VRef<'vm> {
    heap: &'vm Heap,
    value: &'vm Value,
}

impl fmt::Display for VRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.value {
            Value::Str(oid) => write!(f, "{}", self.heap[*oid]),
            v => write!(f, "{}", v),
        }
    }
}