snix_eval/compiler/bindings.rs
1//! This module implements compiler logic related to name/value binding
2//! definitions (that is, attribute sets and let-expressions).
3//!
4//! In the case of recursive scopes these cases share almost all of their
5//! (fairly complex) logic.
6
7use std::iter::Peekable;
8
9use rnix::ast::HasEntry;
10use rowan::ast::AstChildren;
11
12use crate::spans::{EntireFile, OrEntireFile};
13
14use super::{scope::ScopeGuard, *};
15
16type PeekableAttrs = Peekable<AstChildren<ast::Attr>>;
17
18/// What kind of bindings scope is being compiled?
19#[derive(Clone, Copy, PartialEq)]
20enum BindingsKind {
21 /// Standard `let ... in ...`-expression.
22 LetIn,
23
24 /// Non-recursive attribute set.
25 Attrs,
26
27 /// Recursive attribute set.
28 RecAttrs,
29}
30
31impl BindingsKind {
32 fn is_attrs(&self) -> bool {
33 matches!(self, BindingsKind::Attrs | BindingsKind::RecAttrs)
34 }
35}
36
37// Internal representation of an attribute set used for merging sets, or
38// inserting nested keys.
39#[derive(Clone)]
40struct AttributeSet {
41 /// Original span at which this set was first encountered.
42 span: Span,
43
44 /// Tracks the kind of set (rec or not).
45 kind: BindingsKind,
46
47 /// All inherited entries
48 inherits: Vec<ast::Inherit>,
49
50 /// All internal entries
51 entries: Vec<AttributeEntry>,
52}
53
54#[derive(Clone)]
55struct AttributeEntry {
56 span: Span,
57 lowered_from: Option<Span>,
58 remaining_path: PeekableAttrs,
59 expr: ast::Expr,
60}
61
62impl ToSpan for AttributeSet {
63 fn span_for(&self, _: &codemap::File) -> Span {
64 self.span
65 }
66}
67
68impl AttributeSet {
69 fn from_ast(c: &Compiler, node: &ast::AttrSet) -> Self {
70 AttributeSet {
71 span: c.span_for(node),
72
73 // Kind of the attrs depends on the first time it is
74 // encountered. We actually believe this to be a Nix
75 // bug: https://github.com/NixOS/nix/issues/7111
76 kind: if node.rec_token().is_some() {
77 BindingsKind::RecAttrs
78 } else {
79 BindingsKind::Attrs
80 },
81
82 inherits: ast::HasEntry::inherits(node).collect(),
83
84 entries: ast::HasEntry::attrpath_values(node)
85 .map(|entry| AttributeEntry {
86 span: c.span_for(&entry),
87 lowered_from: None,
88 remaining_path: entry.attrpath().unwrap().attrs().peekable(),
89 expr: entry.value().unwrap(),
90 })
91 .collect(),
92 }
93 }
94}
95
96// Data structures to track the bindings observed in the second pass, and
97// forward the information needed to compile their value.
98enum Binding {
99 InheritFrom {
100 namespace: ast::Expr,
101 name: SmolStr,
102 span: Span,
103 },
104
105 Plain {
106 expr: ast::Expr,
107 },
108
109 Set(AttributeSet),
110}
111
112impl Binding {
113 /// Merge the provided value into the current binding, or emit an
114 /// error if this turns out to be impossible.
115 fn merge(&mut self, c: &mut Compiler, mut entry: AttributeEntry) {
116 match self {
117 Binding::InheritFrom { name, span, .. } => {
118 c.emit_error(span, ErrorKind::UnmergeableInherit { name: name.clone() })
119 }
120
121 // If the value is not yet a nested binding, flip the representation
122 // and recurse.
123 Binding::Plain { expr } => match expr {
124 ast::Expr::AttrSet(existing) => {
125 let nested = AttributeSet::from_ast(c, existing);
126 *self = Binding::Set(nested);
127 self.merge(c, entry);
128 }
129
130 _ => c.emit_error(&entry.expr, ErrorKind::UnmergeableValue),
131 },
132
133 // If the value is nested further, it is simply inserted into the
134 // bindings with its full path and resolved recursively further
135 // down.
136 Binding::Set(existing) if entry.remaining_path.peek().is_some() => {
137 existing.entries.push(entry)
138 }
139
140 Binding::Set(existing) => {
141 if let ast::Expr::AttrSet(new) = entry.expr {
142 existing.inherits.extend(ast::HasEntry::inherits(&new));
143 existing
144 .entries
145 .extend(
146 ast::HasEntry::attrpath_values(&new).map(|entry| AttributeEntry {
147 span: c.span_for(&entry),
148 lowered_from: None,
149 remaining_path: entry.attrpath().unwrap().attrs().peekable(),
150 expr: entry.value().unwrap(),
151 }),
152 );
153 } else {
154 // This branch is unreachable because in cases where the
155 // path is empty (i.e. there is no further nesting), the
156 // previous try_merge function already verified that the
157 // expression is an attribute set.
158
159 // TODO(tazjin): Consider making this branch live by
160 // shuffling that check around and emitting a static error
161 // here instead of a runtime error.
162 unreachable!()
163 }
164 }
165 }
166 }
167}
168
169enum KeySlot {
170 /// There is no key slot (`let`-expressions do not emit their key).
171 None { name: SmolStr },
172
173 /// The key is statically known and has a slot.
174 Static {
175 slot: LocalIdx,
176 name: SmolStr,
177 pos_span: Span,
178 },
179
180 /// The key is dynamic, i.e. only known at runtime, and must be compiled
181 /// into its slot.
182 Dynamic {
183 slot: LocalIdx,
184 attr: ast::Attr,
185 pos_span: Span,
186 },
187}
188
189struct TrackedBinding {
190 key_slot: KeySlot,
191 value_slot: LocalIdx,
192 binding: Binding,
193}
194
195impl TrackedBinding {
196 /// Does this binding match the given key?
197 ///
198 /// Used to determine which binding to merge another one into.
199 fn matches(&self, key: &str) -> bool {
200 match &self.key_slot {
201 KeySlot::None { name } => name == key,
202 KeySlot::Static { name, .. } => name == key,
203 KeySlot::Dynamic { .. } => false,
204 }
205 }
206}
207
208struct TrackedBindings {
209 bindings: Vec<TrackedBinding>,
210}
211
212impl TrackedBindings {
213 fn new() -> Self {
214 TrackedBindings { bindings: vec![] }
215 }
216
217 /// Attempt to merge an entry into an existing matching binding, assuming
218 /// that the provided binding is mergable (i.e. either a nested key or an
219 /// attribute set literal).
220 ///
221 /// Returns `Ok` if the binding was merged, `Err` if it needs to be compiled
222 /// separately as a new binding.
223 fn try_merge(
224 &mut self,
225 c: &mut Compiler,
226 name: &ast::Attr,
227 mut entry: AttributeEntry,
228 ) -> Result<(), AttributeEntry> {
229 // If the path has no more entries, and if the entry is not an
230 // attribute set literal, the entry can not be merged.
231 if entry.remaining_path.peek().is_none() && !matches!(&entry.expr, ast::Expr::AttrSet(_)) {
232 return Err(entry);
233 }
234
235 // If the first element of the path is not statically known, the entry
236 // can not be merged.
237 let name_str = match expr_static_attr_str(name) {
238 Some(name) => name,
239 None => return Err(entry),
240 };
241
242 // If there is no existing binding with this key, the entry can not be
243 // merged.
244 // TODO: benchmark whether using a map or something is useful over the
245 // `find` here
246 let binding = match self.bindings.iter_mut().find(|b| b.matches(&name_str)) {
247 Some(b) => b,
248 None => return Err(entry),
249 };
250
251 // To comply with Nix's unsafeGetAttrPos behaviour, lowered attrpath's
252 // position should refer to the first segment of the path.
253 //
254 // example:
255 // foo.bar.baz = 1
256 //
257 // After consuming `foo`, `remaining_path` is `bar.baz`. Any attrset
258 // generated from this attrpath should refer to position of `foo`.
259 //
260 // If we are recursively compiling an already-lowered attrpath,
261 // preserver the first segment's span.
262 if entry.lowered_from.is_none() && entry.remaining_path.peek().is_some() {
263 entry.lowered_from = Some(c.span_for(name));
264 }
265
266 // No more excuses ... the binding can be merged!
267 binding.binding.merge(c, entry);
268
269 Ok(())
270 }
271
272 /// Add a completely new binding to the tracked bindings.
273 fn track_new(&mut self, key_slot: KeySlot, value_slot: LocalIdx, binding: Binding) {
274 self.bindings.push(TrackedBinding {
275 key_slot,
276 value_slot,
277 binding,
278 });
279 }
280}
281
282/// Wrapper around the `ast::HasEntry` trait as that trait can not be
283/// implemented for custom types.
284trait HasEntryProxy {
285 fn inherits(&self) -> Box<dyn Iterator<Item = ast::Inherit>>;
286
287 fn attributes<'a>(
288 &self,
289 file: &'a codemap::File,
290 ) -> Box<dyn Iterator<Item = AttributeEntry> + 'a>;
291}
292
293impl<N: HasEntry> HasEntryProxy for N {
294 fn inherits(&self) -> Box<dyn Iterator<Item = ast::Inherit>> {
295 Box::new(ast::HasEntry::inherits(self))
296 }
297
298 fn attributes<'a>(
299 &self,
300 file: &'a codemap::File,
301 ) -> Box<dyn Iterator<Item = AttributeEntry> + 'a> {
302 Box::new(
303 ast::HasEntry::attrpath_values(self).map(move |entry| AttributeEntry {
304 span: entry.span_for(file),
305 lowered_from: None,
306 remaining_path: entry.attrpath().unwrap().attrs().peekable(),
307 expr: entry.value().unwrap(),
308 }),
309 )
310 }
311}
312
313impl HasEntryProxy for AttributeSet {
314 fn inherits(&self) -> Box<dyn Iterator<Item = ast::Inherit>> {
315 Box::new(self.inherits.clone().into_iter())
316 }
317
318 fn attributes<'a>(
319 &self,
320 _: &'a codemap::File,
321 ) -> Box<dyn Iterator<Item = AttributeEntry> + 'a> {
322 Box::new(self.entries.clone().into_iter())
323 }
324}
325
326/// AST-traversing functions related to bindings.
327impl Compiler<'_, '_> {
328 /// Compile all inherits of a node with entries that do *not* have a
329 /// namespace to inherit from, and return the remaining ones that do.
330 fn compile_plain_inherits<N>(
331 &mut self,
332 slot: LocalIdx,
333 kind: BindingsKind,
334 count: &mut usize,
335 node: &N,
336 ) -> Vec<(ast::Expr, SmolStr, Span)>
337 where
338 N: ToSpan + HasEntryProxy,
339 {
340 // Pass over all inherits, resolving only those without namespaces.
341 // Since they always resolve in a higher scope, we can just compile and
342 // declare them immediately.
343 //
344 // Inherits with namespaces are returned to the caller.
345 let mut inherit_froms: Vec<(ast::Expr, SmolStr, Span)> = vec![];
346
347 for inherit in node.inherits() {
348 if inherit.attrs().peekable().peek().is_none() {
349 self.emit_warning(&inherit, WarningKind::EmptyInherit);
350 continue;
351 }
352
353 match inherit.from() {
354 // Within a `let` binding, inheriting from the outer scope is a
355 // no-op *if* there are no dynamic bindings.
356 None if !kind.is_attrs() && !self.has_dynamic_ancestor() => {
357 self.emit_warning(&inherit, WarningKind::UselessInherit);
358 continue;
359 }
360
361 None => {
362 for attr in inherit.attrs() {
363 let name = match expr_static_attr_str(&attr) {
364 Some(name) => name,
365 None => {
366 self.emit_error(&attr, ErrorKind::DynamicKeyInScope("inherit"));
367 continue;
368 }
369 };
370
371 // If the identifier resolves statically in a `let`, it
372 // has precedence over dynamic bindings, and the inherit
373 // is useless.
374 if kind == BindingsKind::LetIn
375 && matches!(
376 self.scope_mut().resolve_local(&name),
377 LocalPosition::Known(_)
378 )
379 {
380 self.emit_warning(&attr, WarningKind::UselessInherit);
381 continue;
382 }
383
384 *count += 1;
385
386 // Place key on the stack when compiling attribute sets.
387 if kind.is_attrs() {
388 self.emit_constant(name.as_str().into(), &attr);
389 let span = self.span_for(&attr);
390 self.push_attrset_pos(span);
391 self.scope_mut().declare_phantom(span, true);
392 }
393
394 // Place the value on the stack. Note that because plain
395 // inherits are always in the outer scope, the slot of
396 // *this* scope itself is used.
397 self.compile_identifier_access(slot, &name, &attr);
398
399 // In non-recursive attribute sets, the key slot must be
400 // a phantom (i.e. the identifier can not be resolved in
401 // this scope).
402 let idx = if kind == BindingsKind::Attrs {
403 let span = self.span_for(&attr);
404 self.scope_mut().declare_phantom(span, false)
405 } else {
406 self.declare_local(&attr, name)
407 };
408
409 self.scope_mut().mark_initialised(idx);
410 }
411 }
412
413 Some(from) => {
414 for attr in inherit.attrs() {
415 let name = match expr_static_attr_str(&attr) {
416 Some(name) => name,
417 None => {
418 self.emit_error(&attr, ErrorKind::DynamicKeyInScope("inherit"));
419 continue;
420 }
421 };
422
423 *count += 1;
424 inherit_froms.push((from.expr().unwrap(), name, self.span_for(&attr)));
425 }
426 }
427 }
428 }
429
430 inherit_froms
431 }
432
433 /// Declare all namespaced inherits, that is inherits which are inheriting
434 /// values from an attribute set.
435 ///
436 /// This only ensures that the locals stack is aware of the inherits, it
437 /// does not yet emit bytecode that places them on the stack. This is up to
438 /// the owner of the `bindings` vector, which this function will populate.
439 fn declare_namespaced_inherits(
440 &mut self,
441 kind: BindingsKind,
442 inherit_froms: Vec<(ast::Expr, SmolStr, Span)>,
443 bindings: &mut TrackedBindings,
444 ) {
445 for (from, name, span) in inherit_froms {
446 let key_slot = if kind.is_attrs() {
447 // In an attribute set, the keys themselves are placed on the
448 // stack but their stack slot is inaccessible (it is only
449 // consumed by `OpAttrs`).
450 KeySlot::Static {
451 slot: self.scope_mut().declare_phantom(span, false),
452 name: name.clone(),
453 pos_span: span,
454 }
455 } else {
456 KeySlot::None { name: name.clone() }
457 };
458
459 let value_slot = match kind {
460 // In recursive scopes, the value needs to be accessible on the
461 // stack.
462 BindingsKind::LetIn | BindingsKind::RecAttrs => {
463 self.declare_local(&span, name.clone())
464 }
465
466 // In non-recursive attribute sets, the value is inaccessible
467 // (only consumed by `OpAttrs`).
468 BindingsKind::Attrs => self.scope_mut().declare_phantom(span, false),
469 };
470
471 bindings.track_new(
472 key_slot,
473 value_slot,
474 Binding::InheritFrom {
475 namespace: from,
476 name,
477 span,
478 },
479 );
480 }
481 }
482
483 /// Declare all regular bindings (i.e. `key = value;`) in a bindings scope,
484 /// but do not yet compile their values.
485 fn declare_bindings<N>(
486 &mut self,
487 kind: BindingsKind,
488 count: &mut usize,
489 bindings: &mut TrackedBindings,
490 node: &N,
491 ) where
492 N: ToSpan + HasEntryProxy,
493 {
494 for mut entry in node.attributes(self.file) {
495 let key = entry.remaining_path.next().unwrap();
496
497 let mut entry = match bindings.try_merge(self, &key, entry) {
498 // Binding is nested, or already exists and was merged, move on.
499 Ok(()) => continue,
500 Err(entry) => entry,
501 };
502
503 *count += 1;
504
505 let key_span = self.span_for(&key);
506 let pos_span = entry.lowered_from.unwrap_or(key_span);
507
508 let key_slot = match expr_static_attr_str(&key) {
509 Some(name) if kind.is_attrs() => KeySlot::Static {
510 name,
511 slot: self.scope_mut().declare_phantom(key_span, false),
512 pos_span,
513 },
514
515 Some(name) => KeySlot::None { name },
516
517 None if kind.is_attrs() => KeySlot::Dynamic {
518 attr: key,
519 slot: self.scope_mut().declare_phantom(key_span, false),
520 pos_span,
521 },
522
523 None => {
524 self.emit_error(&key, ErrorKind::DynamicKeyInScope("let-expression"));
525 continue;
526 }
527 };
528
529 let value_slot = match kind {
530 BindingsKind::LetIn | BindingsKind::RecAttrs => match &key_slot {
531 // In recursive scopes, the value needs to be accessible on the
532 // stack if it is statically known
533 KeySlot::None { name } | KeySlot::Static { name, .. } => {
534 self.declare_local(&key_span, name.as_str())
535 }
536
537 // Dynamic values are never resolvable (as their names are
538 // of course only known at runtime).
539 //
540 // Note: This branch is unreachable in `let`-expressions.
541 KeySlot::Dynamic { .. } => self.scope_mut().declare_phantom(key_span, false),
542 },
543
544 // In non-recursive attribute sets, the value is inaccessible
545 // (only consumed by `OpAttrs`).
546 BindingsKind::Attrs => self.scope_mut().declare_phantom(key_span, false),
547 };
548
549 let binding = if entry.remaining_path.peek().is_some() {
550 let span = entry.span;
551 entry.lowered_from = Some(pos_span);
552
553 Binding::Set(AttributeSet {
554 span,
555 kind: BindingsKind::Attrs,
556 inherits: vec![],
557 entries: vec![entry],
558 })
559 } else {
560 Binding::Plain { expr: entry.expr }
561 };
562
563 bindings.track_new(key_slot, value_slot, binding);
564 }
565 }
566
567 /// Compile attribute set literals into equivalent bytecode.
568 ///
569 /// This is complicated by a number of features specific to Nix attribute
570 /// sets, most importantly:
571 ///
572 /// 1. Keys can be dynamically constructed through interpolation.
573 /// 2. Keys can refer to nested attribute sets.
574 /// 3. Attribute sets can (optionally) be recursive.
575 pub(super) fn compile_attr_set(&mut self, slot: LocalIdx, node: &ast::AttrSet) {
576 let kind = if node.rec_token().is_some() {
577 BindingsKind::RecAttrs
578 } else {
579 BindingsKind::Attrs
580 };
581
582 let guard = self.compile_bindings(slot, kind, node);
583 self.scope_mut().end_scope(guard);
584 }
585
586 /// Emit definitions for all variables in the top-level global env passed to the evaluation (eg
587 /// local variables in the REPL)
588 pub(super) fn compile_env(&mut self, env: &FxHashMap<SmolStr, Value>) {
589 for (name, value) in env {
590 self.scope_mut().declare_constant(name.to_string());
591 self.emit_constant(value.clone(), &EntireFile);
592 }
593 }
594
595 /// Actually binds all tracked bindings by emitting the bytecode that places
596 /// them in their stack slots.
597 fn bind_values(&mut self, bindings: TrackedBindings) {
598 let mut value_indices: Vec<LocalIdx> = vec![];
599
600 for binding in bindings.bindings.into_iter() {
601 value_indices.push(binding.value_slot);
602
603 match binding.key_slot {
604 KeySlot::None { .. } => {} // nothing to do here
605
606 KeySlot::Static {
607 slot,
608 name,
609 pos_span,
610 } => {
611 let span = self.scope()[slot].span;
612 self.emit_constant(name.as_str().into(), &OrEntireFile(span));
613 self.scope_mut().mark_initialised(slot);
614 self.push_attrset_pos(pos_span);
615 }
616
617 KeySlot::Dynamic {
618 slot,
619 attr,
620 pos_span,
621 } => {
622 self.compile_attr(slot, &attr);
623 self.scope_mut().mark_initialised(slot);
624 self.push_attrset_pos(pos_span);
625 }
626 }
627
628 match binding.binding {
629 // This entry is an inherit (from) expr. The value is placed on
630 // the stack by selecting an attribute.
631 Binding::InheritFrom {
632 namespace,
633 name,
634 span,
635 } => {
636 // Create a thunk wrapping value (which may be one as well)
637 // to avoid forcing the from expr too early.
638 self.thunk(binding.value_slot, &namespace, |c, s| {
639 c.compile(s, namespace.clone());
640 c.emit_force(&namespace);
641
642 c.emit_constant(name.as_str().into(), &span);
643 c.push_op(Op::AttrsSelect, &span);
644 })
645 }
646
647 // Binding is "just" a plain expression that needs to be
648 // compiled.
649 Binding::Plain { expr } => self.compile(binding.value_slot, expr),
650
651 // Binding is a merged or nested attribute set, and needs to be
652 // recursively compiled as another binding.
653 Binding::Set(set) => self.thunk(binding.value_slot, &set, |c, _| {
654 let g = c.compile_bindings(binding.value_slot, set.kind, &set);
655 c.scope_mut().end_scope(g);
656 }),
657 }
658
659 // Any code after this point will observe the value in the right
660 // stack slot, so mark it as initialised.
661 self.scope_mut().mark_initialised(binding.value_slot);
662 }
663
664 // Final pass to emit finaliser instructions if necessary.
665 for idx in value_indices {
666 if self.scope()[idx].needs_finaliser {
667 let stack_idx = self.scope().stack_index(idx);
668 let span = self.scope()[idx].span;
669 self.push_op(Op::Finalise, &OrEntireFile(span));
670 self.push_uvarint(stack_idx.0 as u64)
671 }
672 }
673 }
674
675 fn compile_bindings<N>(&mut self, slot: LocalIdx, kind: BindingsKind, node: &N) -> ScopeGuard
676 where
677 N: ToSpan + HasEntryProxy,
678 {
679 let mut count = 0;
680 let scope_guard = self.scope_mut().begin_scope("compile_bindings");
681
682 // Vector to track all observed bindings.
683 let mut bindings = TrackedBindings::new();
684
685 let inherit_froms = self.compile_plain_inherits(slot, kind, &mut count, node);
686 self.declare_namespaced_inherits(kind, inherit_froms, &mut bindings);
687 self.declare_bindings(kind, &mut count, &mut bindings, node);
688
689 // Check if we can bail out on empty bindings
690 if count == 0 {
691 // still need an attrset to exist, but it is empty.
692 if kind.is_attrs() {
693 self.emit_constant(Value::Attrs(NixAttrs::empty()), node);
694 return scope_guard;
695 }
696
697 self.emit_warning(node, WarningKind::EmptyLet);
698 return scope_guard;
699 }
700
701 // Actually bind values and ensure they are on the stack.
702 self.bind_values(bindings);
703
704 if kind.is_attrs() {
705 self.push_op(Op::Attrs, node);
706 self.push_uvarint(count as u64);
707 }
708
709 scope_guard
710 }
711
712 /// Compile a standard `let ...; in ...` expression.
713 ///
714 /// Unless in a non-standard scope, the encountered values are simply pushed
715 /// on the stack and their indices noted in the entries vector.
716 pub(super) fn compile_let_in(&mut self, slot: LocalIdx, node: &ast::LetIn) {
717 let guard = self.compile_bindings(slot, BindingsKind::LetIn, node);
718
719 // Deal with the body, then clean up the locals afterwards.
720 self.compile(slot, node.body().unwrap());
721 self.cleanup_scope(node, guard);
722 }
723
724 pub(super) fn compile_legacy_let(&mut self, slot: LocalIdx, node: &ast::LegacyLet) {
725 self.emit_warning(node, WarningKind::DeprecatedLegacyLet);
726 let g = self.compile_bindings(slot, BindingsKind::RecAttrs, node);
727
728 // Remove the scope, but do not emit any additional cleanup
729 // (OpAttrs consumes all of these locals).
730 self.scope_mut().end_scope(g);
731
732 self.emit_constant("body".into(), node);
733 self.push_op(Op::AttrsSelect, node);
734 }
735
736 /// Is the given identifier defined *by the user* in any current scope?
737 pub(super) fn is_user_defined(&mut self, ident: &str) -> bool {
738 matches!(
739 self.scope_mut().resolve_local(ident),
740 LocalPosition::Known(_) | LocalPosition::Recursive(_)
741 )
742 }
743
744 /// Resolve and compile access to an identifier in the scope.
745 fn compile_identifier_access<N: ToSpan + Clone>(
746 &mut self,
747 slot: LocalIdx,
748 ident: &str,
749 node: &N,
750 ) {
751 match self.scope_mut().resolve_local(ident) {
752 LocalPosition::Unknown => {
753 // Are we possibly dealing with an upvalue?
754 if let Some(idx) = self.resolve_upvalue_for_use(self.contexts.len() - 1, ident) {
755 self.push_op(Op::GetUpvalue, node);
756 self.push_uvarint(idx.0 as u64);
757 return;
758 }
759
760 // Globals are the "upmost upvalues": they behave
761 // exactly like a `let ... in` prepended to the
762 // program's text, and the global scope is nothing
763 // more than the parent scope of the root scope.
764 if let Some(global) = self.globals.get(ident) {
765 self.emit_constant(global.clone(), &self.span_for(node));
766 return;
767 }
768
769 // If there is a non-empty `with`-stack (or a parent context
770 // with one), emit a runtime dynamic resolution instruction.
771 //
772 // Since it is possible for users to e.g. assign a variable to a
773 // dynamic resolution without actually using it, this operation
774 // is wrapped in an extra thunk.
775 if self.has_dynamic_ancestor() {
776 self.thunk(slot, node, |c, _| {
777 c.context_mut().captures_with_stack = true;
778 c.emit_constant(ident.into(), node);
779 c.push_op(Op::ResolveWith, node);
780 });
781 return;
782 }
783
784 // Otherwise, this variable is missing.
785 self.emit_error(node, ErrorKind::UnknownStaticVariable);
786 }
787
788 LocalPosition::Known(idx) => {
789 self.scope_mut().mark_used(idx);
790
791 let stack_idx = self.scope().stack_index(idx);
792 self.push_op(Op::GetLocal, node);
793 self.push_uvarint(stack_idx.0 as u64);
794 }
795
796 // This identifier is referring to a value from the same scope which
797 // is not yet defined. This identifier access must be thunked.
798 LocalPosition::Recursive(idx) => {
799 self.scope_mut().mark_used(idx);
800 self.thunk(slot, node, move |compiler, _| {
801 let upvalue_idx =
802 compiler.add_upvalue(compiler.contexts.len() - 1, UpvalueKind::Local(idx));
803 compiler.push_op(Op::GetUpvalue, node);
804 compiler.push_uvarint(upvalue_idx.0 as u64);
805 })
806 }
807 };
808 }
809
810 pub(super) fn compile_ident(&mut self, slot: LocalIdx, node: &ast::Ident) {
811 let ident = node.ident_token().unwrap();
812 self.compile_identifier_access(slot, ident.text(), node);
813 }
814}
815
816/// Private compiler helpers related to bindings.
817impl Compiler<'_, '_> {
818 // ATTN: Also marks local backing the upvalue as used if any
819 fn resolve_upvalue_for_use(&mut self, ctx_idx: usize, name: &str) -> Option<UpvalueIdx> {
820 if ctx_idx == 0 {
821 // There can not be any upvalue at the outermost context.
822 return None;
823 }
824
825 // Determine whether the upvalue is a local in the enclosing context.
826 match self.contexts[ctx_idx - 1].scope.resolve_local(name) {
827 // recursive upvalues are dealt with the same way as standard known
828 // ones, as thunks and closures are guaranteed to be placed on the
829 // stack (i.e. in the right position) *during* their runtime
830 // construction
831 LocalPosition::Known(idx) | LocalPosition::Recursive(idx) => {
832 self.contexts[ctx_idx - 1].scope.mark_used(idx);
833 return Some(self.add_upvalue(ctx_idx, UpvalueKind::Local(idx)));
834 }
835
836 LocalPosition::Unknown => { /* continue below */ }
837 };
838
839 // If the upvalue comes from even further up, we need to recurse to make
840 // sure that the upvalues are created at each level.
841 if let Some(idx) = self.resolve_upvalue_for_use(ctx_idx - 1, name) {
842 return Some(self.add_upvalue(ctx_idx, UpvalueKind::Upvalue(idx)));
843 }
844
845 None
846 }
847
848 fn add_upvalue(&mut self, ctx_idx: usize, kind: UpvalueKind) -> UpvalueIdx {
849 // If there is already an upvalue closing over the specified index,
850 // retrieve that instead.
851 for (idx, existing) in self.contexts[ctx_idx].scope.upvalues.iter().enumerate() {
852 if existing.kind == kind {
853 return UpvalueIdx(idx);
854 }
855 }
856
857 self.contexts[ctx_idx].scope.upvalues.push(Upvalue { kind });
858
859 let idx = UpvalueIdx(self.contexts[ctx_idx].lambda.upvalue_count);
860 self.contexts[ctx_idx].lambda.upvalue_count += 1;
861 idx
862 }
863}