nomiscript/runtime/symbol/
scope.rs1use std::collections::HashSet;
5
6use crate::ast::Expr;
7use crate::error::{Error, Result};
8
9use crate::compiler::special::binding::shared::{reads_free, stores_free};
10
11use super::entry::{Function, Symbol, Variable};
12use super::table::SymbolTable;
13
14#[derive(Debug, Clone)]
16pub(super) enum Shadowed {
17 Value(Option<Variable>),
18 Function(Option<Function>),
19}
20
21impl Shadowed {
22 fn same_cell(&self, other: &Self) -> bool {
23 std::mem::discriminant(self) == std::mem::discriminant(other)
24 }
25}
26
27fn is_lexical_binding(specials: &HashSet<String>, name: &str, symbol: &Symbol) -> bool {
28 symbol.is_variable()
29 && symbol
30 .value()
31 .is_some_and(|value| !matches!(value, Expr::WasmGlobal(..)))
32 && !specials.contains(name)
33}
34
35impl SymbolTable {
36 pub(crate) fn set_stored_globals(&mut self, stores: HashSet<String>) {
39 self.stored_globals = stores;
40 }
41
42 pub(crate) fn set_unit_specials(&mut self, defined: HashSet<String>, dynamic: HashSet<String>) {
45 self.unit_specials = defined;
46 self.dynamic_specials = dynamic;
47 }
48
49 #[must_use]
51 pub(crate) fn is_dynamic_special(&self, name: &str) -> bool {
52 self.dynamic_specials.contains(name)
53 }
54
55 #[must_use]
58 pub(crate) fn unit_home_count(&self) -> usize {
59 self.unit_specials
60 .union(&self.dynamic_specials)
61 .chain(self.stored_globals.difference(&self.unit_specials))
62 .collect::<HashSet<_>>()
63 .len()
64 }
65
66 #[must_use]
68 pub(crate) fn is_created_global(&self, name: &str) -> bool {
69 self.created_globals.contains(name)
70 }
71
72 pub(crate) fn mark_created_global(&mut self, name: &str) {
74 self.created_globals.insert(name.to_string());
75 }
76
77 #[must_use]
80 pub(crate) fn constant_global(&self, name: &str) -> Option<Expr> {
81 if self.in_macro_expansion {
82 return None;
83 }
84 let symbol = self.symbols.get(name)?;
85 if symbol.kind().is_builtin() {
86 return None;
87 }
88 symbol
89 .value()
90 .filter(|value| !value.is_wasm_runtime())
91 .cloned()
92 }
93
94 #[must_use]
96 pub(crate) fn instance_global(&self, name: &str) -> Option<Expr> {
97 self.symbols
98 .get(name)?
99 .value()
100 .filter(|value| matches!(value, Expr::Instance(..)))
101 .cloned()
102 }
103
104 #[must_use]
106 pub(crate) fn is_unit_special(&self, name: &str) -> bool {
107 self.unit_specials.contains(name)
108 }
109
110 #[must_use]
112 pub(crate) fn is_special(&self, name: &str) -> bool {
113 self.special_names.contains(name)
114 }
115
116 #[must_use]
118 pub(crate) fn is_stored_global(&self, name: &str) -> bool {
119 self.stored_globals.contains(name)
120 }
121
122 pub fn define_special(&mut self, symbol: Symbol) {
124 let name = symbol.name.clone();
125 self.special_names.insert(name.clone());
126 self.define(symbol);
127 self.shadowed_globals.remove(&name);
128 }
129
130 pub(super) fn shadow_special(&mut self, name: &str) {
132 if !self.special_names.contains(name) || self.shadowed_globals.contains_key(name) {
133 return;
134 }
135 if let Some(global) = self
136 .symbols
137 .get(name)
138 .and_then(|symbol| symbol.value.clone())
139 {
140 self.shadowed_globals.insert(name.to_string(), global);
141 }
142 }
143
144 pub(super) fn function_alias(name: &str) -> String {
147 format!("{name} (global)")
148 }
149
150 pub(super) fn shadow_function(&mut self, binding: &Symbol) {
155 if !binding.is_local_function() {
156 return;
157 }
158 let global = match self
159 .symbols
160 .get(&binding.name)
161 .and_then(|s| s.function.as_ref())
162 {
163 Some(global) if Self::hideable(global) => global.clone(),
164 _ => return,
165 };
166 self.define_scoped(Symbol::from_function(
167 Self::function_alias(&binding.name),
168 global,
169 ));
170 }
171
172 pub(crate) fn designated_function(&self, name: &str) -> Result<Option<String>> {
177 if !self
178 .symbols
179 .get(name)
180 .is_some_and(Symbol::is_local_function)
181 {
182 return Ok(None);
183 }
184 let alias = Self::function_alias(name);
185 if self.symbols.contains_key(&alias) {
186 return Ok(Some(alias));
187 }
188 Err(Error::UndefinedSymbol(name.to_string()))
189 }
190
191 pub(crate) fn mark_special(&mut self, name: &str) {
193 self.created_globals.remove(name);
194 self.special_names.insert(name.to_string());
195 }
196
197 pub(crate) fn lexical_names(&self) -> Vec<(String, u32)> {
200 let mut names = Vec::new();
201 for (name, symbol) in &self.symbols {
202 if symbol.is_local_function() {
203 names.push((name.clone(), symbol.function_definition()));
204 }
205 if self.is_lexical(name, symbol) || self.shadowed_globals.contains_key(name) {
206 names.push((name.clone(), symbol.value_definition()));
207 }
208 }
209 names.sort();
210 names
211 }
212
213 #[must_use]
215 pub(crate) fn lexical_bindings(&self) -> Vec<Symbol> {
216 let mut bindings: Vec<Symbol> = self
217 .symbols
218 .iter()
219 .filter(|(name, symbol)| self.is_lexical(name, symbol))
220 .filter_map(|(name, symbol)| Some(Symbol::from_value(name, symbol.value.clone()?)))
221 .collect();
222 bindings.sort_by(|a, b| a.name.cmp(&b.name));
223 bindings
224 }
225
226 fn restore_kept_lexicals(&mut self, callee: &str) -> Result<()> {
229 let kept = self
230 .lookup(callee)
231 .and_then(|symbol| symbol.function.as_ref())
232 .map_or_else(Vec::new, |function| function.lexical_values.clone());
233 for binding in kept {
234 if self
235 .symbols
236 .get(binding.name())
237 .is_some_and(|s| s.value.is_some())
238 {
239 continue;
240 }
241 if binding.value().is_none() {
242 return Err(Error::Compile(format!(
243 "{}: reads {}, a runtime variable of a binder that ended, which does not outlive its unit; not supported yet",
244 Self::shown(callee),
245 binding.name()
246 )));
247 }
248 if let Some(cell) = binding.value {
249 self.put_value(&binding.name, cell);
250 }
251 }
252 Ok(())
253 }
254
255 pub(crate) fn forget_runtime_lexicals(&mut self) {
258 self.symbols
259 .values_mut()
260 .for_each(Symbol::forget_runtime_lexicals);
261 }
262
263 #[must_use]
265 pub(crate) fn lexical_constants(&self) -> Vec<(String, Expr)> {
266 let mut constants: Vec<(String, Expr)> = self
267 .symbols
268 .iter()
269 .filter(|(name, symbol)| self.is_lexical(name, symbol))
270 .filter_map(|(name, symbol)| Some((name.clone(), symbol.value()?.clone())))
271 .filter(|(_, value)| !value.is_wasm_runtime())
272 .collect();
273 constants.sort_by(|a, b| a.0.cmp(&b.0));
274 constants
275 }
276
277 pub(crate) fn hide_lexicals_except(&mut self, keep: &[(String, u32)]) {
280 let specials = &self.special_names;
281 self.symbols.retain(|name, symbol| {
282 let kept = keep.iter().any(|(kept, _)| kept == name);
283 if !kept && is_lexical_binding(specials, name, symbol) {
284 symbol.value = None;
285 }
286 !symbol.is_bare()
287 });
288 for (name, global) in std::mem::take(&mut self.shadowed_globals) {
289 if keep.iter().any(|(kept, _)| *kept == name) {
290 self.shadowed_globals.insert(name, global);
291 } else {
292 self.put_value(&name, global);
293 }
294 }
295 }
296
297 fn put_value(&mut self, name: &str, cell: Variable) {
298 self.symbols
299 .entry(name.to_string())
300 .or_insert_with(|| Symbol::bare(name))
301 .value = Some(cell);
302 }
303
304 pub(crate) fn hide_caller_lexicals(&mut self, callee: &str) -> Result<()> {
310 let (env, function) = self.lookup(callee).map_or_else(
311 || (Vec::new(), None),
312 |symbol| (symbol.lexical_env().to_vec(), symbol.function().cloned()),
313 );
314 let reads = |name: &str| {
315 function
316 .as_ref()
317 .map_or(Ok(true), |func| reads_free(self, func, name))
318 };
319 for (name, id) in &env {
320 let rebound = self
321 .symbols
322 .get(name)
323 .is_some_and(|sym| !sym.has_definition(*id));
324 if rebound && reads(name)? {
325 let verb = match function.as_ref() {
326 Some(func) if stores_free(self, func, name)? => "stores",
327 _ => "reads",
328 };
329 let callee = Self::shown(callee);
330 return Err(crate::error::Error::Compile(format!(
331 "{callee}: {verb} {name}, which the call site rebinds; a function sees the binding of its definition; not supported yet"
332 )));
333 }
334 }
335 if function.is_some() {
336 self.reject_foreign_local_function(callee, &env, &reads)?;
337 }
338 self.hide_lexicals_except(&env);
339 self.restore_kept_lexicals(callee)
340 }
341
342 pub(crate) fn drop_runtime_locals(&mut self) {
346 self.forget_local_closure_bodies();
347 self.forget_runtime_lexicals();
348 self.symbols.retain(|_, symbol| {
349 if matches!(symbol.value(), Some(Expr::WasmLocal(..))) {
350 symbol.value = None;
351 }
352 !symbol.is_bare()
353 });
354 }
355
356 fn reject_foreign_local_function(
359 &self,
360 callee: &str,
361 env: &[(String, u32)],
362 reads: &dyn Fn(&str) -> Result<bool>,
363 ) -> Result<()> {
364 for (name, symbol) in &self.symbols {
365 let foreign = symbol.is_local_function()
366 && !env
367 .iter()
368 .any(|(kept, id)| kept == name && *id == symbol.function_definition());
369 if foreign && reads(name)? {
370 let callee = Self::shown(callee);
371 return Err(crate::error::Error::Compile(format!(
372 "{callee}: calls {name}, a local function the call site binds; a function sees the functions of its definition; not supported yet"
373 )));
374 }
375 }
376 Ok(())
377 }
378
379 #[must_use]
381 pub(crate) fn is_lexical_variable(&self, name: &str) -> bool {
382 self.symbols
383 .get(name)
384 .is_some_and(|symbol| self.is_lexical(name, symbol))
385 }
386
387 fn is_lexical(&self, name: &str, symbol: &Symbol) -> bool {
388 is_lexical_binding(&self.special_names, name, symbol)
389 }
390
391 #[must_use]
394 pub(crate) fn is_macro_local(&self, name: &str) -> bool {
395 self.macro_locals.contains(name)
396 }
397
398 pub(crate) fn push_scope(&mut self) {
400 self.scopes.push(Vec::new());
401 }
402
403 pub(crate) fn define_scoped(&mut self, symbol: Symbol) {
406 let prior = self.symbols.get(&symbol.name);
407 let mut shadowed = Vec::new();
408 if symbol.value.is_some() {
409 shadowed.push(Shadowed::Value(prior.and_then(|p| p.value.clone())));
410 }
411 if symbol.function.is_some() {
412 shadowed.push(Shadowed::Function(prior.and_then(|p| p.function.clone())));
413 }
414 if let Some(frame) = self.scopes.last_mut() {
415 for cell in shadowed {
416 let recorded = frame
417 .iter()
418 .any(|(name, saved)| *name == symbol.name && saved.same_cell(&cell));
419 if !recorded {
420 frame.push((symbol.name.clone(), cell));
421 }
422 }
423 }
424 self.define(symbol);
425 }
426
427 pub(crate) fn with_scope<T>(&mut self, body: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
429 self.push_scope();
430 let result = body(self);
431 self.pop_scope()?;
432 result
433 }
434
435 pub(crate) fn pop_scope(&mut self) -> Result<()> {
437 let frame = self.scopes.pop().ok_or_else(|| {
438 crate::error::Error::Compile("internal: pop_scope() with no open scope".to_string())
439 })?;
440 for (name, shadowed) in frame.into_iter().rev() {
441 match shadowed {
442 Shadowed::Value(Some(cell)) => self.define(Symbol::from_value(name, cell)),
443 Shadowed::Function(Some(cell)) => self.define(Symbol::from_function(name, cell)),
444 Shadowed::Value(None) => self.clear_cell(&name, |symbol| symbol.value = None),
445 Shadowed::Function(None) => self.clear_cell(&name, |symbol| symbol.function = None),
446 }
447 }
448 Ok(())
449 }
450
451 pub(super) fn clear_cell(&mut self, name: &str, clear: impl FnOnce(&mut Symbol)) {
453 let Some(symbol) = self.symbols.get_mut(name) else {
454 return;
455 };
456 clear(symbol);
457 if symbol.is_bare() {
458 self.symbols.remove(name);
459 }
460 }
461}