marwood 0.3.1

Scheme R5RS Virtual Machine
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
use crate::number::Number;
use crate::vm::char::write_escaped_char;
use crate::vm::continuation::Continuation;
use crate::vm::environment::LexicalEnvironment;
use crate::vm::lambda::Lambda;
use crate::vm::opcode::OpCode;
use crate::vm::transform::Transform;
use crate::vm::vector::Vector;
use crate::vm::Error::ExpectedType;
use crate::vm::{Error, Vm};
use std::cell::RefCell;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use std::rc::Rc;

/// VCell
///
/// VCell is a 24 byte (3x64bit) type that's used to represent values
/// in the VM runtime.
///
/// * Primitive list values (bool, fixednum, pairs, nil, etc)
/// * Opcodes
/// * References into the heap (Ptr)
/// * Global and lexical environment slot references (EnvSlot)
/// * Other runtime sentinel values, such as Undefined and Void.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VCell {
    // Scheme primitive types
    Bool(bool),
    Char(char),
    Nil,
    Number(Number),
    Pair(usize, usize),
    Symbol(Rc<String>),
    String(Rc<RefCell<String>>),
    Vector(Rc<Vector>),

    // other scheme values
    Undefined,
    Void,

    // lambda, closure and lexical environments
    Continuation(Rc<Continuation>),
    Closure(usize, usize),
    Lambda(Rc<Lambda>),
    LexicalEnv(Rc<LexicalEnvironment>),
    LexicalEnvSlot(usize),
    LexicalEnvPtr(usize, usize),
    Macro(Rc<Transform>),

    // VM registers and stack values
    Acc,
    ArgumentCount(usize),
    BasePointer(usize),
    BasePointerOffset(i64),
    BuiltInProc(BuiltInProc),
    EnvironmentPointer(usize),
    GlobalEnvSlot(usize),
    InstructionPointer(usize, usize),
    OpCode(OpCode),
    Ptr(usize),
}

#[derive(Clone)]
pub struct BuiltInProc(pub fn(&mut Vm) -> Result<VCell, Error>);

impl Debug for BuiltInProc {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "VCell::SysCall")
    }
}

impl PartialEq<Self> for BuiltInProc {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.0 as *mut fn(&mut Vm), other.0 as *mut fn(&mut Vm))
    }
}

impl Eq for BuiltInProc {}

pub const ACC_TYPE_TEXT: &str = "#<acc>";
pub const ARGUMENT_COUNT_TYPE_TEXT: &str = "#<argument-count>";
pub const BASE_POINTER_TYPE_TEXT: &str = "#<base-pointer>";
pub const BASE_POINTER_OFFSET_TYPE_TEXT: &str = "#<base-pointer-offset>";
pub const BOOL_TYPE_TEXT: &str = "#<bool>";
pub const CHAR_TYPE_TEXT: &str = "#<char>";
pub const CLOSURE_TYPE_TEXT: &str = "#<closure>";
pub const CONTINUATION_TYPE_TEXT: &str = "#<continuation>";
pub const GLOBAL_ENV_SLOT_TYPE_TEXT: &str = "#<global-environment-slot>";
pub const ENVIRONMENT_POINTER_TYPE_TEXT: &str = "#<environment-pointer>";
pub const MACRO_TYPE_TEXT: &str = "#<macro>";
pub const LEXICAL_ENV_TYPE_TEXT: &str = "#<lexical-environment>";
pub const LEXICAL_ENV_TYPE_SLOT: &str = "#<lexical-environment-slot>";
pub const LEXICAL_ENV_POINTER_TYPE_TEXT: &str = "#<lexical-environment-pointer>";
pub const FIXEDNUM_TYPE_TEXT: &str = "#<fixednum>";
pub const INSTRUCTION_POINTER_TYPE_TEXT: &str = "#<instruction-pointer>";
pub const NUMBER_TYPE_TEXT: &str = "#<number>";
pub const LAMBDA_TYPE_TEXT: &str = "#<lambda>";
pub const NIL_TYPE_TEXT: &str = "#<nil>";
pub const OPCODE_TYPE_TEXT: &str = "#<opcode>";
pub const PAIR_TYPE_TEXT: &str = "#<pair>";
pub const PTR_TYPE_TEXT: &str = "#<ptr>";
pub const STRING_TYPE_TEXT: &str = "#<string>";
pub const SYMBOL_TYPE_TEXT: &str = "#<symbol>";
pub const SYSCALL_TYPE_TEXT: &str = "#<syscall>";
pub const UNDEFINED_TYPE_TEXT: &str = "#<undefined>";
pub const VECTOR_TYPE_TEXT: &str = "#<vector>";
pub const VOID_TYPE_TEXT: &str = "#<void>";

impl VCell {
    /// TYPE_TEXT Text
    ///
    /// TYPE_TEXT text is only used during error paths to print
    /// the TYPE_TEXT of a VCell
    pub fn type_text(&self) -> &'static str {
        match self {
            VCell::Acc => ACC_TYPE_TEXT,
            VCell::ArgumentCount(_) => ARGUMENT_COUNT_TYPE_TEXT,
            VCell::BasePointer(_) => BASE_POINTER_TYPE_TEXT,
            VCell::BasePointerOffset(_) => BASE_POINTER_OFFSET_TYPE_TEXT,
            VCell::Bool(_) => BOOL_TYPE_TEXT,
            VCell::Char(_) => CHAR_TYPE_TEXT,
            VCell::Continuation(_) => CONTINUATION_TYPE_TEXT,
            VCell::Closure(_, _) => CLOSURE_TYPE_TEXT,
            VCell::EnvironmentPointer(_) => ENVIRONMENT_POINTER_TYPE_TEXT,
            VCell::GlobalEnvSlot(_) => GLOBAL_ENV_SLOT_TYPE_TEXT,
            VCell::LexicalEnv(_) => LEXICAL_ENV_TYPE_TEXT,
            VCell::LexicalEnvSlot(_) => LEXICAL_ENV_TYPE_SLOT,
            VCell::LexicalEnvPtr(_, _) => LEXICAL_ENV_POINTER_TYPE_TEXT,
            VCell::InstructionPointer(_, _) => INSTRUCTION_POINTER_TYPE_TEXT,
            VCell::Lambda(_) => LAMBDA_TYPE_TEXT,
            VCell::Nil => NIL_TYPE_TEXT,
            VCell::Number(_) => NUMBER_TYPE_TEXT,
            VCell::OpCode(_) => OPCODE_TYPE_TEXT,
            VCell::Pair(_, _) => PAIR_TYPE_TEXT,
            VCell::Ptr(_) => PTR_TYPE_TEXT,
            VCell::String(_) => STRING_TYPE_TEXT,
            VCell::Symbol(_) => SYMBOL_TYPE_TEXT,
            VCell::BuiltInProc(_) => SYSCALL_TYPE_TEXT,
            VCell::Macro(_) => MACRO_TYPE_TEXT,
            VCell::Undefined => UNDEFINED_TYPE_TEXT,
            VCell::Vector(_) => VECTOR_TYPE_TEXT,
            VCell::Void => VOID_TYPE_TEXT,
        }
    }

    pub fn number<T: Into<Number>>(num: T) -> VCell {
        VCell::Number(num.into())
    }

    pub fn syscall(func: fn(&mut Vm) -> Result<VCell, Error>) -> VCell {
        VCell::BuiltInProc(BuiltInProc(func))
    }

    pub fn undefined() -> VCell {
        VCell::Undefined
    }

    pub fn void() -> VCell {
        VCell::Void
    }

    pub fn ptr(val: usize) -> VCell {
        VCell::Ptr(val)
    }

    pub fn pair(car: usize, cdr: usize) -> VCell {
        VCell::Pair(car, cdr)
    }

    pub fn env_slot<T: Into<usize>>(slot: T) -> VCell {
        VCell::GlobalEnvSlot(slot.into())
    }

    pub fn string<T: Into<String>>(s: T) -> VCell {
        VCell::String(Rc::new(RefCell::new(s.into())))
    }

    pub fn symbol<T: Into<String>>(sym: T) -> VCell {
        VCell::Symbol(Rc::new(sym.into()))
    }

    pub fn vector<T: Into<Vec<VCell>>>(vector: T) -> VCell {
        VCell::Vector(Rc::new(Vector::new(vector.into())))
    }

    pub fn lambda<T: Into<Lambda>>(lambda: T) -> VCell {
        VCell::Lambda(Rc::new(lambda.into()))
    }

    pub fn nil() -> VCell {
        VCell::Nil
    }

    pub fn is_boolean(&self) -> bool {
        matches!(self, VCell::Bool(_))
    }

    pub fn is_number(&self) -> bool {
        matches!(self, VCell::Number(_))
    }

    pub fn is_string(&self) -> bool {
        matches!(self, VCell::String(_))
    }

    pub fn is_char(&self) -> bool {
        matches!(self, VCell::Char(_))
    }

    pub fn is_pair(&self) -> bool {
        matches!(self, VCell::Pair(_, _))
    }

    pub fn is_symbol(&self) -> bool {
        matches!(self, VCell::Symbol(_))
    }

    pub fn is_ptr(&self) -> bool {
        matches!(self, VCell::Ptr(_))
    }

    pub fn is_envslot(&self) -> bool {
        matches!(self, VCell::GlobalEnvSlot(_))
    }

    pub fn is_reference(&self) -> bool {
        self.is_ptr() || self.is_envslot()
    }

    pub fn is_undefined(&self) -> bool {
        *self == VCell::Undefined
    }

    pub fn is_nil(&self) -> bool {
        *self == VCell::Nil
    }

    pub fn is_opcode(&self) -> bool {
        matches!(self, VCell::OpCode(_))
    }

    pub fn is_lambda(&self) -> bool {
        matches!(self, VCell::Lambda(_))
    }

    pub fn is_closure(&self) -> bool {
        matches!(self, VCell::Closure(_, _))
    }

    pub fn is_builtin_proc(&self) -> bool {
        matches!(self, VCell::BuiltInProc(_))
    }

    pub fn is_procedure(&self) -> bool {
        self.is_lambda() || self.is_closure() || self.is_builtin_proc()
    }

    pub fn is_lexical_env(&self) -> bool {
        matches!(self, VCell::LexicalEnv(_))
    }

    pub fn is_macro(&self) -> bool {
        matches!(self, VCell::Macro(_))
    }

    pub fn is_vector(&self) -> bool {
        matches!(self, VCell::Vector(_))
    }

    pub fn as_opcode(&self) -> Result<OpCode, Error> {
        match self {
            VCell::OpCode(op) => Ok(op.clone()),
            _ => Err(ExpectedType(OPCODE_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_car(&self) -> Result<VCell, Error> {
        match self {
            VCell::Pair(car, _) => Ok(VCell::Ptr(*car)),
            _ => Err(ExpectedType(PAIR_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_cdr(&self) -> Result<VCell, Error> {
        match self {
            VCell::Pair(_, cdr) => Ok(VCell::Ptr(*cdr)),
            _ => Err(ExpectedType(PAIR_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_symbol(&self) -> Result<&str, Error> {
        match self {
            VCell::Symbol(s) => Ok(&*s),
            _ => Err(ExpectedType(SYMBOL_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_string(&self) -> Result<&RefCell<String>, Error> {
        match self {
            VCell::String(s) => Ok(&*s),
            _ => Err(ExpectedType(SYMBOL_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_lambda(&self) -> Result<&Lambda, Error> {
        match self {
            VCell::Lambda(lambda) => Ok(&*lambda),
            _ => Err(ExpectedType(LAMBDA_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_macro(&self) -> Result<&Transform, Error> {
        match self {
            VCell::Macro(transform) => Ok(&*transform),
            _ => Err(ExpectedType(MACRO_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_ptr(&self) -> Result<usize, Error> {
        match self {
            VCell::Ptr(ptr) => Ok(*ptr),
            _ => Err(ExpectedType(PTR_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_env_slot(&self) -> Result<usize, Error> {
        match self {
            VCell::GlobalEnvSlot(slot) => Ok(*slot),
            _ => Err(ExpectedType(LEXICAL_ENV_TYPE_SLOT, self.type_text())),
        }
    }

    pub fn as_lexical_env(&self) -> Result<&LexicalEnvironment, Error> {
        match self {
            VCell::LexicalEnv(env) => Ok(&*env),
            _ => Err(ExpectedType(LEXICAL_ENV_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_vector(&self) -> Result<&Vector, Error> {
        match self {
            VCell::Vector(vector) => Ok(&*vector),
            _ => Err(ExpectedType(VECTOR_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_argc(&self) -> Result<usize, Error> {
        match self {
            VCell::ArgumentCount(bp) => Ok(*bp),
            _ => Err(ExpectedType(ARGUMENT_COUNT_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_number(&self) -> Result<&Number, Error> {
        match self {
            VCell::Number(num) => Ok(num),
            _ => Err(ExpectedType(NUMBER_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_ip(&self) -> Result<(usize, usize), Error> {
        match self {
            VCell::InstructionPointer(lambda, ip) => Ok((*lambda, *ip)),
            _ => Err(ExpectedType(
                INSTRUCTION_POINTER_TYPE_TEXT,
                self.type_text(),
            )),
        }
    }

    pub fn as_bp(&self) -> Result<usize, Error> {
        match self {
            VCell::BasePointer(bp) => Ok(*bp),
            _ => Err(ExpectedType(BASE_POINTER_TYPE_TEXT, self.type_text())),
        }
    }

    pub fn as_ep(&self) -> Result<usize, Error> {
        match self {
            VCell::EnvironmentPointer(bp) => Ok(*bp),
            _ => Err(ExpectedType(
                ENVIRONMENT_POINTER_TYPE_TEXT,
                self.type_text(),
            )),
        }
    }

    pub fn as_bp_offset(&self) -> Result<i64, Error> {
        match self {
            VCell::BasePointerOffset(offset) => Ok(*offset),
            _ => Err(ExpectedType(
                BASE_POINTER_OFFSET_TYPE_TEXT,
                self.type_text(),
            )),
        }
    }
}

impl From<OpCode> for VCell {
    fn from(op: OpCode) -> Self {
        VCell::OpCode(op)
    }
}

impl From<Lambda> for VCell {
    fn from(lambda: Lambda) -> Self {
        VCell::lambda(lambda)
    }
}

impl From<bool> for VCell {
    fn from(val: bool) -> Self {
        VCell::Bool(val)
    }
}

impl From<char> for VCell {
    fn from(val: char) -> Self {
        VCell::Char(val)
    }
}

impl From<i64> for VCell {
    fn from(num: i64) -> Self {
        VCell::Number(Number::from(num))
    }
}

impl From<i32> for VCell {
    fn from(num: i32) -> Self {
        VCell::Number(Number::from(num))
    }
}

impl From<Number> for VCell {
    fn from(num: Number) -> Self {
        VCell::Number(num)
    }
}

impl fmt::Display for VCell {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VCell::Acc => write!(f, "%acc"),
            VCell::ArgumentCount(argc) => write!(f, "%argc[{}]", argc),
            VCell::BasePointer(bp) => write!(f, "%bp[${:02x}]", bp),
            VCell::BasePointerOffset(offset) => write!(f, "%bp[{:+}]", *offset),
            VCell::Bool(true) => write!(f, "#t"),
            VCell::Bool(false) => write!(f, "#f"),
            VCell::Char(c) => write_escaped_char(*c, f),
            VCell::Closure(_, _) => write!(f, "#<closure>"),
            VCell::Continuation(_) => write!(f, "#<continuation>"),
            VCell::EnvironmentPointer(ep) => write!(f, "%ep[${:02x}]", ep),
            VCell::GlobalEnvSlot(slot) => write!(f, "genv[${:02x}]", slot),
            VCell::InstructionPointer(lambda, ip) => {
                write!(f, "%ip[${:02x}][${:02x}]", *lambda, *ip)
            }
            VCell::Macro(_) => write!(f, "#<macro>"),
            VCell::LexicalEnv(_) => write!(f, "#<lexical-environment>"),
            VCell::LexicalEnvSlot(slot) => write!(f, "env[${:02x}]", slot),
            VCell::LexicalEnvPtr(env, slot) => write!(f, "env[${:02x}][${:02x}]", env, slot),
            VCell::Lambda(_) => write!(f, "#<lambda>"),
            VCell::Nil => write!(f, "()"),
            VCell::Number(number) => write!(f, "{:?}", number),
            VCell::OpCode(val) => write!(f, "{:?}", val),
            VCell::Pair(car, cdr) => write!(f, "(${:02x} . ${:02x})", car, cdr),
            VCell::Ptr(ptr) => write!(f, "${:02x}", ptr),
            VCell::String(s) => write!(f, "\"{}\"", (**s).borrow().deref()),
            VCell::Symbol(s) => write!(f, "{}", *s),
            VCell::BuiltInProc(_) => write!(f, "#<syscall>"),
            VCell::Undefined => write!(f, "undefined"),
            VCell::Vector(_) => write!(f, "#<vector>"),
            VCell::Void => write!(f, "#<void>"),
        }
    }
}

impl AsRef<VCell> for VCell {
    fn as_ref(&self) -> &VCell {
        self
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cell_size() {
        assert_eq!(std::mem::size_of::<VCell>(), 24);
    }

    #[test]
    fn new_cell_is_undefined() {
        assert!(matches!(VCell::undefined(), VCell::Undefined));
    }
}