Skip to main content

hexicon_vm/
load.rs

1//! Setting up a VM from a program image, and running the program.
2
3use std::rc::Rc;
4
5use hexicon_host::Host;
6use hexicon_image::{Image, Pool, Value as ImageValue};
7
8use crate::bif::FunctionSet;
9use crate::error::{ErrParam, VmError, VmResult, code};
10use crate::map::Map;
11use crate::meta::{MetaKind, MetaTable};
12use crate::object::{BuiltinClass, Object, ObjectTable};
13use crate::program_object::ProgramObject;
14use crate::value::{INVALID_PROP, ObjId, PropId, Value};
15use crate::vm::{Layout, MethodContext, NativeCall, Predef, Return, RunState, STACK_LIMIT, Vm};
16
17/// Width of the console in columns. The reference VM's plain console is
18/// 80 columns wide.
19pub(crate) const CONSOLE_WIDTH: usize = 80;
20
21/// Copy a pool into one contiguous array, so that a pool address is an
22/// index. Pages the image does not supply read as zeros.
23fn flatten(pool: &Pool) -> Rc<[u8]> {
24    let page_size = pool.page_size() as usize;
25    // Up to the last page the image supplies: a damaged definition can
26    // claim millions of pages the image does not have, and an address
27    // past the end is caught when it is read.
28    let used = (0..pool.page_count())
29        .rev()
30        .find(|&index| pool.page(index).is_some())
31        .map_or(0, |index| index + 1);
32    let mut data = vec![0u8; page_size * used];
33    for index in 0..used {
34        if let Some(page) = pool.page(index) {
35            let len = page.len().min(page_size);
36            data[index * page_size..index * page_size + len].copy_from_slice(&page[..len]);
37        }
38    }
39    data.into()
40}
41
42fn bad_export(name: &str) -> VmError {
43    VmError::with(
44        code::INVAL_EXPORT_TYPE,
45        vec![ErrParam::Str(name.to_owned())],
46    )
47}
48
49fn object_symbol(image: &Image, name: &str) -> VmResult<ObjId> {
50    match image.symbol(name) {
51        None => Ok(ObjId::INVALID),
52        Some(ImageValue::Object(id)) => Ok(ObjId(id)),
53        Some(_) => Err(bad_export(name)),
54    }
55}
56
57fn prop_symbol(image: &Image, name: &str) -> VmResult<PropId> {
58    match image.symbol(name) {
59        None => Ok(INVALID_PROP),
60        Some(ImageValue::Property(id)) => Ok(id),
61        Some(_) => Err(bad_export(name)),
62    }
63}
64
65/// Build an object from its image data.
66fn load_object(kind: MetaKind, meta_index: u16, data: &[u8]) -> VmResult<Object> {
67    let bad = || VmError::new(code::INVAL_METACLASS_DATA);
68    let u16_at = |at: usize| -> VmResult<u16> {
69        let b = data.get(at..at + 2).ok_or_else(bad)?;
70        Ok(u16::from_le_bytes([b[0], b[1]]))
71    };
72    Ok(match kind {
73        MetaKind::ProgramObject => {
74            Object::Program(ProgramObject::from_image(data).ok_or_else(bad)?)
75        }
76        MetaKind::IntClassMod => {
77            Object::IntClassMod(ProgramObject::from_image(data).ok_or_else(bad)?)
78        }
79        MetaKind::String => {
80            let len = u16_at(0)? as usize;
81            Object::String(data.get(2..2 + len).ok_or_else(bad)?.into())
82        }
83        MetaKind::List => {
84            let count = u16_at(0)? as usize;
85            let items = data
86                .get(2..2 + count * Value::HOLDER_SIZE)
87                .ok_or_else(bad)?
88                .as_chunks::<{ Value::HOLDER_SIZE }>()
89                .0
90                .iter()
91                .map(|holder| Value::from_holder(holder))
92                .collect::<Vec<_>>();
93            Object::List(items.into())
94        }
95        MetaKind::Vector | MetaKind::Function => {
96            // An allocation size, an element count, and the elements.
97            // Elements the data does not supply are nil.
98            let count = u16_at(2)? as usize;
99            let mut items: Vec<Value> = data
100                .get(4..)
101                .unwrap_or(&[])
102                .as_chunks::<{ Value::HOLDER_SIZE }>()
103                .0
104                .iter()
105                .take(count)
106                .map(|holder| Value::from_holder(holder))
107                .collect();
108            items.resize(count, Value::Nil);
109            if kind == MetaKind::Vector {
110                Object::Vector(items)
111            } else {
112                Object::AnonFn(items)
113            }
114        }
115        MetaKind::Map | MetaKind::WeakMap => Object::Map(Box::new(
116            Map::from_image(data, kind == MetaKind::WeakMap).ok_or_else(bad)?,
117        )),
118        MetaKind::Decimal => Object::Decimal(Box::new(
119            crate::decimal::Big::from_bytes(data).ok_or_else(bad)?,
120        )),
121        MetaKind::ByteArray => {
122            // A length, then the bytes. Any the image leaves out are zero.
123            let len = data.get(..4).ok_or_else(bad)?;
124            let len = u32::from_le_bytes([len[0], len[1], len[2], len[3]]) as usize;
125            let mut bytes = data[4..].to_vec();
126            bytes.resize(len, 0);
127            Object::ByteArray(bytes)
128        }
129        MetaKind::GrammarRule => Object::GrammarRule(Box::new(
130            crate::gram::GrammarRule::from_bytes(data)
131                .ok_or_else(bad)?
132                .0,
133        )),
134        MetaKind::StringComparator => Object::StrComp(std::rc::Rc::new(
135            crate::strcomp::StrComp::from_bytes(data).ok_or_else(bad)?.0,
136        )),
137        MetaKind::Dictionary => Object::Dict(Box::new(
138            crate::dict::Dictionary::from_image(data).ok_or_else(bad)?,
139        )),
140        MetaKind::CharacterSet => {
141            let len = u16_at(0)? as usize;
142            let name = String::from_utf8_lossy(data.get(2..2 + len).ok_or_else(bad)?).into_owned();
143            let map = crate::charset::CharMap::load(&name).map(std::rc::Rc::new);
144            Object::CharSet { name, map }
145        }
146        MetaKind::Regex => Object::Pattern {
147            source: Value::from_holder(data.get(..Value::HOLDER_SIZE).ok_or_else(bad)?),
148            compiled: None,
149        },
150        MetaKind::FileName => {
151            // The number of a special file, or zero and then the name.
152            let special = data.get(..4).ok_or_else(bad)?;
153            let special = i32::from_le_bytes([special[0], special[1], special[2], special[3]]);
154            let path = if special == 0 {
155                let len = u16_at(4)? as usize;
156                String::from_utf8_lossy(data.get(6..6 + len).ok_or_else(bad)?).into_owned()
157            } else {
158                String::new()
159            };
160            Object::FileName(Box::new(crate::file::FileNameObj {
161                path,
162                special,
163                from_ui: 0,
164            }))
165        }
166        MetaKind::File => {
167            // The character set, the mode, the access, and flags. The
168            // file itself is not open: the object is out of sync with it.
169            let charset = data.get(..4).ok_or_else(bad)?;
170            let charset = u32::from_le_bytes([charset[0], charset[1], charset[2], charset[3]]);
171            Object::File(Box::new(crate::file::FileObj {
172                charset: ObjId(charset),
173                mode: *data.get(4).ok_or_else(bad)?,
174                access: *data.get(5).ok_or_else(bad)?,
175                out_of_sync: true,
176                spec: Value::Nil,
177                open: None,
178            }))
179        }
180        MetaKind::TemporaryFile => Object::TempFile(String::new()),
181        MetaKind::TimeZone => {
182            // The offsets, the name, and the abbreviation, the last two
183            // each after a byte with its length.
184            let int = |at: usize| {
185                let bytes = data.get(at..at + 4).ok_or_else(bad)?;
186                Ok::<i32, VmError>(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
187            };
188            let text = |at: usize| {
189                let len = usize::from(*data.get(at).ok_or_else(bad)?);
190                let bytes = data.get(at + 1..at + 1 + len).ok_or_else(bad)?;
191                Ok::<(String, usize), VmError>((
192                    String::from_utf8_lossy(bytes).into_owned(),
193                    at + 1 + len,
194                ))
195            };
196            let (name, after) = text(8)?;
197            let (abbr, _) = text(after)?;
198            Object::TimeZone(std::rc::Rc::new(crate::tz::Zone::recorded(
199                &name,
200                int(0)?,
201                int(4)?,
202                &abbr,
203            )))
204        }
205        MetaKind::Date => {
206            let int = |at: usize| {
207                let bytes = data.get(at..at + 4).ok_or_else(bad)?;
208                Ok::<i32, VmError>(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
209            };
210            Object::Date {
211                dayno: int(0)?,
212                daytime: int(4)?,
213            }
214        }
215        MetaKind::StringBuilder => {
216            // The room, the step it grows by, the length, and the
217            // characters in 16 bits. Loading keeps the sizes within the
218            // limits, as the reference does.
219            let int = |at: usize| {
220                let bytes = data.get(at..at + 4).ok_or_else(bad)?;
221                Ok::<u32, VmError>(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
222            };
223            let limit = |n: u32| n.clamp(16, crate::object::StringBuilder::MAX_ROOM);
224            let room = limit(int(0)?);
225            let mut buffer = crate::object::StringBuilder::new(room, limit(int(4)?));
226            let len = int(8)?.min(room) as usize;
227            for index in 0..len {
228                let unit = u32::from(u16_at(12 + 2 * index)?);
229                buffer
230                    .chars
231                    .push(char::from_u32(unit).unwrap_or('\u{fffd}'));
232            }
233            Object::StringBuilder(buffer)
234        }
235        MetaKind::CompiledCode => Object::CompiledCode(Box::new(
236            crate::compiled_code::CompiledCode::read(data, &mut |holder| {
237                Some(Value::from_holder(holder))
238            })
239            .ok_or_else(bad)?,
240        )),
241        MetaKind::StackFrameRef => Object::FrameRef(Box::new(
242            crate::frameref::FrameRef::read(
243                data,
244                &mut |holder| Some(Value::from_holder(holder)),
245                &|id| id,
246            )
247            .ok_or_else(bad)?,
248        )),
249        MetaKind::StackFrame => {
250            Object::FrameDesc(crate::frameref::FrameDesc::read(data).ok_or_else(bad)?)
251        }
252        MetaKind::BuiltinClass => {
253            // A length, the index of the class in the dependency list,
254            // the modifier object, and optionally the class state.
255            if data.len() < 8 {
256                return Err(bad());
257            }
258            let modifier = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
259            let class_state = match data.get(8..8 + Value::HOLDER_SIZE) {
260                Some(holder) => Value::from_holder(holder),
261                None => Value::Nil,
262            };
263            Object::Class(BuiltinClass {
264                meta_index: u16_at(2)?,
265                modifier: ObjId(modifier),
266                class_state,
267            })
268        }
269        _ => Object::Opaque {
270            meta_index,
271            data: data.into(),
272        },
273    })
274}
275
276impl Vm {
277    /// Load a program image.
278    pub fn new(image: &Image, host: Box<dyn Host>) -> VmResult<Self> {
279        if image.code_pool.page_count() < 1 {
280            return Err(VmError::new(code::IMAGE_NO_CODE));
281        }
282        // As in the reference, a pool's pages are a power of two in size,
283        // and every page the pool has is in the image.
284        for pool in [&image.code_pool, &image.constant_pool] {
285            let size = pool.page_size();
286            if size != 0 && !size.is_power_of_two() {
287                return Err(VmError::new(code::BAD_POOL_PAGE_SIZE));
288            }
289            if pool.loaded_page_count() != pool.page_count() {
290                return Err(VmError::new(code::LOAD_UNDEF_PAGE));
291            }
292        }
293
294        let mut meta = MetaTable::new();
295        for dependency in &image.metaclasses {
296            meta.add(&dependency.name, dependency.properties.clone())?;
297        }
298        meta.add_if_new(MetaKind::Root);
299
300        let function_sets = image
301            .function_sets
302            .iter()
303            .map(|name| FunctionSet::from_image_name(name))
304            .collect::<VmResult<Vec<_>>>()?;
305
306        crate::heap::reset();
307        let mut objects = ObjectTable::new();
308        // Object IDs are a few times as many as the objects at most, in
309        // any image a compiler writes. A damaged one could name an ID in
310        // the billions, which would take as much memory to hold.
311        let count: usize = image.object_blocks.iter().map(|b| b.objects.len()).sum();
312        let id_limit = 16 * count as u64 + 65_536;
313        for block in &image.object_blocks {
314            let Some(kind) = meta.get(block.metaclass_index as usize).map(|e| e.kind) else {
315                return Err(VmError::new(code::BAD_METACLASS_INDEX));
316            };
317            for object in &block.objects {
318                if u64::from(object.id) >= id_limit {
319                    return Err(VmError::new(code::OUT_OF_MEMORY));
320                }
321                let id = ObjId(object.id);
322                let loaded = load_object(kind, block.metaclass_index, &object.data)?;
323                // A built-in class object tells the VM which object
324                // stands for the class.
325                if let Object::Class(class) = &loaded
326                    && let Some(entry) = meta.get_mut(class.meta_index as usize)
327                {
328                    entry.class_obj = id;
329                }
330                if !objects.alloc_with_id(id, loaded, block.transient) {
331                    return Err(VmError::new(code::OBJ_IN_USE));
332                }
333                // A vector has the room the image says, or at least
334                // room for its elements.
335                if matches!(kind, MetaKind::Vector | MetaKind::Function)
336                    && let Some(room) = object.data.get(..2)
337                {
338                    let room = usize::from(u16::from_le_bytes([room[0], room[1]]));
339                    let room = room.max(objects.vector_alloc(id));
340                    objects.set_vector_alloc(id, room);
341                }
342            }
343        }
344
345        let entry = &image.entry_point;
346        let mut vm = Self {
347            code: flatten(&image.code_pool),
348            image_code_len: 0,
349            consts: flatten(&image.constant_pool),
350            layout: Layout {
351                method_header: entry.method_header_size.into(),
352                exception_entry: entry.exception_entry_size.into(),
353                debug_line_entry: entry.debug_line_entry_size.into(),
354                debug_table_header: entry.debug_table_header_size.into(),
355                debug_local_header: entry.debug_local_header_size.into(),
356                debug_frame_header: entry.debug_frame_header_size.into(),
357            },
358            objects,
359            meta,
360            function_sets,
361            predef: Predef::default(),
362            stack: Vec::with_capacity(STACK_LIMIT),
363            frames: Vec::new(),
364            stack_limit: STACK_LIMIT,
365            r0: Value::Nil,
366            pc: 0,
367            say_function: Value::Nil,
368            say_method: INVALID_PROP,
369            entry_point: entry.code_offset,
370            static_initializers: image
371                .static_initializers
372                .iter()
373                .flat_map(|list| &list.initializers)
374                .map(|init| (ObjId(init.object), init.property))
375                .collect(),
376            debug: image.debug.clone(),
377            preinit_mode: false,
378            last_match: Default::default(),
379            undo_stash: None,
380            pattern_cache: Default::default(),
381            rng: crate::rng::Rng::new(),
382            image_timestamp: image.header.timestamp.as_bytes().to_vec(),
383            image_name: String::new(),
384            exception_message_synthesized: false,
385            run_depth: 0,
386            in_gc: false,
387            nesting: 0,
388            big_cache: Default::default(),
389            symbol_table: None,
390            macro_table: None,
391            trace_errors: false,
392            reporting_overflow: false,
393            console: crate::console::Formatter::new(CONSOLE_WIDTH),
394            io: crate::io::IoState::default(),
395            host,
396        };
397        vm.image_code_len = vm.code.len();
398        vm.link(image)?;
399        // A dictionary's words are stored by its comparator's hash, which
400        // can only be worked out once the comparator is loaded.
401        let dictionaries: Vec<ObjId> = vm
402            .objects
403            .ids()
404            .filter(|&id| matches!(vm.objects.get(id), Some(Object::Dict(d)) if d.comparator.is_valid()))
405            .collect();
406        for id in dictionaries {
407            vm.dict_rehash(id)?;
408        }
409        vm.resolve_zones();
410        // From here on, a change to an object from the image is a change
411        // the program made.
412        vm.objects.track_image_state();
413        Ok(vm)
414    }
415
416    /// Record the name of the image file, which saved states carry so
417    /// that a saved state can lead back to its program.
418    pub fn set_image_name(&mut self, name: &str) {
419        self.image_name = name.to_owned();
420    }
421
422    /// Resolve the symbols the VM imports from the image, and create the
423    /// objects the VM needs that the image does not supply.
424    fn link(&mut self, image: &Image) -> VmResult<()> {
425        self.predef = Predef {
426            runtime_error: object_symbol(image, "RuntimeError")?,
427            exception_message: prop_symbol(image, "exceptionMessage")?,
428            construct: prop_symbol(image, "Constructor")?,
429            destruct: prop_symbol(image, "Destructor")?,
430            last_prop: prop_symbol(image, "LastProp")?,
431            prop_not_defined: prop_symbol(image, "propNotDefined")?,
432            stack_info_class: object_symbol(image, "StackInfo")?,
433            length: prop_symbol(image, "length")?,
434            const_str_obj: ObjId::INVALID,
435            const_lst_obj: ObjId::INVALID,
436            last_prop_obj: ObjId::INVALID,
437            operator_add: prop_symbol(image, "operator +")?,
438            operator_sub: prop_symbol(image, "operator -")?,
439            operator_mul: prop_symbol(image, "operator *")?,
440            operator_div: prop_symbol(image, "operator /")?,
441            operator_mod: prop_symbol(image, "operator %")?,
442            operator_xor: prop_symbol(image, "operator ^")?,
443            operator_shl: prop_symbol(image, "operator <<")?,
444            operator_ashr: prop_symbol(image, "operator >>")?,
445            operator_lshr: prop_symbol(image, "operator >>>")?,
446            operator_bit_not: prop_symbol(image, "operator ~")?,
447            operator_bit_and: prop_symbol(image, "operator &")?,
448            operator_bit_or: prop_symbol(image, "operator |")?,
449            operator_neg: prop_symbol(image, "operator negate")?,
450            operator_idx: prop_symbol(image, "operator []")?,
451            operator_setidx: prop_symbol(image, "operator []=")?,
452            reflection_services: object_symbol(image, "reflection.reflectionServices")?,
453            reflection_val_to_symbol: prop_symbol(image, "reflection.valToSymbol")?,
454            obj_to_string: prop_symbol(image, "objToString")?,
455            calc_hash: prop_symbol(image, "IfcComparator.calcHash")?,
456            gram_first_token: prop_symbol(image, "GrammarRule.firstTokenIndex")?,
457            gram_last_token: prop_symbol(image, "GrammarRule.lastTokenIndex")?,
458            gram_token_list: prop_symbol(image, "GrammarRule.tokenList")?,
459            gram_token_match_list: prop_symbol(image, "GrammarRule.tokenMatchList")?,
460            gram_tag: prop_symbol(image, "GrammarRule.grammarTag")?,
461            gram_misc_vocab: prop_symbol(image, "GrammarRule.miscVocab")?,
462            gram_alt_props: prop_symbol(image, "GrammarRule.altProps")?,
463            gram_alt_info: object_symbol(image, "GrammarRule.GrammarAltInfo")?,
464            gram_alt_token_info: object_symbol(image, "GrammarRule.GrammarAltTokInfo")?,
465            match_values: prop_symbol(image, "IfcComparator.matchValues")?,
466            charset_unknown_exception: object_symbol(
467                image,
468                "CharacterSet.UnknownCharSetException",
469            )?,
470            file_not_found_exc: object_symbol(image, "File.FileNotFoundException")?,
471            file_creation_exc: object_symbol(image, "File.FileCreationException")?,
472            file_open_exc: object_symbol(image, "File.FileOpenException")?,
473            file_io_exc: object_symbol(image, "File.FileIOException")?,
474            file_sync_exc: object_symbol(image, "File.FileSyncException")?,
475            file_closed_exc: object_symbol(image, "File.FileClosedException")?,
476            file_mode_exc: object_symbol(image, "File.FileModeException")?,
477            file_safety_exc: object_symbol(image, "File.FileSafetyException")?,
478            compiler_exc: object_symbol(image, "CompiledCode.CompilerException")?,
479            file_info: object_symbol(image, "File.FileInfo")?,
480            filespec_get_filename: prop_symbol(image, "FileSpec.getFilename")?,
481            filespec_close_file: prop_symbol(image, "FileSpec.closeFile")?,
482            string_sth_flags: prop_symbol(image, "String.specialsToHtml.flags")?,
483            string_sth_tag: prop_symbol(image, "String.specialsToHtml.tag")?,
484            iter_get_next: INVALID_PROP,
485            iter_next_avail: INVALID_PROP,
486        };
487
488        self.create_synthesized_objects()?;
489        // Functions compiled while the program ran before its image was
490        // written go with the code.
491        self.place_dynamic_code();
492        self.create_class_objects();
493
494        if let Some(iterator) = self.meta.entry(MetaKind::Iterator) {
495            self.predef.iter_get_next = iterator.method_prop(1);
496            self.predef.iter_next_avail = iterator.method_prop(2);
497        }
498        Ok(())
499    }
500
501    /// Create the objects the VM needs that the image does not supply.
502    /// They are created in the same order as in the reference VM, so
503    /// that objects the program creates later get the same IDs.
504    pub(crate) fn create_synthesized_objects(&mut self) -> VmResult<()> {
505        let last_prop = self.predef.last_prop;
506        self.predef.last_prop_obj = self.alloc_obj(Object::Vector(vec![Value::Prop(last_prop)]));
507        if self.predef.exception_message == INVALID_PROP || self.exception_message_synthesized {
508            self.predef.exception_message = self.alloc_prop_for_vm()?;
509            self.exception_message_synthesized = true;
510        }
511        self.predef.const_str_obj = self.alloc_obj(Object::String(Rc::from(&[][..])));
512        self.predef.const_lst_obj = self.alloc_obj(Object::List(Rc::from(&[][..])));
513        Ok(())
514    }
515
516    /// Give every built-in class that has none an object to represent
517    /// it.
518    pub(crate) fn create_class_objects(&mut self) {
519        for index in 0..self.meta.len() {
520            if self
521                .meta
522                .get(index)
523                .is_some_and(|e| !e.class_obj.is_valid())
524            {
525                let id = self.objects.alloc(Object::Class(BuiltinClass {
526                    meta_index: index as u16,
527                    modifier: ObjId::INVALID,
528                    class_state: Value::Nil,
529                }));
530                if let Some(entry) = self.meta.get_mut(index) {
531                    entry.class_obj = id;
532                }
533            }
534        }
535    }
536
537    fn alloc_prop_for_vm(&mut self) -> VmResult<PropId> {
538        let holder = self.predef.last_prop_obj;
539        match self.objects.get_mut(holder) {
540            Some(Object::Vector(items)) => match items.first() {
541                Some(Value::Prop(u16::MAX)) => Err(VmError::new(code::OUT_OF_PROPIDS)),
542                Some(Value::Prop(last)) => {
543                    let next = last + 1;
544                    items[0] = Value::Prop(next);
545                    Ok(next)
546                }
547                _ => Err(VmError::new(code::OUT_OF_PROPIDS)),
548            },
549            _ => Err(VmError::new(code::OUT_OF_PROPIDS)),
550        }
551    }
552
553    /// Run the program to its end. The program sees `args` as the
554    /// arguments of its main function.
555    ///
556    /// This is for a host that can wait for the player. With one that
557    /// cannot, use [`Vm::start`] and [`Vm::resume`].
558    pub fn run(&mut self, args: &[String]) -> VmResult<()> {
559        let mut state = self.start(args)?;
560        while state == RunState::Suspended {
561            state = self.resume()?;
562        }
563        Ok(())
564    }
565
566    /// Start the program, and run it until it ends or has to wait for
567    /// the host. The program sees `args` as the arguments of its main
568    /// function.
569    pub fn start(&mut self, args: &[String]) -> VmResult<RunState> {
570        self.sync_console_width();
571        self.build_symbol_tables();
572        self.run_static_initializers()?;
573
574        let mut items = Vec::with_capacity(args.len());
575        for arg in args {
576            let string = self.new_str(arg);
577            self.push(string);
578            items.push(string);
579        }
580        self.discard(items.len());
581        let list = self.new_list(items);
582        self.push(list);
583
584        let entry = self.entry_point;
585        let pc = self.push_frame(
586            entry,
587            1,
588            MethodContext::function(Value::FuncPtr(entry)),
589            Return::Native,
590            0,
591            Some(Box::new(NativeCall::named("Main entrypoint"))),
592        )?;
593        let base_depth = self.frames.len() - 1;
594        self.io.resumable = true;
595        self.drive(pc, base_depth)
596    }
597
598    /// Carry on with a program that stopped to wait for the host, until
599    /// it ends or has to wait again.
600    pub fn resume(&mut self) -> VmResult<RunState> {
601        match self.io.suspended.take() {
602            Some((pc, base_depth)) => self.drive(pc, base_depth),
603            None => Ok(RunState::Finished),
604        }
605    }
606
607    fn drive(&mut self, pc: u32, base_depth: usize) -> VmResult<RunState> {
608        match self.run_at(pc, base_depth) {
609            Err(VmError::Suspend) => Ok(RunState::Suspended),
610            result => {
611                self.io.resumable = false;
612                result.map(|()| RunState::Finished)
613            }
614        }
615    }
616
617    /// Run the initializers of `static` properties. An image that has been
618    /// pre-initialized has none left.
619    pub(crate) fn run_static_initializers(&mut self) -> VmResult<()> {
620        let initializers = self.static_initializers.clone();
621        for (object, prop) in initializers {
622            let result = self.call_prop(Value::Obj(object), prop, 0, None);
623            if let Err(error) = result {
624                if matches!(error, VmError::Unimplemented(_)) {
625                    return Err(error);
626                }
627                let message = self.error_message(&error, false);
628                return Err(VmError::with(
629                    code::EXC_IN_STATIC_INIT,
630                    vec![
631                        ErrParam::Str("[object name not available]".to_owned()),
632                        ErrParam::Str("[property name not available]".to_owned()),
633                        ErrParam::Str(message),
634                    ],
635                ));
636            }
637        }
638        Ok(())
639    }
640
641    /// The text of an exception's message, if the exception has one.
642    fn exception_text(&mut self, exception: ObjId) -> Option<String> {
643        let prop = self.predef.exception_message;
644        if prop == INVALID_PROP || !exception.is_valid() {
645            return None;
646        }
647        let (value, _) = self.obj_get_prop(exception, prop, None).ok()??;
648        let text = self.as_str(value)?;
649        Some(String::from_utf8_lossy(&text).into_owned())
650    }
651
652    /// Describe an error that ended the program, in the reference VM's
653    /// words.
654    pub fn error_message(&mut self, error: &VmError, unhandled_prefix: bool) -> String {
655        match error {
656            VmError::Thrown(exception) => match self.exception_text(*exception) {
657                Some(text) if unhandled_prefix => format!("Unhandled exception: {text}"),
658                Some(text) => text,
659                None => "unhandled exception".to_owned(),
660            },
661            VmError::Runtime(error) => format!("VM Error: {error}"),
662            VmError::Suspend => "the program is waiting for input".to_owned(),
663            VmError::Unimplemented(what) => format!("not implemented in Hexicon: {what}"),
664        }
665    }
666}