Skip to main content

nybl/
lib.rs

1//! Nybl language core and tree-walking runtime.
2//!
3//! Nybl is a small, dynamically typed scripting language designed to be
4//! embedded in Rust applications. The core runtime has no ambient access to
5//! the filesystem, network, environment, clock, or standard I/O: a program
6//! can only reach capabilities exposed through [`NyblHost`].
7//!
8//! # Choose an execution API
9//!
10//! - [`run`] parses and executes one isolated program with the tree-walker.
11//! - [`NyblInstance`] loads a program once and lets a host repeatedly call
12//!   root-level `pub fn` entry points while program state remains live.
13//! - [`ReplSession`] retains declarations across source submissions and is
14//!   intended for interactive tools.
15//! - [`parse`], [`parse_with_warnings`], and
16//!   [`parse_with_warnings_and_resolver`] expose the parser and static
17//!   diagnostics without executing the program.
18//!
19//! The [`nybl-vm`](https://docs.rs/nybl-vm) crate provides a faster bytecode
20//! implementation with equivalent one-shot and persistent APIs.
21//! [`nybl-compile`](https://docs.rs/nybl-compile) transpiles the same language
22//! to Rust.
23//!
24//! # One-shot embedding
25//!
26//! ```
27//! use nybl::{NyblError, NyblHost, NyblLimits, Value};
28//!
29//! struct Host {
30//!     output: Vec<String>,
31//! }
32//!
33//! impl NyblHost for Host {
34//!     fn call(
35//!         &mut self,
36//!         name: &str,
37//!         args: &[Value],
38//!         line: u32,
39//!     ) -> Option<Result<Value, NyblError>> {
40//!         match (name, args) {
41//!             ("double", [Value::Int(value)]) => {
42//!                 Some(Ok(Value::Int(value * 2)))
43//!             }
44//!             ("double", _) => Some(Err(NyblError::runtime(
45//!                 "double(value) expects one int",
46//!                 line,
47//!             ))),
48//!             _ => None,
49//!         }
50//!     }
51//!
52//!     fn on_print(&mut self, message: &str) {
53//!         self.output.push(message.to_owned());
54//!     }
55//! }
56//!
57//! let mut host = Host { output: Vec::new() };
58//! nybl::run(
59//!     "print(double(21))",
60//!     &mut host,
61//!     &NyblLimits::standard(),
62//! ).unwrap();
63//! assert_eq!(host.output, ["42"]);
64//! ```
65//!
66//! # Reference parameters
67//!
68//! Nybl normally passes independent values. User-defined functions may opt
69//! into explicit, second-class reference parameters by writing `ref` at both
70//! the declaration and call:
71//!
72//! ```nybl
73//! fn increment(ref value) {
74//!   value += 1
75//! }
76//!
77//! let count = 0
78//! increment(ref count)
79//! print(count)    // 1
80//! ```
81//!
82//! A reference argument must be a distinct mutable field/index place rooted in
83//! a `let` binding.
84//! The callee receives a staged copy; every reference target commits together
85//! only after a normal return and rolls back together on runtime or resource
86//! errors. Reference parameters may be forwarded but not captured. Built-in
87//! and host functions are value-only.
88//!
89//! User-defined methods may declare `ref self` to update a mutable
90//! place receiver. Method-call syntax supplies that reference
91//! implicitly (`counter.increment()`); the receiver joins explicit reference
92//! arguments in the same transaction. Ordinary `self` receivers are read-only,
93//! and assigning through one is a parse error with a `ref self` hint.
94//!
95//! [`NyblInstance::call`] and [`NyblInstance::call_value`] also accept values,
96//! not Nybl bindings, and reject ref-bearing callables before execution. Keep
97//! host-facing `pub fn` entries value-only and perform ref calls inside Nybl.
98//! The complete language contract is in the [reference-parameters
99//! guide](https://nybl-lang.com/docs/functions/reference-parameters/).
100//!
101//! # Persistent programs
102//!
103//! A persistent program explicitly publishes its host-callable ABI with
104//! direct root-level `pub fn` declarations:
105//!
106//! ```
107//! # use nybl::{NyblError, NyblHost, NyblInstance, NyblLimits, Value};
108//! # struct Host;
109//! # impl NyblHost for Host {
110//! #     fn call(&mut self, _: &str, _: &[Value], _: u32)
111//! #         -> Option<Result<Value, NyblError>> { None }
112//! # }
113//! let mut host = Host;
114//! let mut instance = NyblInstance::load(
115//!     "let count = 0\npub fn next() { count += 1; return count }",
116//!     &mut host,
117//!     &NyblLimits::standard(),
118//! ).unwrap();
119//!
120//! assert_eq!(
121//!     instance.call("next", &[], &mut host).unwrap().inspect(),
122//!     "1",
123//! );
124//! assert_eq!(
125//!     instance.call("next", &[], &mut host).unwrap().inspect(),
126//!     "2",
127//! );
128//! ```
129//!
130//! # Rust values
131//!
132//! [`Value::to_rust`], [`IntoValue`], [`FromValue`], and the
133//! [`nybl_value!`] macro provide checked conversions at host boundaries.
134//! Conversions include strict numeric scalars, borrowed and owned strings,
135//! `Vec<T>`, `Option<T>`, `Result<T, E>`, and deterministic
136//! `BTreeMap<String, T>` dictionaries. Recursive construction remains
137//! fallible so Nybl's maximum value-depth invariant cannot be bypassed.
138//!
139//! # Limits and features
140//!
141//! [`NyblLimits`] bounds executed steps and tracked allocations. All engines
142//! also enforce a fixed function-call depth. Limit failures are fatal and
143//! cannot be swallowed by Nybl's `try_call`.
144//!
145//! The default `std` feature enables Rust standard-library integration. The
146//! separate default `nybl-std` feature bundles the `std.math`, `std.iter`,
147//! `std.collections`, `std.string`, `std.json`, and `std.test` modules as Nybl
148//! source; resolve them through [`stdlib::resolve`]. Disable default features
149//! to omit the bundled modules while keeping Rust `std` by explicitly enabling
150//! `std`. A genuine no_std build uses `default-features = false` plus the
151//! opt-in `no_std` feature, which replaces standard-library floating-point
152//! operations with `libm`. If Cargo unifies `std` and `no_std`, `std` wins.
153//!
154//! The complete language and embedding guides live at
155//! <https://nybl-lang.com/docs/>.
156
157#![cfg_attr(all(feature = "no_std", not(feature = "std")), no_std)]
158
159#[cfg(all(feature = "no_std", not(feature = "std")))]
160extern crate alloc;
161
162// A genuine no_std unit-test build still uses Rust's standard test harness;
163// make that test-only dependency explicit.
164#[cfg(all(test, feature = "no_std", not(feature = "std")))]
165#[macro_use]
166extern crate std;
167
168#[cfg(all(feature = "no_std", not(feature = "std")))]
169use alloc::{collections::BTreeSet, string::String, vec::Vec};
170#[cfg(any(feature = "std", not(feature = "no_std")))]
171use std::collections::BTreeSet;
172
173pub mod ast_depth;
174#[doc(hidden)]
175pub mod ast_visit;
176pub mod builtins;
177pub mod check;
178pub mod error;
179pub mod error_messages;
180#[doc(hidden)]
181pub mod formatting;
182pub mod host;
183#[doc(hidden)]
184pub mod import_scope;
185mod instance;
186pub mod lexer;
187pub mod math;
188pub mod memory;
189pub mod methods;
190pub mod naming;
191pub mod ops;
192pub mod parser;
193pub mod precheck;
194pub mod ref_params;
195/// Bundled Nybl standard library (`use std.math`, `std.json`,
196/// `std.collections`, `std.iter`, `std.string`, `std.test`).
197/// Feature-gated behind `nybl-std` (on by default).
198///
199/// The module is named `stdlib` rather than `std` specifically
200/// to avoid shadowing Rust's own `::std` when a consumer does
201/// `use nybl::*` (or when anything in the crate's own tests
202/// does `use super::*`). `nybl::stdlib::resolve(...)` is the
203/// public entry point.
204#[cfg(feature = "nybl-std")]
205pub mod stdlib;
206pub mod suggest;
207pub mod value;
208pub mod value_conversion;
209
210mod evaluator;
211
212pub use error::NyblError;
213pub use error::NyblWarning;
214pub use instance::{EntryPoint, NyblInstance, PreparedEntry};
215pub use parser::{ParamMode, Stmt, count_instructions};
216pub use ref_params::{validate_call_modes, validate_value_only_call_modes};
217pub use value::{HostValue, Value};
218pub use value_conversion::{FromValue, IntoValue, ValueConversionError, ValuePathSegment};
219
220/// The core pattern matcher. Re-exported so engines beyond the
221/// tree-walker (the bytecode VM, the AOT runtime) can apply the
222/// same structural rules without re-implementing them.
223pub use evaluator::{pattern_matches, pattern_matches_in};
224
225/// Shared scope walker for resolving source-level type
226/// references to the declaring module. Re-exported because VM
227/// and AOT both need to build per-frame type resolvers when
228/// calling [`pattern_matches`] — the identity comparison lives
229/// on the matcher side, but the scope lookup is identical
230/// across engines.
231pub use evaluator::resolve_type_in;
232#[doc(hidden)]
233pub use evaluator::resolve_type_in_scoped;
234
235/// Type alias for the resolver closure `pattern_matches` expects.
236pub use evaluator::TypeResolveFn;
237
238/// Persistent state for an interactive REPL session. Unlike the one-shot
239/// [`run`] API, a
240/// `ReplSession` carries its scopes, fns, user types, method
241/// tables, and import cache across calls, so
242/// `session.eval("let x = 5")` followed by
243/// `session.eval("print(x)")` sees the same `x`.
244pub use evaluator::ReplSession;
245
246// ─── NyblLimits ─────────────────────────────────────────────────────────────
247
248/// Resource limits enforced during execution.
249#[derive(Debug, Clone)]
250pub struct NyblLimits {
251    /// Max interpreter ticks (loop iterations, statements, etc.)
252    pub max_steps: u64,
253    /// Max total tracked memory (bytes) for strings + arrays
254    pub max_memory: usize,
255    /// Engine builtins the host forbids for this program (e.g.
256    /// `rand` in a deterministic simulation whose randomness must
257    /// flow through a host-provided seeded RNG). A definite
258    /// reference to a disabled builtin is a fatal load-time error;
259    /// references that static analysis cannot prove (a shadowing
260    /// binding might apply) fail with the same fatal error at the
261    /// moment they would invoke the builtin, and `try_call` cannot
262    /// catch them. Names that are not engine builtins are allowed
263    /// and never match. Empty (the default) disables nothing.
264    pub disabled_builtins: BTreeSet<String>,
265    /// Budget for code nesting across active frames. Each running function,
266    /// lambda, or method body, each loading module top level, and the root
267    /// program charge their static nesting depth (see [`ast_depth`]) while
268    /// they are active; a call or `use` that would exceed the budget fails
269    /// with an ordinary, `try_call`-catchable error. Together with the fixed
270    /// call-depth and parse-depth caps this bounds the native stack an
271    /// execution can use, so a host can size its threads from Nybl's limits
272    /// (see the crate README for the per-profile sizes).
273    pub max_nesting: u32,
274}
275
276/// Default [`NyblLimits::max_nesting`] for both presets.
277pub const DEFAULT_MAX_NESTING: u32 = 2048;
278
279impl NyblLimits {
280    /// The general-purpose preset: 10,000 steps, 10 MiB of tracked memory, and
281    /// a nesting budget of [`DEFAULT_MAX_NESTING`].
282    pub fn standard() -> Self {
283        Self {
284            max_steps: 10_000,
285            max_memory: 10 * 1024 * 1024, // 10 MB
286            disabled_builtins: BTreeSet::new(),
287            max_nesting: DEFAULT_MAX_NESTING,
288        }
289    }
290
291    /// A smaller preset for demos: 1,000 steps, 1 MiB of tracked memory, and
292    /// a nesting budget of [`DEFAULT_MAX_NESTING`].
293    pub fn demo() -> Self {
294        Self {
295            max_steps: 1_000,
296            max_memory: 1024 * 1024, // 1 MB
297            disabled_builtins: BTreeSet::new(),
298            max_nesting: DEFAULT_MAX_NESTING,
299        }
300    }
301
302    /// Builder-style helper that disables the given builtins on top of
303    /// the receiver's other settings:
304    /// `NyblLimits::standard().with_disabled_builtins(["rand"])`.
305    pub fn with_disabled_builtins(
306        mut self,
307        names: impl IntoIterator<Item = impl Into<String>>,
308    ) -> Self {
309        self.disabled_builtins
310            .extend(names.into_iter().map(Into::into));
311        self
312    }
313
314    /// Builder-style helper that sets [`Self::max_nesting`]:
315    /// `NyblLimits::standard().with_max_nesting(512)`.
316    pub fn with_max_nesting(mut self, max_nesting: u32) -> Self {
317        self.max_nesting = max_nesting;
318        self
319    }
320}
321
322impl Default for NyblLimits {
323    fn default() -> Self {
324        Self::standard()
325    }
326}
327
328// ─── NyblHost trait ─────────────────────────────────────────────────────────
329
330/// Extension point for embedders to add custom built-in functions.
331pub trait NyblHost {
332    /// Called for unknown function names. Return `None` = not handled.
333    fn call(&mut self, name: &str, args: &[Value], line: u32) -> Option<Result<Value, NyblError>>;
334
335    /// Called for a non-common method on an opaque [`HostValue`]. Return
336    /// `None` when this host does not implement the method.
337    ///
338    /// Host methods are value-only calls. Any mutation they perform is an
339    /// external host side effect and is not part of Nybl's `ref` transaction
340    /// or rollback semantics.
341    fn call_method(
342        &mut self,
343        receiver: &HostValue,
344        method: &str,
345        args: &[Value],
346        line: u32,
347    ) -> Option<Result<Value, NyblError>> {
348        let _ = (receiver, method, args, line);
349        None
350    }
351
352    /// Called by `print()`.
353    fn on_print(&mut self, message: &str) {
354        let _ = message;
355    }
356
357    /// Report a failure from the most recent [`Self::on_print`] call.
358    ///
359    /// `on_print` predates fallible host output, so changing its return type
360    /// would break every existing host implementation. Hosts that write to a
361    /// fallible destination can instead retain the error in `on_print` and
362    /// return it here. Engines call this hook immediately after `on_print`.
363    ///
364    /// The default keeps existing in-memory and infallible hosts unchanged.
365    fn print_error(&self, line: u32) -> Option<NyblError> {
366        let _ = line;
367        None
368    }
369
370    /// Hint text for "function not found" errors.
371    fn function_hint(&self) -> &str {
372        ""
373    }
374
375    /// Called each tick. Return `Err` to halt execution.
376    fn on_tick(&mut self) -> Result<(), NyblError> {
377        Ok(())
378    }
379
380    /// Resolve a `use` target to Nybl source.
381    ///
382    /// The core language doesn't know where modules live — a
383    /// filesystem embedder reads `.nybl` files, a browser embedder
384    /// might fetch a URL, an embedded host might look up bundled
385    /// string assets. Returning:
386    ///
387    /// - `None` — "I don't handle this module path": the runtime
388    ///   raises a *module not found* error.
389    /// - `Some(Ok(source))` — the module's source text, to be
390    ///   parsed and executed by the engine.
391    /// - `Some(Err(e))` — the resolver itself failed (I/O error,
392    ///   bad path, …); the engine propagates the error as-is.
393    ///
394    /// The default impl returns `None`, so by default a program
395    /// that uses another module halts with *module not found*.
396    fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
397        let _ = name;
398        None
399    }
400}
401
402// ─── Public API ────────────────────────────────────────────────────────────
403
404/// Run a Nybl program with the given host and limits.
405pub fn run<H: NyblHost>(source: &str, host: &mut H, limits: &NyblLimits) -> Result<(), NyblError> {
406    let tokens = lexer::lex(source)?;
407    let stmts = parser::parse(tokens)?;
408    check::enforce_disabled_builtins(&stmts, &limits.disabled_builtins)?;
409    let eval = evaluator::Evaluator::new(host, limits.clone());
410    eval.run(&stmts)
411}
412
413/// Parse Nybl source into an AST (useful for instruction counting).
414pub fn parse(source: &str) -> Result<Vec<Stmt>, NyblError> {
415    let tokens = lexer::lex(source)?;
416    parser::parse(tokens)
417}
418
419/// Parse Nybl source and run the static check pass, returning
420/// both the AST and any non-fatal warnings (currently:
421/// match-exhaustiveness). Prefer this over [`parse`] in tools
422/// that surface diagnostics to users — the CLI uses it to
423/// print warnings before running the program.
424///
425/// Imported enums are opaque at this layer — see
426/// [`parse_with_warnings_and_resolver`] for a variant that
427/// walks `use` statements to pick up imported enum decls so
428/// exhaustiveness warnings fire on them too.
429pub fn parse_with_warnings(
430    source: &str,
431) -> Result<(Vec<Stmt>, Vec<error::NyblWarning>), NyblError> {
432    let stmts = parse(source)?;
433    let warnings = check::check_program(&stmts);
434    Ok((stmts, warnings))
435}
436
437/// Like [`parse_with_warnings`] but follows every top-level
438/// `use` statement via the supplied resolver so the
439/// exhaustiveness check can see imported enums. `resolver`
440/// has the same shape as [`NyblHost::resolve_module`].
441///
442/// Returning `Some(Err(_))` or `None` from `resolver` is
443/// *not* propagated — the checker silently falls back to
444/// treating that module's enums as opaque, same as
445/// [`parse_with_warnings`]. Only a parse error of the root
446/// `source` is surfaced.
447pub fn parse_with_warnings_and_resolver<R>(
448    source: &str,
449    mut resolver: R,
450) -> Result<(Vec<Stmt>, Vec<error::NyblWarning>), NyblError>
451where
452    R: FnMut(&str) -> Option<Result<String, NyblError>>,
453{
454    let stmts = parse(source)?;
455    let warnings = check::check_program_with_resolver(&stmts, &mut resolver);
456    Ok((stmts, warnings))
457}
458
459// ─── Tests ─────────────────────────────────────────────────────────────────
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    #[cfg(all(feature = "no_std", not(feature = "std")))]
465    use alloc::string::ToString;
466    use std::cell::RefCell;
467
468    // ─── Test host ─────────────────────────────────────────────────
469
470    struct TestHost {
471        prints: RefCell<Vec<String>>,
472    }
473
474    impl TestHost {
475        fn new() -> Self {
476            Self {
477                prints: RefCell::new(Vec::new()),
478            }
479        }
480
481        fn last_print(&self) -> String {
482            self.prints
483                .borrow()
484                .last()
485                .cloned()
486                .expect("no print output")
487        }
488    }
489
490    impl NyblHost for TestHost {
491        fn call(
492            &mut self,
493            _name: &str,
494            _args: &[Value],
495            _line: u32,
496        ) -> Option<Result<Value, NyblError>> {
497            None
498        }
499
500        fn on_print(&mut self, message: &str) {
501            self.prints.borrow_mut().push(message.to_string());
502        }
503    }
504
505    // ─── Test helpers ──────────────────────────────────────────────
506
507    fn test_limits() -> NyblLimits {
508        NyblLimits::standard()
509    }
510
511    /// Run code, return last print output
512    fn say(code: &str) -> String {
513        // Change say() -> print() in test code
514        let mut host = TestHost::new();
515        run(code, &mut host, &test_limits()).unwrap();
516        host.last_print()
517    }
518
519    /// Run code, expect runtime error, return message
520    fn run_err(code: &str) -> String {
521        let mut host = TestHost::new();
522        run(code, &mut host, &test_limits()).unwrap_err().message
523    }
524
525    /// Expect a lex or parse error, return message
526    fn parse_err(code: &str) -> String {
527        parse(code).unwrap_err().message
528    }
529
530    /// Run code with custom limits, expect a runtime error, return message
531    fn run_err_with_limits(code: &str, limits: NyblLimits) -> String {
532        let mut host = TestHost::new();
533        run(code, &mut host, &limits).unwrap_err().message
534    }
535
536    /// Tight limits for safety tests
537    fn tight_limits() -> NyblLimits {
538        NyblLimits {
539            max_steps: 500,
540            max_memory: 64 * 1024,
541            ..NyblLimits::standard()
542        }
543    }
544
545    #[test]
546    fn multiline_delimiters_parse_and_run() {
547        let source = r#"fn add(a, b) { return a + b }
548let values = [
549    1,
550    add(
551        2,
552        3
553    ),
554    [
555        6,
556    ][
557        0
558    ],
559]
560let config = {
561    "target": values[
562        1
563    ],
564    "label": "nybl"
565}
566if (
567    config[
568        "target"
569    ] == 5 && values.len() == 3
570) {
571    print(
572        values[0] +
573        values[1] +
574        values[2]
575    )
576}
577let length = values
578    // Leading-dot continuation may cross comments and blank lines.
579
580    .len()
581    .to_str()
582print(length)"#;
583
584        parse(source).unwrap();
585        let mut host = TestHost::new();
586        run(source, &mut host, &test_limits()).unwrap();
587        assert_eq!(host.prints.borrow().as_slice(), ["12", "3"]);
588    }
589
590    #[test]
591    fn nested_lambda_blocks_keep_newline_statement_boundaries() {
592        assert_eq!(
593            say(r#"let functions = [
594    fn() {
595        let x = 1
596        let y = 2
597        return x + y
598    },
599]
600let wrapped = (fn() {
601    let x = 4
602    let y = 5
603    return x + y
604})
605print(functions[0]() + wrapped())"#),
606            "12"
607        );
608    }
609
610    #[test]
611    fn return_newline_is_bare_but_parenthesized_return_can_span_lines() {
612        let mut host = TestHost::new();
613        run(
614            r#"fn bare() {
615    return
616    42
617}
618fn grouped() {
619    return (
620        42
621    )
622}
623print(bare())
624print(grouped())"#,
625            &mut host,
626            &test_limits(),
627        )
628        .unwrap();
629        assert_eq!(host.prints.borrow().as_slice(), ["none", "42"]);
630    }
631
632    // ─── Arithmetic ────────────────────────────────────────────────
633
634    #[test]
635    fn add_numbers() {
636        assert_eq!(say("print(1 + 2)"), "3");
637    }
638
639    #[test]
640    fn subtract() {
641        assert_eq!(say("print(10 - 3)"), "7");
642    }
643
644    #[test]
645    fn multiply() {
646        assert_eq!(say("print(4 * 5)"), "20");
647    }
648
649    #[test]
650    fn divide_float() {
651        assert_eq!(say("print(7 / 2)"), "3.5");
652    }
653
654    #[test]
655    fn divide_whole() {
656        assert_eq!(say("print(6 / 2)"), "3");
657    }
658
659    #[test]
660    fn modulo() {
661        assert_eq!(say("print(10 % 3)"), "1");
662    }
663
664    #[test]
665    fn precedence() {
666        assert_eq!(say("print(2 + 3 * 4)"), "14");
667    }
668
669    #[test]
670    fn parentheses() {
671        assert_eq!(say("print((2 + 3) * 4)"), "20");
672    }
673
674    #[test]
675    fn unary_neg() {
676        assert_eq!(say("print(-5)"), "-5");
677    }
678
679    #[test]
680    fn unary_not() {
681        assert_eq!(say("print(!true)"), "false");
682    }
683
684    // ─── Strings ───────────────────────────────────────────────────
685
686    #[test]
687    fn string_concat() {
688        assert_eq!(say(r#"print("hello" + " " + "world")"#), "hello world");
689    }
690
691    #[test]
692    fn string_repeat() {
693        assert_eq!(say(r#"print("ab" * 3)"#), "ababab");
694    }
695
696    #[test]
697    fn string_interpolation() {
698        assert_eq!(
699            say(r#"let name = "nybl"
700print("hi {name}!")"#),
701            "hi nybl!"
702        );
703    }
704
705    #[test]
706    fn string_auto_coerce_in_add() {
707        assert_eq!(say(r#"print("val=" + 42)"#), "val=42");
708    }
709
710    // ─── Comparisons & Logic ───────────────────────────────────────
711
712    #[test]
713    fn equality() {
714        assert_eq!(say("print(1 == 1)"), "true");
715        assert_eq!(say("print(1 == 2)"), "false");
716        assert_eq!(say("print(1 != 2)"), "true");
717    }
718
719    #[test]
720    fn ordering() {
721        assert_eq!(say("print(3 < 5)"), "true");
722        assert_eq!(say("print(5 <= 5)"), "true");
723        assert_eq!(say("print(6 > 5)"), "true");
724        assert_eq!(say("print(5 >= 6)"), "false");
725    }
726
727    #[test]
728    fn logical_and_or() {
729        assert_eq!(say("print(true && false)"), "false");
730        assert_eq!(say("print(true || false)"), "true");
731    }
732
733    #[test]
734    fn short_circuit_and() {
735        assert_eq!(say("print(false && x)"), "false");
736    }
737
738    #[test]
739    fn short_circuit_or() {
740        assert_eq!(say("print(true || x)"), "true");
741    }
742
743    // ─── Variables ─────────────────────────────────────────────────
744
745    #[test]
746    fn let_and_use() {
747        assert_eq!(say("let x = 10\nprint(x)"), "10");
748    }
749
750    #[test]
751    fn assign() {
752        assert_eq!(say("let x = 1\nx = 5\nprint(x)"), "5");
753    }
754
755    #[test]
756    fn compound_assign() {
757        assert_eq!(say("let x = 10\nx += 5\nprint(x)"), "15");
758        assert_eq!(say("let x = 10\nx -= 3\nprint(x)"), "7");
759        assert_eq!(say("let x = 4\nx *= 3\nprint(x)"), "12");
760        assert_eq!(say("let x = 10\nx /= 4\nprint(x)"), "2.5");
761        assert_eq!(say("let x = 10\nx %= 3\nprint(x)"), "1");
762    }
763
764    #[test]
765    fn undefined_variable_error() {
766        assert!(run_err("print(nope)").contains("not found"));
767    }
768
769    #[test]
770    fn assign_undeclared_error() {
771        assert!(run_err("x = 5").contains("doesn't exist"));
772    }
773
774    // ─── If / Else ─────────────────────────────────────────────────
775
776    #[test]
777    fn if_true_branch() {
778        assert_eq!(
779            say("if true { print(\"yes\") } else { print(\"no\") }"),
780            "yes"
781        );
782    }
783
784    #[test]
785    fn if_false_branch() {
786        assert_eq!(
787            say("if false { print(\"yes\") } else { print(\"no\") }"),
788            "no"
789        );
790    }
791
792    #[test]
793    fn if_else_if() {
794        assert_eq!(
795            say(r#"let x = 2
796if x == 1 { print("one") } else if x == 2 { print("two") } else { print("other") }"#),
797            "two"
798        );
799    }
800
801    #[test]
802    fn if_expression() {
803        assert_eq!(say("let x = if true { 1 } else { 2 }\nprint(x)"), "1");
804    }
805
806    #[test]
807    fn if_expression_accepts_multiline_single_expression_branches() {
808        let source = r#"let first = if true {
809    // Leading comments and blank lines are layout, not statements.
810
811    1 +
812        2;
813}
814else {
815    99
816}
817print(first)
818
819let second = if false {
820    0
821} else {
822    if true {
823        4
824    }
825    else {
826        5
827    }
828}
829print(second)
830
831let third = if true {
832    (
833        5
834        + 6
835    )
836} else {
837    0
838}
839print(third)"#;
840        let mut host = TestHost::new();
841        run(source, &mut host, &test_limits()).expect("multiline if-expression should run");
842        assert_eq!(host.prints.borrow().clone(), ["3", "4", "11"]);
843    }
844
845    #[test]
846    fn if_expression_rejects_multiple_branch_expressions_at_second_token() {
847        let source = r#"let value = if true {
848    1
849    2
850} else {
851    3
852}"#;
853        let error = parse_err_full(source);
854        assert_eq!(error.line, Some(3));
855        assert_eq!(error.column, Some(5));
856        assert_eq!(error.message, "Expected `}` but found `an integer`");
857
858        let statement_source = r#"let value = if true {
859    1
860    let inner = 2
861} else {
862    3
863}"#;
864        let statement_error = parse_err_full(statement_source);
865        assert_eq!(statement_error.line, Some(3));
866        assert_eq!(statement_error.column, Some(5));
867        assert_eq!(statement_error.message, "Expected `}` but found `let`");
868    }
869
870    #[test]
871    fn if_expression_rejects_statement_branches() {
872        let error = parse_err_full("let value = if true { let inner = 1 } else { 2 }");
873        assert_eq!(error.line, Some(1));
874        assert_eq!(error.column, Some(23));
875        assert!(error.message.contains("I didn't expect `let` here"));
876
877        let leading_semicolon = parse_err_full("let value = if true { ; 1 } else { 2 }");
878        assert_eq!(leading_semicolon.column, Some(23));
879        assert_eq!(leading_semicolon.message, "I didn't expect `;` here");
880
881        let boundary_semicolon = parse_err_full("let value = if true { 1 };\nelse { 2 }");
882        assert_eq!(boundary_semicolon.line, Some(1));
883        assert_eq!(boundary_semicolon.column, Some(26));
884        assert_eq!(boundary_semicolon.message, "Expected `else` but found `;`");
885    }
886
887    // ─── While ─────────────────────────────────────────────────────
888
889    #[test]
890    fn while_loop() {
891        assert_eq!(say("let i = 0\nwhile i < 5 { i += 1 }\nprint(i)"), "5");
892    }
893
894    #[test]
895    fn while_break() {
896        assert_eq!(
897            say("let i = 0\nwhile true { i += 1\nif i == 3 { break } }\nprint(i)"),
898            "3"
899        );
900    }
901
902    #[test]
903    fn while_continue() {
904        assert_eq!(
905            say(r#"let sum = 0
906let i = 0
907while i < 10 {
908    i += 1
909    if i % 2 == 0 { continue }
910    sum += i
911}
912print(sum)"#),
913            "25"
914        );
915    }
916
917    // ─── For ───────────────────────────────────────────────────────
918
919    #[test]
920    fn for_over_array() {
921        assert_eq!(
922            say(r#"let sum = 0
923for x in [10, 20, 30] { sum += x }
924print(sum)"#),
925            "60"
926        );
927    }
928
929    #[test]
930    fn for_over_range() {
931        assert_eq!(
932            say("let sum = 0\nfor i in range(5) { sum += i }\nprint(sum)"),
933            "10"
934        );
935    }
936
937    #[test]
938    fn for_over_string() {
939        assert_eq!(
940            say(r#"let out = ""
941for ch in "abc" { out += ch + "-" }
942print(out)"#),
943            "a-b-c-"
944        );
945    }
946
947    #[test]
948    fn for_with_break() {
949        assert_eq!(
950            say("let last = 0\nfor i in range(100) { if i == 3 { break }\nlast = i }\nprint(last)"),
951            "2"
952        );
953    }
954
955    // ─── Repeat ────────────────────────────────────────────────────
956
957    #[test]
958    fn repeat_loop() {
959        assert_eq!(say("let n = 0\nrepeat 4 { n += 1 }\nprint(n)"), "4");
960    }
961
962    #[test]
963    fn repeat_zero() {
964        assert_eq!(say("let n = 99\nrepeat 0 { n = 0 }\nprint(n)"), "99");
965    }
966
967    // ─── Functions ─────────────────────────────────────────────────
968
969    #[test]
970    fn fn_basic() {
971        assert_eq!(say("fn double(x) { return x * 2 }\nprint(double(5))"), "10");
972    }
973
974    #[test]
975    fn fn_implicit_return_none() {
976        assert_eq!(
977            say(r#"fn noop() { let x = 1 }
978print(noop().type())"#),
979            "none"
980        );
981    }
982
983    #[test]
984    fn fn_multiple_params() {
985        assert_eq!(say("fn add(a, b) { return a + b }\nprint(add(3, 7))"), "10");
986    }
987
988    #[test]
989    fn fn_uses_defining_root_but_not_caller_locals() {
990        assert_eq!(
991            say("let secret = 42\nfn peek() { return secret }\nprint(peek())"),
992            "42"
993        );
994        assert!(
995            run_err(
996                r#"fn peek() { return caller_local }
997fn caller() { let caller_local = 42; return peek() }
998caller()"#
999            )
1000            .contains("not found")
1001        );
1002    }
1003
1004    #[test]
1005    fn fn_wrong_arg_count() {
1006        assert!(run_err("fn f(a, b) { return a }\nf(1)").contains("expects 2"));
1007    }
1008
1009    #[test]
1010    fn ref_parameters_commit_on_normal_returns_and_survive_aliases() {
1011        assert_eq!(
1012            say(r#"fn swap(ref left, ref right) {
1013    let old = left
1014    left = right
1015    right = old
1016}
1017let alias = swap
1018let a = 1
1019let b = 2
1020alias(ref a, ref b)
1021print([a, b])"#,),
1022            "[2, 1]"
1023        );
1024        assert_eq!(
1025            say(r#"fn set_and_return_err(ref value) {
1026    value = 7
1027    return Err("ordinary value")
1028}
1029let value = 1
1030let result = set_and_return_err(ref value)
1031print([value, result.is_err()])"#,),
1032            "[7, true]"
1033        );
1034        assert_eq!(
1035            say(r#"fn set_and_try(ref value) {
1036    value = 8
1037    try Err("ordinary early return")
1038}
1039let value = 1
1040let result = set_and_try(ref value)
1041print([value, result.is_err()])"#,),
1042            "[8, true]"
1043        );
1044    }
1045
1046    #[test]
1047    fn ref_preflight_blocks_argument_side_effects_and_reports_modes() {
1048        assert_eq!(
1049            say(r#"let hits = []
1050fn side() { hits.push(1); return 1 }
1051fn needs_ref(ref value) { value = 2 }
1052fn missing_marker() { needs_ref(side()) }
1053let result = try_call(missing_marker)
1054print([hits, result.is_err()])"#,),
1055            "[[], true]"
1056        );
1057
1058        assert_eq!(
1059            say(r#"let hits = []
1060fn target(ref value) { }
1061fn choose() { hits.push("callee"); return target }
1062fn side() { hits.push("argument"); return 1 }
1063fn invoke() { choose()(side()) }
1064let result = try_call(invoke)
1065print([hits, result.is_err()])"#,),
1066            "[[\"callee\"], true]"
1067        );
1068
1069        let invalid = run_err_full("fn target(ref value) { }\ntarget(ref [1])");
1070        assert_eq!(
1071            invalid.message,
1072            "`ref` argument 1 must name a mutable variable"
1073        );
1074        assert!(
1075            invalid
1076                .friendly_hint
1077                .as_deref()
1078                .unwrap()
1079                .contains("`let` variable")
1080        );
1081        let missing = run_err_full("fn needs_ref(ref value) { }\nlet value = 1\nneeds_ref(value)");
1082        assert_eq!(
1083            missing.message,
1084            "argument 1 to `needs_ref` must be passed with `ref`"
1085        );
1086        assert!(
1087            missing
1088                .friendly_hint
1089                .as_deref()
1090                .unwrap()
1091                .contains("Write `ref`")
1092        );
1093
1094        assert_eq!(
1095            say(r#"let hits = []
1096fn side() { hits.push(1); return 1 }
1097fn invalid_target(ref value, ordinary) { }
1098fn invoke() { invalid_target(ref [1], side()) }
1099let result = try_call(invoke)
1100print([hits, result.is_err()])"#,),
1101            "[[], true]"
1102        );
1103    }
1104
1105    #[test]
1106    fn ref_snapshots_after_ordinary_arguments_and_commits_all_targets() {
1107        assert_eq!(
1108            say(r#"let value = 1
1109fn ordinary() { value += 1; return 10 }
1110fn update(ref target, amount) { target += amount }
1111update(ref value, ordinary())
1112print(value)"#,),
1113            "12"
1114        );
1115        assert_eq!(
1116            say(r#"fn assign_pair(ref left, ref right) {
1117    left = 10
1118    right = 20
1119}
1120let left = 1
1121let right = 2
1122assign_pair(ref left, ref right)
1123print([left, right])"#,),
1124            "[10, 20]"
1125        );
1126    }
1127
1128    #[test]
1129    fn ref_errors_roll_back_every_target_including_forwarded_stages() {
1130        assert_eq!(
1131            say(r#"let left = 1
1132let right = 2
1133fn fail(ref a, ref b) {
1134    a = 10
1135    b = 20
1136    panic("stop")
1137}
1138fn invoke() { fail(ref left, ref right) }
1139let result = try_call(invoke)
1140print([left, right, result.is_err()])"#,),
1141            "[1, 2, true]"
1142        );
1143        assert_eq!(
1144            say(r#"let value = 1
1145fn inner(ref staged) { staged = 9 }
1146fn outer(ref staged) {
1147    inner(ref staged)
1148    panic("after inner commit")
1149}
1150fn invoke() { outer(ref value) }
1151let result = try_call(invoke)
1152print([value, result.is_err()])"#,),
1153            "[1, true]"
1154        );
1155    }
1156
1157    #[test]
1158    fn ref_target_fences_reject_duplicates_captures_and_ref_capture() {
1159        let duplicate =
1160            run_err("fn pair(ref a, ref b) { }\nlet value = 1\npair(ref value, ref value)");
1161        assert!(duplicate.contains("same variable"));
1162
1163        assert_eq!(
1164            say(r#"fn touch(ref value) { value = 2 }
1165fn make() {
1166    let captured = 1
1167    return fn() { touch(ref captured) }
1168}
1169let closure = make()
1170let result = try_call(closure)
1171print(result.is_err())"#,),
1172            "true"
1173        );
1174
1175        assert_eq!(
1176            say(r#"let value = 1
1177fn outer(ref staged) {
1178    let closure = fn() { return staged }
1179}
1180fn invoke() { outer(ref value) }
1181let result = try_call(invoke)
1182print([value, result.is_err()])"#,),
1183            "[1, true]"
1184        );
1185    }
1186
1187    #[test]
1188    fn ref_method_receivers_stage_after_args_and_user_methods_allow_ref_args() {
1189        assert_eq!(
1190            say(r#"let items = [1]
1191fn argument() { items.push(2); return 3 }
1192(items).push(argument())
1193print(items)"#,),
1194            "[1, 2, 3]"
1195        );
1196        assert_eq!(say("print(([1, 2]).pop())"), "2");
1197        assert_eq!(say("print(([1, 2]).push(3))"), "none");
1198        assert_eq!(
1199            say(r#"struct Amount { n }
1200fn Amount.add_to(self, ref target) { target += self.n }
1201let amount = Amount { n: 4 }
1202let value = 3
1203amount.add_to(ref value)
1204print(value)"#,),
1205            "7"
1206        );
1207
1208        assert_eq!(
1209            say(r#"let items = []
1210let hits = []
1211fn side() { hits.push(1); return 1 }
1212fn invoke() { items.push(ref side()) }
1213let result = try_call(invoke)
1214print([items, hits, result.is_err()])"#,),
1215            "[[], [], true]"
1216        );
1217        assert_eq!(
1218            say(r#"struct Box { value }
1219fn Box.set(ref self, value) { self.value = value }
1220let item = Box { value: 1 }
1221item.set(4)
1222print(item.value)"#),
1223            "4"
1224        );
1225    }
1226
1227    #[test]
1228    fn nested_places_support_assignment_refs_and_mutating_receivers() {
1229        assert_eq!(
1230            say(r#"
1231struct Bucket { items }
1232struct Counter { value }
1233
1234fn add_many(ref value, ..extra) {
1235    value += extra.len()
1236    return extra
1237}
1238
1239fn Counter.add(ref self, amount) {
1240    self.value += amount
1241}
1242
1243let buckets = [Bucket { items: [10, 20] }]
1244buckets[0].items[1] += 2
1245let captured = add_many(ref buckets[0].items[0], 7, 8, 9)
1246buckets[0].items.push(30)
1247
1248let rows = [[Counter { value: 1 }]]
1249rows[0][0].add(4)
1250
1251print([buckets[0].items, captured, rows[0][0].value])
1252"#),
1253            "[[13, 22, 30], [7, 8, 9], 5]"
1254        );
1255    }
1256
1257    #[test]
1258    fn nested_ref_places_are_atomic_and_unique_by_root() {
1259        let error = run_err(
1260            r#"
1261fn fail(ref value) {
1262    value = 99
1263    return 1 / 0
1264}
1265let rows = [[1]]
1266fail(ref rows[0][0])
1267"#,
1268        );
1269        assert!(error.contains("Division by zero"), "got: {error}");
1270
1271        let duplicate = run_err(
1272            r#"
1273fn swap(ref left, ref right) {}
1274let values = [1, 2]
1275swap(ref values[0], ref values[1])
1276"#,
1277        );
1278        assert!(duplicate.contains("same variable"), "got: {duplicate}");
1279    }
1280
1281    #[test]
1282    fn place_indexes_run_once_before_root_snapshot() {
1283        let assignment = run_err("let values = [0, 1]\nvalues[values.pop()] = 9");
1284        assert!(assignment.contains("out of bounds"), "got: {assignment}");
1285
1286        assert_eq!(
1287            say(r#"
1288let indexes = [0]
1289let groups = [[1]]
1290groups[indexes.pop()].push(indexes.len())
1291print([groups, indexes])
1292"#),
1293            "[[[1, 0]], []]"
1294        );
1295    }
1296
1297    #[test]
1298    fn rest_parameters_are_value_only_and_accept_zero_or_many_extras() {
1299        assert_eq!(
1300            say(r#"
1301fn collect(head, ..tail) { return [head, tail] }
1302let closure = fn(..items) { return items.len() }
1303print([collect(1), collect(1, 2, 3), closure(), closure(4, 5)])
1304"#),
1305            "[[1, []], [1, [2, 3]], 0, 2]"
1306        );
1307
1308        let error = run_err(
1309            r#"
1310fn collect(..items) {}
1311let value = 1
1312collect(ref value)
1313"#,
1314        );
1315        assert!(error.contains("value parameter"), "got: {error}");
1316    }
1317
1318    #[test]
1319    fn rest_and_public_surface_syntax_is_strict() {
1320        let not_final = parse_err("fn collect(..items, value) {}");
1321        assert!(not_final.contains("final parameter"), "got: {not_final}");
1322
1323        let nested_surface = parse_err("if true { pub { value } }");
1324        assert!(
1325            nested_surface.contains("module root"),
1326            "got: {nested_surface}"
1327        );
1328
1329        let duplicate = parse_err("pub { value }\npub { value }");
1330        assert!(
1331            duplicate.contains("duplicate public name"),
1332            "got: {duplicate}"
1333        );
1334
1335        let ast = parse("fn collect(ref first, ..items) {}\npub { collect }").unwrap();
1336        let parser::StmtKind::FnDecl { params, .. } = &ast[0].kind else {
1337            panic!("expected function declaration");
1338        };
1339        assert_eq!(params[0].mode, ParamMode::Ref);
1340        assert_eq!(params[1].mode, ParamMode::Rest);
1341        assert!(matches!(
1342            ast[1].kind,
1343            parser::StmtKind::PublicSurface { .. }
1344        ));
1345    }
1346
1347    #[test]
1348    fn walker_instances_expose_variadic_entry_metadata() {
1349        let mut host = TestHost::new();
1350        let mut instance = NyblInstance::load(
1351            "pub fn collect(first, ..items) { return [first, items] }",
1352            &mut host,
1353            &test_limits(),
1354        )
1355        .unwrap();
1356        let entry = &instance.entry_points()[0];
1357        assert_eq!(entry.name(), "collect");
1358        assert_eq!(entry.arity(), 1);
1359        assert_eq!(entry.max_arity(), None);
1360        assert!(entry.is_variadic());
1361        assert!(entry.accepts_arity(3));
1362        assert_eq!(
1363            instance
1364                .call(
1365                    "collect",
1366                    &[Value::Int(1), Value::Int(2), Value::Int(3)],
1367                    &mut host,
1368                )
1369                .unwrap()
1370                .inspect(),
1371            "[1, [2, 3]]"
1372        );
1373    }
1374
1375    #[test]
1376    fn zero_parameter_method_reports_total_arity_before_evaluating_arguments() {
1377        let error =
1378            run_err_full("struct Empty { }\nfn Empty.zero() { return none }\nEmpty { }.zero()");
1379        assert_eq!(
1380            error.message,
1381            "`Empty.zero` expects 0 arguments (including `self`), but got 1"
1382        );
1383        assert_eq!(error.line, Some(3));
1384        assert!(!error.is_fatal);
1385
1386        assert_eq!(
1387            say(r#"struct Empty { }
1388let events = []
1389fn Empty.zero() { return none }
1390fn make() { events.push("receiver"); return Empty { } }
1391fn side() { events.push("argument"); return 1 }
1392fn invoke() { make().zero(side()) }
1393let result = try_call(invoke)
1394print([events, result.is_err()])"#,),
1395            r#"[["receiver"], true]"#
1396        );
1397    }
1398
1399    #[test]
1400    fn fatal_ref_failure_rolls_back_staged_values() {
1401        let mut session = ReplSession::new();
1402        let mut host = TestHost::new();
1403        session
1404            .eval(
1405                r#"let value = 1
1406fn exhaust(ref staged) {
1407    staged = 99
1408    while true { staged += 1 }
1409}
1410fn invoke() { exhaust(ref value) }"#,
1411                &mut host,
1412                &NyblLimits::standard(),
1413            )
1414            .unwrap();
1415        let error = session
1416            .eval(
1417                "invoke()",
1418                &mut host,
1419                &NyblLimits {
1420                    max_steps: 8,
1421                    max_memory: 1024 * 1024,
1422                    ..NyblLimits::standard()
1423                },
1424            )
1425            .unwrap_err();
1426        assert!(error.is_fatal);
1427        assert_eq!(session.get("value").unwrap().inspect(), "1");
1428    }
1429
1430    #[test]
1431    fn final_memory_limit_failure_rolls_back_all_ref_targets() {
1432        let mut session = ReplSession::new();
1433        let mut host = TestHost::new();
1434        session
1435            .eval(
1436                r#"let first = 1
1437let second = "safe"
1438let payload = "this payload is retained outside the call"
1439fn grow(ref staged_first, ref staged_second, value) {
1440    staged_first = 99
1441    staged_second = value + value
1442}
1443fn invoke() { grow(ref first, ref second, payload) }"#,
1444                &mut host,
1445                &NyblLimits::standard(),
1446            )
1447            .unwrap();
1448
1449        let error = session
1450            .eval(
1451                "invoke()",
1452                &mut host,
1453                &NyblLimits {
1454                    max_steps: 1_000,
1455                    max_memory: 1,
1456                    ..NyblLimits::standard()
1457                },
1458            )
1459            .unwrap_err();
1460        assert!(error.is_fatal);
1461        assert!(error.message.contains("Memory limit exceeded"));
1462        assert_eq!(session.get("first").unwrap().inspect(), "1");
1463        assert_eq!(session.get("second").unwrap().inspect(), "\"safe\"");
1464    }
1465
1466    #[test]
1467    fn fn_recursion() {
1468        assert_eq!(
1469            say(r#"fn fib(n) {
1470    if n <= 1 { return n }
1471    return fib(n - 1) + fib(n - 2)
1472}
1473print(fib(10))"#),
1474            "55"
1475        );
1476    }
1477
1478    // ─── Closures / first-class functions ──────────────────────────
1479
1480    #[test]
1481    fn lambda_basic() {
1482        assert_eq!(
1483            say(r#"let double = fn(x) { return x * 2 }
1484print(double(5))"#),
1485            "10"
1486        );
1487    }
1488
1489    #[test]
1490    fn lambda_captures_value() {
1491        assert_eq!(
1492            say(r#"let n = 5
1493let add_n = fn(x) { return x + n }
1494print(add_n(3))"#),
1495            "8"
1496        );
1497    }
1498
1499    #[test]
1500    fn lambda_captures_are_snapshot() {
1501        // Mutating `n` after the lambda is built should not
1502        // affect the captured value — the snapshot semantics are
1503        // deliberate.
1504        assert_eq!(
1505            say(r#"let n = 5
1506let add_n = fn(x) { return x + n }
1507n = 100
1508print(add_n(3))"#),
1509            "8"
1510        );
1511    }
1512
1513    #[test]
1514    fn lambda_returned_from_fn() {
1515        // Classic closure pattern: factory function returns a
1516        // specialised closure. The captured `n` outlives the
1517        // enclosing frame because it was cloned into the closure.
1518        assert_eq!(
1519            say(r#"fn make_adder(n) { return fn(x) { return x + n } }
1520let add5 = make_adder(5)
1521let add10 = make_adder(10)
1522print(add5(3))
1523print(add10(3))"#),
1524            "13"
1525        );
1526    }
1527
1528    #[test]
1529    fn named_fn_is_first_class_value() {
1530        assert_eq!(
1531            say(r#"fn double(x) { return x * 2 }
1532let f = double
1533print(f(7))"#),
1534            "14"
1535        );
1536    }
1537
1538    #[test]
1539    fn fn_stored_in_array_and_called_via_index() {
1540        assert_eq!(
1541            say(r#"fn add(x, y) { return x + y }
1542fn mul(x, y) { return x * y }
1543let ops = [add, mul]
1544print(ops[0](2, 3))
1545print(ops[1](2, 3))"#),
1546            "6"
1547        );
1548    }
1549
1550    #[test]
1551    fn higher_order_apply() {
1552        // `apply` takes any callable, proving we call through a
1553        // parameter, not a statically known name.
1554        assert_eq!(
1555            say(r#"fn apply(f, x) { return f(x) }
1556fn square(n) { return n * n }
1557print(apply(square, 4))
1558print(apply(fn(n) { return n + 1 }, 4))"#),
1559            "5"
1560        );
1561    }
1562
1563    #[test]
1564    fn lambda_self_reference_via_named_fn() {
1565        // Named-fn decls see themselves through `self.functions`,
1566        // so recursion works. Let-bound lambdas are documented as
1567        // not supporting self-reference — this test pins the
1568        // working case.
1569        assert_eq!(
1570            say(r#"fn countdown(n) {
1571    if n <= 0 { return "done" }
1572    return countdown(n - 1)
1573}
1574print(countdown(3))"#),
1575            "done"
1576        );
1577    }
1578
1579    #[test]
1580    fn type_of_fn_is_fn() {
1581        assert_eq!(say("fn f() { }\nprint(f.type())"), "fn");
1582        assert_eq!(say("let g = fn() { }\nprint(g.type())"), "fn");
1583    }
1584
1585    #[test]
1586    fn calling_non_callable_value_errors() {
1587        assert!(run_err("let x = 5\nx(1)").contains("not a function"));
1588    }
1589
1590    #[test]
1591    fn lambda_captures_nested_scope() {
1592        // Closures snapshot the full lexical scope stack, so
1593        // bindings from outer blocks are visible inside nested
1594        // lambdas.
1595        assert_eq!(
1596            say(r#"let a = 1
1597if true {
1598    let b = 2
1599    let f = fn() { return a + b }
1600    print(f())
1601}"#),
1602            "3"
1603        );
1604    }
1605
1606    #[test]
1607    fn iife() {
1608        // Immediately-invoked lambda: `(fn() { ... })()`. Falls
1609        // out of the parser for free once lambdas are expressions.
1610        assert_eq!(say("print((fn(x) { return x * 3 })(4))"), "12");
1611    }
1612
1613    // ─── Arrays ────────────────────────────────────────────────────
1614
1615    #[test]
1616    fn array_literal_and_index() {
1617        assert_eq!(say("let a = [10, 20, 30]\nprint(a[1])"), "20");
1618    }
1619
1620    #[test]
1621    fn array_negative_index() {
1622        assert_eq!(say("let a = [10, 20, 30]\nprint(a[-1])"), "30");
1623    }
1624
1625    #[test]
1626    fn array_assign_index() {
1627        assert_eq!(say("let a = [1, 2, 3]\na[1] = 99\nprint(a[1])"), "99");
1628    }
1629
1630    #[test]
1631    fn array_push_pop() {
1632        assert_eq!(
1633            say(r#"let a = [1, 2]
1634a.push(3)
1635print(a.len())"#),
1636            "3"
1637        );
1638        assert_eq!(
1639            say(r#"let a = [1, 2, 3]
1640let last = a.pop()
1641print(last)"#),
1642            "3"
1643        );
1644    }
1645
1646    #[test]
1647    fn array_has() {
1648        assert_eq!(say("print([1, 2, 3].has(2))"), "true");
1649        assert_eq!(say("print([1, 2, 3].has(9))"), "false");
1650    }
1651
1652    #[test]
1653    fn array_index_of() {
1654        assert_eq!(say("print([10, 20, 30].index_of(20))"), "1");
1655        assert_eq!(say("print([10, 20, 30].index_of(99))"), "-1");
1656    }
1657
1658    #[test]
1659    fn array_slice() {
1660        assert_eq!(say("print([1, 2, 3, 4, 5].slice(1, 4))"), "[2, 3, 4]");
1661    }
1662
1663    #[test]
1664    fn array_join() {
1665        assert_eq!(say(r#"print([1, 2, 3].join("-"))"#), "1-2-3");
1666    }
1667
1668    #[test]
1669    fn array_sort() {
1670        assert_eq!(say("let a = [3, 1, 2]\na.sort()\nprint(a)"), "[1, 2, 3]");
1671    }
1672
1673    #[test]
1674    fn array_reverse() {
1675        assert_eq!(say("let a = [1, 2, 3]\na.reverse()\nprint(a)"), "[3, 2, 1]");
1676    }
1677
1678    #[test]
1679    fn array_insert_remove() {
1680        assert_eq!(
1681            say(r#"let a = [1, 3]
1682a.insert(1, 2)
1683print(a)"#),
1684            "[1, 2, 3]"
1685        );
1686        assert_eq!(
1687            say(r#"let a = [1, 2, 3]
1688let removed = a.remove(1)
1689print(removed)"#),
1690            "2"
1691        );
1692    }
1693
1694    #[test]
1695    fn array_concat() {
1696        assert_eq!(say("print([1, 2] + [3, 4])"), "[1, 2, 3, 4]");
1697    }
1698
1699    #[test]
1700    fn array_out_of_bounds() {
1701        assert!(run_err("let a = [1]\nprint(a[5])").contains("out of bounds"));
1702    }
1703
1704    // ─── Strings (methods) ─────────────────────────────────────────
1705
1706    #[test]
1707    fn string_len() {
1708        assert_eq!(say(r#"print("hello".len())"#), "5");
1709    }
1710
1711    #[test]
1712    fn string_contains() {
1713        assert_eq!(say(r#"print("abcdef".contains("cd"))"#), "true");
1714        assert_eq!(say(r#"print("abcdef".contains("zz"))"#), "false");
1715    }
1716
1717    #[test]
1718    fn string_starts_ends_with() {
1719        assert_eq!(say(r#"print("hello".starts_with("he"))"#), "true");
1720        assert_eq!(say(r#"print("hello".ends_with("lo"))"#), "true");
1721    }
1722
1723    #[test]
1724    fn string_split() {
1725        assert_eq!(say(r#"print("a,b,c".split(","))"#), r#"["a", "b", "c"]"#);
1726    }
1727
1728    #[test]
1729    fn string_replace() {
1730        assert_eq!(
1731            say(r#"print("hello world".replace("world", "nybl"))"#),
1732            "hello nybl"
1733        );
1734    }
1735
1736    #[test]
1737    fn string_upper_lower_trim() {
1738        assert_eq!(say(r#"print("Hello".upper())"#), "HELLO");
1739        assert_eq!(say(r#"print("Hello".lower())"#), "hello");
1740        assert_eq!(say(r#"print("  hi  ".trim())"#), "hi");
1741    }
1742
1743    #[test]
1744    fn string_slice() {
1745        assert_eq!(say(r#"print("hello".slice(1, 4))"#), "ell");
1746    }
1747
1748    #[test]
1749    fn string_index_of() {
1750        assert_eq!(say(r#"print("hello".index_of("ll"))"#), "2");
1751        assert_eq!(say(r#"print("hello".index_of("zz"))"#), "-1");
1752    }
1753
1754    #[test]
1755    fn string_index_char() {
1756        assert_eq!(say(r#"print("abc"[1])"#), "b");
1757    }
1758
1759    // ─── Dicts ─────────────────────────────────────────────────────
1760
1761    #[test]
1762    fn dict_literal_and_access() {
1763        assert_eq!(
1764            say(r#"let d = {"name": "nybl", "hp": 100}
1765print(d["name"])"#),
1766            "nybl"
1767        );
1768    }
1769
1770    #[test]
1771    fn dict_assign_key() {
1772        assert_eq!(
1773            say(r#"let d = {"a": 1}
1774d["b"] = 2
1775print(d["b"])"#),
1776            "2"
1777        );
1778    }
1779
1780    #[test]
1781    fn dict_methods() {
1782        assert_eq!(
1783            say(r#"let d = {"x": 1, "y": 2}
1784print(d.len())"#),
1785            "2"
1786        );
1787        assert_eq!(say(r#"print({"a": 1, "b": 2}.has("a"))"#), "true");
1788        assert_eq!(say(r#"print({"a": 1, "b": 2}.has("z"))"#), "false");
1789    }
1790
1791    #[test]
1792    fn dict_keys_values() {
1793        assert_eq!(say(r#"print({"a": 1, "b": 2}.keys())"#), r#"["a", "b"]"#);
1794        assert_eq!(say(r#"print({"a": 1, "b": 2}.values())"#), "[1, 2]");
1795    }
1796
1797    #[test]
1798    fn dict_remove_mutates_named_binding() {
1799        assert_eq!(
1800            say(r#"let d = {"a": 1, "b": 2, "c": 3}
1801let gone = d.remove("b")
1802print([gone, d.len(), d.has("b"), d.keys()])"#),
1803            r#"[2, 2, false, ["a", "c"]]"#
1804        );
1805        // Missing keys return `none`, matching missing-key reads.
1806        assert_eq!(
1807            say(r#"let d = {"a": 1}
1808print([d.remove("zzz"), d.len()])"#),
1809            "[none, 1]"
1810        );
1811        assert_eq!(
1812            run_err(
1813                r#"let d = {"a": 1}
1814d.remove(0)"#
1815            ),
1816            ".remove() needs a string key"
1817        );
1818    }
1819
1820    #[test]
1821    fn dict_remove_commits_through_nested_places() {
1822        assert_eq!(
1823            say(r#"struct Holder { config }
1824let holder = Holder { config: {"x": 1, "y": 2} }
1825let d = {"inner": {"a": 1, "b": 2}}
1826print([holder.config.remove("x"), d["inner"].remove("b"), holder.config.keys(), d["inner"].keys()])"#),
1827            r#"[1, 2, ["y"], ["a"]]"#
1828        );
1829    }
1830
1831    #[test]
1832    fn dict_remove_on_shared_backing_preserves_value_semantics() {
1833        assert_eq!(
1834            say(r#"let d = {"a": 1, "b": 2}
1835let snapshot = d
1836d.remove("a")
1837print([d.len(), snapshot.len(), snapshot.has("a")])"#),
1838            "[1, 2, true]"
1839        );
1840    }
1841
1842    #[test]
1843    fn collection_clear_semantics() {
1844        assert_eq!(
1845            say(r#"let a = [1, 2, 3]
1846a.clear()
1847let d = {"x": 1, "y": 2}
1848d.clear()
1849d["z"] = 9
1850print([a, a.len(), d.len(), d.has("x"), d["z"]])"#),
1851            "[[], 0, 1, false, 9]"
1852        );
1853        assert_eq!(
1854            run_err("let d = {\"a\": 1}\nd.clear(1)"),
1855            "`.clear()` needs 0 arguments"
1856        );
1857    }
1858
1859    #[test]
1860    fn collection_mutators_commit_through_ref_params_and_ref_self() {
1861        // Reassignment inside a callee only rebinds its local; `ref`
1862        // receivers must observe the mutating built-ins themselves.
1863        assert_eq!(
1864            say(r#"fn wipe(ref d) { d.clear() }
1865fn prune(ref d, key) { return d.remove(key) }
1866fn shorten(ref a, n) { a.truncate(n) }
1867let state = {"a": 1, "b": 2}
1868wipe(ref state)
1869let scores = {"x": 1, "y": 2}
1870let pruned = prune(ref scores, "x")
1871let items = [1, 2, 3, 4]
1872shorten(ref items, 2)
1873struct Cache { entries }
1874fn Cache.reset(ref self) { self.entries.clear() }
1875let cache = Cache { entries: {"k": 1} }
1876cache.reset()
1877print([state.len(), pruned, scores.keys(), items, cache.entries.len()])"#),
1878            r#"[0, 1, ["y"], [1, 2], 0]"#
1879        );
1880    }
1881
1882    #[test]
1883    fn array_truncate_semantics() {
1884        for (call, expected) in [
1885            ("truncate(2)", "[1, 2]"),
1886            ("truncate(0)", "[]"),
1887            ("truncate(99)", "[1, 2, 3, 4]"),
1888            // Negative lengths count from the end, matching `.slice()` bounds.
1889            ("truncate(-1)", "[1, 2, 3]"),
1890            ("truncate(-99)", "[]"),
1891        ] {
1892            let source = format!("let a = [1, 2, 3, 4]\na.{call}\nprint(a)");
1893            assert_eq!(say(&source), expected, "call: {call}");
1894        }
1895        assert_eq!(
1896            run_err("let a = [1, 2]\na.truncate(\"x\")"),
1897            "`truncate` expects a number, but got string"
1898        );
1899    }
1900
1901    // ─── Built-in functions ────────────────────────────────────────
1902
1903    #[test]
1904    fn builtin_range_1arg() {
1905        assert_eq!(say("print(range(5))"), "[0, 1, 2, 3, 4]");
1906    }
1907
1908    #[test]
1909    fn builtin_range_2args() {
1910        assert_eq!(say("print(range(2, 5))"), "[2, 3, 4]");
1911    }
1912
1913    #[test]
1914    fn builtin_range_3args() {
1915        assert_eq!(say("print(range(0, 10, 3))"), "[0, 3, 6, 9]");
1916    }
1917
1918    #[test]
1919    fn builtin_range_reverse() {
1920        assert_eq!(say("print(range(5, 0))"), "[5, 4, 3, 2, 1]");
1921    }
1922
1923    #[test]
1924    fn builtin_str() {
1925        assert_eq!(say(r#"print(42.to_str())"#), "42");
1926        assert_eq!(say(r#"print(true.to_str())"#), "true");
1927    }
1928
1929    #[test]
1930    fn builtin_int() {
1931        assert_eq!(say("print(3.7.to_int())"), "3");
1932        assert_eq!(say("print((-2.9).to_int())"), "-2");
1933    }
1934
1935    #[test]
1936    fn builtin_type() {
1937        // Phase 6 split numeric types: `42` is an int, `42.0`
1938        // is a number.
1939        assert_eq!(say("print(42.type())"), "int");
1940        assert_eq!(say("print(42.0.type())"), "number");
1941        assert_eq!(say(r#"print("hi".type())"#), "string");
1942        assert_eq!(say("print(true.type())"), "bool");
1943        assert_eq!(say("print(none.type())"), "none");
1944        assert_eq!(say("print([].type())"), "array");
1945    }
1946
1947    #[test]
1948    fn builtin_abs_min_max() {
1949        assert_eq!(say("print((-5).abs())"), "5");
1950        assert_eq!(say("print(3.min(7))"), "3");
1951        assert_eq!(say("print(3.max(7))"), "7");
1952    }
1953
1954    #[test]
1955    fn builtin_len() {
1956        assert_eq!(say(r#"print("hello".len())"#), "5");
1957        assert_eq!(say("print([1, 2, 3].len())"), "3");
1958    }
1959
1960    #[test]
1961    fn builtin_inspect() {
1962        assert_eq!(say(r#"print("hi".inspect())"#), r#""hi""#);
1963        assert_eq!(say("print(42.inspect())"), "42");
1964    }
1965
1966    #[test]
1967    fn builtin_print_multi_args() {
1968        let mut host = TestHost::new();
1969        run(r#"print("a", "b", "c")"#, &mut host, &test_limits()).unwrap();
1970        assert_eq!(host.prints.borrow().as_slice(), &["a b c"]);
1971    }
1972
1973    #[test]
1974    fn builtin_rand_deterministic() {
1975        let a = say("print(rand(100))");
1976        let b = say("print(rand(100))");
1977        assert_eq!(a, b);
1978    }
1979
1980    // ─── Error cases ───────────────────────────────────────────────
1981
1982    #[test]
1983    fn error_division_by_zero() {
1984        assert!(run_err("print(1 / 0)").contains("Division by zero"));
1985    }
1986
1987    #[test]
1988    fn error_type_mismatch_subtract() {
1989        let msg = run_err(r#"print("a" - 1)"#);
1990        assert!(msg.contains("Can't use `-`"));
1991    }
1992
1993    #[test]
1994    fn error_unknown_function() {
1995        assert!(run_err("nope()").contains("not found"));
1996    }
1997
1998    #[test]
1999    fn error_infinite_loop_protection() {
2000        let msg = run_err("while true { }");
2001        assert!(msg.contains("too many steps"));
2002    }
2003
2004    #[test]
2005    fn error_break_outside_loop() {
2006        assert!(run_err("break").contains("outside of a loop"));
2007    }
2008
2009    #[test]
2010    fn error_continue_outside_loop() {
2011        assert!(run_err("continue").contains("outside of a loop"));
2012    }
2013
2014    // ─── Parse errors ──────────────────────────────────────────────
2015
2016    #[test]
2017    fn parse_error_missing_rparen() {
2018        assert!(parse_err("print(1").contains("Expected `)`"));
2019    }
2020
2021    #[test]
2022    fn parse_error_missing_rbrace() {
2023        assert!(parse_err("if true {").contains("Expected `}`"));
2024    }
2025
2026    // ─── Edge cases ────────────────────────────────────────────────
2027
2028    #[test]
2029    fn empty_program() {
2030        let mut host = TestHost::new();
2031        run("", &mut host, &test_limits()).unwrap();
2032        assert!(host.prints.borrow().is_empty());
2033    }
2034
2035    #[test]
2036    fn trailing_comma_in_array() {
2037        assert_eq!(say("print([1, 2, 3,])"), "[1, 2, 3]");
2038    }
2039
2040    #[test]
2041    fn trailing_comma_in_dict() {
2042        assert_eq!(say(r#"print({"a": 1,}.len())"#), "1");
2043    }
2044
2045    #[test]
2046    fn none_value() {
2047        assert_eq!(say("print(none)"), "none");
2048        assert_eq!(say("print(none == none)"), "true");
2049    }
2050
2051    #[test]
2052    fn equality_across_types() {
2053        assert_eq!(say("print(1 == true)"), "false");
2054        assert_eq!(say(r#"print(0 == "")"#), "false");
2055        assert_eq!(say("print(none == false)"), "false");
2056    }
2057
2058    #[test]
2059    fn dict_equality() {
2060        assert_eq!(
2061            say(r#"print({"a": 1, "b": 2} == {"b": 2, "a": 1})"#),
2062            "true"
2063        );
2064        assert_eq!(say(r#"print({"a": 1} == {"a": 2})"#), "false");
2065        assert_eq!(say(r#"print({"a": 1} == {"b": 1})"#), "false");
2066        assert_eq!(say(r#"print({"a": 1} == {"a": 1, "b": 2})"#), "false");
2067        assert_eq!(say(r#"print({"a": {"x": 1}} == {"a": {"x": 1}})"#), "true");
2068    }
2069
2070    #[test]
2071    fn nested_array_access() {
2072        assert_eq!(say("let m = [[1, 2], [3, 4]]\nprint(m[1][0])"), "3");
2073    }
2074
2075    #[test]
2076    fn method_chain() {
2077        assert_eq!(say(r#"print("  HELLO  ".trim().lower())"#), "hello");
2078    }
2079
2080    // ─── Error diagnostics (phase 8 polish) ──────────────────────
2081
2082    #[test]
2083    fn parse_error_carries_column_info() {
2084        // "let 42" is a parse error — the int `42` shows up
2085        // where a name was expected. Column should point at the
2086        // start of the `42` token (column 5).
2087        let err = parse_err_full("let 42");
2088        assert_eq!(err.line, Some(1), "err: {err:?}");
2089        assert_eq!(err.column, Some(5), "err: {err:?}");
2090        assert!(err.message.contains("Expected a name"));
2091    }
2092
2093    #[test]
2094    fn parser_reports_real_reserved_word_bindings_at_the_keyword() {
2095        for (source, keyword, line, column) in [
2096            ("let if = 1", "if", 1, 5),
2097            ("\nfn const() { none }", "const", 2, 4),
2098            ("for while in [] {}", "while", 1, 5),
2099            ("print(match 1 { if => 1, _ => 2 })", "if", 1, 17),
2100            ("print(match [1] { [..if] => 1, _ => 2 })", "if", 1, 22),
2101        ] {
2102            let error = parse_err_full(source);
2103            assert_eq!(error.line, Some(line), "source: {source}");
2104            assert_eq!(error.column, Some(column), "source: {source}");
2105            assert_eq!(
2106                error.message,
2107                format!("`{keyword}` is a reserved word in Nybl"),
2108                "source: {source}"
2109            );
2110            assert!(error.friendly_hint.is_some(), "source: {source}");
2111        }
2112    }
2113
2114    #[test]
2115    fn parse_error_renders_with_snippet_and_caret() {
2116        let src = "let 42";
2117        let err = parse_err_full(src);
2118        let rendered = err.render(src);
2119        assert!(rendered.contains("--> line 1:5"), "rendered:\n{rendered}");
2120        assert!(rendered.contains("let 42"));
2121        // Four spaces for `let ` before the caret at col 5.
2122        assert!(rendered.contains("    ^"), "rendered:\n{rendered}");
2123    }
2124
2125    #[test]
2126    fn parse_error_on_line_2_points_at_line_2() {
2127        let src = "let x = 1\nlet = 2";
2128        let err = parse_err_full(src);
2129        assert_eq!(err.line, Some(2), "err: {err:?}");
2130        let rendered = err.render(src);
2131        assert!(rendered.contains("let = 2"), "rendered:\n{rendered}");
2132    }
2133
2134    #[test]
2135    fn runtime_error_renders_without_column() {
2136        // Runtime errors don't currently carry column; the
2137        // renderer should still produce a readable snippet.
2138        let src = "let x = 1 / 0";
2139        let err = run_err_full(src);
2140        assert_eq!(err.line, Some(1));
2141        assert!(err.column.is_none());
2142        let rendered = err.render(src);
2143        assert!(rendered.contains("--> line 1"));
2144        assert!(rendered.contains("let x = 1 / 0"));
2145        // No caret line (column unknown).
2146        assert!(!rendered.contains("^"), "rendered:\n{rendered}");
2147    }
2148
2149    /// Like `parse_err` but returns the full `NyblError` so
2150    /// tests can inspect line / column fields directly.
2151    fn parse_err_full(code: &str) -> NyblError {
2152        parse(code).unwrap_err()
2153    }
2154
2155    /// Like `run_err` but returns the full `NyblError`.
2156    fn run_err_full(code: &str) -> NyblError {
2157        let mut host = TestHost::new();
2158        run(code, &mut host, &test_limits()).unwrap_err()
2159    }
2160
2161    // ─── "Did you mean?" suggestions ─────────────────────────────
2162
2163    #[test]
2164    fn typo_variable_suggests_closest_local() {
2165        let err = run_err_full(
2166            r#"let length = 5
2167print(lenght)"#,
2168        );
2169        assert!(err.message.contains("not found"), "err: {err:?}");
2170        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `length`?"));
2171    }
2172
2173    #[test]
2174    fn typo_variable_falls_back_when_nothing_close() {
2175        // No similar name in scope → keeps the generic hint
2176        // rather than suggesting something wild.
2177        let err = run_err_full("print(xylophone_constant)");
2178        assert_eq!(
2179            err.friendly_hint.as_deref(),
2180            Some("Did you forget to create it with `let`?")
2181        );
2182    }
2183
2184    #[test]
2185    fn typo_function_suggests_user_fn() {
2186        let err = run_err_full(
2187            r#"fn greet(name) { print("hi " + name) }
2188gret("world")"#,
2189        );
2190        assert!(err.message.contains("not found"));
2191        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `greet`?"));
2192    }
2193
2194    #[test]
2195    fn typo_builtin_suggests_core_name() {
2196        // `rang(5)` → core builtin `range`.
2197        let err = run_err_full("rang(5)");
2198        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `range`?"));
2199    }
2200
2201    #[test]
2202    fn typo_struct_field_at_access_suggests_declared() {
2203        let err = run_err_full(
2204            r#"struct Point { x, y }
2205let p = Point { x: 1, y: 2 }
2206print(p.z)"#,
2207        );
2208        assert!(err.message.contains("has no field `z`"));
2209        // Both `x` and `y` are within 1 edit of `z`; the
2210        // candidate order in `s.fields()` is declaration order,
2211        // so `x` wins the tie.
2212        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `x`?"));
2213    }
2214
2215    #[test]
2216    fn typo_struct_field_at_construction_suggests_declared() {
2217        let err = run_err_full(
2218            r#"struct Point { x, y }
2219let p = Point { x: 1, ya: 2 }"#,
2220        );
2221        assert!(err.message.contains("has no field `ya`"));
2222        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `y`?"));
2223    }
2224
2225    #[test]
2226    fn typo_enum_variant_suggests_declared() {
2227        let err = run_err_full(
2228            r#"enum Shape { Circle(r), Rectangle { w, h } }
2229let s = Shape::Circel(5)"#,
2230        );
2231        assert!(err.message.contains("has no variant `Circel`"));
2232        assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `Circle`?"));
2233    }
2234
2235    #[test]
2236    fn typo_hint_renders_in_source_snippet() {
2237        let src = r#"let length = 5
2238print(lenght)"#;
2239        let err = run_err_full(src);
2240        let rendered = err.render(src);
2241        assert!(
2242            rendered.contains("hint: Did you mean `length`?"),
2243            "rendered:\n{rendered}"
2244        );
2245    }
2246
2247    #[test]
2248    fn comments_in_code() {
2249        // `//` is the line-comment marker. There's no
2250        // integer-division operator — `/` always returns a
2251        // `Number`, and users who want an integer cast through
2252        // `(a / b).to_int()` — which frees `//` for comments.
2253        assert_eq!(
2254            say(r#"// this is a comment
2255let x = 42 // inline comment
2256print(x)"#),
2257            "42"
2258        );
2259    }
2260
2261    // ─── Instruction counting ─────────────────────────────────────
2262
2263    fn count(code: &str) -> u32 {
2264        let stmts = parse(code).unwrap();
2265        count_instructions(&stmts)
2266    }
2267
2268    #[test]
2269    fn count_simple_calls() {
2270        assert_eq!(count("print(1)"), 1);
2271        assert_eq!(count("print(1); print(2); print(3)"), 3);
2272    }
2273
2274    #[test]
2275    fn count_repeat() {
2276        assert_eq!(count("repeat 7 { print(1) }"), 2);
2277    }
2278
2279    #[test]
2280    fn count_if() {
2281        assert_eq!(count("if true { print(1) }"), 2);
2282        assert_eq!(count("if true { print(1) } else { print(2) }"), 3);
2283    }
2284
2285    #[test]
2286    fn count_while() {
2287        assert_eq!(count("while true { print(1) }"), 2);
2288    }
2289
2290    #[test]
2291    fn count_fn_skips_body() {
2292        assert_eq!(count("fn go() { print(1); print(2); print(3) }\ngo()"), 2);
2293    }
2294
2295    #[test]
2296    fn count_format_independent() {
2297        let one_line = count("repeat 7 { print(1) }");
2298        let multi_line = count("repeat 7 {\n    print(1)\n}");
2299        assert_eq!(one_line, multi_line);
2300        assert_eq!(one_line, 2);
2301    }
2302
2303    #[test]
2304    fn count_nested() {
2305        assert_eq!(count("repeat 7 { if true { print(1) } }"), 3);
2306    }
2307
2308    #[test]
2309    fn count_empty_program() {
2310        assert_eq!(count(""), 0);
2311    }
2312
2313    // ─── Scope / block isolation ───────────────────────────────────
2314
2315    #[test]
2316    fn if_block_scope() {
2317        assert!(
2318            run_err(
2319                r#"if true { let inner = 1 }
2320print(inner)"#
2321            )
2322            .contains("not found")
2323        );
2324    }
2325
2326    #[test]
2327    fn for_loop_var_scoped() {
2328        assert!(
2329            run_err(
2330                r#"for item in [1, 2] { let x = item }
2331print(item)"#
2332            )
2333            .contains("not found")
2334        );
2335    }
2336
2337    // ─── Complex programs ──────────────────────────────────────────
2338
2339    #[test]
2340    fn fizzbuzz() {
2341        assert_eq!(
2342            say(r#"let result = []
2343for i in range(1, 16) {
2344    if i % 15 == 0 {
2345        result.push("FizzBuzz")
2346    } else if i % 3 == 0 {
2347        result.push("Fizz")
2348    } else if i % 5 == 0 {
2349        result.push("Buzz")
2350    } else {
2351        result.push(i.to_str())
2352    }
2353}
2354print(result.join(", "))"#),
2355            "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz"
2356        );
2357    }
2358
2359    #[test]
2360    fn nested_function_calls() {
2361        assert_eq!(
2362            say(r#"fn square(n) { return n * n }
2363fn sum_squares(a, b) { return square(a) + square(b) }
2364print(sum_squares(3, 4))"#),
2365            "25"
2366        );
2367    }
2368
2369    #[test]
2370    fn array_manipulation_program() {
2371        assert_eq!(
2372            say(r#"let data = [5, 2, 8, 1, 9, 3]
2373data.sort()
2374let top3 = data.slice(3, 6)
2375print(top3.join(", "))"#),
2376            "5, 8, 9"
2377        );
2378    }
2379
2380    // ─── Truthiness ────────────────────────────────────────────────
2381
2382    #[test]
2383    fn truthy_values() {
2384        assert_eq!(say("print(if 1 { \"yes\" } else { \"no\" })"), "yes");
2385        assert_eq!(say(r#"print(if "x" { "yes" } else { "no" })"#), "yes");
2386        assert_eq!(say("print(if [1] { \"yes\" } else { \"no\" })"), "yes");
2387    }
2388
2389    #[test]
2390    fn falsy_values() {
2391        assert_eq!(say("print(if 0 { \"yes\" } else { \"no\" })"), "no");
2392        assert_eq!(say("print(if false { \"yes\" } else { \"no\" })"), "no");
2393        assert_eq!(say("print(if none { \"yes\" } else { \"no\" })"), "no");
2394        assert_eq!(say(r#"print(if "" { "yes" } else { "no" })"#), "no");
2395    }
2396
2397    // ─── Number display ────────────────────────────────────────────
2398
2399    #[test]
2400    fn display_whole_number_as_int() {
2401        assert_eq!(say("print(5.0)"), "5");
2402    }
2403
2404    #[test]
2405    fn display_float_with_decimals() {
2406        assert_eq!(say("print(3.14)"), "3.14");
2407    }
2408
2409    // ─── Safety / resource-limit tests ──────────────────────────────
2410
2411    #[test]
2412    fn safety_infinite_loop_halts() {
2413        let msg = run_err_with_limits("while true { }", tight_limits());
2414        assert!(msg.contains("too many steps"), "got: {msg}");
2415    }
2416
2417    #[test]
2418    fn safety_memory_bomb_string_doubling() {
2419        let msg = run_err_with_limits(
2420            r#"let s = "aaaaaaaaaa"
2421repeat 100 { s = s + s }"#,
2422            tight_limits(),
2423        );
2424        assert!(msg.contains("Memory limit"), "got: {msg}");
2425    }
2426
2427    #[test]
2428    fn safety_memory_bomb_array_growth() {
2429        let msg = run_err_with_limits(
2430            r#"let arr = []
2431repeat 1000 {
2432    arr.push("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
2433}"#,
2434            tight_limits(),
2435        );
2436        assert!(
2437            msg.contains("Memory limit") || msg.contains("too many steps"),
2438            "got: {msg}"
2439        );
2440    }
2441
2442    #[test]
2443    fn safety_deep_recursion_halts() {
2444        // Run the recursing program on a worker thread with a
2445        // generous stack budget. Debug builds grow each walker
2446        // frame enough that the default ~2 MiB stack can abort
2447        // (SIGABRT) before the engine's 64-frame call-depth cap
2448        // fires — which would look like a crash rather than the
2449        // clean "too many nested function calls" the sandbox
2450        // promises. 8 MiB comfortably fits `MAX_CALL_DEPTH`
2451        // walker frames with debug frame bloat, and release
2452        // builds never needed the headroom.
2453        let handle = std::thread::Builder::new()
2454            .stack_size(8 * 1024 * 1024)
2455            .spawn(|| run_err_with_limits("fn f() { f() }\nf()", tight_limits()))
2456            .expect("spawn recursion test thread");
2457        let msg = handle.join().expect("recursion test thread panicked");
2458        assert!(
2459            msg.contains("nested function calls") || msg.contains("recursion"),
2460            "got: {msg}"
2461        );
2462    }
2463
2464    #[test]
2465    fn safety_deep_parse_nesting() {
2466        let code = "(".repeat(200) + "1" + &")".repeat(200);
2467        let msg = parse(&code).unwrap_err().message;
2468        assert!(msg.contains("nested too deeply"), "got: {msg}");
2469    }
2470
2471    #[test]
2472    fn safety_deep_parse_nesting_fits_a_pinned_stack() {
2473        // Parsing hostile input at the depth cap must return "nested too
2474        // deeply" rather than abort, on a stack well inside the RUN-002
2475        // thread size. This pins the parser's frame budget deliberately:
2476        // the worst shapes measured 0.8 MiB in release and 4.5 MiB in debug
2477        // (nested `match`; arm64 macOS, Rust 1.98), so growing `NyblError`
2478        // or parser frames by a large factor fails here, not in embedders'
2479        // processes.
2480        let stack = if cfg!(debug_assertions) {
2481            9 * 1024 * 1024
2482        } else {
2483            2 * 1024 * 1024
2484        };
2485        let nest =
2486            |open: &str, close: &str| format!("let x = {}1{}", open.repeat(200), close.repeat(200));
2487        let shapes = [
2488            nest("(", ")"),
2489            nest("[", "]"),
2490            nest("{ \"a\": ", " }"),
2491            nest("Ok(", ")"),
2492            nest("if true { ", " } else { 0 }"),
2493            format!(
2494                "let y = {}",
2495                (0..200).fold("x".to_string(), |expr, _| format!(
2496                    "match x {{ _ => {expr} }}"
2497                ))
2498            ),
2499        ];
2500        let handle = std::thread::Builder::new()
2501            .stack_size(stack)
2502            .spawn(move || {
2503                shapes
2504                    .iter()
2505                    .map(|code| parse(code).unwrap_err().message)
2506                    .collect::<Vec<_>>()
2507            })
2508            .expect("spawn parse test thread");
2509        let messages = handle
2510            .join()
2511            .expect("deep parse must not overflow the pinned stack");
2512        for message in messages {
2513            assert!(message.contains("nested too deeply"), "got: {message}");
2514        }
2515    }
2516
2517    #[test]
2518    fn safety_string_repeat_bomb() {
2519        let msg = run_err_with_limits(r#"let s = "x" * 999999"#, tight_limits());
2520        assert!(msg.contains("Memory limit"), "got: {msg}");
2521    }
2522
2523    #[test]
2524    fn safety_string_concat_bomb() {
2525        let msg = run_err_with_limits(
2526            r#"let s = "x" * 1000
2527repeat 100 { s = s + s }"#,
2528            tight_limits(),
2529        );
2530        assert!(msg.contains("Memory limit"), "got: {msg}");
2531    }
2532
2533    #[test]
2534    fn safety_array_concat_bomb() {
2535        let msg = run_err_with_limits(
2536            r#"let a = range(100)
2537repeat 50 { a = a + a }"#,
2538            tight_limits(),
2539        );
2540        assert!(
2541            msg.contains("Memory limit") || msg.contains("too many steps"),
2542            "got: {msg}"
2543        );
2544    }
2545
2546    #[test]
2547    fn safety_for_in_large_string() {
2548        let msg = run_err_with_limits(
2549            r#"let s = "x" * 10000
2550for c in s { }"#,
2551            tight_limits(),
2552        );
2553        assert!(
2554            msg.contains("too many steps") || msg.contains("Memory limit"),
2555            "got: {msg}"
2556        );
2557    }
2558
2559    #[test]
2560    fn safety_demo_limits_step_bound() {
2561        let msg = run_err_with_limits("let i = 0\nwhile true { i = i + 1 }", NyblLimits::demo());
2562        assert!(msg.contains("too many steps"), "got: {msg}");
2563    }
2564
2565    #[test]
2566    fn safety_demo_limits_memory_bound() {
2567        let msg = run_err_with_limits(
2568            r#"let s = "x" * 1100000
2569print(s)"#,
2570            NyblLimits::demo(),
2571        );
2572        assert!(msg.contains("Memory limit"), "got: {msg}");
2573    }
2574
2575    #[test]
2576    fn safety_nested_loop_step_bound() {
2577        let msg = run_err_with_limits("repeat 100 { repeat 100 { let x = 1 } }", tight_limits());
2578        assert!(msg.contains("too many steps"), "got: {msg}");
2579    }
2580
2581    #[test]
2582    fn safety_string_split_bomb() {
2583        let msg = run_err_with_limits(
2584            r#"let s = "abababababab" * 2000
2585let parts = s.split("a")
2586let x = 1"#,
2587            tight_limits(),
2588        );
2589        assert!(
2590            msg.contains("Memory limit") || msg.contains("too many steps"),
2591            "got: {msg}"
2592        );
2593    }
2594
2595    #[test]
2596    fn safety_join_bomb() {
2597        let msg = run_err_with_limits(
2598            r#"let a = []
2599repeat 400 { a.push("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }
2600let s = a.join("")
2601let x = 1"#,
2602            tight_limits(),
2603        );
2604        assert!(
2605            msg.contains("Memory limit") || msg.contains("too many steps"),
2606            "got: {msg}"
2607        );
2608    }
2609
2610    #[test]
2611    fn safety_range_hard_cap() {
2612        let msg = run_err_with_limits(
2613            r#"let a = range(100000)
2614let x = 1"#,
2615            tight_limits(),
2616        );
2617        assert!(
2618            msg.contains(builtins::RANGE_LIMIT_ERROR_MESSAGE),
2619            "got: {msg}"
2620        );
2621    }
2622
2623    #[test]
2624    fn safety_array_method_doubling() {
2625        let msg = run_err_with_limits(
2626            r#"let a = []
2627repeat 400 { a.push("aaaaaaaaaaaaaaaaaaaaaa") }
2628a.reverse()
2629let x = 1"#,
2630            tight_limits(),
2631        );
2632        assert!(
2633            msg.contains("Memory limit") || msg.contains("too many steps"),
2634            "got: {msg}"
2635        );
2636    }
2637
2638    #[test]
2639    fn safety_preflight_catches() {
2640        let limits = NyblLimits {
2641            max_steps: 500,
2642            max_memory: 32 * 1024,
2643            ..NyblLimits::standard()
2644        };
2645        let msg = run_err_with_limits(r#"let s = "x" * 40000"#, limits);
2646        assert!(msg.contains("Memory limit"), "got: {msg}");
2647    }
2648
2649    #[test]
2650    fn safety_final_retained_allocation_is_checked() {
2651        let limits = NyblLimits {
2652            max_steps: 500,
2653            max_memory: 64 * 1024,
2654            ..NyblLimits::standard()
2655        };
2656        let mut host = TestHost::new();
2657        let error = run(
2658            r#"let s = "abababab" * 1000
2659let parts = s.split("a")"#,
2660            &mut host,
2661            &limits,
2662        )
2663        .expect_err("retained allocations above the limit must fail at the return boundary");
2664        assert!(error.is_fatal);
2665        assert!(error.message.contains("Memory limit exceeded"));
2666    }
2667
2668    #[test]
2669    fn safety_dict_growth_tracked() {
2670        let msg = run_err_with_limits(
2671            r#"let d = {}
2672repeat 400 {
2673    d[d.len().to_str()] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2674}
2675let x = 1"#,
2676            tight_limits(),
2677        );
2678        assert!(
2679            msg.contains("Memory limit") || msg.contains("too many steps"),
2680            "got: {msg}"
2681        );
2682    }
2683
2684    // ─── NyblHost extension ─────────────────────────────────────────
2685
2686    struct CustomHost {
2687        prints: Vec<String>,
2688    }
2689
2690    impl NyblHost for CustomHost {
2691        fn call(
2692            &mut self,
2693            name: &str,
2694            args: &[Value],
2695            line: u32,
2696        ) -> Option<Result<Value, NyblError>> {
2697            match name {
2698                "greet" => {
2699                    if args.len() != 1 {
2700                        return Some(Err(NyblError {
2701                            line: Some(line),
2702                            column: None,
2703                            message: "greet() needs 1 argument".into(),
2704                            friendly_hint: None,
2705                            source_context: None,
2706                            is_fatal: false,
2707                            is_try_return: false,
2708                        }));
2709                    }
2710                    Some(Ok(Value::new_str(format!("Hello, {}!", args[0]))))
2711                }
2712                _ => None,
2713            }
2714        }
2715
2716        fn on_print(&mut self, message: &str) {
2717            self.prints.push(message.to_string());
2718        }
2719
2720        fn function_hint(&self) -> &str {
2721            "Available: greet(name)"
2722        }
2723    }
2724
2725    #[test]
2726    fn host_custom_builtin() {
2727        let mut host = CustomHost { prints: vec![] };
2728        run(
2729            r#"print(greet("world"))"#,
2730            &mut host,
2731            &NyblLimits::standard(),
2732        )
2733        .unwrap();
2734        assert_eq!(host.prints, vec!["Hello, world!"]);
2735    }
2736
2737    #[test]
2738    fn host_function_hint() {
2739        let mut host = CustomHost { prints: vec![] };
2740        let err = run("unknown()", &mut host, &NyblLimits::standard()).unwrap_err();
2741        assert!(err.message.contains("not found"));
2742    }
2743
2744    // ─── Pattern matching ─────────────────────────────────────────
2745
2746    #[test]
2747    fn match_literal_arms() {
2748        assert_eq!(
2749            say(r#"let x = 2
2750let out = match x {
2751    1 => "one",
2752    2 => "two",
2753    3 => "three",
2754    _ => "other",
2755}
2756print(out)"#),
2757            "two"
2758        );
2759    }
2760
2761    #[test]
2762    fn match_falls_through_to_wildcard() {
2763        assert_eq!(
2764            say(r#"let x = 42
2765print(match x {
2766    1 => "one",
2767    _ => "other",
2768})"#),
2769            "other"
2770        );
2771    }
2772
2773    #[test]
2774    fn match_no_arm_errors() {
2775        let err = run_err(
2776            r#"let x = 5
2777match x { 1 => "a", 2 => "b" }"#,
2778        );
2779        assert!(err.contains("No match arm matched"), "got: {err}");
2780    }
2781
2782    #[test]
2783    fn match_binding_captures_scrutinee() {
2784        assert_eq!(
2785            say(r#"print(match 42 {
2786    x => x + 1,
2787})"#),
2788            "43"
2789        );
2790    }
2791
2792    #[test]
2793    fn match_guard_accepts() {
2794        assert_eq!(
2795            say(r#"print(match 7 {
2796    n if n > 10 => "big",
2797    n if n > 0 => "small",
2798    _ => "zero or less",
2799})"#),
2800            "small"
2801        );
2802    }
2803
2804    #[test]
2805    fn match_guard_rejects_continues() {
2806        assert_eq!(
2807            say(r#"print(match 5 {
2808    n if n < 0 => "neg",
2809    n if n > 100 => "huge",
2810    _ => "mid",
2811})"#),
2812            "mid"
2813        );
2814    }
2815
2816    #[test]
2817    fn match_or_pattern() {
2818        assert_eq!(
2819            say(r#"let x = 3
2820print(match x {
2821    1 | 2 | 3 => "small",
2822    _ => "other",
2823})"#),
2824            "small"
2825        );
2826    }
2827
2828    #[test]
2829    fn match_enum_unit_variant() {
2830        assert_eq!(
2831            say(r#"enum E { A, B, C }
2832print(match E::B {
2833    E::A => "a",
2834    E::B => "b",
2835    E::C => "c",
2836})"#),
2837            "b"
2838        );
2839    }
2840
2841    #[test]
2842    fn match_enum_tuple_binds() {
2843        assert_eq!(
2844            say(r#"enum Shape { Circle(r), Square(s), Empty }
2845let s = Shape::Circle(5)
2846print(match s {
2847    Shape::Circle(r) => r * 2,
2848    Shape::Square(s) => s * s,
2849    Shape::Empty => 0,
2850})"#),
2851            "10"
2852        );
2853    }
2854
2855    #[test]
2856    fn match_enum_struct_variant_binds() {
2857        assert_eq!(
2858            say(r#"enum Shape { Rect { w, h }, Empty }
2859let r = Shape::Rect { w: 4, h: 3 }
2860print(match r {
2861    Shape::Rect { w, h } => w * h,
2862    Shape::Empty => 0,
2863})"#),
2864            "12"
2865        );
2866    }
2867
2868    #[test]
2869    fn match_struct_destructure() {
2870        assert_eq!(
2871            say(r#"struct Point { x, y }
2872let p = Point { x: 7, y: 3 }
2873print(match p {
2874    Point { x, y } => x + y,
2875})"#),
2876            "10"
2877        );
2878    }
2879
2880    #[test]
2881    fn match_struct_partial_with_rest() {
2882        // `Point { x, .. }` matches regardless of the other
2883        // fields. The walker's match_struct_fields looks up by
2884        // name; `rest` relaxes the "mention every field" rule.
2885        assert_eq!(
2886            say(r#"struct Triple { a, b, c }
2887let t = Triple { a: 1, b: 2, c: 3 }
2888print(match t {
2889    Triple { b, .. } => b,
2890})"#),
2891            "2"
2892        );
2893    }
2894
2895    #[test]
2896    fn match_nested_pattern() {
2897        // Classic Rust-style: Err(FileError::NotFound(path)).
2898        assert_eq!(
2899            say(
2900                r#"enum FileError { NotFound(path), Permission(path), Other }
2901enum Result { Ok(value), Err(error) }
2902let r = Result::Err(FileError::NotFound("/etc/passwd"))
2903print(match r {
2904    Result::Ok(v) => v,
2905    Result::Err(FileError::NotFound(p)) => p,
2906    Result::Err(FileError::Permission(p)) => p,
2907    Result::Err(FileError::Other) => "other",
2908})"#
2909            ),
2910            "/etc/passwd"
2911        );
2912    }
2913
2914    #[test]
2915    fn match_array_exact() {
2916        assert_eq!(
2917            say(r#"let a = [1, 2, 3]
2918print(match a {
2919    [] => "empty",
2920    [x] => "one",
2921    [x, y] => "two",
2922    [x, y, z] => x + y + z,
2923    _ => "long",
2924})"#),
2925            "6"
2926        );
2927    }
2928
2929    #[test]
2930    fn match_array_with_rest() {
2931        assert_eq!(
2932            say(r#"let a = [10, 20, 30, 40, 50]
2933print(match a {
2934    [head, ..rest] => rest,
2935    _ => [],
2936})"#),
2937            "[20, 30, 40, 50]"
2938        );
2939    }
2940
2941    #[test]
2942    fn match_array_with_ignored_rest() {
2943        assert_eq!(
2944            say(r#"let a = [10, 20, 30]
2945print(match a {
2946    [first, ..] => first,
2947    _ => 0,
2948})"#),
2949            "10"
2950        );
2951    }
2952
2953    #[test]
2954    fn match_binding_scope_limited_to_arm() {
2955        assert!(
2956            run_err(
2957                r#"let v = 5
2958match v { x => print(x) }
2959print(x)"#
2960            )
2961            .contains("not found")
2962        );
2963    }
2964
2965    #[test]
2966    fn match_negative_literal() {
2967        assert_eq!(
2968            say(r#"print(match -3 {
2969    -3 => "neg three",
2970    _ => "other",
2971})"#),
2972            "neg three"
2973        );
2974    }
2975
2976    #[test]
2977    fn match_string_literal() {
2978        assert_eq!(
2979            say(r#"let s = "hello"
2980print(match s {
2981    "hi" => 1,
2982    "hello" => 2,
2983    _ => 0,
2984})"#),
2985            "2"
2986        );
2987    }
2988
2989    #[test]
2990    fn match_bool_none() {
2991        assert_eq!(
2992            say(r#"print(match true {
2993    true => "t",
2994    false => "f",
2995})"#),
2996            "t"
2997        );
2998        assert_eq!(
2999            say(r#"print(match none {
3000    none => "n",
3001    _ => "other",
3002})"#),
3003            "n"
3004        );
3005    }
3006
3007    // ─── `try` operator ────────────────────────────────────────────
3008
3009    #[test]
3010    fn try_unwraps_ok_variant() {
3011        assert_eq!(
3012            say(r#"enum Result { Ok(v), Err(e) }
3013fn doit() {
3014    let v = try Result::Ok(42)
3015    return v
3016}
3017print(doit())"#),
3018            "42"
3019        );
3020    }
3021
3022    #[test]
3023    fn try_propagates_err_variant() {
3024        // `try` on Err inside a fn causes the fn to return the
3025        // same Err variant unchanged. The caller matches it out.
3026        assert_eq!(
3027            say(r#"enum Result { Ok(v), Err(e) }
3028fn doit() {
3029    let v = try Result::Err("boom")
3030    return Result::Ok(v)
3031}
3032let r = doit()
3033print(match r {
3034    Result::Ok(v) => v,
3035    Result::Err(e) => e,
3036})"#),
3037            "boom"
3038        );
3039    }
3040
3041    #[test]
3042    fn try_sentinel_uses_flag_not_message_string() {
3043        // Regression for the tech-debt-2 refactor: the walker
3044        // used to check whether a `NyblError`'s `.message`
3045        // equalled the string `"__nybl_try_return_signal__"` to
3046        // know whether an error was a `try`-unwinding sentinel.
3047        // Now it checks `is_try_return` — a dedicated flag that
3048        // user-authored errors can't accidentally set.
3049        //
3050        // A user program whose code happens to produce that
3051        // exact message should NOT trigger try-return unwind;
3052        // it should propagate as a normal runtime error.
3053        // We can't construct that specific message from Nybl
3054        // source directly (none of our error sites spell it),
3055        // but we can verify the flag-based design by pinning
3056        // the NyblError the walker produces: a real runtime
3057        // failure has `is_try_return: false`, while a `try`-
3058        // triggered unwind internally carries `is_try_return:
3059        // true` but is caught at the fn boundary and never
3060        // reaches the caller.
3061        let mut host = TestHost::new();
3062        let err = run("print(1 / 0)", &mut host, &test_limits()).unwrap_err();
3063        assert_eq!(err.message, "Division by zero");
3064        // A real error must not be classified as a try-return
3065        // — otherwise it'd silently get swallowed by any
3066        // enclosing `try_call`.
3067        assert!(!err.is_try_return, "got: {err:?}");
3068        // And the fatal flag is independent of the try flag.
3069        assert!(!err.is_fatal, "got: {err:?}");
3070    }
3071
3072    #[test]
3073    fn try_chains_through_nested_calls() {
3074        // An Err at the deepest fn short-circuits back up through
3075        // the whole chain, skipping each caller's remaining work.
3076        assert_eq!(
3077            say(r#"enum Result { Ok(v), Err(e) }
3078fn leaf() { return Result::Err("leaf-err") }
3079fn middle() {
3080    let v = try leaf()
3081    return Result::Ok(v + 1)
3082}
3083fn top() {
3084    let v = try middle()
3085    return Result::Ok(v * 2)
3086}
3087print(match top() {
3088    Result::Ok(v) => v,
3089    Result::Err(e) => e,
3090})"#),
3091            "leaf-err"
3092        );
3093    }
3094
3095    #[test]
3096    fn user_result_with_unit_ok_coexists_with_builtin() {
3097        // Module-scoped types: the program's own `enum Result
3098        // { Ok, Err(e) }` lives under `<root>.Result`, distinct
3099        // from the `<builtin>.Result` that `try_call` returns.
3100        // `try Result::Ok` resolves to the user's root-level
3101        // Result and unwraps the Unit-Ok variant to `none`.
3102        assert_eq!(
3103            say(r#"enum Result { Ok, Err(e) }
3104fn doit() {
3105    let v = try Result::Ok
3106    return v.type()
3107}
3108print(doit())"#),
3109            "none"
3110        );
3111    }
3112
3113    #[test]
3114    fn try_inside_lambda_returns_from_lambda_only() {
3115        // The lambda's own fn-boundary catches the `try` unwind;
3116        // the caller keeps running.
3117        assert_eq!(
3118            say(r#"enum Result { Ok(v), Err(e) }
3119let f = fn() {
3120    let v = try Result::Err("inner")
3121    return Result::Ok(v)
3122}
3123let r = f()
3124print("after lambda")
3125print(match r {
3126    Result::Ok(_) => "ok",
3127    Result::Err(e) => e,
3128})"#),
3129            "inner"
3130        );
3131    }
3132
3133    #[test]
3134    fn try_at_top_level_on_err_value_errors() {
3135        let error = run_err_full(
3136            r#"enum Result { Ok(v), Err(e) }
3137let r = try Result::Err("boom")"#,
3138        );
3139        assert_eq!(
3140            error.message,
3141            crate::error_messages::TOP_LEVEL_TRY_ERROR_MESSAGE
3142        );
3143        assert_eq!(
3144            error.friendly_hint.as_deref(),
3145            Some(crate::error_messages::TOP_LEVEL_TRY_HINT)
3146        );
3147        assert_eq!(error.line, Some(2));
3148        assert_eq!(error.column, None);
3149    }
3150
3151    #[test]
3152    fn try_on_non_result_errors() {
3153        let msg = run_err(
3154            r#"fn doit() {
3155    let v = try 42
3156    return v
3157}
3158doit()"#,
3159        );
3160        assert!(msg.contains("Result-shaped"), "got: {msg}");
3161    }
3162
3163    #[test]
3164    fn try_ok_tuple_wrong_arity_errors() {
3165        // Module-scoped types: the program's own two-field
3166        // `Ok(a, b)` is a valid enum declaration (lives under
3167        // `<root>.Result`), but `try` still enforces the
3168        // "Ok must carry exactly one value" rule it uses to
3169        // unwrap successful results. The check fires at the
3170        // `try` site, not at the type declaration.
3171        let msg = run_err(
3172            r#"enum Result { Ok(a, b), Err(e) }
3173fn doit() {
3174    let v = try Result::Ok(1, 2)
3175    return v
3176}
3177doit()"#,
3178        );
3179        assert!(
3180            msg.contains("Ok variant must carry exactly one"),
3181            "got: {msg}"
3182        );
3183    }
3184
3185    #[test]
3186    fn try_in_for_loop_short_circuits() {
3187        // `try` on the first Err ends the loop and the fn.
3188        assert_eq!(
3189            say(r#"enum Result { Ok(v), Err(e) }
3190fn lookup(i) {
3191    if i == 2 { return Result::Err("stop") }
3192    return Result::Ok(i * 10)
3193}
3194fn sum_until_err() {
3195    let total = 0
3196    for i in range(5) {
3197        let v = try lookup(i)
3198        total = total + v
3199    }
3200    return Result::Ok(total)
3201}
3202print(match sum_until_err() {
3203    Result::Ok(v) => v,
3204    Result::Err(e) => e,
3205})"#),
3206            "stop"
3207        );
3208    }
3209
3210    #[test]
3211    fn try_threaded_through_nested_fn_composition() {
3212        // Mirrors the "try lowers to match" equivalence: a fn
3213        // using `try` delivers the same outcome as a hand-
3214        // written match+return using the same Err short-circuit.
3215        assert_eq!(
3216            say(r#"enum Result { Ok(v), Err(e) }
3217fn compute(input) {
3218    if input < 0 { return Result::Err("negative") }
3219    return Result::Ok(input * 2)
3220}
3221fn with_try(x) {
3222    let doubled = try compute(x)
3223    return Result::Ok(doubled + 1)
3224}
3225print(match with_try(5) { Result::Ok(v) => v, Result::Err(_) => -1 })
3226print(match with_try(-1) { Result::Ok(_) => "ok", Result::Err(e) => e })"#),
3227            "negative"
3228        );
3229    }
3230
3231    // ─── `try_call` builtin ────────────────────────────────────────
3232
3233    #[test]
3234    fn try_call_wraps_successful_return_in_ok() {
3235        // Plain successful call: `try_call(f)` yields
3236        // `Result::Ok(return_value)`. The program doesn't need
3237        // to declare `Result` — the value comes out pre-shaped
3238        // because `try_call` constructs it directly.
3239        assert_eq!(
3240            say(r#"let r = try_call(fn() { return 42 })
3241print(match r {
3242    Result::Ok(v) => v,
3243    Result::Err(_) => -1,
3244})"#),
3245            "42"
3246        );
3247    }
3248
3249    #[test]
3250    fn try_call_wraps_non_fatal_error_in_err() {
3251        // Division by zero is a non-fatal runtime error, so
3252        // `try_call` catches it and yields
3253        // `Result::Err(RuntimeError { message, line })`.
3254        assert_eq!(
3255            say(r#"let r = try_call(fn() { return 1 / 0 })
3256print(match r {
3257    Result::Ok(_) => "ok",
3258    Result::Err(e) => e.message,
3259})"#),
3260            "Division by zero"
3261        );
3262    }
3263
3264    #[test]
3265    fn try_call_runtime_error_carries_line_number() {
3266        // The RuntimeError struct exposes `line` so callers can
3267        // report where the failure happened.
3268        assert_eq!(
3269            say(r#"let r = try_call(fn() {
3270    let x = 1
3271    return x / 0
3272})
3273print(match r {
3274    Result::Ok(_) => -1,
3275    Result::Err(e) => e.line,
3276})"#),
3277            "3"
3278        );
3279    }
3280
3281    #[test]
3282    fn try_call_step_limit_error_is_fatal_and_bypasses_wrap() {
3283        // The step-limit error is fatal — `try_call` must NOT
3284        // swallow it or the sandbox invariant breaks. The
3285        // outer `run()` sees the fatal error unchanged.
3286        let tight = NyblLimits {
3287            max_steps: 200,
3288            max_memory: 1 << 20,
3289            ..NyblLimits::standard()
3290        };
3291        let mut host = TestHost::new();
3292        let err = run(
3293            r#"let r = try_call(fn() {
3294    while true { }
3295})
3296print("should never run")"#,
3297            &mut host,
3298            &tight,
3299        )
3300        .unwrap_err();
3301        assert!(err.is_fatal, "expected fatal: {}", err.message);
3302        assert!(
3303            err.message.contains("too many steps"),
3304            "got: {}",
3305            err.message
3306        );
3307        // The post-try_call `print` never ran because the
3308        // error short-circuited the program.
3309        assert!(host.prints.borrow().is_empty());
3310    }
3311
3312    #[test]
3313    fn try_call_plays_with_try_operator_to_chain_errors() {
3314        // Classic "convert caught runtime error into a Result".
3315        // The fn uses `try` to short-circuit on Err; the outer
3316        // wraps the whole thing in try_call to catch anything
3317        // it didn't anticipate.
3318        assert_eq!(
3319            say(r#"fn risky(x) {
3320    let arr = [1, 2]
3321    return arr[x]  // out-of-bounds when x > 1
3322}
3323let r = try_call(fn() { return risky(5) })
3324print(match r {
3325    Result::Ok(_) => "ok",
3326    Result::Err(e) => e.message,
3327})"#),
3328            "Index 5 is out of bounds (array has 2 items)"
3329        );
3330    }
3331
3332    #[test]
3333    fn try_call_errors_on_wrong_arg_count() {
3334        let msg = run_err("try_call()");
3335        assert!(msg.contains("try_call` expects 1"), "got: {msg}");
3336    }
3337
3338    #[test]
3339    fn try_call_errors_on_non_function_arg() {
3340        let msg = run_err("try_call(42)");
3341        assert!(msg.contains("try_call` expects a function"), "got: {msg}");
3342    }
3343
3344    #[test]
3345    fn try_call_result_ok_is_matchable_even_without_declared_type() {
3346        // The returned `Result::Ok(...)` carries a type_name
3347        // of `"Result"` and variant_name of `"Ok"` — the
3348        // pattern matcher uses string comparison, so the user's
3349        // pattern matches regardless of whether they declared
3350        // their own `Result` enum. Same for `RuntimeError`.
3351        assert_eq!(
3352            say(r#"let r = try_call(fn() { return "yay" })
3353print(match r {
3354    Result::Ok(v) => v + "!",
3355    Result::Err(_) => "bad",
3356})"#),
3357            "yay!"
3358        );
3359    }
3360
3361    #[test]
3362    fn try_call_nested_outer_sees_ok_of_inner_err() {
3363        // Inner try_call catches its own error and returns
3364        // `Result::Err(...)`. Outer try_call sees a clean
3365        // return and wraps THAT in `Result::Ok(...)`.
3366        assert_eq!(
3367            say(r#"let r = try_call(fn() {
3368    let inner = try_call(fn() { return 1 / 0 })
3369    return inner
3370})
3371print(match r {
3372    Result::Ok(Result::Err(e)) => e.message,
3373    Result::Ok(Result::Ok(_)) => "inner ok?",
3374    Result::Err(_) => "outer caught",
3375})"#),
3376            "Division by zero"
3377        );
3378    }
3379
3380    // ─── Integer type (phase 6) ────────────────────────────────────
3381
3382    #[test]
3383    fn int_literal_produces_int_value() {
3384        assert_eq!(say("print(42.type())"), "int");
3385        assert_eq!(say("print((-3).type())"), "int");
3386        assert_eq!(say("print(0.type())"), "int");
3387    }
3388
3389    #[test]
3390    fn float_literal_produces_number_value() {
3391        assert_eq!(say("print(42.0.type())"), "number");
3392        assert_eq!(say("print(3.14.type())"), "number");
3393        assert_eq!(say("print((-0.5).type())"), "number");
3394    }
3395
3396    #[test]
3397    fn int_int_arithmetic_stays_int() {
3398        assert_eq!(say("print((1 + 2).type())"), "int");
3399        assert_eq!(say("print(1 + 2)"), "3");
3400        assert_eq!(say("print(10 - 4)"), "6");
3401        assert_eq!(say("print(3 * 4)"), "12");
3402        assert_eq!(say("print(10 % 3)"), "1");
3403    }
3404
3405    #[test]
3406    fn division_slash_always_returns_number() {
3407        // `/` always produces a `Number`, even for `Int / Int`.
3408        // Sidesteps the "1 / 2 == 0" surprise every C-family
3409        // language inflicts on beginners.
3410        assert_eq!(say("print((10 / 3).type())"), "number");
3411        assert_eq!(say("print(10 / 4)"), "2.5");
3412        assert_eq!(say("print((10 / 5).type())"), "number");
3413    }
3414
3415    #[test]
3416    fn int_division_via_int_of_quotient() {
3417        // There's no dedicated `//` operator — users who want
3418        // integer division coerce the float result back with
3419        // `(...).to_int()`. Truncates toward zero, matching the
3420        // behaviour of the removed `//` operator.
3421        assert_eq!(say("print((10 / 3).to_int().type())"), "int");
3422        assert_eq!(say("print((10 / 3).to_int())"), "3");
3423        assert_eq!(say("print((-7 / 2).to_int())"), "-3");
3424        assert_eq!(say("print((10 / -3).to_int())"), "-3");
3425    }
3426
3427    #[test]
3428    fn int_number_mixed_widens_to_number() {
3429        assert_eq!(say("print((1 + 2.0).type())"), "number");
3430        assert_eq!(say("print(1 + 2.0)"), "3");
3431        assert_eq!(say("print(3 * 0.5)"), "1.5");
3432        assert_eq!(say("print((2.0 - 1).type())"), "number");
3433    }
3434
3435    #[test]
3436    fn int_comparison_uses_exact_integer_ordering() {
3437        assert_eq!(say("print(10 < 20)"), "true");
3438        assert_eq!(say("print(10 == 10)"), "true");
3439        // Cross-type numeric equality: int == number when
3440        // numerically equal.
3441        assert_eq!(say("print(1 == 1.0)"), "true");
3442        assert_eq!(say("print(2 > 1.5)"), "true");
3443    }
3444
3445    #[test]
3446    fn division_by_zero_errors() {
3447        let msg = run_err("print(10 / 0)");
3448        assert!(msg.contains("Division by zero"), "got: {msg}");
3449    }
3450
3451    #[test]
3452    fn int_overflow_on_add_errors() {
3453        // i64::MAX + 1 overflows. The message should mention
3454        // "overflow".
3455        let msg = run_err("print(9223372036854775807 + 1)");
3456        assert!(msg.contains("Integer overflow"), "got: {msg}");
3457    }
3458
3459    #[test]
3460    fn i64_min_literal_is_an_exact_int_in_expressions_and_patterns() {
3461        assert_eq!(say("print(-9223372036854775808)"), "-9223372036854775808");
3462        assert_eq!(say("print((-9223372036854775808).type())"), "int");
3463        assert_eq!(
3464            say("print(-9223372036854775808 == (-9223372036854775807 - 1))"),
3465            "true"
3466        );
3467        assert_eq!(
3468            say("print(-9223372036854775808 < -9223372036854775807)"),
3469            "true"
3470        );
3471        assert_eq!(
3472            say("print(-9223372036854775808 + 1)"),
3473            "-9223372036854775807"
3474        );
3475        assert_eq!(
3476            say(r#"let min = -9223372036854775808
3477print(match min {
3478    -9223372036854775808 => "minimum",
3479    _ => "other",
3480})"#,),
3481            "minimum"
3482        );
3483    }
3484
3485    #[test]
3486    fn int_overflow_on_neg_of_i64_min_errors() {
3487        for source in [
3488            "print(--9223372036854775808)",
3489            "print(-9223372036854775808 - 1)",
3490        ] {
3491            let msg = run_err(source);
3492            assert_eq!(msg, "Integer overflow in `-`", "source: {source}");
3493        }
3494    }
3495
3496    #[test]
3497    fn int_builtin_converts_to_int() {
3498        assert_eq!(say("print(3.7.to_int())"), "3");
3499        assert_eq!(say("print(3.7.to_int().type())"), "int");
3500        assert_eq!(say(r#"print("42".to_int())"#), "42");
3501        assert_eq!(say(r#"print("42".to_int().type())"#), "int");
3502        // Truncating a string that looks float-y still works.
3503        assert_eq!(say(r#"print("3.7".to_int())"#), "3");
3504    }
3505
3506    #[test]
3507    fn float_builtin_converts_to_number() {
3508        assert_eq!(say("print(42.to_float())"), "42");
3509        assert_eq!(say("print(42.to_float().type())"), "number");
3510        assert_eq!(say(r#"print("3.14".to_float())"#), "3.14");
3511    }
3512
3513    #[test]
3514    fn len_returns_int() {
3515        assert_eq!(say(r#"print("hi".len().type())"#), "int");
3516        assert_eq!(say("print([1, 2, 3].len().type())"), "int");
3517    }
3518
3519    #[test]
3520    fn range_produces_int_elements() {
3521        assert_eq!(say("print((range(3)[0]).type())"), "int");
3522    }
3523
3524    #[test]
3525    fn array_index_accepts_int_and_float() {
3526        // Both `arr[0]` (Int) and `arr[0.0]` (Number-via-cast)
3527        // should work — keeps legacy code with `0.0` running.
3528        assert_eq!(say("let a = [10, 20]\nprint(a[0])"), "10");
3529        assert_eq!(say("let a = [10, 20]\nprint(a[0.0])"), "10");
3530    }
3531
3532    #[test]
3533    fn int_match_literal_pattern() {
3534        assert_eq!(
3535            say(r#"let x = 2
3536print(match x {
3537    1 => "one",
3538    2 => "two",
3539    _ => "other",
3540})"#),
3541            "two"
3542        );
3543    }
3544
3545    #[test]
3546    fn repeat_accepts_int() {
3547        assert_eq!(
3548            say(r#"let n = 0
3549repeat 5 { n = n + 1 }
3550print(n)"#),
3551            "5"
3552        );
3553    }
3554
3555    #[test]
3556    fn int_overflow_literal_parse_errors() {
3557        // Integer literal that doesn't fit in i64 is a
3558        // lex-time error, not a silent downgrade to float.
3559        let msg = parse_err("let x = 99999999999999999999");
3560        assert!(msg.contains("out of range"), "got: {msg}");
3561    }
3562
3563    #[test]
3564    fn signed_integer_literal_boundaries_report_the_owning_column() {
3565        let cases = [
3566            ("let x = 9223372036854775808", 9),
3567            ("let x = 9223372036854775809", 9),
3568            ("let x = -9223372036854775809", 10),
3569        ];
3570        for (source, column) in cases {
3571            let error = parse_err_full(source);
3572            assert_eq!(error.line, Some(1), "source: {source}");
3573            assert_eq!(error.column, Some(column), "source: {source}");
3574            assert!(error.message.contains("out of range"), "error: {error:?}");
3575        }
3576    }
3577
3578    // ─── Modules / use ──────────────────────────────────────────
3579
3580    /// Host that resolves modules from an in-memory map keyed by
3581    /// the dot-joined use path. Captures prints and tracks how
3582    /// many times each module was resolved so we can pin the
3583    /// caching behaviour.
3584    struct ModuleHost {
3585        prints: RefCell<Vec<String>>,
3586        modules: std::collections::HashMap<String, String>,
3587        resolve_counts: RefCell<std::collections::HashMap<String, u32>>,
3588    }
3589
3590    impl ModuleHost {
3591        fn new(modules: &[(&str, &str)]) -> Self {
3592            let mut map = std::collections::HashMap::new();
3593            for (name, source) in modules {
3594                map.insert((*name).to_string(), (*source).to_string());
3595            }
3596            Self {
3597                prints: RefCell::new(Vec::new()),
3598                modules: map,
3599                resolve_counts: RefCell::new(std::collections::HashMap::new()),
3600            }
3601        }
3602
3603        fn prints(&self) -> Vec<String> {
3604            self.prints.borrow().clone()
3605        }
3606
3607        fn resolve_count(&self, name: &str) -> u32 {
3608            *self.resolve_counts.borrow().get(name).unwrap_or(&0)
3609        }
3610    }
3611
3612    impl NyblHost for ModuleHost {
3613        fn call(
3614            &mut self,
3615            _name: &str,
3616            _args: &[Value],
3617            _line: u32,
3618        ) -> Option<Result<Value, NyblError>> {
3619            None
3620        }
3621
3622        fn on_print(&mut self, message: &str) {
3623            self.prints.borrow_mut().push(message.to_string());
3624        }
3625
3626        fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
3627            *self
3628                .resolve_counts
3629                .borrow_mut()
3630                .entry(name.to_string())
3631                .or_insert(0) += 1;
3632            self.modules.get(name).cloned().map(Ok)
3633        }
3634    }
3635
3636    #[test]
3637    fn import_brings_let_binding_into_scope() {
3638        let mut host = ModuleHost::new(&[("math", "let pi = 3")]);
3639        run(
3640            r#"use math
3641print(pi)"#,
3642            &mut host,
3643            &NyblLimits::standard(),
3644        )
3645        .unwrap();
3646        assert_eq!(host.prints(), vec!["3"]);
3647    }
3648
3649    #[test]
3650    fn import_brings_fn_into_scope() {
3651        let mut host = ModuleHost::new(&[(
3652            "math",
3653            r#"fn square(n) { return n * n }
3654let pi = 3"#,
3655        )]);
3656        run(
3657            r#"use math
3658print(square(5))
3659print(pi)"#,
3660            &mut host,
3661            &NyblLimits::standard(),
3662        )
3663        .unwrap();
3664        assert_eq!(host.prints(), vec!["25", "3"]);
3665    }
3666
3667    #[test]
3668    fn import_dotted_path_passes_through_to_host() {
3669        let mut host = ModuleHost::new(&[("std.math", "let e = 2")]);
3670        run(
3671            r#"use std.math
3672print(e)"#,
3673            &mut host,
3674            &NyblLimits::standard(),
3675        )
3676        .unwrap();
3677        assert_eq!(host.prints(), vec!["2"]);
3678        // Exactly one resolve — `std.math` is the full key.
3679        assert_eq!(host.resolve_count("std.math"), 1);
3680    }
3681
3682    #[test]
3683    fn import_module_not_found_errors() {
3684        let mut host = ModuleHost::new(&[]);
3685        let err = run("use nope", &mut host, &NyblLimits::standard()).unwrap_err();
3686        assert!(
3687            err.message.contains("Module `nope` not found"),
3688            "got: {}",
3689            err.message
3690        );
3691    }
3692
3693    #[test]
3694    fn import_cache_resolves_once() {
3695        // Two imports of the same module in the same run should
3696        // only hit the resolver once.
3697        let mut host = ModuleHost::new(&[("m", "let x = 1")]);
3698        run(
3699            r#"use m
3700use m
3701print(x)"#,
3702            &mut host,
3703            &NyblLimits::standard(),
3704        )
3705        .unwrap();
3706        assert_eq!(host.prints(), vec!["1"]);
3707        assert_eq!(host.resolve_count("m"), 1);
3708    }
3709
3710    #[test]
3711    fn import_module_can_import_other_modules() {
3712        let mut host = ModuleHost::new(&[
3713            ("a", "use b\nlet doubled_pi = pi + pi"),
3714            ("b", "let pi = 3"),
3715        ]);
3716        run(
3717            r#"use a
3718print(doubled_pi)"#,
3719            &mut host,
3720            &NyblLimits::standard(),
3721        )
3722        .unwrap();
3723        assert_eq!(host.prints(), vec!["6"]);
3724    }
3725
3726    #[test]
3727    fn imported_module_parse_error_renders_against_module_source() {
3728        let module_source = "let okay = 1\nlet broken =";
3729        let root_source = "use bad";
3730        let mut host = ModuleHost::new(&[("bad", module_source)]);
3731
3732        let error = run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
3733        let rendered = error.render(root_source);
3734
3735        assert_eq!(
3736            error
3737                .source_context
3738                .as_ref()
3739                .map(|context| context.module_path.as_str()),
3740            Some("bad")
3741        );
3742        assert!(rendered.contains("in module `bad` at line 2"));
3743        assert!(rendered.contains("let broken ="));
3744        assert!(!rendered.contains("1 | use bad"));
3745    }
3746
3747    #[test]
3748    fn transitive_module_parse_error_preserves_leaf_identity() {
3749        let root_source = "use outer";
3750        let inner_source = "let okay = 1\nlet broken =";
3751        let mut host = ModuleHost::new(&[
3752            ("outer", "use inner\nlet outer = 1"),
3753            ("inner", inner_source),
3754        ]);
3755
3756        let error = run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
3757        let context = error.source_context.as_ref().expect("module context");
3758
3759        assert_eq!(context.module_path, "inner");
3760        assert_eq!(context.source.as_deref(), Some(inner_source));
3761        assert!(
3762            error
3763                .render(root_source)
3764                .contains("in module `inner` at line 2")
3765        );
3766    }
3767
3768    #[test]
3769    fn import_circular_detected() {
3770        let mut host = ModuleHost::new(&[("a", "use b\nlet x = 1"), ("b", "use a\nlet y = 2")]);
3771        let err = run("use a", &mut host, &NyblLimits::standard()).unwrap_err();
3772        assert!(
3773            err.message.contains("Circular import"),
3774            "got: {}",
3775            err.message
3776        );
3777    }
3778
3779    #[test]
3780    fn glob_use_over_an_existing_binding_is_an_error() {
3781        // A glob import that would bind a name the scope already defines
3782        // fails instead of silently keeping either definition.
3783        let mut host = ModuleHost::new(&[("m", "let x = 99")]);
3784        let err = run(
3785            r#"let x = 1
3786use m
3787print(x)"#,
3788            &mut host,
3789            &NyblLimits::standard(),
3790        )
3791        .unwrap_err();
3792        assert_eq!(
3793            err.message,
3794            "`x` is already defined — `use m` would import a different `x`"
3795        );
3796        assert_eq!(err.line, Some(2));
3797        assert!(host.prints().is_empty());
3798    }
3799
3800    #[test]
3801    fn use_selective_form_pulls_only_listed_names() {
3802        let mut host = ModuleHost::new(&[("m", "let a = 1\nlet b = 2\nlet c = 3")]);
3803        run(
3804            r#"use m.{a, c}
3805print(a)
3806print(c)"#,
3807            &mut host,
3808            &NyblLimits::standard(),
3809        )
3810        .expect("run ok");
3811        assert_eq!(host.prints(), vec!["1".to_string(), "3".to_string()]);
3812    }
3813
3814    #[test]
3815    fn use_selective_unknown_name_errors() {
3816        let mut host = ModuleHost::new(&[("m", "let a = 1")]);
3817        let err = run(r#"use m.{b}"#, &mut host, &NyblLimits::standard()).unwrap_err();
3818        assert!(
3819            err.message.contains("isn't exported"),
3820            "got: {}",
3821            err.message
3822        );
3823    }
3824
3825    #[test]
3826    fn use_alias_binds_module_value() {
3827        let mut host = ModuleHost::new(&[("m", "let pi = 3\nfn double(n) { return n + n }")]);
3828        run(
3829            r#"use m as m
3830print(m.pi)
3831print(m.double(7))"#,
3832            &mut host,
3833            &NyblLimits::standard(),
3834        )
3835        .expect("run ok");
3836        assert_eq!(host.prints(), vec!["3".to_string(), "14".to_string()]);
3837    }
3838
3839    #[test]
3840    fn use_alias_selective_form() {
3841        let mut host = ModuleHost::new(&[("m", "let a = 1\nlet b = 2\nlet c = 3")]);
3842        run(
3843            r#"use m.{a, c} as m
3844print(m.a)
3845print(m.c)"#,
3846            &mut host,
3847            &NyblLimits::standard(),
3848        )
3849        .expect("run ok");
3850        assert_eq!(host.prints(), vec!["1".to_string(), "3".to_string()]);
3851    }
3852
3853    #[test]
3854    fn use_alias_rejects_missing_module_field() {
3855        let mut host = ModuleHost::new(&[("m", "let a = 1")]);
3856        let err = run(
3857            r#"use m as m
3858print(m.b)"#,
3859            &mut host,
3860            &NyblLimits::standard(),
3861        )
3862        .unwrap_err();
3863        assert!(
3864            err.message.contains("isn't exported"),
3865            "got: {}",
3866            err.message
3867        );
3868    }
3869
3870    #[test]
3871    fn glob_skips_underscore_prefixed_exports() {
3872        // Privacy convention: glob import skips `_foo`, so the
3873        // importer can't see it unless they selectively opt in.
3874        let mut host = ModuleHost::new(&[("m", "let public = 1\nlet _private = 2")]);
3875        let err = run(
3876            r#"use m
3877print(_private)"#,
3878            &mut host,
3879            &NyblLimits::standard(),
3880        )
3881        .unwrap_err();
3882        // The private binding didn't land in scope — we get a
3883        // normal "variable not found" error.
3884        assert!(
3885            err.message.contains("_private"),
3886            "expected `_private not found`, got: {}",
3887            err.message
3888        );
3889    }
3890
3891    #[test]
3892    fn selective_form_can_reach_underscore_prefixed_names() {
3893        // Explicit listing overrides the privacy skip — the user
3894        // said they want `_private` and got it.
3895        let mut host = ModuleHost::new(&[("m", "let _private = 42")]);
3896        run(
3897            r#"use m.{_private}
3898print(_private)"#,
3899            &mut host,
3900            &NyblLimits::standard(),
3901        )
3902        .expect("run ok");
3903        assert_eq!(host.prints(), vec!["42".to_string()]);
3904    }
3905
3906    #[test]
3907    fn alias_exposes_underscore_prefixed_names() {
3908        // Alias form keeps everything — privacy was about not
3909        // polluting the caller's scope with glob. When the user
3910        // says `as m`, they accept the whole module surface.
3911        let mut host = ModuleHost::new(&[("m", "let _private = 7")]);
3912        run(
3913            r#"use m as m
3914print(m._private)"#,
3915            &mut host,
3916            &NyblLimits::standard(),
3917        )
3918        .expect("run ok");
3919        assert_eq!(host.prints(), vec!["7".to_string()]);
3920    }
3921
3922    #[test]
3923    fn alias_namespaced_struct_literal() {
3924        let mut host = ModuleHost::new(&[(
3925            "g",
3926            "struct Entity { id, hp }\nfn spawn(id) { return Entity { id: id, hp: 100 } }",
3927        )]);
3928        run(
3929            r#"use g as g
3930let e = g.Entity { id: 1, hp: 50 }
3931print(e.id)
3932print(e.hp)"#,
3933            &mut host,
3934            &NyblLimits::standard(),
3935        )
3936        .expect("run ok");
3937        assert_eq!(host.prints(), vec!["1".to_string(), "50".to_string()]);
3938    }
3939
3940    #[test]
3941    fn alias_namespaced_variant_ctor() {
3942        let mut host = ModuleHost::new(&[("r", "enum Result { Ok(v), Err(e) }")]);
3943        run(
3944            r#"use r as r
3945let v = r.Result::Ok(42)
3946match v {
3947    r.Result::Ok(n) => print(n),
3948    r.Result::Err(_) => print("err"),
3949}"#,
3950            &mut host,
3951            &NyblLimits::standard(),
3952        )
3953        .expect("run ok");
3954        assert_eq!(host.prints(), vec!["42".to_string()]);
3955    }
3956
3957    #[test]
3958    fn alias_module_value_is_a_module_type() {
3959        let mut host = ModuleHost::new(&[("m", "let x = 1")]);
3960        run(
3961            r#"use m as mm
3962print(mm.type())"#,
3963            &mut host,
3964            &NyblLimits::standard(),
3965        )
3966        .expect("run ok");
3967        assert_eq!(host.prints(), vec!["module".to_string()]);
3968    }
3969
3970    // ─── Structs ──────────────────────────────────────────────────
3971
3972    #[test]
3973    fn struct_decl_and_construct() {
3974        assert_eq!(
3975            say(r#"struct Point { x, y }
3976let p = Point { x: 3, y: 4 }
3977print(p.x)
3978print(p.y)"#),
3979            "4"
3980        );
3981    }
3982
3983    #[test]
3984    fn struct_display_shows_type_name_and_fields() {
3985        assert_eq!(
3986            say(r#"struct Point { x, y }
3987let p = Point { x: 3, y: 4 }
3988print(p)"#),
3989            "Point { x: 3, y: 4 }"
3990        );
3991    }
3992
3993    #[test]
3994    fn struct_fields_respect_declaration_order() {
3995        // Fields specified out of declaration order should still
3996        // appear in declaration order in the value — stable
3997        // ordering matters for `print` / `inspect` / equality.
3998        assert_eq!(
3999            say(r#"struct Point { x, y }
4000let p = Point { y: 4, x: 3 }
4001print(p)"#),
4002            "Point { x: 3, y: 4 }"
4003        );
4004    }
4005
4006    #[test]
4007    fn struct_equality_is_structural() {
4008        assert_eq!(
4009            say(r#"struct Point { x, y }
4010let a = Point { x: 1, y: 2 }
4011let b = Point { x: 1, y: 2 }
4012print(a == b)"#),
4013            "true"
4014        );
4015        assert_eq!(
4016            say(r#"struct Point { x, y }
4017let a = Point { x: 1, y: 2 }
4018let b = Point { x: 1, y: 3 }
4019print(a == b)"#),
4020            "false"
4021        );
4022    }
4023
4024    #[test]
4025    fn struct_different_types_never_equal() {
4026        assert_eq!(
4027            say(r#"struct A { x }
4028struct B { x }
4029let a = A { x: 1 }
4030let b = B { x: 1 }
4031print(a == b)"#),
4032            "false"
4033        );
4034    }
4035
4036    #[test]
4037    fn struct_type_name_is_struct() {
4038        // `type()` returns a generic bucket; a per-type name
4039        // would require `display_type_name()` which isn't wired
4040        // to the builtin yet.
4041        assert_eq!(
4042            say(r#"struct Foo { a }
4043print(Foo { a: 1 }.type())"#),
4044            "struct"
4045        );
4046    }
4047
4048    #[test]
4049    fn struct_missing_field_errors() {
4050        let err = run_err(
4051            r#"struct Point { x, y }
4052let p = Point { x: 1 }"#,
4053        );
4054        assert!(err.contains("Missing field"), "got: {err}");
4055    }
4056
4057    #[test]
4058    fn struct_extra_field_errors() {
4059        let err = run_err(
4060            r#"struct Point { x, y }
4061let p = Point { x: 1, y: 2, z: 3 }"#,
4062        );
4063        assert!(err.contains("has no field"), "got: {err}");
4064    }
4065
4066    #[test]
4067    fn struct_duplicate_field_errors() {
4068        let err = run_err(
4069            r#"struct Point { x, y }
4070let p = Point { x: 1, x: 2, y: 3 }"#,
4071        );
4072        assert!(err.contains("specified twice"), "got: {err}");
4073    }
4074
4075    #[test]
4076    fn struct_undeclared_type_errors() {
4077        let err = run_err(r#"let p = Nope { x: 1 }"#);
4078        assert!(err.contains("not declared"), "got: {err}");
4079    }
4080
4081    #[test]
4082    fn struct_field_access_missing_errors() {
4083        let err = run_err(
4084            r#"struct Point { x, y }
4085let p = Point { x: 1, y: 2 }
4086print(p.z)"#,
4087        );
4088        assert!(err.contains("no field"), "got: {err}");
4089    }
4090
4091    #[test]
4092    fn struct_field_access_on_non_struct_errors() {
4093        let err = run_err("let x = 42\nprint(x.value)");
4094        assert!(err.contains("Can't read field"), "got: {err}");
4095    }
4096
4097    #[test]
4098    fn struct_duplicate_decl_errors() {
4099        let err = run_err(
4100            r#"struct Foo { x }
4101struct Foo { y }"#,
4102        );
4103        assert!(err.contains("already declared"), "got: {err}");
4104    }
4105
4106    #[test]
4107    fn struct_nested() {
4108        assert_eq!(
4109            say(r#"struct Inner { v }
4110struct Outer { name, inner }
4111let o = Outer { name: "nest", inner: Inner { v: 42 } }
4112print(o.inner.v)"#),
4113            "42"
4114        );
4115    }
4116
4117    #[test]
4118    fn struct_in_array_and_iteration() {
4119        assert_eq!(
4120            say(r#"struct Item { name, qty }
4121let cart = [Item { name: "apple", qty: 3 }, Item { name: "banana", qty: 2 }]
4122let total = 0
4123for i in cart { total += i.qty }
4124print(total)"#),
4125            "5"
4126        );
4127    }
4128
4129    #[test]
4130    fn struct_literal_disallowed_in_if_condition_parses() {
4131        // `if Foo { body }` should parse as `if Foo` with body
4132        // `{ body }`, not as `if (Foo { body })`. Reading a
4133        // bare `Foo` ident that isn't bound fails at runtime
4134        // with "not found" — confirming the struct-literal
4135        // restriction held at parse.
4136        let err = run_err("if Foo { print(\"hi\") }");
4137        assert!(err.contains("not found"), "got: {err}");
4138    }
4139
4140    #[test]
4141    fn struct_literal_disallowed_in_for_iterable() {
4142        // `for x in arr { body }` — without the struct-literal
4143        // restriction, `arr { body }` would try to parse as a
4144        // struct literal where `arr` is the type name and `body`
4145        // is a field. The restriction ensures the `{` belongs to
4146        // the for body.
4147        assert_eq!(
4148            say("let arr = [1, 2, 3]\nlet sum = 0\nfor x in arr { sum += x }\nprint(sum)"),
4149            "6"
4150        );
4151    }
4152
4153    #[test]
4154    fn struct_literals_parse_inside_condition_delimiters() {
4155        let mut host = TestHost::new();
4156        run(
4157            r#"struct Point { x, y }
4158fn get_x(point) { return point.x }
4159let choices = [false, true]
4160
4161if get_x(Point { x: 1, y: 2 }) == 1 { print("call") }
4162if (Point { x: 2, y: 3 }).x == 2 { print("paren") }
4163if choices[Point { x: 1, y: 0 }.x] { print("index") }
4164if [Point { x: 3, y: 0 }][0].x == 3 { print("array") }
4165if {"point": Point { x: 4, y: 0 }}["point"].x == 4 { print("dict") }
4166if Ok(Point { x: 5, y: 0 }).is_ok() { print("result") }
4167if match 1 {
4168    value if Point { x: value, y: 0 }.x == 1 => Point { x: 6, y: 0 }.x,
4169    _ => 0,
4170} == 6 { print("match") }
4171if (if true { Point { x: 7, y: 0 }.x } else { 0 }) == 7 { print("if-expr") }
4172if fn() { return Point { x: 8, y: 0 }.x }() == 8 { print("lambda") }"#,
4173            &mut host,
4174            &test_limits(),
4175        )
4176        .expect("delimiter-scoped struct literals should run");
4177        assert_eq!(
4178            host.prints.borrow().clone(),
4179            [
4180                "call", "paren", "index", "array", "dict", "result", "match", "if-expr", "lambda",
4181            ]
4182        );
4183    }
4184
4185    #[test]
4186    fn control_flow_head_braces_remain_disambiguated() {
4187        assert_eq!(
4188            say(r#"const CONDITION = false
4189const ITEMS = [1, 2]
4190const COUNT = 0
4191const VALUE = 1
4192if CONDITION { print("bad-if") }
4193while CONDITION { print("bad-while") }
4194for item in ITEMS { print(item) }
4195repeat COUNT { print("bad-repeat") }
4196print(match VALUE { _ => "ok" })"#,),
4197            "ok"
4198        );
4199    }
4200
4201    #[test]
4202    fn struct_literal_ok_in_let_rhs() {
4203        // In a let rhs, struct literals are allowed. This
4204        // confirms the context flag is re-enabled outside
4205        // control-flow conditions.
4206        assert_eq!(
4207            say(r#"struct P { x }
4208let p = P { x: 7 }
4209print(p.x)"#),
4210            "7"
4211        );
4212    }
4213
4214    #[test]
4215    fn struct_field_assign_basic() {
4216        assert_eq!(
4217            say(r#"struct Point { x, y }
4218let p = Point { x: 1, y: 2 }
4219p.x = 99
4220print(p.x)
4221print(p.y)"#),
4222            "2"
4223        );
4224    }
4225
4226    #[test]
4227    fn struct_field_compound_assign() {
4228        assert_eq!(
4229            say(r#"struct Counter { n }
4230let c = Counter { n: 10 }
4231c.n += 5
4232c.n *= 2
4233print(c.n)"#),
4234            "30"
4235        );
4236    }
4237
4238    #[test]
4239    fn struct_field_assign_unknown_field_errors() {
4240        let err = run_err(
4241            r#"struct P { x }
4242let p = P { x: 1 }
4243p.y = 99"#,
4244        );
4245        assert!(err.contains("no field"), "got: {err}");
4246    }
4247
4248    #[test]
4249    fn struct_field_assign_on_non_struct_errors() {
4250        let err = run_err(
4251            r#"let x = 5
4252x.field = 1"#,
4253        );
4254        assert!(err.contains("Can't assign to field"), "got: {err}");
4255    }
4256
4257    #[test]
4258    fn struct_field_assign_chain_via_intermediate_var() {
4259        // `outer.inner.v = 99` isn't supported yet (needs nested
4260        // writeback). Users can re-build through intermediate
4261        // vars instead.
4262        assert_eq!(
4263            say(r#"struct Inner { v }
4264struct Outer { inner }
4265let o = Outer { inner: Inner { v: 1 } }
4266let i = o.inner
4267i.v = 99
4268o.inner = i
4269print(o.inner.v)"#),
4270            "99"
4271        );
4272    }
4273
4274    // ─── Enums ────────────────────────────────────────────────────
4275
4276    #[test]
4277    fn enum_unit_variant_basic() {
4278        assert_eq!(
4279            say(r#"enum Shape { Empty, Circle(r), Square(s) }
4280let s = Shape::Empty
4281print(s)"#),
4282            "Shape::Empty"
4283        );
4284    }
4285
4286    #[test]
4287    fn enum_tuple_variant() {
4288        assert_eq!(
4289            say(r#"enum Shape { Empty, Circle(r), Pair(x, y) }
4290let p = Shape::Pair(3, 4)
4291print(p)"#),
4292            "Shape::Pair(3, 4)"
4293        );
4294    }
4295
4296    #[test]
4297    fn enum_struct_variant() {
4298        assert_eq!(
4299            say(r#"enum Shape { Rectangle { width, height }, Empty }
4300let r = Shape::Rectangle { width: 4, height: 3 }
4301print(r)
4302print(r.width)
4303print(r.height)"#),
4304            "3"
4305        );
4306    }
4307
4308    #[test]
4309    fn enum_equality_same_variant() {
4310        assert_eq!(
4311            say(r#"enum E { A, B(x) }
4312print(E::A == E::A)
4313print(E::B(1) == E::B(1))
4314print(E::B(1) == E::B(2))
4315print(E::A == E::B(1))"#),
4316            "false"
4317        );
4318    }
4319
4320    #[test]
4321    fn enum_different_types_not_equal() {
4322        assert_eq!(
4323            say(r#"enum A { X }
4324enum B { X }
4325print(A::X == B::X)"#),
4326            "false"
4327        );
4328    }
4329
4330    #[test]
4331    fn enum_variant_mismatch_unit_given_args() {
4332        let err = run_err(
4333            r#"enum E { A }
4334let x = E::A(1)"#,
4335        );
4336        assert!(err.contains("no payload"), "got: {err}");
4337    }
4338
4339    #[test]
4340    fn enum_variant_mismatch_tuple_arity() {
4341        let err = run_err(
4342            r#"enum E { P(x, y) }
4343let p = E::P(1)"#,
4344        );
4345        assert!(err.contains("expects 2 argument"), "got: {err}");
4346    }
4347
4348    #[test]
4349    fn enum_variant_mismatch_struct_missing_field() {
4350        let err = run_err(
4351            r#"enum E { R { w, h } }
4352let r = E::R { w: 1 }"#,
4353        );
4354        assert!(err.contains("Missing field"), "got: {err}");
4355    }
4356
4357    #[test]
4358    fn enum_variant_mismatch_struct_extra_field() {
4359        let err = run_err(
4360            r#"enum E { R { w, h } }
4361let r = E::R { w: 1, h: 2, extra: 3 }"#,
4362        );
4363        assert!(err.contains("no field"), "got: {err}");
4364    }
4365
4366    #[test]
4367    fn enum_undeclared_variant_errors() {
4368        let err = run_err(
4369            r#"enum E { A }
4370let x = E::Z"#,
4371        );
4372        assert!(err.contains("no variant"), "got: {err}");
4373    }
4374
4375    #[test]
4376    fn enum_undeclared_type_errors() {
4377        let err = run_err("let x = Nope::V");
4378        assert!(err.contains("not declared"), "got: {err}");
4379    }
4380
4381    #[test]
4382    fn enum_struct_variant_field_access() {
4383        assert_eq!(
4384            say(r#"enum Shape { Rect { w, h }, Empty }
4385let r = Shape::Rect { w: 10, h: 3 }
4386print(r.w * r.h)"#),
4387            "30"
4388        );
4389    }
4390
4391    #[test]
4392    fn enum_used_in_if_condition() {
4393        // The struct-literal disambiguation flag also covers
4394        // enum struct-variants — `if Foo::V { body }` must
4395        // parse `V` as a unit variant and `{ body }` as the
4396        // if's block.
4397        assert_eq!(
4398            say(r#"enum E { V }
4399if E::V == E::V {
4400    print("yes")
4401} else {
4402    print("no")
4403}"#),
4404            "yes"
4405        );
4406    }
4407
4408    #[test]
4409    fn enum_type_name_is_enum() {
4410        assert_eq!(
4411            say(r#"enum E { V }
4412print((E::V).type())"#),
4413            "enum"
4414        );
4415    }
4416
4417    #[test]
4418    fn enum_in_array_of_values() {
4419        assert_eq!(
4420            say(r#"enum Color { Red, Green, Blue }
4421let palette = [Color::Red, Color::Green, Color::Blue]
4422print(palette)"#),
4423            "[Color::Red, Color::Green, Color::Blue]"
4424        );
4425    }
4426
4427    #[test]
4428    fn enum_duplicate_decl_errors() {
4429        let err = run_err(
4430            r#"enum E { A }
4431enum E { B }"#,
4432        );
4433        assert!(err.contains("already declared"), "got: {err}");
4434    }
4435
4436    // ─── User-defined methods on structs + enums ──────────────────
4437
4438    #[test]
4439    fn method_on_struct_basic() {
4440        assert_eq!(
4441            say(r#"struct Point { x, y }
4442fn Point.sum(self) { return self.x + self.y }
4443let p = Point { x: 3, y: 4 }
4444print(p.sum())"#),
4445            "7"
4446        );
4447    }
4448
4449    #[test]
4450    fn method_with_extra_args() {
4451        assert_eq!(
4452            say(r#"struct Counter { n }
4453fn Counter.add(self, delta) { return Counter { n: self.n + delta } }
4454let c = Counter { n: 10 }
4455let c2 = c.add(5)
4456print(c2.n)
4457print(c.n)"#),
4458            "10"
4459        );
4460    }
4461
4462    #[test]
4463    fn value_method_receiver_cannot_be_mutated() {
4464        let error = parse_err(
4465            r#"struct Counter { n }
4466fn Counter.bump(self) { self.n = self.n + 1 }"#,
4467        );
4468        assert!(error.contains("can't mutate value receiver `self`"));
4469    }
4470
4471    #[test]
4472    fn method_on_enum_dispatches_on_type() {
4473        assert_eq!(
4474            say(r#"enum Shape { Circle(r), Rect { w, h }, Empty }
4475fn Shape.name(self) { return "shape" }
4476print(Shape::Circle(3).name())
4477print(Shape::Rect { w: 4, h: 3 }.name())
4478print(Shape::Empty.name())"#),
4479            "shape"
4480        );
4481    }
4482
4483    #[test]
4484    fn method_overrides_builtin() {
4485        // A user-defined method of the same name as a built-in
4486        // wins — matches the walker-level dispatch rule.
4487        assert_eq!(
4488            say(r#"struct Wrapper { data }
4489fn Wrapper.len(self) { return 99 }
4490let w = Wrapper { data: [1, 2, 3] }
4491print(w.len())"#),
4492            "99"
4493        );
4494    }
4495
4496    #[test]
4497    fn method_unknown_on_struct_errors() {
4498        let err = run_err(
4499            r#"struct P { x }
4500let p = P { x: 1 }
4501p.nope()"#,
4502        );
4503        assert!(err.contains(".nope()"), "got: {err}");
4504    }
4505
4506    #[test]
4507    fn method_wrong_arg_count_errors() {
4508        let err = run_err(
4509            r#"struct P { x }
4510fn P.set(self, v) { return P { x: v } }
4511let p = P { x: 1 }
4512p.set(1, 2)"#,
4513        );
4514        assert!(err.contains("expects"), "got: {err}");
4515    }
4516
4517    #[test]
4518    fn method_chain_user_defined() {
4519        assert_eq!(
4520            say(r#"struct Adder { n }
4521fn Adder.then(self, m) { return Adder { n: self.n + m } }
4522let result = Adder { n: 1 }.then(2).then(3).then(4)
4523print(result.n)"#),
4524            "10"
4525        );
4526    }
4527
4528    #[test]
4529    fn method_self_is_clone() {
4530        // `self` in the method is independent from the caller's
4531        // binding, even if the method returns self: structural
4532        // equality still holds on the returned clone.
4533        assert_eq!(
4534            say(r#"struct P { x }
4535fn P.identity(self) { return self }
4536let a = P { x: 7 }
4537let b = a.identity()
4538print(a == b)
4539print(b.x)"#),
4540            "7"
4541        );
4542    }
4543
4544    #[test]
4545    fn method_on_enum_reads_payload_field() {
4546        assert_eq!(
4547            say(r#"enum Shape { Circle(r), Rect { w, h } }
4548fn Shape.label(self, prefix) {
4549    return prefix + "-shape"
4550}
4551let c = Shape::Circle(5)
4552print(c.label("small"))"#),
4553            "small-shape"
4554        );
4555    }
4556
4557    #[test]
4558    fn enum_duplicate_variant_errors() {
4559        let err = run_err(r#"enum E { A, A }"#);
4560        assert!(err.contains("duplicate variant"), "got: {err}");
4561    }
4562
4563    #[test]
4564    fn struct_empty() {
4565        assert_eq!(
4566            say(r#"struct Unit { }
4567let u = Unit { }
4568print(u)"#),
4569            "Unit {}"
4570        );
4571    }
4572
4573    #[test]
4574    fn import_module_does_not_see_importer_scope() {
4575        // `outer` is defined in the importer's scope; the module
4576        // must not be able to reach it.
4577        let mut host = ModuleHost::new(&[("m", "fn leak() { return outer }")]);
4578        let err = run(
4579            r#"let outer = 42
4580use m
4581print(leak())"#,
4582            &mut host,
4583            &NyblLimits::standard(),
4584        )
4585        .unwrap_err();
4586        assert!(
4587            err.message.contains("outer"),
4588            "expected 'outer' not-found error, got: {}",
4589            err.message
4590        );
4591    }
4592
4593    // ─── Const declarations + case conventions ─────────────────────
4594    //
4595    // The parser enforces three naming buckets — values are
4596    // lowercase-first, types start uppercase, constants are
4597    // all-uppercase. These tests cover the new `const` keyword
4598    // and each of the rule-violation error paths.
4599
4600    #[test]
4601    fn const_declares_an_immutable_binding() {
4602        assert_eq!(say("const PI = 3\nprint(PI)"), "3");
4603    }
4604
4605    #[test]
4606    fn const_can_reference_another_const() {
4607        assert_eq!(
4608            say("const PI = 3\nconst DIAMETER = PI * 2\nprint(DIAMETER)"),
4609            "6"
4610        );
4611    }
4612
4613    #[test]
4614    fn const_reassignment_is_refused_at_parse_time() {
4615        let err = run_err("const PI = 3\nPI = 4");
4616        assert!(
4617            err.contains("can't reassign") && err.contains("constant"),
4618            "expected const-reassignment error, got: {err}"
4619        );
4620    }
4621
4622    #[test]
4623    fn const_container_assignment_is_refused_at_parse_time() {
4624        let cases = [
4625            ("const VALUES = [1, 2]\nVALUES[0] = 9", "VALUES", 2),
4626            ("const VALUES = [1, 2]\nVALUES[0] += 9", "VALUES", 2),
4627            ("const LOOKUP = {\"n\": 1}\nLOOKUP[\"n\"] = 9", "LOOKUP", 2),
4628            ("const LOOKUP = {\"n\": 1}\nLOOKUP[\"n\"] += 9", "LOOKUP", 2),
4629            (
4630                "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\nCOUNTER.n = 9",
4631                "COUNTER",
4632                3,
4633            ),
4634            (
4635                "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\nCOUNTER.n += 9",
4636                "COUNTER",
4637                3,
4638            ),
4639        ];
4640
4641        for (source, name, line) in cases {
4642            let err = parse(source).unwrap_err();
4643            assert_eq!(
4644                err.message,
4645                format!("can't reassign `{name}` — it's a constant"),
4646                "source: {source}"
4647            );
4648            assert_eq!(err.line, Some(line), "source: {source}");
4649            assert_eq!(
4650                err.friendly_hint.as_deref(),
4651                Some("constants are immutable. Use `let` if you want a mutable binding."),
4652                "source: {source}"
4653            );
4654        }
4655    }
4656
4657    #[test]
4658    fn const_assignment_finds_grouped_and_nested_place_roots() {
4659        let cases = [
4660            "const VALUES = [1, 2]\n(VALUES)[0] = 9",
4661            "const VALUES = [1, 2]\n((VALUES))[0] += 9",
4662            "const GRID = [[1]]\nGRID[0][0] = 9",
4663            "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\n(COUNTER).n = 9",
4664        ];
4665
4666        for source in cases {
4667            let err = parse(source).unwrap_err();
4668            assert!(
4669                err.message.contains("can't reassign") && err.message.contains("constant"),
4670                "source: {source}\nerror: {err}"
4671            );
4672        }
4673    }
4674
4675    #[test]
4676    fn const_array_mutating_methods_use_the_canonical_constant_error() {
4677        let cases = [
4678            "VALUES.push(4)",
4679            "VALUES.pop()",
4680            "VALUES.insert(0, 4)",
4681            "VALUES.remove(0)",
4682            "VALUES.truncate(1)",
4683            "VALUES.clear()",
4684            "VALUES.reverse()",
4685            "(VALUES).sort()",
4686        ];
4687
4688        for call in cases {
4689            let source = format!("const VALUES = [3, 1, 2]\n{call}");
4690            let err = run_err_full(&source);
4691            assert_eq!(
4692                err.message, "can't reassign `VALUES` — it's a constant",
4693                "source: {source}"
4694            );
4695            assert_eq!(err.line, Some(2), "source: {source}");
4696            assert_eq!(
4697                err.friendly_hint.as_deref(),
4698                Some(error_messages::CONSTANT_MUTATION_HINT),
4699                "source: {source}"
4700            );
4701        }
4702
4703        let err = run_err_full(
4704            r#"fn mutate() {
4705    const VALUES = [3, 1, 2]
4706    VALUES.sort()
4707}
4708mutate()"#,
4709        );
4710        assert_eq!(err.message, "can't reassign `VALUES` — it's a constant");
4711        assert_eq!(err.line, Some(3));
4712    }
4713
4714    #[test]
4715    fn const_non_array_receivers_keep_ordinary_method_dispatch() {
4716        assert_eq!(
4717            say(r#"struct Accumulator { total }
4718fn Accumulator.push(self, value) { return self.total + value }
4719fn Accumulator.pop(self) { return self.total }
4720const ACCUMULATOR = Accumulator { total: 7 }
4721const LOOKUP = {"n": 1}
4722print([ACCUMULATOR.push(5), ACCUMULATOR.pop(), LOOKUP.keys()])"#),
4723            r#"[12, 7, ["n"]]"#
4724        );
4725
4726        // `.remove()` is now a mutating dict built-in, so a constant dict
4727        // receiver gets the canonical constant error rather than dispatch.
4728        assert_eq!(
4729            run_err(
4730                r#"const LOOKUP = {"n": 1}
4731LOOKUP.remove("n")"#
4732            ),
4733            "can't reassign `LOOKUP` — it's a constant"
4734        );
4735    }
4736
4737    #[test]
4738    fn lowercase_array_mutating_methods_remain_valid() {
4739        assert_eq!(
4740            say(r#"let values = [3, 1, 2]
4741values.sort()
4742values.reverse()
4743values.insert(1, 4)
4744values.remove(0)
4745values.push(5)
4746values.pop()
4747print(values)"#),
4748            "[4, 2, 1]"
4749        );
4750    }
4751
4752    #[test]
4753    fn const_declarations_remain_declarations_not_assignments() {
4754        // Issue #7 distinguishes a declaration that shadows/replaces an
4755        // existing same-shaped binding from an assignment to that binding.
4756        assert_eq!(
4757            say("const VALUE = [1]\nconst VALUE = [2]\nprint(VALUE[0])"),
4758            "2"
4759        );
4760    }
4761
4762    #[test]
4763    fn const_names_remain_readable_inside_mutable_assignment_targets() {
4764        assert_eq!(
4765            say("const INDEX = 0\nlet values = [1]\nvalues[INDEX] += 2\nprint(values)"),
4766            "[3]"
4767        );
4768    }
4769
4770    #[test]
4771    fn let_name_must_start_lowercase() {
4772        let err = run_err("let Foo = 1");
4773        assert!(err.to_lowercase().contains("value"), "got: {err}");
4774    }
4775
4776    #[test]
4777    fn let_with_all_caps_suggests_const() {
4778        let err = run_err("let MAX = 1");
4779        assert!(
4780            err.contains("const"),
4781            "expected hint to suggest `const`, got: {err}"
4782        );
4783    }
4784
4785    #[test]
4786    fn struct_name_must_start_uppercase() {
4787        let err = run_err("struct entity { id }");
4788        assert!(err.to_lowercase().contains("type"), "got: {err}");
4789    }
4790
4791    #[test]
4792    fn enum_variants_start_uppercase() {
4793        let err = run_err("enum Event { spawn, damage }");
4794        assert!(err.to_lowercase().contains("type"), "got: {err}");
4795    }
4796
4797    #[test]
4798    fn enum_with_all_caps_variants_is_allowed() {
4799        // `enum Dir { N, E, S, W }` — short-acronym variants are
4800        // type-shape and pass the type-name check.
4801        assert_eq!(
4802            say("enum Dir { N, E, S, W }\nlet d = Dir::E\nprint(\"ok\")"),
4803            "ok"
4804        );
4805    }
4806
4807    #[test]
4808    fn fn_name_must_start_lowercase() {
4809        let err = run_err("fn Greet() { return 1 }");
4810        assert!(err.to_lowercase().contains("value"), "got: {err}");
4811    }
4812
4813    #[test]
4814    fn fn_params_must_start_lowercase() {
4815        let err = run_err("fn greet(Name) { return Name }");
4816        assert!(err.to_lowercase().contains("value"), "got: {err}");
4817    }
4818
4819    #[test]
4820    fn all_function_forms_use_canonical_parameter_name_diagnostics() {
4821        for (source, site, name, line, column) in [
4822            ("fn run(BAD) { none }", "function parameter", "BAD", 1, 8),
4823            (
4824                "fn Thing.run(BAD) { none }",
4825                "method parameter",
4826                "BAD",
4827                1,
4828                14,
4829            ),
4830            (
4831                "let f = fn(BAD) { none }",
4832                "function parameter",
4833                "BAD",
4834                1,
4835                12,
4836            ),
4837            (
4838                "let f = fn(\n  good,\n  AlsoBad\n) { return good }",
4839                "function parameter",
4840                "AlsoBad",
4841                3,
4842                3,
4843            ),
4844        ] {
4845            let error = parse_err_full(source);
4846            assert_eq!(error.line, Some(line), "source: {source}");
4847            assert_eq!(error.column, Some(column), "source: {source}");
4848            assert_eq!(
4849                error.message,
4850                format!(
4851                    "{site} `{name}` looks like a {}, but a value name is required here",
4852                    if name == "BAD" { "constant" } else { "type" }
4853                ),
4854                "source: {source}"
4855            );
4856            assert!(error.friendly_hint.is_some(), "source: {source}");
4857        }
4858
4859        let reserved = parse_err_full("let f = fn(if) { none }");
4860        assert_eq!(reserved.line, Some(1));
4861        assert_eq!(reserved.column, Some(12));
4862        assert_eq!(reserved.message, "`if` is a reserved word in Nybl");
4863        assert!(reserved.friendly_hint.is_some());
4864    }
4865
4866    #[test]
4867    fn valid_lambda_params_keep_function_binding_semantics() {
4868        let source = r#"fn make(value) { return fn(value) { return value } }
4869let outer = 40
4870let pick = fn(_ignored, value, value) { return outer + value }
4871print(pick(1, 2, 3))
4872print(make(4)(5))"#;
4873        let mut host = TestHost::new();
4874        run(source, &mut host, &test_limits()).unwrap();
4875        assert_eq!(host.prints.borrow().as_slice(), ["43", "5"]);
4876    }
4877
4878    #[test]
4879    fn for_loop_var_must_start_lowercase() {
4880        let err = run_err("for I in range(3) { print(I) }");
4881        assert!(err.to_lowercase().contains("value"), "got: {err}");
4882    }
4883
4884    #[test]
4885    fn const_name_must_be_all_caps() {
4886        let err = run_err("const Pi = 3");
4887        assert!(err.to_lowercase().contains("constant"), "got: {err}");
4888    }
4889
4890    #[test]
4891    fn underscore_prefix_is_allowed_for_all_buckets() {
4892        // Private-by-convention — classification is unchanged.
4893        assert_eq!(
4894            say(r#"
4895                let _hidden = 1
4896                const _DEBUG = true
4897                struct _Internal { _counter }
4898                let s = _Internal { _counter: _hidden }
4899                print(s._counter)
4900            "#),
4901            "1"
4902        );
4903    }
4904
4905    // ─── host helpers ────────────────────────────────────────────────
4906
4907    // ─── module-qualified type identity ──────────────────────────────
4908
4909    #[test]
4910    fn two_modules_can_declare_same_type_name_with_different_shapes() {
4911        // Phase 2b — module-qualified types. Two modules each
4912        // declare `enum Color { ... }` with *different* variant
4913        // sets; both are usable through aliases, and values
4914        // constructed from one never compare equal to values
4915        // from the other even when the variant names match.
4916        let mut host = crate::host::StringModuleHost::new([
4917            ("paint", "enum Color { Red, Blue }"),
4918            ("other", "enum Color { Red, Green, Yellow }"),
4919        ]);
4920        run(
4921            r#"use paint as p
4922use other as o
4923let a = p.Color::Red
4924let b = o.Color::Red
4925print(a == b)
4926print(a == a)
4927print(a)
4928print(b)"#,
4929            &mut host,
4930            &NyblLimits::standard(),
4931        )
4932        .unwrap();
4933        // a and b are both `Color::Red` but from *different*
4934        // modules, so `==` is false. `a == a` is true (same
4935        // identity). Display keeps the bare type name in both
4936        // cases so surface rendering stays readable even when
4937        // the underlying identities differ.
4938        assert_eq!(host.output(), "false\ntrue\nColor::Red\nColor::Red");
4939    }
4940
4941    #[test]
4942    fn namespaced_pattern_matches_only_same_module_value() {
4943        // Patterns resolve their type reference through the
4944        // alias, so `p.Color::Red` *only* matches a value
4945        // declared in the `paint` module — not the lookalike
4946        // value from `other`.
4947        let mut host = crate::host::StringModuleHost::new([
4948            ("paint", "enum Color { Red, Blue }"),
4949            ("other", "enum Color { Red, Green, Yellow }"),
4950        ]);
4951        run(
4952            r#"use paint as p
4953use other as o
4954fn label(c) {
4955    return match c {
4956        p.Color::Red => "paint red",
4957        o.Color::Red => "other red",
4958        _ => "other",
4959    }
4960}
4961print(label(p.Color::Red))
4962print(label(o.Color::Red))
4963print(label(o.Color::Green))"#,
4964            &mut host,
4965            &NyblLimits::standard(),
4966        )
4967        .unwrap();
4968        assert_eq!(host.output(), "paint red\nother red\nother");
4969    }
4970
4971    #[test]
4972    fn string_module_host_runs_use_end_to_end() {
4973        // End-to-end sanity on the embedder helper: the host
4974        // exposes modules through its in-memory map, captures
4975        // prints, and the runtime threads them together with no
4976        // extra wiring on the embedder side.
4977        let mut host = crate::host::StringModuleHost::new([(
4978            "greetings",
4979            "fn hello(name) { print(\"hi \" + name) }",
4980        )]);
4981        run(
4982            "use greetings\nhello(\"nybl\")",
4983            &mut host,
4984            &NyblLimits::standard(),
4985        )
4986        .unwrap();
4987        assert_eq!(host.output(), "hi nybl");
4988    }
4989
4990    #[test]
4991    fn explicit_public_surfaces_filter_values_functions_and_types() {
4992        let module = r#"
4993let visible = 1
4994let hidden = 2
4995let _shown = 3
4996struct Visible { value }
4997struct Hidden { value }
4998fn read_hidden() { return hidden }
4999pub { visible, _shown, read_hidden, Visible }
5000"#;
5001        let mut host = crate::host::StringModuleHost::new([("surface", module)]);
5002        run(
5003            r#"
5004use surface as module
5005use surface
5006print([module.visible, visible, _shown, module.read_hidden(), Visible { value: 4 }])
5007"#,
5008            &mut host,
5009            &NyblLimits::standard(),
5010        )
5011        .unwrap();
5012        assert_eq!(host.output(), "[1, 1, 3, 2, Visible { value: 4 }]");
5013
5014        let mut hidden_host = crate::host::StringModuleHost::new([("surface", module)]);
5015        let hidden = run(
5016            "use surface as module\nprint(module.hidden)",
5017            &mut hidden_host,
5018            &NyblLimits::standard(),
5019        )
5020        .unwrap_err();
5021        assert!(hidden.message.contains("isn't exported"), "got: {hidden:?}");
5022
5023        let mut type_host = crate::host::StringModuleHost::new([("surface", module)]);
5024        let hidden_type = run(
5025            "use surface.{Hidden}",
5026            &mut type_host,
5027            &NyblLimits::standard(),
5028        )
5029        .unwrap_err();
5030        assert!(
5031            hidden_type.message.contains("isn't exported"),
5032            "got: {hidden_type:?}"
5033        );
5034    }
5035
5036    #[test]
5037    fn modules_without_public_surfaces_keep_legacy_private_access() {
5038        let mut host = crate::host::StringModuleHost::new([("legacy", "let _private = 9")]);
5039        run(
5040            "use legacy.{_private}\nprint(_private)",
5041            &mut host,
5042            &NyblLimits::standard(),
5043        )
5044        .unwrap();
5045        assert_eq!(host.output(), "9");
5046    }
5047
5048    // ─── column info on runtime errors ───────────────────────────────
5049
5050    #[test]
5051    fn runtime_error_carries_column_for_undefined_ident() {
5052        // Parse-time errors already carry column; runtime
5053        // errors historically did not. With column now
5054        // threaded through every `Expr` / `Stmt` at parse
5055        // time and surfaced via `error_at`, a runtime error
5056        // on a nested ident carries both line and column.
5057        let err = run_err_full("let x = 1\nprint(undefined)");
5058        assert_eq!(err.line, Some(2), "line");
5059        assert!(
5060            err.column.is_some(),
5061            "expected runtime error to carry column info, got None"
5062        );
5063    }
5064
5065    #[test]
5066    fn runtime_error_column_renders_with_caret() {
5067        // Smoke-test for the end-to-end UX: a rendered
5068        // runtime error shows `--> line:col` and a caret at
5069        // the offending column.
5070        let src = "let x = 1\nprint(undefined)";
5071        let err = run_err_full(src);
5072        let rendered = err.render(src);
5073        assert!(
5074            rendered.contains("--> line 2:"),
5075            "rendered should include line+col header, got:\n{rendered}"
5076        );
5077        assert!(
5078            rendered.contains("^"),
5079            "rendered should draw a caret, got:\n{rendered}"
5080        );
5081    }
5082
5083    #[test]
5084    fn resolve_from_map_returns_none_for_unknown_modules() {
5085        // The closure helper is a pure resolver — no print
5086        // handling, no default module. Unknown names return
5087        // `None` so the runtime falls through to its normal
5088        // "module not found" error.
5089        let resolver = crate::host::resolve_from_map([("m", "let x = 1")]);
5090        assert!(resolver("m").is_some());
5091        assert!(resolver("other").is_none());
5092    }
5093
5094    // ─── ReplSession ─────────────────────────────────────────────────
5095
5096    fn repl_eval(
5097        session: &mut ReplSession,
5098        src: &str,
5099        host: &mut TestHost,
5100    ) -> Result<Option<Value>, NyblError> {
5101        session.eval(src, host, &test_limits())
5102    }
5103
5104    #[test]
5105    fn session_let_binding_survives_between_evals() {
5106        let mut session = ReplSession::new();
5107        let mut host = TestHost::new();
5108        repl_eval(&mut session, "let x = 5", &mut host).unwrap();
5109        repl_eval(&mut session, "print(x)", &mut host).unwrap();
5110        assert_eq!(host.last_print(), "5");
5111    }
5112
5113    #[test]
5114    fn session_mutated_let_reflects_in_next_eval() {
5115        let mut session = ReplSession::new();
5116        let mut host = TestHost::new();
5117        repl_eval(&mut session, "let counter = 0", &mut host).unwrap();
5118        repl_eval(&mut session, "counter = counter + 1", &mut host).unwrap();
5119        repl_eval(&mut session, "counter = counter + 1", &mut host).unwrap();
5120        repl_eval(&mut session, "print(counter)", &mut host).unwrap();
5121        assert_eq!(host.last_print(), "2");
5122    }
5123
5124    #[test]
5125    fn session_fn_declared_on_one_eval_callable_next() {
5126        let mut session = ReplSession::new();
5127        let mut host = TestHost::new();
5128        repl_eval(&mut session, "fn double(x) { return x + x }", &mut host).unwrap();
5129        repl_eval(&mut session, "print(double(21))", &mut host).unwrap();
5130        assert_eq!(host.last_print(), "42");
5131    }
5132
5133    #[test]
5134    fn session_struct_and_method_survive() {
5135        // The stickier path: user types live in
5136        // (module_path, type_name) registries and their
5137        // methods in a separate table. Both need to carry
5138        // across inputs.
5139        let mut session = ReplSession::new();
5140        let mut host = TestHost::new();
5141        repl_eval(
5142            &mut session,
5143            "struct Point { x, y }\nfn Point.sum(self) { return self.x + self.y }",
5144            &mut host,
5145        )
5146        .unwrap();
5147        repl_eval(
5148            &mut session,
5149            "let p = Point { x: 3, y: 4 }\nprint(p.sum())",
5150            &mut host,
5151        )
5152        .unwrap();
5153        assert_eq!(host.last_print(), "7");
5154    }
5155
5156    #[test]
5157    fn session_bare_expression_returns_value() {
5158        // The REPL's "echo the last expression" affordance:
5159        // `let` returns None, a bare expression returns
5160        // Some(Value). Drives the REPL echo behaviour.
5161        let mut session = ReplSession::new();
5162        let mut host = TestHost::new();
5163        assert!(
5164            repl_eval(&mut session, "let x = 5", &mut host)
5165                .unwrap()
5166                .is_none()
5167        );
5168        let v = repl_eval(&mut session, "x + 1", &mut host).unwrap();
5169        match v {
5170            Some(Value::Int(n)) => assert_eq!(n, 6),
5171            other => panic!("expected Int(6), got: {other:?}"),
5172        }
5173    }
5174
5175    #[test]
5176    fn session_errors_preserve_earlier_effects() {
5177        // Partial-execution semantics: if a later stmt
5178        // errors, earlier bindings still stick. Matches what
5179        // a user expects from an interactive prompt.
5180        let mut session = ReplSession::new();
5181        let mut host = TestHost::new();
5182        let err = repl_eval(
5183            &mut session,
5184            "let kept = 1\nlet bad = undefined\nlet skipped = 3",
5185            &mut host,
5186        );
5187        assert!(err.is_err(), "expected runtime error");
5188        // `kept` made it; `skipped` did not.
5189        assert!(session.get("kept").is_some());
5190        assert!(session.get("skipped").is_none());
5191    }
5192
5193    #[test]
5194    fn session_normalises_scope_depth_after_block_error() {
5195        // A runtime error inside a nested block
5196        // (`if true { <error> }`) used to leave extra
5197        // scopes pushed. The session's writeback truncates
5198        // back to the root so the next `eval` starts clean.
5199        let mut session = ReplSession::new();
5200        let mut host = TestHost::new();
5201        let _ = repl_eval(
5202            &mut session,
5203            "if true {\n    let y = undefined\n}",
5204            &mut host,
5205        );
5206        // Next eval must not error on "scopes mysteriously
5207        // pre-pushed" — a plain let should work.
5208        repl_eval(&mut session, "let after = 7", &mut host).unwrap();
5209        let v = repl_eval(&mut session, "after", &mut host).unwrap();
5210        match v {
5211            Some(Value::Int(n)) => assert_eq!(n, 7),
5212            other => panic!("expected Int(7), got: {other:?}"),
5213        }
5214    }
5215
5216    #[test]
5217    fn session_binding_names_surfaces_lets_and_fns() {
5218        // `binding_names()` gives a REPL `:vars`-style
5219        // introspection hook. Covers both `let`-scope
5220        // bindings and `fn` declarations.
5221        let mut session = ReplSession::new();
5222        let mut host = TestHost::new();
5223        repl_eval(&mut session, "let alpha = 1", &mut host).unwrap();
5224        repl_eval(&mut session, "fn beta() { return 2 }", &mut host).unwrap();
5225        let names = session.binding_names();
5226        assert!(names.contains(&"alpha".to_string()));
5227        assert!(names.contains(&"beta".to_string()));
5228    }
5229
5230    #[test]
5231    fn session_use_carries_imports_across_evals() {
5232        // Custom host for this test because we need to
5233        // resolve a module. TestHost doesn't implement
5234        // `resolve_module` at the stdlib level, so we wire
5235        // a tiny one up inline.
5236        struct ModHost {
5237            prints: std::cell::RefCell<Vec<String>>,
5238        }
5239        impl NyblHost for ModHost {
5240            fn call(&mut self, _: &str, _: &[Value], _: u32) -> Option<Result<Value, NyblError>> {
5241                None
5242            }
5243            fn on_print(&mut self, message: &str) {
5244                self.prints.borrow_mut().push(message.to_string());
5245            }
5246            fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
5247                match name {
5248                    "m" => Some(Ok("fn greet() { return \"hi\" }".to_string())),
5249                    _ => None,
5250                }
5251            }
5252        }
5253        let mut host = ModHost {
5254            prints: std::cell::RefCell::new(Vec::new()),
5255        };
5256        let mut session = ReplSession::new();
5257        session.eval("use m", &mut host, &test_limits()).unwrap();
5258        session
5259            .eval("print(greet())", &mut host, &test_limits())
5260            .unwrap();
5261        let prints = host.prints.borrow();
5262        assert_eq!(prints.last().map(|s| s.as_str()), Some("hi"));
5263    }
5264}