hexicon-vm 0.3.0

The Hexicon virtual machine: runs the games Hexicon builds
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
//! The CompiledCode built-in class: functions compiled while the program
//! runs, from source text, against the program's own global names.
//!
//! The code of each is put after the program's own, at an address of its
//! own, so that it runs like any other function. A function compiled can
//! have functions nested in it, each a CompiledCode of its own, which its
//! code refers to by object.

use std::rc::Rc;

use hexicon_compiler::dynamic::{
    DynContext, DynCtxUse, DynHost, DynLocal, DynMode, DynObjKind, DynSymbol, DynValue,
    compile_dynamic,
};
use hexicon_compiler::pp::LinkMacro;

use crate::error::{VmError, VmResult, code};
use crate::object::Object;
use crate::value::{NativeDesc, ObjId, Value};
use crate::vm::Vm;

/// A function compiled while the program runs.
#[derive(Debug, Clone)]
pub struct CompiledCode {
    /// Where its code is, among the VM's code.
    pub addr: u32,
    /// The code: its header, its instructions, and its tables.
    pub code: Rc<[u8]>,
    /// Where in the code the numbers of objects it refers to are.
    pub obj_refs: Vec<u16>,
    /// The source it was compiled from, or nil for a function nested in
    /// another's source.
    pub source: Value,
    /// The method context it runs in, from the frame it was compiled
    /// in, or nil.
    pub method_ctx: Value,
}

impl CompiledCode {
    /// A function read from an image or a saved game: the length of the
    /// code, the number of objects it refers to, the method context, the
    /// source, the code, and where in it each object's number is. The
    /// values are read with `value`. Its code has no place yet: see
    /// [`Vm::place_dynamic_code`].
    pub(crate) fn read(data: &[u8], value: &mut dyn FnMut(&[u8]) -> Option<Value>) -> Option<Self> {
        let u16_at = |at: usize| -> Option<usize> {
            let bytes = data.get(at..at + 2)?;
            Some(usize::from(u16::from_le_bytes([bytes[0], bytes[1]])))
        };
        let len = u16_at(0)?;
        let refs = u16_at(2)?;
        let holder = Value::HOLDER_SIZE;
        let method_ctx = value(data.get(4..4 + holder)?)?;
        let source = value(data.get(4 + holder..4 + 2 * holder)?)?;
        let start = 4 + 2 * holder;
        let code = data.get(start..start + len)?;
        let mut obj_refs = Vec::with_capacity(refs);
        for index in 0..refs {
            obj_refs.push(u16_at(start + len + 2 * index)? as u16);
        }
        Some(Self {
            addr: UNPLACED,
            code: code.into(),
            obj_refs,
            source,
            method_ctx,
        })
    }

    /// The size of what [`CompiledCode::read`] reads.
    pub(crate) fn data_len(data: &[u8]) -> Option<usize> {
        let len = usize::from(u16::from_le_bytes([*data.first()?, *data.get(1)?]));
        let refs = usize::from(u16::from_le_bytes([*data.get(2)?, *data.get(3)?]));
        Some(4 + 2 * Value::HOLDER_SIZE + len + 2 * refs)
    }

    /// A function not compiled yet: the object is made first, so that the
    /// code that refers to it can be.
    fn placeholder() -> Self {
        Self {
            addr: 0,
            code: Rc::from([]),
            obj_refs: Vec::new(),
            source: Value::Nil,
            method_ctx: Value::Nil,
        }
    }

    /// The objects its code refers to.
    pub(crate) fn object_refs(&self) -> impl Iterator<Item = ObjId> + '_ {
        self.obj_refs.iter().filter_map(|&at| {
            let at = usize::from(at);
            let bytes = self.code.get(at..at + 4)?;
            Some(ObjId(u32::from_le_bytes([
                bytes[0], bytes[1], bytes[2], bytes[3],
            ])))
        })
    }
}

/// The address a function read from an image or a saved game has until
/// its code is put with the VM's.
pub(crate) const UNPLACED: u32 = u32::MAX;

/// The name and calling interface of each method, by method number.
const METHODS: &[(&str, NativeDesc)] = &[
    ("", NativeDesc::fixed(0)),
    ("getSource", NativeDesc::fixed(0)),
];

/// What the compiler asks of the VM: objects for the functions.
struct FuncObjects<'v> {
    vm: &'v mut Vm,
}

impl DynHost for FuncObjects<'_> {
    fn new_object(&mut self, class: u32, props: &[(u16, DynValue)]) -> u32 {
        let vm = &mut *self.vm;
        let class = ObjId(class);
        // As `new` of the class makes it, with no arguments.
        let mut argc = 0;
        if class.is_valid() {
            vm.push(Value::Obj(class));
            argc = 1;
        }
        let Ok((id, _)) = vm.create_program_object(argc, false, None) else {
            return 0;
        };
        // Keep it while the rest is made.
        vm.push(Value::Obj(id));
        for (prop, value) in props {
            let value = match value {
                DynValue::Int(n) => Value::Int(*n),
                DynValue::Str(text) => vm.new_string(text.clone()),
            };
            let _ = vm.set_prop(id, *prop, value);
        }
        vm.discard(1);
        id.0
    }

    fn new_func_ids(&mut self, count: usize) -> Vec<u32> {
        (0..count)
            .map(|_| {
                self.vm
                    .alloc_obj(Object::CompiledCode(Box::new(CompiledCode::placeholder())))
                    .0
            })
            .collect()
    }
}

impl Vm {
    /// `new CompiledCode(source, globals?, locals?, macros?)`: compile the
    /// source, against the table of global names and the table of macros
    /// given, which are what `globalSymbols` gives.
    pub(crate) fn create_compiled_code(&mut self, argc: u32) -> VmResult<ObjId> {
        if !(1..=4).contains(&argc) {
            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
        }
        let source = self.arg(0);
        let table = |vm: &Vm, index: u32| -> VmResult<Option<ObjId>> {
            if index >= argc {
                return Ok(None);
            }
            match vm.arg(index as usize) {
                Value::Obj(id) => Ok(Some(id)),
                Value::Nil => Ok(None),
                _ => Err(VmError::new(code::BAD_TYPE_BIF)),
            }
        };
        let globals = table(self, 1)?;
        let locals = table(self, 2)?;
        let macros = table(self, 3)?;
        let Some(text) = self.as_str(source) else {
            return Err(VmError::new(code::BAD_TYPE_BIF));
        };
        let text = text.to_vec();
        let mut context = self.dyn_context(globals, macros);
        let innermost = self.dyn_locals(locals, &mut context)?;
        let result = compile_dynamic(
            &text,
            &context,
            DynMode::Auto,
            &mut FuncObjects { vm: self },
        );
        let compiled = match result {
            Ok(compiled) => compiled,
            Err(message) => {
                self.discard(argc as usize);
                return Err(self.throw_compiler_error(&message));
            }
        };
        self.discard(argc as usize);
        let mut main = None;
        for (index, (id, func)) in compiled.funcs.into_iter().enumerate() {
            let id = ObjId(id);
            let addr = self.add_dynamic_code(&func.code);
            let compiled_code = CompiledCode {
                addr,
                code: func.code.into(),
                obj_refs: func.obj_refs.iter().map(|&at| at as u16).collect(),
                source: if index == 0 { source } else { Value::Nil },
                method_ctx: match (index, compiled.ctx_use, innermost) {
                    (0, DynCtxUse::Full, Some(fref)) => self.frame_ref_loadctx(fref),
                    (0, DynCtxUse::SelfOnly, Some(fref)) => self.frame_ref_self(fref),
                    _ => Value::Nil,
                },
            };
            self.objects
                .replace(id, Object::CompiledCode(Box::new(compiled_code)));
            main.get_or_insert(id);
        }
        main.ok_or_else(|| VmError::new(code::BAD_TYPE_BIF))
    }

    /// The variables the code can use: those of the stack frame given,
    /// or of each in a list of them, innermost first. Returns the call
    /// of the innermost frame, if it has a `self`.
    fn dyn_locals(
        &mut self,
        locals: Option<ObjId>,
        context: &mut DynContext,
    ) -> VmResult<Option<ObjId>> {
        let Some(locals) = locals else {
            return Ok(None);
        };
        let mut frames = Vec::new();
        if self.stack_frame(locals).is_some() {
            frames.push(locals);
        } else if let Some(len) = self.list_like_len(Value::Obj(locals))? {
            for index in 1..=len {
                if let Value::Obj(id) = self.list_like_get(Value::Obj(locals), index)?
                    && self.stack_frame(id).is_some()
                {
                    frames.push(id);
                } else if index == 1 {
                    // Only the first can be the innermost.
                    frames.push(ObjId::INVALID);
                }
            }
        }
        let mut innermost = None;
        for (index, &id) in frames.iter().enumerate() {
            let Some(desc) = self.stack_frame(id) else {
                continue;
            };
            if index == 0 && !self.frame_ref_self(desc.fref).is_nil() {
                context.frame_has_self = true;
                innermost = Some(desc.fref);
            }
            if desc.scope == 0 {
                continue;
            }
            for sym in self.stack_frame_syms(desc) {
                let number = self.frame_var_number(desc.fref, &sym) as u16;
                context.locals.push(DynLocal {
                    name: sym.name,
                    frame_ref: desc.fref.0,
                    number,
                    context: sym.ctx.map_or(0, |ctx| ctx as u16),
                });
            }
        }
        Ok(innermost)
    }

    /// The exception a compilation that failed throws: the program's
    /// `CompilerException`, with the compiler's messages.
    pub(crate) fn throw_compiler_error(&mut self, message: &str) -> VmError {
        let class = self.predef.compiler_exc;
        if !class.is_valid() {
            return self.throw_class(class, "code compilation failed");
        }
        let text = self.new_str(message);
        self.push(text);
        match self.create_instance(class, 1) {
            Err(error) => error,
            Ok(()) => match self.r0 {
                Value::Obj(exception) => VmError::Thrown(exception),
                _ => VmError::new(code::EXCEPTION_OBJ_REQD),
            },
        }
    }

    /// Put the code of the functions read from an image or a saved game
    /// with the VM's, each at an address of its own.
    pub(crate) fn place_dynamic_code(&mut self) {
        let ids: Vec<ObjId> = self
            .objects
            .ids()
            .filter(|&id| {
                matches!(self.objects.get(id), Some(Object::CompiledCode(func)) if func.addr == UNPLACED)
            })
            .collect();
        for id in ids {
            let code = match self.objects.get(id) {
                Some(Object::CompiledCode(func)) => Rc::clone(&func.code),
                _ => continue,
            };
            let addr = self.add_dynamic_code(&code);
            if let Some(Object::CompiledCode(func)) = self.objects.get_mut(id) {
                func.addr = addr;
            }
        }
    }

    /// Put code after the VM's own, and say where it is.
    pub(crate) fn add_dynamic_code(&mut self, code: &[u8]) -> u32 {
        let mut all = Vec::with_capacity(self.code.len() + code.len());
        all.extend_from_slice(&self.code);
        let addr = all.len() as u32;
        all.extend_from_slice(code);
        self.code = all.into();
        addr
    }

    /// What code is compiled against: the global names in a table of
    /// them, the macros in a table of them, and the image's classes.
    pub(crate) fn dyn_context(&self, globals: Option<ObjId>, macros: Option<ObjId>) -> DynContext {
        let mut context = DynContext::default();
        for index in 0..self.meta.len() {
            if let Some(entry) = self.meta.get(index) {
                context
                    .metaclasses
                    .push(entry.image_name.as_bytes().to_vec());
                context.metaclass_props.push(entry.method_props.clone());
            }
        }
        if let Some(Object::Map(table)) = globals.and_then(|id| self.objects.get(id)) {
            for (key, value) in table.entries() {
                let Some(name) = self.as_str(key) else {
                    continue;
                };
                if let Some(symbol) = self.dyn_symbol(value) {
                    context.symbols.push((name.to_vec(), symbol));
                }
            }
        }
        if let Some(Object::Map(table)) = macros.and_then(|id| self.objects.get(id)) {
            for (key, value) in table.entries() {
                if let (Some(name), Some(mac)) = (self.as_str(key), self.dyn_macro(value)) {
                    context.macros.push(LinkMacro {
                        name: name.to_vec(),
                        ..mac
                    });
                }
            }
        }
        context
    }

    /// What a value in the table of global names stands for, to the
    /// compiler, if it is something the compiler can use.
    fn dyn_symbol(&self, value: Value) -> Option<DynSymbol> {
        Some(match value {
            Value::Obj(id) => match self.objects.get(id)? {
                Object::Class(class) => DynSymbol::Class {
                    meta_index: class.meta_index,
                    id: id.0,
                },
                object => {
                    let kind = if self.invoker(id).is_some() {
                        DynObjKind::Invokable
                    } else {
                        match object {
                            Object::Program(_) => DynObjKind::ProgramObject,
                            Object::GrammarRule(_) => DynObjKind::GrammarRule,
                            Object::Dict(_) => DynObjKind::Dictionary,
                            Object::IntClassMod(_) => DynObjKind::ClassModifier,
                            _ => DynObjKind::Other,
                        }
                    };
                    DynSymbol::Object { id: id.0, kind }
                }
            },
            Value::Prop(prop) => DynSymbol::Property(prop),
            Value::FuncPtr(addr) => {
                let header = self.code.get(addr as usize..addr as usize + 2)?;
                DynSymbol::Function {
                    addr,
                    argc: usize::from(header[0] & 0x7f),
                    opt_argc: usize::from(header[1]),
                    varargs: header[0] & 0x80 != 0,
                }
            }
            Value::Enum(id) => DynSymbol::Enum(id),
            Value::BifPtr { set, index } => {
                let desc = self.bif_desc(set, index)?;
                DynSymbol::BuiltIn {
                    set,
                    index,
                    min_argc: usize::from(desc.min_args),
                    opt_argc: usize::from(desc.opt_args),
                    varargs: desc.varargs,
                }
            }
            _ => return None,
        })
    }

    /// A macro as the table of macros has it: a list of its expansion,
    /// the list of its parameters' names, and its flags.
    fn dyn_macro(&self, value: Value) -> Option<LinkMacro> {
        let items = self.list_items(value).ok()?;
        if items.len() < 3 {
            return None;
        }
        let expansion = self.as_str(items[0])?.to_vec();
        let mut params = Vec::new();
        for param in self.list_items(items[1]).ok()? {
            params.push(self.as_str(param)?.to_vec());
        }
        let Value::Int(flags) = items[2] else {
            return None;
        };
        Some(LinkMacro {
            name: Vec::new(),
            has_args: flags & 1 != 0,
            has_varargs: flags & 2 != 0,
            params,
            expansion,
        })
    }

    /// Call a method of the CompiledCode class.
    pub(crate) fn compiled_code_method(
        &mut self,
        id: ObjId,
        index: u16,
        argc: Option<&mut u32>,
    ) -> VmResult<Option<Value>> {
        let Some(&(_, desc)) = METHODS.get(index as usize).filter(|_| index != 0) else {
            return Ok(None);
        };
        self.native_method(argc, desc, |vm, _| {
            Ok(match vm.objects.get(id) {
                Some(Object::CompiledCode(func)) => func.source,
                _ => Value::Nil,
            })
        })
        .map(Some)
    }
}