hematita 0.1.0

A memory safe Lua interpreter
Documentation
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
pub use self::{super::{Chunk, VirtualMachine}, Nillable::{Nil, NonNil}};
use hashbrown::HashMap;
use std::{borrow::Borrow, fmt::{Debug, Display, Formatter, Result as FMTResult}, hash::{BuildHasher, Hash, Hasher}, mem::take, ptr::{eq, hash}, sync::{Arc, Mutex}};

macro_rules! value_conversions {
	(
		impl<$lf:tt $(; $($param:tt),*)?> for $convert:ident @ $for:ty $code:block
		$($rest:tt)*
	) => {
		impl<$lf $(, $($param),*)?> From<$for> for Value<$lf> {
			fn from($convert: $for) -> Value<$lf> {
				$code
			}
		}

		value_conversions! {$($rest)*}
	};
	() => {}
}

macro_rules! nillable_conversions {
	(
		impl<$lf:tt $(; $($param:tt),*)?> all
		for $convert:ident @ $for:ty $code:block $($rest:tt)*
	) => {
		impl<$lf $(, $($param),*)?> IntoNillable<$lf> for $for {
			#[inline]
			fn nillable(self) -> Nillable<$lf> {
				let $convert = self;
				$code
			}
		}

		impl<$lf $(, $($param),*)?> From<$for> for Nillable<$lf> {
			#[inline]
			fn from($convert: $for) -> Self {
				$code
			}
		}

		nillable_conversions! {$($rest)*}
	};
	(
		impl<$lf:tt $(; $($param:tt),*)?>
		for $convert:ident @ $for:ty $code:block $($rest:tt)*
	) => {
		impl<$lf $(, $($param),*)?> IntoNillable<$lf> for $for {
			#[inline]
			fn nillable(self) -> Nillable<$lf> {
				let $convert = self;
				$code
			}
		}

		nillable_conversions! {$($rest)*}
	};
	() => {}
}

#[macro_export]
macro_rules! lua_value {
	($raw:literal) => {$crate::vm::value::Value::from($raw)};
	($($other:tt)*) => {Value::Table(lua_table! {$($other)*}.arc())}
}

#[macro_export]
macro_rules! lua_table {
	($($arm:tt)*) => {{
		#[allow(unused_assignments, unused_mut, unused_variables, unused_imports)]
		{
			use $crate::{vm::value::{Table, Value}, lua_table_inner, lua_value};
			use hashbrown::HashMap;
			use std::{default::Default, sync::Mutex};

			let mut table = HashMap::<Value, Value>::new();
			let mut counter = 1;

			lua_table_inner!(table counter {$($arm)*});

			Table {data: Mutex::new(table), ..Default::default()}
		}
	}}
}

#[macro_export]
macro_rules! lua_table_inner {
	($table:ident $counter:ident {[$key:expr] = $value:expr $(, $($rest:tt)*)?}) => {
		{
			$table.insert(lua_table_inner!($key), lua_table_inner!($value));
		}

		lua_table_inner!($table $counter {$($($rest)*)?});
	};
	($table:ident $counter:ident {$key:ident = $value:expr $(, $($rest:tt)*)?}) => {
		{
			$table.insert(Value::from(stringify!($key)), lua_table_inner!($value));
		}

		lua_table_inner!($table $counter {$($($rest)*)?});
	};
	($table:ident $counter:ident {$value:expr $(, $($rest:tt)*)?}) => {
		{
			$table.insert(Value::from($counter), lua_table_inner!($value));
			$counter += 1;
		}

		lua_table_inner!($table $counter {$($($rest)*)?});
	};
	($table:ident $counter:ident {$($rest:tt)*}) => {};

	($value:literal) => {lua_value!($value)};
	($value:expr) => {$value}
}

#[macro_export]
macro_rules! lua_tuple {
	($($arm:tt)*) => {{
		#[allow(unused_assignments, unused_mut, unused_variables, unused_imports)]
		{
			use $crate::{
				vm::value::{IntoNillable, Nillable::NonNil, Table, Value},
				lua_tuple_inner, lua_value
			};
			use hashbrown::HashMap;
			use std::{default::Default, sync::Mutex};

			let mut table = HashMap::<Value, Value>::new();
			let mut counter = 0;

			lua_tuple_inner!(table counter {$($arm)*});
			table.insert(Value::Integer(0), Value::Integer(counter));

			Table {data: Mutex::new(table), ..Default::default()}
		}
	}}
}

#[macro_export]
macro_rules! lua_tuple_inner {
	($table:ident $counter:ident {$value:expr $(, $($rest:tt)*)?}) => {
		{
			$counter += 1;
			if let NonNil(value) = IntoNillable::nillable(lua_tuple_inner!($value).clone()) {
				$table.insert(Value::Integer($counter), value);
			}
		}

		lua_tuple_inner!($table $counter {$($($rest)*)?});
	};
	($table:ident $counter:ident {}) => {};

	($value:literal) => {lua_value!($value)};
	($value:expr) => {$value}
}

pub trait UserData: Send + Sync {
	fn type_name(&self) -> &'static str;
}

pub type NativeFunction<'n> = &'n (dyn Fn(Arc<Table<'n>>, &VirtualMachine<'n>)
	-> Result<Arc<Table<'n>>, String> + Send + Sync);

/// Represents a lua value.
// TODO: Add floats.
#[derive(Clone)]
pub enum Value<'n> {
	Integer(i64),
	String(Box<str>),
	Boolean(bool),
	Table(Arc<Table<'n>>),
	UserData {
		data: &'n dyn UserData,
		meta: Option<Arc<Table<'n>>>
	},
	Function(Arc<Function<'n>>),
	NativeFunction(NativeFunction<'n>)
}

impl<'n> Value<'n> {
	pub fn new_string(string: impl AsRef<str>) -> Self {
		Self::String(string.as_ref().to_owned().into_boxed_str())
	}

	pub fn type_name(&self) -> &'static str {
		match self {
			Self::Integer(_) => "number",
			Self::String(_) => "string",
			Self::Boolean(_) => "boolean",
			Self::Table(_) => "table",
			Self::UserData {data, ..} => data.type_name(),
			Self::Function(_) | Self::NativeFunction(_) => "function"
		}
	}

	/// Coerces this value to a bool. The rules are as follows; If the value is
	/// not a boolean, then true is returned, otherwise the value of the bool
	/// is returned.
	pub fn coerce_to_bool(&self) -> bool {
		match self {
			Self::Boolean(value) => *value,
			_ => true
		}
	}

	/// Like [coerce_to_bool], but wraps the result in a value.
	pub fn coerce_to_boolean<'nn>(&self) -> Value<'nn> {
		Value::Boolean(self.coerce_to_bool())
	}

	pub fn integer(&self) -> Option<i64> {
		match self {
			Self::Integer(integer) => Some(*integer),
			_ => None
		}
	}

	pub fn string(&self) -> Option<&str> {
		match self {
			Self::String(string) => Some(string),
			_ => None
		}
	}

	pub fn boolean(&self) -> Option<bool> {
		match self {
			Self::Boolean(boolean) => Some(*boolean),
			_ => None
		}
	}

	pub fn table(&self) -> Option<&Arc<Table<'n>>> {
		match self {
			Self::Table(table) => Some(table),
			_ => None
		}
	}

	pub fn function(&self) -> Option<&Arc<Function<'n>>> {
		match self {
			Self::Function(function) => Some(function),
			_ => None
		}
	}
}

impl Display for Value<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		match self {
			Self::Integer(integer) => write!(f, "{}", integer),
			Self::String(string) => write!(f, "{}", string),
			Self::Boolean(boolean) => write!(f, "{}", boolean),
			Self::Table(table) => write!(f, "{}", table),
			Self::UserData {..} => todo!(),
			Self::Function(function) => write!(f, "{}", function),
			Self::NativeFunction(function) => write!(f, "function: {:p}", *function)
		}
	}
}

impl Debug for Value<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		match self {
			Self::Integer(integer) => Debug::fmt(integer, f),
			Self::String(string) => Debug::fmt(string, f),
			Self::Boolean(boolean) => Debug::fmt(boolean, f),
			Self::Table(table) => Debug::fmt(table, f),
			Self::UserData {..} => todo!(),
			Self::Function(function) => Debug::fmt(function, f),
			Self::NativeFunction(function) => write!(f, "function: {:p}", function)
		}
	}
}

impl Eq for Value<'_> {}

impl<'l, 'r> PartialEq<Value<'r>> for Value<'l> {
	fn eq(&self, other: &Value<'r>) -> bool {
		match (self, other) {
			(Self::Integer(a), Value::Integer(b)) => *a == *b,
			(Self::String(a), Value::String(b)) => *a == *b,
			(Self::Boolean(a), Value::Boolean(b)) => *a == *b,
			(Self::Function(a), Value::Function(b)) =>
				eq(Arc::as_ptr(a) as *const u8, Arc::as_ptr(b) as *const u8),
			(Self::Table(a), Value::Table(b)) =>
				eq(Arc::as_ptr(a) as *const u8, Arc::as_ptr(b) as *const u8),
			(Self::NativeFunction(a), Value::NativeFunction(b)) =>
				eq(*a as *const _ as *const u8, *b as *const _ as *const u8),
			_ => false
		}
	}
}

impl Hash for Value<'_> {
	fn hash<H>(&self, state: &mut H)
			where H: Hasher {
		match self {
			Self::Integer(integer) => integer.hash(state),
			Self::String(string) => string.hash(state),
			Self::Boolean(boolean) => boolean.hash(state),
			Self::Table(arc) => Arc::as_ptr(arc).hash(state),
			Self::UserData {data, ..} => hash(data, state),
			Self::Function(arc) => Arc::as_ptr(arc).hash(state),
			Self::NativeFunction(func) => hash(func, state)
		}
	}
}

value_conversions! {
	impl<'n> for value @ i64 {Value::Integer(value)}
	impl<'n; 'r> for value @ &'r str {Value::String(value.into())}
	impl<'n> for value @ Box<str> {Value::String(value)}
	impl<'n> for value @ String {Value::String(value.into_boxed_str())}
	impl<'n> for value @ bool {Value::Boolean(value)}
	impl<'n> for value @ Table<'n> {Value::Table(value.arc())}
	impl<'n> for value @ Arc<Table<'n>> {Value::Table(value)}
}

/// Represents a lua value that may be nil. This type has a lot in common with
/// the [Option] type, but this type has purpose built methods and trait
/// implementations for handling lua nil values. Unlike option, NillableValue
/// can only hold [Value]s or references to them.
#[derive(Clone, Eq, Hash, PartialEq)]
pub enum Nillable<'n> {
	/// Variant for when the value is not nil.
	NonNil(Value<'n>),
	/// Variant for when the value is nil.
	Nil
}

impl<'n> Nillable<'n> {
	/// Get the human readable name of the type of this value.
	pub fn type_name(&self) -> &'static str {
		match self {
			NonNil(value) => value.borrow().type_name(),
			Nil => "nil"
		}
	}

	/// Convenience method for using [Into::into] or [From::from].
	pub fn option(self) -> Option<Value<'n>> {
		self.into()
	}

	/// Like [Value::coerce_to_bool], but also handles nil cases. The rules are as
	/// follows; If the value is nil or false, false is returned, otherwise true
	/// is.
	pub fn coerce_to_bool(&self) -> bool {
		match self {
			NonNil(value) => value.borrow().coerce_to_bool(),
			Nil => false
		}
	}

	/// Like [coerce_to_bool], but wraps the result in a value.
	pub fn coerce_to_boolean<'nn>(&self) -> Value<'nn> {
		Value::Boolean(self.coerce_to_bool())
	}

	pub fn is_nil(&self) -> bool {
		matches!(self, Nil)
	}

	pub fn is_non_nil(&self) -> bool {
		matches!(self, NonNil(_))
	}
}

impl Display for Nillable<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		match self {
			Nillable::NonNil(value) => write!(f, "{}", value.borrow()),
			Nil => write!(f, "nil")
		}
	}
}

impl Debug for Nillable<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		match self {
			Nillable::NonNil(value) => write!(f, "{:?}", value.borrow()),
			Nil => write!(f, "nil")
		}
	}
}

impl Default for Nillable<'_> {
	fn default() -> Self {
		Nil
	}
}

pub trait IntoNillable<'n>: Sized {
	fn nillable(self) -> Nillable<'n>;
}

nillable_conversions! {
	// From Option

	impl<'n> all for value @ Option<Value<'n>> {
		match value {
			Some(value) => NonNil(value),
			None => Nil
		}
	}

	impl<'n; 'r> for value @ Option<&'r Value<'n>> {
		match value {
			Some(value) => NonNil(value.clone()),
			None => Nil
		}
	}

	// From Self or Value

	impl<'n> for value @ Nillable<'n> {value}
	impl<'n> all for value @ Value<'n> {NonNil(value)}

	// From Into<Value>

	impl<'n> all for value @ i64 {NonNil(value.into())}
	impl<'n; 'r> all for value @ &'r str {NonNil(value.into())}
	impl<'n> all for value @ Box<str> {NonNil(value.into())}
	impl<'n> all for value @ String {NonNil(value.into())}
	impl<'n> all for value @ bool {NonNil(value.into())}
	impl<'n> all for value @ Table<'n> {NonNil(value.into())}
	impl<'n> all for value @ Arc<Table<'n>> {NonNil(value.into())}
	impl<'n> all for _value @ () {Nil}
}

impl<'n> From<Nillable<'n>> for Option<Value<'n>> {
	fn from(nillable: Nillable<'n>) -> Self {
		match nillable {
			NonNil(value) => Some(value),
			Nil => None
		}
	}
}

#[derive(Clone, Debug)]
pub enum MaybeUpValue<'n> {
	UpValue(Arc<Mutex<Nillable<'n>>>),
	Normal(Nillable<'n>)
}

impl<'n> MaybeUpValue<'n> {
	pub fn up_value(&mut self) -> &Arc<Mutex<Nillable<'n>>> {
		match self {
			Self::UpValue(up_value) => up_value,
			Self::Normal(normal) => {
				let normal = Arc::new(Mutex::new(std::mem::replace(normal, Nil)));
				*self = Self::UpValue(normal);
				match self {
					Self::UpValue(up_value) => up_value,
					_ => unreachable!()
				}
			}
		}
	}
}

impl Default for MaybeUpValue<'_> {
	fn default() -> Self {
		Self::Normal(Nil)
	}
}

#[derive(Default)]
pub struct Table<'n> {
	pub data: Mutex<HashMap<Value<'n>, Value<'n>>>,
	pub metatable: Mutex<Option<Arc<Table<'n>>>>
}

impl<'n> Table<'n> {
	/// Inserts a value into this table as if it was an array.
	#[inline]
	pub fn array_insert(&self, index: i64, mut value: Nillable<'n>) {
		let len = self.array_len();
		let mut data = self.data.lock().unwrap();

		(index..=(len.max(1) + 1))
			.for_each(|index| match take(&mut value) {
				NonNil(new) =>
					value = data.insert(Value::Integer(index), new).nillable(),
				Nil =>
					value = data.remove(&Value::Integer(index)).nillable()
			});
	}

	#[inline]
	pub fn array_remove(&self, index: i64) -> Nillable<'n> {
		let len = self.array_len();
		let mut data = self.data.lock().unwrap();

		let mut value = Nil;
		(index..=len).rev()
			.for_each(|index| match take(&mut value) {
				NonNil(new) =>
					value = data.insert(Value::Integer(index as i64), new).nillable(),
				Nil =>
					value = data.remove(&Value::Integer(index as i64)).nillable()
			});
		value
	}

	#[inline]
	pub fn array_push(&self, value: Nillable<'n>) {
		self.array_insert(self.array_len(), value)
	}

	pub fn array_len(&self) -> i64 {
		self.data.lock().unwrap().iter()
			.filter_map(|(key, _)| key.integer())
			.fold(0, |result, index| result.max(index))
	}

	pub fn array_is_empty(&self) -> bool {
		self.data.lock().unwrap().iter()
			.any(|(key, _)| key.integer().is_some())
	}

	/// Inserts a value into this table as if it was a tuple.
	#[inline]
	pub fn tuple_insert(&self, index: i64, mut value: Nillable<'n>) {
		let len = self.tuple_len();
		let mut data = self.data.lock().unwrap();
		data.insert(Value::Integer(0), Value::Integer(len + 1));

		(index..=(len.max(1) + 1))
			.for_each(|index| match take(&mut value) {
				NonNil(new) =>
					value = data.insert(Value::Integer(index), new).nillable(),
				Nil =>
					value = data.remove(&Value::Integer(index)).nillable()
			});
	}

	pub fn tuple_len(&self) -> i64 {
		self.data.lock().unwrap().get(&Value::Integer(0))
			.unwrap().integer().unwrap()
	}

	pub fn index<'qn>(&self, index: &Value<'qn>) -> Nillable<'n> {
		// std::collections::HashMap::get's signature is overly strict. It requires
		// that Q lives as long as K does, but it only uses Q as long as the call.
		// To get around this, we *could* use the nightly feature `hash_raw_entry`,
		// or we could just require the hash library the standard library uses under
		// the hood, hashbrown. Obviously the less painful solution was taken.
		// TODO: Should we drop hashbrown as a dependency when `hash_raw_entry` is
		// stablized? Or is it better to have something that can be upgraded
		// according to semver?

		let data = self.data.lock().unwrap();
		let mut hasher = data.hasher().build_hasher();
		index.hash(&mut hasher);
		data.raw_entry().from_hash(hasher.finish(), |check| index == check)
			.map(|(_, value)| value).cloned().nillable()
		//todo!()
	}

	pub fn arc(self) -> Arc<Self> {
		Arc::new(self)
	}
}

impl<'n> PartialEq for Table<'n> {
	fn eq(&self, other: &Table<'n>) -> bool {
		eq(self, other)
	}
}

impl Display for Table<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		write!(f, "table: {:p}", &*self)
	}
}

impl Debug for Table<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		match self.data.try_lock() {
			Ok(data) => {
				let mut first = true;
				let mut comma = || {
					if first {first = false; ""}
					else {", "}
				};

				write!(f, "{{")?;
				let mut array = data.iter()
					.filter_map(|(key, value)| if let Value::Integer(key) = key
						{Some((key, value))} else {None})
					.collect::<Vec<_>>();
				array.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
				if let Some((highest, _)) = array.last() {
					(1..=**highest)
						.map(|index| array.iter().find(|value| *value.0 == index)
							.map(|(_, value)| *value))
						.try_for_each(|value| write!(f, "{}{:?}", comma(), value.nillable()))?;
				}

				data.iter()
					.try_for_each(|(key, value)| match key {
						Value::Integer(_) => Ok(()),
						key => write!(f, "{}[{:?}] = {:?}", comma(), key, value)
					})?;

				write!(f, "}}")
			},
			Err(_) => write!(f, "{{<table is being accessed>}}")
		}
	}
}

#[derive(Debug)]
pub struct Function<'n> {
	pub up_values: Box<[Arc<Mutex<Nillable<'n>>>]>,
	pub chunk: Arc<Chunk>
}

impl Function<'_> {
	pub fn arc(self) -> Arc<Self> {
		Arc::new(self)
	}
}

impl<'n> PartialEq for Function<'n> {
	fn eq(&self, other: &Function<'n>) -> bool {
		eq(self, other)
	}
}

impl Eq for Function<'_> {}

impl Display for Function<'_> {
	fn fmt(&self, f: &mut Formatter) -> FMTResult {
		write!(f, "function: {:p}", &self)
	}
}

impl From<Chunk> for Function<'_> {
	fn from(chunk: Chunk) -> Self {
		Self {chunk: chunk.arc(), up_values: vec![].into_boxed_slice()}
	}
}