put body of function behind Rc for cheaper copy

This commit is contained in:
Moritz Gmeiner 2024-09-03 17:07:29 +02:00
commit 7c4faebf9c
3 changed files with 8 additions and 5 deletions

View file

@ -32,7 +32,8 @@ impl LoxClass {
let name = init.name().clone(); let name = init.name().clone();
let closure = init.closure().clone(); let closure = init.closure().clone();
let param_names = init.param_names().to_vec(); let param_names = init.param_names().to_vec();
let mut body = init.body().clone();
let mut body = init.body().as_ref().clone();
if let Stmt::Block { ref mut statements } = body { if let Stmt::Block { ref mut statements } = body {
statements.push(Stmt::return_stmt(Expr::local_variable("this", 1))); statements.push(Stmt::return_stmt(Expr::local_variable("this", 1)));
@ -40,6 +41,8 @@ impl LoxClass {
panic!("Body of init method of class {name} wasn't a block"); panic!("Body of init method of class {name} wasn't a block");
} }
let body = Rc::new(body);
let new_init = Value::function(LoxFunction::new(name, closure, param_names, body)); let new_init = Value::function(LoxFunction::new(name, closure, param_names, body));
methods.insert("init".into(), new_init); methods.insert("init".into(), new_init);

View file

@ -14,7 +14,7 @@ pub struct LoxFunction {
name: SmolStr, name: SmolStr,
closure: ClosureScope, closure: ClosureScope,
param_names: Vec<SmolStr>, param_names: Vec<SmolStr>,
body: Stmt, body: Rc<Stmt>,
} }
impl LoxFunction { impl LoxFunction {
@ -22,7 +22,7 @@ impl LoxFunction {
name: impl Into<SmolStr>, name: impl Into<SmolStr>,
closure: ClosureScope, closure: ClosureScope,
param_names: Vec<SmolStr>, param_names: Vec<SmolStr>,
body: Stmt, body: Rc<Stmt>,
) -> Rc<Self> { ) -> Rc<Self> {
let name = name.into(); let name = name.into();
let fun = LoxFunction { let fun = LoxFunction {
@ -46,7 +46,7 @@ impl LoxFunction {
&self.param_names &self.param_names
} }
pub fn body(&self) -> &Stmt { pub fn body(&self) -> &Rc<Stmt> {
&self.body &self.body
} }

View file

@ -185,7 +185,7 @@ impl Eval for Expr {
let name = name.clone(); let name = name.clone();
let closure = env.collect_closure(closure_vars); let closure = env.collect_closure(closure_vars);
let param_names = param_names.clone(); let param_names = param_names.clone();
let body = body.as_ref().clone(); let body = Rc::new(body.as_ref().clone());
Ok(Value::function(LoxFunction::new( Ok(Value::function(LoxFunction::new(
name, name,