Skip to main content

hexicon_vm/
vm.rs

1//! The virtual machine's state and the helpers everything else builds on.
2
3use std::ops::Deref;
4use std::rc::Rc;
5
6use hexicon_host::Host;
7use hexicon_image::DebugInfo;
8
9use crate::bif::FunctionSet;
10use crate::console::{Formatter, Newline};
11use crate::error::{VmError, VmResult, code};
12use crate::meta::{MetaKind, MetaTable};
13use crate::object::{Object, ObjectTable};
14use crate::value::{INVALID_PROP, ObjId, PropId, Value};
15
16/// What happens when a function returns.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum Return {
19    /// Continue the calling function at the return address.
20    Normal,
21    /// The function was called by the VM itself, not by byte code. Leave
22    /// the interpreter loop and hand the result to the caller.
23    Native,
24    /// The function implements an overloaded operator. Push its result
25    /// and continue at the return address.
26    Operator,
27    /// The function implements an overloaded operator in a compound
28    /// assignment to a local. Store its result in that local of the
29    /// caller and continue at the return address.
30    OperatorToLocal(u16),
31}
32
33/// What the VM was doing when it called into byte code. Stack traces show
34/// this in place of a byte-code frame.
35#[derive(Debug, Clone)]
36pub(crate) struct NativeCall {
37    /// A description for error messages.
38    pub name: &'static str,
39    /// The built-in function making the call, if it is one.
40    pub function: Option<(u16, u16)>,
41    /// The object whose built-in method is making the call, or `nil`.
42    pub self_value: Value,
43    /// The number of that method within its built-in class.
44    pub method_index: u16,
45    /// The arguments the native code was called with, first argument first.
46    pub args: Vec<Value>,
47    /// Address of the instruction that invoked the native code, or zero.
48    pub caller_pc: u32,
49    /// How much was on the stack when the native code was called, with
50    /// its arguments on top, or zero if that was not recorded. Named
51    /// arguments lie under the positional ones.
52    pub arg_top: usize,
53}
54
55impl NativeCall {
56    /// A call with only a description.
57    pub(crate) fn named(name: &'static str) -> Self {
58        Self {
59            name,
60            function: None,
61            self_value: Value::Nil,
62            method_index: 0,
63            args: Vec::new(),
64            caller_pc: 0,
65            arg_top: 0,
66        }
67    }
68}
69
70/// An activation of a byte-code function.
71#[derive(Debug, Clone)]
72pub(crate) struct Frame {
73    /// Code pool address of the function's method header.
74    pub func: u32,
75    /// What to do when the function returns.
76    pub ret: Return,
77    /// Code pool address in the caller to continue at.
78    pub return_pc: u32,
79    /// Stack index of local variable 0. The arguments are just below:
80    /// argument `i` (from 0) is at `base - 1 - i`.
81    pub base: u32,
82    /// Number of arguments the function was called with.
83    pub argc: u32,
84    /// The property being evaluated, or the invalid property.
85    pub prop: PropId,
86    /// The object the property was first looked up on, or `nil`.
87    pub target: Value,
88    /// The object the method was found in, or the invalid ID.
89    pub definer: ObjId,
90    /// `self`, or `nil` outside a method.
91    pub self_value: Value,
92    /// The function pointer or object that was invoked.
93    pub invokee: Value,
94    /// Present when the VM, not byte code, made the call.
95    pub native: Option<Box<NativeCall>>,
96    /// The `StackFrameRef` that stands for the call, once a stack trace
97    /// has asked for one.
98    pub frame_ref: Option<ObjId>,
99}
100
101impl Predef {
102    /// The objects the VM knows by name, which are never garbage.
103    pub(crate) fn objects(&self) -> [ObjId; 18] {
104        [
105            self.gram_alt_info,
106            self.gram_alt_token_info,
107            self.runtime_error,
108            self.stack_info_class,
109            self.const_str_obj,
110            self.const_lst_obj,
111            self.last_prop_obj,
112            self.reflection_services,
113            self.charset_unknown_exception,
114            self.file_not_found_exc,
115            self.file_creation_exc,
116            self.file_open_exc,
117            self.file_io_exc,
118            self.file_sync_exc,
119            self.file_closed_exc,
120            self.file_mode_exc,
121            self.file_safety_exc,
122            self.file_info,
123        ]
124    }
125}
126
127/// The method context a call starts with.
128#[derive(Debug, Clone, Copy)]
129pub(crate) struct MethodContext {
130    pub prop: PropId,
131    pub target: Value,
132    pub definer: ObjId,
133    pub self_value: Value,
134    pub invokee: Value,
135}
136
137impl MethodContext {
138    /// The context of a plain function call.
139    pub(crate) fn function(invokee: Value) -> Self {
140        Self {
141            prop: INVALID_PROP,
142            target: Value::Nil,
143            definer: ObjId::INVALID,
144            self_value: Value::Nil,
145            invokee,
146        }
147    }
148}
149
150/// Objects and properties the VM itself refers to. Images name most of
151/// them through exported symbols; the rest the VM creates at load time.
152#[derive(Debug, Clone, Default)]
153pub(crate) struct Predef {
154    /// Base class of the exceptions the VM throws.
155    pub runtime_error: ObjId,
156    /// Property holding a VM exception's message text.
157    pub exception_message: PropId,
158    /// The constructor property.
159    pub construct: PropId,
160    /// The finalizer property.
161    #[allow(dead_code)]
162    pub destruct: PropId,
163    /// The highest property ID the compiler assigned.
164    pub last_prop: PropId,
165    /// Property invoked when an undefined property is called.
166    pub prop_not_defined: PropId,
167    /// Class of the entries in a stack trace.
168    pub stack_info_class: ObjId,
169    /// The `length` property.
170    pub length: PropId,
171    /// A string object standing for all constant strings in method lookups.
172    pub const_str_obj: ObjId,
173    /// A list object standing for all constant lists in method lookups.
174    pub const_lst_obj: ObjId,
175    /// A one-element vector holding the last property ID allocated.
176    pub last_prop_obj: ObjId,
177    /// Operator overload properties.
178    pub operator_add: PropId,
179    pub operator_sub: PropId,
180    pub operator_mul: PropId,
181    pub operator_div: PropId,
182    pub operator_mod: PropId,
183    pub operator_xor: PropId,
184    pub operator_shl: PropId,
185    pub operator_ashr: PropId,
186    pub operator_lshr: PropId,
187    pub operator_bit_not: PropId,
188    pub operator_bit_and: PropId,
189    pub operator_bit_or: PropId,
190    pub operator_neg: PropId,
191    pub operator_idx: PropId,
192    pub operator_setidx: PropId,
193    /// The object and property the VM calls to name a value.
194    pub reflection_services: ObjId,
195    pub reflection_val_to_symbol: PropId,
196    /// What the grammar parser sets on the match objects it creates,
197    /// and the classes `getGrammarInfo` describes a production with.
198    pub gram_first_token: PropId,
199    pub gram_last_token: PropId,
200    pub gram_token_list: PropId,
201    pub gram_token_match_list: PropId,
202    pub gram_tag: PropId,
203    pub gram_misc_vocab: PropId,
204    pub gram_alt_props: PropId,
205    pub gram_alt_info: ObjId,
206    pub gram_alt_token_info: ObjId,
207    /// The methods of a comparator a program writes for a dictionary.
208    pub calc_hash: PropId,
209    pub match_values: PropId,
210    /// The exception class for using a character set the VM lacks.
211    pub charset_unknown_exception: ObjId,
212    /// The exception classes of the File class.
213    pub file_not_found_exc: ObjId,
214    pub file_creation_exc: ObjId,
215    pub file_open_exc: ObjId,
216    pub file_io_exc: ObjId,
217    pub file_sync_exc: ObjId,
218    pub file_closed_exc: ObjId,
219    pub file_mode_exc: ObjId,
220    pub file_safety_exc: ObjId,
221    /// The exception class for code that would not compile.
222    pub compiler_exc: ObjId,
223    /// The class that describes a file for `FileName.getFileInfo`.
224    pub file_info: ObjId,
225    /// The methods of an object a program writes to stand for a file.
226    pub filespec_get_filename: PropId,
227    pub filespec_close_file: PropId,
228    /// Where `specialsToHtml` keeps its state between calls.
229    pub string_sth_flags: PropId,
230    pub string_sth_tag: PropId,
231    /// Property for converting an object to a string.
232    pub obj_to_string: PropId,
233    /// The iterator methods `for..in` loops call.
234    pub iter_get_next: PropId,
235    pub iter_next_avail: PropId,
236}
237
238/// The text of a string value: a constant in the image or a string object.
239#[derive(Debug, Clone)]
240pub(crate) enum StrRef {
241    /// Bytes `start..start + len` of the constant pool.
242    Const(Rc<[u8]>, u32, u32),
243    /// The text of a string object.
244    Obj(Rc<[u8]>),
245}
246
247impl Deref for StrRef {
248    type Target = [u8];
249
250    fn deref(&self) -> &[u8] {
251        match self {
252            Self::Const(pool, start, len) => &pool[*start as usize..(*start + *len) as usize],
253            Self::Obj(text) => text,
254        }
255    }
256}
257
258/// The elements of a list value: a constant in the image or a list object.
259#[derive(Debug, Clone)]
260pub(crate) enum ListRef {
261    /// A constant list: the pool, the offset of the first element, and the
262    /// element count.
263    Const(Rc<[u8]>, u32, u32),
264    /// The elements of a list object.
265    Obj(Rc<[Value]>),
266}
267
268impl ListRef {
269    /// Number of elements.
270    pub(crate) fn len(&self) -> usize {
271        match self {
272            Self::Const(_, _, len) => *len as usize,
273            Self::Obj(items) => items.len(),
274        }
275    }
276
277    /// The element at a zero-based index. Panics if out of range.
278    pub(crate) fn get(&self, index: usize) -> Value {
279        match self {
280            Self::Const(pool, start, len) => {
281                assert!(index < *len as usize);
282                let at = *start as usize + index * Value::HOLDER_SIZE;
283                Value::from_holder(&pool[at..at + Value::HOLDER_SIZE])
284            }
285            Self::Obj(items) => items[index],
286        }
287    }
288
289    /// The elements, in order.
290    pub(crate) fn iter(&self) -> impl Iterator<Item = Value> + '_ {
291        (0..self.len()).map(|index| self.get(index))
292    }
293
294    /// The elements as a vector.
295    pub(crate) fn to_vec(&self) -> Vec<Value> {
296        self.iter().collect()
297    }
298}
299
300/// Sizes of the structures in the code pool, which each image states.
301#[derive(Debug, Clone, Copy, Default)]
302pub(crate) struct Layout {
303    pub method_header: u32,
304    pub exception_entry: u32,
305    pub debug_line_entry: u32,
306    pub debug_table_header: u32,
307    /// Size of the header of a local symbol record in a debug table.
308    pub debug_local_header: u32,
309    /// Size of the header of a frame in a debug table.
310    pub debug_frame_header: u32,
311}
312
313/// Stack slots available to a program, as in the reference VM's default
314/// configuration. Programs can observe it: it decides how deep a runaway
315/// recursion gets before it is stopped.
316pub(crate) const STACK_LIMIT: usize = 4096;
317
318/// Extra slots released while a stack overflow error is being reported:
319/// enough to build its stack trace, which then keeps only the innermost and
320/// outermost levels (`OVERFLOW_TRACE_LEVELS` of each).
321pub(crate) const STACK_RESERVE: usize = 512;
322
323/// How many of the innermost, and of the outermost, levels the stack trace
324/// of a stack overflow keeps.
325pub(crate) const OVERFLOW_TRACE_LEVELS: usize = 40;
326
327/// Stack slots the reference VM spends on each call for bookkeeping that
328/// Hexicon keeps elsewhere. They still count against the limit.
329pub(crate) const FRAME_OVERHEAD: usize = 11;
330
331/// Where a program stands after it has run for a while.
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333pub enum RunState {
334    /// The program has ended.
335    Finished,
336    /// The program is waiting for something the host did not have yet:
337    /// a line of input, a key, or the end of a pause. The host calls
338    /// [`Vm::resume`] when it has it.
339    Suspended,
340}
341
342/// The most bytes a string can hold.
343pub(crate) const MAX_STRING_LEN: usize = 65_535;
344
345/// The virtual machine with a program loaded.
346pub struct Vm {
347    /// The code pool, as one contiguous array, and after it the code
348    /// compiled while the program runs.
349    pub(crate) code: Rc<[u8]>,
350    /// The length of the image's own code.
351    pub(crate) image_code_len: usize,
352    /// The constant pool, as one contiguous array.
353    pub(crate) consts: Rc<[u8]>,
354    pub(crate) layout: Layout,
355    pub(crate) objects: ObjectTable,
356    pub(crate) meta: MetaTable,
357    pub(crate) function_sets: Vec<FunctionSet>,
358    pub(crate) predef: Predef,
359    pub(crate) stack: Vec<Value>,
360    pub(crate) frames: Vec<Frame>,
361    /// The stack limit in force; raised briefly to report an overflow.
362    pub(crate) stack_limit: usize,
363    /// Register 0: the result of the last call.
364    pub(crate) r0: Value,
365    /// Address of the instruction being executed.
366    pub(crate) pc: u32,
367    /// The function the `say` instructions call, or `nil`.
368    pub(crate) say_function: Value,
369    /// The method the `say` instructions call on `self`, if it has one.
370    pub(crate) say_method: PropId,
371    /// The entry point's code address.
372    pub(crate) entry_point: u32,
373    /// Static initializers still to run: object and property.
374    pub(crate) static_initializers: Vec<(ObjId, PropId)>,
375    /// Debug records from the image, for stack traces.
376    pub(crate) debug: DebugInfo,
377    /// Whether the program is running under pre-initialization.
378    pub(crate) preinit_mode: bool,
379    /// The tables `globalSymbols` returns, once built.
380    pub(crate) symbol_table: Option<ObjId>,
381    pub(crate) macro_table: Option<ObjId>,
382    /// Mathematical constants Decimal has computed so far.
383    pub(crate) big_cache: crate::decimal_math::Cache,
384    /// The random number generator.
385    pub(crate) rng: crate::rng::Rng,
386    /// The image's timestamp and file name, which a saved state records
387    /// so that it is only restored into the program that made it.
388    pub(crate) image_timestamp: Vec<u8>,
389    pub(crate) image_name: String,
390    /// The VM chose the property for exception messages itself, because
391    /// the image did not name one.
392    pub(crate) exception_message_synthesized: bool,
393    /// How deeply byte code is running inside calls made by the VM
394    /// itself: 1 for the program's own code, more inside a callback.
395    pub(crate) run_depth: u32,
396    /// The collector is running, and must not start again.
397    pub(crate) in_gc: bool,
398    /// How deep the VM is in converting or comparing values that hold
399    /// values: see [`Vm::nested`].
400    pub(crate) nesting: u32,
401    /// The most recent regular expression match.
402    pub(crate) last_match: crate::string::LastMatch,
403    /// Savepoints set aside by a restore that keeps them, to be put back
404    /// by the restore that returns (see `RestoreMode`).
405    pub(crate) undo_stash: Option<crate::object::UndoStash>,
406    /// Patterns given as strings, compiled, by their text. Compiling a
407    /// pattern always gives the same result, so one is compiled once.
408    pub(crate) pattern_cache: std::collections::HashMap<Vec<u8>, Rc<crate::regex::Pattern>>,
409    /// Report each VM error on standard error as it is raised.
410    pub(crate) trace_errors: bool,
411    /// A stack overflow is being reported: its stack trace is shortened.
412    pub(crate) reporting_overflow: bool,
413    /// Formats what the program displays into lines for the host.
414    pub(crate) console: Formatter,
415    pub(crate) io: crate::io::IoState,
416    pub(crate) host: Box<dyn Host>,
417}
418
419impl Vm {
420    // ---- the stack ----
421
422    /// Push a value.
423    #[inline]
424    pub(crate) fn push(&mut self, value: Value) {
425        self.stack.push(value);
426    }
427
428    /// Pop a value.
429    #[inline]
430    pub(crate) fn pop(&mut self) -> Value {
431        self.stack.pop().unwrap_or(Value::Nil)
432    }
433
434    /// The value `depth` slots below the top of the stack.
435    #[inline]
436    pub(crate) fn top(&self, depth: usize) -> Value {
437        // Only damaged code reaches below the bottom; it finds nil.
438        match self.stack.len().checked_sub(1 + depth) {
439            Some(at) => self.stack[at],
440            None => Value::Nil,
441        }
442    }
443
444    /// The slot `depth` slots below the top of the stack.
445    #[inline]
446    pub(crate) fn top_mut(&mut self, depth: usize) -> &mut Value {
447        // Only damaged code reaches below the bottom; the stack is made
448        // deep enough for it, with nil.
449        if self.stack.len() <= depth {
450            let missing = depth + 1 - self.stack.len();
451            self.stack
452                .splice(0..0, std::iter::repeat_n(Value::Nil, missing));
453        }
454        let index = self.stack.len() - 1 - depth;
455        &mut self.stack[index]
456    }
457
458    /// Remove `count` values from the top of the stack.
459    #[inline]
460    pub(crate) fn discard(&mut self, count: usize) {
461        let len = self.stack.len().saturating_sub(count);
462        self.stack.truncate(len);
463    }
464
465    /// Argument `index` (from 0) of a native function called with its
466    /// arguments on top of the stack.
467    #[inline]
468    pub(crate) fn arg(&self, index: usize) -> Value {
469        self.top(index)
470    }
471
472    /// Stack slots in use, counted the way the reference VM counts them.
473    pub(crate) fn stack_depth(&self) -> usize {
474        self.stack.len() + self.frames.len() * FRAME_OVERHEAD
475    }
476
477    /// Fail with a stack overflow unless `slots` more slots are available.
478    pub(crate) fn check_stack(&self, slots: usize) -> VmResult<()> {
479        if self.stack_depth() + slots > self.stack_limit {
480            Err(VmError::new(code::STACK_OVERFLOW))
481        } else {
482            Ok(())
483        }
484    }
485
486    // ---- the current frame ----
487
488    /// `self` in the current frame, or the invalid ID.
489    pub(crate) fn self_obj(&self) -> ObjId {
490        self.frames
491            .last()
492            .map_or(ObjId::INVALID, |frame| frame.self_value.obj_id())
493    }
494
495    // ---- objects ----
496
497    /// Create a string object.
498    pub(crate) fn new_string(&mut self, text: impl Into<Rc<[u8]>>) -> Value {
499        Value::Obj(self.alloc_obj(Object::String(text.into())))
500    }
501
502    /// Create a string object, unless it is longer than a string can be:
503    /// a string's length is 16 bits in every saved form, so the
504    /// reference allows no more than 65,535 bytes.
505    pub(crate) fn try_new_string(&mut self, text: impl Into<Rc<[u8]>>) -> VmResult<Value> {
506        let text = text.into();
507        if text.len() > MAX_STRING_LEN {
508            return Err(VmError::new(code::STR_TOO_LONG));
509        }
510        Ok(self.new_string(text))
511    }
512
513    /// Create a string object from Rust text, unless it is longer than a
514    /// string can be.
515    pub(crate) fn try_new_str(&mut self, text: &str) -> VmResult<Value> {
516        self.try_new_string(text.as_bytes())
517    }
518
519    /// Create a string object from Rust text.
520    pub(crate) fn new_str(&mut self, text: &str) -> Value {
521        self.new_string(text.as_bytes())
522    }
523
524    /// Create an object. Once enough objects have been created since
525    /// the collector last ran, it runs first, as in the reference VM:
526    /// at the creation, with what is reachable then.
527    pub(crate) fn alloc_obj(&mut self, object: Object) -> ObjId {
528        prof_scope!(crate::prof::ALLOC);
529        if self.objects.gc_due() && !self.in_gc {
530            // What the new object refers to is in use, though the object
531            // is not in the table yet.
532            let mut keep = Vec::new();
533            crate::object::references_of(&object, &mut keep);
534            self.collect_garbage_keeping(true, keep);
535        }
536        self.objects.alloc(object)
537    }
538
539    /// Create a list object.
540    pub(crate) fn new_list(&mut self, items: impl Into<Rc<[Value]>>) -> Value {
541        Value::Obj(self.alloc_obj(Object::List(items.into())))
542    }
543
544    /// The built-in class an object belongs to.
545    pub(crate) fn kind_of(&self, id: ObjId) -> Option<MetaKind> {
546        Some(match self.objects.get(id)? {
547            Object::Program(_) => MetaKind::ProgramObject,
548            Object::IntClassMod(_) => MetaKind::IntClassMod,
549            Object::String(_) => MetaKind::String,
550            Object::List(_) => MetaKind::List,
551            Object::Vector(_) => MetaKind::Vector,
552            Object::AnonFn(_) => MetaKind::Function,
553            Object::IndexedIter { .. } => MetaKind::IndexedIterator,
554            Object::Map(table) if table.weak => MetaKind::WeakMap,
555            Object::Map(_) => MetaKind::Map,
556            Object::MapIter { .. } => MetaKind::MapIterator,
557            Object::Pattern { .. } => MetaKind::Regex,
558            Object::StringBuilder(_) => MetaKind::StringBuilder,
559            Object::CompiledCode(_) => MetaKind::CompiledCode,
560            Object::FrameRef(_) => MetaKind::StackFrameRef,
561            Object::FrameDesc(_) => MetaKind::StackFrame,
562            Object::Decimal(_) => MetaKind::Decimal,
563            Object::ByteArray(_) => MetaKind::ByteArray,
564            Object::StrComp(_) => MetaKind::StringComparator,
565            Object::Dict(_) => MetaKind::Dictionary,
566            Object::GrammarRule(_) => MetaKind::GrammarRule,
567            Object::CharSet { .. } => MetaKind::CharacterSet,
568            Object::FileName(_) => MetaKind::FileName,
569            Object::Date { .. } => MetaKind::Date,
570            Object::TimeZone(_) => MetaKind::TimeZone,
571            Object::File(_) => MetaKind::File,
572            Object::TempFile(_) => MetaKind::TemporaryFile,
573            Object::Class(_) => MetaKind::BuiltinClass,
574            Object::Opaque { meta_index, .. } => self.meta.get(*meta_index as usize)?.kind,
575        })
576    }
577
578    // ---- strings and lists ----
579
580    /// The constant string at a pool offset.
581    pub(crate) fn const_str(&self, offset: u32) -> StrRef {
582        let at = offset as usize;
583        match self.consts.get(at..at + 2) {
584            Some(b) => {
585                let len = u32::from(u16::from_le_bytes([b[0], b[1]]));
586                let available = self.consts.len() - at - 2;
587                StrRef::Const(self.consts.clone(), offset + 2, len.min(available as u32))
588            }
589            None => StrRef::Const(self.consts.clone(), 0, 0),
590        }
591    }
592
593    /// The constant list at a pool offset.
594    pub(crate) fn const_list(&self, offset: u32) -> ListRef {
595        let at = offset as usize;
596        match self.consts.get(at..at + 2) {
597            Some(b) => {
598                let len = u32::from(u16::from_le_bytes([b[0], b[1]]));
599                let available = (self.consts.len() - at - 2) / Value::HOLDER_SIZE;
600                ListRef::Const(self.consts.clone(), offset + 2, len.min(available as u32))
601            }
602            None => ListRef::Const(self.consts.clone(), 0, 0),
603        }
604    }
605
606    /// The text of a value, if it is a string constant or string object.
607    pub(crate) fn as_str(&self, value: Value) -> Option<StrRef> {
608        match value {
609            Value::SString(offset) => Some(self.const_str(offset)),
610            Value::Obj(id) => match self.objects.get(id)? {
611                Object::String(text) => Some(StrRef::Obj(text.clone())),
612                _ => None,
613            },
614            _ => None,
615        }
616    }
617
618    /// The elements of a value, if it is a list constant or list object.
619    pub(crate) fn as_list(&self, value: Value) -> Option<ListRef> {
620        match value {
621            Value::List(offset) => Some(self.const_list(offset)),
622            Value::Obj(id) => match self.objects.get(id)? {
623                Object::List(items) => Some(ListRef::Obj(items.clone())),
624                _ => None,
625            },
626            _ => None,
627        }
628    }
629
630    /// The text of a value; anything but a string is an error.
631    pub(crate) fn require_str(&self, value: Value) -> VmResult<StrRef> {
632        self.as_str(value)
633            .ok_or_else(|| VmError::new(code::STRING_VAL_REQD))
634    }
635
636    // ---- argument helpers for native code ----
637
638    /// An integer argument.
639    pub(crate) fn int_arg(&self, value: Value) -> VmResult<i32> {
640        match value {
641            Value::Int(n) => Ok(n),
642            _ => Err(VmError::new(code::INT_VAL_REQD)),
643        }
644    }
645
646    /// A property ID argument.
647    pub(crate) fn prop_arg(&self, value: Value) -> VmResult<PropId> {
648        match value {
649            Value::Prop(prop) => Ok(prop),
650            _ => Err(VmError::new(code::PROPPTR_VAL_REQD)),
651        }
652    }
653
654    /// An object argument.
655    pub(crate) fn obj_arg(&self, value: Value) -> VmResult<ObjId> {
656        match value {
657            Value::Obj(id) => Ok(id),
658            _ => Err(VmError::new(code::OBJ_VAL_REQD)),
659        }
660    }
661
662    /// Report each VM error on standard error as it is raised, with the
663    /// address of the instruction that caused it. This is a debugging aid
664    /// for work on the VM itself.
665    pub fn set_error_trace(&mut self, on: bool) {
666        self.trace_errors = on;
667    }
668
669    /// Write out any text the console is holding for an unfinished line.
670    /// Call this when the program ends.
671    pub fn flush_output(&mut self) {
672        self.flush_console(Newline::None);
673    }
674}