summaryrefslogtreecommitdiffstats
path: root/crates/rebel-lang/src/scope.rs
blob: 08149a94be36dd9b5eb93663b3aed524ad2d4e5e (plain)
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
use std::collections::HashMap;

use rebel_parse::ast::{self, pat};

use crate::{
	func::Func,
	typing::{Coerce, Type, TypeFamily},
	value::Value,
	Error, Result,
};

#[derive(Debug, Clone)]
pub struct Var {
	pub explicit_type: Type,
	inferred_type: Type,
	value: Value,
	initialized: bool,
}

impl Var {
	pub fn new(explicit_type: Type, value: Value) -> Result<Self> {
		Ok(Var {
			explicit_type: explicit_type.clone(),
			inferred_type: explicit_type.unify(value.typ()?, Coerce::Assign)?,
			value,
			initialized: true,
		})
	}

	pub fn new_uninitialized(explicit_type: Type) -> Self {
		Var {
			inferred_type: explicit_type.clone(),
			explicit_type,
			value: Value::Uninitialized,
			initialized: false,
		}
	}

	pub fn inferred_type(&self) -> Result<&Type> {
		if !self.initialized {
			return Err(Error::typ("uninitialized variable"));
		}
		Ok(&self.inferred_type)
	}

	pub fn value(&self) -> Result<&Value> {
		if !self.initialized {
			return Err(Error::typ("uninitialized variable"));
		}
		Ok(&self.value)
	}
}

#[derive(Debug, Clone)]
pub struct Context {
	pub vars: Module<Var>,
	pub types: Module<Type>,
	pub methods: HashMap<TypeFamily, HashMap<&'static str, Func>>,
}

impl Default for Context {
	fn default() -> Self {
		let vars = Module::default();
		let mut types = Module::default();
		let methods = HashMap::default();

		// Type "prelude"
		types.insert("bool", Type::Bool);
		types.insert("int", Type::Int);
		types.insert("str", Type::Str);

		Self {
			vars,
			types,
			methods,
		}
	}
}

impl Context {
	fn pat_ident<'a>(pat: &pat::Pat<'a>) -> ast::Ident<'a> {
		match pat {
			pat::Pat::Paren(subpat) => Self::pat_ident(subpat),
			pat::Pat::Ident(ident) => *ident,
		}
	}

	pub fn lookup_var(&self, path: &ast::Path) -> Result<&Var> {
		if path.root != ast::PathRoot::Relative {
			return Err(Error::lookup("invalid path"));
		}

		if path.components == [ast::Ident { name: "_" }] {
			return Err(Error::lookup("_ in evaluated expression"));
		}

		self.vars
			.lookup(&path.components)
			.ok_or(Error::lookup("undefined variable"))
	}

	pub fn lookup_type(&self, path: &ast::Path) -> Result<&Type> {
		if path.root != ast::PathRoot::Relative {
			return Err(Error::lookup("invalid path"));
		}

		if path.components == [ast::Ident { name: "_" }] {
			return Ok(&Type::Free);
		}

		self.types
			.lookup(&path.components)
			.ok_or(Error::lookup("undefined type"))
	}

	fn lookup_path_var_mut(&mut self, path: &ast::Path) -> Result<&mut Var> {
		if path.root != ast::PathRoot::Relative {
			return Err(Error::lookup("invalid path"));
		}

		self.vars
			.lookup_mut(&path.components)
			.ok_or(Error::lookup("undefined variable"))
	}

	fn lookup_destr_pat_var_type_mut(
		&mut self,
		pat: &pat::DestrPat,
	) -> Result<(&mut Type, &mut bool)> {
		Ok(match pat {
			pat::DestrPat::Index { base, index } => {
				match Type::ast_expr_type(self, index)? {
					Type::Int => {}
					_ => {
						return Err(Error::typ("invalid array index type"));
					}
				}
				let (typ, initialized) = self.lookup_destr_pat_var_type_mut(base)?;
				if !*initialized {
					return Err(Error::typ(
						"tried to assign field of uninitialized variable",
					));
				}
				(
					match typ {
						Type::Array(inner) => inner.as_mut(),
						_ => return Err(Error::typ("invalid array index base")),
					},
					initialized,
				)
			}
			pat::DestrPat::Field { base, field } => {
				let (typ, initialized) = self.lookup_destr_pat_var_type_mut(base)?;
				if !*initialized {
					return Err(Error::typ(
						"tried to assign field of uninitialized variable",
					));
				}
				(
					match typ {
						Type::Tuple(elems) => {
							let index: usize =
								field.name.parse().or(Err(Error::typ("no such field")))?;
							elems.get_mut(index).ok_or(Error::typ("no such field"))?
						}
						Type::Struct(entries) => entries
							.get_mut(field.name)
							.ok_or(Error::typ("no such field"))?,
						_ => return Err(Error::typ("invalid field access base type")),
					},
					initialized,
				)
			}
			pat::DestrPat::Paren(subpat) => self.lookup_destr_pat_var_type_mut(subpat)?,
			pat::DestrPat::Path(path) => {
				let var = self.lookup_path_var_mut(path)?;
				(&mut var.inferred_type, &mut var.initialized)
			}
		})
	}

	fn lookup_destr_pat_var_type_value_mut(
		&mut self,
		pat: &pat::DestrPat,
	) -> Result<(&mut Type, &mut Value, &mut bool)> {
		Ok(match pat {
			pat::DestrPat::Index { base, index } => {
				let index = usize::try_from(match Value::eval(self, index)? {
					Value::Int(index) => index,
					_ => {
						return Err(Error::typ("invalid array index type"));
					}
				})
				.or(Err(Error::eval("array index out of bounds")))?;
				let (typ, value, initialized) = self.lookup_destr_pat_var_type_value_mut(base)?;
				if !*initialized {
					return Err(Error::typ(
						"tried to assign field of uninitialized variable",
					));
				}
				let (inner_type, inner_value) = match (typ, value) {
					(Type::Array(inner_type), Value::Array(inner_value)) => (
						inner_type.as_mut(),
						inner_value
							.get_mut(index)
							.ok_or(Error::eval("array index out of bounds"))?,
					),
					_ => return Err(Error::typ("invalid array index base")),
				};
				(inner_type, inner_value, initialized)
			}
			pat::DestrPat::Field { base, field } => {
				let (typ, value, initialized) = self.lookup_destr_pat_var_type_value_mut(base)?;
				if !*initialized {
					return Err(Error::typ(
						"tried to assign field of uninitialized variable",
					));
				}
				let (inner_type, inner_value) = match (typ, value) {
					(Type::Tuple(type_elems), Value::Tuple(value_elems)) => {
						let index: usize =
							field.name.parse().or(Err(Error::typ("no such field")))?;
						(
							type_elems
								.get_mut(index)
								.ok_or(Error::typ("no such field"))?,
							value_elems
								.get_mut(index)
								.ok_or(Error::typ("no such field"))?,
						)
					}
					(Type::Struct(type_entries), Value::Struct(value_entries)) => (
						type_entries
							.get_mut(field.name)
							.ok_or(Error::typ("no such field"))?,
						value_entries
							.get_mut(field.name)
							.ok_or(Error::typ("no such field"))?,
					),
					_ => return Err(Error::typ("invalid field access base type")),
				};
				(inner_type, inner_value, initialized)
			}
			pat::DestrPat::Paren(subpat) => self.lookup_destr_pat_var_type_value_mut(subpat)?,
			pat::DestrPat::Path(path) => {
				let var = self.lookup_path_var_mut(path)?;
				(&mut var.inferred_type, &mut var.value, &mut var.initialized)
			}
		})
	}

	fn is_wildcard_destr_pat(pat: &pat::DestrPat) -> bool {
		match pat {
			pat::DestrPat::Index { .. } => false,
			pat::DestrPat::Field { .. } => false,
			pat::DestrPat::Paren(pat) => Self::is_wildcard_destr_pat(pat),
			pat::DestrPat::Path(path) => {
				path.root == ast::PathRoot::Relative
					&& path.components == [ast::Ident { name: "_" }]
			}
		}
	}

	fn assign_destr_pat_type(&mut self, dest: &pat::DestrPat, typ: Type) -> Result<Type> {
		if Self::is_wildcard_destr_pat(dest) {
			return Ok(Type::Unit);
		}

		let (dest_type, initialized) = self.lookup_destr_pat_var_type_mut(dest)?;

		let inferred_type = dest_type.clone().unify(typ, Coerce::Common)?;
		*dest_type = inferred_type.clone();
		*initialized = true;

		// TODO: Check explicit type

		Ok(inferred_type)
	}

	fn assign_destr_pat_value(&mut self, dest: &pat::DestrPat, value: Value) -> Result<Value> {
		let typ = value.typ()?;

		if Self::is_wildcard_destr_pat(dest) {
			return Ok(Value::Unit);
		}

		let (dest_type, dest_value, initialized) =
			self.lookup_destr_pat_var_type_value_mut(dest)?;

		*dest_type = dest_type.clone().unify(typ, Coerce::Common)?;
		*dest_value = value.clone();
		*initialized = true;

		// TODO: Check explicit type

		Ok(value)
	}

	pub fn record_type(&mut self, stmt: &ast::BlockStmt) -> Result<Type> {
		Ok(match stmt {
			ast::BlockStmt::Let { dest, expr } => {
				let ast::TypedPat { pat, typ } = dest.as_ref();

				let dest_ident = Self::pat_ident(pat);

				let explicit_type = if let Some(typ) = typ {
					Type::ast_type(self, typ)?
				} else {
					Type::Free
				};

				let expr_type = expr
					.as_ref()
					.map(|expr| {
						let expr_type = Type::ast_expr_type(self, expr)?;
						explicit_type
							.clone()
							.unify(expr_type.clone(), Coerce::Assign)?;
						Ok(expr_type)
					})
					.transpose()?;

				if dest_ident.name == "_" {
					return Ok(Type::Unit);
				}

				self.vars
					.insert(dest_ident.name, Var::new_uninitialized(explicit_type));

				let Some(expr_type) = expr_type else {
					return Ok(Type::Unit);
				};

				self.assign_destr_pat_type(&pat::DestrPat::from(pat), expr_type)?
			}
			ast::BlockStmt::Assign { dest, expr } => {
				let expr_type = Type::ast_expr_type(self, expr)?;
				self.assign_destr_pat_type(dest, expr_type)?
			}
			ast::BlockStmt::Expr { expr } => Type::ast_expr_type(self, expr)?,
			ast::BlockStmt::Empty => Type::Unit,
		})
	}

	pub fn execute(&mut self, stmt: &ast::BlockStmt) -> Result<Value> {
		Ok(match stmt {
			ast::BlockStmt::Let { dest, expr } => {
				let ast::TypedPat { pat, typ } = dest.as_ref();

				let dest_ident = Self::pat_ident(pat);

				let explicit_type = if let Some(typ) = typ {
					Type::ast_type(self, typ)?
				} else {
					Type::Free
				};

				let value = expr
					.as_ref()
					.map(|expr| Value::eval(self, expr))
					.transpose()?;

				if dest_ident.name == "_" {
					return Ok(Value::Unit);
				}

				self.vars
					.insert(dest_ident.name, Var::new_uninitialized(explicit_type));

				let Some(value) = value else {
					return Ok(Value::Unit);
				};

				self.assign_destr_pat_value(&pat::DestrPat::from(pat), value)?
			}
			ast::BlockStmt::Assign { dest, expr } => {
				let value = Value::eval(self, expr)?;
				self.assign_destr_pat_value(dest, value)?
			}
			ast::BlockStmt::Expr { expr } => Value::eval(self, expr)?,
			ast::BlockStmt::Empty => Value::Unit,
		})
	}
}

#[derive(Debug, Clone)]
pub struct Module<T>(pub HashMap<String, ModuleEntry<T>>);

impl<T> Module<T> {
	pub fn insert(&mut self, ident: &str, value: T) {
		self.0.insert(ident.to_owned(), ModuleEntry::Def(value));
	}

	pub fn lookup(&self, path: &[ast::Ident<'_>]) -> Option<&T> {
		let (ident, rest) = path.split_first()?;

		match self.0.get(ident.name)? {
			ModuleEntry::Module(module) => module.lookup(rest),
			ModuleEntry::Def(def) => {
				if rest.is_empty() {
					Some(def)
				} else {
					None
				}
			}
		}
	}

	pub fn lookup_mut(&mut self, path: &[ast::Ident<'_>]) -> Option<&mut T> {
		let (ident, rest) = path.split_first()?;

		match self.0.get_mut(ident.name)? {
			ModuleEntry::Module(module) => module.lookup_mut(rest),
			ModuleEntry::Def(def) => {
				if rest.is_empty() {
					Some(def)
				} else {
					None
				}
			}
		}
	}
}

impl<T> Default for Module<T> {
	fn default() -> Self {
		Self(HashMap::new())
	}
}

#[derive(Debug, Clone)]
pub enum ModuleEntry<T> {
	Module(Module<T>),
	Def(T),
}