roussillon_type_system/value/
function.rs1use crate::types::concept::Type;
2use crate::types::functional::FunctionDeclaration;
3use crate::value::concept::{DataValue, ValueCell};
4use crate::value::sequence::Sequence;
5
6pub type FunctionBody = fn(&Sequence) -> ValueCell;
7
8#[derive(Clone, Debug)]
9pub struct FunctionDefinition {
10 pub declaration: FunctionDeclaration,
11 execution: FunctionBody,
12 return_value: Option<ValueCell>,
13}
14
15impl FunctionDefinition {
16 pub fn new(declaration: FunctionDeclaration, execution: fn(&Sequence) -> ValueCell) -> Self {
17 Self {
18 declaration,
19 execution,
20 return_value: None,
21 }
22 }
23
24 pub fn call(&mut self, arguments: &Sequence) -> ValueCell {
25 self.return_value = Some((self.execution)(arguments));
26 self.unwrap_value()
27 }
28
29 pub fn has_value(&self) -> bool {
30 self.return_value.is_some()
31 }
32
33 pub fn unwrap_value(&self) -> ValueCell {
34 self.return_value.clone().expect("Return value used before the function has been called")
35 }
36}
37
38impl DataValue for FunctionDefinition {
39 fn data_type(&self) -> Type {
40 self.declaration.signature.clone()
41 }
42
43 fn raw(&self) -> Vec<u8> {
44 self.unwrap_value().borrow().raw()
45 }
46
47 fn set(&mut self, raw: &[u8]) {
48 self.call(&Sequence::from(self.declaration.signature.arguments.clone(), raw).unwrap());
49 }
50}