1#![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#[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#[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
215pub use evaluator::{pattern_matches, pattern_matches_in};
219
220pub use evaluator::resolve_type_in;
227#[doc(hidden)]
228pub use evaluator::resolve_type_in_scoped;
229
230pub use evaluator::TypeResolveFn;
232
233pub use evaluator::ReplSession;
240
241#[derive(Debug, Clone)]
245pub struct NyblLimits {
246 pub max_steps: u64,
248 pub max_memory: usize,
250}
251
252impl NyblLimits {
253 pub fn standard() -> Self {
255 Self {
256 max_steps: 10_000,
257 max_memory: 10 * 1024 * 1024, }
259 }
260
261 pub fn demo() -> Self {
263 Self {
264 max_steps: 1_000,
265 max_memory: 1024 * 1024, }
267 }
268}
269
270impl Default for NyblLimits {
271 fn default() -> Self {
272 Self::standard()
273 }
274}
275
276pub trait NyblHost {
280 fn call(&mut self, name: &str, args: &[Value], line: u32) -> Option<Result<Value, NyblError>>;
282
283 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 fn on_print(&mut self, message: &str) {
302 let _ = message;
303 }
304
305 fn print_error(&self, line: u32) -> Option<NyblError> {
314 let _ = line;
315 None
316 }
317
318 fn function_hint(&self) -> &str {
320 ""
321 }
322
323 fn on_tick(&mut self) -> Result<(), NyblError> {
325 Ok(())
326 }
327
328 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
345 let _ = name;
346 None
347 }
348}
349
350pub 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
360pub fn parse(source: &str) -> Result<Vec<Stmt>, NyblError> {
362 let tokens = lexer::lex(source)?;
363 parser::parse(tokens)
364}
365
366pub 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
384pub 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#[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 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 fn test_limits() -> NyblLimits {
455 NyblLimits::standard()
456 }
457
458 fn say(code: &str) -> String {
460 let mut host = TestHost::new();
462 run(code, &mut host, &test_limits()).unwrap();
463 host.last_print()
464 }
465
466 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 fn parse_err(code: &str) -> String {
474 parse(code).unwrap_err().message
475 }
476
477 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 assert_eq!(say("print((fn(x) { return x * 3 })(4))"), "12");
1555 }
1556
1557 #[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 #[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 #[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 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 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 ("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 #[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 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 #[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 #[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 #[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 #[test]
2027 fn parse_error_carries_column_info() {
2028 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 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 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 assert!(!rendered.contains("^"), "rendered:\n{rendered}");
2091 }
2092
2093 fn parse_err_full(code: &str) -> NyblError {
2096 parse(code).unwrap_err()
2097 }
2098
2099 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 #[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 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 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 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 assert_eq!(
2198 say(r#"// this is a comment
2199let x = 42 // inline comment
2200print(x)"#),
2201 "42"
2202 );
2203 }
2204
2205 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 #[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 #[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 #[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 #[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 #[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 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 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 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 #[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 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 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 #[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 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 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 assert!(!err.is_try_return, "got: {err:?}");
2987 assert!(!err.is_fatal, "got: {err:?}");
2989 }
2990
2991 #[test]
2992 fn try_chains_through_nested_calls() {
2993 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 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 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 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 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 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 #[test]
3153 fn try_call_wraps_successful_return_in_ok() {
3154 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 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 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 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 assert!(host.prints.borrow().is_empty());
3228 }
3229
3230 #[test]
3231 fn try_call_plays_with_try_operator_to_chain_errors() {
3232 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 #[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 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 #[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 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 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 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 #[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 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 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 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 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 #[test]
4827 fn two_modules_can_declare_same_type_name_with_different_shapes() {
4828 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 assert_eq!(host.output(), "false\ntrue\nColor::Red\nColor::Red");
4856 }
4857
4858 #[test]
4859 fn namespaced_pattern_matches_only_same_module_value() {
4860 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 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 #[test]
4968 fn runtime_error_carries_column_for_undefined_ident() {
4969 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 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 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 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 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 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 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 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 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 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 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 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}