1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum Return {
19 Normal,
21 Native,
24 Operator,
27 OperatorToLocal(u16),
31}
32
33#[derive(Debug, Clone)]
36pub(crate) struct NativeCall {
37 pub name: &'static str,
39 pub function: Option<(u16, u16)>,
41 pub self_value: Value,
43 pub method_index: u16,
45 pub args: Vec<Value>,
47 pub caller_pc: u32,
49 pub arg_top: usize,
53}
54
55impl NativeCall {
56 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#[derive(Debug, Clone)]
72pub(crate) struct Frame {
73 pub func: u32,
75 pub ret: Return,
77 pub return_pc: u32,
79 pub base: u32,
82 pub argc: u32,
84 pub prop: PropId,
86 pub target: Value,
88 pub definer: ObjId,
90 pub self_value: Value,
92 pub invokee: Value,
94 pub native: Option<Box<NativeCall>>,
96 pub frame_ref: Option<ObjId>,
99}
100
101impl Predef {
102 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#[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 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#[derive(Debug, Clone, Default)]
153pub(crate) struct Predef {
154 pub runtime_error: ObjId,
156 pub exception_message: PropId,
158 pub construct: PropId,
160 #[allow(dead_code)]
162 pub destruct: PropId,
163 pub last_prop: PropId,
165 pub prop_not_defined: PropId,
167 pub stack_info_class: ObjId,
169 pub length: PropId,
171 pub const_str_obj: ObjId,
173 pub const_lst_obj: ObjId,
175 pub last_prop_obj: ObjId,
177 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 pub reflection_services: ObjId,
195 pub reflection_val_to_symbol: PropId,
196 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 pub calc_hash: PropId,
209 pub match_values: PropId,
210 pub charset_unknown_exception: ObjId,
212 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 pub compiler_exc: ObjId,
223 pub file_info: ObjId,
225 pub filespec_get_filename: PropId,
227 pub filespec_close_file: PropId,
228 pub string_sth_flags: PropId,
230 pub string_sth_tag: PropId,
231 pub obj_to_string: PropId,
233 pub iter_get_next: PropId,
235 pub iter_next_avail: PropId,
236}
237
238#[derive(Debug, Clone)]
240pub(crate) enum StrRef {
241 Const(Rc<[u8]>, u32, u32),
243 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#[derive(Debug, Clone)]
260pub(crate) enum ListRef {
261 Const(Rc<[u8]>, u32, u32),
264 Obj(Rc<[Value]>),
266}
267
268impl ListRef {
269 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 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 pub(crate) fn iter(&self) -> impl Iterator<Item = Value> + '_ {
291 (0..self.len()).map(|index| self.get(index))
292 }
293
294 pub(crate) fn to_vec(&self) -> Vec<Value> {
296 self.iter().collect()
297 }
298}
299
300#[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 pub debug_local_header: u32,
309 pub debug_frame_header: u32,
311}
312
313pub(crate) const STACK_LIMIT: usize = 4096;
317
318pub(crate) const STACK_RESERVE: usize = 512;
322
323pub(crate) const OVERFLOW_TRACE_LEVELS: usize = 40;
326
327pub(crate) const FRAME_OVERHEAD: usize = 11;
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333pub enum RunState {
334 Finished,
336 Suspended,
340}
341
342pub(crate) const MAX_STRING_LEN: usize = 65_535;
344
345pub struct Vm {
347 pub(crate) code: Rc<[u8]>,
350 pub(crate) image_code_len: usize,
352 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 pub(crate) stack_limit: usize,
363 pub(crate) r0: Value,
365 pub(crate) pc: u32,
367 pub(crate) say_function: Value,
369 pub(crate) say_method: PropId,
371 pub(crate) entry_point: u32,
373 pub(crate) static_initializers: Vec<(ObjId, PropId)>,
375 pub(crate) debug: DebugInfo,
377 pub(crate) preinit_mode: bool,
379 pub(crate) symbol_table: Option<ObjId>,
381 pub(crate) macro_table: Option<ObjId>,
382 pub(crate) big_cache: crate::decimal_math::Cache,
384 pub(crate) rng: crate::rng::Rng,
386 pub(crate) image_timestamp: Vec<u8>,
389 pub(crate) image_name: String,
390 pub(crate) exception_message_synthesized: bool,
393 pub(crate) run_depth: u32,
396 pub(crate) in_gc: bool,
398 pub(crate) nesting: u32,
401 pub(crate) last_match: crate::string::LastMatch,
403 pub(crate) undo_stash: Option<crate::object::UndoStash>,
406 pub(crate) pattern_cache: std::collections::HashMap<Vec<u8>, Rc<crate::regex::Pattern>>,
409 pub(crate) trace_errors: bool,
411 pub(crate) reporting_overflow: bool,
413 pub(crate) console: Formatter,
415 pub(crate) io: crate::io::IoState,
416 pub(crate) host: Box<dyn Host>,
417}
418
419impl Vm {
420 #[inline]
424 pub(crate) fn push(&mut self, value: Value) {
425 self.stack.push(value);
426 }
427
428 #[inline]
430 pub(crate) fn pop(&mut self) -> Value {
431 self.stack.pop().unwrap_or(Value::Nil)
432 }
433
434 #[inline]
436 pub(crate) fn top(&self, depth: usize) -> Value {
437 match self.stack.len().checked_sub(1 + depth) {
439 Some(at) => self.stack[at],
440 None => Value::Nil,
441 }
442 }
443
444 #[inline]
446 pub(crate) fn top_mut(&mut self, depth: usize) -> &mut Value {
447 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 #[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 #[inline]
468 pub(crate) fn arg(&self, index: usize) -> Value {
469 self.top(index)
470 }
471
472 pub(crate) fn stack_depth(&self) -> usize {
474 self.stack.len() + self.frames.len() * FRAME_OVERHEAD
475 }
476
477 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 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 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 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 pub(crate) fn try_new_str(&mut self, text: &str) -> VmResult<Value> {
516 self.try_new_string(text.as_bytes())
517 }
518
519 pub(crate) fn new_str(&mut self, text: &str) -> Value {
521 self.new_string(text.as_bytes())
522 }
523
524 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 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 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 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 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 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 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 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 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 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 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 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 pub fn set_error_trace(&mut self, on: bool) {
666 self.trace_errors = on;
667 }
668
669 pub fn flush_output(&mut self) {
672 self.flush_console(Newline::None);
673 }
674}