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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
use source_map::{SourceId, Span, SpanWithSource};
use std::collections::HashSet;

use crate::{
	behavior::{
		assignments::{Assignable, AssignmentKind, Reference},
		functions,
		modules::{Exported, ImportKind, NamePair},
		operations::{
			evaluate_logical_operation_with_expression,
			evaluate_pure_binary_operation_handle_errors, MathematicalAndBitwise,
		},
		variables::{VariableMutability, VariableOrImport, VariableWithValue},
	},
	diagnostics::{NotInLoopOrCouldNotFindLabel, TypeCheckError, TypeStringRepresentation, TDZ},
	events::{Event, RootReference},
	subtyping::BasicEquality,
	types::{
		is_type_truthy_falsy,
		properties::{PropertyKey, PropertyKind, PropertyValue},
		subtyping::{type_is_subtype, SubTypeResult},
		PolyNature, Type, TypeStore,
	},
	CheckingData, Decidable, Instance, RootContext, TypeCombinable, TypeId,
};

use super::{
	calling::CheckThings, facts::Publicity, get_on_ctx, get_value_of_variable, AssignmentError,
	ClosedOverReferencesInScope, Context, ContextType, Environment, GeneralContext,
	SetPropertyError,
};

pub type ContextLocation = Option<String>;

#[derive(Debug)]
pub struct Syntax<'a> {
	pub scope: Scope,
	pub(super) parent: GeneralContext<'a>,

	/// Variables that this context pulls in from above (across a dynamic context). aka not from parameters of bound this
	/// Not to be confused with `closed_over_references`
	pub free_variables: HashSet<RootReference>,

	/// Variables used in this scope which are closed over by functions. These need to be stored
	/// Not to be confused with `used_parent_references`
	pub closed_over_references: ClosedOverReferencesInScope,

	/// TODO WIP! server, client, worker etc
	pub location: ContextLocation,
}

impl<'a> ContextType for Syntax<'a> {
	fn as_general_context(et: &Context<Self>) -> GeneralContext<'_> {
		GeneralContext::Syntax(et)
	}

	fn get_parent(&self) -> Option<&GeneralContext<'_>> {
		Some(&self.parent)
	}

	fn is_dynamic_boundary(&self) -> bool {
		matches!(self.scope, Scope::Function { .. } | Scope::Looping { .. })
	}

	fn is_conditional(&self) -> bool {
		matches!(self.scope, Scope::Conditional { .. })
	}

	fn get_closed_over_references(&mut self) -> Option<&mut ClosedOverReferencesInScope> {
		Some(&mut self.closed_over_references)
	}

	fn get_exports(&mut self) -> Option<&mut Exported> {
		if let Scope::Module { ref mut exported, .. } = self.scope {
			Some(exported)
		} else {
			None
		}
	}
}

/// TODO better names
/// Decides whether `await` and `yield` are available
#[derive(Debug, Clone)]
pub enum FunctionScope {
	ArrowFunction {
		// This always points to a poly free variable type
		free_this_type: TypeId,
		is_async: bool,
	},
	MethodFunction {
		// This always points to a poly free variable type
		free_this_type: TypeId,
		is_async: bool,
		is_generator: bool,
	},
	// is new-able
	Function {
		is_generator: bool,
		is_async: bool,
		// This always points to a conditional type based on `new.target === undefined`
		this_type: TypeId,
		type_of_super: TypeId,
	},
	Constructor {
		/// Can call `super`
		extends: bool,
		type_of_super: Option<TypeId>,
		// This is always creates, but may not be used (or have the relevant properties & prototype)
		this_object_type: TypeId,
	},
}

pub type Label = Option<String>;

/// TODO name of structure
/// TODO conditionals should have conditional proofs (separate from the ones on context)
#[derive(Debug, Clone)]
pub enum Scope {
	Function(FunctionScope),
	InterfaceEnvironment {
		this_constraint: TypeId,
	},
	FunctionAnnotation {},
	/// For ifs, elses, or lazy operators
	Conditional {
		/// Something that is truthy for this to run
		antecedent: TypeId,

		is_switch: Option<Label>,
	},
	/// Variables here are dependent on the iteration,
	Looping {
		label: Label, // TODO on: Proofs,
	},
	TryBlock {},
	// Just blocks and modules
	Block {},
	Module {
		source: SourceId,
		exported: Exported,
	},
	DefinitionModule {
		source: SourceId,
	},
	/// For generic parameters
	TypeAlias,
	StaticBlock {},
	/// For repl only
	PassThrough {
		source: SourceId,
	},
}

impl<'a> Environment<'a> {
	/// Handles all assignments, including updates and destructuring
	///
	/// Will evaluate the expression with the right timing and conditions, including never if short circuit
	///
	/// TODO finish operator. Unify increment and decrement. The RHS span should be fine with [`Span::NULL ...?`] Maybe RHS type could be None to accommodate
	pub fn assign_to_assignable_handle_errors<
		'b,
		T: crate::ReadFromFS,
		A: crate::ASTImplementation,
	>(
		&mut self,
		lhs: Assignable,
		operator: AssignmentKind,
		// Can be `None` for increment and decrement
		expression: Option<&'b A::Expression<'b>>,
		assignment_span: SpanWithSource,
		checking_data: &mut CheckingData<T, A>,
	) -> TypeId {
		match lhs {
			Assignable::Reference(reference) => {
				/// Returns
				fn get_reference<U: crate::ReadFromFS, A: crate::ASTImplementation>(
					env: &mut Environment,
					reference: Reference,
					checking_data: &mut CheckingData<U, A>,
				) -> TypeId {
					match reference {
						Reference::Variable(name, position) => {
							env.get_variable_handle_error(&name, position, checking_data).unwrap().1
						}
						Reference::Property { on, with, publicity, span } => {
							let get_property_handle_errors = env.get_property_handle_errors(
								on,
								publicity,
								with,
								checking_data,
								span,
							);
							match get_property_handle_errors {
								Ok(i) => i.get_value(),
								Err(()) => TypeId::ERROR_TYPE,
							}
						}
					}
				}

				fn set_reference<U: crate::ReadFromFS, A: crate::ASTImplementation>(
					env: &mut Environment,
					reference: Reference,
					new: TypeId,
					checking_data: &mut CheckingData<U, A>,
				) -> Result<TypeId, SetPropertyError> {
					match reference {
						Reference::Variable(name, position) => Ok(env
							.assign_to_variable_handle_errors(
								name.as_str(),
								position,
								new,
								checking_data,
							)),
						Reference::Property { on, with, publicity, span } => Ok(env
							.set_property(
								on,
								publicity,
								&with,
								new,
								&checking_data.types,
								Some(span),
							)?
							.unwrap_or(new)),
					}
				}

				fn set_property_error_to_type_check_error(
					ctx: &GeneralContext,
					error: SetPropertyError,
					assignment_span: SpanWithSource,
					types: &TypeStore,
					new: TypeId,
				) -> TypeCheckError<'static> {
					match error {
						SetPropertyError::NotWriteable => {
							TypeCheckError::PropertyNotWriteable(assignment_span)
						}
						SetPropertyError::DoesNotMeetConstraint {
							property_constraint,
							reason: _,
						} => TypeCheckError::AssignmentError(AssignmentError::PropertyConstraint {
							property_constraint,
							value_type: TypeStringRepresentation::from_type_id(
								new, ctx, types, false,
							),
							assignment_position: assignment_span,
						}),
					}
				}

				match operator {
					AssignmentKind::Assign => {
						let new = A::synthesise_expression(
							expression.unwrap(),
							TypeId::ANY_TYPE,
							self,
							checking_data,
						);
						let result = set_reference(self, reference, new, checking_data);
						match result {
							Ok(ty) => ty,
							Err(error) => {
								let error = set_property_error_to_type_check_error(
									&self.as_general_context(),
									error,
									assignment_span,
									&checking_data.types,
									new,
								);
								checking_data.diagnostics_container.add_error(error);
								TypeId::ERROR_TYPE
							}
						}
					}
					AssignmentKind::PureUpdate(operator) => {
						// Order matters here
						let reference_position = reference.get_position();
						let existing = get_reference(self, reference.clone(), checking_data);

						let expression = expression.unwrap();
						let expression_pos =
							A::expression_position(expression).with_source(self.get_source());
						let rhs = A::synthesise_expression(
							expression,
							TypeId::ANY_TYPE,
							self,
							checking_data,
						);

						let new = evaluate_pure_binary_operation_handle_errors(
							(existing, reference_position),
							operator.into(),
							(rhs, expression_pos),
							checking_data,
							self,
						);
						let result = set_reference(self, reference, new, checking_data);
						match result {
							Ok(ty) => ty,
							Err(error) => {
								let error = set_property_error_to_type_check_error(
									&self.as_general_context(),
									error,
									assignment_span,
									&checking_data.types,
									new,
								);
								checking_data.diagnostics_container.add_error(error);
								TypeId::ERROR_TYPE
							}
						}
					}
					AssignmentKind::IncrementOrDecrement(direction, return_kind) => {
						// let value =
						// 	self.get_variable_or_error(&name, &assignment_span, checking_data);
						let span = reference.get_position();
						let existing = get_reference(self, reference.clone(), checking_data);

						// TODO existing needs to be cast to number!!

						let new = evaluate_pure_binary_operation_handle_errors(
							(existing, span),
							match direction {
								crate::behavior::assignments::IncrementOrDecrement::Increment => {
									MathematicalAndBitwise::Add
								}
								crate::behavior::assignments::IncrementOrDecrement::Decrement => {
									MathematicalAndBitwise::Subtract
								}
							}
							.into(),
							(TypeId::ONE, SpanWithSource::NULL_SPAN),
							checking_data,
							self,
						);

						let result = set_reference(self, reference, new, checking_data);

						match result {
							Ok(new) => match return_kind {
								crate::behavior::assignments::AssignmentReturnStatus::Previous => {
									existing
								}
								crate::behavior::assignments::AssignmentReturnStatus::New => new,
							},
							Err(error) => {
								let error = set_property_error_to_type_check_error(
									&self.as_general_context(),
									error,
									assignment_span,
									&checking_data.types,
									new,
								);
								checking_data.diagnostics_container.add_error(error);
								TypeId::ERROR_TYPE
							}
						}
					}
					AssignmentKind::ConditionalUpdate(operator) => {
						let _span = reference.get_position();
						let existing = get_reference(self, reference.clone(), checking_data);
						let expression = expression.unwrap();
						let new = evaluate_logical_operation_with_expression(
							existing,
							operator,
							expression,
							checking_data,
							self,
						)
						.unwrap();

						let result = set_reference(self, reference, new, checking_data);

						match result {
							Ok(new) => new,
							Err(error) => {
								let error = set_property_error_to_type_check_error(
									&self.as_general_context(),
									error,
									assignment_span,
									&checking_data.types,
									new,
								);
								checking_data.diagnostics_container.add_error(error);
								TypeId::ERROR_TYPE
							}
						}
					}
				}
			}
			Assignable::ObjectDestructuring(_) => todo!(),
			Assignable::ArrayDestructuring(_) => todo!(),
		}
	}

	pub fn new_function<U, F, A>(
		&mut self,
		checking_data: &mut CheckingData<U, A>,
		function: &F,
		behavior: functions::FunctionRegisterBehavior<A>,
	) -> crate::types::FunctionType
	where
		U: crate::ReadFromFS,
		A: crate::ASTImplementation,
		F: functions::SynthesisableFunction<A>,
	{
		functions::register_function(self, behavior, function, checking_data)
	}

	pub fn assign_to_variable_handle_errors<T: crate::ReadFromFS, A: crate::ASTImplementation>(
		&mut self,
		variable_name: &str,
		assignment_position: SpanWithSource,
		new_type: TypeId,
		checking_data: &mut CheckingData<T, A>,
	) -> TypeId {
		let result = self.assign_to_variable(
			variable_name,
			assignment_position,
			new_type,
			&checking_data.types,
		);
		match result {
			Ok(ok) => ok,
			Err(error) => {
				checking_data
					.diagnostics_container
					.add_error(TypeCheckError::AssignmentError(error));
				TypeId::ERROR_TYPE
			}
		}
	}

	/// This is top level variables, not properties.
	pub fn assign_to_variable(
		&mut self,
		variable_name: &str,
		assignment_position: SpanWithSource,
		new_type: TypeId,
		store: &TypeStore,
	) -> Result<TypeId, AssignmentError> {
		// Get without the effects
		let variable_in_map = self.get_variable_unbound(variable_name);

		if let Some((_, _, variable)) = variable_in_map {
			match variable {
				VariableOrImport::Variable { mutability, declared_at, context: _ } => {
					match mutability {
						VariableMutability::Constant => {
							Err(AssignmentError::Constant(*declared_at))
						}
						VariableMutability::Mutable { reassignment_constraint } => {
							let variable = variable.clone();

							if let Some(reassignment_constraint) = *reassignment_constraint {
								// TODO tuple with position:
								let mut basic_subtyping = BasicEquality {
									add_property_restrictions: false,
									position: *declared_at,
								};
								let result = type_is_subtype(
									reassignment_constraint,
									new_type,
									&mut basic_subtyping,
									self,
									store,
								);

								if let SubTypeResult::IsNotSubType(_mismatches) = result {
									return Err(AssignmentError::DoesNotMeetConstraint {
										variable_type: TypeStringRepresentation::from_type_id(
											reassignment_constraint,
											&self.as_general_context(),
											store,
											false,
										),
										value_type: TypeStringRepresentation::from_type_id(
											new_type,
											&self.as_general_context(),
											store,
											false,
										),
										// TODO split
										variable_site: assignment_position,
										value_site: assignment_position,
									});
								}
							}

							let variable_id = variable.get_id();

							self.facts.events.push(Event::SetsVariable(
								variable_id,
								new_type,
								assignment_position,
							));
							self.facts.variable_current_value.insert(variable_id, new_type);

							Ok(new_type)
						}
					}
				}
				VariableOrImport::MutableImport { .. }
				| VariableOrImport::ConstantImport { .. } => {
					Err(AssignmentError::Constant(assignment_position))
				}
			}
		} else {
			crate::utils::notify!("Could say it is on the window here");
			Err(AssignmentError::VariableNotFound {
				variable: variable_name.to_owned(),
				assignment_position,
			})
		}
	}

	pub(crate) fn get_root(&self) -> &RootContext {
		match self.context_type.parent {
			GeneralContext::Syntax(syntax) => syntax.get_root(),
			GeneralContext::Root(root) => root,
		}
	}

	#[must_use]
	pub fn get_environment_type(&self) -> &Scope {
		&self.context_type.scope
	}

	pub fn get_environment_type_mut(&mut self) -> &mut Scope {
		&mut self.context_type.scope
	}

	/// TODO decidable & private?
	#[must_use]
	pub fn property_in(&self, on: TypeId, property: &PropertyKey) -> bool {
		self.facts_chain().any(|facts| match facts.current_properties.get(&on) {
			Some(v) => {
				v.iter().any(
					|(_, p, v)| if let PropertyValue::Deleted = v { false } else { p == property },
				)
			}
			None => false,
		})
	}

	/// TODO decidable & private?
	pub fn delete_property(&mut self, on: TypeId, property: &PropertyKey) -> bool {
		let existing = self.property_in(on, property);

		let under = property.into_owned();

		// on_default() okay because might be in a nested context.
		// entry empty does not mean no properties, just no properties set on this level
		self.facts.current_properties.entry(on).or_default().push((
			Publicity::Public,
			under.clone(),
			PropertyValue::Deleted,
		));

		// TODO Event::Delete. Dependent result based on in
		self.facts.events.push(Event::Setter {
			on,
			under,
			new: PropertyValue::Deleted,
			initialization: false,
			publicity: Publicity::Public,
			position: None,
		});

		existing
	}

	pub(crate) fn get_parent(&self) -> GeneralContext {
		match self.context_type.parent {
			GeneralContext::Syntax(syn) => GeneralContext::Syntax(syn),
			GeneralContext::Root(rt) => GeneralContext::Root(rt),
		}
	}

	/// Also evaluates getter and binds `this`
	pub fn get_property(
		&mut self,
		on: TypeId,
		publicity: Publicity,
		property: PropertyKey,
		types: &mut TypeStore,
		with: Option<TypeId>,
		position: SpanWithSource,
	) -> Option<(PropertyKind, TypeId)> {
		crate::types::properties::get_property(
			on,
			publicity,
			property,
			with,
			self,
			&mut CheckThings,
			types,
			position,
		)
	}

	pub fn get_property_handle_errors<U: crate::ReadFromFS, A: crate::ASTImplementation>(
		&mut self,
		on: TypeId,
		publicity: Publicity,
		key: PropertyKey,
		checking_data: &mut CheckingData<U, A>,
		site: SpanWithSource,
	) -> Result<Instance, ()> {
		let get_property =
			self.get_property(on, publicity, key.clone(), &mut checking_data.types, None, site);
		if let Some((kind, result)) = get_property {
			Ok(match kind {
				PropertyKind::Getter => Instance::GValue(result),
				// TODO instance.property...?
				PropertyKind::Generic | PropertyKind::Direct => Instance::RValue(result),
			})
		} else {
			let types = &checking_data.types;
			let ctx = &self.as_general_context();
			checking_data.diagnostics_container.add_error(TypeCheckError::PropertyDoesNotExist {
				// TODO printing temp
				property: match key {
					PropertyKey::String(s) => {
						crate::diagnostics::PropertyRepresentation::StringKey(s.to_string())
					}
					PropertyKey::Type(t) => crate::diagnostics::PropertyRepresentation::Type(
						crate::types::printing::print_type(
							t,
							&checking_data.types,
							&self.as_general_context(),
							false,
						),
					),
				},
				on: crate::diagnostics::TypeStringRepresentation::from_type_id(
					on, ctx, types, false,
				),
				site,
			});
			Err(())
		}
	}

	pub fn get_variable_handle_error<U: crate::ReadFromFS, A: crate::ASTImplementation>(
		&mut self,
		name: &str,
		position: SpanWithSource,
		checking_data: &mut CheckingData<U, A>,
	) -> Result<VariableWithValue, TypeId> {
		let (in_root, crossed_boundary, og_var) = {
			let this = self.get_variable_unbound(name);
			if let Some((in_root, crossed_boundary, og_var)) = this {
				(in_root, crossed_boundary, og_var.clone())
			} else {
				checking_data.diagnostics_container.add_error(
					TypeCheckError::CouldNotFindVariable {
						variable: name,
						// TODO
						possibles: Default::default(),
						position,
					},
				);
				return Err(TypeId::ERROR_TYPE);
			}
		};

		let reference = RootReference::Variable(og_var.get_id());

		if let VariableOrImport::Variable { context: Some(ref context), .. } = og_var {
			if let Some(ref current_context) = self.parents_iter().find_map(|a| {
				if let GeneralContext::Syntax(syn) = a {
					syn.context_type.location.clone()
				} else {
					None
				}
			}) {
				if current_context != context {
					checking_data.diagnostics_container.add_error(
						TypeCheckError::VariableNotDefinedInContext {
							variable: name,
							expected_context: context,
							current_context: current_context.clone(),
							position,
						},
					);
					return Err(TypeId::ERROR_TYPE);
				}
			}
		}

		// let treat_as_in_same_scope = (og_var.is_constant && self.is_immutable(current_value));

		// TODO in_root temp fix
		if let (Some(_boundary), false) = (crossed_boundary, in_root) {
			let based_on = match og_var.get_mutability() {
				VariableMutability::Constant => {
					let constraint = checking_data
						.type_mappings
						.variables_to_constraints
						.0
						.get(&og_var.get_origin_variable_id());

					// TODO temp
					{
						let current_value = get_value_of_variable(
							self.facts_chain(),
							og_var.get_id(),
							None::<&crate::types::poly_types::FunctionTypeArguments>,
						);

						if let Some(current_value) = current_value {
							let ty = checking_data.types.get_type_by_id(current_value);

							// TODO temp
							if matches!(ty, Type::Function(..)) {
								return Ok(VariableWithValue(og_var.clone(), current_value));
							} else if let Type::RootPolyType(PolyNature::Open(_)) = ty {
								// crate::utils::notify!(
								// 	"Open poly type treated as immutable free variable"
								// );
								return Ok(VariableWithValue(og_var.clone(), current_value));
							} else if let Type::Constant(_) = ty {
								return Ok(VariableWithValue(og_var.clone(), current_value));
							}

							crate::utils::notify!("Free variable!");
						}
					}

					// TODO is primitive, then can just use type
					if let Some(constraint) = constraint {
						*constraint
					} else {
						crate::utils::notify!("TODO record that parent variable is `any` here");
						TypeId::ANY_TYPE
					}
				}
				VariableMutability::Mutable { reassignment_constraint } => {
					// TODO is there a nicer way to do this
					// Look for reassignments
					for p in self.parents_iter() {
						if let Some(value) =
							get_on_ctx!(p.facts.variable_current_value.get(&og_var.get_id()))
						{
							return Ok(VariableWithValue(og_var.clone(), *value));
						}
						if get_on_ctx!(p.context_type.is_dynamic_boundary()) {
							break;
						}
					}

					if let Some(constraint) = reassignment_constraint {
						constraint
					} else {
						crate::utils::notify!("TODO record that parent variable is `any` here");
						TypeId::ANY_TYPE
					}
				}
			};

			// TODO temp position
			let mut value = None;

			for event in &self.facts.events {
				// TODO explain why don't need to detect sets
				if let Event::ReadsReference {
					reference: other_reference,
					reflects_dependency: Some(dep),
					position: _,
				} = event
				{
					if reference == *other_reference {
						value = Some(dep);
						break;
					}
				}
			}

			let type_id = if let Some(value) = value {
				*value
			} else {
				// TODO dynamic ?
				let ty = Type::RootPolyType(crate::types::PolyNature::FreeVariable {
					reference: reference.clone(),
					based_on,
				});
				let ty = checking_data.types.register_type(ty);

				// TODO would it be useful to record the type somewhere?
				self.context_type.free_variables.insert(reference);

				// if inferred {
				// 	self.context_type.get_inferrable_constraints_mut().unwrap().insert(type_id);
				// }

				self.facts.events.push(Event::ReadsReference {
					reference: RootReference::Variable(og_var.get_id()),
					reflects_dependency: Some(ty),
					position,
				});

				ty
			};

			Ok(VariableWithValue(og_var.clone(), type_id))
		} else {
			// TODO recursively in
			if let VariableOrImport::MutableImport { of, constant: false, import_specified_at: _ } =
				og_var.clone()
			{
				let current_value = get_value_of_variable(
					self.facts_chain(),
					of,
					None::<&crate::types::poly_types::FunctionTypeArguments>,
				)
				.expect("import not assigned yet");
				return Ok(VariableWithValue(og_var.clone(), current_value));
			}

			let current_value = get_value_of_variable(
				self.facts_chain(),
				og_var.get_id(),
				None::<&crate::types::poly_types::FunctionTypeArguments>,
			);
			if let Some(current_value) = current_value {
				Ok(VariableWithValue(og_var.clone(), current_value))
			} else {
				checking_data.diagnostics_container.add_error(TypeCheckError::TDZ(TDZ {
					variable_name: self.get_variable_name(og_var.get_id()).to_owned(),
					position,
				}));
				Ok(VariableWithValue(og_var.clone(), TypeId::ERROR_TYPE))
			}
		}
	}

	pub(crate) fn new_conditional_context<T, A, R>(
		&mut self,
		condition: TypeId,
		then_evaluate: impl FnOnce(&mut Environment, &mut CheckingData<T, A>) -> R,
		else_evaluate: Option<impl FnOnce(&mut Environment, &mut CheckingData<T, A>) -> R>,
		checking_data: &mut CheckingData<T, A>,
	) -> R
	where
		A: crate::ASTImplementation,
		R: TypeCombinable,
		T: crate::ReadFromFS,
	{
		if let Decidable::Known(result) = is_type_truthy_falsy(condition, &checking_data.types) {
			// TODO emit warning
			return if result {
				then_evaluate(self, checking_data)
			} else if let Some(else_evaluate) = else_evaluate {
				else_evaluate(self, checking_data)
			} else {
				R::default()
			};
		}

		let (truthy_result, truthy_events) = {
			let mut truthy_environment = self.new_lexical_environment(Scope::Conditional {
				antecedent: condition,
				is_switch: None,
			});

			let result = then_evaluate(&mut truthy_environment, checking_data);

			(result, truthy_environment.facts.events)
		};

		if let Some(else_evaluate) = else_evaluate {
			let mut falsy_environment = self.new_lexical_environment(Scope::Conditional {
				antecedent: checking_data.types.new_logical_negation_type(condition),
				is_switch: None,
			});

			let falsy_result = else_evaluate(&mut falsy_environment, checking_data);

			let combined_result =
				R::combine(condition, truthy_result, falsy_result, &mut checking_data.types);

			let falsy_events = falsy_environment.facts.events;
			// TODO It might be possible to get position from one of the SynthesisableConditional but its `get_position` is not implemented yet
			self.facts.events.push(Event::Conditionally {
				condition,
				events_if_truthy: truthy_events.into_boxed_slice(),
				else_events: falsy_events.into_boxed_slice(),
				position: None,
			});

			// TODO all things that are
			// - variable and property values (these aren't read from events)
			// - immutable, mutable, prototypes etc

			combined_result
		} else {
			self.facts.events.push(Event::Conditionally {
				condition,
				events_if_truthy: truthy_events.into_boxed_slice(),
				else_events: Default::default(),
				position: None,
			});

			// TODO above

			truthy_result
		}
	}

	pub fn throw_value(&mut self, value: TypeId, position: SpanWithSource) {
		self.facts.events.push(Event::Throw(value, position));
	}

	pub fn return_value(&mut self, returned: TypeId, returned_position: SpanWithSource) {
		self.facts.events.push(Event::Return { returned, returned_position });
	}

	pub fn add_continue(
		&mut self,
		label: Option<&str>,
		position: Span,
	) -> Result<(), NotInLoopOrCouldNotFindLabel> {
		if let Some(carry) = self.find_label_or_conditional_count(label, true) {
			self.facts.events.push(Event::Continue {
				position: Some(position.with_source(self.get_source())),
				carry,
			});
			Ok(())
		} else {
			Err(NotInLoopOrCouldNotFindLabel {
				label: label.map(ToOwned::to_owned),
				position: position.with_source(self.get_source()),
			})
		}
	}

	pub fn add_break(
		&mut self,
		label: Option<&str>,
		position: Span,
	) -> Result<(), NotInLoopOrCouldNotFindLabel> {
		if let Some(carry) = self.find_label_or_conditional_count(label, false) {
			self.facts.events.push(Event::Break {
				position: Some(position.with_source(self.get_source())),
				carry,
			});
			Ok(())
		} else {
			Err(NotInLoopOrCouldNotFindLabel {
				label: label.map(ToOwned::to_owned),
				position: position.with_source(self.get_source()),
			})
		}
	}

	/// Updates **a existing property**
	///
	/// Returns the result of the setter... TODO could return new else
	pub fn set_property(
		&mut self,
		on: TypeId,
		publicity: Publicity,
		under: &PropertyKey,
		new: TypeId,
		types: &TypeStore,
		setter_position: Option<SpanWithSource>,
	) -> Result<Option<TypeId>, SetPropertyError> {
		crate::types::properties::set_property(
			on,
			publicity,
			under,
			&PropertyValue::Value(new),
			self,
			&mut CheckThings,
			types,
			setter_position,
		)
	}

	/// `continue` has different behavior to `break` right?
	fn find_label_or_conditional_count(
		&self,
		looking_for_label: Option<&str>,
		is_continue: bool,
	) -> Option<u8> {
		let mut falling_through_structures = 0;
		for ctx in self.parents_iter() {
			if let GeneralContext::Syntax(ctx) = ctx {
				let scope = &ctx.context_type.scope;

				match scope {
					Scope::Function(_)
					| Scope::InterfaceEnvironment { .. }
					| Scope::FunctionAnnotation {}
					| Scope::Module { .. }
					| Scope::DefinitionModule { .. }
					| Scope::TypeAlias
					| Scope::StaticBlock {} => {
						break;
					}
					Scope::Looping { ref label } => {
						if looking_for_label.is_none() {
							return Some(falling_through_structures);
						} else if let Some(label) = label {
							if label == looking_for_label.unwrap() {
								return Some(falling_through_structures);
							}
							falling_through_structures += 1;
						}
					}
					Scope::Conditional { is_switch: Some(_label @ Some(_)), .. }
						if !is_continue && looking_for_label.is_some() =>
					{
						todo!("switch break")
					}
					Scope::PassThrough { .. }
					| Scope::Conditional { .. }
					| Scope::TryBlock {}
					| Scope::Block {} => {}
				}
			}
		}
		None
	}

	pub(crate) fn import_items<
		'b,
		P: Iterator<Item = NamePair<'b>>,
		T: crate::ReadFromFS,
		A: crate::ASTImplementation,
	>(
		&mut self,
		partial_import_path: &str,
		import_position: Span,
		default_import: Option<(&str, Span)>,
		kind: ImportKind<'b, P>,
		checking_data: &mut CheckingData<T, A>,
		also_export: bool,
	) {
		let current_source = self.get_source();
		if !matches!(self.context_type.scope, crate::Scope::Module { .. }) {
			checking_data.diagnostics_container.add_error(TypeCheckError::NotTopLevelImport(
				import_position.with_source(current_source),
			));
			return;
		}

		let exports = checking_data.import_file(current_source, partial_import_path, self);

		if let Err(ref err) = exports {
			checking_data.diagnostics_container.add_error(TypeCheckError::CannotOpenFile {
				file: err.clone(),
				position: Some(import_position.with_source(self.get_source())),
			});
		}

		if let Some((default_name, position)) = default_import {
			if let Ok(Ok(ref exports)) = exports {
				if let Some(item) = &exports.default {
					let id = crate::VariableId(current_source, position.start);
					let v = VariableOrImport::ConstantImport {
						to: None,
						import_specified_at: position.with_source(current_source),
					};
					self.facts.variable_current_value.insert(id, *item);
					let existing = self.variables.insert(default_name.to_owned(), v);
					if let Some(_existing) = existing {
						todo!("diagnostic")
					}
				} else {
					todo!("emit 'no default export' diagnostic")
				}
			} else {
				let behavior = crate::context::VariableRegisterBehavior::ConstantImport {
					value: TypeId::ERROR_TYPE,
				};

				self.register_variable_handle_error(
					default_name,
					position.with_source(current_source),
					behavior,
					checking_data,
				);
			}
		}

		match kind {
			ImportKind::Parts(parts) => {
				for part in parts {
					if let Ok(Ok(ref exports)) = exports {
						if let Some(export) = exports.get_export(part.value) {
							match export {
								crate::behavior::modules::TypeOrVariable::ExportedVariable((
									variable,
									mutability,
								)) => {
									let constant = match mutability {
										VariableMutability::Constant => {
											let k = crate::VariableId(
												current_source,
												part.position.start,
											);
											let v = self
												.get_value_of_constant_import_variable(variable);
											self.facts.variable_current_value.insert(k, v);
											true
										}
										VariableMutability::Mutable {
											reassignment_constraint: _,
										} => false,
									};

									let v = VariableOrImport::MutableImport {
										of: variable,
										constant,
										import_specified_at: part
											.position
											.with_source(self.get_source()),
									};
									let existing = self.variables.insert(part.r#as.to_owned(), v);
									if let Some(_existing) = existing {
										todo!("diagnostic")
									}
									if also_export {
										if let Scope::Module { ref mut exported, .. } =
											self.context_type.scope
										{
											exported.named.push((
												part.r#as.to_owned(),
												(variable, mutability),
											));
										}
									}
								}
								crate::behavior::modules::TypeOrVariable::Type(ty) => {
									let existing =
										self.named_types.insert(part.r#as.to_owned(), ty);
									assert!(existing.is_none(), "TODO exception");
								}
							}
						} else {
							let position = part.position.with_source(current_source);
							checking_data.diagnostics_container.add_error(
								TypeCheckError::FieldNotExported {
									file: partial_import_path,
									position,
									importing: part.value,
								},
							);

							let behavior =
								crate::context::VariableRegisterBehavior::ConstantImport {
									value: TypeId::ERROR_TYPE,
								};

							self.register_variable_handle_error(
								part.r#as,
								position,
								behavior,
								checking_data,
							);
						}
					} else {
						let behavior = crate::context::VariableRegisterBehavior::ConstantImport {
							value: TypeId::ERROR_TYPE,
						};

						self.register_variable_handle_error(
							part.r#as,
							part.position.with_source(current_source),
							behavior,
							checking_data,
						);
					}
				}
			}
			ImportKind::All { under, position } => {
				if let Ok(Ok(ref exports)) = exports {
					let value = checking_data.types.register_type(Type::SpecialObject(
						crate::behavior::objects::SpecialObjects::Import(exports.clone()),
					));

					self.register_variable_handle_error(
						under,
						position.with_source(current_source),
						crate::context::VariableRegisterBehavior::ConstantImport { value },
						checking_data,
					);
				} else {
					let behavior = crate::context::VariableRegisterBehavior::Declare {
						base: TypeId::ERROR_TYPE,
						context: None,
					};
					self.register_variable_handle_error(
						under,
						position.with_source(current_source),
						behavior,
						checking_data,
					);
				}
			}
			ImportKind::Everything => {
				if let Ok(Ok(ref exports)) = exports {
					for (name, (variable, mutability)) in &exports.named {
						// TODO are variables put into scope?
						if let Scope::Module { ref mut exported, .. } = self.context_type.scope {
							exported.named.push((name.clone(), (*variable, *mutability)));
						}
					}
				} else {
					// TODO ??
				}
			}
		}
	}
}