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
#![doc = include_str!("../README.md")]
#![allow(
	unreachable_code,
	unused_variables,
	unused_imports,
	unused_mut,
	dead_code,
	irrefutable_let_patterns,
	deprecated
)]

mod behavior;
pub mod context;
pub mod diagnostics;
pub mod events;
pub mod range_map;
mod serialization;
mod settings;
pub mod structures;
pub mod temp;
mod type_mappings;
pub mod types;
mod utils;

pub const INTERNAL_DEFINITION_FILE_PATH: &str = "internal.d.ts";
pub const INTERNAL_DEFINITION_FILE: &str = include_str!("../definitions/internal.d.ts");

// TODO temp pub
#[cfg(feature = "ezno-parser")]
pub mod synthesis;

use diagnostics::{TypeCheckError, TypeCheckWarning};
pub(crate) use serialization::BinarySerializable;

use context::store::ExistingContextStore;

use indexmap::IndexMap;
use source_map::SpanWithSource;
use std::{
	collections::{HashMap, HashSet},
	path::PathBuf,
};
use structures::functions::AutoConstructorId;

use types::{
	subtyping::{check_satisfies, type_is_subtype, BasicEquality, SubTypeResult},
	TypeStore,
};

pub use behavior::{
	assignments::{
		Assignable, AssignmentKind, AssignmentReturnStatus, IncrementOrDecrement, Reference,
		SynthesizableExpression,
	},
	functions::{
		GetterSetterGeneratorOrNone, RegisterAsType, RegisterOnExisting, RegisterOnExistingObject,
		SynthesizableFunction,
	},
	variables::check_variable_initialization,
};
pub use context::{GeneralContext, Root};
pub use diagnostics::{Diagnostic, DiagnosticKind, DiagnosticsContainer};
pub use settings::TypeCheckSettings;
pub use structures::{
	functions::{FunctionPointer, InternalFunctionId},
	jsx::*,
	modules::SynthesizedModule,
	variables::Variable,
};
pub use types::{calling::call_type_handle_errors, poly_types::GenericTypeParameters, subtyping};

pub use type_mappings::*;
pub use types::{properties::Property, Constant, Type, TypeId};

pub use context::{Environment, Scope};
pub(crate) use structures::modules::ModuleFromPathError;

pub trait FSResolver: Fn(&std::path::Path) -> Option<String> {}

impl<T> FSResolver for T where T: Fn(&std::path::Path) -> Option<String> {}

// TODO
pub use source_map::{SourceId, Span};

/// Contains all the modules and mappings for import statements
pub struct ModuleData<'a, T> {
	pub(crate) currently_checking_modules: HashSet<PathBuf>,
	/// TODO this also covers checked modules
	pub(crate) synthesized_modules: IndexMap<PathBuf, SynthesizedModule>,
	// pub(crate) custom_module_resolvers: HashMap<String, Box<dyn CustomModuleResolver>>,
	pub(crate) fs_resolver: &'a T,
	pub(crate) current_working_directory: PathBuf,
}

impl<'a, T: crate::FSResolver> ModuleData<'a, T> {
	pub(crate) fn new_with_custom_module_resolvers(
		// custom_module_resolvers: HashMap<String, Box<dyn CustomModuleResolver>>,
		fs_resolver: &'a T,
		current_working_directory: PathBuf,
	) -> Self {
		Self {
			synthesized_modules: Default::default(),
			currently_checking_modules: Default::default(),
			// custom_module_resolvers,
			fs_resolver,
			current_working_directory,
		}
	}
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, binary_serialize_derive::BinarySerializable)]
pub struct VariableId(pub SourceId, pub u32);

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, binary_serialize_derive::BinarySerializable)]
pub struct FunctionId(pub SourceId, pub u32);

pub enum TruthyFalsy {
	Decidable(bool),
	/// Poly types
	Unknown,
}

/// TODO
pub enum PredicateBound<T> {
	Always(T),
}

/// Contains logic for **checking phase** (none of the later steps)
/// All data is global, non local to current scope
/// TODO some of these should be mutex / ref cell
pub struct CheckingData<'a, T> {
	// pub(crate) type_resolving_visitors: [Box<dyn TypeResolvingExpressionVisitor>],
	// pub(crate) pre_type_visitors: FirstPassVisitors,
	/// Type checking errors
	pub diagnostics_container: DiagnosticsContainer,
	/// TODO temp pub
	pub type_mappings: TypeMappings,
	/// All module information
	pub(crate) modules: ModuleData<'a, T>,
	/// Settings for checking
	pub(crate) settings: TypeCheckSettings,
	// pub(crate) parse_settings: parser::ParseSettings,
	/// For LSP, and more TODO
	pub(crate) existing_contexts: ExistingContextStore,

	// pub(crate) events: EventsStore,
	pub types: TypeStore,

	/// Do not repeat emitting unimplemented parts
	unimplemented_items: HashSet<&'static str>,
}

impl<'a, T: crate::FSResolver> CheckingData<'a, T> {
	// TODO improve on this function
	pub fn new(settings: TypeCheckSettings, resolver: &'a T) -> Self {
		// let custom_file_resolvers = HashMap::default();
		let cwd = Default::default();
		let modules = ModuleData::new_with_custom_module_resolvers(resolver, cwd);

		Self {
			settings,
			type_mappings: Default::default(),
			diagnostics_container: Default::default(),
			modules,
			existing_contexts: Default::default(),
			types: Default::default(),
			unimplemented_items: Default::default(),
		}
	}

	/// TODO method is a bit junky
	/// Returns the exports of the module
	pub(crate) fn load_and_check_module(
		&mut self,
		path: PathBuf,
		base_environment: &mut Root,
	) -> Result<
		(&HashMap<String, Variable>, &mut DiagnosticsContainer, &mut TypeMappings),
		ModuleFromPathError,
	> {
		todo!()
		// if let Some(ref _synthesized_modules) = self.modules.synthesized_modules.get(&path) {
		// 	todo!()
		// }

		// // TODO check module is not already loaded or checked.
		// // TODO paths maybe different to what is in map here here .... :(
		// let (module_result, _) = Module::from_path(
		// 	path.clone(),
		// 	&self.modules.custom_module_resolvers,
		// 	&self.modules.fs_resolver,
		// 	todo!("parse settings"),
		// )?;

		// self.modules.currently_checking_modules.insert(path.clone());
		// let synthesized_module = module_result.synthesize(base_environment, self);
		// self.modules.currently_checking_modules.remove(&path);

		// self.modules
		// 	.synthesized_modules
		// 	.insert(synthesized_module.module.path.clone(), synthesized_module)
		// 	.unwrap();

		// // module.get_exports()
		// Ok((todo!(), &mut self.diagnostics_container, &mut self.type_mappings))
	}

	/// TODO temp, needs better place
	pub fn raise_decidable_result_error(&mut self, span: SpanWithSource, value: bool) {
		self.diagnostics_container.add_error(TypeCheckWarning::DeadBranch {
			expression_span: span,
			expression_value: value,
		})
	}

	/// TODO temp, needs better place
	pub fn raise_unimplemented_error(&mut self, item: &'static str, span: SpanWithSource) {
		if self.unimplemented_items.insert(item) {
			self.diagnostics_container
				.add_warning(TypeCheckWarning::Unimplemented { thing: item, at: span });
		}
	}

	pub fn add_expression_mapping(&mut self, span: SpanWithSource, instance: Instance) {
		self.type_mappings.expressions_to_instances.push(span, instance);
	}

	pub fn check_satisfies(
		&mut self,
		expr_ty: TypeId,
		to_satisfy: TypeId,
		at: SpanWithSource,
		environment: &mut Environment,
	) {
		if !check_satisfies(expr_ty, to_satisfy, &self.types, environment) {
			let expected = diagnostics::TypeStringRepresentation::from_type_id(
				to_satisfy,
				&environment.into_general_context(),
				&self.types,
				false,
			);
			let found = diagnostics::TypeStringRepresentation::from_type_id(
				expr_ty,
				&environment.into_general_context(),
				&self.types,
				false,
			);
			self.diagnostics_container.add_error(TypeCheckError::NotSatisfied {
				at,
				expected,
				found,
			});
		}
	}
}

pub trait SynthesizableConditional {
	/// For conditional expressions (`a ? b : c`) as they return a type.
	/// **Not for return in conditional if blocks**
	type ExpressionResult;

	fn synthesize_condition<T: crate::FSResolver>(
		self,
		environment: &mut Environment,
		checking_data: &mut CheckingData<T>,
	) -> Self::ExpressionResult;

	fn conditional_expression_result(
		condition: TypeId,
		truthy_result: Self::ExpressionResult,
		falsy_result: Self::ExpressionResult,
		types: &mut TypeStore,
	) -> Self::ExpressionResult;

	fn default_result() -> Self::ExpressionResult;
}

impl<'a, T: crate::SynthesizableExpression> crate::SynthesizableConditional for &'a T {
	type ExpressionResult = TypeId;

	fn synthesize_condition<U: crate::FSResolver>(
		self,
		environment: &mut crate::Environment,
		checking_data: &mut crate::CheckingData<U>,
	) -> Self::ExpressionResult {
		self.synthesize_expression(environment, checking_data)
	}

	fn conditional_expression_result(
		condition: TypeId,
		truthy_result: Self::ExpressionResult,
		else_result: Self::ExpressionResult,
		types: &mut TypeStore,
	) -> Self::ExpressionResult {
		types.new_conditional_type(condition, truthy_result, else_result)
	}

	fn default_result() -> Self::ExpressionResult {
		unreachable!("If was reachable it should be TypeID::Undefined")
	}
}