1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use core::fmt::Debug;
use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc};

use crate::{
	data::Data,
	error::{Error, ErrorSource},
	evaluator,
	parser::PosNode,
};

use super::{Scope, ScopeRef};

#[derive(Debug, Clone)]
pub struct CallScope {
	parent: ScopeRef,
	arguments: Rc<Vec<Data>>,
	body_fn: Rc<Option<Function>>,
	from_scope: ScopeRef,
}

impl CallScope {
	pub fn args(&self) -> Rc<Vec<Data>> {
		Rc::clone(&self.arguments)
	}

	pub fn body_fn(&self) -> Rc<Option<Function>> {
		Rc::clone(&self.body_fn)
	}

	pub fn from_scope(&self) -> ScopeRef {
		Rc::clone(&self.from_scope)
	}
}

impl Scope for CallScope {
	fn has_function(&self, name: &str) -> bool {
		RefCell::borrow(&self.parent).has_function(name)
	}

	fn get_function(&self, name: &str) -> Option<Function> {
		RefCell::borrow(&self.parent).get_function(name)
	}

	fn set_function(&mut self, name: &str, function: Function) {
		self.parent.borrow_mut().set_function(name, function)
	}

	fn delete_function(&mut self, name: &str) {
		self.parent.borrow_mut().delete_function(name)
	}

	fn parent(&self) -> Option<ScopeRef> {
		Some(Rc::clone(&self.parent) as ScopeRef)
	}

	fn get_call_scope(&self) -> Option<Rc<RefCell<CallScope>>> {
		Some(Rc::new(RefCell::new(self.clone())))
	}

	fn set_return_value(&mut self, _value: Data) {}
	fn get_function_list(&self) -> std::collections::HashMap<String, Function> {
		HashMap::new()
	}

	fn as_any(&self) -> &dyn Any {
		self
	}
	fn as_mut(&mut self) -> &mut dyn Any {
		self
	}

	fn set_if_state(&mut self, _state: super::block_scope::IfState) {}
}

#[derive(Clone)]
pub enum Function {
	Custom {
		body: Rc<PosNode>,
		scope_ref: ScopeRef,
	},
	BuiltIn {
		callback:
			Rc<dyn Fn(Vec<Data>, Option<Function>, ScopeRef) -> Result<Data, Error>>,
	},
	Variable {
		value: Data,
		scope_ref: ScopeRef,
		name: String,
	},
	Constant {
		value: Data,
	},
}

impl Function {
	fn call_verbose(
		&self,
		args: Vec<Data>,
		body_fn: Option<Function>,
		scope: ScopeRef,
		return_scope: bool,
		abstract_call_scope: bool,
		from_scope: Option<ScopeRef>,
	) -> Result<Data, Error> {
		match self {
			Function::Custom { body, scope_ref } => {
				let call_scope = CallScope {
					parent: Rc::clone(&scope_ref),
					arguments: Rc::new(args),
					body_fn: Rc::new(body_fn),
					from_scope: Rc::clone(from_scope.as_ref().unwrap_or(&scope)),
				};

				evaluator::evaluate_verbose(
					body,
					if abstract_call_scope {
						Rc::new(RefCell::new(call_scope))
					} else {
						scope
					},
					return_scope,
					None,
				)
			}
			Function::BuiltIn { callback } => callback(args, body_fn, scope),
			Function::Variable {
				value,
				name,
				scope_ref,
			} => {
				if let Some(v) = body_fn {
					let pass = value.clone();
					scope_ref.borrow_mut().set_function(
						name,
						Function::Variable {
							value: v.call(Vec::new(), None, Rc::clone(&scope))?,
							scope_ref: Rc::clone(scope_ref),
							name: String::from(name),
						},
					);
					Ok(pass)
				} else {
					Ok(value.clone())
				}
			}
			Function::Constant { value } => {
				if let Some(_) = body_fn {
					Err(Error::new("Tried to edit constant.", ErrorSource::Internal))
				} else {
					Ok(value.clone())
				}
			}
		}
	}

	pub fn call(
		&self,
		args: Vec<Data>,
		body_fn: Option<Function>,
		scope: ScopeRef,
	) -> Result<Data, Error> {
		self.call_verbose(args, body_fn, scope, false, true, None)
	}

	pub fn call_scope(
		&self,
		args: Vec<Data>,
		body_fn: Option<Function>,
		scope: ScopeRef,
	) -> Result<Data, Error> {
		self.call_verbose(args, body_fn, scope, true, false, None)
	}

	pub fn call_from(
		&self,
		args: Vec<Data>,
		body_fn: Option<Function>,
		scope: ScopeRef,
		from_scope: Option<ScopeRef>,
	) -> Result<Data, Error> {
		self.call_verbose(args, body_fn, scope, false, true, from_scope)
	}

	pub fn call_direct(
		&self,
		args: Vec<Data>,
		body_fn: Option<Function>,
		scope: ScopeRef,
	) -> Result<Data, Error> {
		self.call_verbose(args, body_fn, scope, false, false, None)
	}
}

impl Debug for Function {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Custom { body, scope_ref: _ } => {
				f.debug_struct("Custom").field("body", body).finish()
			}
			Self::BuiltIn { .. } => f.debug_struct("BuiltIn").finish(),
			Self::Variable {
				value,
				scope_ref: _,
				name: _,
			} => f.debug_struct("Variable").field("value", value).finish(),
			Self::Constant { value } => {
				f.debug_struct("Constant").field("value", value).finish()
			}
		}
	}
}