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
use std::mem;
use crate::common::{
number::build_number,
data::Data,
opcode::Opcode,
lambda::Lambda,
closure::Closure,
};
use crate::vm::{
trace::Trace,
stack::Stack,
};
#[derive(Debug)]
pub struct VM {
closure: Closure,
stack: Stack,
ip: usize,
}
impl VM {
pub fn init() -> VM {
VM {
closure: Closure::wrap(Lambda::empty()),
stack: Stack::init(),
ip: 0,
}
}
pub fn next(&mut self) { self.ip += 1; }
pub fn terminate(&mut self) -> Result<(), Trace> { self.ip = self.closure.lambda.code.len(); Ok(()) }
pub fn done(&mut self) -> Result<(), Trace> { self.next(); Ok(()) }
pub fn peek_byte(&mut self) -> u8 { self.closure.lambda.code[self.ip] }
pub fn next_byte(&mut self) -> u8 { self.next(); self.peek_byte() }
pub fn next_number(&mut self) -> usize {
self.next();
let remaining = &self.closure.lambda.code[self.ip..];
let (index, eaten) = build_number(remaining);
self.ip += eaten - 1;
return index;
}
pub fn step(&mut self) -> Result<(), Trace> {
let opcode = Opcode::from_byte(self.peek_byte());
match opcode {
Opcode::Con => self.con(),
Opcode::Del => self.del(),
Opcode::Capture => self.capture(),
Opcode::Save => self.save(),
Opcode::SaveCap => self.save_cap(),
Opcode::Load => self.load(),
Opcode::LoadCap => self.load_cap(),
Opcode::Call => self.call(),
Opcode::Return => self.return_val(),
Opcode::Closure => self.closure(),
Opcode::Print => self.print(),
}
}
pub fn run(&mut self, closure: Closure) -> Result<(), Trace> {
let old_closure = mem::replace(&mut self.closure, closure);
let old_ip = mem::replace(&mut self.ip, 0);
let mut result = Ok(());
while self.ip < self.closure.lambda.code.len() {
if let error @ Err(_) = self.step() {
result = error;
break;
};
}
mem::drop(mem::replace(&mut self.closure, old_closure));
self.ip = old_ip;
return result;
}
pub fn con(&mut self) -> Result<(), Trace> {
let index = self.next_number();
self.stack.push_data(self.closure.lambda.constants[index].clone());
self.done()
}
pub fn capture(&mut self) -> Result<(), Trace> {
let index = self.next_number();
let reference = self.stack.heapify(index);
self.closure.captureds.push(reference);
self.done()
}
pub fn save(&mut self) -> Result<(), Trace> {
let index = self.next_number();
self.stack.set_local(index);
self.done()
}
pub fn save_cap(&mut self) -> Result<(), Trace> {
let index = self.next_number();
let data = self.stack.pop_data();
mem::drop(self.closure.captureds[index].replace(data));
self.done()
}
pub fn load(&mut self) -> Result<(), Trace> {
let index = self.next_number();
self.stack.get_local(index);
self.done()
}
pub fn load_cap(&mut self) -> Result<(), Trace> {
let index = self.next_number();
self.stack.push_data(Data::Heaped(self.closure.captureds[index].clone()));
self.done()
}
pub fn del(&mut self) -> Result<(), Trace> {
mem::drop(self.stack.pop_data());
self.done()
}
pub fn print(&mut self) -> Result<(), Trace> {
let data = self.stack.pop_data();
println!("{}", data);
self.stack.push_data(data);
self.done()
}
pub fn call(&mut self) -> Result<(), Trace> {
let fun = match self.stack.pop_data() {
Data::Closure(c) => c,
o => return Err(Trace::error(
"Call",
&format!("The data '{}' is not a function and can not be called", o),
vec![self.closure.lambda.index_span(self.ip)],
)),
};
let arg = self.stack.pop_data();
self.stack.push_frame();
self.stack.push_data(arg);
match self.run(fun) {
Ok(()) => (),
Err(mut trace) => {
trace.add_context(self.closure.lambda.index_span(self.ip));
return Err(trace);
},
};
self.done()
}
pub fn return_val(&mut self) -> Result<(), Trace> {
let val = self.stack.pop_data();
let locals = self.next_number();
for _ in 0..locals { self.del()?; }
self.stack.pop_frame();
self.stack.push_data(val);
self.terminate()
}
pub fn closure(&mut self) -> Result<(), Trace> {
let index = self.next_number();
let lambda = match self.closure.lambda.constants[index].clone() {
Data::Lambda(lambda) => lambda,
_ => unreachable!("Expected a lambda to be wrapped with a closure"),
};
let mut closure = Closure::wrap(lambda);
for upvalue in closure.lambda.captureds.iter().rev() {
closure.captureds.push(self.closure.captureds[*upvalue].clone())
}
self.stack.push_data(Data::Closure(closure));
self.done()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::compiler::{
parse::parse,
lex::lex,
gen::gen,
};
use crate::common::source::Source;
fn inspect(source: &str) -> VM {
let lambda = lex(Source::source(source))
.and_then(parse)
.and_then(gen)
.map_err(|e| println!("{}", e))
.unwrap();
let mut vm = VM::init();
match vm.run(Closure::wrap(lambda)) {
Ok(()) => vm,
Err(e) => {
println!("{}", e);
panic!();
},
}
}
#[test]
fn init_run() {
inspect("x = 0.0");
}
#[test]
fn block_expression() {
inspect("x = false; boop = true; heck = { x = boop; x }; heck");
}
#[test]
fn functions() {
let mut vm = inspect("iden = x -> x; y = true; iden ({y = false; iden iden} (iden y))");
let identity = vm.stack.pop_data();
assert_eq!(identity, Data::Boolean(true));
}
#[test]
fn fun_scope() {
let mut vm = inspect("one = 1.0\npi = 3.14\ne = 2.72\n\nx = w -> pi\nx 37.6");
let pi = vm.stack.pop_data();
assert_eq!(pi, Data::Real(3.14));
}
#[test]
fn mutate_capture() {
inspect("odd = (); even = x -> odd; odd = 1.0; even (); odd");
}
#[test]
fn mutate_capture_fn() {
inspect("\
pi = 3.14\n\
printpi = x -> print pi\n\
\n\
redef = ()\n\
redef = w -> {\n \
w (printpi ())\n\
}\n\
\n\
redef printpi\n\
");
}
}