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