1use crate::{
2 expr::{Arg, ModPath},
3 typ::{FnType, TVar, Type},
4 BindId, Ctx, InitFn, LambdaId, UserEvent,
5};
6use anyhow::{bail, Result};
7use arcstr::ArcStr;
8use compact_str::CompactString;
9use fxhash::{FxHashMap, FxHashSet};
10use immutable_chunkmap::{map::MapS as Map, set::SetS as Set};
11use netidx::path::Path;
12use std::{cell::RefCell, fmt, iter, ops::Bound, sync::Weak};
13use triomphe::Arc;
14
15pub struct LambdaDef<C: Ctx, E: UserEvent> {
16 pub id: LambdaId,
17 pub env: Env<C, E>,
18 pub scope: ModPath,
19 pub argspec: Arc<[Arg]>,
20 pub typ: Arc<FnType>,
21 pub init: InitFn<C, E>,
22}
23
24impl<C: Ctx, E: UserEvent> fmt::Debug for LambdaDef<C, E> {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 write!(f, "LambdaDef({:?})", self.id)
27 }
28}
29
30pub struct Bind {
31 pub id: BindId,
32 pub export: bool,
33 pub typ: Type,
34 pub doc: Option<ArcStr>,
35 pub scope: ModPath,
36 pub name: CompactString,
37}
38
39impl fmt::Debug for Bind {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "Bind {{ id: {:?}, export: {} }}", self.id, self.export,)
42 }
43}
44
45impl Clone for Bind {
46 fn clone(&self) -> Self {
47 Self {
48 id: self.id,
49 scope: self.scope.clone(),
50 name: self.name.clone(),
51 doc: self.doc.clone(),
52 export: self.export,
53 typ: self.typ.clone(),
54 }
55 }
56}
57
58#[derive(Debug, Clone)]
59pub struct TypeDef {
60 pub params: Arc<[(TVar, Option<Type>)]>,
61 pub typ: Type,
62}
63
64#[derive(Debug)]
65pub struct Env<C: Ctx, E: UserEvent> {
66 pub by_id: Map<BindId, Bind>,
67 pub lambdas: Map<LambdaId, Weak<LambdaDef<C, E>>>,
68 pub byref_chain: Map<BindId, BindId>,
69 pub binds: Map<ModPath, Map<CompactString, BindId>>,
70 pub used: Map<ModPath, Arc<Vec<ModPath>>>,
71 pub modules: Set<ModPath>,
72 pub typedefs: Map<ModPath, Map<CompactString, TypeDef>>,
73}
74
75impl<C: Ctx, E: UserEvent> Clone for Env<C, E> {
76 fn clone(&self) -> Self {
77 Self {
78 by_id: self.by_id.clone(),
79 binds: self.binds.clone(),
80 byref_chain: self.byref_chain.clone(),
81 used: self.used.clone(),
82 modules: self.modules.clone(),
83 typedefs: self.typedefs.clone(),
84 lambdas: self.lambdas.clone(),
85 }
86 }
87}
88
89impl<C: Ctx, E: UserEvent> Env<C, E> {
90 pub(super) fn new() -> Self {
91 Self {
92 by_id: Map::new(),
93 binds: Map::new(),
94 byref_chain: Map::new(),
95 used: Map::new(),
96 modules: Set::new(),
97 typedefs: Map::new(),
98 lambdas: Map::new(),
99 }
100 }
101
102 pub(super) fn clear(&mut self) {
103 let Self { by_id, binds, byref_chain, used, modules, typedefs, lambdas } = self;
104 *by_id = Map::new();
105 *binds = Map::new();
106 *byref_chain = Map::new();
107 *used = Map::new();
108 *modules = Set::new();
109 *typedefs = Map::new();
110 *lambdas = Map::new();
111 }
112
113 pub(super) fn restore_lexical_env(&self, other: Self) -> Self {
117 Self {
118 binds: other.binds,
119 used: other.used,
120 modules: other.modules,
121 typedefs: other.typedefs,
122 by_id: self.by_id.clone(),
123 lambdas: self.lambdas.clone(),
124 byref_chain: self.byref_chain.clone(),
125 }
126 }
127
128 pub fn find_visible<R, F: FnMut(&str, &str) -> Option<R>>(
129 &self,
130 scope: &ModPath,
131 name: &ModPath,
132 mut f: F,
133 ) -> Option<R> {
134 let mut buf = CompactString::from("");
135 let name_scope = Path::dirname(&**name);
136 let name = Path::basename(&**name).unwrap_or("");
137 for scope in Path::dirnames(&**scope).rev() {
138 let used = self.used.get(scope);
139 let used = iter::once(scope)
140 .chain(used.iter().flat_map(|s| s.iter().map(|p| &***p)));
141 for scope in used {
142 let scope = name_scope
143 .map(|ns| {
144 buf.clear();
145 buf.push_str(scope);
146 if let Some(Path::SEP) = buf.chars().next_back() {
147 buf.pop();
148 }
149 buf.push_str(ns);
150 buf.as_str()
151 })
152 .unwrap_or(scope);
153 if let Some(res) = f(scope, name) {
154 return Some(res);
155 }
156 }
157 }
158 None
159 }
160
161 pub fn lookup_bind(
162 &self,
163 scope: &ModPath,
164 name: &ModPath,
165 ) -> Option<(&ModPath, &Bind)> {
166 self.find_visible(scope, name, |scope, name| {
167 self.binds.get_full(scope).and_then(|(scope, vars)| {
168 vars.get(name)
169 .and_then(|bid| self.by_id.get(bid).map(|bind| (scope, bind)))
170 })
171 })
172 }
173
174 pub fn lookup_typedef(&self, scope: &ModPath, name: &ModPath) -> Option<&TypeDef> {
175 self.find_visible(scope, name, |scope, name| {
176 self.typedefs.get(scope).and_then(|m| m.get(name))
177 })
178 }
179
180 pub fn lookup_matching(
184 &self,
185 scope: &ModPath,
186 part: &ModPath,
187 ) -> Vec<(CompactString, BindId)> {
188 let mut res = vec![];
189 self.find_visible(scope, part, |scope, part| {
190 if let Some(vars) = self.binds.get(scope) {
191 let r = vars.range::<str, _>((Bound::Included(part), Bound::Unbounded));
192 for (name, bind) in r {
193 if name.starts_with(part) {
194 res.push((name.clone(), *bind));
195 }
196 }
197 }
198 None::<()>
199 });
200 res
201 }
202
203 pub fn lookup_matching_modules(
207 &self,
208 scope: &ModPath,
209 part: &ModPath,
210 ) -> Vec<ModPath> {
211 let mut res = vec![];
212 self.find_visible(scope, part, |scope, part| {
213 let p = ModPath(Path::from(ArcStr::from(scope)).append(part));
214 for m in self.modules.range((Bound::Included(p.clone()), Bound::Unbounded)) {
215 if m.0.starts_with(&*p.0) {
216 if let Some(m) = m.strip_prefix(scope) {
217 if !m.trim().is_empty() {
218 res.push(ModPath(Path::from(ArcStr::from(m))));
219 }
220 }
221 }
222 }
223 None::<()>
224 });
225 res
226 }
227
228 pub fn canonical_modpath(&self, scope: &ModPath, name: &ModPath) -> Option<ModPath> {
229 self.find_visible(scope, name, |scope, name| {
230 let p = ModPath(Path::from(ArcStr::from(scope)).append(name));
231 if self.modules.contains(&p) {
232 Some(p)
233 } else {
234 None
235 }
236 })
237 }
238
239 pub fn deftype(
240 &mut self,
241 scope: &ModPath,
242 name: &str,
243 params: Arc<[(TVar, Option<Type>)]>,
244 typ: Type,
245 ) -> Result<()> {
246 let defs = self.typedefs.get_or_default_cow(scope.clone());
247 if defs.get(name).is_some() {
248 bail!("{name} is already defined in scope {scope}")
249 } else {
250 thread_local! {
251 static KNOWN: RefCell<FxHashMap<ArcStr, TVar>> = RefCell::new(FxHashMap::default());
252 static DECLARED: RefCell<FxHashSet<ArcStr>> = RefCell::new(FxHashSet::default());
253 }
254 KNOWN.with_borrow_mut(|known| {
255 known.clear();
256 for (tv, tc) in params.iter() {
257 Type::TVar(tv.clone()).alias_tvars(known);
258 if let Some(tc) = tc {
259 tc.alias_tvars(known);
260 }
261 }
262 typ.alias_tvars(known);
263 });
264 DECLARED.with_borrow_mut(|declared| {
265 declared.clear();
266 for (tv, _) in params.iter() {
267 if !declared.insert(tv.name.clone()) {
268 bail!("duplicate type variable {tv} in definition of {name}");
269 }
270 }
271 typ.check_tvars_declared(declared)?;
272 for (_, t) in params.iter() {
273 if let Some(t) = t {
274 t.check_tvars_declared(declared)?;
275 }
276 }
277 Ok::<_, anyhow::Error>(())
278 })?;
279 KNOWN.with_borrow(|known| {
280 DECLARED.with_borrow(|declared| {
281 for dec in declared {
282 if !known.contains_key(dec) {
283 bail!("unused type parameter {dec} in definition of {name}")
284 }
285 }
286 Ok(())
287 })
288 })?;
289 defs.insert_cow(name.into(), TypeDef { params, typ });
290 Ok(())
291 }
292 }
293
294 pub fn undeftype(&mut self, scope: &ModPath, name: &str) {
295 if let Some(defs) = self.typedefs.get_mut_cow(scope) {
296 defs.remove_cow(&CompactString::from(name));
297 if defs.len() == 0 {
298 self.typedefs.remove_cow(scope);
299 }
300 }
301 }
302
303 pub fn bind_variable(&mut self, scope: &ModPath, name: &str, typ: Type) -> &mut Bind {
306 let binds = self.binds.get_or_default_cow(scope.clone());
307 let mut existing = true;
308 let id = binds.get_or_insert_cow(CompactString::from(name), || {
309 existing = false;
310 BindId::new()
311 });
312 if existing {
313 *id = BindId::new();
314 }
315 self.by_id.get_or_insert_cow(*id, || Bind {
316 export: true,
317 id: *id,
318 scope: scope.clone(),
319 doc: None,
320 name: CompactString::from(name),
321 typ,
322 })
323 }
324
325 pub fn unbind_variable(&mut self, id: BindId) {
326 if let Some(b) = self.by_id.remove_cow(&id) {
327 if let Some(binds) = self.binds.get_mut_cow(&b.scope) {
328 binds.remove_cow(&b.name);
329 if binds.len() == 0 {
330 self.binds.remove_cow(&b.scope);
331 }
332 }
333 }
334 }
335}