gruggers 0.9.0

rust implementation of the grug language
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use crate::types::{Value, GrugEntity, FileId};
use crate::ast::{
	Parameter, Statement, Expr, ExprData, MemberVariable, OnFunction,
	HelperFunction, UnaryOperator, BinaryOperator, Type, GrugAst,
};
use crate::xar::{Xar, XarHandle};
use crate::arena::Arena;
use crate::backend::Backend;
use crate::ntstring::{NTStrPtr};

use gruggers_core::runtime_error::{RuntimeError, ON_FN_TIME_LIMIT, MAX_RECURSION_LIMIT};
use gruggers_core::state::State;

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::time::{Instant, Duration};

use allocator_api2::boxed::Box;
use allocator_api2::vec::Vec;

fn copy_into_arena<'arena>(ast: &GrugAst<'_>, arena: &'arena Arena) -> GrugAst<'arena> {
	let mut members = Vec::with_capacity_in(ast.members.len(), arena);
	for member in ast.members.iter() {
		let name = copy_string(member.name, arena);
		let ty = copy_type(member.ty, arena);
		let assignment_expr = copy_expr(&member.assignment_expr, arena);
		members.push(MemberVariable {
			name,
			ty, 
			type_span: member.type_span,
			assignment_expr,
			span: member.span,
		});
	}

	let mut on_functions = Vec::with_capacity_in(ast.on_functions.len(), arena);
	for on_function in ast.on_functions.iter() {
		let Some(on_function) = on_function else {on_functions.push(None); continue;};
		let name = copy_string(on_function.name, arena);
		let mut parameters = Vec::with_capacity_in(on_function.parameters.len(), arena);
		for parameter in on_function.parameters {
			parameters.push(Parameter {
				name: copy_string(parameter.name, arena),
				ty: copy_type(parameter.ty, arena),
				..*parameter
			});
		}
		
		let body_statements = copy_statements(on_function.body_statements, arena);
		on_functions.push(Some(&*Box::leak(Box::new_in(OnFunction{
			name, 
			parameters: parameters.leak(),
			body_statements,
			span: on_function.span,
		}, arena))));
	}

	let mut helper_functions = Vec::with_capacity_in(ast.helper_functions.len(), arena);
	for helper_function in ast.helper_functions.iter() {
		let name = copy_string(helper_function.name, arena);
		let return_type = copy_type(helper_function.return_type, arena);
		let mut parameters = Vec::with_capacity_in(helper_function.parameters.len(), arena);
		for parameter in helper_function.parameters {
			parameters.push(Parameter {
				name: copy_string(parameter.name, arena),
				ty: copy_type(parameter.ty, arena),
				..*parameter
			});
		}
		
		let body_statements = copy_statements(helper_function.body_statements, arena);
		helper_functions.push(HelperFunction{
			name, 
			return_type,
			return_type_span: helper_function.return_type_span,
			parameters: parameters.leak(),
			body_statements,
			span: helper_function.span
		});
	}

	let file_text = arena.copy_str_into_nt(ast.file_text.to_str());

	GrugAst {
		members: members.leak(),
		on_functions: on_functions.leak(),
		helper_functions: helper_functions.leak(),
		file_text: file_text.as_ntstrptr(),
	}
}

fn copy_statements<'arena>(stmts: &[Statement<'_>], arena: &'arena Arena) -> &'arena mut [Statement<'arena>] {
	let mut vec = Vec::with_capacity_in(stmts.len(), arena);
	for stmt in stmts {
		let stmt = match stmt {
			Statement::Variable {
				name,
				ty,
				type_span,
				assignment_expr,
				name_span,
			} => Statement::Variable {
				name: copy_string(*name, arena),
				ty: ty.map(|ty| &*Box::leak(Box::new_in(copy_type(*ty, arena), arena))),
				type_span: *type_span,
				assignment_expr : copy_expr(assignment_expr, arena),
				name_span: *name_span,
			},
			Statement::Call(expr) => Statement::Call(copy_expr(expr, arena)),
			Statement::If {
				condition,
				is_chained,
				if_block,
				else_block,
			} => {
				let mut ifs = Vec::new();
				let mut condition = condition;
				let mut is_chained = is_chained;
				let mut if_block = if_block;
				let mut else_block = else_block;
				while *is_chained {
					ifs.push((
						copy_expr(condition, arena),
						*is_chained,
						copy_statements(if_block, arena),
					));
					(condition, is_chained, if_block, else_block) = match else_block {
						[Statement::If{condition, is_chained, if_block, else_block}] => (condition, is_chained, if_block, else_block),
						_ => panic!("invalid ast"),
					};
				}
				let mut current = Statement::If {
					condition: copy_expr(condition, arena),
					is_chained: *is_chained,
					if_block: copy_statements(if_block, arena),
					else_block: copy_statements(else_block, arena),
				};
				for (condition, is_chained, if_block) in ifs.into_iter().rev() {
					current = Statement::If {
						condition,
						is_chained,
						if_block,
						else_block: std::slice::from_mut(Box::leak(Box::new_in(current, arena))),
					};
				}
				current
			}
			Statement::While {
				condition,
				block,
			} => Statement::While {
				condition: copy_expr(condition, arena),
				block: copy_statements(block, arena),
			},
			Statement::Return {
				return_span,
				expr,
			} => Statement::Return {
				return_span: *return_span,
				expr: expr.as_ref().map(|expr| Box::leak(Box::new_in(copy_expr(expr, arena), arena))),
			},
			Statement::Comment{comment_span, value} => Statement::Comment{comment_span: *comment_span, value: copy_string(*value, arena)},
			Statement::Break(span) => Statement::Break(*span),
			Statement::Continue(span) => Statement::Continue(*span),
			Statement::EmptyLine => Statement::EmptyLine,
		};
		vec.push(stmt);
	}
	vec.leak()
}

fn copy_expr<'arena>(expr: &Expr<'_>, arena: &'arena Arena) -> Expr<'arena> {
	let result_type = expr.result_type.map(|res| &*Box::leak(Box::new_in(copy_type(*res, arena), arena)));
	let data = match &expr.data {
		ExprData::True  => ExprData::True,
		ExprData::False => ExprData::False,
		ExprData::String(string) => ExprData::String(copy_string(*string, arena)),
		ExprData::Resource(string) => ExprData::Resource(copy_string(*string, arena)),
		ExprData::Entity(string) => ExprData::Entity(copy_string(*string, arena)),
		ExprData::Identifier(string) => ExprData::Identifier(copy_string(*string, arena)),
		ExprData::Number(number, string) => ExprData::Number(*number, copy_string(*string, arena)),
		ExprData::Unary {
			op,
			expr,
			op_span,
		} => {
			ExprData::Unary {
				op: *op,
				expr: Box::leak(Box::new_in(copy_expr(expr, arena), arena)),
				op_span: *op_span,
			}
		},
		ExprData::Binary {
			op,
			left,
			right,
			op_span,
		} => {
			ExprData::Binary {
				op: *op,
				left: Box::leak(Box::new_in(copy_expr(left, arena), arena)),
				right: Box::leak(Box::new_in(copy_expr(right, arena), arena)),
				op_span: *op_span,
			}
		},
		ExprData::Call {
			receiver,
			name,
			args,
			ptr,
			name_span,
			generics,
		} => {
			ExprData::Call {
				receiver: receiver.as_ref().map(|x| &mut *arena.alloc_into(copy_expr(x, arena))),
				name: copy_string(*name, arena),
				args: arena.slice_from_iter(args.iter().map(|expr| copy_expr(expr, arena))),
				ptr: *ptr,
				name_span: *name_span,
				generics
			}
		},
		ExprData::Parenthesized(expr) => ExprData::Parenthesized(Box::leak(Box::new_in(copy_expr(expr, arena), arena))),
	};
	Expr {
		result_type,
		data,
		span: expr.span,
	}
}

fn copy_type<'arena>(ty: Type<'_>, arena: &'arena Arena) -> Type<'arena> {
	match ty {
		Type::Void => Type::Void,
		Type::Bool => Type::Bool,
		Type::Number => Type::Number,
		Type::String => Type::String,
		Type::Entity{entity_type: None} => Type::Entity{entity_type: None},
		Type::Resource{extension} => Type::Resource{extension: copy_string(extension, arena)},
		Type::Id{name, generics} => Type::Id{
			name: copy_string(name, arena),
			generics: {
				let mut temp = Vec::with_capacity_in(generics.len(), arena);
				temp.extend(generics.iter().map(|ty| {
					copy_type(*ty, arena)
				}));
				temp.leak()
			}
		},
		Type::Entity{entity_type: Some(entity_type)} => Type::Entity{entity_type: Some(copy_string(entity_type, arena))},
		Type::Existential{..} => panic!("Existential passed to backend"),
	}
}

fn copy_string<'arena>(string: NTStrPtr<'_>, arena: &'arena Arena) -> NTStrPtr<'arena> {
	arena.copy_str_into_nt(string.to_str()).as_ntstrptr()
}

struct GrugEntityData {
	pub(crate) global_variables: HashMap<&'static str, Cell<Value>>,
}

impl GrugEntityData {
	pub(crate) fn get_global_variable(&self, name: &str) -> Option<&Cell<Value>> {
		self.global_variables.get(name)
	}
}

struct CompiledFile {
	file: GrugAst<'static>,
	data: Xar<GrugEntityData>,
	_arena: Arena,
}

impl CompiledFile {
	fn new(file: GrugAst) -> Self {
		let arena = Arena::new();
		let file = unsafe{std::mem::transmute::<GrugAst<'_>, GrugAst<'static>>(copy_into_arena(&file, &arena))};
		Self {
			file,
			data: Xar::new(),
			_arena: arena,
		}
	}
}

pub struct Interpreter {
	files: RefCell<Vec<CompiledFile>>,
}

struct CallStack {
	start_time: Instant,
	local_variables: Vec<Vec<HashMap<&'static str, Value>>>,
}

impl CallStack {
	fn new() -> Self {
		Self {
			start_time: Instant::now(),
			local_variables: Vec::new(),
		}
	}
	
	fn pop_scope(&mut self) {
		self.local_variables.last_mut()
			.expect("must already have a stack frame").pop()
			.expect("must have scope");
	}

	fn add_local_variable(&mut self, name: &str, value: Value) {
		assert!(self.local_variables.last_mut()
			.expect("must have stack frame").last_mut()
			.expect("last frame must have scope").insert(unsafe{std::mem::transmute::<&str, &'static str>(name)}, value)
			.is_none(), "variable already exists");
	}

	fn pop_stack_frame(&mut self) {
		self.local_variables.pop().expect("must have stack frame");
	}

	fn push_scope(&mut self) {
		self.local_variables.last_mut()
			.expect("must already have a stack frame")
			.push(HashMap::new());
	}

	fn push_stack_frame(&mut self) {
		self.local_variables.push(Vec::new());
	}

	fn get_local_variable(&mut self, name: &str) -> Option<&mut Value> {
		for scope in self.local_variables.last_mut()?{
			if let Some(val) = scope.get_mut(name) {
				return Some(val)
			}
		}
		None
	}
}

enum GrugControlFlow {
	Return(Value),
	Break,
	Continue,
	None,
}

impl Interpreter {
	pub fn new() -> Self {
		Self {
			files: RefCell::new(Vec::new()),
		}
	}

	#[expect(clippy::too_many_arguments)]
	fn run_function<GrugState: State>(&self, call_stack: &mut CallStack, state: &GrugState, file: &CompiledFile, entity: &GrugEntityData, arguments: &'static [Parameter], values: &[Value], statements: &[Statement]) -> Option<Value> {
		if call_stack.local_variables.len() > MAX_RECURSION_LIMIT {
			state.handle_runtime_error(RuntimeError::StackOverflow);
			return None
		}
		if arguments.len() != values.len() {
			panic!("argument count mismatch")
		}
		call_stack.push_stack_frame();
		call_stack.push_scope();

		for (argument, value) in arguments.iter().zip(values) {
			call_stack.add_local_variable(argument.name.to_str(), *value);
		}
		let value = self.run_statements(call_stack, state, file, entity, statements)?;
		let value = match value {
			GrugControlFlow::Return(value) => value,
			GrugControlFlow::None          => Value{void: ()},
			GrugControlFlow::Break         => unreachable!(),
			GrugControlFlow::Continue      => unreachable!(),
		};

		call_stack.pop_scope();
		call_stack.pop_stack_frame();
		Some(value)
	}

	fn run_statements<GrugState: State>(&self, call_stack: &mut CallStack, state: &GrugState, file: &CompiledFile, entity: &GrugEntityData, statements: &[Statement]) -> Option<GrugControlFlow> {
		call_stack.push_scope();
		let mut ret_val = GrugControlFlow::None;
		'outer: for statement in statements {
			match statement {
				Statement::Variable{
					name,
					ty,
					type_span: _,
					assignment_expr,
					name_span: _,
				} => {
					let name = name.to_str();
					let assignment_expr = self.run_expr(call_stack, state, file, entity, assignment_expr)?;
					if ty.is_some() {
						call_stack.add_local_variable(name, assignment_expr);
					} else if let Some(var) = call_stack.get_local_variable(name) {
						*var = assignment_expr;
					} else if let Some(var) = entity.get_global_variable(name) {
						var.set(assignment_expr);
					} else {
						panic!("variable not found");
					}
				},
				Statement::Call(expr) => {
					self.run_expr(call_stack, state, file, entity, expr)?;
				},
				Statement::If{
					condition,
					is_chained,
					if_block,
					else_block,
				} => {
					let mut condition = condition;
					let mut is_chained = is_chained;
					let mut if_block = if_block;
					let mut else_block = else_block;
					loop {
						// if block
						if unsafe{self.run_expr(call_stack, state, file, entity, condition)?.bool} != 0 {
							let control_flow = self.run_statements(call_stack, state, file, entity, if_block)?;
							if let GrugControlFlow::None = control_flow {
								break;
							} else {
								ret_val = control_flow;
								break 'outer;
							} 
						} else {
							// else block
							if *is_chained {
								(condition, is_chained, if_block, else_block) = match else_block {
									[Statement::If{condition, is_chained, if_block, else_block}] => (condition, is_chained, if_block, else_block),
									_ => panic!("invalid ast"),
								};
								continue;
							} else {
								let control_flow = self.run_statements(call_stack, state, file, entity, else_block)?;
								if let GrugControlFlow::None = control_flow {
									break;
								} else {
									ret_val = control_flow;
									break 'outer;
								} 
							}
						}
					}
				},
				Statement::Return{
					return_span: _,
					expr,
				} => {
					if let Some(expr) = expr {
						ret_val = GrugControlFlow::Return(self.run_expr(call_stack, state, file, entity, expr)?);
					} else {
						ret_val = GrugControlFlow::Return(Value{void: ()});
					}
					break 'outer;
				},
				Statement::While{
					condition,
					block,
				} => {
					loop {
						let condition = unsafe{self.run_expr(call_stack, state, file, entity, condition)?.bool};
						if condition == 0 {
							break;
						}
						match self.run_statements(call_stack, state, file, entity, block)? {
							GrugControlFlow::Return(value) => {
								ret_val = GrugControlFlow::Return(value);
								break 'outer;
							}
							GrugControlFlow::Continue => (),
							GrugControlFlow::Break    => break,
							GrugControlFlow::None     => (),
						}
					}
				},
				Statement::Comment{comment_span: _, value: _} => (),
				Statement::Break(_) => {
					ret_val = GrugControlFlow::Break;
					break 'outer;
				},
				Statement::Continue(_) => {
					ret_val = GrugControlFlow::Continue;
					break 'outer;
				},
				Statement::EmptyLine => (),
			}
		}
		call_stack.pop_scope();
		Some(ret_val)
	}

	fn run_expr<GrugState: State>(&self, call_stack: &mut CallStack, state: &GrugState, file: &CompiledFile, entity: &GrugEntityData, expr: &Expr) -> Option<Value> {
		if call_stack.start_time.elapsed() > Duration::from_millis(ON_FN_TIME_LIMIT) {
			state.set_runtime_error(RuntimeError::ExceededTimeLimit);
			return None;
		}
		Some(match &expr.data {
			ExprData::True => Value{bool: 1},
			ExprData::False => Value{bool: 0},
			ExprData::String(value) => Value{string: unsafe{std::mem::transmute::<NTStrPtr, NTStrPtr<'static>>(*value)}},
			ExprData::Resource(value) => Value{string: unsafe{std::mem::transmute::<NTStrPtr, NTStrPtr<'static>>(*value)}},
			ExprData::Entity(value) => Value{string: unsafe{std::mem::transmute::<NTStrPtr, NTStrPtr<'static>>(*value)}},
			ExprData::Number (value, _) => Value{number: *value},
			ExprData::Identifier(name) => {
				let name = name.to_str();
				if let Some(var) = call_stack.get_local_variable(name) {
					*var
				} else {
					entity.get_global_variable(name)
						.expect("could not find variable")
						.get()
				}
			},
			ExprData::Unary{
				op,
				expr,
				..
			} => {
				let mut value = self.run_expr(call_stack, state, file, entity, expr)?;
				match (op, &expr.result_type) {
					(UnaryOperator::Not, Some(Type::Bool)) => unsafe{value.bool = (value.bool == 0) as u8},
					(UnaryOperator::Minus, Some(Type::Number)) => unsafe{value.number = -value.number},
					_ => unreachable!(),
				}
				value
			}
			ExprData::Binary{
				op,
				left,
				right,
				..
			} => {
				let first_value = self.run_expr(call_stack, state, file, entity, left)?; 
				let mut second_value = || self.run_expr(call_stack, state, file, entity, right);
				// debug_assert!(left.result_ty == right.result_ty || matches!((&left.result_ty, &right.result_ty), (Some(Type::Id{custom_name: None}), Some(Type::Id{..})) | (Some(GrugType::Id{..}), Some(GrugType::Id{custom_name: None}))));
				match (op, &left.result_type) {
					(BinaryOperator::Or,             Some(Type::Bool  ))  => Value{bool: unsafe{first_value.bool | second_value()?.bool}},
					(BinaryOperator::And,            Some(Type::Bool  ))  => Value{bool: unsafe{(first_value.bool != 0 && second_value()?.bool != 0) as u8}},
					(BinaryOperator::DoubleEquals,   Some(ty)              )  => {
						let value = match ty {
							Type::Bool => !unsafe{(first_value.bool == 0) ^ (second_value()?.bool == 0)},
							Type::Number => unsafe{first_value.number == second_value()?.number},
							Type::Id{..} => unsafe{first_value.id == second_value()?.id},
							Type::String => {
								unsafe{first_value.string.to_str() == second_value()?.string.to_str()}
							},
							_ => unreachable!(),
						};
						Value{bool: value as u8}
					},
					(BinaryOperator::NotEquals,      Some(ty)              )  => {
						let value = match ty {
							Type::Bool => unsafe{(first_value.bool == 0) ^ (second_value()?.bool == 0)}
							Type::Number => unsafe{first_value.number != second_value()?.number}
							Type::Id{..} => unsafe{first_value.id != second_value()?.id}
							Type::String => {
								unsafe{first_value.string.to_str() != second_value()?.string.to_str()}
							}
							_ => unreachable!(),
						};
						Value{bool: value as u8}
					},
					(BinaryOperator::Greater,        Some(Type::Number))  => Value{bool: unsafe{first_value.number > second_value()?.number} as u8},
					(BinaryOperator::GreaterEquals,  Some(Type::Number))  => Value{bool: unsafe{first_value.number >= second_value()?.number} as u8},
					(BinaryOperator::Less,           Some(Type::Number))  => Value{bool: unsafe{first_value.number < second_value()?.number} as u8},
					(BinaryOperator::LessEquals,     Some(Type::Number))  => Value{bool: unsafe{first_value.number <= second_value()?.number} as u8},
					(BinaryOperator::Plus,           Some(Type::Number))  => Value{number: unsafe{first_value.number + second_value()?.number}},
					(BinaryOperator::Minus,          Some(Type::Number))  => Value{number: unsafe{first_value.number - second_value()?.number}},
					(BinaryOperator::Multiply,       Some(Type::Number))  => Value{number: unsafe{first_value.number * second_value()?.number}},
					(BinaryOperator::Division,       Some(Type::Number))  => Value{number: unsafe{first_value.number / second_value()?.number}},
					_ => unreachable!(),
				}
			}
			ExprData::Call{
				name,
				args,
				ptr: None,
				..
			} => {
				let name = name.to_str();
				let values = args.iter().map(|argument| self.run_expr(call_stack, state, file, entity, argument)).collect::<Option<Vec<_>>>()?;
				for helper_fn in file.file.helper_functions.iter() {
					if helper_fn.name.to_str() != name {
						continue;
					}
					return self.run_function(call_stack, state, file, entity, helper_fn.parameters, &values, &*helper_fn.body_statements);
				}
				unreachable!("helper function not found");
			}
			ExprData::Call{
				receiver,
				name: _,
				args,
				ptr: Some(ptr),
				..
			} => {
				let mut values = if let Some(receiver) = receiver {
					vec![self.run_expr(call_stack, state, file, entity, receiver)?]
				} else {
					vec![]
				};
				args.iter().map(|arg| Some(values.push(self.run_expr(call_stack, state, file, entity, arg)?))).collect::<Option<Vec<()>>>()?;
				let ret_val = unsafe{ptr(state as *const _ as _, values.as_ptr(), &[] as *const _)};
				let ret_val = if expr.result_type == Some(&Type::Void) {Value{void: ()}} else {ret_val};
				if state.is_errorring() {
					return None;
				}
				ret_val
			}
			ExprData::Parenthesized(expr) => {
				self.run_expr(call_stack, state, file, entity, expr)?
			}
		})
	}

	fn init_global_variables<GrugState: State>(&self, state: &GrugState, file: &CompiledFile, entity: &mut GrugEntityData) -> Option<()> {
		file.file.members.iter().map(|variable| {
			let value = self.run_expr(
				&mut CallStack::new(), 
				state, 
				file,
				entity, 
				&variable.assignment_expr
			)?;
			entity.global_variables.insert(variable.name.to_str(), Cell::new(value));
			Some(())
		}).collect::<Option<Vec<_>>>()?;
		Some(())
	}
}

impl Default for Interpreter {
	fn default() -> Self {
		Self::new()
	}
}

impl Backend for Interpreter {
	#[inline]
	fn insert_file(&self, id: FileId, file: GrugAst) {
		let compiled_file = CompiledFile::new(file);
		let mut files = self.files.borrow_mut();
		if let Some(old_file) = files.get_mut(id.0 as usize) {
			*old_file = compiled_file;
		} else if files.len() == id.0 as usize {
			files.push(compiled_file);
		} else {
			unreachable!("GrugScriptIds must be contigious, Expected {}, got {}", files.len(), id.0);
		}
	}

	#[inline]
	fn init_entity<GrugState: State>(&self, state: &GrugState, entity: &GrugEntity) -> bool {
		let file = self.files.borrow();
		let file = file.get(entity.file_id.0 as usize)
			.expect("file already compiled");

		let mut data = GrugEntityData {
			global_variables: HashMap::from([("me", Cell::new(Value{id:entity.id}))]),
		};
		if self.init_global_variables(state, file, &mut data).is_none() {
			return false;
		}

		let data = file.data.insert(data);
		entity.members.set(data.as_ptr().cast());

		true
	}

	#[inline]
	fn clear_entities(&mut self) {
		self.files.borrow_mut().iter_mut().for_each(|file| {
			file.data.clear();
		});
	}

	#[inline]
	unsafe fn destroy_entity_data(&self, entity: &GrugEntity) {
		let file = self.files.borrow();
		let file = file.get(entity.file_id.0 as usize)
			.expect("file compiled");
		// This pointer is guaranteed to point within file.data because we only ever set it to file.data.
		// The only case were it may point to something else is if the entity
		// is uninitialized. That is handled by the precondition (entity must be initialized)
		// SAFETY: We only ever set the members field to a XarHandle<GrugEntityData>
		let data_ptr = unsafe{XarHandle::from_ptr(entity.members.get().cast::<GrugEntityData>())};

		// Sanity check. Should never fire and we don't want this overhead in release mode
		debug_assert!(file.data.contains(data_ptr));
		// SAFETY: data_ptr belongs to data_ptr
		unsafe {file.data.delete(data_ptr)};
	}

	#[inline]
	unsafe fn call_on_function_raw<GrugState: State>(&self, state: &GrugState, entity: &GrugEntity, on_fn_index: usize, values: *const Value) -> bool {
		let file = &self.files.borrow();
		let file = file.get(entity.file_id.0 as usize)
			.expect("file already created");

		let Some(on_function) = &file.file.on_functions[on_fn_index] else {
			return false;
		};

		let values = if on_function.parameters.is_empty() {
			&[]
		} else {
			unsafe{std::slice::from_raw_parts(values, on_function.parameters.len())}
		};

		self.run_function(
			&mut CallStack::new(),
			state,
			file,
			unsafe{entity.members.get().cast::<GrugEntityData>().as_ref()}, 
			on_function.parameters, 
			values,
			on_function.body_statements
		).is_some()
	}

	#[inline]
	fn call_on_function<GrugState: State>(&self, state: &GrugState, entity: &GrugEntity, on_fn_index: usize, values: &[Value]) -> bool {
		let file = &self.files.borrow();
		let file = file.get(entity.file_id.0 as usize)
			.expect("file already created");

		let Some(on_function) = &file.file.on_functions[on_fn_index] else {
			return false;
		};

		self.run_function(
			&mut CallStack::new(),
			state,
			file,
			unsafe{entity.members.get().cast::<GrugEntityData>().as_ref()}, 
			on_function.parameters, 
			values,
			on_function.body_statements
		).is_some()
	}

	#[inline]
	fn raise_runtime_error<GrugState: State>(&self, state: &GrugState, message: &str) {
		todo!();
	}
}