From c3cf09c517dcfd4adb418ff84c189dc3910f089c Mon Sep 17 00:00:00 2001 From: Sebastian Hugentobler Date: Wed, 28 May 2025 22:05:30 +0200 Subject: [PATCH] try some macro magic --- src/native_functions.rs | 41 +++++++++++++++++------------------------ 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/src/native_functions.rs b/src/native_functions.rs index 5639664..3ce4d2a 100644 --- a/src/native_functions.rs +++ b/src/native_functions.rs @@ -263,32 +263,25 @@ impl Callable for CliArgs { } } +/// Helper macro to create a (String, Value) tuple for a native function. +macro_rules! native_fn { + ($callable:expr) => {{ + let callable_rc: Rc = Rc::new($callable); + ( + callable_rc.name(), + Value::Callable((callable_rc.clone(), CallableType::Function)), + ) + }}; +} + /// Return all native functions available to the Lox interpreter pub fn all(cli_args: Vec) -> Vec<(String, Value)> { vec![ - ( - "asciiOut".into(), - Value::Callable((Rc::new(AsciiOut {}), CallableType::Function)), - ), - ( - "clock".into(), - Value::Callable((Rc::new(Clock {}), CallableType::Function)), - ), - ( - "out".into(), - Value::Callable((Rc::new(Out {}), CallableType::Function)), - ), - ( - "read".into(), - Value::Callable((Rc::new(ReadFile {}), CallableType::Function)), - ), - ( - "promptAscii".into(), - Value::Callable((Rc::new(PromptAscii {}), CallableType::Function)), - ), - ( - "args".into(), - Value::Callable((Rc::new(CliArgs { cli_args }), CallableType::Function)), - ), + native_fn!(AsciiOut {}), + native_fn!(Clock {}), + native_fn!(Out {}), + native_fn!(ReadFile {}), + native_fn!(PromptAscii {}), + native_fn!(CliArgs { cli_args }), ] }