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
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
use crate::ast::parser::AssignmentTarget;

use self::super::{
	ast::parser::{BinaryOperator, Block, Expression, KeyValue, Statement},
	vm::{
		constant::{Constant, KnownValue},
		Chunk, BinaryOperation, OpCode, UnaryOperation
	}
};
use std::{collections::HashMap, convert::TryInto, iter::once};

#[macro_export]
macro_rules! insert_byte_code {
	($into:ident {$($code:tt)*}) => {{
		use $crate::byte_code;
		$into.opcodes.extend(byte_code! {$($code)*});
	}}
}

/// Compiles Lua statements into bytecode.
pub fn compile_block(block: &Block) -> Chunk {
	let mut compiler = Generator::new();
	compiler.compile(block);
	compiler.finish()
}

/// Compiles Lua statements into bytecode, as a Lua function.
///
/// The only difference between this function and [compile_block], is that this
/// function accepts arguments, and assigns received arguments to them.
pub fn compile_function(block: &Block, arguments: &[String],
		up_values: HashMap<String, (usize, bool)>, method: bool) -> Chunk {
	let mut compiler = Generator {up_values, ..Generator::new()};
	compiler.compile_function_header(arguments, method);
	compiler.compile(block);
	compiler.finish()
}

#[derive(Clone, Debug)]
enum CompileResult {
	Evaluated(KnownValue),
	Register(usize, bool)
}

impl CompileResult {
	fn register(self, compiler: &mut Generator) -> usize {
		match self {
			Self::Evaluated(known) => compiler.compile_known(known),
			Self::Register(register, tuple) => {
				if tuple {compiler.unwrap_tuple(register)}
				register
			}
		}
	}
}

#[derive(Debug)]
struct Generator {
	/// The constant pool.
	///
	/// The constant pool is a staic list of primitive values that can be loaded
	/// during runtime. During compile time, this list is typically accessed
	/// indirectly via the [CompileResult] and [KnownValue] types.
	constants: Vec<Constant>,
	opcodes: Vec<OpCode<'static>>,

	up_values: HashMap<String, (usize, bool)>,

	// TODO: currently only written to
	registers: Vec<Option<KnownValue>>,
	evaluated_variables: HashMap<String, KnownValue>,
	variables_to_registers: HashMap<String, usize>
}

impl Generator {
	fn new() -> Self {
		Self::default()
	}

	fn opcode(&mut self, opcode: OpCode<'static>) {
		self.opcodes.push(opcode);
	}

	fn register(&mut self) -> usize {
		self.registers.push(None);
		self.registers.len() - 1
	}

	fn compile_known(&mut self, value: impl Into<KnownValue>) -> usize {
		let value = value.into();

		if let Some(register) = self.registers.iter()
				.position(|known| known.as_ref().map(|known| known == &value)
					.unwrap_or(false))
			{return register}

		let register = self.register();
		self.registers[register] = Some(value.clone());
		let value = match value {
			KnownValue::Nil => {
				self.opcode(OpCode::LoadConst {constant: u16::MAX, register});
				return register
			},
			KnownValue::Integer(value) => Constant::Integer(value),
			KnownValue::String(value) => Constant::String(value),
			KnownValue::Boolean(value) => Constant::Boolean(value)
		};

		let constant = self.constants.iter()
			.position(|constant| constant == &value)
			.unwrap_or_else(|| {
				self.constants.push(value);
				self.constants.len() - 1
			}) as u16;
		self.opcode(OpCode::LoadConst {constant, register});
		register
	}

	fn finish(self) -> Chunk {
		let Self {constants, opcodes, registers, up_values, ..} = self;

		let registers = registers.len() + 1; // 0th register is always arguments.

		let up_values =
			(0..up_values.values().filter_map(|&(a, b)| (!b).then(|| a))
				.max().map(|v| v + 1).unwrap_or(0)).map(|a| (a, false))
			.chain((0..up_values.values().filter_map(|&(a, b)| b.then(|| a))
				.max().map(|v| v + 1).unwrap_or(0)).map(|a| (a, true)))
			.collect::<Vec<_>>();

		Chunk {constants, opcodes, registers, up_values}
	}

	fn up_value_id(&self, (up_value, use_up_value): (usize, bool)) -> usize {
		match use_up_value {
			true => up_value + self.up_values.values()
				.filter_map(|(up_value, use_up_value)|
					(!use_up_value).then(|| *up_value))
				.max().unwrap_or(0),
			false => up_value
		}
	}

	fn unwrap_tuple(&mut self, tuple: usize) {
		let index = self.compile_known(1);
		self.opcode(OpCode::IndexRead {index, indexee: tuple, destination: tuple});
	}

	fn compile(&mut self, block: &Block) {
		let Block(block) = block;
		let mut current_statement = 0;

		loop {
			if current_statement >= block.len() {return}

			match &block[current_statement] {
				// Control

				// TODO: else_ifs
				Statement::If {condition, then, r#else, ..} =>
						match self.compile_expression(condition) {
					// We know what condition is now.
					CompileResult::Evaluated(result) => {
						if result.coerce_to_bool() {
							// If the condition is known to be true, we can skip compiling
							// any other block except then.
							self.compile(then);
						} else if let Some(r#else) = r#else {
							// Or, if it's known to be false, we can do the same thing but
							// with r#else...
							self.compile(r#else);
						}
					},
					// We don't know what condition is.
					CompileResult::Register(variable, tuple) => match r#else {
						Some(r#else) => {
							// Jump If local To 'then
							// Block r#else
							// Jump To 'done
							// 'then
							// Block then
							// 'done

							if tuple {self.unwrap_tuple(variable)}

							let jump_then = self.opcodes.len();
							self.opcode(OpCode::NoOp);
							self.compile(r#else);
							let jump_done = self.opcodes.len();
							self.opcode(OpCode::NoOp);

							self.opcodes[jump_then] = OpCode::Jump {
								r#if: Some(variable),
								operation: self.opcodes.len() as u64
							};
							// TODO: Everytime we add a jump opcode we have to add this or
							// else internal state gets funky. Need a better long term
							// solution..
							self.registers.iter_mut().for_each(|value| *value = None);
							self.compile(then);
							self.opcodes[jump_done] = OpCode::Jump {
								r#if: None,
								operation: self.opcodes.len() as u64
							};
							self.registers.iter_mut().for_each(|value| *value = None);
						},
						None => {
							// UnaryOperation not local To local
							// Jump If local To 'skip
							// Block then
							// 'skip

							self.opcode(OpCode::UnaryOperation {
								operand: variable,
								operation: UnaryOperation::LogicalNot,
								destination: variable
							});
							let jump = self.opcodes.len();
							self.opcode(OpCode::NoOp);
							self.compile(then);

							self.registers.iter_mut().for_each(|value| *value = None);
							self.opcodes[jump] = OpCode::Jump {
								r#if: Some(variable),
								operation: self.opcodes.len() as u64
							};
						}
					}
				},

				Statement::GenericFor {variable, iterator, r#do} => {
					self.prepare_side_effects();

					let top = self.opcodes.len() as u64;
					let function = self.compile_expression(iterator).register(self);
					let arguments = self.register();

					self.opcode(OpCode::Create {destination: arguments});
					//let index = self.compile_known(2 as i64);
					//self.opcode(OpCode::IndexWrite {indexee: arguments, index, value})

					let destination = self.register();
					let index = self.compile_known(1);
					self.opcode(OpCode::Call {function, arguments, destination});
					self.opcode(OpCode::IndexRead {indexee: destination,
						index, destination});
					let condition = self.register();
					let right = self.compile_known(KnownValue::Nil);
					self.opcode(OpCode::BinaryOperation {left: destination, right,
						operation: BinaryOperation::Equal, destination: condition});
					let done = self.opcodes.len();
					self.opcode(OpCode::NoOp);

					self.variables_to_registers.insert(variable.clone(), destination);
					self.compile(r#do);
					self.opcode(OpCode::Jump {operation: top, r#if: None});

					self.opcodes[done] = OpCode::Jump {
						operation: self.opcodes.len() as u64, r#if: Some(condition)};
					self.registers.iter_mut().for_each(|value| *value = None);
				},

				Statement::NumericFor {variable, first, step, limit, r#do} => {
					self.prepare_side_effects();

					let value = self.compile_expression(first).register(self);
					let limit = self.compile_expression(limit).register(self);
					let step = self.compile_expression(step).register(self);
					let condition = self.register();

					let value = {
						let new = self.register();
						self.opcode(OpCode::ReAssign {actor: value, destination: new});
						new
					};

					let operation = self.opcodes.len() as u64;
					self.registers.iter_mut().for_each(|value| *value = None);

					self.variables_to_registers.insert(variable.clone(), value);
					self.compile(r#do);
					self.opcode(OpCode::BinaryOperation {left: value, right: limit,
						operation: BinaryOperation::Equal, destination: condition});
					let jump = self.opcodes.len();
					self.opcode(OpCode::NoOp);
					self.opcode(OpCode::BinaryOperation {left: value, right: step,
						operation: BinaryOperation::Add, destination: value});
					self.opcode(OpCode::Jump {operation, r#if: None});

					self.opcodes[jump] = OpCode::Jump {r#if: Some(condition),
						operation: self.opcodes.len() as u64};
					self.registers.iter_mut().for_each(|value| *value = None);
				},

				Statement::While {block, condition, run_first: false} => {
					self.prepare_side_effects();

					let operation = self.opcodes.len() as u64;
					let operand = self.compile_expression(condition).register(self);
					self.opcode(OpCode::UnaryOperation {operand, destination: operand,
						operation: UnaryOperation::LogicalNot});
					let jump = self.opcodes.len();
					self.opcode(OpCode::NoOp);
					
					self.compile(block);
					self.opcode(OpCode::Jump {operation, r#if: None});
					self.opcodes[jump] = OpCode::Jump {operation: self.opcodes.len() as u64, r#if: Some(operand)};
					self.registers.iter_mut().for_each(|value| *value = None);
				},

				Statement::While {block, condition, run_first: true} => {
					self.prepare_side_effects();

					let operation = self.opcodes.len() as u64;
					self.compile(block);

					let operand = self.compile_expression(condition).register(self);
					self.opcode(OpCode::UnaryOperation {operand, destination: operand,
						operation: UnaryOperation::LogicalNot});
					self.opcode(OpCode::Jump {operation, r#if: Some(operand)});
					self.registers.iter_mut().for_each(|value| *value = None);
				},

				Statement::Return {values} => {
					let destination = self.register();
					self.opcode(OpCode::Create {destination});
					values.iter().enumerate().for_each(|(index, value)| {
						let index = self.compile_known(index as i64 + 1);
						let variable = self.compile_expression(value).register(self);

						self.opcode(OpCode::IndexWrite {indexee: destination, index, value: variable});
					});

					let zero = self.compile_known(0i64);
					let count = self.compile_known(values.len() as i64);
					self.opcode(OpCode::IndexWrite {indexee: destination, index: zero, value: count});

					self.opcode(OpCode::Return {result: destination});
				},

				// Assignment

				Statement::Assign {variables, values} => {
					let mut variables = once(&variables.0).chain(variables.1.iter());
					let mut names = Vec::new();
					let mut value = {
						let values: Vec<_> = values.iter()
							.map(|value| self.compile_expression(value)).collect();
						iter_tuple(values.into_iter())
					};

					while let Some(target) = variables.next() {
							match (target, value(self)) {
						(AssignmentTarget::Identifier(identifier),
								CompileResult::Evaluated(value)) => match (
							self.evaluated_variables.get(identifier),
							self.variables_to_registers.get(identifier),
							self.up_values.get(identifier)
						) {
							(Some(_), _, _) => names.push((identifier.clone(),
								CompileResult::Evaluated(value))),
							(None, Some(&register), _) => {
								// TODO: We could probably add destination to compile_known?
								let old = self.compile_known(value.clone());
								insert_byte_code!(self {reas old, register});
								self.registers[register] = Some(value);
							},
							(None, None, Some(&up_value)) => {
								let register = self.compile_known(value);
								let up_value = self.up_value_id(up_value);
								insert_byte_code!(self {suv register, ^up_value})
							},
							(None, None, None) => {
								let global = Box::leak(identifier.clone().into_boxed_str());
								let register = self.compile_known(value);
								self.opcode(OpCode::SaveGlobal {register, global});
								// FIXME: Requires GATs
								//insert_byte_code!(self {sglb register, {&*global}});
							},
						},
						(AssignmentTarget::Identifier(identifier),
								CompileResult::Register(old, tuple)) => {
							if tuple {self.unwrap_tuple(old)}
							match (
								self.evaluated_variables.get(identifier),
								self.variables_to_registers.get(identifier),
								self.up_values.get(identifier)
							) {
								(Some(_), _, _) => names.push((identifier.clone(),
									CompileResult::Register(old, false))),
								// TODO: This is what destination in compile_expression was
								// for.
								(None, Some(&new), _) =>
									insert_byte_code!(self {reas old, new}),
								(None, None, Some(&up_value)) => {
									let up_value = self.up_value_id(up_value);
									insert_byte_code!(self {suv old, ^up_value})
								},
								(None, None, None) => {
									let global = Box::leak(identifier.clone().into_boxed_str());
									self.opcode(OpCode::SaveGlobal {register: old, global});
									// FIXME: Requires GATs
									//insert_byte_code!(self {sglb register, {&*global}});
								}
							}
						}
						(AssignmentTarget::Index {indexee, index},
								CompileResult::Evaluated(value)) => {
							let indexee = self.compile_expression(indexee).register(self);
							let index = self.compile_expression(index).register(self);
							let register = self.compile_known(value);
							insert_byte_code!(self {idxw indexee, index, register});
						},
						(AssignmentTarget::Index {indexee, index},
								CompileResult::Register(value, tuple)) => {
							if tuple {self.unwrap_tuple(value)}
							let indexee = self.compile_expression(indexee).register(self);
							let index = self.compile_expression(index).register(self);
							insert_byte_code!(self {idxw indexee, index, value});
						}
					}}

					names.into_iter()
						.for_each(|(name, value)| match value {
							CompileResult::Register(value, _) => {
								self.evaluated_variables.remove(&name);
								self.variables_to_registers.insert(name, value);
							},
							CompileResult::Evaluated(value) => {
								// TODO: Next line may not be necessary?
								self.variables_to_registers.remove(&name);
								self.evaluated_variables.insert(name, value);
							}
						});
				},

				Statement::LocalAssign {variables, values} => {
					let mut variables = once(&variables.0).chain(variables.1.iter());
					let mut names = Vec::new();
					let mut value = {
						let values: Vec<_> = values.iter()
							.map(|value| self.compile_expression(value)).collect();
						iter_tuple(values.into_iter())
					};

					while let Some(name) = variables.next() {match value(self) {
						CompileResult::Evaluated(value) => {
							// We don't have to assign this variable immediately, because
							// it's known.
							names.push((name.clone(),
								CompileResult::Evaluated(value)));
						},
						CompileResult::Register(register, tuple) => {
							// identifier already has it's own register. We don't want to
							// be able to change it's data if we write to the new
							// variable, so we make a new register, and reassign.

							let destination = self.register();
							if tuple {self.unwrap_tuple(register)}
							insert_byte_code!(self {reas register, destination});
							names.push((name.clone(),
								CompileResult::Register(destination, false)));
						}
					}}

					names.into_iter()
						.for_each(|(name, value)| match value {
							CompileResult::Register(value, _) => {
								self.evaluated_variables.remove(&name);
								self.variables_to_registers.insert(name, value);
							},
							CompileResult::Evaluated(value) => {
								// TODO: Next line may not be necessary?
								self.variables_to_registers.remove(&name);
								self.evaluated_variables.insert(name, value);
							}
						});
				},
				/*
				(true, Expression::Identifier(name),
								CompileResult::Evaluated(value)) => {
							// We don't have to assign this variable immediately, because
							// it's known.
							clea.push((name.clone(), CompileResult::Evaluated(value)));
						},
						(true, Expression::Identifier(name),
								CompileResult::Register(actor, tuple)) => {
							// identifier already has it's own register. We don't want to
							// be able to change it's data if we write to the new
							// variable, so we make a new register, and reassign.
							if tuple {self.unwrap_tuple(actor)}
							let destination = self.register();
							self.opcode(OpCode::ReAssign {actor, destination});

							clea.push((name.clone(), CompileResult::Register(destination, false)));
						},
						(true, _, _) => panic!(),*/

				// Expressions

				Statement::FunctionCall {function, arguments} =>
					drop(self.compile_call(function, arguments)),

				Statement::MethodCall {class, method, arguments} =>
					drop(self.compile_method_call(class, method, arguments)),

				Statement::Function
						{name: (name_first, name_rest), arguments, body} => {
					self.prepare_side_effects();

					let register = self.register();
					let up_values = self.variables_to_registers.iter()
						.map(|(key, &value)| (key.clone(), (value, false)))
						.chain(self.up_values.iter()
							.map(|(key, &(value, _))| (key.clone(), (value, true))))
						.collect();
					let function = compile_function(body, arguments, up_values, false);
					self.constants.push(Constant::Chunk(function.arc()));
					let constant = self.constants.len() as u16 - 1;
					self.opcode(OpCode::LoadConst {constant, register});

					if !name_rest.is_empty() {
						let indexee = self.compile_expression(
							&Expression::Identifier(name_first.clone())).register(self);
						name_rest.iter().take(name_rest.len() - 1).for_each(|part| {
							let index = self.compile_known(KnownValue::String(part.clone()));
							self.opcode(OpCode::IndexRead {
								indexee, index, destination: indexee});
						});
						let index = self.compile_known(KnownValue::String(
							name_rest[name_rest.len() - 1].clone()));
						self.opcode(OpCode::IndexWrite {index, indexee, value: register});
					} else {
						// TODO: Assigning is hard... :(
						self.opcode(OpCode::SaveGlobal {register,
							global: Box::leak(name_first.clone().into_boxed_str())});
					}
				},

				Statement::Method
						{class: (class_first, class_rest), name, arguments, body} => {
					self.prepare_side_effects();

					let register = self.register();
					let up_values = self.variables_to_registers.iter()
						.map(|(key, &value)| (key.clone(), (value, false)))
						.chain(self.up_values.iter()
							.map(|(key, &(value, _))| (key.clone(), (value, true))))
						.collect();
					let function = compile_function(body, arguments, up_values, true);
					self.constants.push(Constant::Chunk(function.arc()));
					let constant = self.constants.len() as u16 - 1;
					self.opcode(OpCode::LoadConst {constant, register});

					let indexee = self.compile_expression(
						&Expression::Identifier(class_first.clone())).register(self);
					class_rest.iter().for_each(|part| {
						let index = self.compile_known(KnownValue::String(part.clone()));
						self.opcode(OpCode::IndexRead {
							indexee, index, destination: indexee});
					});
					let index = self.compile_known(KnownValue::String(name.clone()));
					self.opcode(OpCode::IndexWrite {index, indexee, value: register});
				},

				Statement::LocalFunction {name, arguments, body} => {
					self.prepare_side_effects();

					let register = self.register();
					let up_values = self.variables_to_registers.iter()
						.map(|(key, &value)| (key.clone(), (value, false)))
						.chain(self.up_values.iter()
							.map(|(key, &(value, _))| (key.clone(), (value, true))))
						.collect();
					let function = compile_function(body, arguments, up_values, false);
					self.constants.push(Constant::Chunk(function.arc()));
					let constant = self.constants.len() as u16 - 1;
					self.opcode(OpCode::LoadConst {constant, register});
					self.variables_to_registers.insert(name.clone(), register);
				}
			}

			current_statement += 1;
		}
	}

	fn compile_expression(&mut self, expression: &Expression) -> CompileResult {
		match expression {
			// Identifier

			Expression::Identifier(identifier) =>
					match self.evaluated_variables.get(identifier) {
				// If we evaluated a value for identifier, return it.
				Some(known) => CompileResult::Evaluated(known.clone()),
				// Otherwise, check the local scope.
				None => match self.variables_to_registers.get(identifier) {
					// If it's in local scope, return it's register.
					Some(&register) => CompileResult::Register(register, false),
					// Otherwise, check up values.
					None => match self.up_values.get(identifier) {
						Some(&up_value) => {
							let register = self.register();
							self.opcode(OpCode::LoadUpValue {up_value: self.up_value_id(up_value), register});
							CompileResult::Register(register, false)
						},
						// Otherwise, load from global scope.
						None => {
							let register = self.register();
							self.opcode(OpCode::LoadGlobal {global: Box::leak(
								identifier.clone().into_boxed_str()), register});
							CompileResult::Register(register, false)
						}
					}
				}
			},

			// Singleton literals

			// These all just return evaluated.
			Expression::Nil => CompileResult::Evaluated(KnownValue::Nil),
			Expression::True => CompileResult::Evaluated(KnownValue::Boolean(true)),
			Expression::False => CompileResult::Evaluated(KnownValue::Boolean(false)),

			// Literals

			// Same with these.
			Expression::Integer(integer) =>
				CompileResult::Evaluated(KnownValue::Integer(*integer)),
			Expression::String(string) =>
				CompileResult::Evaluated(KnownValue::String(string.clone())),

			// Complex literals

			Expression::Table {array, key_value} => {
				let register = self.register();
				self.opcode(OpCode::Create {destination: register});

				key_value.iter().for_each(|KeyValue {key, value}| {
					let key = self.compile_expression(key).register(self);
					let value = self.compile_expression(value).register(self);

					self.opcode(OpCode::IndexWrite {index: key, value, indexee: register});
				});
				array.iter().enumerate().for_each(|(index, value)| {
					let value = self.compile_expression(value).register(self);
					let temporary = self.compile_known(index as i64 + 1);
					self.opcode(OpCode::IndexWrite {index: temporary, value, indexee: register});
				});

				CompileResult::Register(register, false)
			},

			Expression::Function {arguments, body} => {
				self.prepare_side_effects();
				let up_values = self.variables_to_registers.iter()
					.map(|(key, &value)| (key.clone(), (value, false)))
					.chain(self.up_values.iter()
						.map(|(key, &(value, _))| (key.clone(), (value, true))))
					.collect();
				let function = compile_function(body, arguments, up_values, false);
				self.constants.push(Constant::Chunk(function.arc()));
				let constant = self.constants.len() as u16 - 1;
				let destination = self.register();

				self.opcode(OpCode::LoadConst {constant, register: destination});
				CompileResult::Register(destination, false)
			},

			// Operators

			Expression::Call {function, arguments} => {
				let register = self.compile_call(function, arguments);
				CompileResult::Register(register, true)
			},

			Expression::MethodCall {class, method, arguments} => {
				let register = self.compile_method_call(class, method, arguments);
				CompileResult::Register(register, true)
			},

			Expression::Index {indexee, index} => {
				let destination = self.register();
				let indexee = self.compile_expression(indexee).register(self);
				let index = self.compile_expression(index).register(self);
				self.opcode(OpCode::IndexRead {indexee, index, destination});
				CompileResult::Register(destination, false)
			},

			Expression::BinaryOperation {left, right,
					operator: BinaryOperator::LogicalAnd} =>
						match self.compile_expression(left) {
				CompileResult::Evaluated(left) =>
					if !left.coerce_to_bool() {CompileResult::Evaluated(left)}
					else {self.compile_expression(right)},
				CompileResult::Register(left, tuple) => {
					// unop not {left} {boolean}
					// cjmp {done} {boolean}
					// <right compiled to {right}>
					// reas {right} {left}
					// <location of done>

					if tuple {self.unwrap_tuple(left)}

					let boolean = self.register();
					self.opcode(OpCode::UnaryOperation {operand: left,
						operation: UnaryOperation::LogicalNot, destination: boolean});
					let jump = self.opcodes.len();
					self.opcode(OpCode::NoOp);

					let right = self.compile_expression(right).register(self);
					self.opcode(OpCode::ReAssign {actor: right, destination: left});
					let operation = self.opcodes.len() as u64;
					self.opcodes[jump] = OpCode::Jump {operation, r#if: Some(boolean)};
					self.registers.iter_mut().for_each(|value| *value = None);

					CompileResult::Register(left, false)
				}
			},

			Expression::BinaryOperation {left, right,
					operator: BinaryOperator::LogicalOr} =>
						match self.compile_expression(left) {
				CompileResult::Evaluated(left) =>
					if left.coerce_to_bool() {CompileResult::Evaluated(left)}
					else {self.compile_expression(right)},
				CompileResult::Register(left, tuple) => {
					// cjmp {done} {left}
					// <right compiled to {right}>
					// reas {right} {left}
					// <location of done>

					if tuple {self.unwrap_tuple(left)}

					let jump = self.opcodes.len();
					self.opcode(OpCode::NoOp);

					let right = self.compile_expression(right).register(self);
					self.opcode(OpCode::ReAssign {actor: right, destination: left});
					let operation = self.opcodes.len() as u64;
					self.opcodes[jump] = OpCode::Jump {operation, r#if: Some(left)};
					self.registers.iter_mut().for_each(|value| *value = None);

					CompileResult::Register(left, false)
				}
			},

			Expression::BinaryOperation {left, operator, right} => {
				let left = self.compile_expression(left).register(self);
				let right = self.compile_expression(right).register(self);
				let destination = self.register();
				self.opcode(OpCode::BinaryOperation {left, right, destination,
					operation: (*operator).try_into().unwrap()});
				CompileResult::Register(destination, false)
			},

			Expression::UnaryOperation {operator, operand} => {
				let operand = self.compile_expression(operand).register(self);
				let destination = self.register();
				self.opcode(OpCode::UnaryOperation {operand, destination,
					operation: (*operator).into()});
				CompileResult::Register(destination, false)
			}
		}
	}

	fn compile_tuple<'i, T>(&mut self, tuple: T) -> usize
			where T: Iterator<Item = &'i dyn CompileOrCompiled> {
		let mut indexee = usize::MAX;
		let mut tuple = tuple.into_iter().peekable();
		let mut index = 0usize;

		loop {
			match (tuple.next().map(|compileable| compileable.compile(self)),
					tuple.peek().is_some()) {
				// If the last argument is a tuple, and it's the *only* argument, use
				// it as the tuple.
				(Some(CompileResult::Register(register, true)), false)
						if index == 0 => break register,

				// If the last argument is a tuple, assign each item from it to the new
				// tuple.
				(Some(CompileResult::Register(other, true)), false) => {
					let mut load = |value| {
						let constant = self.constants.iter()
							.position(|constant| constant == &value)
							.unwrap_or_else(|| {
								self.constants.push(value);
								self.constants.len() - 1
							}) as u16;
						let register = self.register();
						self.opcode(OpCode::LoadConst {constant, register});
						register
					};

					let index = load(Constant::Integer(index as i64));
					let other_index = load(Constant::Integer(0i64));
					let one = load(Constant::Integer(1i64));
					let zero = load(Constant::Integer(0i64));
					self.prepare_side_effects();

					let temporary = self.register();
					let operation = self.opcodes.len() as u64;
					self.opcode(OpCode::BinaryOperation {left: index, right: one,
						operation: BinaryOperation::Add, destination: index});
					self.opcode(OpCode::BinaryOperation {left: other_index, right: one,
						operation: BinaryOperation::Add, destination: other_index});
					self.opcode(OpCode::IndexRead
						{indexee: other, index: other_index, destination: temporary});
					self.opcode(OpCode::IndexWrite {indexee, index, value: temporary});
					self.opcode(OpCode::IndexRead
						{indexee: other, index: zero, destination: temporary});
					self.opcode(OpCode::BinaryOperation {left: temporary,
						right: other_index, operation: BinaryOperation::NotEqual,
							destination: temporary});
					self.opcode(OpCode::Jump {operation, r#if: Some(temporary)});
					self.opcode(OpCode::IndexWrite {indexee, index: zero, value: index});

					break indexee
				},

				(Some(value), _) => {
					if index == 0 {
						indexee = self.register();
						self.opcode(OpCode::Create {destination: indexee});
					}

					index += 1;
					let index = self.compile_known(index as i64);
					let value = value.register(self);
					self.opcode(OpCode::IndexWrite {indexee, index, value});
				},

				(None, _) => {
					if index == 0 {
						indexee = self.register();
						self.opcode(OpCode::Create {destination: indexee});
					}

					let value = self.compile_known(index as i64);
					let index = self.compile_known(0);
					self.opcode(OpCode::IndexWrite {indexee, index, value});
					break indexee
				}
			}
		}
	}

	fn compile_call(&mut self, function: &Expression, arguments: &[Expression])
			-> usize {
		let function = self.compile_expression(function).register(self);
		let arguments = self.compile_tuple(
			arguments.iter().map(CompileOrCompiled::r#dyn));
		let destination = self.register();
		self.opcode(OpCode::Call {function, arguments, destination});
		destination
	}

	fn compile_method_call(&mut self, class: &Expression, method: &str,
			arguments: &[Expression]) -> usize {
		let class = self.compile_expression(class);
		let arguments = self.compile_tuple(once(class.r#dyn())
			.chain(arguments.iter().map(CompileOrCompiled::r#dyn)));
		let method = self.compile_known(KnownValue::String(method.to_owned()));

		let class = class.register(self);
		let destination = self.register();
		self.opcode(OpCode::IndexRead {indexee: class, index: method, destination});
		self.opcode(OpCode::Call {function: destination, arguments, destination});
		destination
	}

	fn compile_function_header(&mut self, arguments: &[String], method: bool) {
		let indexee = 0; // Function arguments...

		method.then(|| "self".to_string()).iter().chain(arguments.iter())
				.enumerate().for_each(|(index, argument)| {
			let index = self.compile_known(index as i64 + 1);
			let value = self.register();
			self.opcode(OpCode::IndexRead {index, indexee, destination: value});
			self.variables_to_registers.insert(argument.clone(), value);
		});
	}

	fn prepare_side_effects(&mut self) {
		// We need to realize all values...
		#[allow(clippy::needless_collect)] // Needed by borrow checker.
		let evaluated = self.evaluated_variables.iter()
			.map(|(name, value)| (name.clone(), value.clone()))
			.collect::<Vec<_>>();
		evaluated.into_iter()
			.for_each(|(name, value)| {
				let register = self.compile_known(value);
				self.variables_to_registers.insert(name, register);
				self.registers[register] = None;
			});
	}
}

impl Default for Generator {
	fn default() -> Self {
		Self {
			constants: Vec::default(),
			evaluated_variables: HashMap::default(),
			opcodes: Vec::default(),
			registers: vec![None],
			up_values: HashMap::default(),
			variables_to_registers: HashMap::default()
		}
	}
}

fn iter_tuple<I>(values: I) -> impl FnMut(&mut Generator) -> CompileResult
		where I: ExactSizeIterator<Item = CompileResult> {
	enum State<I>
			where I: ExactSizeIterator<Item = CompileResult> {
		Values(I),
		Call {
			tuple: usize,
			index: i64,
			temporary: usize
		}
	}

	let mut this = State::Values(values);
	move |compiler| match &mut this {
		State::Values(values) => match values.next() {
			Some(CompileResult::Register(tuple, true)) if values.len() == 0 => {
				let temporary = compiler.register();
				this = State::Call {tuple, index: 1, temporary};
				let index = compiler.compile_known(1);
				insert_byte_code!(compiler {idxr tuple, index, temporary});
				CompileResult::Register(temporary, false)
			},
			Some(result) => result,
			None => CompileResult::Register(compiler.register(), false)
		},
		&mut State::Call {tuple, ref mut index, temporary} => {
			*index += 1;
			let index = compiler.compile_known(*index);
			insert_byte_code!(compiler {idxr tuple, index, temporary});
			CompileResult::Register(temporary, false)
		}
	}
}

// Silly trait because silly borrow checker problems. Perhaps this could be used
// more in normal code?
trait CompileOrCompiled {
	fn compile(&self, compiler: &mut Generator) -> CompileResult;

	fn r#dyn(&self) -> &dyn CompileOrCompiled
			where Self: Sized {
		self as &dyn CompileOrCompiled
	}
}

impl CompileOrCompiled for CompileResult {
	fn compile(&self, _: &mut Generator) -> CompileResult {
		self.clone()
	}
}

impl CompileOrCompiled for Expression {
	fn compile(&self, compiler: &mut Generator) -> CompileResult {
		compiler.compile_expression(self)
	}
}