Skip to main content

nybl/
evaluator.rs

1#[cfg(all(feature = "no_std", not(feature = "std")))]
2use alloc::{
3    boxed::Box,
4    format,
5    string::{String, ToString},
6    vec,
7    vec::Vec,
8};
9
10use alloc_import::collections::{BTreeMap, BTreeSet};
11
12#[cfg(all(feature = "no_std", not(feature = "std")))]
13use alloc as alloc_import;
14#[cfg(any(feature = "std", not(feature = "no_std")))]
15use std as alloc_import;
16
17#[cfg(all(feature = "no_std", not(feature = "std")))]
18use alloc::rc::Rc;
19
20#[cfg(any(feature = "std", not(feature = "no_std")))]
21use std::rc::Rc;
22
23use core::cell::RefCell;
24
25use crate::builtins::{
26    self, error, error_at, error_fatal_with_hint, error_with_hint, error_with_hint_at,
27};
28use crate::error::NyblError;
29use crate::import_scope::{ImportScope, ImportedName};
30use crate::lexer::StringPart;
31use crate::methods;
32use crate::ops;
33use crate::parser::*;
34use crate::value::{EnumPayload, FnBody, NyblFn, NyblFnOrigin, NyblTypeExports, Value};
35use crate::{NyblHost, NyblLimits};
36
37/// What the tree-walker stores for each imported module once it
38/// has been loaded. Cached by dot-joined path so the same module
39/// imported twice in one `run` only evaluates once.
40///
41/// `Loading` is the in-progress sentinel; if an import request
42/// sees a module already in this state it's a circular import and
43/// halts with a clear error.
44enum ImportSlot {
45    Loading,
46    Loaded(Box<ModuleBindings>),
47}
48
49#[derive(Clone)]
50struct ModuleBindings {
51    /// Whether this module opted into an explicit `pub { ... }` allow-list.
52    explicit_surface: bool,
53    /// `(name, value)` pairs for every top-level `let` in the
54    /// module (fns are handled separately — they also need to
55    /// land in `self.functions` so cross-fn calls within the
56    /// module resolve).
57    bindings: Vec<(String, Value)>,
58    binding_origins: BTreeMap<String, (String, String)>,
59    /// Top-level `fn` declarations, keyed by name. The importer
60    /// registers each both in its `self.functions` table
61    /// (for nested call resolution) and as a scope binding
62    /// (so the fn is also usable as a first-class value).
63    fn_decls: Vec<(String, FunctionDefinition)>,
64    /// Struct type declarations the module introduces, already
65    /// qualified with their full identity `(module_path,
66    /// type_name)`. The importer copies these into its own
67    /// `struct_defs` without rewriting keys, so type identity
68    /// stays pinned to the declaring module across the import
69    /// boundary.
70    struct_defs: Vec<((String, String), Vec<String>)>,
71    /// Enum type declarations, qualified the same way as
72    /// `struct_defs` above.
73    enum_defs: Vec<((String, String), Vec<crate::parser::VariantDecl>)>,
74    /// User methods the module declared, keyed by the *full
75    /// type identity* of the receiver. `((module_path,
76    /// type_name), method_name, fn_def)` — the importer merges
77    /// these directly into its own `methods` table.
78    methods: Vec<((String, String), String, FunctionDefinition)>,
79    /// Public type names exposed by this module, retaining each type's
80    /// declaration module across facade re-exports.
81    type_exports: BTreeMap<String, String>,
82    /// Exported value bindings that are themselves module namespaces. The
83    /// original module object remains authoritative for path and surface.
84    module_exports: BTreeMap<String, Rc<crate::value::NyblModule>>,
85    /// Module-owned lexical metadata that named functions and methods need
86    /// after the loading evaluator has gone away. Installed as a protected
87    /// outer call frame so caller-local aliases/types cannot affect the
88    /// callee, while the callee's own locals remain free to shadow it.
89    lexical_context: Rc<ModuleLexicalContext>,
90}
91
92#[derive(Clone, Default)]
93struct ModuleLexicalContext {
94    type_bindings: Rc<BTreeMap<String, String>>,
95    module_aliases: Rc<BTreeMap<String, Rc<crate::value::NyblModule>>>,
96    imported_functions: Rc<BTreeMap<String, FunctionDefinition>>,
97}
98
99type ImportCache = Rc<RefCell<alloc_import::collections::BTreeMap<String, ImportSlot>>>;
100type LiveValueEnvironments = Rc<RefCell<BTreeMap<String, BTreeMap<String, Value>>>>;
101type BindingOrigin = (String, String);
102type LiveBindingOrigins = Rc<RefCell<BTreeMap<String, BTreeMap<String, BindingOrigin>>>>;
103
104fn take_live_environment(
105    environments: &LiveValueEnvironments,
106    module_path: &str,
107    origins: &BTreeMap<String, BindingOrigin>,
108) -> BTreeMap<String, Value> {
109    let mut environments = environments.borrow_mut();
110    let mut environment = environments.remove(module_path).unwrap_or_default();
111    for (binding, (origin_module, origin_binding)) in origins {
112        if origin_module == module_path && origin_binding == binding {
113            continue;
114        }
115        let authoritative = environments
116            .get_mut(origin_module)
117            .and_then(|origin| origin.remove(origin_binding));
118        if let Some(value) = authoritative {
119            environment.insert(binding.clone(), value);
120        }
121    }
122    environment
123}
124
125fn put_live_environment(
126    environments: &LiveValueEnvironments,
127    module_path: &str,
128    mut environment: BTreeMap<String, Value>,
129    origins: &BTreeMap<String, BindingOrigin>,
130) {
131    let mut environments = environments.borrow_mut();
132    for (binding, (origin_module, origin_binding)) in origins {
133        if origin_module == module_path && origin_binding == binding {
134            continue;
135        }
136        if let Some(value) = environment.remove(binding) {
137            environments
138                .entry(origin_module.clone())
139                .or_default()
140                .insert(origin_binding.clone(), value);
141        }
142    }
143    environments.insert(module_path.to_string(), environment);
144}
145
146fn restore_failed_module_environment(
147    environments: &LiveValueEnvironments,
148    live_origins: &LiveBindingOrigins,
149    module_path: &str,
150    scopes: &mut [BTreeMap<String, Value>],
151    binding_origins: &BTreeMap<String, BindingOrigin>,
152) {
153    let failed_environment = scopes.first_mut().map(core::mem::take).unwrap_or_default();
154    put_live_environment(
155        environments,
156        module_path,
157        failed_environment,
158        binding_origins,
159    );
160    // Forwarded values have been returned to their authoritative origins. The
161    // failed module's own partial state must not become cacheable.
162    environments.borrow_mut().remove(module_path);
163    live_origins.borrow_mut().remove(module_path);
164}
165
166fn snapshot_module_bindings(
167    top_scope: &BTreeMap<String, Value>,
168    binding_origins: &BTreeMap<String, BindingOrigin>,
169    module_path: &str,
170    imports: &ImportCache,
171    line: u32,
172) -> Result<Vec<(String, Value)>, NyblError> {
173    // Re-exported value bindings can reuse their origin's already-external
174    // snapshot. Named functions are intentionally absent from `bindings`
175    // (their callable metadata lives in `fn_decls`), so those are snapshot
176    // locally with the module's own values instead.
177    let forwarded: BTreeMap<String, Value> = {
178        let imports = imports.borrow();
179        top_scope
180            .keys()
181            .filter_map(|name| {
182                let origin = binding_origins.get(name)?;
183                if origin.0 == module_path && origin.1 == *name {
184                    return None;
185                }
186                let ImportSlot::Loaded(origin_module) = imports.get(&origin.0)? else {
187                    return None;
188                };
189                origin_module
190                    .bindings
191                    .iter()
192                    .find(|(origin_name, _)| origin_name == &origin.1)
193                    .map(|(_, value)| (name.clone(), value.clone()))
194            })
195            .collect()
196    };
197    let local: BTreeMap<String, Value> = top_scope
198        .iter()
199        .filter(|(name, _)| !forwarded.contains_key(*name))
200        .map(|(name, value)| (name.clone(), value.clone()))
201        .collect();
202    let mut local_snapshots: BTreeMap<String, Value> =
203        Value::__compatibility_snapshot_bindings(&local, line)?
204            .into_iter()
205            .collect();
206
207    top_scope
208        .keys()
209        .map(|name| {
210            let value = forwarded
211                .get(name)
212                .cloned()
213                .or_else(|| local_snapshots.remove(name))
214                .ok_or_else(|| {
215                    error(line, format!("Missing compatibility snapshot for `{name}`"))
216                })?;
217            Ok((name.clone(), value))
218        })
219        .collect()
220}
221
222const MAX_CALL_DEPTH: usize = 64;
223
224// `try` unwinds via `NyblError::try_return_signal` — a proper
225// sentinel with `is_try_return = true` rather than the older
226// magic-string approach. The value travels on
227// `Evaluator::pending_try_return` so the `NyblError` itself
228// doesn't need to carry a `Value` (which would introduce a
229// module cycle between `nybl::error` and `nybl::value`).
230
231// ─── Control flow signals ──────────────────────────────────────────────────
232
233enum Signal {
234    None,
235    Break,
236    Continue,
237    Return(Value),
238}
239
240/// An executed declaration's canonical callable.
241///
242/// Named functions and methods are immutable after their declaration site is
243/// reached. Sharing the same callable through every registry, import, and
244/// first-class value keeps the AST owned once instead of rebuilding it on each
245/// lookup or call.
246type FunctionDefinition = Rc<NyblFn>;
247
248fn parameter_metadata(params: &[Parameter]) -> (Vec<String>, Vec<ParamMode>) {
249    (
250        params.iter().map(|param| param.name.clone()).collect(),
251        params.iter().map(|param| param.mode).collect(),
252    )
253}
254
255#[allow(clippy::too_many_arguments)]
256fn function_definition(
257    params: &[Parameter],
258    body: &[Stmt],
259    self_name: Option<String>,
260    module_path: String,
261    origin: NyblFnOrigin,
262    line: u32,
263) -> Result<FunctionDefinition, NyblError> {
264    let (param_names, param_modes) = parameter_metadata(params);
265    NyblFn::try_new_ast_in_module_with_origin_and_modes(
266        param_names,
267        param_modes,
268        Vec::new(),
269        body.to_vec(),
270        self_name,
271        Some(module_path),
272        origin,
273        line,
274    )
275}
276
277#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
278struct BindingIdentity {
279    scope: usize,
280    name: String,
281}
282
283#[derive(Clone)]
284enum PlaceProjectionExpr {
285    Index(Expr),
286    Field(String),
287}
288
289#[derive(Clone)]
290enum PlaceProjection {
291    Index(Value),
292    Field(String),
293}
294
295#[derive(Clone)]
296struct PlacePlan {
297    target: BindingIdentity,
298    projections: Vec<PlaceProjectionExpr>,
299}
300
301struct ResolvedPlace {
302    target: BindingIdentity,
303    root: Value,
304    projections: Vec<PlaceProjection>,
305}
306
307struct MethodReceiver {
308    value: Value,
309    place: Option<ResolvedPlace>,
310}
311
312/// Lexical free-variable analysis for walker-created lambdas.
313///
314/// The VM performs the same analysis while compiling a lambda. The walker
315/// needs an explicit pass because evaluating a lambda only has the AST and
316/// the current runtime scopes available. Declarations take effect in source
317/// order, while control-flow bodies and match arms introduce child scopes.
318struct FreeVariableCollector {
319    scopes: Vec<alloc_import::collections::BTreeSet<String>>,
320    free: alloc_import::collections::BTreeSet<String>,
321}
322
323impl FreeVariableCollector {
324    fn for_lambda(params: &[Parameter]) -> Self {
325        Self {
326            scopes: vec![params.iter().map(|param| param.name.clone()).collect()],
327            free: alloc_import::collections::BTreeSet::new(),
328        }
329    }
330
331    fn finish(mut self, body: &[Stmt]) -> alloc_import::collections::BTreeSet<String> {
332        self.visit_statements(body);
333        self.free
334    }
335
336    fn is_bound(&self, name: &str) -> bool {
337        self.scopes.iter().rev().any(|scope| scope.contains(name))
338    }
339
340    fn reference(&mut self, name: &str) {
341        if !self.is_bound(name) {
342            self.free.insert(name.to_string());
343        }
344    }
345
346    fn declare(&mut self, name: &str) {
347        self.scopes
348            .last_mut()
349            .expect("free-variable scope")
350            .insert(name.to_string());
351    }
352
353    fn visit_scoped_block(&mut self, bindings: impl IntoIterator<Item = String>, body: &[Stmt]) {
354        self.scopes.push(bindings.into_iter().collect());
355        self.visit_statements(body);
356        self.scopes.pop();
357    }
358
359    fn visit_statements(&mut self, statements: &[Stmt]) {
360        for statement in statements {
361            self.visit_statement(statement);
362        }
363    }
364
365    fn visit_statement(&mut self, statement: &Stmt) {
366        match &statement.kind {
367            StmtKind::Let { name, value, .. } => {
368                // The initializer runs before the new name is visible.
369                self.visit_expr(value);
370                self.declare(name);
371            }
372            StmtKind::Assign { target, value, .. } => {
373                self.visit_expr(value);
374                self.visit_assign_target(target);
375            }
376            StmtKind::If {
377                condition,
378                body,
379                else_ifs,
380                else_body,
381            } => {
382                self.visit_expr(condition);
383                self.visit_scoped_block(core::iter::empty(), body);
384                for (condition, body) in else_ifs {
385                    self.visit_expr(condition);
386                    self.visit_scoped_block(core::iter::empty(), body);
387                }
388                if let Some(body) = else_body {
389                    self.visit_scoped_block(core::iter::empty(), body);
390                }
391            }
392            StmtKind::While { condition, body } => {
393                self.visit_expr(condition);
394                self.visit_scoped_block(core::iter::empty(), body);
395            }
396            StmtKind::Repeat { count, body } => {
397                self.visit_expr(count);
398                self.visit_scoped_block(core::iter::empty(), body);
399            }
400            StmtKind::ForIn {
401                var,
402                iterable,
403                body,
404            } => {
405                self.visit_expr(iterable);
406                self.visit_scoped_block(core::iter::once(var.clone()), body);
407            }
408            // Named functions and methods have their own call-time scope and
409            // are not closures in either the walker or VM.
410            StmtKind::FnDecl { .. } | StmtKind::MethodDecl { .. } => {}
411            StmtKind::Return { value } => {
412                if let Some(value) = value {
413                    self.visit_expr(value);
414                }
415            }
416            StmtKind::Use { items, alias, .. } => {
417                if let Some(alias) = alias {
418                    self.declare(alias);
419                } else if let Some(items) = items {
420                    for item in items {
421                        self.declare(item);
422                    }
423                }
424            }
425            StmtKind::ExprStmt(expr) => self.visit_expr(expr),
426            StmtKind::Break
427            | StmtKind::Continue
428            | StmtKind::PublicSurface { .. }
429            | StmtKind::StructDecl { .. }
430            | StmtKind::EnumDecl { .. } => {}
431        }
432    }
433
434    fn visit_assign_target(&mut self, target: &AssignTarget) {
435        match target {
436            AssignTarget::Variable(name) => self.reference(name),
437            AssignTarget::Index { object, index } => {
438                self.visit_expr(index);
439                self.visit_expr(object);
440            }
441            AssignTarget::Field { object, .. } => self.visit_expr(object),
442        }
443    }
444
445    fn visit_expr(&mut self, expr: &Expr) {
446        match &expr.kind {
447            ExprKind::Int(_)
448            | ExprKind::Number(_)
449            | ExprKind::Str(_)
450            | ExprKind::Bool(_)
451            | ExprKind::None => {}
452            ExprKind::StringInterp(parts) => {
453                for part in parts {
454                    if let StringPart::Variable(name) = part {
455                        self.reference(name);
456                    }
457                }
458            }
459            ExprKind::Ident(name) => self.reference(name),
460            ExprKind::BinaryOp { left, right, .. } => {
461                self.visit_expr(left);
462                self.visit_expr(right);
463            }
464            ExprKind::UnaryOp { expr, .. } | ExprKind::Try(expr) => self.visit_expr(expr),
465            ExprKind::Call { callee, args } => {
466                self.visit_expr(callee);
467                for arg in args {
468                    self.visit_expr(arg);
469                }
470            }
471            ExprKind::MethodCall { object, args, .. } => {
472                self.visit_expr(object);
473                for arg in args {
474                    self.visit_expr(arg);
475                }
476            }
477            ExprKind::FieldAccess { object, .. } => self.visit_expr(object),
478            ExprKind::StructConstruct {
479                namespace, fields, ..
480            } => {
481                if let Some(namespace) = namespace {
482                    self.reference(namespace);
483                }
484                for (_, value) in fields {
485                    self.visit_expr(value);
486                }
487            }
488            ExprKind::EnumConstruct {
489                namespace, payload, ..
490            } => {
491                if let Some(namespace) = namespace {
492                    self.reference(namespace);
493                }
494                match payload {
495                    VariantPayload::Unit => {}
496                    VariantPayload::Tuple(values) => {
497                        for value in values {
498                            self.visit_expr(value);
499                        }
500                    }
501                    VariantPayload::Struct(fields) => {
502                        for (_, value) in fields {
503                            self.visit_expr(value);
504                        }
505                    }
506                }
507            }
508            ExprKind::Index { object, index } => {
509                self.visit_expr(object);
510                self.visit_expr(index);
511            }
512            ExprKind::Array(values) => {
513                for value in values {
514                    self.visit_expr(value);
515                }
516            }
517            ExprKind::Dict(entries) => {
518                for (_, value) in entries {
519                    self.visit_expr(value);
520                }
521            }
522            ExprKind::IfExpr {
523                condition,
524                then_expr,
525                else_expr,
526            } => {
527                self.visit_expr(condition);
528                self.visit_expr(then_expr);
529                self.visit_expr(else_expr);
530            }
531            ExprKind::Lambda { params, body } => {
532                let nested = FreeVariableCollector::for_lambda(params).finish(body);
533                for name in nested {
534                    self.reference(&name);
535                }
536            }
537            ExprKind::Match { scrutinee, arms } => {
538                self.visit_expr(scrutinee);
539                for arm in arms {
540                    for namespace in arm.pattern.namespace_names() {
541                        self.reference(&namespace);
542                    }
543                    let bindings = arm.pattern.binding_names();
544                    self.scopes.push(bindings);
545                    if let Some(guard) = &arm.guard {
546                        self.visit_expr(guard);
547                    }
548                    self.visit_expr(&arm.body);
549                    self.scopes.pop();
550                }
551            }
552        }
553    }
554}
555
556// ─── Evaluator ─────────────────────────────────────────────────────────────
557
558pub struct Evaluator<'h, H: NyblHost + ?Sized> {
559    scopes: Vec<BTreeMap<String, Value>>,
560    functions: BTreeMap<String, FunctionDefinition>,
561    binding_origins: BTreeMap<String, (String, String)>,
562    /// Executed direct root declarations, with final-site replacement and an
563    /// immutable target separate from ordinary runtime function lookup.
564    abi_declarations: Vec<(String, Visibility, Rc<NyblFn>)>,
565    live_value_environments: LiveValueEnvironments,
566    live_binding_origins: LiveBindingOrigins,
567    active_value_module: String,
568    function_origin: NyblFnOrigin,
569    /// Module this evaluator is running. Used to tag newly
570    /// declared types with the module they live in, so two
571    /// modules that declare `struct Color { ... }` produce
572    /// distinct types rather than colliding by name. `<root>`
573    /// for the top-level program, the dot-joined module path
574    /// for a sub-evaluator loading a `use`'d module.
575    current_module: String,
576    /// User-defined struct types, keyed by their full identity
577    /// `(module_path, type_name)` — the same pair the runtime
578    /// values carry. Two modules declaring the same struct name
579    /// coexist at different keys with independently-validated
580    /// field lists.
581    struct_defs: BTreeMap<(String, String), Vec<String>>,
582    /// User-defined enum types, same `(module_path, type_name)`
583    /// keying scheme as [`Self::struct_defs`].
584    enum_defs: BTreeMap<(String, String), Vec<VariantDecl>>,
585    /// User-defined methods. Outer key is the *full type
586    /// identity* `(module_path, type_name)`; inner key is the
587    /// method name. Methods receive the receiver as their first
588    /// parameter (conventionally `self`). Dispatch looks up the
589    /// receiver's own `(module_path, type_name)` so a method
590    /// declared for `paint.Color` isn't accidentally called on
591    /// `other.Color`.
592    methods: BTreeMap<(String, String), BTreeMap<String, FunctionDefinition>>,
593    /// Public type projection for the module currently being evaluated.
594    /// Unlike `type_bindings`, this excludes builtins, aliases, and nested
595    /// declarations and is therefore safe to cache as the module's exports.
596    type_exports: BTreeMap<String, String>,
597    /// Per-scope bare-name → module_path bindings for types
598    /// *and* module aliases. Parallels `scopes`: a declared
599    /// type or an aliased `use` binds `name → module_path` in
600    /// the current scope. Bare-name lookup (`Color::Red`,
601    /// `m.Color::Red`) walks this stack inside-out. `<builtin>`
602    /// types (`Result`, `RuntimeError`) are seeded into scope
603    /// 0 at evaluator construction so they're visible
604    /// everywhere.
605    ///
606    /// Unlike `scopes`, this stack is *preserved* across
607    /// function calls — type identity follows lexical scoping
608    /// at the module level, so a `fn` declared inside the root
609    /// program can still match patterns against types + aliases
610    /// that were visible at its declaration site. Function
611    /// bodies push a fresh frame on entry so any locally-
612    /// declared types are discarded on return; module-scope
613    /// entries below stay put.
614    type_bindings: Vec<BTreeMap<String, String>>,
615    /// Module-level aliases `m → Rc<NyblModule>`, populated by
616    /// aliased `use` statements. Separate from `scopes` so
617    /// aliases remain reachable from inside function bodies
618    /// (where `self.scopes` is fresh per call). Field access /
619    /// method dispatch on `m.foo` falls back to this map when
620    /// `m` isn't a local binding.
621    module_aliases: Vec<BTreeMap<String, Rc<crate::value::NyblModule>>>,
622    /// Callable exports introduced by non-aliased `use`, paired with lexical
623    /// value scopes. This keeps direct calls fast without publishing a local
624    /// import in the evaluator-wide named-function registry.
625    imported_functions: Vec<BTreeMap<String, FunctionDefinition>>,
626    /// Current module namespace, refreshed only by top-level declarations and
627    /// imports. Calls clone this one Rc and keep mutable locals in ordinary
628    /// per-call maps.
629    root_lexical_context: Rc<ModuleLexicalContext>,
630    active_lexical_contexts: Vec<Rc<ModuleLexicalContext>>,
631    host: &'h mut H,
632    steps: u64,
633    /// Header lines of the source loops currently executing,
634    /// outermost first. Spans function calls (a callee runs on the
635    /// same evaluator) but not module imports (those get a fresh
636    /// sub-evaluator, mirroring the VM's nested module VM). Read
637    /// only when the step budget trips, so the error points at the
638    /// outermost active loop's header rather than whichever
639    /// statement the counter happened to cross the limit on — see
640    /// `tick`.
641    loop_lines: Vec<u32>,
642    /// Function frames active on this evaluator.
643    call_depth: usize,
644    /// Frames active below this evaluator: an imported module's
645    /// sub-evaluator inherits its importer's depth plus one frame for the
646    /// load itself, so call depth is shared across module boundaries.
647    call_depth_base: usize,
648    /// Static nesting depth charged by active frames against
649    /// `NyblLimits::max_nesting`; inherited by module sub-evaluators.
650    nesting_used: u32,
651    /// Defining module for each active function call. This keeps module-owned
652    /// sibling lookup private to that function instead of leaking aliased
653    /// functions into the caller-visible `functions` map.
654    function_modules: Vec<String>,
655    /// First alias-frame index visible to the active function, excluding the
656    /// always-visible module/root frame at index 0.
657    alias_scope_floors: Vec<usize>,
658    limits: NyblLimits,
659    memory: crate::memory::MemoryContext,
660    rand_state: u64,
661    /// Shared across nested evaluators so recursive imports see
662    /// the same cache — every sub-evaluator inherits the parent's
663    /// `Rc` clone in `new_nested`.
664    imports: ImportCache,
665    /// Imports applied to each lexical scope of *this* evaluator (not
666    /// shared with sub-evaluators): plain-glob paths, so re-importing the
667    /// same path at the same level is a no-op, and the origin of every name
668    /// a flat `use` bound, for clash detection.
669    import_scopes: Vec<ImportScope>,
670    /// Set by `try` when it sees an `Err(...)` variant and wants
671    /// the enclosing fn to early-return with that value. The
672    /// expression that raised stuffs the value here and returns
673    /// a sentinel `NyblError`; the fn-call wrapper detects the
674    /// sentinel, takes the value, and converts it to
675    /// `Signal::Return`. Always `None` outside the narrow
676    /// unwinding window.
677    pending_try_return: Option<Value>,
678    /// Binding identities that are staged `ref` parameters in the active
679    /// function frame. They may be forwarded, but a nested closure may not
680    /// capture them.
681    active_ref_bindings: alloc_import::collections::BTreeSet<BindingIdentity>,
682    /// Captures seeded into the active closure frame. Explicit `ref`
683    /// arguments may not target these second-class bindings.
684    active_capture_bindings: alloc_import::collections::BTreeSet<BindingIdentity>,
685}
686
687impl<'h, H: NyblHost + ?Sized> Evaluator<'h, H> {
688    pub fn new(host: &'h mut H, limits: NyblLimits) -> Self {
689        let memory = crate::memory::MemoryContext::__new(limits.max_memory);
690        let (struct_defs, enum_defs, builtin_bindings) = seed_builtin_types();
691        let root_lexical_context = Rc::new(ModuleLexicalContext {
692            type_bindings: Rc::new(builtin_bindings.clone()),
693            module_aliases: Rc::new(BTreeMap::new()),
694            imported_functions: Rc::new(BTreeMap::new()),
695        });
696        Self {
697            scopes: vec![BTreeMap::new()],
698            functions: BTreeMap::new(),
699            binding_origins: BTreeMap::new(),
700            abi_declarations: Vec::new(),
701            live_value_environments: Rc::new(RefCell::new(BTreeMap::new())),
702            live_binding_origins: Rc::new(RefCell::new(BTreeMap::new())),
703            active_value_module: String::from(crate::value::ROOT_MODULE_PATH),
704            function_origin: NyblFnOrigin::__instance("walker"),
705            current_module: String::from(crate::value::ROOT_MODULE_PATH),
706            struct_defs,
707            enum_defs,
708            methods: BTreeMap::new(),
709            type_exports: BTreeMap::new(),
710            type_bindings: vec![builtin_bindings],
711            module_aliases: vec![BTreeMap::new()],
712            imported_functions: vec![BTreeMap::new()],
713            root_lexical_context,
714            active_lexical_contexts: Vec::new(),
715            host,
716            steps: 0,
717            loop_lines: Vec::new(),
718            call_depth: 0,
719            call_depth_base: 0,
720            nesting_used: 0,
721            function_modules: Vec::new(),
722            alias_scope_floors: Vec::new(),
723            limits,
724            memory,
725            rand_state: 0,
726            imports: Rc::new(RefCell::new(alloc_import::collections::BTreeMap::new())),
727            import_scopes: vec![ImportScope::default()],
728            pending_try_return: None,
729            active_ref_bindings: alloc_import::collections::BTreeSet::new(),
730            active_capture_bindings: alloc_import::collections::BTreeSet::new(),
731        }
732    }
733
734    /// Build a sub-evaluator for loading a module — inherits the
735    /// parent's import cache, memory ceiling, and step budget, but
736    /// runs with a fresh scope stack so module code can't see the
737    /// importer's locals. `module_path` is the dot-joined name the
738    /// module is being loaded under; types it declares tag their
739    /// runtime values with this path.
740    #[allow(clippy::too_many_arguments)]
741    fn new_for_module(
742        host: &'h mut H,
743        limits: NyblLimits,
744        imports: ImportCache,
745        live_value_environments: LiveValueEnvironments,
746        live_binding_origins: LiveBindingOrigins,
747        function_origin: NyblFnOrigin,
748        module_path: String,
749        memory: crate::memory::MemoryContext,
750    ) -> Self {
751        let (struct_defs, enum_defs, builtin_bindings) = seed_builtin_types();
752        let root_lexical_context = Rc::new(ModuleLexicalContext {
753            type_bindings: Rc::new(builtin_bindings.clone()),
754            module_aliases: Rc::new(BTreeMap::new()),
755            imported_functions: Rc::new(BTreeMap::new()),
756        });
757        Self {
758            scopes: vec![BTreeMap::new()],
759            functions: BTreeMap::new(),
760            binding_origins: BTreeMap::new(),
761            abi_declarations: Vec::new(),
762            live_value_environments,
763            live_binding_origins,
764            active_value_module: module_path.clone(),
765            function_origin,
766            current_module: module_path,
767            struct_defs,
768            enum_defs,
769            methods: BTreeMap::new(),
770            type_exports: BTreeMap::new(),
771            type_bindings: vec![builtin_bindings],
772            module_aliases: vec![BTreeMap::new()],
773            imported_functions: vec![BTreeMap::new()],
774            root_lexical_context,
775            active_lexical_contexts: Vec::new(),
776            host,
777            steps: 0,
778            loop_lines: Vec::new(),
779            call_depth: 0,
780            call_depth_base: 0,
781            nesting_used: 0,
782            function_modules: Vec::new(),
783            alias_scope_floors: Vec::new(),
784            limits,
785            memory,
786            rand_state: 0,
787            imports,
788            import_scopes: vec![ImportScope::default()],
789            pending_try_return: None,
790            active_ref_bindings: alloc_import::collections::BTreeSet::new(),
791            active_capture_bindings: alloc_import::collections::BTreeSet::new(),
792        }
793    }
794
795    pub fn run(mut self, stmts: &[Stmt]) -> Result<(), NyblError> {
796        // The root top level is the first active frame.
797        self.enter_nesting(crate::ast_depth::body_depth(stmts), 0)?;
798        let mut result = self.exec_block(stmts);
799        if result.is_ok() && self.memory.__exceeded() {
800            result = Err(error_fatal_with_hint(
801                stmts.last().map_or(0, |stmt| stmt.line),
802                "Memory limit exceeded",
803                "Your code is using too much memory. Check for large strings or arrays growing in loops.",
804            ));
805        }
806        match result? {
807            Signal::Break => {
808                return Err(error(0, "break used outside of a loop"));
809            }
810            Signal::Continue => {
811                return Err(error(0, "continue used outside of a loop"));
812            }
813            _ => {}
814        }
815        Ok(())
816    }
817
818    fn tick(&mut self, line: u32) -> Result<(), NyblError> {
819        self.steps += 1;
820        if self.steps > self.limits.max_steps {
821            // Fatal — `try_call` must not swallow this, or the
822            // sandbox invariant breaks.
823            //
824            // Which statement the budget trips on is an accident of
825            // step-count phase (and differs from the VM's
826            // per-instruction accounting), so report the outermost
827            // active source loop's header instead — the VM does the
828            // same, keeping the two engines' error lines aligned.
829            // Outermost, not innermost: a finite inner loop inside
830            // an infinite outer loop trips at an engine-dependent
831            // phase (sometimes inside the inner loop, sometimes
832            // between passes), but the outermost active loop is the
833            // same either way.
834            return Err(error_fatal_with_hint(
835                self.loop_lines.first().copied().unwrap_or(line),
836                "Your code took too many steps (possible infinite loop)",
837                "Check your loops — make sure they have a condition that eventually stops them.",
838            ));
839        }
840        if self.memory.__exceeded() {
841            return Err(error_fatal_with_hint(
842                line,
843                "Memory limit exceeded",
844                "Your code is using too much memory. Check for large strings or arrays growing in loops.",
845            ));
846        }
847        self.host.on_tick()?;
848        Ok(())
849    }
850
851    /// Charge a fixed step cost (a module load) against the step budget.
852    fn charge_steps(&mut self, steps: u64, line: u32) -> Result<(), NyblError> {
853        self.steps = self.steps.saturating_add(steps);
854        if self.steps > self.limits.max_steps {
855            return Err(crate::error_messages::step_limit_error(line));
856        }
857        Ok(())
858    }
859
860    /// Frames active across this evaluator and the importers below it.
861    fn active_call_depth(&self) -> usize {
862        self.call_depth_base + self.call_depth
863    }
864
865    /// Charge a frame's static nesting depth; the frame releases it with
866    /// [`Self::leave_nesting`] on every exit path.
867    fn enter_nesting(&mut self, depth: u32, line: u32) -> Result<(), NyblError> {
868        let used = self.nesting_used.saturating_add(depth);
869        if used > self.limits.max_nesting {
870            return Err(crate::error_messages::nesting_error(line));
871        }
872        self.nesting_used = used;
873        Ok(())
874    }
875
876    fn leave_nesting(&mut self, depth: u32) {
877        self.nesting_used = self.nesting_used.saturating_sub(depth);
878    }
879
880    // ─── Scope ─────────────────────────────────────────────────────
881
882    fn push_scope(&mut self) {
883        self.scopes.push(BTreeMap::new());
884        // Type bindings parallel the value scopes — same push /
885        // pop rhythm keeps `use`-injected type names stack-scoped.
886        self.type_bindings.push(BTreeMap::new());
887        self.module_aliases.push(BTreeMap::new());
888        self.imported_functions.push(BTreeMap::new());
889        self.import_scopes.push(ImportScope::default());
890    }
891
892    fn pop_scope(&mut self) {
893        self.scopes.pop();
894        self.type_bindings.pop();
895        self.module_aliases.pop();
896        self.imported_functions.pop();
897        self.import_scopes.pop();
898    }
899
900    fn module_alias(&self, name: &str) -> Option<&Rc<crate::value::NyblModule>> {
901        let floor = self.alias_scope_floors.last().copied();
902        self.module_aliases
903            .iter()
904            .enumerate()
905            .rev()
906            .filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
907            .find_map(|(_, frame)| frame.get(name))
908            .or_else(|| {
909                self.active_lexical_contexts
910                    .last()
911                    .and_then(|context| context.module_aliases.get(name))
912            })
913    }
914
915    fn imported_function(&self, name: &str) -> Option<&FunctionDefinition> {
916        let floor = self.alias_scope_floors.last().copied();
917        self.imported_functions
918            .iter()
919            .enumerate()
920            .rev()
921            .filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
922            .find_map(|(_, frame)| frame.get(name))
923            .or_else(|| {
924                self.active_lexical_contexts
925                    .last()
926                    .and_then(|context| context.imported_functions.get(name))
927            })
928    }
929
930    fn module_lexical_context(&self, module_path: &str) -> Rc<ModuleLexicalContext> {
931        if module_path == self.current_module {
932            return Rc::clone(&self.root_lexical_context);
933        }
934        let cache = self.imports.borrow();
935        match cache.get(module_path) {
936            Some(ImportSlot::Loaded(bindings)) => Rc::clone(&bindings.lexical_context),
937            _ => Rc::new(ModuleLexicalContext::default()),
938        }
939    }
940
941    fn publish_root_type_binding(&mut self, name: String, origin: String) {
942        let context = Rc::make_mut(&mut self.root_lexical_context);
943        Rc::make_mut(&mut context.type_bindings).insert(name, origin);
944    }
945
946    fn publish_root_module_alias(
947        &mut self,
948        name: String,
949        module: Option<Rc<crate::value::NyblModule>>,
950    ) {
951        let context = Rc::make_mut(&mut self.root_lexical_context);
952        let aliases = Rc::make_mut(&mut context.module_aliases);
953        if let Some(module) = module {
954            aliases.insert(name, module);
955        } else {
956            aliases.remove(&name);
957        }
958    }
959
960    fn publish_root_imported_function(&mut self, name: String, function: FunctionDefinition) {
961        let context = Rc::make_mut(&mut self.root_lexical_context);
962        Rc::make_mut(&mut context.imported_functions).insert(name, function);
963    }
964
965    fn is_module_top_scope(&self) -> bool {
966        self.call_depth == 0 && self.scopes.len() == 1
967    }
968
969    /// Origin of `name`'s binding in the current scope, as a flat `use`
970    /// sees it: `None` when unbound, `Some(None)` for a local declaration
971    /// (a `let`, parameter, or — at module top level — an executed `fn`),
972    /// and `Some(Some(origin))` for a name a flat `use` bound here or a
973    /// function body's own name.
974    fn flat_binding_origin(
975        &self,
976        name: &str,
977        module_top_scope: bool,
978    ) -> Option<Option<crate::import_scope::BindingOrigin>> {
979        if let Some(origin) = self
980            .import_scopes
981            .last()
982            .and_then(|scope| scope.known_origin(name))
983        {
984            return Some(Some(origin.clone()));
985        }
986        (self
987            .scopes
988            .last()
989            .is_some_and(|scope| scope.contains_key(name))
990            || self
991                .import_scopes
992                .last()
993                .is_some_and(|scope| scope.functions.contains(name))
994            || (module_top_scope && self.functions.contains_key(name)))
995        .then_some(None)
996    }
997
998    /// Resolve a type reference to the module it was declared
999    /// in. `namespace` is the explicit qualifier (from
1000    /// `m.Color::Red`) or `None` for bare names. For bare names
1001    /// the scope stack is walked inside-out; for namespaced
1002    /// references the alias is resolved via
1003    /// `validate_namespaced_type` and its backing module path
1004    /// returned. Returns `None` when no matching type is visible.
1005    fn resolve_type_ref(&self, namespace: Option<&str>, type_name: &str) -> Option<String> {
1006        resolve_type_in_evaluator_context(
1007            &self.scopes,
1008            &self.type_bindings,
1009            &self.module_aliases,
1010            self.alias_scope_floors.last().copied(),
1011            self.active_lexical_contexts.last().map(Rc::as_ref),
1012            namespace,
1013            type_name,
1014        )
1015    }
1016
1017    /// Record a type declaration in the current module.
1018    /// Registers `(current_module, name)` in the appropriate
1019    /// table and binds the bare name in the current scope so
1020    /// subsequent references resolve to *this* module's version.
1021    /// Same-shape redeclarations in the same module are a no-op;
1022    /// different-shape ones error.
1023    fn bind_local_type(&mut self, name: &str) {
1024        if let Some(top) = self.type_bindings.last_mut() {
1025            top.insert(name.to_string(), self.current_module.clone());
1026        }
1027        if self.is_module_top_scope() {
1028            self.type_exports
1029                .insert(name.to_string(), self.current_module.clone());
1030            self.publish_root_type_binding(name.to_string(), self.current_module.clone());
1031        }
1032    }
1033
1034    fn define(&mut self, name: String, value: Value) {
1035        if let Some(scope) = self.scopes.last_mut() {
1036            scope.insert(name, value);
1037        }
1038    }
1039
1040    fn get_var(&self, name: &str) -> Option<&Value> {
1041        for scope in self.scopes.iter().rev() {
1042            if let Some(val) = scope.get(name) {
1043                return Some(val);
1044            }
1045        }
1046        None
1047    }
1048
1049    fn resolve_binding_identity(&self, name: &str) -> Option<BindingIdentity> {
1050        self.scopes
1051            .iter()
1052            .enumerate()
1053            .rev()
1054            .find(|(_, scope)| scope.contains_key(name))
1055            .map(|(scope, _)| BindingIdentity {
1056                scope,
1057                name: name.to_string(),
1058            })
1059    }
1060
1061    fn binding_value(&self, target: &BindingIdentity) -> Option<Value> {
1062        self.scopes
1063            .get(target.scope)
1064            .and_then(|scope| scope.get(&target.name))
1065            .cloned()
1066    }
1067
1068    fn pending_memory_error(&self, line: u32) -> Option<NyblError> {
1069        self.memory.__exceeded().then(|| {
1070            error_fatal_with_hint(
1071                line,
1072                "Memory limit exceeded",
1073                "Your code is using too much memory. Check for large strings or arrays growing in loops.",
1074            )
1075        })
1076    }
1077
1078    fn decompose_place_expr(
1079        expr: &Expr,
1080        projections: &mut Vec<PlaceProjectionExpr>,
1081    ) -> Option<String> {
1082        match &expr.kind {
1083            ExprKind::Ident(name) => Some(name.clone()),
1084            ExprKind::Index { object, index } => {
1085                let root = Self::decompose_place_expr(object, projections)?;
1086                projections.push(PlaceProjectionExpr::Index((**index).clone()));
1087                Some(root)
1088            }
1089            ExprKind::FieldAccess { object, field } => {
1090                let root = Self::decompose_place_expr(object, projections)?;
1091                projections.push(PlaceProjectionExpr::Field(field.clone()));
1092                Some(root)
1093            }
1094            _ => None,
1095        }
1096    }
1097
1098    fn preflight_place_expr(
1099        &self,
1100        expr: &Expr,
1101        position: usize,
1102        line: u32,
1103    ) -> Result<PlacePlan, NyblError> {
1104        let mut projections = Vec::new();
1105        let root = Self::decompose_place_expr(expr, &mut projections)
1106            .ok_or_else(|| crate::ref_params::invalid_ref_target(position, line))?;
1107        self.preflight_place_parts(root, projections, position, line)
1108    }
1109
1110    fn read_place_plan(&self, expr: &Expr) -> Option<PlacePlan> {
1111        let mut projections = Vec::new();
1112        let root = Self::decompose_place_expr(expr, &mut projections)?;
1113        let target = self.resolve_binding_identity(&root)?;
1114        Some(PlacePlan {
1115            target,
1116            projections,
1117        })
1118    }
1119
1120    fn validate_mutable_place(
1121        &self,
1122        place: &ResolvedPlace,
1123        position: usize,
1124        line: u32,
1125    ) -> Result<(), NyblError> {
1126        if crate::naming::is_constant_name(&place.target.name) {
1127            return Err(crate::error_messages::constant_mutation_error(
1128                &place.target.name,
1129                line,
1130            ));
1131        }
1132        if self.active_capture_bindings.contains(&place.target) {
1133            return Err(crate::ref_params::captured_ref_target(position, line));
1134        }
1135        Ok(())
1136    }
1137
1138    fn preflight_place_parts(
1139        &self,
1140        root: String,
1141        projections: Vec<PlaceProjectionExpr>,
1142        position: usize,
1143        line: u32,
1144    ) -> Result<PlacePlan, NyblError> {
1145        if crate::naming::is_constant_name(&root) {
1146            return Err(crate::error_messages::constant_mutation_error(&root, line));
1147        }
1148        let target = self
1149            .resolve_binding_identity(&root)
1150            .ok_or_else(|| crate::ref_params::invalid_ref_target(position, line))?;
1151        if self.active_capture_bindings.contains(&target) {
1152            return Err(crate::ref_params::captured_ref_target(position, line));
1153        }
1154        Ok(PlacePlan {
1155            target,
1156            projections,
1157        })
1158    }
1159
1160    fn assignment_place_parts(
1161        &self,
1162        root: String,
1163        projections: Vec<PlaceProjectionExpr>,
1164        line: u32,
1165    ) -> Result<PlacePlan, NyblError> {
1166        if crate::naming::is_constant_name(&root) {
1167            return Err(crate::error_messages::constant_mutation_error(&root, line));
1168        }
1169        let target = self.resolve_binding_identity(&root).ok_or_else(|| {
1170            error_with_hint(
1171                line,
1172                format!("Variable `{root}` doesn't exist yet"),
1173                format!("Use `let` to create a new variable: let {root} = ..."),
1174            )
1175        })?;
1176        // Unlike a `ref` call boundary, ordinary assignment may update the
1177        // closure's local captured snapshot during that invocation.
1178        Ok(PlacePlan {
1179            target,
1180            projections,
1181        })
1182    }
1183
1184    fn preflight_ref_places(
1185        &self,
1186        args: &[CallArg],
1187        line: u32,
1188    ) -> Result<Vec<PlacePlan>, NyblError> {
1189        let mut places = Vec::new();
1190        let mut unique = alloc_import::collections::BTreeSet::new();
1191        for (index, arg) in args.iter().enumerate() {
1192            if arg.mode != ParamMode::Ref {
1193                continue;
1194            }
1195            let place = self.preflight_place_expr(&arg.value, index + 1, line)?;
1196            // A call stages and commits each root once. Rejecting two paths
1197            // into the same root keeps copy-out deterministic without an
1198            // alias analysis (`ref rows[0], ref rows[1]` is therefore an
1199            // intentional error).
1200            if !unique.insert(place.target.clone()) {
1201                return Err(crate::ref_params::duplicate_ref_target(line));
1202            }
1203            places.push(place);
1204        }
1205        Ok(places)
1206    }
1207
1208    fn resolve_place(
1209        &mut self,
1210        plan: PlacePlan,
1211        position: usize,
1212        line: u32,
1213    ) -> Result<ResolvedPlace, NyblError> {
1214        let mut projections = Vec::with_capacity(plan.projections.len());
1215        for projection in plan.projections {
1216            projections.push(match projection {
1217                PlaceProjectionExpr::Index(index) => {
1218                    PlaceProjection::Index(self.eval_expr(&index)?)
1219                }
1220                PlaceProjectionExpr::Field(field) => PlaceProjection::Field(field),
1221            });
1222        }
1223        // Projection expressions may mutate the root. Snapshot only after
1224        // each projection has been evaluated so the resolved leaf observes
1225        // those effects (and so every expression still runs exactly once).
1226        let root = self
1227            .binding_value(&plan.target)
1228            .ok_or_else(|| crate::ref_params::invalid_ref_target(position, line))?;
1229        Ok(ResolvedPlace {
1230            target: plan.target,
1231            root,
1232            projections,
1233        })
1234    }
1235
1236    fn place_value_from(
1237        &self,
1238        root: &Value,
1239        projections: &[PlaceProjection],
1240        line: u32,
1241    ) -> Result<Value, NyblError> {
1242        let mut value = root.clone();
1243        for projection in projections {
1244            value = match projection {
1245                PlaceProjection::Index(index) => {
1246                    ops::index_get_in(&value, index, line, &self.memory)?
1247                }
1248                PlaceProjection::Field(field) => match &value {
1249                    Value::Struct(struct_value) => {
1250                        struct_value.field(field).cloned().ok_or_else(|| {
1251                            error(
1252                                line,
1253                                crate::error_messages::struct_has_no_field(
1254                                    struct_value.type_name(),
1255                                    field,
1256                                ),
1257                            )
1258                        })?
1259                    }
1260                    other => {
1261                        return Err(error(
1262                            line,
1263                            crate::error_messages::cant_assign_field(field, other.type_name()),
1264                        ));
1265                    }
1266                },
1267            };
1268        }
1269        Ok(value)
1270    }
1271
1272    fn write_place_value(
1273        &self,
1274        root: &mut Value,
1275        projections: &[PlaceProjection],
1276        value: Value,
1277        line: u32,
1278    ) -> Result<(), NyblError> {
1279        let Some((projection, tail)) = projections.split_first() else {
1280            *root = value;
1281            return Ok(());
1282        };
1283        if tail.is_empty() {
1284            return match projection {
1285                PlaceProjection::Index(index) => {
1286                    ops::index_set_in(root, index, value, line, &self.memory)
1287                }
1288                PlaceProjection::Field(field) => match root {
1289                    Value::Struct(struct_value) => {
1290                        let type_name = struct_value.type_name().to_string();
1291                        if struct_value.__try_set_field_in(field, value, line, &self.memory)? {
1292                            Ok(())
1293                        } else {
1294                            Err(error(
1295                                line,
1296                                crate::error_messages::struct_has_no_field(&type_name, field),
1297                            ))
1298                        }
1299                    }
1300                    other => Err(error(
1301                        line,
1302                        crate::error_messages::cant_assign_field(field, other.type_name()),
1303                    )),
1304                },
1305            };
1306        }
1307        let mut child = match projection {
1308            PlaceProjection::Index(index) => ops::index_get_in(root, index, line, &self.memory)?,
1309            PlaceProjection::Field(field) => match root {
1310                Value::Struct(struct_value) => {
1311                    struct_value.field(field).cloned().ok_or_else(|| {
1312                        error(
1313                            line,
1314                            crate::error_messages::struct_has_no_field(
1315                                struct_value.type_name(),
1316                                field,
1317                            ),
1318                        )
1319                    })?
1320                }
1321                other => {
1322                    return Err(error(
1323                        line,
1324                        crate::error_messages::cant_assign_field(field, other.type_name()),
1325                    ));
1326                }
1327            },
1328        };
1329        self.write_place_value(&mut child, tail, value, line)?;
1330        match projection {
1331            PlaceProjection::Index(index) => {
1332                ops::index_set_in(root, index, child, line, &self.memory)
1333            }
1334            PlaceProjection::Field(field) => match root {
1335                Value::Struct(struct_value) => {
1336                    let type_name = struct_value.type_name().to_string();
1337                    if struct_value.__try_set_field_in(field, child, line, &self.memory)? {
1338                        Ok(())
1339                    } else {
1340                        Err(error(
1341                            line,
1342                            crate::error_messages::struct_has_no_field(&type_name, field),
1343                        ))
1344                    }
1345                }
1346                other => Err(error(
1347                    line,
1348                    crate::error_messages::cant_assign_field(field, other.type_name()),
1349                )),
1350            },
1351        }
1352    }
1353
1354    fn commit_ref_places(
1355        &mut self,
1356        places: &[ResolvedPlace],
1357        values: Vec<Value>,
1358        line: u32,
1359    ) -> Result<(), NyblError> {
1360        if places.len() != values.len()
1361            || places.iter().any(|place| {
1362                self.scopes
1363                    .get(place.target.scope)
1364                    .is_none_or(|scope| !scope.contains_key(&place.target.name))
1365            })
1366        {
1367            return Err(error(
1368                line,
1369                "a `ref` target stopped being available before commit",
1370            ));
1371        }
1372        let mut candidates = Vec::with_capacity(places.len());
1373        for (place, value) in places.iter().zip(values) {
1374            let mut root = place.root.clone();
1375            self.write_place_value(&mut root, &place.projections, value, line)?;
1376            candidates.push(root);
1377        }
1378        for (place, root) in places.iter().zip(candidates) {
1379            self.scopes[place.target.scope].insert(place.target.name.clone(), root);
1380        }
1381        Ok(())
1382    }
1383
1384    fn get_var_value(&self, name: &str) -> Option<Value> {
1385        self.get_var(name).cloned().or_else(|| {
1386            self.module_alias(name)
1387                .map(|module| Value::Module(Rc::clone(module)))
1388        })
1389    }
1390
1391    fn live_origin_value(&self, origin: &BindingOrigin) -> Option<Value> {
1392        if self.active_value_module == origin.0
1393            && let Some(value) = self
1394                .scopes
1395                .first()
1396                .and_then(|environment| environment.get(&origin.1))
1397        {
1398            return Some(value.clone());
1399        }
1400        if let Some(binding) = self
1401            .binding_origins
1402            .iter()
1403            .find_map(|(binding, candidate)| (candidate == origin).then_some(binding))
1404            && let Some(value) = self
1405                .scopes
1406                .first()
1407                .and_then(|environment| environment.get(binding))
1408        {
1409            return Some(value.clone());
1410        }
1411        self.live_value_environments
1412            .borrow()
1413            .get(&origin.0)
1414            .and_then(|environment| environment.get(&origin.1))
1415            .cloned()
1416    }
1417
1418    fn module_binding(&self, module: &crate::value::NyblModule, name: &str) -> Option<Value> {
1419        // Establish export membership before consulting the defining module's
1420        // full live environment, which also contains private bindings.
1421        let exported = module.__binding(name)?;
1422        if module.path == self.active_value_module
1423            && let Some(value) = self
1424                .scopes
1425                .first()
1426                .and_then(|scope| scope.get(name))
1427                .cloned()
1428        {
1429            return Some(value);
1430        }
1431        let (origin_module, origin_binding) = module.__binding_origin(name);
1432        if origin_module == self.active_value_module
1433            && let Some(value) = self
1434                .scopes
1435                .first()
1436                .and_then(|scope| scope.get(&origin_binding))
1437                .cloned()
1438        {
1439            return Some(value);
1440        }
1441        if let Some(active_binding) =
1442            self.binding_origins
1443                .iter()
1444                .find_map(|(active_binding, active_origin)| {
1445                    (active_origin.0 == origin_module && active_origin.1 == origin_binding)
1446                        .then_some(active_binding)
1447                })
1448            && let Some(value) = self
1449                .scopes
1450                .first()
1451                .and_then(|scope| scope.get(active_binding))
1452        {
1453            return Some(value.clone());
1454        }
1455        Some(exported)
1456    }
1457
1458    fn set_var(&mut self, name: &str, value: Value) -> bool {
1459        for scope in self.scopes.iter_mut().rev() {
1460            if scope.contains_key(name) {
1461                scope.insert(name.to_string(), value);
1462                return true;
1463            }
1464        }
1465        if self
1466            .active_lexical_contexts
1467            .last()
1468            .is_some_and(|context| context.module_aliases.contains_key(name))
1469        {
1470            self.scopes
1471                .first_mut()
1472                .expect("function call base scope")
1473                .insert(name.to_string(), value);
1474            return true;
1475        }
1476        false
1477    }
1478
1479    // ─── "Did you mean?" candidate collectors ─────────────────
1480    //
1481    // Every name the user could reasonably have meant, gathered
1482    // into a single list so `nybl::suggest::did_you_mean` picks
1483    // the closest match. Separate methods for the "ident used
1484    // as a value" and "ident called as a function" paths since
1485    // the reachable sets differ (builtins are callable but
1486    // aren't scope values).
1487
1488    /// Names reachable when an identifier is used as a value:
1489    /// any local from the enclosing scopes plus any top-level
1490    /// fn declaration (fns are first-class — `let g = some_fn`
1491    /// works, so they count as value-like).
1492    fn value_candidates_hint(&self, target: &str) -> Option<String> {
1493        let mut candidates: Vec<String> = Vec::new();
1494        for scope in &self.scopes {
1495            for k in scope.keys() {
1496                candidates.push(k.clone());
1497            }
1498        }
1499        for name in self.functions.keys() {
1500            candidates.push(name.clone());
1501        }
1502        crate::suggest::did_you_mean(target, candidates)
1503    }
1504
1505    /// Names reachable in a call position: user fns, core
1506    /// builtins, plus `try_call`. Host builtins stay with the
1507    /// host's own `function_hint()` path — embedders often want
1508    /// to list theirs differently.
1509    fn callable_candidates_hint(&self, target: &str) -> Option<String> {
1510        let mut candidates: Vec<String> = self.functions.keys().cloned().collect();
1511        for builtin in crate::suggest::CORE_CALLABLE_BUILTINS {
1512            candidates.push((*builtin).to_string());
1513        }
1514        crate::suggest::did_you_mean(target, candidates)
1515    }
1516
1517    /// Resolve a named function in the active function's defining module
1518    /// before falling back to caller-visible bindings. Loaded module artifacts
1519    /// are the module-scope environment: aliases therefore keep sibling calls
1520    /// working without exposing those siblings as bare names to the importer.
1521    fn lookup_function(&self, name: &str) -> Option<FunctionDefinition> {
1522        if let Some(module_path) = self.function_modules.last()
1523            && module_path != crate::value::ROOT_MODULE_PATH
1524        {
1525            let cache = self.imports.borrow();
1526            if let Some(ImportSlot::Loaded(bindings)) = cache.get(module_path)
1527                && let Some((_, function)) = bindings
1528                    .fn_decls
1529                    .iter()
1530                    .find(|(candidate, _)| candidate == name)
1531            {
1532                return Some(Rc::clone(function));
1533            }
1534        }
1535        if let Some(function) = self.imported_function(name) {
1536            return Some(Rc::clone(function));
1537        }
1538        let defining_module = self.function_modules.last().map(String::as_str);
1539        if let Some(module_path) = defining_module
1540            && let Some(function) = self
1541                .functions
1542                .get(name)
1543                .filter(|function| function.module_path.as_deref() == Some(module_path))
1544        {
1545            return Some(Rc::clone(function));
1546        }
1547        if defining_module.is_none_or(|path| path == self.current_module) {
1548            self.functions.get(name).map(Rc::clone)
1549        } else {
1550            None
1551        }
1552    }
1553
1554    // ─── Statements ────────────────────────────────────────────────
1555
1556    fn exec_block(&mut self, stmts: &[Stmt]) -> Result<Signal, NyblError> {
1557        for stmt in stmts {
1558            let signal = self.exec_stmt(stmt)?;
1559            match signal {
1560                Signal::None => {}
1561                other => return Ok(other),
1562            }
1563        }
1564        Ok(Signal::None)
1565    }
1566
1567    fn exec_stmt(&mut self, stmt: &Stmt) -> Result<Signal, NyblError> {
1568        self.tick(stmt.line)?;
1569
1570        match &stmt.kind {
1571            StmtKind::Let {
1572                name,
1573                value,
1574                is_const: _,
1575            } => {
1576                let val = self.eval_expr(value)?;
1577                let module = match &val {
1578                    Value::Module(module) => Some(Rc::clone(module)),
1579                    _ => None,
1580                };
1581                if self.is_module_top_scope()
1582                    && let Some(origin) = self.binding_origins.get(name).cloned()
1583                    && (origin.0 != self.current_module || origin.1 != name.as_str())
1584                    && let Some(previous) =
1585                        self.scopes.last_mut().and_then(|scope| scope.remove(name))
1586                {
1587                    self.live_value_environments
1588                        .borrow_mut()
1589                        .entry(origin.0)
1590                        .or_default()
1591                        .insert(origin.1, previous);
1592                }
1593                self.define(name.clone(), val);
1594                if let Some(imports) = self.import_scopes.last_mut() {
1595                    imports.forget(name);
1596                }
1597                if self.is_module_top_scope() {
1598                    self.binding_origins
1599                        .insert(name.clone(), (self.current_module.clone(), name.clone()));
1600                }
1601                let published_module = module.as_ref().map(Rc::clone);
1602                let aliases = self.module_aliases.last_mut().expect("module alias scope");
1603                if let Some(module) = module {
1604                    aliases.insert(name.clone(), module);
1605                } else {
1606                    aliases.remove(name);
1607                }
1608                if self.is_module_top_scope() {
1609                    self.publish_root_module_alias(name.clone(), published_module);
1610                }
1611                Ok(Signal::None)
1612            }
1613
1614            StmtKind::Assign { target, op, value } => {
1615                let new_val = self.eval_expr(value)?;
1616                self.exec_assign(target, op, new_val, stmt.line)?;
1617                Ok(Signal::None)
1618            }
1619
1620            StmtKind::If {
1621                condition,
1622                body,
1623                else_ifs,
1624                else_body,
1625            } => {
1626                if self.eval_expr(condition)?.is_truthy() {
1627                    self.push_scope();
1628                    let sig = self.exec_block(body)?;
1629                    self.pop_scope();
1630                    return Ok(sig);
1631                }
1632                for (elif_cond, elif_body) in else_ifs {
1633                    if self.eval_expr(elif_cond)?.is_truthy() {
1634                        self.push_scope();
1635                        let sig = self.exec_block(elif_body)?;
1636                        self.pop_scope();
1637                        return Ok(sig);
1638                    }
1639                }
1640                if let Some(else_body) = else_body {
1641                    self.push_scope();
1642                    let sig = self.exec_block(else_body)?;
1643                    self.pop_scope();
1644                    return Ok(sig);
1645                }
1646                Ok(Signal::None)
1647            }
1648
1649            StmtKind::While { condition, body } => {
1650                // The loop-line entry must come off on every exit —
1651                // including caught errors — so the body runs inside
1652                // a closure and the pop is unconditional.
1653                self.loop_lines.push(stmt.line);
1654                let result = (|| {
1655                    loop {
1656                        self.tick(stmt.line)?;
1657                        if !self.eval_expr(condition)?.is_truthy() {
1658                            break;
1659                        }
1660                        self.push_scope();
1661                        let sig = self.exec_block(body)?;
1662                        self.pop_scope();
1663                        match sig {
1664                            Signal::Break => break,
1665                            Signal::Continue => continue,
1666                            Signal::Return(v) => return Ok(Signal::Return(v)),
1667                            Signal::None => {}
1668                        }
1669                    }
1670                    Ok(Signal::None)
1671                })();
1672                self.loop_lines.pop();
1673                result
1674            }
1675
1676            StmtKind::Repeat { count, body } => {
1677                let n = match self.eval_expr(count)? {
1678                    Value::Int(n) => n,
1679                    Value::Number(n) => n as i64,
1680                    other => {
1681                        return Err(error(
1682                            stmt.line,
1683                            format!("repeat needs a number, but got {}", other.type_name()),
1684                        ));
1685                    }
1686                };
1687                // Count evaluation stays outside the loop context —
1688                // it runs once, like the VM's `MakeRepeatCount`.
1689                self.loop_lines.push(stmt.line);
1690                let result = (|| {
1691                    for _ in 0..n.max(0) {
1692                        self.tick(stmt.line)?;
1693                        self.push_scope();
1694                        let sig = self.exec_block(body)?;
1695                        self.pop_scope();
1696                        match sig {
1697                            Signal::Break => break,
1698                            Signal::Continue => continue,
1699                            Signal::Return(v) => return Ok(Signal::Return(v)),
1700                            Signal::None => {}
1701                        }
1702                    }
1703                    Ok(Signal::None)
1704                })();
1705                self.loop_lines.pop();
1706                result
1707            }
1708
1709            StmtKind::ForIn {
1710                var,
1711                iterable,
1712                body,
1713            } => {
1714                let val = self.eval_expr(iterable)?;
1715                // Fast path for the three built-in iterables:
1716                // materialise up-front and loop over the Vec
1717                // directly, skipping the method-dispatch cost of
1718                // the iterator protocol. Semantically identical
1719                // to `for x in v.iter()` for these types.
1720                if matches!(&val, Value::Array(_) | Value::Str(_) | Value::Dict(_)) {
1721                    let mut val = val;
1722                    let items: Vec<Value> = match &mut val {
1723                        Value::Array(arr) => arr.__take_in(&self.memory),
1724                        Value::Str(s) => s
1725                            .chars()
1726                            .map(|c| Value::__new_str_in(c.to_string(), &self.memory))
1727                            .collect(),
1728                        Value::Dict(d) => d
1729                            .iter()
1730                            .map(|(k, _)| Value::__new_str_in(k.clone(), &self.memory))
1731                            .collect(),
1732                        _ => unreachable!(),
1733                    };
1734                    self.loop_lines.push(stmt.line);
1735                    let result = (|| {
1736                        for item in items {
1737                            self.tick(stmt.line)?;
1738                            self.push_scope();
1739                            self.define(var.clone(), item);
1740                            let sig = self.exec_block(body)?;
1741                            self.pop_scope();
1742                            match sig {
1743                                Signal::Break => break,
1744                                Signal::Continue => continue,
1745                                Signal::Return(v) => return Ok(Signal::Return(v)),
1746                                Signal::None => {}
1747                            }
1748                        }
1749                        Ok(Signal::None)
1750                    })();
1751                    self.loop_lines.pop();
1752                    return result;
1753                }
1754                // Protocol path: anything else must either be an
1755                // iterator already (Value::Iter, or a user value
1756                // with a `.next()` method that returns
1757                // `Iter::Next/Done`) or an iterable — a value
1758                // whose `.iter()` method returns an iterator.
1759                // Primitives and callables that don't fit get a
1760                // clean "can't iterate over X" error instead of
1761                // a raw "no such method" surface from the
1762                // dispatcher below.
1763                let iterator = match &val {
1764                    Value::Iter(_) | Value::Struct(_) | Value::EnumVariant(_) => {
1765                        // Ask the value for an iterator. User
1766                        // structs typically implement `iter` to
1767                        // return either a built-in iterator or
1768                        // themselves.
1769                        self.call_method_full(&val, "iter", Vec::new(), stmt.line)?
1770                    }
1771                    other => {
1772                        return Err(error(
1773                            stmt.line,
1774                            crate::error_messages::cant_iterate_over(other.type_name()),
1775                        ));
1776                    }
1777                };
1778                // Iterator acquisition above stays outside the loop
1779                // context — it runs once, like the VM's `MakeIter`.
1780                self.loop_lines.push(stmt.line);
1781                let result = (|| {
1782                    loop {
1783                        self.tick(stmt.line)?;
1784                        let next_val =
1785                            self.call_method_full(&iterator, "next", Vec::new(), stmt.line)?;
1786                        let item = match unwrap_iter_result(&next_val) {
1787                            Some(IterStep::Next(v)) => v,
1788                            Some(IterStep::Done) => break,
1789                            None => {
1790                                return Err(error(
1791                                    stmt.line,
1792                                    format!(
1793                                        "`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
1794                                        next_val.inspect()
1795                                    ),
1796                                ));
1797                            }
1798                        };
1799                        self.push_scope();
1800                        self.define(var.clone(), item);
1801                        let sig = self.exec_block(body)?;
1802                        self.pop_scope();
1803                        match sig {
1804                            Signal::Break => break,
1805                            Signal::Continue => continue,
1806                            Signal::Return(v) => return Ok(Signal::Return(v)),
1807                            Signal::None => {}
1808                        }
1809                    }
1810                    Ok(Signal::None)
1811                })();
1812                self.loop_lines.pop();
1813                result
1814            }
1815
1816            StmtKind::FnDecl {
1817                name,
1818                params,
1819                body,
1820                visibility,
1821            } => {
1822                // A flat `use` already bound this name in this scope; a
1823                // declaration silently replacing the import (or being
1824                // shadowed by it) would lose one of the two definitions.
1825                if let Some(imported) = self
1826                    .import_scopes
1827                    .last()
1828                    .and_then(|scope| scope.names.get(name))
1829                {
1830                    return Err(crate::error_messages::function_replaces_import_error(
1831                        name,
1832                        &imported.path,
1833                        stmt.line,
1834                    ));
1835                }
1836                if let Some(imports) = self.import_scopes.last_mut() {
1837                    imports.functions.insert(name.clone());
1838                }
1839                let is_direct_root = self.is_module_top_scope()
1840                    && self.current_module == crate::value::ROOT_MODULE_PATH;
1841                let module_path = self
1842                    .function_modules
1843                    .last()
1844                    .cloned()
1845                    .unwrap_or_else(|| self.current_module.clone());
1846                let definition = function_definition(
1847                    params,
1848                    body,
1849                    Some(name.clone()),
1850                    module_path,
1851                    self.function_origin.clone(),
1852                    stmt.line,
1853                )?;
1854                self.functions.insert(name.clone(), Rc::clone(&definition));
1855                if is_direct_root {
1856                    self.abi_declarations
1857                        .retain(|(existing, _, _)| existing != name);
1858                    self.abi_declarations
1859                        .push((name.clone(), *visibility, definition));
1860                }
1861                Ok(Signal::None)
1862            }
1863
1864            StmtKind::MethodDecl {
1865                type_name,
1866                method_name,
1867                params,
1868                body,
1869            } => {
1870                // Methods belong to a *specific* type identity —
1871                // `fn Color.area(self)` inside module `paint`
1872                // registers under `(paint, Color)` and doesn't
1873                // leak to `other.Color`. If the named type isn't
1874                // declared in this module, that's an error at
1875                // parse/emit consistency — fall back to the
1876                // current module as the owner.
1877                let type_key = (self.current_module.clone(), type_name.clone());
1878                let definition = function_definition(
1879                    params,
1880                    body,
1881                    None,
1882                    self.current_module.clone(),
1883                    self.function_origin.clone(),
1884                    stmt.line,
1885                )?;
1886                self.methods
1887                    .entry(type_key)
1888                    .or_default()
1889                    .insert(method_name.clone(), definition);
1890                Ok(Signal::None)
1891            }
1892
1893            StmtKind::Return { value } => {
1894                let val = match value {
1895                    Some(expr) => self.eval_expr(expr)?,
1896                    None => Value::None,
1897                };
1898                Ok(Signal::Return(val))
1899            }
1900
1901            StmtKind::Break => Ok(Signal::Break),
1902            StmtKind::Continue => Ok(Signal::Continue),
1903
1904            StmtKind::Use { path, items, alias } => {
1905                self.exec_import(path, items.as_deref(), alias.as_deref(), stmt.line)?;
1906                Ok(Signal::None)
1907            }
1908
1909            StmtKind::StructDecl { name, fields } => {
1910                // Reject duplicate field names at decl time so
1911                // downstream code doesn't have to re-check. Walker,
1912                // VM, and AOT all assume unique fields per struct.
1913                let mut seen = alloc_import::collections::BTreeSet::new();
1914                for f in fields {
1915                    if !seen.insert(f.clone()) {
1916                        return Err(error(
1917                            stmt.line,
1918                            format!("Struct `{name}` has duplicate field `{f}`"),
1919                        ));
1920                    }
1921                }
1922                // Type identity is `(current_module, name)` —
1923                // two different modules declaring the same name
1924                // coexist because their keys differ. A redecl
1925                // *in the same module* is a no-op when the shape
1926                // matches (mirrors the same-module idempotency
1927                // rule for re-imports) and a clash otherwise.
1928                let key = (self.current_module.clone(), name.clone());
1929                if let Some(existing) = self.struct_defs.get(&key) {
1930                    if existing == fields {
1931                        self.bind_local_type(name);
1932                        return Ok(Signal::None);
1933                    }
1934                    return Err(error(
1935                        stmt.line,
1936                        format!("Struct `{name}` is already declared"),
1937                    ));
1938                }
1939                self.struct_defs.insert(key, fields.clone());
1940                self.bind_local_type(name);
1941                Ok(Signal::None)
1942            }
1943
1944            StmtKind::EnumDecl { name, variants } => {
1945                let key = (self.current_module.clone(), name.clone());
1946                if let Some(existing) = self.enum_defs.get(&key) {
1947                    // Same rule as `StructDecl` above — a
1948                    // same-module same-shape redeclaration is a
1949                    // no-op, anything else is a clash.
1950                    if variants_equivalent(existing, variants) {
1951                        self.bind_local_type(name);
1952                        return Ok(Signal::None);
1953                    }
1954                    return Err(error(
1955                        stmt.line,
1956                        format!("Enum `{name}` is already declared"),
1957                    ));
1958                }
1959                let mut seen_variants = alloc_import::collections::BTreeSet::new();
1960                for v in variants {
1961                    if !seen_variants.insert(v.name.clone()) {
1962                        return Err(error(
1963                            stmt.line,
1964                            format!("Enum `{}` has duplicate variant `{}`", name, v.name),
1965                        ));
1966                    }
1967                    if let VariantKind::Struct(fields) | VariantKind::Tuple(fields) = &v.kind {
1968                        let mut seen_fields = alloc_import::collections::BTreeSet::new();
1969                        for f in fields {
1970                            if !seen_fields.insert(f.clone()) {
1971                                return Err(error(
1972                                    stmt.line,
1973                                    format!(
1974                                        "Enum variant `{}::{}` has duplicate field `{}`",
1975                                        name, v.name, f
1976                                    ),
1977                                ));
1978                            }
1979                        }
1980                    }
1981                }
1982                self.enum_defs.insert(key, variants.clone());
1983                self.bind_local_type(name);
1984                Ok(Signal::None)
1985            }
1986
1987            StmtKind::ExprStmt(expr) => {
1988                self.eval_expr(expr)?;
1989                Ok(Signal::None)
1990            }
1991
1992            // Module export validation and filtering are handled by the
1993            // module surface pass. The declaration itself has no runtime
1994            // side effect.
1995            StmtKind::PublicSurface { .. } => Ok(Signal::None),
1996        }
1997    }
1998
1999    /// Execute a `use` statement.
2000    ///
2001    /// Four shapes are dispatched from the parser:
2002    ///
2003    /// - `use foo`                 — glob: inject all public
2004    ///   (non-`_`-prefixed) exports into the caller's scope.
2005    ///   A name the scope already binds to a different
2006    ///   declaration is an error; one bound to the same
2007    ///   declaration is left as is.
2008    /// - `use foo.{a, b}`          — selective: inject only the
2009    ///   listed names. Missing names raise a clear error. Names
2010    ///   that start with `_` are accepted when listed
2011    ///   explicitly (the selective form is how you opt-in to
2012    ///   private bindings).
2013    /// - `use foo as m`            — aliased: every export
2014    ///   (including `_`-prefixed) hangs off a `Value::Module`
2015    ///   bound as `m`. Access via `m.binding` or
2016    ///   `m.Type { ... }` / `m.Type::Variant(...)`.
2017    /// - `use foo.{a, b} as m`     — selective + aliased: same
2018    ///   filtering, and the resulting module only exposes the
2019    ///   listed names.
2020    ///
2021    /// Struct / enum / method declarations from the imported
2022    /// module still register globally on every form — types
2023    /// are first-come-first-served across the engine. Conflicts
2024    /// there produce the same "clashes with existing" error as
2025    /// before. (Qualified type names that genuinely disambiguate
2026    /// same-named types across modules are a future extension.)
2027    fn exec_import(
2028        &mut self,
2029        path: &str,
2030        items: Option<&[String]>,
2031        alias: Option<&str>,
2032        line: u32,
2033    ) -> Result<(), NyblError> {
2034        let refresh_root_context = self.is_module_top_scope();
2035        // Idempotent at the glob injection site: re-importing a
2036        // module already applied is a no-op. Aliased / selective
2037        // forms don't enter this cache — they always run, because
2038        // the same module imported with different shapes can
2039        // legitimately produce different scope effects.
2040        let is_plain_glob = items.is_none() && alias.is_none();
2041        if is_plain_glob
2042            && self
2043                .import_scopes
2044                .last()
2045                .is_some_and(|imports| imports.paths.contains(path))
2046        {
2047            return Ok(());
2048        }
2049
2050        // A lazily evaluated dependency may import the module currently
2051        // executing this `use`. Park that active environment in the shared
2052        // registry so the nested evaluator moves the one authoritative value
2053        // set instead of consulting cached compatibility snapshots.
2054        let active_module = self.active_value_module.clone();
2055        let active_origins = self.binding_origins.clone();
2056        let active_environment = self
2057            .scopes
2058            .first_mut()
2059            .map(core::mem::take)
2060            .unwrap_or_default();
2061        self.live_binding_origins
2062            .borrow_mut()
2063            .insert(active_module.clone(), active_origins.clone());
2064        put_live_environment(
2065            &self.live_value_environments,
2066            &active_module,
2067            active_environment,
2068            &active_origins,
2069        );
2070        let loaded = self.load_module(path, line);
2071        let restored_environment = take_live_environment(
2072            &self.live_value_environments,
2073            &active_module,
2074            &active_origins,
2075        );
2076        if let Some(scope) = self.scopes.first_mut() {
2077            *scope = restored_environment;
2078        } else {
2079            self.scopes.push(restored_environment);
2080        }
2081        let bindings = loaded?;
2082
2083        // Types always register under their *full identity*
2084        // `(module_path, type_name)`. That means two modules
2085        // declaring `struct Color { ... }` with different fields
2086        // coexist at different registry keys — no clash. Same-
2087        // identity reinsertion is a no-op; same key + different
2088        // shape would mean the same module got loaded twice with
2089        // a different source, which we treat as a hard error.
2090        for (key, fields) in &bindings.struct_defs {
2091            if let Some(existing) = self.struct_defs.get(key) {
2092                if existing == fields {
2093                    continue;
2094                }
2095                return Err(error(
2096                    line,
2097                    format!(
2098                        "Type `{}` from `{}` reloaded with different fields",
2099                        key.1, key.0
2100                    ),
2101                ));
2102            }
2103            self.struct_defs.insert(key.clone(), fields.clone());
2104        }
2105        for (key, variants) in &bindings.enum_defs {
2106            if let Some(existing) = self.enum_defs.get(key) {
2107                if variants_equivalent(existing, variants) {
2108                    continue;
2109                }
2110                return Err(error(
2111                    line,
2112                    format!(
2113                        "Type `{}` from `{}` reloaded with different variants",
2114                        key.1, key.0
2115                    ),
2116                ));
2117            }
2118            self.enum_defs.insert(key.clone(), variants.clone());
2119        }
2120        for (type_key, method_name, fn_def) in &bindings.methods {
2121            let slot = self.methods.entry(type_key.clone()).or_default();
2122            slot.insert(method_name.clone(), fn_def.clone());
2123        }
2124
2125        // Figure out which name-value pairs to surface based on
2126        // the (items, alias) combination. Fn declarations and
2127        // plain `let` bindings are threaded together so the
2128        // caller-visible order matches the module's declaration
2129        // order.
2130        let mut exports: Vec<(String, Value)> =
2131            Vec::with_capacity(bindings.fn_decls.len() + bindings.bindings.len());
2132        let mut fn_entries: BTreeMap<String, FunctionDefinition> = BTreeMap::new();
2133        for (name, fn_def) in &bindings.fn_decls {
2134            if bindings.bindings.iter().any(|(binding, _)| binding == name) {
2135                continue;
2136            }
2137            exports.push((name.clone(), Value::Fn(Rc::clone(fn_def))));
2138            fn_entries.insert(name.clone(), Rc::clone(fn_def));
2139        }
2140        for (name, value) in &bindings.bindings {
2141            exports.push((name.clone(), value.clone()));
2142        }
2143        // Module values and functions live in separate runtime tables, but a
2144        // single `use` projects one logical namespace. Sort the combined
2145        // surface so the first reported clash is the same in all engines.
2146        exports.sort_by(|(left, _), (right, _)| left.cmp(right));
2147
2148        // Selective filter: restrict to the listed names.
2149        // Missing names error loudly — a silent skip would make
2150        // typos hard to spot.
2151        if let Some(list) = items {
2152            let available: alloc_import::collections::BTreeSet<&str> =
2153                exports.iter().map(|(k, _)| k.as_str()).collect();
2154            for wanted in list {
2155                if !available.contains(wanted.as_str())
2156                    && !bindings.type_exports.contains_key(wanted)
2157                {
2158                    return Err(error(
2159                        line,
2160                        format!("`{wanted}` isn't exported from `{path}` (selective import)"),
2161                    ));
2162                }
2163            }
2164            let listed: alloc_import::collections::BTreeSet<String> =
2165                list.iter().cloned().collect();
2166            exports.retain(|(k, _)| listed.contains(k));
2167            fn_entries.retain(|name, _| listed.contains(name));
2168        }
2169
2170        // Figure out which of the module's types the caller
2171        // should see *by bare name*. The selective form picks
2172        // exactly the listed names; the glob form takes
2173        // everything public; the aliased form never binds bare
2174        // names (the alias is the only way in).
2175        let exposed_types: BTreeMap<String, String> = match items {
2176            Some(list) => bindings
2177                .type_exports
2178                .iter()
2179                .filter(|(name, _)| list.iter().any(|item| item == *name))
2180                .map(|(name, origin)| (name.clone(), origin.clone()))
2181                .collect(),
2182            None => bindings
2183                .type_exports
2184                .iter()
2185                .filter(|(name, _)| {
2186                    alias.is_some() || bindings.explicit_surface || !crate::naming::is_private(name)
2187                })
2188                .map(|(name, origin)| (name.clone(), origin.clone()))
2189                .collect(),
2190        };
2191
2192        if let Some(alias_name) = alias {
2193            // Aliased form: build a `Value::Module` and bind it
2194            // under the alias. The module carries its bindings
2195            // (let + fn) and the names of declared types so
2196            // namespaced constructors like `m.Entity { ... }`
2197            // can verify they're reaching for something the
2198            // module actually exports.
2199            if self
2200                .scopes
2201                .last()
2202                .map(|s| s.contains_key(alias_name))
2203                .unwrap_or(false)
2204                || self.functions.contains_key(alias_name)
2205                || self
2206                    .imported_functions
2207                    .last()
2208                    .is_some_and(|functions| functions.contains_key(alias_name))
2209            {
2210                return Err(error(
2211                    line,
2212                    format!("`{alias_name}` is already bound — can't use it as a module alias"),
2213                ));
2214            }
2215            // The callable values retain their defining module, so sibling
2216            // calls resolve through that module's cached bindings. Publishing
2217            // these entries in `self.functions` would make `helper()` visible
2218            // after `use module as alias`, violating the alias-only surface.
2219            let live_bindings = exports
2220                .iter()
2221                .map(|(name, _)| {
2222                    let origin = bindings
2223                        .binding_origins
2224                        .get(name)
2225                        .cloned()
2226                        .unwrap_or_else(|| (path.to_string(), name.clone()));
2227                    (name.clone(), origin)
2228                })
2229                .collect();
2230            let module_rc = crate::value::NyblModule::__try_new_live_with_type_exports(
2231                path.to_string(),
2232                exports,
2233                NyblTypeExports::from_origins(exposed_types),
2234                live_bindings,
2235                Rc::clone(&self.live_value_environments),
2236                line,
2237            )?;
2238            // Bind the alias three ways:
2239            //   1. as a Value::Module in the current value
2240            //      scope (for `m.helper(x)` style calls that
2241            //      happen directly at the callsite);
2242            //   2. in `module_aliases` so it survives the
2243            //      fresh-scope reset at function boundaries and
2244            //      stays reachable for field access inside fns;
2245            //   3. in `type_bindings` so patterns + construction
2246            //      can resolve `m.Type` inside function bodies
2247            //      without needing the Value::Module in value
2248            //      scope.
2249            self.define(alias_name.to_string(), Value::Module(Rc::clone(&module_rc)));
2250            self.module_aliases
2251                .last_mut()
2252                .expect("module alias scope")
2253                .insert(alias_name.to_string(), Rc::clone(&module_rc));
2254            if let Some(scope) = self.type_bindings.last_mut() {
2255                scope.insert(alias_name.to_string(), path.to_string());
2256            }
2257            if refresh_root_context {
2258                self.publish_root_module_alias(alias_name.to_string(), Some(Rc::clone(&module_rc)));
2259                self.publish_root_type_binding(alias_name.to_string(), path.to_string());
2260            }
2261        } else {
2262            // Glob / selective without alias — flat injection.
2263            // Privacy: glob-only drops `_`-prefixed names.
2264            // Selective lets the user reach into private
2265            // bindings explicitly.
2266            let skip_private = items.is_none() && !bindings.explicit_surface;
2267            let module_top_scope = self.is_module_top_scope();
2268            let incoming_origin = |name: &str| {
2269                bindings
2270                    .binding_origins
2271                    .get(name)
2272                    .cloned()
2273                    .unwrap_or_else(|| (path.to_string(), name.to_string()))
2274            };
2275            // A flat import binds every selected name or none. A name this
2276            // scope already binds to the same declaration (a diamond
2277            // re-export, or a selective import followed by a glob) is
2278            // already in place; any other existing binding is a clash.
2279            let mut already_bound = BTreeSet::new();
2280            for (name, _) in &exports {
2281                if skip_private && crate::naming::is_private(name) {
2282                    continue;
2283                }
2284                match self.flat_binding_origin(name, module_top_scope) {
2285                    None => {}
2286                    Some(Some(existing)) if existing == incoming_origin(name) => {
2287                        already_bound.insert(name.clone());
2288                    }
2289                    Some(_) => {
2290                        return Err(crate::error_messages::import_clash_error(name, path, line));
2291                    }
2292                }
2293            }
2294            for (type_name, origin) in &exposed_types {
2295                if let Some(existing) = self
2296                    .type_bindings
2297                    .last()
2298                    .and_then(|scope| scope.get(type_name))
2299                    && existing != origin
2300                {
2301                    return Err(crate::error_messages::import_clash_error(
2302                        type_name, path, line,
2303                    ));
2304                }
2305            }
2306            for (name, mut value) in exports {
2307                if skip_private && crate::naming::is_private(&name) {
2308                    continue;
2309                }
2310                if already_bound.contains(&name) {
2311                    continue;
2312                }
2313                self.import_scopes
2314                    .last_mut()
2315                    .expect("import scope")
2316                    .names
2317                    .insert(
2318                        name.clone(),
2319                        ImportedName {
2320                            origin: incoming_origin(&name),
2321                            path: path.to_string(),
2322                        },
2323                    );
2324                if let Some(fn_def) = fn_entries.remove(&name) {
2325                    self.imported_functions
2326                        .last_mut()
2327                        .expect("imported function scope")
2328                        .insert(name.clone(), Rc::clone(&fn_def));
2329                    if module_top_scope {
2330                        self.publish_root_imported_function(name.clone(), fn_def);
2331                    }
2332                }
2333                let module = bindings.module_exports.get(&name).cloned();
2334                if module_top_scope {
2335                    let origin = bindings
2336                        .binding_origins
2337                        .get(&name)
2338                        .cloned()
2339                        .unwrap_or_else(|| (path.to_string(), name.clone()));
2340                    self.binding_origins.insert(name.clone(), origin.clone());
2341                    if (origin.0 != self.active_value_module || origin.1 != name)
2342                        && let Some(authoritative) = self
2343                            .live_value_environments
2344                            .borrow_mut()
2345                            .get_mut(&origin.0)
2346                            .and_then(|environment| environment.remove(&origin.1))
2347                    {
2348                        value = authoritative;
2349                    }
2350                } else {
2351                    let origin = bindings
2352                        .binding_origins
2353                        .get(&name)
2354                        .cloned()
2355                        .unwrap_or_else(|| (path.to_string(), name.clone()));
2356                    if let Some(current) = self.live_origin_value(&origin) {
2357                        value = current;
2358                    }
2359                }
2360                self.define(name.clone(), value);
2361                if let Some(module) = module {
2362                    self.module_aliases
2363                        .last_mut()
2364                        .expect("module alias scope")
2365                        .insert(name.clone(), Rc::clone(&module));
2366                    if module_top_scope {
2367                        self.publish_root_module_alias(name, Some(module));
2368                    }
2369                }
2370            }
2371            // Bind the bare type names in the current scope's
2372            // type_bindings so subsequent `Color::Red` /
2373            // `Color { ... }` resolves to the module the name
2374            // came from. Clashing names were rejected above, so a
2375            // bound name here already has this origin. Types without
2376            // an explicit bare binding remain reachable through the
2377            // alias form only.
2378            for (type_name, origin) in &exposed_types {
2379                let already_bound = self
2380                    .type_bindings
2381                    .last()
2382                    .map(|s| s.contains_key(type_name))
2383                    .unwrap_or(false);
2384                if already_bound {
2385                    continue;
2386                }
2387                if let Some(scope) = self.type_bindings.last_mut() {
2388                    scope.insert(type_name.clone(), origin.clone());
2389                }
2390                if module_top_scope {
2391                    self.type_exports
2392                        .entry(type_name.clone())
2393                        .or_insert_with(|| origin.clone());
2394                    self.publish_root_type_binding(type_name.clone(), origin.clone());
2395                }
2396            }
2397        }
2398
2399        if is_plain_glob {
2400            self.import_scopes
2401                .last_mut()
2402                .expect("import scope")
2403                .paths
2404                .insert(path.to_string());
2405        }
2406        Ok(())
2407    }
2408
2409    /// Resolve and evaluate a module, caching the result. Returns
2410    /// the module's exported bindings.
2411    fn load_module(&mut self, path: &str, line: u32) -> Result<ModuleBindings, NyblError> {
2412        // Fast path: already loaded.
2413        {
2414            let cache = self.imports.borrow();
2415            if let Some(ImportSlot::Loaded(bindings)) = cache.get(path) {
2416                return Ok((**bindings).clone());
2417            }
2418            if let Some(ImportSlot::Loading) = cache.get(path) {
2419                return Err(error(
2420                    line,
2421                    format!("Circular import: module `{path}` is still loading"),
2422                ));
2423            }
2424        }
2425
2426        // A load runs the module's top level as one more active frame.
2427        if self.active_call_depth() >= MAX_CALL_DEPTH {
2428            return Err(crate::error_messages::call_depth_error(line));
2429        }
2430
2431        // Ask the host for source.
2432        let resolved = self.host.resolve_module(path);
2433        let source = match resolved {
2434            Some(Ok(s)) => s,
2435            Some(Err(e)) => return Err(e),
2436            None => {
2437                return Err(error(line, format!("Module `{path}` not found")));
2438            }
2439        };
2440
2441        // Loading costs one step per token, charged to the importer before
2442        // the module is parsed; a failed load is not refunded.
2443        let tokens = crate::lexer::lex(&source)
2444            .map_err(|error| error.with_module_source(path, source.as_str()))?;
2445        self.charge_steps(crate::lexer::module_load_steps(&tokens), line)?;
2446        let stmts = crate::parser::parse(tokens)
2447            .and_then(|stmts| {
2448                // Modules load lazily at their `use` site, so this is the
2449                // earliest point their source is visible — apply the same
2450                // disabled-builtin gate the root program got, before any of
2451                // the module's statements run.
2452                crate::check::enforce_disabled_builtins(&stmts, &self.limits.disabled_builtins)?;
2453                Ok(stmts)
2454            })
2455            .map_err(|error| error.with_module_source(path, source.as_str()))?;
2456        let nesting = crate::ast_depth::body_depth(&stmts);
2457        self.enter_nesting(nesting, line)?;
2458
2459        // Mark in-progress before we start evaluating so a
2460        // circular import surfaces as a clean error.
2461        self.imports
2462            .borrow_mut()
2463            .insert(path.to_string(), ImportSlot::Loading);
2464
2465        let result = self
2466            .evaluate_module(path, &stmts)
2467            .map_err(|error| error.with_module_source(path, source.as_str()));
2468        self.leave_nesting(nesting);
2469
2470        match result {
2471            Ok(bindings) => {
2472                self.imports.borrow_mut().insert(
2473                    path.to_string(),
2474                    ImportSlot::Loaded(Box::new(bindings.clone())),
2475                );
2476                Ok(bindings)
2477            }
2478            Err(e) => {
2479                // Drop the Loading marker so a subsequent, non-
2480                // broken context could retry.
2481                self.imports.borrow_mut().remove(path);
2482                Err(e)
2483            }
2484        }
2485    }
2486
2487    /// Walk a parsed module in a fresh scope, returning its top-level
2488    /// bindings as a `ModuleBindings`. Reuses the parent evaluator's host,
2489    /// limits, and import cache, and shares its step budget, call depth
2490    /// (the load itself is one frame), and nesting budget.
2491    /// `module_path` is the dot-joined name the importer used —
2492    /// the sub-evaluator tags its own declared types with this
2493    /// path so runtime values keep a stable identity across the
2494    /// import boundary.
2495    fn evaluate_module(
2496        &mut self,
2497        module_path: &str,
2498        stmts: &[Stmt],
2499    ) -> Result<ModuleBindings, NyblError> {
2500        let public_surface: Option<BTreeSet<String>> = {
2501            let mut names = BTreeSet::new();
2502            let mut explicit = false;
2503            for stmt in stmts {
2504                if let StmtKind::PublicSurface { names: listed } = &stmt.kind {
2505                    explicit = true;
2506                    names.extend(listed.iter().cloned());
2507                }
2508            }
2509            explicit.then_some(names)
2510        };
2511        let imports = Rc::clone(&self.imports);
2512        let live_value_environments = Rc::clone(&self.live_value_environments);
2513        let live_binding_origins = Rc::clone(&self.live_binding_origins);
2514        let limits = self.limits.clone();
2515        let mut sub = Evaluator::new_for_module(
2516            self.host,
2517            limits,
2518            imports,
2519            Rc::clone(&live_value_environments),
2520            Rc::clone(&live_binding_origins),
2521            self.function_origin.clone(),
2522            module_path.to_string(),
2523            self.memory.clone(),
2524        );
2525        sub.steps = self.steps;
2526        sub.rand_state = self.rand_state;
2527        sub.call_depth_base = self.call_depth_base + self.call_depth + 1;
2528        sub.nesting_used = self.nesting_used;
2529        // Run the module body to top — errors propagate as-is.
2530        let module_result = sub.exec_block(stmts);
2531        self.steps = sub.steps;
2532        self.rand_state = sub.rand_state;
2533        let module_signal = match module_result {
2534            Ok(signal) => signal,
2535            Err(module_error) => {
2536                restore_failed_module_environment(
2537                    &live_value_environments,
2538                    &live_binding_origins,
2539                    module_path,
2540                    &mut sub.scopes,
2541                    &sub.binding_origins,
2542                );
2543                return Err(module_error);
2544            }
2545        };
2546        match module_signal {
2547            Signal::Return(_) | Signal::None => {}
2548            Signal::Break => {
2549                restore_failed_module_environment(
2550                    &live_value_environments,
2551                    &live_binding_origins,
2552                    module_path,
2553                    &mut sub.scopes,
2554                    &sub.binding_origins,
2555                );
2556                return Err(error(0, "break used outside of a loop"));
2557            }
2558            Signal::Continue => {
2559                restore_failed_module_environment(
2560                    &live_value_environments,
2561                    &live_binding_origins,
2562                    module_path,
2563                    &mut sub.scopes,
2564                    &sub.binding_origins,
2565                );
2566                return Err(error(0, "continue used outside of a loop"));
2567            }
2568        }
2569        // Collect top-level `let` bindings from the module's
2570        // one remaining scope. Fns are handled separately so
2571        // the importer can register them in `self.functions`
2572        // as well as in the scope (see `exec_import`).
2573        let top_scope = sub
2574            .scopes
2575            .first_mut()
2576            .map(core::mem::take)
2577            .unwrap_or_default();
2578        let mut bindings = match snapshot_module_bindings(
2579            &top_scope,
2580            &sub.binding_origins,
2581            module_path,
2582            &self.imports,
2583            0,
2584        ) {
2585            Ok(bindings) => bindings,
2586            Err(snapshot_error) => {
2587                put_live_environment(
2588                    &self.live_value_environments,
2589                    module_path,
2590                    top_scope,
2591                    &sub.binding_origins,
2592                );
2593                self.live_value_environments
2594                    .borrow_mut()
2595                    .remove(module_path);
2596                self.live_binding_origins.borrow_mut().remove(module_path);
2597                return Err(snapshot_error);
2598            }
2599        };
2600        let mut binding_origins = sub.binding_origins;
2601        put_live_environment(
2602            &self.live_value_environments,
2603            module_path,
2604            top_scope,
2605            &binding_origins,
2606        );
2607        self.live_binding_origins
2608            .borrow_mut()
2609            .insert(module_path.to_string(), binding_origins.clone());
2610        let mut fn_decls: Vec<(String, FunctionDefinition)> = sub.functions.into_iter().collect();
2611        // Type decls and methods transfer with their full
2612        // identity. Engine builtins (`<builtin>` module path)
2613        // are seeded into every evaluator anyway, so we filter
2614        // those out here to avoid duplicating them in the
2615        // importer's merge step.
2616        let builtin_mp = crate::value::BUILTIN_MODULE_PATH;
2617        let struct_defs: Vec<((String, String), Vec<String>)> = sub
2618            .struct_defs
2619            .into_iter()
2620            .filter(|((mp, _), _)| mp != builtin_mp)
2621            .collect();
2622        let enum_defs: Vec<((String, String), Vec<crate::parser::VariantDecl>)> = sub
2623            .enum_defs
2624            .into_iter()
2625            .filter(|((mp, _), _)| mp != builtin_mp)
2626            .collect();
2627        let mut methods: Vec<((String, String), String, FunctionDefinition)> = Vec::new();
2628        for (type_key, by_method) in sub.methods {
2629            for (method_name, fn_def) in by_method {
2630                methods.push((type_key.clone(), method_name, fn_def));
2631            }
2632        }
2633        let mut type_exports = sub.type_exports;
2634        let all_module_exports: BTreeMap<String, Rc<crate::value::NyblModule>> = bindings
2635            .iter()
2636            .filter_map(|(name, value)| match value {
2637                Value::Module(module) => Some((name.clone(), Rc::clone(module))),
2638                _ => None,
2639            })
2640            .collect();
2641        let mut lexical_context = Rc::try_unwrap(core::mem::take(&mut sub.root_lexical_context))
2642            .unwrap_or_else(|context| (*context).clone());
2643        // Only exported module values are valid protected aliases after the
2644        // loading evaluator is gone. Type and function maps already reflect
2645        // every reached top-level publication incrementally.
2646        lexical_context.module_aliases = Rc::new(all_module_exports);
2647        let lexical_context = Rc::new(lexical_context);
2648        let explicit_surface = public_surface.is_some();
2649        if let Some(names) = public_surface {
2650            bindings.retain(|(name, _)| names.contains(name));
2651            binding_origins.retain(|name, _| names.contains(name));
2652            fn_decls.retain(|(name, _)| names.contains(name));
2653            type_exports.retain(|name, _| names.contains(name));
2654        }
2655        let module_exports: BTreeMap<String, Rc<crate::value::NyblModule>> = bindings
2656            .iter()
2657            .filter_map(|(name, value)| match value {
2658                Value::Module(module) => Some((name.clone(), Rc::clone(module))),
2659                _ => None,
2660            })
2661            .collect();
2662        Ok(ModuleBindings {
2663            explicit_surface,
2664            bindings,
2665            binding_origins,
2666            fn_decls,
2667            struct_defs,
2668            enum_defs,
2669            methods,
2670            type_exports,
2671            module_exports,
2672            lexical_context,
2673        })
2674    }
2675
2676    /// Validate `ns.Type` — the caller wrote `ns.Type { ... }`
2677    /// or `ns.Type::Variant(...)`. `ns` must be a
2678    /// `Value::Module` in scope, and `Type` must appear in that
2679    /// module's exported type map. Construction and patterns use
2680    /// [`Self::resolve_type_ref`] to recover the declaration origin.
2681    fn validate_namespaced_type(
2682        &self,
2683        ns: &str,
2684        type_name: &str,
2685        line: u32,
2686    ) -> Result<(), NyblError> {
2687        // Prefer the local value scope so a shadowing binding
2688        // (`let p = 3` after `use paint as p`) is caught — but
2689        // fall back to the evaluator-level alias map so
2690        // namespaced references inside function bodies still
2691        // resolve.
2692        if let Some(v) = self.get_var(ns) {
2693            let module = match v {
2694                Value::Module(m) => m,
2695                _ => {
2696                    return Err(error(
2697                        line,
2698                        format!(
2699                            "`{}` is a {}, not a module alias — can't reach `{}` through it",
2700                            ns,
2701                            v.type_name(),
2702                            type_name
2703                        ),
2704                    ));
2705                }
2706            };
2707            if !module.has_type(type_name) {
2708                return Err(error(
2709                    line,
2710                    format!(
2711                        "`{}` isn't a type exported from `{}`",
2712                        type_name, module.path
2713                    ),
2714                ));
2715            }
2716            return Ok(());
2717        }
2718        if let Some(module) = self.module_alias(ns) {
2719            if !module.has_type(type_name) {
2720                return Err(error(
2721                    line,
2722                    format!(
2723                        "`{}` isn't a type exported from `{}`",
2724                        type_name, module.path
2725                    ),
2726                ));
2727            }
2728            return Ok(());
2729        }
2730        Err(error(line, format!("`{ns}` isn't a module alias in scope")))
2731    }
2732
2733    fn eval_enum_construct(
2734        &mut self,
2735        namespace: Option<&str>,
2736        type_name: &str,
2737        variant: &str,
2738        payload: &VariantPayload,
2739        line: u32,
2740    ) -> Result<Value, NyblError> {
2741        // Resolve the type reference to its full
2742        // `(module_path, type_name)` identity before validating
2743        // the variant shape. `namespace` means the source wrote
2744        // `ns.Type::Variant(...)`; bare means we look the name up
2745        // in the current scope's type bindings.
2746        let module_path = match namespace {
2747            Some(ns) => {
2748                self.validate_namespaced_type(ns, type_name, line)?;
2749                // validate_namespaced_type guaranteed the alias
2750                // is a Module and the type is in its exports —
2751                // pick up the module path for the full identity.
2752                self.resolve_type_ref(Some(ns), type_name)
2753                    .unwrap_or_else(|| self.current_module.clone())
2754            }
2755            None => self
2756                .resolve_type_ref(None, type_name)
2757                .ok_or_else(|| error(line, crate::error_messages::enum_not_declared(type_name)))?,
2758        };
2759        let key = (module_path.clone(), type_name.to_string());
2760        let variants = self
2761            .enum_defs
2762            .get(&key)
2763            .ok_or_else(|| error(line, crate::error_messages::enum_not_declared(type_name)))?
2764            .clone();
2765        let decl = variants
2766            .iter()
2767            .find(|v| v.name == variant)
2768            .ok_or_else(|| {
2769                let msg = crate::error_messages::enum_has_no_variant(type_name, variant);
2770                let names = variants.iter().map(|v| v.name.as_str());
2771                match crate::suggest::did_you_mean(variant, names) {
2772                    Some(hint) => error_with_hint(line, msg, hint),
2773                    None => error(line, msg),
2774                }
2775            })?
2776            .clone();
2777
2778        match (&decl.kind, payload) {
2779            (VariantKind::Unit, VariantPayload::Unit) => Ok(Value::__new_enum_unit_in(
2780                module_path,
2781                type_name.to_string(),
2782                variant.to_string(),
2783                &self.memory,
2784            )),
2785            (VariantKind::Tuple(fields), VariantPayload::Tuple(args)) => {
2786                if args.len() != fields.len() {
2787                    return Err(error(
2788                        line,
2789                        format!(
2790                            "`{}::{}` expects {} argument{}, but got {}",
2791                            type_name,
2792                            variant,
2793                            fields.len(),
2794                            if fields.len() == 1 { "" } else { "s" },
2795                            args.len()
2796                        ),
2797                    ));
2798                }
2799                let mut items = Vec::with_capacity(args.len());
2800                for arg in args {
2801                    items.push(self.eval_expr(arg)?);
2802                }
2803                Value::__try_new_enum_tuple_in(
2804                    module_path,
2805                    type_name.to_string(),
2806                    variant.to_string(),
2807                    items,
2808                    line,
2809                    &self.memory,
2810                )
2811            }
2812            (VariantKind::Struct(decl_fields), VariantPayload::Struct(provided)) => {
2813                let mut seen = alloc_import::collections::BTreeSet::new();
2814                for (fname, _) in provided {
2815                    if !seen.insert(fname.clone()) {
2816                        return Err(error(
2817                            line,
2818                            format!("Field `{fname}` specified twice in `{type_name}::{variant}`"),
2819                        ));
2820                    }
2821                    if !decl_fields.iter().any(|d| d == fname) {
2822                        return Err(error(
2823                            line,
2824                            crate::error_messages::variant_has_no_field(type_name, variant, fname),
2825                        ));
2826                    }
2827                }
2828                for decl_field in decl_fields {
2829                    if !seen.contains(decl_field) {
2830                        return Err(error(
2831                            line,
2832                            format!(
2833                                "Missing field `{decl_field}` in `{type_name}::{variant}` construction"
2834                            ),
2835                        ));
2836                    }
2837                }
2838                let mut provided_map: BTreeMap<String, Value> = BTreeMap::new();
2839                for (fname, fexpr) in provided {
2840                    provided_map.insert(fname.clone(), self.eval_expr(fexpr)?);
2841                }
2842                let mut values: Vec<(String, Value)> = Vec::with_capacity(decl_fields.len());
2843                for decl_field in decl_fields {
2844                    values.push((
2845                        decl_field.clone(),
2846                        provided_map
2847                            .remove(decl_field)
2848                            .expect("variant shape validated before payload evaluation"),
2849                    ));
2850                }
2851                Value::__try_new_enum_struct_in(
2852                    module_path,
2853                    type_name.to_string(),
2854                    variant.to_string(),
2855                    values,
2856                    line,
2857                    &self.memory,
2858                )
2859            }
2860            (VariantKind::Unit, _) => Err(error(
2861                line,
2862                format!("Variant `{type_name}::{variant}` takes no payload"),
2863            )),
2864            (VariantKind::Tuple(_), _) => Err(error(
2865                line,
2866                format!("Variant `{type_name}::{variant}` expects positional arguments `(…)`"),
2867            )),
2868            (VariantKind::Struct(_), _) => Err(error(
2869                line,
2870                format!("Variant `{type_name}::{variant}` expects named fields `{{ … }}`"),
2871            )),
2872        }
2873    }
2874
2875    fn exec_assign(
2876        &mut self,
2877        target: &AssignTarget,
2878        op: &AssignOp,
2879        new_val: Value,
2880        line: u32,
2881    ) -> Result<(), NyblError> {
2882        match target {
2883            AssignTarget::Variable(name) => {
2884                let final_val = match op {
2885                    AssignOp::Eq => new_val,
2886                    _ => {
2887                        let current = self.get_var_value(name).ok_or_else(|| {
2888                            error(line, crate::error_messages::variable_not_found(name))
2889                        })?;
2890                        self.apply_compound_op(&current, op, &new_val, line)?
2891                    }
2892                };
2893                if !self.set_var(name, final_val) {
2894                    return Err(error_with_hint(
2895                        line,
2896                        format!("Variable `{name}` doesn't exist yet"),
2897                        format!("Use `let` to create a new variable: let {name} = ..."),
2898                    ));
2899                }
2900                if self.is_module_top_scope() {
2901                    let module = match self.get_var(name) {
2902                        Some(Value::Module(module)) => Some(Rc::clone(module)),
2903                        _ => None,
2904                    };
2905                    let published_module = module.as_ref().map(Rc::clone);
2906                    let aliases = self.module_aliases.last_mut().expect("module alias scope");
2907                    if let Some(module) = module {
2908                        aliases.insert(name.clone(), module);
2909                    } else {
2910                        aliases.remove(name);
2911                    }
2912                    self.publish_root_module_alias(name.clone(), published_module);
2913                }
2914                Ok(())
2915            }
2916            AssignTarget::Index { object, index } => {
2917                let mut projections = Vec::new();
2918                let root =
2919                    Self::decompose_place_expr(object, &mut projections).ok_or_else(|| {
2920                        error(
2921                            line,
2922                            "Can only assign through a mutable place rooted in a variable",
2923                        )
2924                    })?;
2925                projections.push(PlaceProjectionExpr::Index(index.clone()));
2926                let plan = self.assignment_place_parts(root, projections, line)?;
2927                let place = self.resolve_place(plan, 1, line)?;
2928                let val_to_set = match op {
2929                    AssignOp::Eq => new_val,
2930                    _ => {
2931                        let current =
2932                            self.place_value_from(&place.root, &place.projections, line)?;
2933                        self.apply_compound_op(&current, op, &new_val, line)?
2934                    }
2935                };
2936                self.commit_ref_places(&[place], vec![val_to_set], line)
2937            }
2938            AssignTarget::Field { object, field } => {
2939                let mut projections = Vec::new();
2940                let root =
2941                    Self::decompose_place_expr(object, &mut projections).ok_or_else(|| {
2942                        error(
2943                            line,
2944                            "Can only assign through a mutable place rooted in a variable",
2945                        )
2946                    })?;
2947                projections.push(PlaceProjectionExpr::Field(field.clone()));
2948                let plan = self.assignment_place_parts(root, projections, line)?;
2949                let place = self.resolve_place(plan, 1, line)?;
2950                let val_to_set = match op {
2951                    AssignOp::Eq => new_val,
2952                    _ => {
2953                        let current =
2954                            self.place_value_from(&place.root, &place.projections, line)?;
2955                        self.apply_compound_op(&current, op, &new_val, line)?
2956                    }
2957                };
2958                self.commit_ref_places(&[place], vec![val_to_set], line)
2959            }
2960        }
2961    }
2962
2963    fn apply_compound_op(
2964        &self,
2965        left: &Value,
2966        op: &AssignOp,
2967        right: &Value,
2968        line: u32,
2969    ) -> Result<Value, NyblError> {
2970        match op {
2971            AssignOp::Eq => Ok(right.clone()),
2972            AssignOp::AddEq => ops::add_in(left, right, line, &self.memory),
2973            AssignOp::SubEq => ops::sub_in(left, right, line, &self.memory),
2974            AssignOp::MulEq => ops::mul_in(left, right, line, &self.memory),
2975            AssignOp::DivEq => ops::div_in(left, right, line, &self.memory),
2976            AssignOp::ModEq => ops::rem_in(left, right, line, &self.memory),
2977        }
2978    }
2979
2980    // ─── Expressions ───────────────────────────────────────────────
2981
2982    fn eval_expr(&mut self, expr: &Expr) -> Result<Value, NyblError> {
2983        match &expr.kind {
2984            ExprKind::Int(n) => Ok(Value::Int(*n)),
2985            ExprKind::Number(n) => Ok(Value::Number(*n)),
2986            ExprKind::Str(s) => Ok(Value::__new_str_in(s.clone(), &self.memory)),
2987            ExprKind::Bool(b) => Ok(Value::Bool(*b)),
2988            ExprKind::None => Ok(Value::None),
2989
2990            ExprKind::StringInterp(parts) => {
2991                let mut result = String::new();
2992                for part in parts {
2993                    match part {
2994                        StringPart::Literal(s) => result.push_str(s),
2995                        StringPart::Variable(name) => {
2996                            let val = self.get_var_value(name).ok_or_else(|| {
2997                                error_at(
2998                                    expr.line,
2999                                    expr.column,
3000                                    crate::error_messages::variable_not_found(name),
3001                                )
3002                            })?;
3003                            result.push_str(&format!("{val}"));
3004                        }
3005                    }
3006                }
3007                Ok(Value::__new_str_in(result, &self.memory))
3008            }
3009
3010            ExprKind::Ident(name) => {
3011                // Lexical lookup first — matches the intuition that
3012                // `let x = ...` locally shadows everything else.
3013                if let Some(v) = self.get_var_value(name) {
3014                    return Ok(v);
3015                }
3016                // Fall back to the canonical callable created when the named
3017                // declaration was reached. First-class access only clones the
3018                // `Rc`; it never clones or reconstructs the function AST.
3019                if let Some(f) = self.lookup_function(name) {
3020                    return Ok(Value::Fn(f));
3021                }
3022                // Typo? Offer a "did you mean" hint if something
3023                // close is visible in the current scope / fn
3024                // registry. Falls back to the original "did you
3025                // forget `let`" when no candidate is similar
3026                // enough.
3027                let hint = self
3028                    .value_candidates_hint(name)
3029                    .unwrap_or_else(|| "Did you forget to create it with `let`?".to_string());
3030                Err(error_with_hint_at(
3031                    expr.line,
3032                    expr.column,
3033                    crate::error_messages::variable_not_found(name),
3034                    hint,
3035                ))
3036            }
3037
3038            ExprKind::BinaryOp { left, op, right } => {
3039                // Short-circuit for && and ||
3040                if matches!(op, BinOp::And) {
3041                    let lval = self.eval_expr(left)?;
3042                    if !lval.is_truthy() {
3043                        return Ok(Value::Bool(false));
3044                    }
3045                    let rval = self.eval_expr(right)?;
3046                    return Ok(Value::Bool(rval.is_truthy()));
3047                }
3048                if matches!(op, BinOp::Or) {
3049                    let lval = self.eval_expr(left)?;
3050                    if lval.is_truthy() {
3051                        return Ok(Value::Bool(true));
3052                    }
3053                    let rval = self.eval_expr(right)?;
3054                    return Ok(Value::Bool(rval.is_truthy()));
3055                }
3056
3057                let lval = self.eval_expr(left)?;
3058                let rval = self.eval_expr(right)?;
3059                self.binary_op(&lval, op, &rval, expr.line)
3060            }
3061
3062            ExprKind::UnaryOp { op, expr: inner } => {
3063                let val = self.eval_expr(inner)?;
3064                match op {
3065                    UnaryOp::Neg => ops::neg(&val, expr.line),
3066                    UnaryOp::Not => Ok(ops::not(&val)),
3067                }
3068            }
3069
3070            ExprKind::Call { callee, args } => {
3071                if let ExprKind::Ident(name) = &callee.kind {
3072                    // Lexical callable first: if the name is bound
3073                    // to a `Value::Fn` in the current scope, call
3074                    // it. A bound non-callable is an explicit
3075                    // error — "shadowing a builtin with a number
3076                    // then calling it" should fail loudly, not
3077                    // silently dispatch to the builtin.
3078                    if let Some(v) = self.get_var(name).cloned() {
3079                        return match v {
3080                            Value::Fn(func) => self.eval_nybl_call(func, args, expr.line, name),
3081                            other => Err(error(
3082                                expr.line,
3083                                format!("`{}` is a {}, not a function", name, other.type_name()),
3084                            )),
3085                        };
3086                    }
3087                    let declaration_alias =
3088                        self.active_lexical_contexts.last().and_then(|context| {
3089                            if context.module_aliases.is_empty() {
3090                                None
3091                            } else {
3092                                context.module_aliases.get(name).cloned()
3093                            }
3094                        });
3095                    if declaration_alias.is_some() {
3096                        return Err(error(
3097                            expr.line,
3098                            format!("`{name}` is a module, not a function"),
3099                        ));
3100                    }
3101                    if let Some(function) = self.lookup_function(name) {
3102                        // Preserve the established host-before-named-function
3103                        // dispatch for legacy value-only calls. Ref-aware
3104                        // calls must use the retained Nybl callable metadata so
3105                        // their staged targets can be committed transactionally.
3106                        if function
3107                            .param_modes
3108                            .iter()
3109                            .all(|mode| *mode == ParamMode::Value)
3110                            && args.iter().all(|arg| arg.mode == ParamMode::Value)
3111                        {
3112                            if args.len() != function.params.len() {
3113                                return Err(error(
3114                                    expr.line,
3115                                    format!(
3116                                        "`{}` expects {} argument{}, but got {}",
3117                                        name,
3118                                        function.params.len(),
3119                                        if function.params.len() == 1 { "" } else { "s" },
3120                                        args.len()
3121                                    ),
3122                                ));
3123                            }
3124                            let mut eval_args = Vec::with_capacity(args.len());
3125                            for arg in args {
3126                                eval_args.push(self.eval_expr(&arg.value)?);
3127                            }
3128                            return self.call_function(name, eval_args, expr.line, Some(function));
3129                        }
3130                        return self.eval_nybl_call(function, args, expr.line, name);
3131                    }
3132
3133                    let actual_modes: Vec<ParamMode> = args.iter().map(|arg| arg.mode).collect();
3134                    crate::validate_value_only_call_modes(name, &actual_modes, expr.line)?;
3135                    self.validate_builtin_arity(name, args.len(), expr.line)?;
3136                    let mut eval_args = Vec::with_capacity(args.len());
3137                    for arg in args {
3138                        eval_args.push(self.eval_expr(&arg.value)?);
3139                    }
3140                    return self.call_function(name, eval_args, expr.line, None);
3141                }
3142
3143                // The callee expression is always resolved exactly once before
3144                // preflight and before any argument expression.
3145                let callee_val = self.eval_expr(callee)?;
3146                match callee_val {
3147                    Value::Fn(func) => {
3148                        let label = func.self_name.as_deref().unwrap_or("fn").to_string();
3149                        self.eval_nybl_call(func, args, expr.line, &label)
3150                    }
3151                    other => Err(error(
3152                        expr.line,
3153                        crate::error_messages::cant_call_a(other.type_name()),
3154                    )),
3155                }
3156            }
3157
3158            ExprKind::Lambda { params, body } => {
3159                let free_variables = FreeVariableCollector::for_lambda(params).finish(body);
3160                if free_variables.iter().any(|name| {
3161                    self.resolve_binding_identity(name)
3162                        .is_some_and(|identity| self.active_ref_bindings.contains(&identity))
3163                }) {
3164                    return Err(crate::ref_params::ref_capture_error(expr.line));
3165                }
3166                let captures = self.snapshot_captures(&free_variables);
3167                let module_path = self
3168                    .function_modules
3169                    .last()
3170                    .cloned()
3171                    .unwrap_or_else(|| self.current_module.clone());
3172                let (param_names, param_modes) = parameter_metadata(params);
3173                NyblFn::try_new_ast_in_module_with_origin_and_modes(
3174                    param_names,
3175                    param_modes,
3176                    captures,
3177                    body.clone(),
3178                    None,
3179                    Some(module_path),
3180                    self.function_origin.clone(),
3181                    expr.line,
3182                )
3183                .map(Value::Fn)
3184            }
3185
3186            ExprKind::MethodCall {
3187                object,
3188                method,
3189                args,
3190            } => {
3191                let actual_modes: Vec<ParamMode> = args.iter().map(|arg| arg.mode).collect();
3192
3193                // Keep the direct-binding fast path for a bare array or dict.
3194                // It avoids manufacturing a second CoW owner immediately
3195                // before mutation, which preserves exact instance memory
3196                // accounting.
3197                if let ExprKind::Ident(name) = &object.kind
3198                    && self.get_var(name).is_some_and(|value| {
3199                        methods::is_mutating_collection_receiver(value, method)
3200                    })
3201                {
3202                    crate::validate_value_only_call_modes(method, &actual_modes, expr.line)?;
3203                    let expected = methods::builtin_method_arity(method)
3204                        .expect("mutating built-in has arity metadata");
3205                    if args.len() != expected {
3206                        return Err(error(
3207                            expr.line,
3208                            format!(
3209                                "`.{}()` needs {} argument{}",
3210                                method,
3211                                expected,
3212                                if expected == 1 { "" } else { "s" }
3213                            ),
3214                        ));
3215                    }
3216                    methods::reject_constant_array_mutation(name, method, expr.line)?;
3217                    let target = self
3218                        .resolve_binding_identity(name)
3219                        .ok_or_else(|| crate::ref_params::invalid_ref_target(1, expr.line))?;
3220                    if self.active_capture_bindings.contains(&target) {
3221                        return Err(crate::ref_params::captured_ref_target(1, expr.line));
3222                    }
3223                    let mut eval_args = Vec::with_capacity(args.len());
3224                    for arg in args {
3225                        eval_args.push(self.eval_expr(&arg.value)?);
3226                    }
3227                    if let Some(error) = self.pending_memory_error(expr.line) {
3228                        return Err(error);
3229                    }
3230                    let binding = self
3231                        .scopes
3232                        .get_mut(target.scope)
3233                        .and_then(|scope| scope.get_mut(&target.name))
3234                        .ok_or_else(|| crate::ref_params::invalid_ref_target(1, expr.line))?;
3235                    return methods::transactional_collection_method_in(
3236                        binding,
3237                        method,
3238                        eval_args,
3239                        expr.line,
3240                        &self.memory,
3241                    );
3242                }
3243
3244                // Preserve a resolved place while evaluating an index/field
3245                // receiver exactly once. Read-only methods use only the leaf;
3246                // mutating built-ins and `ref self` methods can later commit a
3247                // replacement leaf through the retained projection chain.
3248                let mut receiver_place = if let Some(plan) = self.read_place_plan(object) {
3249                    Some(self.resolve_place(plan, 1, expr.line)?)
3250                } else {
3251                    None
3252                };
3253                let obj_val = if let Some(place) = &receiver_place {
3254                    self.place_value_from(&place.root, &place.projections, expr.line)?
3255                } else {
3256                    self.eval_expr(object)?
3257                };
3258
3259                if methods::is_mutating_collection_receiver(&obj_val, method)
3260                    && receiver_place.is_some()
3261                {
3262                    crate::validate_value_only_call_modes(method, &actual_modes, expr.line)?;
3263                    let expected = methods::builtin_method_arity(method)
3264                        .expect("mutating built-in has arity metadata");
3265                    if args.len() != expected {
3266                        return Err(error(
3267                            expr.line,
3268                            format!(
3269                                "`.{}()` needs {} argument{}",
3270                                method,
3271                                expected,
3272                                if expected == 1 { "" } else { "s" }
3273                            ),
3274                        ));
3275                    }
3276                    let place = receiver_place
3277                        .take()
3278                        .expect("place presence checked for mutating receiver");
3279                    self.validate_mutable_place(&place, 1, expr.line)?;
3280                    let mut eval_args = Vec::with_capacity(args.len());
3281                    for arg in args {
3282                        eval_args.push(self.eval_expr(&arg.value)?);
3283                    }
3284                    if let Some(error) = self.pending_memory_error(expr.line) {
3285                        return Err(error);
3286                    }
3287                    // Arguments may mutate the same root. Copy-in therefore
3288                    // occurs after argument evaluation, using the already
3289                    // evaluated projection values.
3290                    let current_root = self
3291                        .binding_value(&place.target)
3292                        .ok_or_else(|| crate::ref_params::invalid_ref_target(1, expr.line))?;
3293                    let mut leaf =
3294                        self.place_value_from(&current_root, &place.projections, expr.line)?;
3295                    let result = methods::transactional_collection_method_in(
3296                        &mut leaf,
3297                        method,
3298                        eval_args,
3299                        expr.line,
3300                        &self.memory,
3301                    )?;
3302                    let committed = ResolvedPlace {
3303                        target: place.target,
3304                        root: current_root,
3305                        projections: place.projections,
3306                    };
3307                    self.commit_ref_places(&[committed], vec![leaf], expr.line)?;
3308                    return Ok(result);
3309                }
3310                let type_key: Option<(String, String)> = match &obj_val {
3311                    Value::Struct(s) => {
3312                        Some((s.module_path().to_string(), s.type_name().to_string()))
3313                    }
3314                    Value::EnumVariant(e) => {
3315                        Some((e.module_path().to_string(), e.type_name().to_string()))
3316                    }
3317                    _ => None,
3318                };
3319                if let Some(key) = type_key {
3320                    let user = self
3321                        .methods
3322                        .get(&key)
3323                        .and_then(|ms| ms.get(method))
3324                        .cloned();
3325                    if let Some(m) = user {
3326                        let receiver_place = if m
3327                            .param_modes
3328                            .first()
3329                            .is_some_and(|mode| *mode == ParamMode::Ref)
3330                        {
3331                            let Some(place) = receiver_place.take() else {
3332                                let mut error = NyblError::runtime(
3333                                    "a `ref` method receiver must be a mutable place",
3334                                    expr.line,
3335                                );
3336                                error.friendly_hint = Some(
3337                                    "Store the value in a `let` binding, or call through one of its fields or indexes."
3338                                        .to_string(),
3339                                );
3340                                return Err(error);
3341                            };
3342                            self.validate_mutable_place(&place, 1, expr.line)?;
3343                            Some(place)
3344                        } else {
3345                            None
3346                        };
3347                        return self.eval_user_method_call(
3348                            MethodReceiver {
3349                                value: obj_val,
3350                                place: receiver_place,
3351                            },
3352                            &key.1,
3353                            method,
3354                            m,
3355                            args,
3356                            expr.line,
3357                        );
3358                    }
3359                }
3360
3361                // Module export calls retain callable metadata too. Common
3362                // value methods still win over an export with the same name.
3363                if let Value::Module(module) = &obj_val
3364                    && !matches!(method.as_str(), "type" | "to_str" | "inspect")
3365                {
3366                    let callee = self.module_binding(module, method).ok_or_else(|| {
3367                        error(
3368                            expr.line,
3369                            format!("`{}` isn't exported from `{}`", method, module.path),
3370                        )
3371                    })?;
3372                    return match callee {
3373                        Value::Fn(func) => self.eval_nybl_call(func, args, expr.line, method),
3374                        other => Err(error(
3375                            expr.line,
3376                            format!("`{}` is a {}, not a function", method, other.type_name()),
3377                        )),
3378                    };
3379                }
3380
3381                // Index and field reads currently produce values,
3382                // not write-back places. Reject only built-in array
3383                // mutations on those syntactic receiver forms so
3384                // they cannot silently mutate-and-discard. Genuine
3385                // temporaries remain legal, and user methods above
3386                // retain precedence even when named `push`, `pop`,
3387                // and so on.
3388                if matches!(
3389                    &object.kind,
3390                    ExprKind::Index { .. } | ExprKind::FieldAccess { .. }
3391                ) {
3392                    methods::reject_nested_array_mutation(&obj_val, method, expr.line)?;
3393                }
3394
3395                crate::validate_value_only_call_modes(method, &actual_modes, expr.line)?;
3396                if !matches!(&obj_val, Value::Host(_))
3397                    && let Some(expected) = methods::builtin_method_arity(method)
3398                    && args.len() != expected
3399                {
3400                    return Err(error(
3401                        expr.line,
3402                        format!(
3403                            "`.{}()` needs {} argument{}",
3404                            method,
3405                            expected,
3406                            if expected == 1 { "" } else { "s" }
3407                        ),
3408                    ));
3409                }
3410                let mut eval_args = Vec::with_capacity(args.len());
3411                for arg in args {
3412                    eval_args.push(self.eval_expr(&arg.value)?);
3413                }
3414
3415                // Callable-taking Result methods — `r.map(f)`,
3416                // `r.map_err(f)`, `r.and_then(f)`. These need the
3417                // evaluator's call primitive to invoke `f`, which
3418                // `call_method` doesn't have access to, so they
3419                // dispatch inline before the pure `call_method`
3420                // fall-through. Receiver must be the built-in
3421                // Result; user enums named `Result` don't qualify.
3422                if methods::is_builtin_result(&obj_val)
3423                    && let Some(kind) = methods::is_result_callable_method(method)
3424                {
3425                    return self
3426                        .call_result_callable_method(&obj_val, kind, method, eval_args, expr.line);
3427                }
3428
3429                let (ret, mutated) = self.call_method(&obj_val, method, &eval_args, expr.line)?;
3430                // A true temporary mutates its staged owned value and discards
3431                // the update. Named array receivers returned through the
3432                // transactional path above.
3433                let _ = mutated;
3434                Ok(ret)
3435            }
3436
3437            ExprKind::Index { object, index } => {
3438                let obj = self.eval_expr(object)?;
3439                let idx = self.eval_expr(index)?;
3440                ops::index_get_in(&obj, &idx, expr.line, &self.memory)
3441            }
3442
3443            ExprKind::FieldAccess { object, field } => {
3444                let obj = self.eval_expr(object)?;
3445                match &obj {
3446                    Value::Struct(s) => s.field(field).cloned().ok_or_else(|| {
3447                        let msg = crate::error_messages::struct_has_no_field(s.type_name(), field);
3448                        // Suggest from the struct's own declared
3449                        // field list — `p.z` when `Point` has `x`
3450                        // and `y` should point to `x`/`y`.
3451                        let field_names: Vec<&str> =
3452                            s.fields().iter().map(|(k, _)| k.as_str()).collect();
3453                        match crate::suggest::did_you_mean(field, field_names) {
3454                            Some(hint) => error_with_hint_at(expr.line, expr.column, msg, hint),
3455                            None => error_at(expr.line, expr.column, msg),
3456                        }
3457                    }),
3458                    Value::EnumVariant(e) => e.field(field).cloned().ok_or_else(|| {
3459                        error(
3460                            expr.line,
3461                            crate::error_messages::variant_has_no_field(
3462                                e.type_name(),
3463                                e.variant(),
3464                                field,
3465                            ),
3466                        )
3467                    }),
3468                    Value::Module(m) => {
3469                        // `alias.name` — look up an export in the
3470                        // aliased module.
3471                        if let Some(v) = self.module_binding(m, field) {
3472                            return Ok(v);
3473                        }
3474                        if m.has_type(field) {
3475                            // Types aren't first-class values; the
3476                            // parser should have taken the namespaced
3477                            // struct-lit / variant-ctor path
3478                            // already. Reaching a FieldAccess here
3479                            // means the user wrote `m.Type` in a
3480                            // value-returning position.
3481                            let alias = m.path.rsplit('.').next().unwrap_or(&m.path);
3482                            return Err(error_with_hint(
3483                                expr.line,
3484                                format!("`{}` in `{}` is a type, not a value", field, m.path),
3485                                format!(
3486                                    "construct through the alias: `{alias}.{field} {{ ... }}` or `{alias}.{field}::Variant(...)`",
3487                                ),
3488                            ));
3489                        }
3490                        Err(error(
3491                            expr.line,
3492                            format!("`{}` isn't exported from `{}`", field, m.path),
3493                        ))
3494                    }
3495                    other => Err(error(
3496                        expr.line,
3497                        crate::error_messages::cant_read_field(field, other.type_name()),
3498                    )),
3499                }
3500            }
3501
3502            ExprKind::EnumConstruct {
3503                namespace,
3504                type_name,
3505                variant,
3506                payload,
3507            } => self.eval_enum_construct(
3508                namespace.as_deref(),
3509                type_name,
3510                variant,
3511                payload,
3512                expr.line,
3513            ),
3514
3515            ExprKind::StructConstruct {
3516                namespace,
3517                type_name,
3518                fields,
3519            } => {
3520                let module_path = match namespace {
3521                    Some(ns) => {
3522                        self.validate_namespaced_type(ns, type_name, expr.line)?;
3523                        self.resolve_type_ref(Some(ns), type_name)
3524                            .unwrap_or_else(|| self.current_module.clone())
3525                    }
3526                    None => self.resolve_type_ref(None, type_name).ok_or_else(|| {
3527                        error(
3528                            expr.line,
3529                            crate::error_messages::struct_not_declared(type_name),
3530                        )
3531                    })?,
3532                };
3533                let key = (module_path.clone(), type_name.clone());
3534                let decl_fields = self
3535                    .struct_defs
3536                    .get(&key)
3537                    .ok_or_else(|| {
3538                        error(
3539                            expr.line,
3540                            crate::error_messages::struct_not_declared(type_name),
3541                        )
3542                    })?
3543                    .clone();
3544                // Enforce exactly-this-field-set at construction:
3545                // no duplicates, no unknown fields, no missing
3546                // fields. The per-field loops below produce the
3547                // specific messages the tests assert on.
3548                let mut seen = alloc_import::collections::BTreeSet::new();
3549                for (fname, _) in fields {
3550                    if !seen.insert(fname.clone()) {
3551                        return Err(error(
3552                            expr.line,
3553                            format!(
3554                                "Field `{fname}` specified twice in `{type_name}` construction"
3555                            ),
3556                        ));
3557                    }
3558                    if !decl_fields.iter().any(|d| d == fname) {
3559                        let msg = crate::error_messages::struct_has_no_field(type_name, fname);
3560                        let err = match crate::suggest::did_you_mean(
3561                            fname,
3562                            decl_fields.iter().map(|s| s.as_str()),
3563                        ) {
3564                            Some(hint) => error_with_hint_at(expr.line, expr.column, msg, hint),
3565                            None => error_at(expr.line, expr.column, msg),
3566                        };
3567                        return Err(err);
3568                    }
3569                }
3570                for decl in &decl_fields {
3571                    if !seen.contains(decl) {
3572                        return Err(error(
3573                            expr.line,
3574                            format!("Missing field `{decl}` in `{type_name}` construction"),
3575                        ));
3576                    }
3577                }
3578                let mut provided: BTreeMap<String, Value> = BTreeMap::new();
3579                for (fname, fexpr) in fields {
3580                    provided.insert(fname.clone(), self.eval_expr(fexpr)?);
3581                }
3582                let mut values: Vec<(String, Value)> = Vec::with_capacity(decl_fields.len());
3583                for decl in &decl_fields {
3584                    values.push((
3585                        decl.clone(),
3586                        provided
3587                            .remove(decl)
3588                            .expect("struct shape validated before payload evaluation"),
3589                    ));
3590                }
3591                Value::__try_new_struct_in(
3592                    module_path,
3593                    type_name.clone(),
3594                    values,
3595                    expr.line,
3596                    &self.memory,
3597                )
3598            }
3599
3600            ExprKind::Array(elements) => {
3601                let mut items = Vec::new();
3602                for elem in elements {
3603                    items.push(self.eval_expr(elem)?);
3604                }
3605                Value::__try_new_array_in(items, expr.line, &self.memory)
3606            }
3607
3608            ExprKind::Dict(entries) => {
3609                let mut result = Vec::new();
3610                for (key, value_expr) in entries {
3611                    let val = self.eval_expr(value_expr)?;
3612                    result.push((key.clone(), val));
3613                }
3614                Value::__try_new_dict_in(result, expr.line, &self.memory)
3615            }
3616
3617            ExprKind::IfExpr {
3618                condition,
3619                then_expr,
3620                else_expr,
3621            } => {
3622                if self.eval_expr(condition)?.is_truthy() {
3623                    self.eval_expr(then_expr)
3624                } else {
3625                    self.eval_expr(else_expr)
3626                }
3627            }
3628
3629            ExprKind::Match { scrutinee, arms } => self.eval_match(scrutinee, arms, expr.line),
3630
3631            ExprKind::Try(inner) => self.eval_try(inner, expr.line),
3632        }
3633    }
3634
3635    /// `try` expression handler. Evaluates the inner expression,
3636    /// matches the conventional Result-shape (any enum variant
3637    /// named `Ok` or `Err`), and either unwraps `Ok` or stashes
3638    /// the `Err` value into `pending_try_return` so the enclosing
3639    /// `call_nybl_fn` can convert it to `Signal::Return`.
3640    ///
3641    /// Top-level `try` on `Err` (call_depth == 0) surfaces as a
3642    /// real runtime error — there's no enclosing fn to return
3643    /// from, and the roadmap explicitly rejects the idea of
3644    /// swallowing it silently.
3645    fn eval_try(&mut self, inner: &Expr, line: u32) -> Result<Value, NyblError> {
3646        let value = self.eval_expr(inner)?;
3647        // An earlier `try` in `inner` might have already fired —
3648        // e.g. `try try foo()` — in which case we just keep
3649        // propagating without poking at the unwound value.
3650        if self.pending_try_return.is_some() {
3651            return Ok(Value::None);
3652        }
3653        match &value {
3654            Value::EnumVariant(ev) if ev.variant() == "Ok" => {
3655                // Extract the single payload for `Ok(v)`, or fall
3656                // back to `none` for `Ok` used as a unit variant.
3657                match ev.payload() {
3658                    EnumPayload::Tuple(items) if items.len() == 1 => Ok(items[0].clone()),
3659                    EnumPayload::Unit => Ok(Value::None),
3660                    EnumPayload::Tuple(items) => Err(error(
3661                        line,
3662                        format!(
3663                            "try: Ok variant must carry exactly one value, got {}",
3664                            items.len()
3665                        ),
3666                    )),
3667                    EnumPayload::Struct(_) => Err(error(
3668                        line,
3669                        "try: Ok variant must carry a single positional value, not named fields",
3670                    )),
3671                }
3672            }
3673            Value::EnumVariant(ev) if ev.variant() == "Err" => {
3674                if self.call_depth == 0 {
3675                    return Err(crate::error_messages::top_level_try_error(line));
3676                }
3677                self.pending_try_return = Some(value);
3678                // Sentinel error whose only job is to unwind up
3679                // to the nearest `call_nybl_fn`, which converts
3680                // it back into a `Signal::Return`. The `is_try_return`
3681                // flag on `NyblError` is the only thing that
3682                // matters — line is kept for debug clarity;
3683                // message is unused.
3684                Err(NyblError::try_return_signal(line))
3685            }
3686            other => Err(error(
3687                line,
3688                format!(
3689                    "try expected a Result-shaped value (Ok/Err variant), got {}",
3690                    other.type_name()
3691                ),
3692            )),
3693        }
3694    }
3695
3696    fn eval_match(
3697        &mut self,
3698        scrutinee: &Expr,
3699        arms: &[MatchArm],
3700        line: u32,
3701    ) -> Result<Value, NyblError> {
3702        let value = self.eval_expr(scrutinee)?;
3703        for arm in arms {
3704            let mut bindings: Vec<(String, Value)> = Vec::new();
3705            // Resolve patterns' type references through the
3706            // walker's current scope. Capturing the three scope
3707            // tables as immutable slices / refs keeps the
3708            // closure free of the mutable-self borrow we need
3709            // right after for `push_scope` + binding injection.
3710            let scopes = &self.scopes;
3711            let type_bindings = &self.type_bindings;
3712            let module_aliases = &self.module_aliases;
3713            let alias_scope_floor = self.alias_scope_floors.last().copied();
3714            let resolver = |ns: Option<&str>, tn: &str| -> Option<String> {
3715                resolve_type_in_evaluator_context(
3716                    scopes,
3717                    type_bindings,
3718                    module_aliases,
3719                    alias_scope_floor,
3720                    self.active_lexical_contexts.last().map(Rc::as_ref),
3721                    ns,
3722                    tn,
3723                )
3724            };
3725            if !pattern_matches_in(&arm.pattern, &value, &mut bindings, &resolver, &self.memory) {
3726                continue;
3727            }
3728            // Pattern matched — open a fresh scope, bind every
3729            // captured name, evaluate the guard (in that scope).
3730            self.push_scope();
3731            for (name, v) in bindings {
3732                self.define(name, v);
3733            }
3734            let guard_ok = match &arm.guard {
3735                Some(g) => self.eval_expr(g)?.is_truthy(),
3736                None => true,
3737            };
3738            if !guard_ok {
3739                self.pop_scope();
3740                continue;
3741            }
3742            let result = self.eval_expr(&arm.body);
3743            self.pop_scope();
3744            return result;
3745        }
3746        Err(error(line, "No match arm matched the scrutinee"))
3747    }
3748
3749    // ─── Binary operations ─────────────────────────────────────────
3750
3751    fn binary_op(
3752        &self,
3753        left: &Value,
3754        op: &BinOp,
3755        right: &Value,
3756        line: u32,
3757    ) -> Result<Value, NyblError> {
3758        match op {
3759            BinOp::Add => ops::add_in(left, right, line, &self.memory),
3760            BinOp::Sub => ops::sub_in(left, right, line, &self.memory),
3761            BinOp::Mul => ops::mul_in(left, right, line, &self.memory),
3762            BinOp::Div => ops::div_in(left, right, line, &self.memory),
3763            BinOp::Mod => ops::rem_in(left, right, line, &self.memory),
3764            BinOp::Eq => Ok(ops::eq(left, right)),
3765            BinOp::NotEq => Ok(ops::not_eq(left, right)),
3766            BinOp::Lt => ops::lt_in(left, right, line, &self.memory),
3767            BinOp::Gt => ops::gt_in(left, right, line, &self.memory),
3768            BinOp::LtEq => ops::lt_eq_in(left, right, line, &self.memory),
3769            BinOp::GtEq => ops::gt_eq_in(left, right, line, &self.memory),
3770            BinOp::And | BinOp::Or => unreachable!("handled in eval_expr"),
3771        }
3772    }
3773
3774    // ─── Function calls ────────────────────────────────────────────
3775
3776    /// Snapshot only the referenced free variables that currently resolve to
3777    /// lexical values. Names belonging to builtins, hosts, or declared
3778    /// functions deliberately remain absent so call-time fallback can resolve
3779    /// them through their owning registries.
3780    fn snapshot_captures(
3781        &self,
3782        free_variables: &alloc_import::collections::BTreeSet<String>,
3783    ) -> Vec<(String, Value)> {
3784        free_variables
3785            .iter()
3786            .filter_map(|name| {
3787                // During a function call scope zero is the injected live
3788                // defining-module environment. Capturing it would freeze
3789                // globals inside a returned closure. At top level it remains a
3790                // genuine lexical scope and keeps the language's established
3791                // snapshot-capture semantics.
3792                self.scopes
3793                    .iter()
3794                    .skip(usize::from(self.call_depth > 0))
3795                    .rev()
3796                    .find_map(|scope| scope.get(name))
3797                    .cloned()
3798                    .map(|value| (name.clone(), value))
3799            })
3800            .collect()
3801    }
3802
3803    fn eval_nybl_call(
3804        &mut self,
3805        func: Rc<NyblFn>,
3806        args: &[CallArg],
3807        line: u32,
3808        callable: &str,
3809    ) -> Result<Value, NyblError> {
3810        if !func.__is_allowed_by(&self.function_origin, "walker") {
3811            return Err(error(
3812                line,
3813                "This function belongs to a different Nybl engine instance",
3814            ));
3815        }
3816        if !matches!(func.body, FnBody::Ast(_)) {
3817            return Err(error(
3818                line,
3819                "This function was compiled for another engine and can't be run in the tree-walker",
3820            ));
3821        }
3822        if !crate::ref_params::accepts_arity(&func.param_modes, args.len()) {
3823            let required = crate::ref_params::required_arity(&func.param_modes);
3824            let variadic = matches!(func.param_modes.last(), Some(ParamMode::Rest));
3825            return Err(error(
3826                line,
3827                if variadic {
3828                    format!(
3829                        "`{callable}` expects at least {required} arguments, but got {}",
3830                        args.len()
3831                    )
3832                } else {
3833                    format!(
3834                        "`{callable}` expects {required} argument{}, but got {}",
3835                        if required == 1 { "" } else { "s" },
3836                        args.len()
3837                    )
3838                },
3839            ));
3840        }
3841        let actual_modes: Vec<ParamMode> = args.iter().map(|arg| arg.mode).collect();
3842        crate::validate_call_modes(callable, &func.param_modes, &actual_modes, line)?;
3843        let plans = self.preflight_ref_places(args, line)?;
3844
3845        // Ordinary argument expressions run left-to-right. Ref places are
3846        // intentionally not read yet: side effects here must be visible in
3847        // the subsequent copy-in snapshot.
3848        let mut evaluated: Vec<Option<Value>> = Vec::with_capacity(args.len());
3849        for arg in args {
3850            evaluated.push(match arg.mode {
3851                ParamMode::Value => Some(self.eval_expr(&arg.value)?),
3852                ParamMode::Ref => None,
3853                ParamMode::Rest => unreachable!("rest is a declaration-only parameter mode"),
3854            });
3855        }
3856
3857        let mut plan_iter = plans.into_iter();
3858        let mut places = Vec::new();
3859        let mut ref_positions = Vec::new();
3860        let mut call_args = Vec::with_capacity(args.len());
3861        for (index, (arg, value)) in args.iter().zip(evaluated).enumerate() {
3862            match arg.mode {
3863                ParamMode::Value => {
3864                    call_args.push(value.expect("value argument was evaluated"));
3865                }
3866                ParamMode::Ref => {
3867                    let plan = plan_iter.next().expect("place preflight matched modes");
3868                    let place = self.resolve_place(plan, index + 1, line)?;
3869                    let snapshot = self.place_value_from(&place.root, &place.projections, line)?;
3870                    call_args.push(snapshot);
3871                    places.push(place);
3872                    ref_positions.push(index);
3873                }
3874                ParamMode::Rest => unreachable!("rest is a declaration-only parameter mode"),
3875            }
3876        }
3877
3878        let (value, staged) =
3879            self.call_nybl_fn_with_refs(&func, call_args, &ref_positions, line)?;
3880        self.commit_ref_places(&places, staged, line)?;
3881        Ok(value)
3882    }
3883
3884    fn eval_user_method_call(
3885        &mut self,
3886        mut receiver: MethodReceiver,
3887        receiver_type: &str,
3888        method: &str,
3889        definition: FunctionDefinition,
3890        args: &[CallArg],
3891        line: u32,
3892    ) -> Result<Value, NyblError> {
3893        let actual_arity = args.len() + 1;
3894        if !crate::ref_params::accepts_arity(&definition.param_modes, actual_arity) {
3895            let required = crate::ref_params::required_arity(&definition.param_modes);
3896            let variadic = matches!(definition.param_modes.last(), Some(ParamMode::Rest));
3897            return Err(error(
3898                line,
3899                if variadic {
3900                    format!(
3901                        "`{receiver_type}.{method}` expects at least {required} arguments (including `self`), but got {actual_arity}"
3902                    )
3903                } else {
3904                    format!(
3905                        "`{receiver_type}.{method}` expects {required} argument{} (including `self`), but got {actual_arity}",
3906                        if required == 1 { "" } else { "s" }
3907                    )
3908                },
3909            ));
3910        }
3911        // The exact total-arity check above guarantees the implicit receiver
3912        // has a corresponding first parameter before we inspect ordinary
3913        // argument modes or evaluate any ordinary argument expressions.
3914        let expected_modes = &definition.param_modes[1..];
3915        let actual_modes: Vec<ParamMode> = args.iter().map(|arg| arg.mode).collect();
3916        crate::validate_call_modes(method, expected_modes, &actual_modes, line)?;
3917        let explicit_plans = self.preflight_ref_places(args, line)?;
3918        if let Some(receiver_place) = &receiver.place
3919            && explicit_plans
3920                .iter()
3921                .any(|place| place.target == receiver_place.target)
3922        {
3923            return Err(crate::ref_params::duplicate_ref_target(line));
3924        }
3925
3926        let mut evaluated = Vec::with_capacity(args.len());
3927        for arg in args {
3928            evaluated.push(match arg.mode {
3929                ParamMode::Value => Some(self.eval_expr(&arg.value)?),
3930                ParamMode::Ref => None,
3931                ParamMode::Rest => unreachable!("rest is a declaration-only parameter mode"),
3932            });
3933        }
3934        let mut plan_iter = explicit_plans.into_iter();
3935        let mut explicit_places = Vec::new();
3936        let mut full_args = Vec::with_capacity(args.len() + 1);
3937        let mut ref_positions = Vec::new();
3938        if let Some(place) = &mut receiver.place {
3939            // Receiver projections were evaluated before argument preflight,
3940            // but copy-in observes argument side effects to the root.
3941            place.root = self
3942                .binding_value(&place.target)
3943                .ok_or_else(|| crate::ref_params::invalid_ref_target(1, line))?;
3944            full_args.push(self.place_value_from(&place.root, &place.projections, line)?);
3945            ref_positions.push(0);
3946        } else {
3947            full_args.push(receiver.value);
3948        }
3949        for (index, (arg, value)) in args.iter().zip(evaluated).enumerate() {
3950            match arg.mode {
3951                ParamMode::Value => {
3952                    full_args.push(value.expect("ordinary method argument was evaluated"));
3953                }
3954                ParamMode::Ref => {
3955                    let plan = plan_iter.next().expect("place count matched ref modes");
3956                    let place = self.resolve_place(plan, index + 1, line)?;
3957                    full_args.push(self.place_value_from(&place.root, &place.projections, line)?);
3958                    explicit_places.push(place);
3959                    ref_positions.push(index + 1);
3960                }
3961                ParamMode::Rest => unreachable!("rest is a declaration-only parameter mode"),
3962            }
3963        }
3964        let (value, staged) =
3965            self.call_nybl_fn_with_refs(&definition, full_args, &ref_positions, line)?;
3966        let mut places =
3967            Vec::with_capacity(explicit_places.len() + usize::from(receiver.place.is_some()));
3968        if let Some(place) = receiver.place {
3969            places.push(place);
3970        }
3971        places.extend(explicit_places);
3972        self.commit_ref_places(&places, staged, line)?;
3973        Ok(value)
3974    }
3975
3976    fn validate_builtin_arity(&self, name: &str, count: usize, line: u32) -> Result<(), NyblError> {
3977        let expected = match name {
3978            "rand" | "try_call" | "panic" => Some((1, 1)),
3979            "range" => Some((1, 3)),
3980            "print" => None,
3981            _ => return Ok(()),
3982        };
3983        if let Some((min, max)) = expected
3984            && (count < min || count > max)
3985        {
3986            let expectation = if min == max {
3987                format!("{} argument{}", min, if min == 1 { "" } else { "s" })
3988            } else {
3989                format!("{min} to {max} arguments")
3990            };
3991            return Err(error(
3992                line,
3993                format!("`{name}` expects {expectation}, but got {count}"),
3994            ));
3995        }
3996        Ok(())
3997    }
3998
3999    /// Call a value directly. Non-`Value::Fn` payloads are an
4000    /// explicit "not callable" error — this is the safety net for
4001    /// `let x = 5; x(1)` and friends.
4002    ///
4003    /// `name_hint` is the Ident text when the callee was a bare
4004    /// name, used only for error messages. Non-Ident callees pass
4005    /// `None`.
4006    fn call_value(
4007        &mut self,
4008        callee: Value,
4009        args: Vec<Value>,
4010        line: u32,
4011        name_hint: Option<&str>,
4012    ) -> Result<Value, NyblError> {
4013        match &callee {
4014            Value::Fn(f) => {
4015                let f = Rc::clone(f);
4016                drop(callee);
4017                self.call_nybl_fn(&f, args, line)
4018            }
4019            other => match name_hint {
4020                Some(n) => Err(error(
4021                    line,
4022                    format!("`{}` is a {}, not a function", n, other.type_name()),
4023                )),
4024                None => Err(error(
4025                    line,
4026                    crate::error_messages::cant_call_a(other.type_name()),
4027                )),
4028            },
4029        }
4030    }
4031
4032    /// Shared call path for every `Value::Fn` — the body of both
4033    /// `let f = fn(...) {...}; f(x)` and the reified version of
4034    /// `fn name(...) {...}; name(x)` come through here.
4035    fn call_nybl_fn(
4036        &mut self,
4037        func: &Rc<NyblFn>,
4038        args: Vec<Value>,
4039        line: u32,
4040    ) -> Result<Value, NyblError> {
4041        let actual_modes = vec![ParamMode::Value; args.len()];
4042        crate::validate_call_modes(
4043            func.self_name.as_deref().unwrap_or("fn"),
4044            &func.param_modes,
4045            &actual_modes,
4046            line,
4047        )?;
4048        self.call_nybl_fn_with_refs(func, args, &[], line)
4049            .map(|(value, _)| value)
4050    }
4051
4052    fn call_nybl_fn_with_refs(
4053        &mut self,
4054        func: &Rc<NyblFn>,
4055        mut args: Vec<Value>,
4056        ref_positions: &[usize],
4057        line: u32,
4058    ) -> Result<(Value, Vec<Value>), NyblError> {
4059        if !func.__is_allowed_by(&self.function_origin, "walker") {
4060            return Err(error(
4061                line,
4062                "This function belongs to a different Nybl engine instance",
4063            ));
4064        }
4065        let body = match &func.body {
4066            FnBody::Ast(stmts) => stmts,
4067            FnBody::Compiled(_) => {
4068                return Err(error(
4069                    line,
4070                    "This function was compiled for another engine and can't be run in the tree-walker",
4071                ));
4072            }
4073        };
4074        if !crate::ref_params::accepts_arity(&func.param_modes, args.len()) {
4075            let name = func.self_name.as_deref().unwrap_or("fn");
4076            let required = crate::ref_params::required_arity(&func.param_modes);
4077            let variadic = matches!(func.param_modes.last(), Some(ParamMode::Rest));
4078            return Err(error(
4079                line,
4080                if variadic {
4081                    format!(
4082                        "`{name}` expects at least {required} arguments, but got {}",
4083                        args.len()
4084                    )
4085                } else {
4086                    format!(
4087                        "`{name}` expects {required} argument{}, but got {}",
4088                        if required == 1 { "" } else { "s" },
4089                        args.len()
4090                    )
4091                },
4092            ));
4093        }
4094        if matches!(func.param_modes.last(), Some(ParamMode::Rest)) {
4095            let required = crate::ref_params::required_arity(&func.param_modes);
4096            let extras = args.split_off(required);
4097            args.push(Value::__try_new_array_in(extras, line, &self.memory)?);
4098        }
4099
4100        if self.active_call_depth() >= MAX_CALL_DEPTH {
4101            return Err(crate::error_messages::call_depth_error(line));
4102        }
4103        let nesting = func.body_depth();
4104        self.enter_nesting(nesting, line)?;
4105
4106        // A function call gets a fresh scope stack: no outer
4107        // locals leak in. Captures and parameters seed the new
4108        // scope; self-reference via `self_name` lets recursive
4109        // lambdas see themselves.
4110        //
4111        // `type_bindings` is NOT reset — types and module
4112        // aliases declared at module scope need to be visible
4113        // inside nested fn bodies for construction + pattern
4114        // matching to work. We push a fresh frame so any
4115        // type decl inside the fn body still ends up scoped to
4116        // that fn and vanishes on return.
4117        self.call_depth += 1;
4118        let saved_ref_bindings = core::mem::take(&mut self.active_ref_bindings);
4119        let saved_capture_bindings = core::mem::take(&mut self.active_capture_bindings);
4120        let function_module = func
4121            .module_path
4122            .clone()
4123            .unwrap_or_else(|| crate::value::ROOT_MODULE_PATH.to_string());
4124        let lexical_context = self.module_lexical_context(&function_module);
4125        self.function_modules.push(function_module.clone());
4126        self.active_lexical_contexts.push(lexical_context);
4127        let mut saved_scopes = core::mem::take(&mut self.scopes);
4128        let caller_environment = if let Some(scope) = saved_scopes.first_mut() {
4129            core::mem::take(scope)
4130        } else {
4131            BTreeMap::new()
4132        };
4133        let caller_binding_origins = core::mem::take(&mut self.binding_origins);
4134        let caller_value_module =
4135            core::mem::replace(&mut self.active_value_module, function_module.clone());
4136        self.live_binding_origins
4137            .borrow_mut()
4138            .insert(caller_value_module.clone(), caller_binding_origins.clone());
4139        put_live_environment(
4140            &self.live_value_environments,
4141            &caller_value_module,
4142            caller_environment,
4143            &caller_binding_origins,
4144        );
4145        let defining_binding_origins = self
4146            .live_binding_origins
4147            .borrow()
4148            .get(&function_module)
4149            .cloned()
4150            .unwrap_or_default();
4151        let defining_environment = take_live_environment(
4152            &self.live_value_environments,
4153            &function_module,
4154            &defining_binding_origins,
4155        );
4156        self.binding_origins = defining_binding_origins;
4157        // Keep the live root environment below the call-local frame. This is
4158        // intentionally moved, not cloned: reads and writes observe retained
4159        // instance state, and named in-place mutation keeps a refcount-1
4160        // receiver instead of defeating collection CoW.
4161        self.scopes = vec![defining_environment, BTreeMap::new()];
4162        let type_scope_floor = self.type_bindings.len();
4163        self.type_bindings.push(BTreeMap::new());
4164        let alias_scope_floor = self.module_aliases.len();
4165        self.module_aliases.push(BTreeMap::new());
4166        self.imported_functions.push(BTreeMap::new());
4167        self.alias_scope_floors.push(alias_scope_floor);
4168        self.import_scopes.push(ImportScope::default());
4169
4170        // Captures go in first so parameters shadow them on
4171        // collision (matches the lexical snapshot semantics).
4172        for (name, value) in &func.captures {
4173            self.define(name.clone(), value.clone());
4174            if let Some(identity) = self.resolve_binding_identity(name) {
4175                self.active_capture_bindings.insert(identity);
4176            }
4177        }
4178        if let Some(self_name) = &func.self_name {
4179            // Make the reified `fn name` value visible inside its
4180            // own body so `fn fib(n) { return fib(n-1) ... }`
4181            // works without a special "named fn" path.
4182            self.define(self_name.clone(), Value::Fn(Rc::clone(func)));
4183            if !func.params.contains(self_name)
4184                && let Some(imports) = self.import_scopes.last_mut()
4185            {
4186                imports.self_binding = Some((function_module.clone(), self_name.clone()));
4187            }
4188        }
4189        for (index, (param, arg)) in func.params.iter().zip(args).enumerate() {
4190            self.define(param.clone(), arg);
4191            if let Some(identity) = self.resolve_binding_identity(param) {
4192                self.active_capture_bindings.remove(&identity);
4193                if func.param_modes.get(index) == Some(&ParamMode::Ref) {
4194                    self.active_ref_bindings.insert(identity);
4195                }
4196            }
4197        }
4198
4199        let raw_result = self.exec_block(body);
4200        // Convert every normal language return shape before looking at staged
4201        // outputs. A `try Err(...)` sentinel is a normal return and commits;
4202        // every other error rolls back.
4203        let mut result = match raw_result {
4204            Ok(Signal::Return(value)) => Ok(value),
4205            Ok(Signal::None) => Ok(Value::None),
4206            Ok(Signal::Break) => Err(error(line, "break used outside of a loop")),
4207            Ok(Signal::Continue) => Err(error(line, "continue used outside of a loop")),
4208            Err(err) if err.is_try_return => self.pending_try_return.take().ok_or(err),
4209            Err(err) => Err(err),
4210        };
4211        // Allocation accounting can become exceeded during the final
4212        // expression/statement even when that operation returns a nominal
4213        // value. Convert it to a fatal error before reading staged outputs or
4214        // restoring the caller, so no ref target can commit across the limit.
4215        let final_memory_error = result
4216            .is_ok()
4217            .then(|| self.pending_memory_error(line))
4218            .flatten();
4219        if let Some(error) = final_memory_error {
4220            result = Err(error);
4221        }
4222        let staged_result = if result.is_ok() {
4223            ref_positions
4224                .iter()
4225                .map(|position| {
4226                    let name = func.params.get(*position).ok_or_else(|| {
4227                        error(line, "Function parameter mode metadata is invalid")
4228                    })?;
4229                    self.scopes
4230                        .get(1)
4231                        .and_then(|scope| scope.get(name))
4232                        .cloned()
4233                        .ok_or_else(|| {
4234                            error(line, format!("`ref` parameter `{name}` is unavailable"))
4235                        })
4236                })
4237                .collect::<Result<Vec<_>, _>>()
4238        } else {
4239            Ok(Vec::new())
4240        };
4241        let staged_outputs = match staged_result {
4242            Ok(values) => values,
4243            Err(err) => {
4244                result = Err(err);
4245                Vec::new()
4246            }
4247        };
4248        let updated_defining_environment = self
4249            .scopes
4250            .first_mut()
4251            .map(core::mem::take)
4252            .unwrap_or_default();
4253        let updated_defining_origins = core::mem::take(&mut self.binding_origins);
4254        put_live_environment(
4255            &self.live_value_environments,
4256            &function_module,
4257            updated_defining_environment,
4258            &updated_defining_origins,
4259        );
4260        self.live_binding_origins
4261            .borrow_mut()
4262            .insert(function_module, updated_defining_origins);
4263        let restored_caller_environment = take_live_environment(
4264            &self.live_value_environments,
4265            &caller_value_module,
4266            &caller_binding_origins,
4267        );
4268        if let Some(scope) = saved_scopes.first_mut() {
4269            *scope = restored_caller_environment;
4270        } else {
4271            saved_scopes.push(restored_caller_environment);
4272        }
4273        self.scopes = saved_scopes;
4274        self.binding_origins = caller_binding_origins;
4275        self.active_value_module = caller_value_module;
4276        self.type_bindings.truncate(type_scope_floor);
4277        self.module_aliases.truncate(alias_scope_floor);
4278        self.imported_functions.truncate(alias_scope_floor);
4279        self.alias_scope_floors.pop();
4280        self.import_scopes.truncate(alias_scope_floor);
4281        self.active_lexical_contexts.pop();
4282        self.function_modules.pop();
4283        self.call_depth -= 1;
4284        self.leave_nesting(nesting);
4285        self.active_ref_bindings = saved_ref_bindings;
4286        self.active_capture_bindings = saved_capture_bindings;
4287
4288        match result {
4289            Ok(value) => Ok((value, staged_outputs)),
4290            Err(err) => {
4291                // A runtime error escaping the fn body carries line
4292                // numbers from the fn's *defining* module, not the
4293                // caller's source. Attach the owning module so
4294                // rendering never quotes an unrelated root-file (or
4295                // outer-module) line. Deepest context wins, so a
4296                // nested call that already attached its own module
4297                // is preserved; root-declared fns attach the root
4298                // sentinel, which renders as plain root source but
4299                // blocks an enclosing module fn (e.g. one invoking
4300                // a root callback) from claiming the error.
4301                let owner = func
4302                    .module_path
4303                    .as_deref()
4304                    .unwrap_or(crate::value::ROOT_MODULE_PATH);
4305                Err(err.with_module(owner))
4306            }
4307        }
4308    }
4309
4310    /// Implement the `try_call(f)` builtin.
4311    ///
4312    /// Takes a zero-arg callable `f` and invokes it. On a clean
4313    /// return, yields `Result::Ok(value)`. On a **non-fatal**
4314    /// `NyblError`, yields `Result::Err(RuntimeError { message,
4315    /// line })` — both values are constructed directly by
4316    /// `nybl::builtins::make_try_call_ok` / `_err`, so they
4317    /// work even in programs that never declared `Result` or
4318    /// `RuntimeError` themselves.
4319    ///
4320    /// Fatal errors (resource-limit violations — see
4321    /// `NyblError::is_fatal`) bypass the wrap and propagate
4322    /// unchanged, preserving the sandbox invariant.
4323    fn builtin_try_call(&mut self, args: Vec<Value>, line: u32) -> Result<Value, NyblError> {
4324        if args.len() != 1 {
4325            return Err(error(
4326                line,
4327                format!("`try_call` expects 1 argument, but got {}", args.len()),
4328            ));
4329        }
4330        let callable = args.into_iter().next().unwrap();
4331        let func = match &callable {
4332            Value::Fn(f) => Rc::clone(f),
4333            other => {
4334                return Err(error(
4335                    line,
4336                    format!("`try_call` expects a function, got {}", other.type_name()),
4337                ));
4338            }
4339        };
4340        drop(callable);
4341        let result = match self.call_nybl_fn(&func, Vec::new(), line) {
4342            Ok(value) => builtins::make_try_call_ok_in(value, line, &self.memory),
4343            Err(err) => {
4344                if err.is_fatal {
4345                    Err(err)
4346                } else {
4347                    Ok(builtins::make_try_call_err_in(&err, &self.memory))
4348                }
4349            }
4350        };
4351        if result.is_ok() && self.memory.__exceeded() {
4352            Err(error_fatal_with_hint(
4353                line,
4354                "Memory limit exceeded",
4355                "Your code is using too much memory. Check for large strings or arrays growing in loops.",
4356            ))
4357        } else {
4358            result
4359        }
4360    }
4361
4362    fn call_function(
4363        &mut self,
4364        name: &str,
4365        args: Vec<Value>,
4366        line: u32,
4367        resolved_function: Option<FunctionDefinition>,
4368    ) -> Result<Value, NyblError> {
4369        // Executed lexical function declarations shadow engine builtins while
4370        // preserving the established host-before-named-function precedence.
4371        // Direct-call classification passes the canonical declaration here,
4372        // avoiding a second lookup.
4373        if let Some(func) = resolved_function {
4374            if let Some(result) = self.host.call(name, &args, line) {
4375                return result;
4376            }
4377            return self.call_nybl_fn(&func, args, line);
4378        }
4379
4380        // 1. Global builtins. The short list: anything variadic
4381        // (`print`), a collection constructor (`range`), session-
4382        // stateful (`rand`), or inherently takes a callable
4383        // (`try_call`). Every other global builtin that used to
4384        // live here is now a method on the receiver's type —
4385        // see `methods::common_method` and `methods::numeric_method`.
4386        match name {
4387            // Runtime backstop for host-disabled builtins: a call the
4388            // load-time pass could not prove (a shadowing binding
4389            // exists somewhere) still dies — fatally, so `try_call`
4390            // can't swallow it — the moment it reaches the builtin.
4391            "range" | "rand" | "print" | "try_call" | "panic"
4392                if !self.limits.disabled_builtins.is_empty()
4393                    && self.limits.disabled_builtins.contains(name) =>
4394            {
4395                return Err(crate::check::disabled_builtin_error(name, line));
4396            }
4397            "range" => {
4398                return builtins::builtin_range_in(&args, line, &mut self.rand_state, &self.memory);
4399            }
4400            "rand" => return builtins::builtin_rand(&args, line, &mut self.rand_state),
4401            "print" => {
4402                let message =
4403                    crate::formatting::__format_values_in(&args, " ", line, &self.memory)?;
4404                self.host.on_print(&message);
4405                if let Some(error) = self.host.print_error(line) {
4406                    return Err(error);
4407                }
4408                return Ok(Value::None);
4409            }
4410            "try_call" => return self.builtin_try_call(args, line),
4411            "panic" => return builtins::builtin_panic(&args, line),
4412            _ => {}
4413        }
4414
4415        // 2. Host-provided builtins
4416        let host_result = self.host.call(name, &args, line);
4417        if let Some(result) = host_result {
4418            return result;
4419        }
4420
4421        // 3. A dynamically published/imported user function not classified
4422        // by the direct-call path above.
4423        let func = self.lookup_function(name).ok_or_else(|| {
4424            // Preference order: "did you mean" suggestion first
4425            // (most specific to the user's typo), then the
4426            // host's generic function hint (embedder-specific
4427            // tips like "available host functions: …"), then a
4428            // bare error.
4429            if let Some(hint) = self.callable_candidates_hint(name) {
4430                error_with_hint(line, crate::error_messages::function_not_found(name), hint)
4431            } else {
4432                let host_hint = self.host.function_hint().to_string();
4433                if host_hint.is_empty() {
4434                    error(line, crate::error_messages::function_not_found(name))
4435                } else {
4436                    error_with_hint(
4437                        line,
4438                        crate::error_messages::function_not_found(name),
4439                        host_hint,
4440                    )
4441                }
4442            }
4443        })?;
4444
4445        self.call_nybl_fn(&func, args, line)
4446    }
4447
4448    // ─── Methods ───────────────────────────────────────────────────
4449
4450    /// Full method dispatch: user methods win, then common,
4451    /// then type-specific (via [`Self::call_method`]). This is
4452    /// what call sites outside the `MethodCall` arm (for-loop
4453    /// iterator protocol, future trait-like uses) want — the
4454    /// normal `MethodCall` path inlines the same logic.
4455    fn call_method_full(
4456        &mut self,
4457        obj: &Value,
4458        method: &str,
4459        args: Vec<Value>,
4460        line: u32,
4461    ) -> Result<Value, NyblError> {
4462        // User-method dispatch first — matches MethodCall's
4463        // priority so `fn MyType.iter(self)` wins over any
4464        // built-in method of the same name.
4465        let type_key: Option<(String, String)> = match obj {
4466            Value::Struct(s) => Some((s.module_path().to_string(), s.type_name().to_string())),
4467            Value::EnumVariant(e) => Some((e.module_path().to_string(), e.type_name().to_string())),
4468            _ => None,
4469        };
4470        if let Some(key) = type_key {
4471            let user = self
4472                .methods
4473                .get(&key)
4474                .and_then(|ms| ms.get(method))
4475                .cloned();
4476            if let Some(m) = user {
4477                if !crate::ref_params::accepts_arity(&m.param_modes, args.len() + 1) {
4478                    let required = crate::ref_params::required_arity(&m.param_modes);
4479                    let variadic = matches!(m.param_modes.last(), Some(ParamMode::Rest));
4480                    return Err(error(
4481                        line,
4482                        if variadic {
4483                            format!(
4484                                "`{}.{method}` expects at least {required} arguments (including `self`), but got {}",
4485                                key.1,
4486                                args.len() + 1
4487                            )
4488                        } else {
4489                            format!(
4490                                "`{}.{method}` expects {required} argument{} (including `self`), but got {}",
4491                                key.1,
4492                                if required == 1 { "" } else { "s" },
4493                                args.len() + 1
4494                            )
4495                        },
4496                    ));
4497                }
4498                let mut full_args = Vec::with_capacity(args.len() + 1);
4499                full_args.push(obj.clone());
4500                full_args.extend(args);
4501                return self.call_nybl_fn(&m, full_args, line);
4502            }
4503        }
4504        // Fall through to the built-in dispatch.
4505        let (ret, _mutated) = self.call_method(obj, method, &args, line)?;
4506        Ok(ret)
4507    }
4508
4509    fn call_method(
4510        &mut self,
4511        obj: &Value,
4512        method: &str,
4513        args: &[Value],
4514        line: u32,
4515    ) -> Result<(Value, Option<Value>), NyblError> {
4516        // `type` / `to_str` / `inspect` work on every value.
4517        // Try the shared dispatcher first so we don't have to
4518        // duplicate those three names across every type-
4519        // specific method table.
4520        if let Some(result) = methods::common_method_in(obj, method, args, line, &self.memory)? {
4521            return Ok(result);
4522        }
4523        // Built-in Result combinators (`is_ok`, `is_err`,
4524        // `unwrap`, `expect`, `unwrap_or`). Callable-taking
4525        // variants (`map`, `map_err`, `and_then`) are dispatched
4526        // one level up in the MethodCall arm so they can invoke
4527        // the user callable via `call_value`.
4528        if methods::is_builtin_result(obj)
4529            && let Some(v) = methods::result_method(obj, method, args, line)?
4530        {
4531            return Ok((v, None));
4532        }
4533        match obj {
4534            Value::Array(arr) => methods::array_method_in(arr, method, args, line, &self.memory),
4535            Value::Str(s) => methods::string_method_in(s, method, args, line, &self.memory),
4536            Value::Dict(entries) => {
4537                methods::dict_method_in(entries, method, args, line, &self.memory)
4538            }
4539            Value::Int(_) | Value::Number(_) => methods::numeric_method(obj, method, args, line),
4540            Value::Bool(_) => methods::bool_method(obj, method, args, line),
4541            Value::Iter(_) => methods::iter_method_in(obj, method, args, line, &self.memory),
4542            Value::Host(value) => match self.host.call_method(value, method, args, line) {
4543                Some(result) => result.map(|value| (value, None)),
4544                None => Err(error(
4545                    line,
4546                    crate::error_messages::no_such_method(obj.type_name(), method),
4547                )),
4548            },
4549            _ => Err(error(
4550                line,
4551                crate::error_messages::no_such_method(obj.type_name(), method),
4552            )),
4553        }
4554    }
4555
4556    /// Handle `r.map(f)`, `r.map_err(f)`, `r.and_then(f)` for a
4557    /// built-in `Result` receiver. Factored out of the
4558    /// `MethodCall` arm so the evaluator / VM / AOT can keep the
4559    /// same shape.
4560    fn call_result_callable_method(
4561        &mut self,
4562        receiver: &Value,
4563        kind: methods::ResultCallableKind,
4564        method: &str,
4565        args: Vec<Value>,
4566        line: u32,
4567    ) -> Result<Value, NyblError> {
4568        use crate::builtins::expect_args;
4569        use methods::{ResultCallableKind, make_result_err_in, make_result_ok_in};
4570        expect_args(method, &args, 1, line)?;
4571        let callable = args
4572            .into_iter()
4573            .next()
4574            .expect("expect_args ensured len = 1");
4575        let variant_info = match receiver {
4576            Value::EnumVariant(e) => e,
4577            _ => return Err(error(line, "Result method called on non-Result")),
4578        };
4579        let payload = match variant_info.payload() {
4580            crate::value::EnumPayload::Tuple(items) if items.len() == 1 => items[0].clone(),
4581            // Unreachable for the built-in shape, but keep the
4582            // error clean rather than panicking.
4583            _ => {
4584                return Err(error(
4585                    line,
4586                    format!("malformed Result::{} payload", variant_info.variant()),
4587                ));
4588            }
4589        };
4590        let is_ok = variant_info.variant() == "Ok";
4591        match kind {
4592            ResultCallableKind::Map => {
4593                if is_ok {
4594                    let new_value = self.call_value(callable, vec![payload], line, Some(method))?;
4595                    make_result_ok_in(new_value, line, &self.memory)
4596                } else {
4597                    // Err passes through unchanged. Rebuild it so
4598                    // the caller sees the same type identity —
4599                    // matches the pure-Nybl combinator's behaviour.
4600                    make_result_err_in(payload, line, &self.memory)
4601                }
4602            }
4603            ResultCallableKind::MapErr => {
4604                if !is_ok {
4605                    let new_value = self.call_value(callable, vec![payload], line, Some(method))?;
4606                    make_result_err_in(new_value, line, &self.memory)
4607                } else {
4608                    make_result_ok_in(payload, line, &self.memory)
4609                }
4610            }
4611            ResultCallableKind::AndThen => {
4612                if is_ok {
4613                    // `f` is expected to return a Result; we
4614                    // surface whatever it returns verbatim. A
4615                    // match on the returned shape at the call
4616                    // site catches misuse.
4617                    self.call_value(callable, vec![payload], line, Some(method))
4618                } else {
4619                    make_result_err_in(payload, line, &self.memory)
4620                }
4621            }
4622        }
4623    }
4624}
4625
4626// ─── Pattern matching ──────────────────────────────────────────────
4627//
4628// `pattern_matches` returns true if `value` fits `pattern`, filling
4629// `bindings` with every `Binding` name along the way. On a partial
4630// match it's the caller's responsibility to discard the bindings
4631// — `eval_match` does this by only consuming them after the match
4632// + guard both succeed.
4633
4634/// Destructured view of an `Iter::Next(v) | Iter::Done` result.
4635/// Returned by [`unwrap_iter_result`] so the for-loop can bind
4636/// the payload cleanly without repeating the pattern-match.
4637enum IterStep {
4638    Next(Value),
4639    Done,
4640}
4641
4642/// Inspect a value returned from an iterator's `.next()` method.
4643/// Returns `Some(step)` when the value is a well-formed
4644/// `Iter::Next(v)` / `Iter::Done` (built-in or not), or `None`
4645/// when it doesn't match so the caller can raise a clear error.
4646fn unwrap_iter_result(v: &Value) -> Option<IterStep> {
4647    let e = match v {
4648        Value::EnumVariant(e) => e,
4649        _ => return None,
4650    };
4651    if e.type_name() != "Iter" {
4652        return None;
4653    }
4654    match (e.variant(), e.payload()) {
4655        ("Next", crate::value::EnumPayload::Tuple(items)) if items.len() == 1 => {
4656            Some(IterStep::Next(items[0].clone()))
4657        }
4658        ("Done", crate::value::EnumPayload::Unit) => Some(IterStep::Done),
4659        _ => None,
4660    }
4661}
4662
4663type BuiltinTypeTables = (
4664    BTreeMap<(String, String), Vec<String>>,
4665    BTreeMap<(String, String), Vec<VariantDecl>>,
4666    BTreeMap<String, String>,
4667);
4668
4669/// Seed a fresh evaluator's type tables with the engine-wide
4670/// builtin types (`Result`, `RuntimeError`). The shapes come from
4671/// `crate::builtins` so walker / VM / AOT can never drift out of
4672/// sync — they all read the same source.
4673///
4674/// Returns:
4675/// - struct_defs keyed by `(module_path, type_name)` with the
4676///   builtin registered under `<builtin>`;
4677/// - enum_defs keyed the same way;
4678/// - a bare-name → module_path map seeded with entries for every
4679///   builtin, so the program's outermost scope can resolve
4680///   bare `Result::Ok(...)` and `RuntimeError { ... }` without
4681///   an explicit `use`.
4682fn seed_builtin_types() -> BuiltinTypeTables {
4683    use crate::value::BUILTIN_MODULE_PATH;
4684    let mut struct_defs: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
4685    let mut enum_defs: BTreeMap<(String, String), Vec<VariantDecl>> = BTreeMap::new();
4686    let mut type_bindings: BTreeMap<String, String> = BTreeMap::new();
4687    struct_defs.insert(
4688        (
4689            String::from(BUILTIN_MODULE_PATH),
4690            String::from("RuntimeError"),
4691        ),
4692        crate::builtins::builtin_runtime_error_fields(),
4693    );
4694    type_bindings.insert(
4695        String::from("RuntimeError"),
4696        String::from(BUILTIN_MODULE_PATH),
4697    );
4698    enum_defs.insert(
4699        (String::from(BUILTIN_MODULE_PATH), String::from("Result")),
4700        crate::builtins::builtin_result_variants(),
4701    );
4702    type_bindings.insert(String::from("Result"), String::from(BUILTIN_MODULE_PATH));
4703    enum_defs.insert(
4704        (String::from(BUILTIN_MODULE_PATH), String::from("Iter")),
4705        crate::builtins::builtin_iter_variants(),
4706    );
4707    type_bindings.insert(String::from("Iter"), String::from(BUILTIN_MODULE_PATH));
4708    (struct_defs, enum_defs, type_bindings)
4709}
4710
4711/// True when two enum declarations describe the same runtime
4712/// shape. Strictly looser than `PartialEq` on `Vec<VariantDecl>`:
4713/// tuple variants compare by *arity* only (their payload field
4714/// names are positional stubs with no runtime meaning), while
4715/// struct variants still require matching field names. Same for
4716/// the outer variant ordering — positional.
4717///
4718/// Used by the "redeclare-same-shape" rules so a user program
4719/// that declares `enum Result { Ok(v), Err(e) }` is compatible
4720/// with the engine's builtin `enum Result { Ok(value), Err(error) }`.
4721fn variants_equivalent(a: &[VariantDecl], b: &[VariantDecl]) -> bool {
4722    if a.len() != b.len() {
4723        return false;
4724    }
4725    for (va, vb) in a.iter().zip(b.iter()) {
4726        if va.name != vb.name {
4727            return false;
4728        }
4729        match (&va.kind, &vb.kind) {
4730            (VariantKind::Unit, VariantKind::Unit) => {}
4731            (VariantKind::Tuple(fa), VariantKind::Tuple(fb)) => {
4732                if fa.len() != fb.len() {
4733                    return false;
4734                }
4735            }
4736            (VariantKind::Struct(fa), VariantKind::Struct(fb)) => {
4737                if fa != fb {
4738                    return false;
4739                }
4740            }
4741            _ => return false,
4742        }
4743    }
4744    true
4745}
4746
4747/// Walk a pair of scope stacks to resolve a source-level type
4748/// reference. This is free-standing so the
4749/// pattern matcher can be called with a borrow of the
4750/// evaluator's tables without needing the evaluator itself.
4751/// Returns `None` if the name isn't in scope.
4752///
4753/// `module_aliases` is the persistent map of aliased `use`
4754/// modules so namespaced references (`m.Color`) resolve even
4755/// inside function bodies, where `scopes` no longer contains
4756/// `m` (the function call stack is reset per-call).
4757pub fn resolve_type_in(
4758    value_scopes: &[BTreeMap<String, Value>],
4759    type_scopes: &[BTreeMap<String, String>],
4760    module_aliases: &BTreeMap<String, Rc<crate::value::NyblModule>>,
4761    namespace: Option<&str>,
4762    type_name: &str,
4763) -> Option<String> {
4764    resolve_type_in_scoped(
4765        value_scopes,
4766        type_scopes,
4767        core::slice::from_ref(module_aliases),
4768        None,
4769        namespace,
4770        type_name,
4771    )
4772}
4773
4774fn resolve_type_in_evaluator_context(
4775    value_scopes: &[BTreeMap<String, Value>],
4776    type_scopes: &[BTreeMap<String, String>],
4777    module_aliases: &[BTreeMap<String, Rc<crate::value::NyblModule>>],
4778    local_floor: Option<usize>,
4779    defining_context: Option<&ModuleLexicalContext>,
4780    namespace: Option<&str>,
4781    type_name: &str,
4782) -> Option<String> {
4783    if let Some(namespace) = namespace {
4784        for scope in value_scopes.iter().rev() {
4785            if let Some(value) = scope.get(namespace) {
4786                return match value {
4787                    Value::Module(module) => module.type_origin(type_name).map(str::to_string),
4788                    _ => None,
4789                };
4790            }
4791        }
4792        for (index, aliases) in module_aliases.iter().enumerate().rev() {
4793            if local_floor.is_some_and(|floor| index < floor) {
4794                continue;
4795            }
4796            if let Some(module) = aliases.get(namespace) {
4797                return module.type_origin(type_name).map(str::to_string);
4798            }
4799        }
4800        return defining_context
4801            .and_then(|context| context.module_aliases.get(namespace))
4802            .and_then(|module| module.type_origin(type_name).map(str::to_string));
4803    }
4804
4805    for (index, bindings) in type_scopes.iter().enumerate().rev() {
4806        if local_floor.is_some_and(|floor| index < floor) {
4807            continue;
4808        }
4809        if let Some(module_path) = bindings.get(type_name) {
4810            return Some(module_path.clone());
4811        }
4812    }
4813    defining_context.and_then(|context| context.type_bindings.get(type_name).cloned())
4814}
4815
4816/// Scoped variant used by evaluators that retain one module-alias frame per
4817/// lexical value scope. At call time the defining module's context is copied
4818/// at `alias_scope_floor`, so every caller frame below that floor is hidden.
4819#[doc(hidden)]
4820pub fn resolve_type_in_scoped<T, A>(
4821    value_scopes: &[BTreeMap<String, Value>],
4822    type_scopes: &[T],
4823    module_aliases: &[A],
4824    alias_scope_floor: Option<usize>,
4825    namespace: Option<&str>,
4826    type_name: &str,
4827) -> Option<String>
4828where
4829    T: core::borrow::Borrow<BTreeMap<String, String>>,
4830    A: core::borrow::Borrow<BTreeMap<String, Rc<crate::value::NyblModule>>>,
4831{
4832    if let Some(ns) = namespace {
4833        // First: look the alias up in value scopes (catches
4834        // locally-bound modules, if any). Then fall back to
4835        // the evaluator-level alias map so function bodies can
4836        // reach module-level aliases even when their own value
4837        // scope is empty.
4838        for scope in value_scopes.iter().rev() {
4839            if let Some(value) = scope.get(ns) {
4840                if let Value::Module(module) = value {
4841                    return module.type_origin(type_name).map(str::to_string);
4842                }
4843                return None;
4844            }
4845        }
4846        for (index, frame) in module_aliases.iter().enumerate().rev() {
4847            if alias_scope_floor.is_some_and(|floor| index < floor) {
4848                continue;
4849            }
4850            if let Some(module) = frame.borrow().get(ns) {
4851                return module.type_origin(type_name).map(str::to_string);
4852            }
4853        }
4854        return None;
4855    }
4856    for (index, scope) in type_scopes.iter().enumerate().rev() {
4857        if alias_scope_floor.is_some_and(|floor| index < floor) {
4858            continue;
4859        }
4860        if let Some(mp) = scope.borrow().get(type_name) {
4861            return Some(mp.clone());
4862        }
4863    }
4864    None
4865}
4866
4867/// Resolver that turns a source-level type reference — optional
4868/// namespace plus bare name (`m.Color` vs plain `Color`) — into
4869/// the declaring module's path. Pattern matching threads this
4870/// through so a pattern like `Color::Red` only matches values
4871/// whose module identity agrees with the current scope's binding
4872/// of `Color`.
4873///
4874/// Returning `None` means "no type with this name is visible in
4875/// the calling scope" — the matcher treats that as a mismatch
4876/// rather than a fallback, to avoid silently matching a
4877/// same-named type from a different module.
4878pub type TypeResolveFn<'a> = &'a dyn Fn(Option<&str>, &str) -> Option<String>;
4879
4880/// Attempt to match `pattern` against `value`. On success, appends
4881/// any captured `(name, Value)` bindings to `bindings` and returns
4882/// `true`; on failure, returns `false` and leaves `bindings` in an
4883/// undefined state — it's the caller's responsibility to discard it.
4884///
4885/// `resolver` is consulted whenever a pattern names a user type
4886/// (`Pattern::Struct` or `Pattern::EnumVariant`) so the matcher
4887/// can compare the value's full identity `(module_path,
4888/// type_name)` against the source-level reference.
4889///
4890/// Exported so other engines (the bytecode VM, AOT transpiler)
4891/// can run the exact same structural matcher as the tree-walker
4892/// without re-implementing the rules.
4893pub fn pattern_matches(
4894    pattern: &Pattern,
4895    value: &Value,
4896    bindings: &mut Vec<(String, Value)>,
4897    resolver: TypeResolveFn<'_>,
4898) -> bool {
4899    pattern_matches_in(
4900        pattern,
4901        value,
4902        bindings,
4903        resolver,
4904        &crate::memory::MemoryContext::__legacy_current(),
4905    )
4906}
4907
4908#[doc(hidden)]
4909pub fn pattern_matches_in(
4910    pattern: &Pattern,
4911    value: &Value,
4912    bindings: &mut Vec<(String, Value)>,
4913    resolver: TypeResolveFn<'_>,
4914    memory: &crate::memory::MemoryContext,
4915) -> bool {
4916    match pattern {
4917        Pattern::Wildcard => true,
4918        Pattern::Binding(name) => {
4919            bindings.push((name.clone(), value.clone()));
4920            true
4921        }
4922        Pattern::Literal(lit) => match (lit, value) {
4923            (LiteralPattern::Int(a), Value::Int(b)) => a == b,
4924            (LiteralPattern::Number(a), Value::Number(b)) => a == b,
4925            // Cross-type numeric literal patterns — same rule
4926            // as `values_equal`: `match 1 { 1.0 => ... }` and
4927            // `match 1.0 { 1 => ... }` both match.
4928            (LiteralPattern::Int(a), Value::Number(b)) => (*a as f64) == *b,
4929            (LiteralPattern::Number(a), Value::Int(b)) => *a == (*b as f64),
4930            (LiteralPattern::Str(a), Value::Str(b)) => a.as_str() == b.as_str(),
4931            (LiteralPattern::Bool(a), Value::Bool(b)) => a == b,
4932            (LiteralPattern::None, Value::None) => true,
4933            _ => false,
4934        },
4935        Pattern::EnumVariant {
4936            namespace,
4937            type_name,
4938            variant,
4939            payload,
4940        } => {
4941            let ev = match value {
4942                Value::EnumVariant(e) => e,
4943                _ => return false,
4944            };
4945            // Full identity check: resolve the pattern's type
4946            // reference to a module path, then compare against
4947            // the value's own module path.
4948            let expected_mp = match resolver(namespace.as_deref(), type_name) {
4949                Some(mp) => mp,
4950                None => return false,
4951            };
4952            if ev.module_path() != expected_mp.as_str()
4953                || ev.type_name() != type_name.as_str()
4954                || ev.variant() != variant.as_str()
4955            {
4956                return false;
4957            }
4958            match (payload, ev.payload()) {
4959                (VariantPatternPayload::Unit, crate::value::EnumPayload::Unit) => true,
4960                (VariantPatternPayload::Tuple(pats), crate::value::EnumPayload::Tuple(items)) => {
4961                    if pats.len() != items.len() {
4962                        return false;
4963                    }
4964                    for (p, v) in pats.iter().zip(items.iter()) {
4965                        if !pattern_matches_in(p, v, bindings, resolver, memory) {
4966                            return false;
4967                        }
4968                    }
4969                    true
4970                }
4971                (
4972                    VariantPatternPayload::Struct { fields, rest },
4973                    crate::value::EnumPayload::Struct(entries),
4974                ) => match_struct_fields(fields, *rest, entries, bindings, resolver, memory),
4975                _ => false,
4976            }
4977        }
4978        Pattern::Struct {
4979            namespace,
4980            type_name,
4981            fields,
4982            rest,
4983        } => {
4984            let st = match value {
4985                Value::Struct(s) => s,
4986                _ => return false,
4987            };
4988            let expected_mp = match resolver(namespace.as_deref(), type_name) {
4989                Some(mp) => mp,
4990                None => return false,
4991            };
4992            if st.module_path() != expected_mp.as_str() || st.type_name() != type_name.as_str() {
4993                return false;
4994            }
4995            match_struct_fields(fields, *rest, st.fields(), bindings, resolver, memory)
4996        }
4997        Pattern::Array { elements, rest } => {
4998            let items = match value {
4999                Value::Array(arr) => arr,
5000                _ => return false,
5001            };
5002            match rest {
5003                None => {
5004                    if elements.len() != items.len() {
5005                        return false;
5006                    }
5007                    for (p, v) in elements.iter().zip(items.iter()) {
5008                        if !pattern_matches_in(p, v, bindings, resolver, memory) {
5009                            return false;
5010                        }
5011                    }
5012                    true
5013                }
5014                Some(rest_kind) => {
5015                    if items.len() < elements.len() {
5016                        return false;
5017                    }
5018                    for (i, p) in elements.iter().enumerate() {
5019                        if !pattern_matches_in(p, &items[i], bindings, resolver, memory) {
5020                            return false;
5021                        }
5022                    }
5023                    if let ArrayRest::Named(name) = rest_kind {
5024                        let tail: Vec<Value> = items[elements.len()..].to_vec();
5025                        bindings.push((
5026                            name.clone(),
5027                            Value::__try_new_array_in(tail, 0, memory)
5028                                .expect("an array-rest slice cannot increase ownership depth"),
5029                        ));
5030                    }
5031                    true
5032                }
5033            }
5034        }
5035        Pattern::Or(alts) => {
5036            for alt in alts {
5037                let mut attempt: Vec<(String, Value)> = Vec::new();
5038                if pattern_matches_in(alt, value, &mut attempt, resolver, memory) {
5039                    bindings.extend(attempt);
5040                    return true;
5041                }
5042            }
5043            false
5044        }
5045    }
5046}
5047
5048fn match_struct_fields(
5049    fields: &[(String, Pattern)],
5050    rest: bool,
5051    entries: &[(String, Value)],
5052    bindings: &mut Vec<(String, Value)>,
5053    resolver: TypeResolveFn<'_>,
5054    memory: &crate::memory::MemoryContext,
5055) -> bool {
5056    // Every declared field-pattern must find its value in the
5057    // struct. `rest` just relaxes the requirement that *every*
5058    // value's key must appear in the pattern — non-rest patterns
5059    // may still leave fields unmatched, which is fine: the walker
5060    // matches named-field lookup semantics, not whole-shape
5061    // destructuring.
5062    let _ = rest;
5063    for (fname, pat) in fields {
5064        let value = match entries.iter().find(|(k, _)| k == fname) {
5065            Some((_, v)) => v,
5066            None => return false,
5067        };
5068        if !pattern_matches_in(pat, value, bindings, resolver, memory) {
5069            return false;
5070        }
5071    }
5072    true
5073}
5074
5075// ─── REPL session ──────────────────────────────────────────────────
5076//
5077// `Evaluator` itself is a one-shot: `Evaluator::new(host, limits)` +
5078// `eval.run(stmts)` + drop. That's the right shape for running a
5079// complete program from top to bottom. REPL workloads need the
5080// opposite: fresh *input* evaluated against *accumulated* state.
5081//
5082// `ReplSession` owns every Evaluator field that should survive
5083// across inputs — scopes, functions, user types, method tables,
5084// import caches, module aliases, rng state. The ephemeral
5085// per-run fields (host, step counter, call depth, the try-
5086// return sentinel slot, transient warnings) stay on the
5087// temporary `Evaluator` that the session spins up for each
5088// `eval` call.
5089//
5090// The session model also handles REPL-specific niceties:
5091//
5092//   - Bare expression statements at the end of an input yield
5093//     their value back to the caller, so the REPL can echo it.
5094//     `let x = 5` returns None; `x + 1` returns Some(Value).
5095//   - Scope depth is normalised back to the root on each
5096//     `eval` — if an earlier input errored mid-block, we
5097//     don't leave half-pushed scopes lying around for the next
5098//     input to trip over.
5099
5100/// Persistent state for an interactive REPL session. Build
5101/// once with [`Self::new`], then call [`Self::eval`] for each
5102/// fresh line / block the user types. State carried across
5103/// calls: every `let` / `const` / `fn` / `struct` / `enum` /
5104/// method declaration, every `use`'d module's bindings and
5105/// aliases, the global rng seed, and the import cache.
5106///
5107/// A `ReplSession` is not a sandboxing boundary — embedders
5108/// that want a fresh identity between inputs should construct
5109/// a new session. Resource limits (steps, memory) are supplied
5110/// per `eval` call since they reset each time.
5111pub struct ReplSession {
5112    scopes: Vec<BTreeMap<String, Value>>,
5113    functions: BTreeMap<String, FunctionDefinition>,
5114    binding_origins: BTreeMap<String, (String, String)>,
5115    abi_declarations: Vec<(String, Visibility, Rc<NyblFn>)>,
5116    live_value_environments: LiveValueEnvironments,
5117    live_binding_origins: LiveBindingOrigins,
5118    active_value_module: String,
5119    function_origin: NyblFnOrigin,
5120    current_module: String,
5121    struct_defs: BTreeMap<(String, String), Vec<String>>,
5122    enum_defs: BTreeMap<(String, String), Vec<VariantDecl>>,
5123    methods: BTreeMap<(String, String), BTreeMap<String, FunctionDefinition>>,
5124    type_exports: BTreeMap<String, String>,
5125    type_bindings: Vec<BTreeMap<String, String>>,
5126    module_aliases: Vec<BTreeMap<String, Rc<crate::value::NyblModule>>>,
5127    imported_functions: Vec<BTreeMap<String, FunctionDefinition>>,
5128    root_lexical_context: Rc<ModuleLexicalContext>,
5129    imports: ImportCache,
5130    import_scopes: Vec<ImportScope>,
5131    rand_state: u64,
5132}
5133
5134impl Default for ReplSession {
5135    fn default() -> Self {
5136        Self::new()
5137    }
5138}
5139
5140impl ReplSession {
5141    pub(crate) fn validate_instance_callable(
5142        &self,
5143        callable: &Value,
5144        arg_count: usize,
5145    ) -> Result<(), NyblError> {
5146        let function = match callable {
5147            Value::Fn(function) => function,
5148            other => {
5149                return Err(error(
5150                    0,
5151                    format!("expected function, got {}", other.type_name()),
5152                ));
5153            }
5154        };
5155        if !function.__is_allowed_by(&self.function_origin, "walker") {
5156            return Err(error(
5157                0,
5158                "This function belongs to a different Nybl engine instance",
5159            ));
5160        }
5161        if !crate::ref_params::accepts_arity(&function.param_modes, arg_count) {
5162            let required = crate::ref_params::required_arity(&function.param_modes);
5163            let variadic = matches!(function.param_modes.last(), Some(ParamMode::Rest));
5164            return Err(error(
5165                0,
5166                if variadic {
5167                    format!("Function expects at least {required} arguments, but got {arg_count}")
5168                } else {
5169                    format!(
5170                        "Function expects {required} argument{}, but got {arg_count}",
5171                        if required == 1 { "" } else { "s" }
5172                    )
5173                },
5174            ));
5175        }
5176        Ok(())
5177    }
5178
5179    /// Build a fresh session. Type tables are pre-seeded with
5180    /// the engine builtins (`Result`, `RuntimeError`) so
5181    /// `Result::Ok(...)` resolves without an explicit `use`.
5182    pub fn new() -> Self {
5183        let (struct_defs, enum_defs, builtin_bindings) = seed_builtin_types();
5184        let root_lexical_context = Rc::new(ModuleLexicalContext {
5185            type_bindings: Rc::new(builtin_bindings.clone()),
5186            module_aliases: Rc::new(BTreeMap::new()),
5187            imported_functions: Rc::new(BTreeMap::new()),
5188        });
5189        Self {
5190            scopes: vec![BTreeMap::new()],
5191            functions: BTreeMap::new(),
5192            binding_origins: BTreeMap::new(),
5193            abi_declarations: Vec::new(),
5194            live_value_environments: Rc::new(RefCell::new(BTreeMap::new())),
5195            live_binding_origins: Rc::new(RefCell::new(BTreeMap::new())),
5196            active_value_module: String::from(crate::value::ROOT_MODULE_PATH),
5197            function_origin: NyblFnOrigin::__instance("walker"),
5198            current_module: String::from(crate::value::ROOT_MODULE_PATH),
5199            struct_defs,
5200            enum_defs,
5201            methods: BTreeMap::new(),
5202            type_exports: BTreeMap::new(),
5203            type_bindings: vec![builtin_bindings],
5204            module_aliases: vec![BTreeMap::new()],
5205            imported_functions: vec![BTreeMap::new()],
5206            root_lexical_context,
5207            imports: Rc::new(RefCell::new(alloc_import::collections::BTreeMap::new())),
5208            import_scopes: vec![ImportScope::default()],
5209            rand_state: 0,
5210        }
5211    }
5212
5213    /// Look up a binding by name. Convenience for tests and
5214    /// embedders that want to peek at the session's state
5215    /// between `eval` calls — e.g. checking that `let x = 5`
5216    /// actually stuck.
5217    pub fn get(&self, name: &str) -> Option<Value> {
5218        for scope in self.scopes.iter().rev() {
5219            if let Some(v) = scope.get(name) {
5220                return Some(v.clone());
5221            }
5222        }
5223        None
5224    }
5225
5226    /// Every currently-bound name in the root scope, sorted.
5227    /// Handy for REPL introspection commands (`:vars`) and
5228    /// for tab-completers that want to stay honest about
5229    /// what's actually in scope rather than guessing from
5230    /// observed tokens.
5231    pub fn binding_names(&self) -> Vec<String> {
5232        let mut names: Vec<String> = self
5233            .scopes
5234            .first()
5235            .map(|s| s.keys().cloned().collect())
5236            .unwrap_or_default();
5237        for name in self.functions.keys() {
5238            names.push(name.clone());
5239        }
5240        names.sort();
5241        names.dedup();
5242        names
5243    }
5244
5245    /// Parse `source` and run its statements against this
5246    /// session's accumulated state.
5247    ///
5248    /// If the last statement is a bare expression
5249    /// (`ExprStmt`), the session evaluates it and returns its
5250    /// value as `Ok(Some(v))` so the REPL can echo the
5251    /// result. Every other shape — `let x = ...`, `fn foo`,
5252    /// `struct`, `use`, loops — returns `Ok(None)`.
5253    ///
5254    /// Partial failure semantics: if an earlier statement
5255    /// errors, the session's state reflects whatever ran
5256    /// before the failure. That matches what a user would
5257    /// expect from an interactive prompt.
5258    pub fn eval<H: NyblHost + ?Sized>(
5259        &mut self,
5260        source: &str,
5261        host: &mut H,
5262        limits: &NyblLimits,
5263    ) -> Result<Option<Value>, NyblError> {
5264        let stmts = crate::parse(source)?;
5265        self.run_stmts(&stmts, host, limits)
5266    }
5267
5268    /// Like [`Self::eval`] but takes an already-parsed AST.
5269    /// Useful when the caller has already run a
5270    /// `parse_with_warnings` pass and wants to surface
5271    /// warnings before executing.
5272    pub fn run_stmts<H: NyblHost + ?Sized>(
5273        &mut self,
5274        stmts: &[Stmt],
5275        host: &mut H,
5276        limits: &NyblLimits,
5277    ) -> Result<Option<Value>, NyblError> {
5278        let memory = crate::memory::MemoryContext::__new(limits.max_memory);
5279        self.run_stmts_in(stmts, host, limits, &memory)
5280    }
5281
5282    pub(crate) fn run_stmts_in<H: NyblHost + ?Sized>(
5283        &mut self,
5284        stmts: &[Stmt],
5285        host: &mut H,
5286        limits: &NyblLimits,
5287        memory: &crate::memory::MemoryContext,
5288    ) -> Result<Option<Value>, NyblError> {
5289        // If the last stmt is a bare expression we strip it
5290        // off, run the rest, and then evaluate it as an
5291        // expression so we can return its value. Anything
5292        // else runs as a normal statement block.
5293        let (tail_expr, body) = match stmts.last().map(|s| &s.kind) {
5294            Some(StmtKind::ExprStmt(_)) => {
5295                let (last, rest) = stmts.split_last().unwrap();
5296                let expr = match &last.kind {
5297                    StmtKind::ExprStmt(e) => e.clone(),
5298                    _ => unreachable!(),
5299                };
5300                (Some(expr), rest)
5301            }
5302            _ => (None, stmts),
5303        };
5304
5305        // Spin up a temporary Evaluator around the session's
5306        // state. We hand off each field by `mem::take` /
5307        // `clone` of the Rc so the Evaluator owns working
5308        // copies; at the end we unconditionally write the
5309        // (possibly-mutated) state back so partial failures
5310        // still persist whatever changes happened before the
5311        // error.
5312        let mut eval = self.take_evaluator(host, limits.clone(), memory.clone());
5313        let mut result: Result<Option<Value>, NyblError> = (|| {
5314            // The evaluated top level (including a tail expression) is the
5315            // first active frame of this operation.
5316            eval.enter_nesting(crate::ast_depth::body_depth(stmts), 0)?;
5317            let sig = eval.exec_block(body)?;
5318            match sig {
5319                Signal::Break => Err(error(0, "break used outside of a loop")),
5320                Signal::Continue => Err(error(0, "continue used outside of a loop")),
5321                Signal::Return(_) => Ok(None),
5322                Signal::None => match tail_expr {
5323                    Some(expr) => Ok(Some(eval.eval_expr(&expr)?)),
5324                    None => Ok(None),
5325                },
5326            }
5327        })();
5328        if result.is_ok() && memory.__exceeded() {
5329            result = Err(error_fatal_with_hint(
5330                stmts.last().map_or(0, |stmt| stmt.line),
5331                "Memory limit exceeded",
5332                "Your code is using too much memory. Check for large strings or arrays growing in loops.",
5333            ));
5334        }
5335        self.put_evaluator(eval);
5336        result
5337    }
5338
5339    /// Call a Nybl closure value inside this session's current module state.
5340    ///
5341    /// Embedders that retain closure values from an earlier evaluation can use
5342    /// this to invoke them later while preserving the same functions, imports,
5343    /// type bindings, and module aliases that normal in-language calls see.
5344    pub fn call_fn<H: NyblHost + ?Sized>(
5345        &mut self,
5346        func: Value,
5347        args: Vec<Value>,
5348        host: &mut H,
5349        limits: &NyblLimits,
5350    ) -> Result<Value, NyblError> {
5351        let memory = crate::memory::MemoryContext::__new(limits.max_memory);
5352        self.call_fn_in(func, args, host, limits, &memory)
5353    }
5354
5355    pub(crate) fn call_fn_in<H: NyblHost + ?Sized>(
5356        &mut self,
5357        func: Value,
5358        args: Vec<Value>,
5359        host: &mut H,
5360        limits: &NyblLimits,
5361        memory: &crate::memory::MemoryContext,
5362    ) -> Result<Value, NyblError> {
5363        let func = match &func {
5364            Value::Fn(f) => Rc::clone(f),
5365            other => {
5366                return Err(error(
5367                    0,
5368                    format!("expected function, got {}", other.type_name()),
5369                ));
5370            }
5371        };
5372
5373        let mut eval = self.take_evaluator(host, limits.clone(), memory.clone());
5374        let result = eval.call_nybl_fn(&func, args, 0);
5375        self.put_evaluator(eval);
5376        result
5377    }
5378
5379    pub(crate) fn instance_entries(&self) -> Vec<crate::EntryPoint> {
5380        self.abi_declarations
5381            .iter()
5382            .filter(|(_, visibility, _)| *visibility == Visibility::Public)
5383            .map(|(name, _, target)| {
5384                let required = crate::ref_params::required_arity(&target.param_modes);
5385                if matches!(target.param_modes.last(), Some(ParamMode::Rest)) {
5386                    crate::EntryPoint::__new_variadic(name.clone(), required)
5387                } else {
5388                    crate::EntryPoint::__new(name.clone(), required)
5389                }
5390            })
5391            .collect()
5392    }
5393
5394    pub(crate) fn prepared_entry_target(&self, name: &str) -> Option<Rc<NyblFn>> {
5395        self.abi_declarations
5396            .iter()
5397            .find(|(entry_name, visibility, _)| {
5398                entry_name == name && *visibility == Visibility::Public
5399            })
5400            .map(|(_, _, target)| Rc::clone(target))
5401    }
5402
5403    pub(crate) fn call_prepared_in<H: NyblHost + ?Sized>(
5404        &mut self,
5405        target: &Rc<NyblFn>,
5406        args: &[Value],
5407        host: &mut H,
5408        limits: &NyblLimits,
5409        memory: &crate::memory::MemoryContext,
5410    ) -> Result<Value, NyblError> {
5411        let mut eval = self.take_evaluator(host, limits.clone(), memory.clone());
5412        let result = eval
5413            .call_nybl_fn_with_refs(target, args.to_vec(), &[], 0)
5414            .map(|(value, _)| value);
5415        self.put_evaluator(eval);
5416        result
5417    }
5418
5419    #[allow(clippy::too_many_arguments)]
5420    pub(crate) fn call_prepared_batch_in<H, A>(
5421        &mut self,
5422        target: &Rc<NyblFn>,
5423        name: &str,
5424        arity: usize,
5425        variadic: bool,
5426        calls: &[A],
5427        host: &mut H,
5428        limits: &NyblLimits,
5429        memory: &crate::memory::MemoryContext,
5430    ) -> Result<Vec<Value>, NyblError>
5431    where
5432        H: NyblHost + ?Sized,
5433        A: AsRef<[Value]>,
5434    {
5435        let mut eval = self.take_evaluator(host, limits.clone(), memory.clone());
5436        let mut values = Vec::with_capacity(calls.len());
5437        let result = (|| {
5438            for call in calls {
5439                let args = call.as_ref();
5440                let accepts_arity = if variadic {
5441                    args.len() >= arity
5442                } else {
5443                    args.len() == arity
5444                };
5445                if !accepts_arity {
5446                    return Err(error(
5447                        0,
5448                        if variadic {
5449                            format!(
5450                                "`{name}` expects at least {arity} arguments, but got {}",
5451                                args.len()
5452                            )
5453                        } else {
5454                            format!(
5455                                "`{name}` expects {arity} argument{}, but got {}",
5456                                if arity == 1 { "" } else { "s" },
5457                                args.len()
5458                            )
5459                        },
5460                    ));
5461                }
5462                eval.steps = 0;
5463                debug_assert_eq!(eval.call_depth, 0);
5464                debug_assert_eq!(eval.nesting_used, 0);
5465                let value = eval
5466                    .call_nybl_fn_with_refs(target, args.to_vec(), &[], 0)
5467                    .map(|(value, _)| value);
5468                values.push(value?);
5469            }
5470            Ok(values)
5471        })();
5472        self.put_evaluator(eval);
5473        result
5474    }
5475
5476    pub(crate) fn call_named<H: NyblHost + ?Sized>(
5477        &mut self,
5478        name: &str,
5479        args: &[Value],
5480        host: &mut H,
5481        limits: &NyblLimits,
5482        memory: &crate::memory::MemoryContext,
5483    ) -> Result<Value, NyblError> {
5484        let target = self
5485            .abi_declarations
5486            .iter()
5487            .find(|(entry_name, visibility, _)| {
5488                entry_name == name && *visibility == Visibility::Public
5489            })
5490            .map(|(_, _, target)| Rc::clone(target))
5491            .ok_or_else(|| error(0, format!("Entry point `{name}` is not available")))?;
5492        if !crate::ref_params::accepts_arity(&target.param_modes, args.len()) {
5493            let required = crate::ref_params::required_arity(&target.param_modes);
5494            let variadic = matches!(target.param_modes.last(), Some(ParamMode::Rest));
5495            return Err(error(
5496                0,
5497                if variadic {
5498                    format!(
5499                        "`{name}` expects at least {required} arguments, but got {}",
5500                        args.len()
5501                    )
5502                } else {
5503                    format!(
5504                        "`{name}` expects {required} argument{}, but got {}",
5505                        if required == 1 { "" } else { "s" },
5506                        args.len()
5507                    )
5508                },
5509            ));
5510        }
5511        let mut eval = self.take_evaluator(host, limits.clone(), memory.clone());
5512        let result = eval.call_nybl_fn(&target, args.to_vec(), 0);
5513        self.put_evaluator(eval);
5514        result
5515    }
5516
5517    /// Internal: move the session's state into a fresh
5518    /// Evaluator. `host` and `limits` are the ephemeral
5519    /// per-run bits.
5520    fn take_evaluator<'h, H: NyblHost + ?Sized>(
5521        &mut self,
5522        host: &'h mut H,
5523        limits: NyblLimits,
5524        memory: crate::memory::MemoryContext,
5525    ) -> Evaluator<'h, H> {
5526        let root_lexical_context = core::mem::replace(
5527            &mut self.root_lexical_context,
5528            Rc::new(ModuleLexicalContext::default()),
5529        );
5530        Evaluator {
5531            scopes: core::mem::take(&mut self.scopes),
5532            functions: core::mem::take(&mut self.functions),
5533            binding_origins: core::mem::take(&mut self.binding_origins),
5534            abi_declarations: core::mem::take(&mut self.abi_declarations),
5535            live_value_environments: Rc::clone(&self.live_value_environments),
5536            live_binding_origins: Rc::clone(&self.live_binding_origins),
5537            active_value_module: core::mem::take(&mut self.active_value_module),
5538            function_origin: self.function_origin.clone(),
5539            current_module: core::mem::take(&mut self.current_module),
5540            struct_defs: core::mem::take(&mut self.struct_defs),
5541            enum_defs: core::mem::take(&mut self.enum_defs),
5542            methods: core::mem::take(&mut self.methods),
5543            type_exports: core::mem::take(&mut self.type_exports),
5544            type_bindings: core::mem::take(&mut self.type_bindings),
5545            module_aliases: core::mem::take(&mut self.module_aliases),
5546            imported_functions: core::mem::take(&mut self.imported_functions),
5547            root_lexical_context,
5548            active_lexical_contexts: Vec::new(),
5549            imports: Rc::clone(&self.imports),
5550            import_scopes: core::mem::take(&mut self.import_scopes),
5551            rand_state: self.rand_state,
5552            host,
5553            steps: 0,
5554            loop_lines: Vec::new(),
5555            call_depth: 0,
5556            call_depth_base: 0,
5557            nesting_used: 0,
5558            function_modules: Vec::new(),
5559            alias_scope_floors: Vec::new(),
5560            limits,
5561            memory,
5562            pending_try_return: None,
5563            active_ref_bindings: alloc_import::collections::BTreeSet::new(),
5564            active_capture_bindings: alloc_import::collections::BTreeSet::new(),
5565        }
5566    }
5567
5568    /// Internal: move the Evaluator's state back into the
5569    /// session. Also normalises scope depth back to the root
5570    /// so a mid-block error doesn't leave leftover pushed
5571    /// scopes hanging around for the next input.
5572    fn put_evaluator<'h, H: NyblHost + ?Sized>(&mut self, eval: Evaluator<'h, H>) {
5573        self.root_lexical_context = Rc::clone(&eval.root_lexical_context);
5574        let mut scopes = eval.scopes;
5575        if scopes.len() > 1 {
5576            scopes.truncate(1);
5577        }
5578        if scopes.is_empty() {
5579            scopes.push(BTreeMap::new());
5580        }
5581        let mut type_bindings = eval.type_bindings;
5582        if type_bindings.len() > 1 {
5583            type_bindings.truncate(1);
5584        }
5585        if type_bindings.is_empty() {
5586            // Re-seed so builtins stay visible.
5587            let (_, _, builtins) = seed_builtin_types();
5588            type_bindings.push(builtins);
5589        }
5590        self.scopes = scopes;
5591        self.functions = eval.functions;
5592        self.binding_origins = eval.binding_origins;
5593        self.abi_declarations = eval.abi_declarations;
5594        self.active_value_module = eval.active_value_module;
5595        self.current_module = eval.current_module;
5596        self.struct_defs = eval.struct_defs;
5597        self.enum_defs = eval.enum_defs;
5598        self.methods = eval.methods;
5599        self.type_exports = eval.type_exports;
5600        self.type_bindings = type_bindings;
5601        let mut module_aliases = eval.module_aliases;
5602        if module_aliases.len() > 1 {
5603            module_aliases.truncate(1);
5604        }
5605        if module_aliases.is_empty() {
5606            module_aliases.push(BTreeMap::new());
5607        }
5608        self.module_aliases = module_aliases;
5609        let mut imported_functions = eval.imported_functions;
5610        if imported_functions.len() > 1 {
5611            imported_functions.truncate(1);
5612        }
5613        if imported_functions.is_empty() {
5614            imported_functions.push(BTreeMap::new());
5615        }
5616        self.imported_functions = imported_functions;
5617        let mut import_scopes = eval.import_scopes;
5618        if import_scopes.len() > 1 {
5619            import_scopes.truncate(1);
5620        }
5621        if import_scopes.is_empty() {
5622            import_scopes.push(ImportScope::default());
5623        }
5624        self.import_scopes = import_scopes;
5625        self.rand_state = eval.rand_state;
5626        // `imports` is shared via `Rc` — nothing to do; the
5627        // cache the Evaluator wrote into is the same one the
5628        // session holds.
5629    }
5630}
5631
5632#[cfg(test)]
5633mod tests {
5634    use super::*;
5635
5636    #[derive(Default)]
5637    struct TestHost {
5638        prints: Vec<String>,
5639    }
5640
5641    impl NyblHost for TestHost {
5642        fn call(
5643            &mut self,
5644            _name: &str,
5645            _args: &[Value],
5646            _line: u32,
5647        ) -> Option<Result<Value, NyblError>> {
5648            None
5649        }
5650
5651        fn on_print(&mut self, message: &str) {
5652            self.prints.push(message.to_string());
5653        }
5654    }
5655
5656    fn run(source: &str) -> Vec<String> {
5657        let statements = crate::parse(source).expect("program should parse");
5658        let mut host = TestHost::default();
5659        Evaluator::new(&mut host, crate::NyblLimits::standard())
5660            .run(&statements)
5661            .expect("program should run");
5662        host.prints
5663    }
5664
5665    #[test]
5666    fn named_calls_reuse_one_shared_module_context() {
5667        let mut host = TestHost::default();
5668        let evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5669        let context = evaluator.module_lexical_context(crate::value::ROOT_MODULE_PATH);
5670
5671        assert!(Rc::ptr_eq(&context, &evaluator.root_lexical_context));
5672        assert_eq!(Rc::strong_count(&context), 2);
5673    }
5674
5675    #[test]
5676    fn root_type_publication_reuses_unique_context_storage() {
5677        const DECLARATIONS: usize = 1_024;
5678        let mut source = String::new();
5679        for index in 0..DECLARATIONS {
5680            source.push_str(&format!("struct Type{index} {{}}\n"));
5681        }
5682        let statements = crate::parse(&source).expect("type-heavy source should parse");
5683        let mut host = TestHost::default();
5684        let mut evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5685        let context = Rc::as_ptr(&evaluator.root_lexical_context);
5686        let bindings = Rc::as_ptr(&evaluator.root_lexical_context.type_bindings);
5687
5688        evaluator
5689            .exec_block(&statements)
5690            .expect("declarations should execute");
5691
5692        assert_eq!(Rc::as_ptr(&evaluator.root_lexical_context), context);
5693        assert_eq!(
5694            Rc::as_ptr(&evaluator.root_lexical_context.type_bindings),
5695            bindings
5696        );
5697        assert_eq!(
5698            evaluator.root_lexical_context.type_bindings.len(),
5699            DECLARATIONS + 3
5700        );
5701    }
5702
5703    #[test]
5704    fn restored_lexical_snapshot_forks_without_leaking_abandoned_changes() {
5705        let mut host = TestHost::default();
5706        let mut evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5707        evaluator.publish_root_type_binding("A".to_string(), "root".to_string());
5708        let snapshot = Rc::clone(&evaluator.root_lexical_context);
5709        evaluator.publish_root_type_binding("B".to_string(), "leaked".to_string());
5710
5711        evaluator.root_lexical_context = Rc::clone(&snapshot);
5712        evaluator.publish_root_type_binding("C".to_string(), "root".to_string());
5713
5714        assert_eq!(
5715            evaluator.root_lexical_context.type_bindings.get("A"),
5716            Some(&"root".to_string())
5717        );
5718        assert!(
5719            !evaluator
5720                .root_lexical_context
5721                .type_bindings
5722                .contains_key("B")
5723        );
5724        assert_eq!(
5725            evaluator.root_lexical_context.type_bindings.get("C"),
5726            Some(&"root".to_string())
5727        );
5728    }
5729
5730    #[test]
5731    fn repeated_publication_replaces_in_place_without_retaining_history() {
5732        let mut host = TestHost::default();
5733        let mut evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5734        let bindings = Rc::as_ptr(&evaluator.root_lexical_context.type_bindings);
5735
5736        for index in 0..1_000 {
5737            evaluator.publish_root_type_binding("Repeated".to_string(), index.to_string());
5738        }
5739
5740        assert_eq!(
5741            Rc::as_ptr(&evaluator.root_lexical_context.type_bindings),
5742            bindings
5743        );
5744        assert_eq!(evaluator.root_lexical_context.type_bindings.len(), 4);
5745        assert_eq!(
5746            evaluator.root_lexical_context.type_bindings.get("Repeated"),
5747            Some(&"999".to_string())
5748        );
5749    }
5750
5751    #[test]
5752    fn named_lookups_and_first_class_values_share_one_large_function_ast() {
5753        const UNREACHABLE_STATEMENTS: usize = 4_096;
5754
5755        let mut source = String::from("fn large() { return 7\n");
5756        for _ in 0..UNREACHABLE_STATEMENTS {
5757            source.push_str("none\n");
5758        }
5759        source.push_str("}\n");
5760
5761        let statements = crate::parse(&source).expect("large function should parse");
5762        let mut host = TestHost::default();
5763        let mut evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5764        evaluator
5765            .exec_block(&statements)
5766            .expect("declaration should execute");
5767
5768        let stored = Rc::clone(evaluator.functions.get("large").unwrap());
5769        let first_lookup = evaluator.lookup_function("large").unwrap();
5770        let second_lookup = evaluator.lookup_function("large").unwrap();
5771        assert!(Rc::ptr_eq(&stored, &first_lookup));
5772        assert!(Rc::ptr_eq(&stored, &second_lookup));
5773        assert!(matches!(
5774            &stored.body,
5775            FnBody::Ast(body) if body.len() == UNREACHABLE_STATEMENTS + 1
5776        ));
5777
5778        let calls = crate::parse("let alias = large\nprint(large())\nprint(alias())").unwrap();
5779        evaluator.exec_block(&calls).expect("calls should execute");
5780        let Value::Fn(alias) = evaluator.scopes[0].get("alias").unwrap() else {
5781            panic!("alias should retain the declared function")
5782        };
5783        assert!(Rc::ptr_eq(&stored, alias));
5784        assert_eq!(host.prints, ["7", "7"]);
5785    }
5786
5787    struct FanoutHost {
5788        modules: BTreeMap<String, String>,
5789    }
5790
5791    impl NyblHost for FanoutHost {
5792        fn call(
5793            &mut self,
5794            _name: &str,
5795            _args: &[Value],
5796            _line: u32,
5797        ) -> Option<Result<Value, NyblError>> {
5798            None
5799        }
5800
5801        fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
5802            self.modules.get(name).cloned().map(Ok)
5803        }
5804    }
5805
5806    #[derive(Default)]
5807    struct DispatchHost {
5808        prints: Vec<String>,
5809        modules: BTreeMap<String, String>,
5810    }
5811
5812    impl NyblHost for DispatchHost {
5813        fn call(
5814            &mut self,
5815            name: &str,
5816            _args: &[Value],
5817            _line: u32,
5818        ) -> Option<Result<Value, NyblError>> {
5819            (name == "pick").then_some(Ok(Value::Int(99)))
5820        }
5821
5822        fn on_print(&mut self, message: &str) {
5823            self.prints.push(message.to_string());
5824        }
5825
5826        fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
5827            self.modules.get(name).cloned().map(Ok)
5828        }
5829    }
5830
5831    #[test]
5832    fn shared_definitions_preserve_named_call_semantics() {
5833        let source = r#"
5834fn recurse(n) {
5835    if n == 0 { return 0 }
5836    return recurse(n - 1) + 1
5837}
5838let original = recurse
5839fn recurse(n) { return n + 10 }
5840
5841fn bump(ref value) { value += 2 }
5842let bump_alias = bump
5843let value = 1
5844bump(ref value)
5845bump_alias(ref value)
5846
5847fn pick() { return 1 }
5848let local_pick = pick
5849
5850struct Box { value }
5851fn Box.add(self, amount) { return self.value + amount }
5852
5853use funcs as funcs
5854print(original(4), recurse(4), value)
5855print(pick(), local_pick(), funcs.call(5))
5856print(Box { value: 2 }.add(3))
5857"#;
5858        let mut host = DispatchHost {
5859            modules: BTreeMap::from([(
5860                "funcs".to_string(),
5861                "fn twice(n) { return n * 2 }\nfn call(n) { return twice(n) + 1 }".to_string(),
5862            )]),
5863            ..DispatchHost::default()
5864        };
5865        let statements = crate::parse(source).expect("program should parse");
5866        Evaluator::new(&mut host, crate::NyblLimits::standard())
5867            .run(&statements)
5868            .expect("program should run");
5869
5870        assert_eq!(host.prints, ["4 14 5", "99 1 11", "5"]);
5871    }
5872
5873    #[test]
5874    fn facade_fanout_reuses_the_origin_compatibility_snapshot() {
5875        const FACADES: usize = 8;
5876        let items = (0..256)
5877            .map(|value| value.to_string())
5878            .collect::<Vec<_>>()
5879            .join(", ");
5880        let mut modules = BTreeMap::from([(
5881            "leaf".to_string(),
5882            format!("let items = [{items}]\nfn size() {{ return items.len() }}"),
5883        )]);
5884        let mut source = String::new();
5885        for index in 0..FACADES {
5886            modules.insert(format!("facade{index}"), "use leaf".to_string());
5887            source.push_str(&format!("use facade{index} as f{index}\n"));
5888            source.push_str(&format!("let size{index} = f{index}.size()\n"));
5889        }
5890        let statements = crate::parse(&source).unwrap();
5891        let mut host = FanoutHost { modules };
5892        let mut evaluator = Evaluator::new(&mut host, crate::NyblLimits::standard());
5893        evaluator.exec_block(&statements).unwrap();
5894        for index in 0..FACADES {
5895            assert!(matches!(
5896                evaluator.scopes[0].get(&format!("size{index}")),
5897                Some(Value::Int(256))
5898            ));
5899        }
5900
5901        let imports = evaluator.imports.borrow();
5902        let ImportSlot::Loaded(leaf) = imports.get("leaf").unwrap() else {
5903            panic!("leaf should be loaded")
5904        };
5905        let leaf_items = &leaf
5906            .bindings
5907            .iter()
5908            .find(|(name, _)| name == "items")
5909            .unwrap()
5910            .1;
5911        for index in 0..FACADES {
5912            let ImportSlot::Loaded(facade) = imports.get(&format!("facade{index}")).unwrap() else {
5913                panic!("facade should be loaded")
5914            };
5915            let facade_items = &facade
5916                .bindings
5917                .iter()
5918                .find(|(name, _)| name == "items")
5919                .unwrap()
5920                .1;
5921            assert!(leaf_items.__shares_backing_with(facade_items));
5922        }
5923    }
5924
5925    #[test]
5926    fn bare_array_mutation_observes_argument_effects_first() {
5927        assert_eq!(run("let a = [1, 2]\na.push(a.pop())\nprint(a)"), ["[1, 2]"]);
5928    }
5929
5930    #[test]
5931    fn direct_mutation_preserves_value_semantic_aliases() {
5932        assert_eq!(
5933            run("let a = [1, 2]\nlet b = a\na.push(3)\nprint(a)\nprint(b)"),
5934            ["[1, 2, 3]", "[1, 2]"]
5935        );
5936    }
5937}