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

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

use crate::{
	func::Func,
	typing::{self, Coerce, Type, TypeError, TypeFamily},
	value::{self, EvalError, Value},
};

#[derive(Debug, Clone)]
pub struct Var {
	pub explicit_type: Type,
	pub inferred_type: Type,
	pub value: Option<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 {
	pub fn local_ident<'a>(path: &'a ast::Path) -> Option<ast::Ident<'a>> {
		if path.root != ast::PathRoot::Relative {
			return None;
		}

		let [ident] = path.components[..] else {
			return None;
		};
		Some(ident)
	}

	pub fn lookup_var(&self, path: &ast::Path) -> Option<&Var> {
		if path.root != ast::PathRoot::Relative {
			return None;
		}

		if path.components == [ast::Ident { name: "_" }] {
			return None;
		}

		self.vars.lookup(&path.components)
	}

	pub fn lookup_type(&self, path: &ast::Path) -> Option<&Type> {
		if path.root != ast::PathRoot::Relative {
			return None;
		}

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

		self.types.lookup(&path.components)
	}

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

				let pat::Pat::Path(dest_path) = pat;
				let dest_ident = Context::local_ident(dest_path).ok_or(TypeError)?;

				let explicit_type = if let Some(typ) = typ {
					Type::ast_type(self, typ)?
				} else {
					Type::Free
				};
				let inferred_type = if let Some(expr) = expr {
					let expr_type = Type::ast_expr_type(self, expr)?;
					explicit_type.clone().unify(expr_type, Coerce::Assign)?
				} else {
					explicit_type.clone()
				};

				// TODO: Lexical scoping
				// TODO: Free fixed array length

				if dest_ident.name != "_" {
					self.vars.insert(
						dest_ident.name,
						Var {
							explicit_type,
							inferred_type,
							value: None,
						},
					);
				}
			}
			ast::BlockStmt::Assign { dest, expr } => {
				let pat::Pat::Path(dest_path) = dest.as_ref();
				let dest_ident = Context::local_ident(dest_path).ok_or(TypeError)?;

				let expr_type = Type::ast_expr_type(self, expr)?;

				// TODO: Lexical scoping
				let Some(ModuleEntry::Def(var)) = self.vars.0.get_mut(dest_ident.name) else {
					return Err(TypeError);
				};
				let inferred_type = var.inferred_type.clone().unify(expr_type, Coerce::Common)?;

				var.explicit_type
					.clone()
					.unify(inferred_type.clone(), Coerce::Assign)?;

				var.inferred_type = inferred_type.clone();

				return Ok(inferred_type);
			}
			ast::BlockStmt::Expr { expr } => {
				return Type::ast_expr_type(self, expr);
			}
			ast::BlockStmt::Empty => {}
		}
		Ok(Type::Unit)
	}

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

				let pat::Pat::Path(dest_path) = pat;
				let dest_ident = Context::local_ident(dest_path).expect("Type error during eval");

				let explicit_type = if let Some(typ) = typ {
					Type::ast_type(self, typ).expect("Type error during eval")
				} else {
					Type::Free
				};
				let (inferred_type, value) = if let Some(expr) = expr {
					let value = Value::eval(self, expr)?;
					let expr_type = value.typ().expect("Type error during eval");
					(
						explicit_type
							.clone()
							.unify(expr_type, Coerce::Assign)
							.expect("Type error during eval"),
						Some(value),
					)
				} else {
					(explicit_type.clone(), None)
				};

				// TODO: Lexical scoping

				if dest_ident.name != "_" {
					self.vars.insert(
						dest_ident.name,
						Var {
							explicit_type,
							inferred_type,
							value,
						},
					);
				}
			}
			ast::BlockStmt::Assign { dest, expr } => {
				let pat::Pat::Path(dest_path) = dest.as_ref();
				let dest_ident = Context::local_ident(dest_path).expect("Type error during eval");

				let value = Value::eval(self, expr)?;
				let expr_type = value.typ().or(Err(EvalError))?;

				let Some(ModuleEntry::Def(var)) = self.vars.0.get_mut(dest_ident.name) else {
					unreachable!("Type error during eval");
				};

				var.inferred_type = var
					.inferred_type
					.clone()
					.unify(expr_type, Coerce::Common)
					.expect("Type error during eval");
				// TODO: Debug check: Test against explicit type
				var.value = Some(value.clone());
				return Ok(value);
			}
			ast::BlockStmt::Expr { expr } => {
				return Value::eval(self, expr);
			}
			ast::BlockStmt::Empty => {}
		}
		Ok(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
				}
			}
		}
	}
}

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

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