panic on wrong number of args to functions

This commit is contained in:
Scott Richmond 2025-06-18 16:47:53 -04:00
parent 23298c8538
commit ffe5d2ad61
2 changed files with 20 additions and 1 deletions

View File

@ -45,6 +45,13 @@ impl LFn {
} }
} }
pub fn accepts(&self, arity: u8) -> bool {
match self {
LFn::Defined { chunks, .. } => chunks.iter().any(|(a, _)| *a == arity),
LFn::Declared { .. } => unreachable!(),
}
}
pub fn name(&self) -> &'static str { pub fn name(&self) -> &'static str {
match self { match self {
LFn::Declared { name } | LFn::Defined { name, .. } => name, LFn::Declared { name } | LFn::Defined { name, .. } => name,
@ -52,7 +59,6 @@ impl LFn {
} }
pub fn chunk(&self, arity: u8) -> &Chunk { pub fn chunk(&self, arity: u8) -> &Chunk {
// println!("Getting chunk of {arity} from {:?}", self);
match self { match self {
LFn::Declared { .. } => unreachable!(), LFn::Declared { .. } => unreachable!(),
LFn::Defined { chunks, .. } => &chunks.iter().find(|(a, _)| *a == arity).unwrap().1, LFn::Defined { chunks, .. } => &chunks.iter().find(|(a, _)| *a == arity).unwrap().1,
@ -268,4 +274,11 @@ impl Value {
Partial(..) => "fn", Partial(..) => "fn",
} }
} }
pub fn as_fn(&self) -> &LFn {
match self {
Value::Fn(inner) => inner.as_ref(),
_ => unreachable!(),
}
}
} }

View File

@ -790,6 +790,12 @@ impl Vm {
match val { match val {
Value::Fn(_) => { Value::Fn(_) => {
if !val.as_fn().accepts(arity) {
return self.panic_with(format!(
"wrong number of arguments to {} passing {arity} args",
val.show()
));
}
let mut frame = CallFrame { let mut frame = CallFrame {
function: val, function: val,
arity, arity,