jetcrab\runtime/
function.rs1use crate::runtime::context::Context;
2use crate::vm::value::Value;
3use std::collections::HashMap;
4
5pub type NativeFunction = fn(&mut Context, &[Value]) -> Result<Value, String>;
6
7pub struct Function {
8 pub name: String,
9 pub parameters: Vec<String>,
10 pub body: Option<Vec<u8>>,
11 pub native_function: Option<NativeFunction>,
12 pub closure: HashMap<String, Value>,
13}
14
15impl Function {
16 pub fn new(name: String, parameters: Vec<String>) -> Self {
17 Self {
18 name,
19 parameters,
20 body: None,
21 native_function: None,
22 closure: HashMap::new(),
23 }
24 }
25
26 pub fn native(name: String, parameters: Vec<String>, func: NativeFunction) -> Self {
27 Self {
28 name,
29 parameters,
30 body: None,
31 native_function: Some(func),
32 closure: HashMap::new(),
33 }
34 }
35
36 pub fn call(&self, context: &mut Context, arguments: &[Value]) -> Result<Value, String> {
37 if let Some(native_func) = self.native_function {
38 native_func(context, arguments)
39 } else {
40 Err("Function not implemented".to_string())
41 }
42 }
43
44 pub fn set_closure_variable(&mut self, name: String, value: Value) {
45 self.closure.insert(name, value);
46 }
47
48 pub fn get_closure_variable(&self, name: &str) -> Option<&Value> {
49 self.closure.get(name)
50 }
51}