Skip to main content

compiler/
vm.rs

1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::fmt;
4use std::rc::Rc;
5
6use byteorder::{BigEndian, ByteOrder};
7use object::builtins::BuiltIns;
8
9use object::Object::ClosureObj;
10use object::{BoundMethodObject, BuiltinFunc, ClassObject, Closure, InstanceObject, Object};
11
12use crate::compiler::Bytecode;
13use crate::frame::Frame;
14use crate::op_code::Opcode;
15
16const STACK_SIZE: usize = 2048;
17pub const GLOBAL_SIZE: usize = 65536;
18const MAX_FRAMES: usize = 1024;
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum VmRuntimeErrorKind {
22    Arithmetic,
23    Call,
24    Index,
25    Property,
26    Stack,
27    Type,
28}
29
30#[derive(Clone, Debug, Eq, PartialEq)]
31pub struct VmRuntimeError {
32    pub kind: VmRuntimeErrorKind,
33    pub message: String,
34}
35
36impl VmRuntimeError {
37    fn new(kind: VmRuntimeErrorKind, message: impl Into<String>) -> Self {
38        Self {
39            kind,
40            message: message.into(),
41        }
42    }
43}
44
45impl fmt::Display for VmRuntimeError {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        formatter.write_str(&self.message)
48    }
49}
50
51impl std::error::Error for VmRuntimeError {}
52
53type VmResult<T> = Result<T, VmRuntimeError>;
54
55pub struct VM {
56    constants: Vec<Rc<Object>>,
57
58    stack: Vec<Rc<Object>>,
59    sp: usize, // stack pointer. Always point to the next value. Top of the stack is stack[sp -1]
60
61    pub globals: Vec<Rc<Object>>,
62
63    frames: Vec<Frame>,
64    frame_index: usize,
65    last_error: Option<VmRuntimeError>,
66}
67
68impl VM {
69    pub fn new(bytecode: Bytecode) -> VM {
70        // it's rust, it's verbose. You can't just grow your vector size.
71        let empty_frame = Frame::new(
72            Closure {
73                func: Rc::from(object::CompiledFunction {
74                    name: String::new(),
75                    instructions: vec![],
76                    num_locals: 0,
77                    num_parameters: 0,
78                }),
79                free: vec![],
80            },
81            0,
82        );
83
84        let main_fn = Rc::from(object::CompiledFunction {
85            name: String::new(),
86            instructions: bytecode.instructions.data,
87            num_locals: 0,
88            num_parameters: 0,
89        });
90        let main_closure = Closure {
91            func: main_fn,
92            free: vec![],
93        };
94        let main_frame = Frame::new(main_closure, 0);
95        let mut frames = vec![empty_frame; MAX_FRAMES];
96        frames[0] = main_frame;
97
98        let null = Rc::new(Object::Null);
99        return VM {
100            constants: bytecode.constants,
101            stack: vec![Rc::clone(&null); STACK_SIZE],
102            sp: 0,
103            globals: vec![null; GLOBAL_SIZE],
104            frames,
105            frame_index: 1,
106            last_error: None,
107        };
108    }
109
110    pub fn new_with_global_store(bytecode: Bytecode, globals: Vec<Rc<Object>>) -> VM {
111        let mut vm = VM::new(bytecode);
112        vm.globals = globals;
113        return vm;
114    }
115
116    /// Run bytecode while retaining the error for callers of the original API.
117    /// New code should prefer [`Self::run_checked`] so failures cannot be ignored.
118    pub fn run(&mut self) {
119        let _ = self.run_checked();
120    }
121
122    pub fn run_checked(&mut self) -> VmResult<()> {
123        self.last_error = None;
124        let result = self.run_inner();
125        if let Err(error) = &result {
126            self.last_error = Some(error.clone());
127        }
128        result
129    }
130
131    pub fn last_error(&self) -> Option<&VmRuntimeError> {
132        self.last_error.as_ref()
133    }
134
135    fn run_inner(&mut self) -> VmResult<()> {
136        let mut ip: usize;
137        let mut ins: Vec<u8>;
138        while self.current_frame().ip
139            < self.current_frame().instructions().data.clone().len() as i32 - 1
140        {
141            self.current_frame().ip += 1;
142            ip = self.current_frame().ip as usize;
143            ins = self.current_frame().instructions().data.clone();
144
145            let op: u8 = *ins.get(ip).unwrap();
146            let opcode = Opcode::from_repr(op).expect("unknown opcode in compiled bytecode");
147
148            match opcode {
149                Opcode::OpConst => {
150                    let const_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
151                    self.current_frame().ip += 2;
152                    self.push(Rc::clone(&self.constants[const_index]))?;
153                }
154                Opcode::OpAdd | Opcode::OpSub | Opcode::OpMul | Opcode::OpDiv => {
155                    self.execute_binary_operation(opcode)?;
156                }
157                Opcode::OpPop => {
158                    self.pop();
159                }
160                Opcode::OpTrue => {
161                    self.push(Rc::new(Object::Boolean(true)))?;
162                }
163                Opcode::OpFalse => {
164                    self.push(Rc::new(Object::Boolean(false)))?;
165                }
166                Opcode::OpEqual
167                | Opcode::OpNotEqual
168                | Opcode::OpGreaterThan
169                | Opcode::OpLessThan => {
170                    self.execute_comparison(opcode)?;
171                }
172                Opcode::OpMinus => {
173                    self.execute_minus_operation(opcode)?;
174                }
175                Opcode::OpBang => {
176                    self.execute_bang_operation()?;
177                }
178                Opcode::OpJump => {
179                    let pos = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
180                    self.current_frame().ip = pos as i32 - 1;
181                }
182                Opcode::OpJumpNotTruthy => {
183                    let pos = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
184                    self.current_frame().ip += 2;
185                    let condition = self.pop();
186                    if !self.is_truthy(condition) {
187                        self.current_frame().ip = pos as i32 - 1;
188                    }
189                }
190                Opcode::OpNull => {
191                    self.push(Rc::new(Object::Null))?;
192                }
193                Opcode::OpGetGlobal => {
194                    let global_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
195                    self.current_frame().ip += 2;
196                    self.push(Rc::clone(&self.globals[global_index]))?;
197                }
198                Opcode::OpSetGlobal => {
199                    let global_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
200                    self.current_frame().ip += 2;
201                    self.globals[global_index] = self.pop();
202                }
203                Opcode::OpArray => {
204                    let count = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
205                    self.current_frame().ip += 2;
206                    let elements = self.build_array(self.sp - count, self.sp);
207                    self.sp -= count;
208                    self.push(Rc::new(Object::Array(elements)))?;
209                }
210                Opcode::OpHash => {
211                    let count = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
212                    self.current_frame().ip += 2;
213                    #[allow(clippy::mutable_key_type)]
214                    let elements = self.build_hash(self.sp - count, self.sp)?;
215                    self.sp -= count;
216                    self.push(Rc::new(Object::Hash(elements)))?;
217                }
218                Opcode::OpIndex => {
219                    let index = self.pop();
220                    let left = self.pop();
221                    self.execute_index_operation(left, index)?;
222                }
223                Opcode::OpReturnValue => {
224                    let return_value = self.pop();
225                    if self.frame_index == 1 {
226                        // A top-level return ends the program with this value
227                        // as its result, matching the interpreter backend.
228                        self.stack[0] = return_value;
229                        self.sp = 0;
230                        break;
231                    }
232                    let frame = self.pop_frame();
233                    self.sp = frame.base_pointer - 1;
234                    self.push(return_value)?;
235                }
236                Opcode::OpReturn => {
237                    if self.frame_index == 1 {
238                        self.stack[0] = Rc::new(object::Object::Null);
239                        self.sp = 0;
240                        break;
241                    }
242                    let frame = self.pop_frame();
243                    self.sp = frame.base_pointer - 1;
244                    self.push(Rc::new(object::Object::Null))?;
245                }
246                Opcode::OpCall => {
247                    let num_args = ins[ip + 1] as usize;
248                    self.current_frame().ip += 1;
249                    self.execute_call(num_args)?;
250                }
251                Opcode::OpSetLocal => {
252                    let local_index = ins[ip + 1] as usize;
253                    self.current_frame().ip += 1;
254                    let base = self.current_frame().base_pointer;
255                    self.stack[base + local_index] = self.pop();
256                }
257                Opcode::OpGetLocal => {
258                    let local_index = ins[ip + 1] as usize;
259                    self.current_frame().ip += 1;
260                    let base = self.current_frame().base_pointer;
261                    self.push(Rc::clone(&self.stack[base + local_index]))?;
262                }
263                Opcode::OpGetBuiltin => {
264                    let built_index = ins[ip + 1] as usize;
265                    self.current_frame().ip += 1;
266                    let definition = BuiltIns.get(built_index).unwrap().function;
267                    self.push(Rc::new(Object::Builtin(definition)))?;
268                }
269                Opcode::OpClosure => {
270                    let const_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
271                    let num_free = ins[ip + 3] as usize;
272                    self.current_frame().ip += 3;
273                    self.push_closure(const_index, num_free)?;
274                }
275                Opcode::OpGetFree => {
276                    let free_index = ins[ip + 1] as usize;
277                    self.current_frame().ip += 1;
278                    let current_closure = self.current_frame().cl.clone();
279                    self.push(current_closure.free[free_index].clone())?;
280                }
281                Opcode::OpCurrentClosure => {
282                    let current_closure = self.current_frame().cl.clone();
283                    self.push(Rc::new(Object::ClosureObj(current_closure)))?;
284                }
285                Opcode::OpClass => {
286                    let name_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
287                    self.current_frame().ip += 2;
288                    let name = self.constant_string(name_index);
289                    self.push(Rc::new(Object::Class(Rc::new(RefCell::new(ClassObject {
290                        name,
291                        constructor: None,
292                        methods: HashMap::new(),
293                    })))))?;
294                }
295                Opcode::OpMethod => {
296                    let name_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
297                    let kind = ins[ip + 3];
298                    self.current_frame().ip += 3;
299                    let name = self.constant_string(name_index);
300                    let method = self.pop();
301                    let class = match &*self.stack[self.sp - 1] {
302                        Object::Class(class) => Rc::clone(class),
303                        value => panic!("cannot install method on {}", value),
304                    };
305                    if kind == 1 {
306                        class.borrow_mut().constructor = Some(method);
307                    } else {
308                        class.borrow_mut().methods.insert(name, method);
309                    }
310                }
311                Opcode::OpGetProperty => {
312                    let name_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
313                    self.current_frame().ip += 2;
314                    let name = self.constant_string(name_index);
315                    let receiver = self.pop();
316                    let value = self.get_property(&receiver, &name)?;
317                    self.push(value)?;
318                }
319                Opcode::OpSetProperty => {
320                    let name_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
321                    self.current_frame().ip += 2;
322                    let name = self.constant_string(name_index);
323                    let value = self.pop();
324                    let receiver = self.pop();
325                    self.set_property(&receiver, name, value)?;
326                }
327                Opcode::OpNew => {
328                    let num_args = ins[ip + 1] as usize;
329                    self.current_frame().ip += 1;
330                    self.execute_new(num_args)?;
331                }
332            }
333        }
334        Ok(())
335    }
336
337    fn execute_binary_operation(&mut self, opcode: Opcode) -> VmResult<()> {
338        let right = self.pop();
339        let left = self.pop();
340        match (left.as_ref(), right.as_ref()) {
341            (Object::Integer(l), Object::Integer(r)) => {
342                let result = match opcode {
343                    Opcode::OpAdd => l.checked_add(*r).ok_or_else(|| {
344                        VmRuntimeError::new(
345                            VmRuntimeErrorKind::Arithmetic,
346                            "integer overflow in addition",
347                        )
348                    }),
349                    Opcode::OpSub => l.checked_sub(*r).ok_or_else(|| {
350                        VmRuntimeError::new(
351                            VmRuntimeErrorKind::Arithmetic,
352                            "integer overflow in subtraction",
353                        )
354                    }),
355                    Opcode::OpMul => l.checked_mul(*r).ok_or_else(|| {
356                        VmRuntimeError::new(
357                            VmRuntimeErrorKind::Arithmetic,
358                            "integer overflow in multiplication",
359                        )
360                    }),
361                    Opcode::OpDiv if *r == 0 => {
362                        Err(VmRuntimeError::new(VmRuntimeErrorKind::Arithmetic, "division by zero"))
363                    }
364                    Opcode::OpDiv => l.checked_div(*r).ok_or_else(|| {
365                        VmRuntimeError::new(
366                            VmRuntimeErrorKind::Arithmetic,
367                            "integer overflow in division",
368                        )
369                    }),
370                    _ => unreachable!("compiler emitted non-binary opcode"),
371                }?;
372                self.push(Rc::from(Object::Integer(result)))
373            }
374            (Object::String(l), Object::String(r)) if opcode == Opcode::OpAdd => {
375                self.push(Rc::from(Object::String(l.to_string() + r)))
376            }
377            _ => Err(VmRuntimeError::new(
378                VmRuntimeErrorKind::Type,
379                format!("unsupported binary operation for {} and {}", left, right),
380            )),
381        }
382    }
383
384    fn execute_comparison(&mut self, opcode: Opcode) -> VmResult<()> {
385        let right = self.pop();
386        let left = self.pop();
387        if opcode == Opcode::OpEqual || opcode == Opcode::OpNotEqual {
388            let equal = left.as_ref() == right.as_ref();
389            return self.push(Rc::new(Object::Boolean(if opcode == Opcode::OpEqual {
390                equal
391            } else {
392                !equal
393            })));
394        }
395        match (left.as_ref(), right.as_ref()) {
396            (Object::Integer(l), Object::Integer(r)) => {
397                let result = match opcode {
398                    Opcode::OpGreaterThan => l > r,
399                    Opcode::OpLessThan => l < r,
400                    _ => unreachable!("compiler emitted non-comparison opcode"),
401                };
402                self.push(Rc::from(Object::Boolean(result)))
403            }
404            _ => Err(VmRuntimeError::new(
405                VmRuntimeErrorKind::Type,
406                format!("unsupported comparison for {} and {}", left, right),
407            )),
408        }
409    }
410
411    fn execute_minus_operation(&mut self, opcode: Opcode) -> VmResult<()> {
412        let operand = self.pop();
413        match operand.as_ref() {
414            Object::Integer(value) => value
415                .checked_neg()
416                .ok_or_else(|| {
417                    VmRuntimeError::new(
418                        VmRuntimeErrorKind::Arithmetic,
419                        "integer overflow in negation",
420                    )
421                })
422                .and_then(|value| self.push(Rc::from(Object::Integer(value)))),
423            _ => Err(VmRuntimeError::new(
424                VmRuntimeErrorKind::Type,
425                format!("unsupported type for negation {:?}: {}", opcode, operand),
426            )),
427        }
428    }
429
430    fn execute_bang_operation(&mut self) -> VmResult<()> {
431        let operand = self.pop();
432        match operand.as_ref() {
433            Object::Boolean(l) => self.push(Rc::from(Object::Boolean(!*l))),
434            _ => self.push(Rc::from(Object::Boolean(false))),
435        }
436    }
437
438    pub fn last_popped_stack_elm(&self) -> Option<Rc<Object>> {
439        self.stack.get(self.sp).cloned()
440    }
441
442    fn pop(&mut self) -> Rc<Object> {
443        let o = Rc::clone(&self.stack[self.sp - 1]);
444        self.sp -= 1;
445        return o;
446    }
447
448    fn push(&mut self, o: Rc<Object>) -> VmResult<()> {
449        if self.sp >= STACK_SIZE {
450            return Err(VmRuntimeError::new(VmRuntimeErrorKind::Stack, "stack limit exceeded"));
451        }
452        self.stack[self.sp] = o;
453        self.sp += 1;
454        Ok(())
455    }
456    fn is_truthy(&self, condition: Rc<Object>) -> bool {
457        match condition.as_ref() {
458            Object::Boolean(b) => *b,
459            Object::Null => false,
460            _ => true,
461        }
462    }
463    fn build_array(&self, start: usize, end: usize) -> Vec<Rc<Object>> {
464        let mut elements = Vec::with_capacity(end - start);
465        for i in start..end {
466            elements.push(Rc::clone(&self.stack[i]));
467        }
468        return elements;
469    }
470
471    // Object's Hash impl only covers Integer/Boolean/String, which have no
472    // interior mutability, so the keys are effectively immutable.
473    #[allow(clippy::mutable_key_type)]
474    fn build_hash(&self, start: usize, end: usize) -> VmResult<HashMap<Rc<Object>, Rc<Object>>> {
475        let mut elements = HashMap::new();
476        for i in (start..end).step_by(2) {
477            let key = Rc::clone(&self.stack[i]);
478            if !key.is_hashable() {
479                return Err(VmRuntimeError::new(
480                    VmRuntimeErrorKind::Index,
481                    format!("hash key must be hashable, got {}", key),
482                ));
483            }
484            let value = Rc::clone(&self.stack[i + 1]);
485            elements.insert(key, value);
486        }
487        Ok(elements)
488    }
489
490    fn execute_index_operation(&mut self, left: Rc<Object>, index: Rc<Object>) -> VmResult<()> {
491        match (left.as_ref(), index.as_ref()) {
492            (Object::Array(l), Object::Integer(i)) => self.execute_array_index(l, *i),
493            (Object::Hash(l), _) => self.execute_hash_index(l, index),
494            _ => Err(VmRuntimeError::new(
495                VmRuntimeErrorKind::Index,
496                format!("unsupported index operation for {} with {}", left, index),
497            )),
498        }
499    }
500
501    fn execute_array_index(&mut self, array: &[Rc<Object>], index: i64) -> VmResult<()> {
502        if index < array.len() as i64 && index >= 0 {
503            self.push(Rc::clone(&array[index as usize]))
504        } else {
505            self.push(Rc::new(Object::Null))
506        }
507    }
508
509    #[allow(clippy::mutable_key_type)]
510    fn execute_hash_index(
511        &mut self,
512        hash: &HashMap<Rc<Object>, Rc<Object>>,
513        index: Rc<Object>,
514    ) -> VmResult<()> {
515        match &*index {
516            Object::Integer(_) | Object::Boolean(_) | Object::String(_) => match hash.get(&index) {
517                Some(el) => self.push(Rc::clone(el)),
518                None => self.push(Rc::new(Object::Null)),
519            },
520            _ => Err(VmRuntimeError::new(
521                VmRuntimeErrorKind::Index,
522                format!("unsupported hash index key {}", index),
523            )),
524        }
525    }
526
527    fn current_frame(&mut self) -> &mut Frame {
528        &mut self.frames[self.frame_index - 1]
529    }
530
531    fn push_frame(&mut self, frame: Frame) -> VmResult<()> {
532        if self.frame_index >= MAX_FRAMES {
533            return Err(VmRuntimeError::new(VmRuntimeErrorKind::Stack, "frame limit exceeded"));
534        }
535        self.frames[self.frame_index] = frame;
536        self.frame_index += 1;
537        Ok(())
538    }
539
540    fn pop_frame(&mut self) -> Frame {
541        self.frame_index -= 1;
542        return self.frames[self.frame_index].clone();
543    }
544
545    fn execute_call(&mut self, num_args: usize) -> VmResult<()> {
546        let callee = Rc::clone(&self.stack[self.sp - 1 - num_args]);
547        match &*callee {
548            Object::ClosureObj(cf) => self.call_closure(cf.clone(), num_args),
549            Object::Builtin(bt) => self.call_builtin(*bt, num_args),
550            Object::BoundMethod(bound) => self.call_bound_method(bound.clone(), num_args),
551            Object::Class(class) => Err(VmRuntimeError::new(
552                VmRuntimeErrorKind::Call,
553                format!("class {} must be constructed with new", class.borrow().name),
554            )),
555            _ => Err(VmRuntimeError::new(VmRuntimeErrorKind::Call, "calling non-closure")),
556        }
557    }
558
559    fn call_closure(&mut self, cl: Closure, num_args: usize) -> VmResult<()> {
560        if cl.func.num_parameters != num_args {
561            return Err(VmRuntimeError::new(
562                VmRuntimeErrorKind::Call,
563                format!(
564                    "wrong number of arguments: want={}, got={}",
565                    cl.func.num_parameters, num_args
566                ),
567            ));
568        }
569
570        let frame = Frame::new(cl.clone(), self.sp - num_args);
571        let next_sp = frame
572            .base_pointer
573            .checked_add(cl.func.num_locals)
574            .filter(|next_sp| *next_sp <= STACK_SIZE)
575            .ok_or_else(|| {
576                VmRuntimeError::new(VmRuntimeErrorKind::Stack, "stack limit exceeded")
577            })?;
578        self.push_frame(frame)?;
579        self.sp = next_sp;
580        Ok(())
581    }
582
583    fn call_builtin(&mut self, bt: BuiltinFunc, num_args: usize) -> VmResult<()> {
584        let args = self.stack[self.sp - num_args..self.sp].to_vec();
585        let result = bt(args);
586        self.sp = self.sp - num_args - 1;
587        self.push(result)
588    }
589
590    fn push_closure(&mut self, const_index: usize, num_free: usize) -> VmResult<()> {
591        match &*self.constants[const_index] {
592            Object::CompiledFunction(f) => {
593                let mut free = Vec::with_capacity(num_free);
594                for i in 0..num_free {
595                    let f = self.stack[self.sp - num_free + i].clone();
596                    free.push(f);
597                }
598                self.sp -= num_free;
599                let closure = ClosureObj(Closure {
600                    func: f.clone(),
601                    free,
602                });
603                self.push(Rc::new(closure))
604            }
605            o => {
606                panic!("not a function {}", o);
607            }
608        }
609    }
610
611    fn constant_string(&self, index: usize) -> String {
612        match &*self.constants[index] {
613            Object::String(value) => value.clone(),
614            value => panic!("expected string constant, got {}", value),
615        }
616    }
617
618    fn get_property(&self, receiver: &Rc<Object>, name: &str) -> VmResult<Rc<Object>> {
619        let Object::Instance(instance) = &**receiver else {
620            return Err(VmRuntimeError::new(
621                VmRuntimeErrorKind::Property,
622                format!("cannot read property '{}' of {}", name, receiver),
623            ));
624        };
625        if let Some(value) = instance.borrow().fields.get(name).cloned() {
626            return Ok(value);
627        }
628        let (class_name, method) = {
629            let instance_object = instance.borrow();
630            let class = instance_object.class.borrow();
631            (class.name.clone(), class.methods.get(name).cloned())
632        };
633        match method {
634            Some(method) => Ok(Rc::new(Object::BoundMethod(Rc::new(BoundMethodObject {
635                receiver: Rc::clone(instance),
636                method,
637                name: name.to_string(),
638            })))),
639            None => Err(VmRuntimeError::new(
640                VmRuntimeErrorKind::Property,
641                format!("property '{}' does not exist on {}", name, class_name),
642            )),
643        }
644    }
645
646    fn set_property(&self, receiver: &Rc<Object>, name: String, value: Rc<Object>) -> VmResult<()> {
647        let Object::Instance(instance) = &**receiver else {
648            return Err(VmRuntimeError::new(
649                VmRuntimeErrorKind::Property,
650                format!("cannot set property '{}' of {}", name, receiver),
651            ));
652        };
653        instance.borrow_mut().fields.insert(name, value);
654        Ok(())
655    }
656
657    fn execute_new(&mut self, num_args: usize) -> VmResult<()> {
658        let base = self.sp - num_args - 1;
659        let class = match &*self.stack[base] {
660            Object::Class(class) => Rc::clone(class),
661            value => {
662                return Err(VmRuntimeError::new(
663                    VmRuntimeErrorKind::Call,
664                    format!("cannot construct {}", value),
665                ))
666            }
667        };
668        let instance = Rc::new(RefCell::new(InstanceObject {
669            class: Rc::clone(&class),
670            fields: HashMap::new(),
671        }));
672        let instance_value = Rc::new(Object::Instance(instance));
673        let constructor = class.borrow().constructor.clone();
674        let Some(constructor) = constructor else {
675            if num_args != 0 {
676                return Err(VmRuntimeError::new(
677                    VmRuntimeErrorKind::Call,
678                    format!(
679                        "wrong number of arguments for {}.constructor: want=0, got={}",
680                        class.borrow().name,
681                        num_args
682                    ),
683                ));
684            }
685            self.sp = base;
686            self.push(instance_value)?;
687            return Ok(());
688        };
689
690        let closure = match &*constructor {
691            Object::ClosureObj(closure) => closure.clone(),
692            value => panic!("constructor is not a closure: {}", value),
693        };
694        let expected = closure.func.num_parameters.saturating_sub(1);
695        if expected != num_args {
696            return Err(VmRuntimeError::new(
697                VmRuntimeErrorKind::Call,
698                format!(
699                    "wrong number of arguments for {}.constructor: want={}, got={}",
700                    class.borrow().name,
701                    expected,
702                    num_args
703                ),
704            ));
705        }
706        self.rewrite_receiver_call(constructor, instance_value, num_args)?;
707        self.call_closure(closure, num_args + 1)
708    }
709
710    fn call_bound_method(&mut self, bound: Rc<BoundMethodObject>, num_args: usize) -> VmResult<()> {
711        let closure = match &*bound.method {
712            Object::ClosureObj(closure) => closure.clone(),
713            value => panic!("bound method is not a closure: {}", value),
714        };
715        let expected = closure.func.num_parameters.saturating_sub(1);
716        if expected != num_args {
717            let class_name = bound.receiver.borrow().class.borrow().name.clone();
718            return Err(VmRuntimeError::new(
719                VmRuntimeErrorKind::Call,
720                format!(
721                    "wrong number of arguments for {}.{}: want={}, got={}",
722                    class_name, bound.name, expected, num_args
723                ),
724            ));
725        }
726        let receiver = Rc::new(Object::Instance(Rc::clone(&bound.receiver)));
727        self.rewrite_receiver_call(Rc::clone(&bound.method), receiver, num_args)?;
728        self.call_closure(closure, num_args + 1)
729    }
730
731    fn rewrite_receiver_call(
732        &mut self,
733        callable: Rc<Object>,
734        receiver: Rc<Object>,
735        num_args: usize,
736    ) -> VmResult<()> {
737        if self.sp >= STACK_SIZE {
738            return Err(VmRuntimeError::new(VmRuntimeErrorKind::Stack, "stack limit exceeded"));
739        }
740        let base = self.sp - num_args - 1;
741        for index in (base + 1..self.sp).rev() {
742            self.stack[index + 1] = Rc::clone(&self.stack[index]);
743        }
744        self.stack[base] = callable;
745        self.stack[base + 1] = receiver;
746        self.sp += 1;
747        Ok(())
748    }
749}