Files
not-python-rust/src/obj/function.rs
Alek Ratzloff c6e242c39d Change up how function calls are handled
This is a big one.

For a while, builtin functions were a bit cumbersome and not easily
re-entrant. If you needed to call a function from within a builtin
function, the only method of doing so was to take a `FunctionState`
parameter, which would either be "Begin", meaning the function was being
called for the first time, or "Resume", meaning the function was being
re-entered. This meant that if we wanted to call another function within
this function, we'd have to set up a whole `match` statement to figure
out whether we were re-entering the function or starting out. It was a
mess and not very ergonomic, and most importantly, made it very
difficult to implement hashmaps.

Now, builtin functions are handled a little more elegantly. A native
function is pushed to the stack, where it is detected in the
`Vm::dispatch()` function. It is then called, like normal. If the
builtin function then needs to call *another* function, it will push
that function to the stack and call it, and then call `Vm::resume()` to
resume VM execution. `Vm::dispatch()` is then called again, this time
with the current function on top of the stack. If it's another builtin
function, the above is repeated. If it's a user-defined function, then
bytecode is executed in the main `loop` inside of resume. Ultimately, we
are able to compose builtin functions like we would any other internal
function to the program. Overall this should speed things up a little,
make them a whole lot easier to read, and make them a million times
easier to compose with other builtin parts of Rust.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
2024-10-11 16:22:19 -07:00

257 lines
6.3 KiB
Rust

use std::fmt::{self, Debug, Display};
use std::rc::Rc;
use gc::{Finalize, Trace};
use crate::obj::macros::*;
use crate::obj::prelude::*;
use crate::vm::{Argc, Chunk, Frame, Function, Vm};
////////////////////////////////////////////////////////////////////////////////
// BuiltinFunction
////////////////////////////////////////////////////////////////////////////////
pub type BuiltinFunctionPtr = fn(vm: &mut Vm) -> ObjP;
#[derive(Trace, Finalize)]
pub struct BuiltinFunction {
base: Obj,
#[unsafe_ignore_trace]
name: Rc<String>,
#[unsafe_ignore_trace]
function: BuiltinFunctionPtr,
arity: Argc,
}
impl BuiltinFunction {
pub fn new(name: impl ToString, function: BuiltinFunctionPtr, arity: Argc) -> Self {
Self {
base: Default::default(),
name: Rc::new(name.to_string()),
function,
arity,
}
}
impl_create!(
name: impl ToString,
function: BuiltinFunctionPtr,
arity: Argc,
);
pub fn name(&self) -> &Rc<String> {
&self.name
}
}
impl Display for BuiltinFunction {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, fmt)
}
}
impl Debug for BuiltinFunction {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"<BuiltinFunction {}/{} at {:#x}>",
self.name(),
self.arity().unwrap(),
self.function as *const BuiltinFunctionPtr as usize
)
}
}
impl Object for BuiltinFunction {
fn arity(&self) -> Option<Argc> {
Some(self.arity)
}
fn call(&self, vm: &mut Vm, argc: Argc) {
let new_frame = Frame::new(
Rc::clone(&self.name),
Function::Builtin(self.function),
vm.stack().len() - (argc as usize),
);
vm.push_frame(new_frame);
}
impl_base_obj!(BuiltinFunction);
}
////////////////////////////////////////////////////////////////////////////////
// UserFunction
////////////////////////////////////////////////////////////////////////////////
#[derive(Clone, Trace, Finalize)]
pub struct UserFunction {
base: Obj,
#[unsafe_ignore_trace]
path: Rc<String>,
#[unsafe_ignore_trace]
name: Rc<String>,
#[unsafe_ignore_trace]
chunk: Rc<Chunk>,
arity: Argc,
captures: Vec<ObjP>,
}
impl UserFunction {
pub fn new(path: impl ToString, chunk: Chunk, arity: Argc) -> Self {
Self {
base: Default::default(),
path: Rc::new(path.to_string()),
name: Rc::new("(anonymous)".to_string()),
chunk: Rc::new(chunk),
arity,
captures: Default::default(),
}
}
impl_create!(path: impl ToString, chunk: Chunk, arity: Argc);
pub fn path(&self) -> &Rc<String> {
&self.path
}
pub fn name(&self) -> &Rc<String> {
&self.name
}
pub fn set_name(&mut self, name: Rc<String>) {
self.name = name;
}
pub fn chunk(&self) -> &Chunk {
&self.chunk
}
pub fn push_capture(&mut self, value: ObjP) {
self.captures.push(value);
}
}
impl Display for UserFunction {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, fmt)
}
}
impl Debug for UserFunction {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"<UserFunction {}/{} at 0x{:x}>",
self.name(),
self.arity().unwrap(),
self as *const _ as usize
)
}
}
impl Object for UserFunction {
fn arity(&self) -> Option<Argc> {
Some(self.arity)
}
fn call(&self, vm: &mut Vm, argc: Argc) {
assert_eq!(argc, self.arity, "argc must match arity");
let new_frame = Frame::new(
Rc::clone(&self.name),
Function::Chunk(Rc::clone(&self.chunk)),
vm.stack().len() - (argc as usize),
);
vm.push_frame(new_frame);
for capture in &self.captures {
vm.push(capture.clone());
}
}
impl_base_obj!(UserFunction);
}
////////////////////////////////////////////////////////////////////////////////
// Method
////////////////////////////////////////////////////////////////////////////////
#[derive(Trace, Finalize)]
pub struct Method {
base: Obj,
self_binding: ObjP,
function: ObjP,
}
impl Method {
pub fn new(self_binding: ObjP, function: ObjP) -> Self {
Self {
base: Default::default(),
self_binding,
function,
}
}
pub fn create(self_binding: ObjP, function: ObjP) -> ObjP {
let ptr = make_ptr(Self::new(self_binding, function));
ptr.borrow_mut().instantiate();
ptr
}
pub fn self_binding(&self) -> &ObjP {
&self.self_binding
}
}
impl Display for Method {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, fmt)
}
}
impl Debug for Method {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let function_name: Rc<_> = if let Some(function) = self
.function
.borrow()
.as_any()
.downcast_ref::<BuiltinFunction>()
{
Rc::clone(&function.name())
} else if let Some(function) = self
.function
.borrow()
.as_any()
.downcast_ref::<UserFunction>()
{
function.name().clone()
} else {
unreachable!()
};
write!(
fmt,
"<Method {}.{}/{} at {:#x}>",
self.self_binding().borrow().ty_name(),
function_name,
self.function.borrow().arity().unwrap(),
self as *const _ as usize
)
}
}
impl Object for Method {
fn arity(&self) -> Option<Argc> {
// Subtract one from the arity - this is because the VM uses arity() to check against the
// number of arguments passed.
self.function.borrow().arity().map(|arity| arity - 1)
}
fn call(&self, vm: &mut Vm, mut argc: Argc) {
let self_pos = vm.stack().len() - (argc as usize);
vm.stack_mut().insert(self_pos, self.self_binding().clone());
argc += 1;
self.function.borrow().call(vm, argc)
}
impl_base_obj!(Method);
}