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]
1744 fn builtin_range_1arg() {
1745 assert_eq!(say("print(range(5))"), "[0, 1, 2, 3, 4]");
1746 }
1747
1748 #[test]
1749 fn builtin_range_2args() {
1750 assert_eq!(say("print(range(2, 5))"), "[2, 3, 4]");
1751 }
1752
1753 #[test]
1754 fn builtin_range_3args() {
1755 assert_eq!(say("print(range(0, 10, 3))"), "[0, 3, 6, 9]");
1756 }
1757
1758 #[test]
1759 fn builtin_range_reverse() {
1760 assert_eq!(say("print(range(5, 0))"), "[5, 4, 3, 2, 1]");
1761 }
1762
1763 #[test]
1764 fn builtin_str() {
1765 assert_eq!(say(r#"print(42.to_str())"#), "42");
1766 assert_eq!(say(r#"print(true.to_str())"#), "true");
1767 }
1768
1769 #[test]
1770 fn builtin_int() {
1771 assert_eq!(say("print(3.7.to_int())"), "3");
1772 assert_eq!(say("print((-2.9).to_int())"), "-2");
1773 }
1774
1775 #[test]
1776 fn builtin_type() {
1777 assert_eq!(say("print(42.type())"), "int");
1780 assert_eq!(say("print(42.0.type())"), "number");
1781 assert_eq!(say(r#"print("hi".type())"#), "string");
1782 assert_eq!(say("print(true.type())"), "bool");
1783 assert_eq!(say("print(none.type())"), "none");
1784 assert_eq!(say("print([].type())"), "array");
1785 }
1786
1787 #[test]
1788 fn builtin_abs_min_max() {
1789 assert_eq!(say("print((-5).abs())"), "5");
1790 assert_eq!(say("print(3.min(7))"), "3");
1791 assert_eq!(say("print(3.max(7))"), "7");
1792 }
1793
1794 #[test]
1795 fn builtin_len() {
1796 assert_eq!(say(r#"print("hello".len())"#), "5");
1797 assert_eq!(say("print([1, 2, 3].len())"), "3");
1798 }
1799
1800 #[test]
1801 fn builtin_inspect() {
1802 assert_eq!(say(r#"print("hi".inspect())"#), r#""hi""#);
1803 assert_eq!(say("print(42.inspect())"), "42");
1804 }
1805
1806 #[test]
1807 fn builtin_print_multi_args() {
1808 let mut host = TestHost::new();
1809 run(r#"print("a", "b", "c")"#, &mut host, &test_limits()).unwrap();
1810 assert_eq!(host.prints.borrow().as_slice(), &["a b c"]);
1811 }
1812
1813 #[test]
1814 fn builtin_rand_deterministic() {
1815 let a = say("print(rand(100))");
1816 let b = say("print(rand(100))");
1817 assert_eq!(a, b);
1818 }
1819
1820 #[test]
1823 fn error_division_by_zero() {
1824 assert!(run_err("print(1 / 0)").contains("Division by zero"));
1825 }
1826
1827 #[test]
1828 fn error_type_mismatch_subtract() {
1829 let msg = run_err(r#"print("a" - 1)"#);
1830 assert!(msg.contains("Can't use `-`"));
1831 }
1832
1833 #[test]
1834 fn error_unknown_function() {
1835 assert!(run_err("nope()").contains("not found"));
1836 }
1837
1838 #[test]
1839 fn error_infinite_loop_protection() {
1840 let msg = run_err("while true { }");
1841 assert!(msg.contains("too many steps"));
1842 }
1843
1844 #[test]
1845 fn error_break_outside_loop() {
1846 assert!(run_err("break").contains("outside of a loop"));
1847 }
1848
1849 #[test]
1850 fn error_continue_outside_loop() {
1851 assert!(run_err("continue").contains("outside of a loop"));
1852 }
1853
1854 #[test]
1857 fn parse_error_missing_rparen() {
1858 assert!(parse_err("print(1").contains("Expected `)`"));
1859 }
1860
1861 #[test]
1862 fn parse_error_missing_rbrace() {
1863 assert!(parse_err("if true {").contains("Expected `}`"));
1864 }
1865
1866 #[test]
1869 fn empty_program() {
1870 let mut host = TestHost::new();
1871 run("", &mut host, &test_limits()).unwrap();
1872 assert!(host.prints.borrow().is_empty());
1873 }
1874
1875 #[test]
1876 fn trailing_comma_in_array() {
1877 assert_eq!(say("print([1, 2, 3,])"), "[1, 2, 3]");
1878 }
1879
1880 #[test]
1881 fn trailing_comma_in_dict() {
1882 assert_eq!(say(r#"print({"a": 1,}.len())"#), "1");
1883 }
1884
1885 #[test]
1886 fn none_value() {
1887 assert_eq!(say("print(none)"), "none");
1888 assert_eq!(say("print(none == none)"), "true");
1889 }
1890
1891 #[test]
1892 fn equality_across_types() {
1893 assert_eq!(say("print(1 == true)"), "false");
1894 assert_eq!(say(r#"print(0 == "")"#), "false");
1895 assert_eq!(say("print(none == false)"), "false");
1896 }
1897
1898 #[test]
1899 fn dict_equality() {
1900 assert_eq!(
1901 say(r#"print({"a": 1, "b": 2} == {"b": 2, "a": 1})"#),
1902 "true"
1903 );
1904 assert_eq!(say(r#"print({"a": 1} == {"a": 2})"#), "false");
1905 assert_eq!(say(r#"print({"a": 1} == {"b": 1})"#), "false");
1906 assert_eq!(say(r#"print({"a": 1} == {"a": 1, "b": 2})"#), "false");
1907 assert_eq!(say(r#"print({"a": {"x": 1}} == {"a": {"x": 1}})"#), "true");
1908 }
1909
1910 #[test]
1911 fn nested_array_access() {
1912 assert_eq!(say("let m = [[1, 2], [3, 4]]\nprint(m[1][0])"), "3");
1913 }
1914
1915 #[test]
1916 fn method_chain() {
1917 assert_eq!(say(r#"print(" HELLO ".trim().lower())"#), "hello");
1918 }
1919
1920 #[test]
1923 fn parse_error_carries_column_info() {
1924 let err = parse_err_full("let 42");
1928 assert_eq!(err.line, Some(1), "err: {err:?}");
1929 assert_eq!(err.column, Some(5), "err: {err:?}");
1930 assert!(err.message.contains("Expected a name"));
1931 }
1932
1933 #[test]
1934 fn parser_reports_real_reserved_word_bindings_at_the_keyword() {
1935 for (source, keyword, line, column) in [
1936 ("let if = 1", "if", 1, 5),
1937 ("\nfn const() { none }", "const", 2, 4),
1938 ("for while in [] {}", "while", 1, 5),
1939 ("print(match 1 { if => 1, _ => 2 })", "if", 1, 17),
1940 ("print(match [1] { [..if] => 1, _ => 2 })", "if", 1, 22),
1941 ] {
1942 let error = parse_err_full(source);
1943 assert_eq!(error.line, Some(line), "source: {source}");
1944 assert_eq!(error.column, Some(column), "source: {source}");
1945 assert_eq!(
1946 error.message,
1947 format!("`{keyword}` is a reserved word in Nybl"),
1948 "source: {source}"
1949 );
1950 assert!(error.friendly_hint.is_some(), "source: {source}");
1951 }
1952 }
1953
1954 #[test]
1955 fn parse_error_renders_with_snippet_and_caret() {
1956 let src = "let 42";
1957 let err = parse_err_full(src);
1958 let rendered = err.render(src);
1959 assert!(rendered.contains("--> line 1:5"), "rendered:\n{rendered}");
1960 assert!(rendered.contains("let 42"));
1961 assert!(rendered.contains(" ^"), "rendered:\n{rendered}");
1963 }
1964
1965 #[test]
1966 fn parse_error_on_line_2_points_at_line_2() {
1967 let src = "let x = 1\nlet = 2";
1968 let err = parse_err_full(src);
1969 assert_eq!(err.line, Some(2), "err: {err:?}");
1970 let rendered = err.render(src);
1971 assert!(rendered.contains("let = 2"), "rendered:\n{rendered}");
1972 }
1973
1974 #[test]
1975 fn runtime_error_renders_without_column() {
1976 let src = "let x = 1 / 0";
1979 let err = run_err_full(src);
1980 assert_eq!(err.line, Some(1));
1981 assert!(err.column.is_none());
1982 let rendered = err.render(src);
1983 assert!(rendered.contains("--> line 1"));
1984 assert!(rendered.contains("let x = 1 / 0"));
1985 assert!(!rendered.contains("^"), "rendered:\n{rendered}");
1987 }
1988
1989 fn parse_err_full(code: &str) -> NyblError {
1992 parse(code).unwrap_err()
1993 }
1994
1995 fn run_err_full(code: &str) -> NyblError {
1997 let mut host = TestHost::new();
1998 run(code, &mut host, &test_limits()).unwrap_err()
1999 }
2000
2001 #[test]
2004 fn typo_variable_suggests_closest_local() {
2005 let err = run_err_full(
2006 r#"let length = 5
2007print(lenght)"#,
2008 );
2009 assert!(err.message.contains("not found"), "err: {err:?}");
2010 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `length`?"));
2011 }
2012
2013 #[test]
2014 fn typo_variable_falls_back_when_nothing_close() {
2015 let err = run_err_full("print(xylophone_constant)");
2018 assert_eq!(
2019 err.friendly_hint.as_deref(),
2020 Some("Did you forget to create it with `let`?")
2021 );
2022 }
2023
2024 #[test]
2025 fn typo_function_suggests_user_fn() {
2026 let err = run_err_full(
2027 r#"fn greet(name) { print("hi " + name) }
2028gret("world")"#,
2029 );
2030 assert!(err.message.contains("not found"));
2031 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `greet`?"));
2032 }
2033
2034 #[test]
2035 fn typo_builtin_suggests_core_name() {
2036 let err = run_err_full("rang(5)");
2038 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `range`?"));
2039 }
2040
2041 #[test]
2042 fn typo_struct_field_at_access_suggests_declared() {
2043 let err = run_err_full(
2044 r#"struct Point { x, y }
2045let p = Point { x: 1, y: 2 }
2046print(p.z)"#,
2047 );
2048 assert!(err.message.contains("has no field `z`"));
2049 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `x`?"));
2053 }
2054
2055 #[test]
2056 fn typo_struct_field_at_construction_suggests_declared() {
2057 let err = run_err_full(
2058 r#"struct Point { x, y }
2059let p = Point { x: 1, ya: 2 }"#,
2060 );
2061 assert!(err.message.contains("has no field `ya`"));
2062 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `y`?"));
2063 }
2064
2065 #[test]
2066 fn typo_enum_variant_suggests_declared() {
2067 let err = run_err_full(
2068 r#"enum Shape { Circle(r), Rectangle { w, h } }
2069let s = Shape::Circel(5)"#,
2070 );
2071 assert!(err.message.contains("has no variant `Circel`"));
2072 assert_eq!(err.friendly_hint.as_deref(), Some("Did you mean `Circle`?"));
2073 }
2074
2075 #[test]
2076 fn typo_hint_renders_in_source_snippet() {
2077 let src = r#"let length = 5
2078print(lenght)"#;
2079 let err = run_err_full(src);
2080 let rendered = err.render(src);
2081 assert!(
2082 rendered.contains("hint: Did you mean `length`?"),
2083 "rendered:\n{rendered}"
2084 );
2085 }
2086
2087 #[test]
2088 fn comments_in_code() {
2089 assert_eq!(
2094 say(r#"// this is a comment
2095let x = 42 // inline comment
2096print(x)"#),
2097 "42"
2098 );
2099 }
2100
2101 fn count(code: &str) -> u32 {
2104 let stmts = parse(code).unwrap();
2105 count_instructions(&stmts)
2106 }
2107
2108 #[test]
2109 fn count_simple_calls() {
2110 assert_eq!(count("print(1)"), 1);
2111 assert_eq!(count("print(1); print(2); print(3)"), 3);
2112 }
2113
2114 #[test]
2115 fn count_repeat() {
2116 assert_eq!(count("repeat 7 { print(1) }"), 2);
2117 }
2118
2119 #[test]
2120 fn count_if() {
2121 assert_eq!(count("if true { print(1) }"), 2);
2122 assert_eq!(count("if true { print(1) } else { print(2) }"), 3);
2123 }
2124
2125 #[test]
2126 fn count_while() {
2127 assert_eq!(count("while true { print(1) }"), 2);
2128 }
2129
2130 #[test]
2131 fn count_fn_skips_body() {
2132 assert_eq!(count("fn go() { print(1); print(2); print(3) }\ngo()"), 2);
2133 }
2134
2135 #[test]
2136 fn count_format_independent() {
2137 let one_line = count("repeat 7 { print(1) }");
2138 let multi_line = count("repeat 7 {\n print(1)\n}");
2139 assert_eq!(one_line, multi_line);
2140 assert_eq!(one_line, 2);
2141 }
2142
2143 #[test]
2144 fn count_nested() {
2145 assert_eq!(count("repeat 7 { if true { print(1) } }"), 3);
2146 }
2147
2148 #[test]
2149 fn count_empty_program() {
2150 assert_eq!(count(""), 0);
2151 }
2152
2153 #[test]
2156 fn if_block_scope() {
2157 assert!(
2158 run_err(
2159 r#"if true { let inner = 1 }
2160print(inner)"#
2161 )
2162 .contains("not found")
2163 );
2164 }
2165
2166 #[test]
2167 fn for_loop_var_scoped() {
2168 assert!(
2169 run_err(
2170 r#"for item in [1, 2] { let x = item }
2171print(item)"#
2172 )
2173 .contains("not found")
2174 );
2175 }
2176
2177 #[test]
2180 fn fizzbuzz() {
2181 assert_eq!(
2182 say(r#"let result = []
2183for i in range(1, 16) {
2184 if i % 15 == 0 {
2185 result.push("FizzBuzz")
2186 } else if i % 3 == 0 {
2187 result.push("Fizz")
2188 } else if i % 5 == 0 {
2189 result.push("Buzz")
2190 } else {
2191 result.push(i.to_str())
2192 }
2193}
2194print(result.join(", "))"#),
2195 "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz"
2196 );
2197 }
2198
2199 #[test]
2200 fn nested_function_calls() {
2201 assert_eq!(
2202 say(r#"fn square(n) { return n * n }
2203fn sum_squares(a, b) { return square(a) + square(b) }
2204print(sum_squares(3, 4))"#),
2205 "25"
2206 );
2207 }
2208
2209 #[test]
2210 fn array_manipulation_program() {
2211 assert_eq!(
2212 say(r#"let data = [5, 2, 8, 1, 9, 3]
2213data.sort()
2214let top3 = data.slice(3, 6)
2215print(top3.join(", "))"#),
2216 "5, 8, 9"
2217 );
2218 }
2219
2220 #[test]
2223 fn truthy_values() {
2224 assert_eq!(say("print(if 1 { \"yes\" } else { \"no\" })"), "yes");
2225 assert_eq!(say(r#"print(if "x" { "yes" } else { "no" })"#), "yes");
2226 assert_eq!(say("print(if [1] { \"yes\" } else { \"no\" })"), "yes");
2227 }
2228
2229 #[test]
2230 fn falsy_values() {
2231 assert_eq!(say("print(if 0 { \"yes\" } else { \"no\" })"), "no");
2232 assert_eq!(say("print(if false { \"yes\" } else { \"no\" })"), "no");
2233 assert_eq!(say("print(if none { \"yes\" } else { \"no\" })"), "no");
2234 assert_eq!(say(r#"print(if "" { "yes" } else { "no" })"#), "no");
2235 }
2236
2237 #[test]
2240 fn display_whole_number_as_int() {
2241 assert_eq!(say("print(5.0)"), "5");
2242 }
2243
2244 #[test]
2245 fn display_float_with_decimals() {
2246 assert_eq!(say("print(3.14)"), "3.14");
2247 }
2248
2249 #[test]
2252 fn safety_infinite_loop_halts() {
2253 let msg = run_err_with_limits("while true { }", tight_limits());
2254 assert!(msg.contains("too many steps"), "got: {msg}");
2255 }
2256
2257 #[test]
2258 fn safety_memory_bomb_string_doubling() {
2259 let msg = run_err_with_limits(
2260 r#"let s = "aaaaaaaaaa"
2261repeat 100 { s = s + s }"#,
2262 tight_limits(),
2263 );
2264 assert!(msg.contains("Memory limit"), "got: {msg}");
2265 }
2266
2267 #[test]
2268 fn safety_memory_bomb_array_growth() {
2269 let msg = run_err_with_limits(
2270 r#"let arr = []
2271repeat 1000 {
2272 arr.push("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
2273}"#,
2274 tight_limits(),
2275 );
2276 assert!(
2277 msg.contains("Memory limit") || msg.contains("too many steps"),
2278 "got: {msg}"
2279 );
2280 }
2281
2282 #[test]
2283 fn safety_deep_recursion_halts() {
2284 let handle = std::thread::Builder::new()
2294 .stack_size(8 * 1024 * 1024)
2295 .spawn(|| run_err_with_limits("fn f() { f() }\nf()", tight_limits()))
2296 .expect("spawn recursion test thread");
2297 let msg = handle.join().expect("recursion test thread panicked");
2298 assert!(
2299 msg.contains("nested function calls") || msg.contains("recursion"),
2300 "got: {msg}"
2301 );
2302 }
2303
2304 #[test]
2305 fn safety_deep_parse_nesting() {
2306 let code = "(".repeat(200) + "1" + &")".repeat(200);
2307 let msg = parse(&code).unwrap_err().message;
2308 assert!(msg.contains("nested too deeply"), "got: {msg}");
2309 }
2310
2311 #[test]
2312 fn safety_deep_parse_nesting_fits_a_2_mib_stack() {
2313 let handle = std::thread::Builder::new()
2322 .stack_size(2 * 1024 * 1024)
2323 .spawn(|| {
2324 let code = "(".repeat(200) + "1" + &")".repeat(200);
2325 parse(&code).unwrap_err().message
2326 })
2327 .expect("spawn parse test thread");
2328 let msg = handle
2329 .join()
2330 .expect("deep parse must not overflow a 2 MiB stack");
2331 assert!(msg.contains("nested too deeply"), "got: {msg}");
2332 }
2333
2334 #[test]
2335 fn safety_string_repeat_bomb() {
2336 let msg = run_err_with_limits(r#"let s = "x" * 999999"#, tight_limits());
2337 assert!(msg.contains("Memory limit"), "got: {msg}");
2338 }
2339
2340 #[test]
2341 fn safety_string_concat_bomb() {
2342 let msg = run_err_with_limits(
2343 r#"let s = "x" * 1000
2344repeat 100 { s = s + s }"#,
2345 tight_limits(),
2346 );
2347 assert!(msg.contains("Memory limit"), "got: {msg}");
2348 }
2349
2350 #[test]
2351 fn safety_array_concat_bomb() {
2352 let msg = run_err_with_limits(
2353 r#"let a = range(100)
2354repeat 50 { a = a + a }"#,
2355 tight_limits(),
2356 );
2357 assert!(
2358 msg.contains("Memory limit") || msg.contains("too many steps"),
2359 "got: {msg}"
2360 );
2361 }
2362
2363 #[test]
2364 fn safety_for_in_large_string() {
2365 let msg = run_err_with_limits(
2366 r#"let s = "x" * 10000
2367for c in s { }"#,
2368 tight_limits(),
2369 );
2370 assert!(
2371 msg.contains("too many steps") || msg.contains("Memory limit"),
2372 "got: {msg}"
2373 );
2374 }
2375
2376 #[test]
2377 fn safety_demo_limits_step_bound() {
2378 let msg = run_err_with_limits("let i = 0\nwhile true { i = i + 1 }", NyblLimits::demo());
2379 assert!(msg.contains("too many steps"), "got: {msg}");
2380 }
2381
2382 #[test]
2383 fn safety_demo_limits_memory_bound() {
2384 let msg = run_err_with_limits(
2385 r#"let s = "x" * 1100000
2386print(s)"#,
2387 NyblLimits::demo(),
2388 );
2389 assert!(msg.contains("Memory limit"), "got: {msg}");
2390 }
2391
2392 #[test]
2393 fn safety_nested_loop_step_bound() {
2394 let msg = run_err_with_limits("repeat 100 { repeat 100 { let x = 1 } }", tight_limits());
2395 assert!(msg.contains("too many steps"), "got: {msg}");
2396 }
2397
2398 #[test]
2399 fn safety_string_split_bomb() {
2400 let msg = run_err_with_limits(
2401 r#"let s = "abababababab" * 2000
2402let parts = s.split("a")
2403let x = 1"#,
2404 tight_limits(),
2405 );
2406 assert!(
2407 msg.contains("Memory limit") || msg.contains("too many steps"),
2408 "got: {msg}"
2409 );
2410 }
2411
2412 #[test]
2413 fn safety_join_bomb() {
2414 let msg = run_err_with_limits(
2415 r#"let a = []
2416repeat 400 { a.push("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }
2417let s = a.join("")
2418let x = 1"#,
2419 tight_limits(),
2420 );
2421 assert!(
2422 msg.contains("Memory limit") || msg.contains("too many steps"),
2423 "got: {msg}"
2424 );
2425 }
2426
2427 #[test]
2428 fn safety_range_hard_cap() {
2429 let msg = run_err_with_limits(
2430 r#"let a = range(100000)
2431let x = 1"#,
2432 tight_limits(),
2433 );
2434 assert!(
2435 msg.contains(builtins::RANGE_LIMIT_ERROR_MESSAGE),
2436 "got: {msg}"
2437 );
2438 }
2439
2440 #[test]
2441 fn safety_array_method_doubling() {
2442 let msg = run_err_with_limits(
2443 r#"let a = []
2444repeat 400 { a.push("aaaaaaaaaaaaaaaaaaaaaa") }
2445a.reverse()
2446let x = 1"#,
2447 tight_limits(),
2448 );
2449 assert!(
2450 msg.contains("Memory limit") || msg.contains("too many steps"),
2451 "got: {msg}"
2452 );
2453 }
2454
2455 #[test]
2456 fn safety_preflight_catches() {
2457 let limits = NyblLimits {
2458 max_steps: 500,
2459 max_memory: 32 * 1024,
2460 };
2461 let msg = run_err_with_limits(r#"let s = "x" * 40000"#, limits);
2462 assert!(msg.contains("Memory limit"), "got: {msg}");
2463 }
2464
2465 #[test]
2466 fn safety_final_retained_allocation_is_checked() {
2467 let limits = NyblLimits {
2468 max_steps: 500,
2469 max_memory: 64 * 1024,
2470 };
2471 let mut host = TestHost::new();
2472 let error = run(
2473 r#"let s = "abababab" * 1000
2474let parts = s.split("a")"#,
2475 &mut host,
2476 &limits,
2477 )
2478 .expect_err("retained allocations above the limit must fail at the return boundary");
2479 assert!(error.is_fatal);
2480 assert!(error.message.contains("Memory limit exceeded"));
2481 }
2482
2483 #[test]
2484 fn safety_dict_growth_tracked() {
2485 let msg = run_err_with_limits(
2486 r#"let d = {}
2487repeat 400 {
2488 d[d.len().to_str()] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2489}
2490let x = 1"#,
2491 tight_limits(),
2492 );
2493 assert!(
2494 msg.contains("Memory limit") || msg.contains("too many steps"),
2495 "got: {msg}"
2496 );
2497 }
2498
2499 struct CustomHost {
2502 prints: Vec<String>,
2503 }
2504
2505 impl NyblHost for CustomHost {
2506 fn call(
2507 &mut self,
2508 name: &str,
2509 args: &[Value],
2510 line: u32,
2511 ) -> Option<Result<Value, NyblError>> {
2512 match name {
2513 "greet" => {
2514 if args.len() != 1 {
2515 return Some(Err(NyblError {
2516 line: Some(line),
2517 column: None,
2518 message: "greet() needs 1 argument".into(),
2519 friendly_hint: None,
2520 source_context: None,
2521 is_fatal: false,
2522 is_try_return: false,
2523 }));
2524 }
2525 Some(Ok(Value::new_str(format!("Hello, {}!", args[0]))))
2526 }
2527 _ => None,
2528 }
2529 }
2530
2531 fn on_print(&mut self, message: &str) {
2532 self.prints.push(message.to_string());
2533 }
2534
2535 fn function_hint(&self) -> &str {
2536 "Available: greet(name)"
2537 }
2538 }
2539
2540 #[test]
2541 fn host_custom_builtin() {
2542 let mut host = CustomHost { prints: vec![] };
2543 run(
2544 r#"print(greet("world"))"#,
2545 &mut host,
2546 &NyblLimits::standard(),
2547 )
2548 .unwrap();
2549 assert_eq!(host.prints, vec!["Hello, world!"]);
2550 }
2551
2552 #[test]
2553 fn host_function_hint() {
2554 let mut host = CustomHost { prints: vec![] };
2555 let err = run("unknown()", &mut host, &NyblLimits::standard()).unwrap_err();
2556 assert!(err.message.contains("not found"));
2557 }
2558
2559 #[test]
2562 fn match_literal_arms() {
2563 assert_eq!(
2564 say(r#"let x = 2
2565let out = match x {
2566 1 => "one",
2567 2 => "two",
2568 3 => "three",
2569 _ => "other",
2570}
2571print(out)"#),
2572 "two"
2573 );
2574 }
2575
2576 #[test]
2577 fn match_falls_through_to_wildcard() {
2578 assert_eq!(
2579 say(r#"let x = 42
2580print(match x {
2581 1 => "one",
2582 _ => "other",
2583})"#),
2584 "other"
2585 );
2586 }
2587
2588 #[test]
2589 fn match_no_arm_errors() {
2590 let err = run_err(
2591 r#"let x = 5
2592match x { 1 => "a", 2 => "b" }"#,
2593 );
2594 assert!(err.contains("No match arm matched"), "got: {err}");
2595 }
2596
2597 #[test]
2598 fn match_binding_captures_scrutinee() {
2599 assert_eq!(
2600 say(r#"print(match 42 {
2601 x => x + 1,
2602})"#),
2603 "43"
2604 );
2605 }
2606
2607 #[test]
2608 fn match_guard_accepts() {
2609 assert_eq!(
2610 say(r#"print(match 7 {
2611 n if n > 10 => "big",
2612 n if n > 0 => "small",
2613 _ => "zero or less",
2614})"#),
2615 "small"
2616 );
2617 }
2618
2619 #[test]
2620 fn match_guard_rejects_continues() {
2621 assert_eq!(
2622 say(r#"print(match 5 {
2623 n if n < 0 => "neg",
2624 n if n > 100 => "huge",
2625 _ => "mid",
2626})"#),
2627 "mid"
2628 );
2629 }
2630
2631 #[test]
2632 fn match_or_pattern() {
2633 assert_eq!(
2634 say(r#"let x = 3
2635print(match x {
2636 1 | 2 | 3 => "small",
2637 _ => "other",
2638})"#),
2639 "small"
2640 );
2641 }
2642
2643 #[test]
2644 fn match_enum_unit_variant() {
2645 assert_eq!(
2646 say(r#"enum E { A, B, C }
2647print(match E::B {
2648 E::A => "a",
2649 E::B => "b",
2650 E::C => "c",
2651})"#),
2652 "b"
2653 );
2654 }
2655
2656 #[test]
2657 fn match_enum_tuple_binds() {
2658 assert_eq!(
2659 say(r#"enum Shape { Circle(r), Square(s), Empty }
2660let s = Shape::Circle(5)
2661print(match s {
2662 Shape::Circle(r) => r * 2,
2663 Shape::Square(s) => s * s,
2664 Shape::Empty => 0,
2665})"#),
2666 "10"
2667 );
2668 }
2669
2670 #[test]
2671 fn match_enum_struct_variant_binds() {
2672 assert_eq!(
2673 say(r#"enum Shape { Rect { w, h }, Empty }
2674let r = Shape::Rect { w: 4, h: 3 }
2675print(match r {
2676 Shape::Rect { w, h } => w * h,
2677 Shape::Empty => 0,
2678})"#),
2679 "12"
2680 );
2681 }
2682
2683 #[test]
2684 fn match_struct_destructure() {
2685 assert_eq!(
2686 say(r#"struct Point { x, y }
2687let p = Point { x: 7, y: 3 }
2688print(match p {
2689 Point { x, y } => x + y,
2690})"#),
2691 "10"
2692 );
2693 }
2694
2695 #[test]
2696 fn match_struct_partial_with_rest() {
2697 assert_eq!(
2701 say(r#"struct Triple { a, b, c }
2702let t = Triple { a: 1, b: 2, c: 3 }
2703print(match t {
2704 Triple { b, .. } => b,
2705})"#),
2706 "2"
2707 );
2708 }
2709
2710 #[test]
2711 fn match_nested_pattern() {
2712 assert_eq!(
2714 say(
2715 r#"enum FileError { NotFound(path), Permission(path), Other }
2716enum Result { Ok(value), Err(error) }
2717let r = Result::Err(FileError::NotFound("/etc/passwd"))
2718print(match r {
2719 Result::Ok(v) => v,
2720 Result::Err(FileError::NotFound(p)) => p,
2721 Result::Err(FileError::Permission(p)) => p,
2722 Result::Err(FileError::Other) => "other",
2723})"#
2724 ),
2725 "/etc/passwd"
2726 );
2727 }
2728
2729 #[test]
2730 fn match_array_exact() {
2731 assert_eq!(
2732 say(r#"let a = [1, 2, 3]
2733print(match a {
2734 [] => "empty",
2735 [x] => "one",
2736 [x, y] => "two",
2737 [x, y, z] => x + y + z,
2738 _ => "long",
2739})"#),
2740 "6"
2741 );
2742 }
2743
2744 #[test]
2745 fn match_array_with_rest() {
2746 assert_eq!(
2747 say(r#"let a = [10, 20, 30, 40, 50]
2748print(match a {
2749 [head, ..rest] => rest,
2750 _ => [],
2751})"#),
2752 "[20, 30, 40, 50]"
2753 );
2754 }
2755
2756 #[test]
2757 fn match_array_with_ignored_rest() {
2758 assert_eq!(
2759 say(r#"let a = [10, 20, 30]
2760print(match a {
2761 [first, ..] => first,
2762 _ => 0,
2763})"#),
2764 "10"
2765 );
2766 }
2767
2768 #[test]
2769 fn match_binding_scope_limited_to_arm() {
2770 assert!(
2771 run_err(
2772 r#"let v = 5
2773match v { x => print(x) }
2774print(x)"#
2775 )
2776 .contains("not found")
2777 );
2778 }
2779
2780 #[test]
2781 fn match_negative_literal() {
2782 assert_eq!(
2783 say(r#"print(match -3 {
2784 -3 => "neg three",
2785 _ => "other",
2786})"#),
2787 "neg three"
2788 );
2789 }
2790
2791 #[test]
2792 fn match_string_literal() {
2793 assert_eq!(
2794 say(r#"let s = "hello"
2795print(match s {
2796 "hi" => 1,
2797 "hello" => 2,
2798 _ => 0,
2799})"#),
2800 "2"
2801 );
2802 }
2803
2804 #[test]
2805 fn match_bool_none() {
2806 assert_eq!(
2807 say(r#"print(match true {
2808 true => "t",
2809 false => "f",
2810})"#),
2811 "t"
2812 );
2813 assert_eq!(
2814 say(r#"print(match none {
2815 none => "n",
2816 _ => "other",
2817})"#),
2818 "n"
2819 );
2820 }
2821
2822 #[test]
2825 fn try_unwraps_ok_variant() {
2826 assert_eq!(
2827 say(r#"enum Result { Ok(v), Err(e) }
2828fn doit() {
2829 let v = try Result::Ok(42)
2830 return v
2831}
2832print(doit())"#),
2833 "42"
2834 );
2835 }
2836
2837 #[test]
2838 fn try_propagates_err_variant() {
2839 assert_eq!(
2842 say(r#"enum Result { Ok(v), Err(e) }
2843fn doit() {
2844 let v = try Result::Err("boom")
2845 return Result::Ok(v)
2846}
2847let r = doit()
2848print(match r {
2849 Result::Ok(v) => v,
2850 Result::Err(e) => e,
2851})"#),
2852 "boom"
2853 );
2854 }
2855
2856 #[test]
2857 fn try_sentinel_uses_flag_not_message_string() {
2858 let mut host = TestHost::new();
2877 let err = run("print(1 / 0)", &mut host, &test_limits()).unwrap_err();
2878 assert_eq!(err.message, "Division by zero");
2879 assert!(!err.is_try_return, "got: {err:?}");
2883 assert!(!err.is_fatal, "got: {err:?}");
2885 }
2886
2887 #[test]
2888 fn try_chains_through_nested_calls() {
2889 assert_eq!(
2892 say(r#"enum Result { Ok(v), Err(e) }
2893fn leaf() { return Result::Err("leaf-err") }
2894fn middle() {
2895 let v = try leaf()
2896 return Result::Ok(v + 1)
2897}
2898fn top() {
2899 let v = try middle()
2900 return Result::Ok(v * 2)
2901}
2902print(match top() {
2903 Result::Ok(v) => v,
2904 Result::Err(e) => e,
2905})"#),
2906 "leaf-err"
2907 );
2908 }
2909
2910 #[test]
2911 fn user_result_with_unit_ok_coexists_with_builtin() {
2912 assert_eq!(
2918 say(r#"enum Result { Ok, Err(e) }
2919fn doit() {
2920 let v = try Result::Ok
2921 return v.type()
2922}
2923print(doit())"#),
2924 "none"
2925 );
2926 }
2927
2928 #[test]
2929 fn try_inside_lambda_returns_from_lambda_only() {
2930 assert_eq!(
2933 say(r#"enum Result { Ok(v), Err(e) }
2934let f = fn() {
2935 let v = try Result::Err("inner")
2936 return Result::Ok(v)
2937}
2938let r = f()
2939print("after lambda")
2940print(match r {
2941 Result::Ok(_) => "ok",
2942 Result::Err(e) => e,
2943})"#),
2944 "inner"
2945 );
2946 }
2947
2948 #[test]
2949 fn try_at_top_level_on_err_value_errors() {
2950 let error = run_err_full(
2951 r#"enum Result { Ok(v), Err(e) }
2952let r = try Result::Err("boom")"#,
2953 );
2954 assert_eq!(
2955 error.message,
2956 crate::error_messages::TOP_LEVEL_TRY_ERROR_MESSAGE
2957 );
2958 assert_eq!(
2959 error.friendly_hint.as_deref(),
2960 Some(crate::error_messages::TOP_LEVEL_TRY_HINT)
2961 );
2962 assert_eq!(error.line, Some(2));
2963 assert_eq!(error.column, None);
2964 }
2965
2966 #[test]
2967 fn try_on_non_result_errors() {
2968 let msg = run_err(
2969 r#"fn doit() {
2970 let v = try 42
2971 return v
2972}
2973doit()"#,
2974 );
2975 assert!(msg.contains("Result-shaped"), "got: {msg}");
2976 }
2977
2978 #[test]
2979 fn try_ok_tuple_wrong_arity_errors() {
2980 let msg = run_err(
2987 r#"enum Result { Ok(a, b), Err(e) }
2988fn doit() {
2989 let v = try Result::Ok(1, 2)
2990 return v
2991}
2992doit()"#,
2993 );
2994 assert!(
2995 msg.contains("Ok variant must carry exactly one"),
2996 "got: {msg}"
2997 );
2998 }
2999
3000 #[test]
3001 fn try_in_for_loop_short_circuits() {
3002 assert_eq!(
3004 say(r#"enum Result { Ok(v), Err(e) }
3005fn lookup(i) {
3006 if i == 2 { return Result::Err("stop") }
3007 return Result::Ok(i * 10)
3008}
3009fn sum_until_err() {
3010 let total = 0
3011 for i in range(5) {
3012 let v = try lookup(i)
3013 total = total + v
3014 }
3015 return Result::Ok(total)
3016}
3017print(match sum_until_err() {
3018 Result::Ok(v) => v,
3019 Result::Err(e) => e,
3020})"#),
3021 "stop"
3022 );
3023 }
3024
3025 #[test]
3026 fn try_threaded_through_nested_fn_composition() {
3027 assert_eq!(
3031 say(r#"enum Result { Ok(v), Err(e) }
3032fn compute(input) {
3033 if input < 0 { return Result::Err("negative") }
3034 return Result::Ok(input * 2)
3035}
3036fn with_try(x) {
3037 let doubled = try compute(x)
3038 return Result::Ok(doubled + 1)
3039}
3040print(match with_try(5) { Result::Ok(v) => v, Result::Err(_) => -1 })
3041print(match with_try(-1) { Result::Ok(_) => "ok", Result::Err(e) => e })"#),
3042 "negative"
3043 );
3044 }
3045
3046 #[test]
3049 fn try_call_wraps_successful_return_in_ok() {
3050 assert_eq!(
3055 say(r#"let r = try_call(fn() { return 42 })
3056print(match r {
3057 Result::Ok(v) => v,
3058 Result::Err(_) => -1,
3059})"#),
3060 "42"
3061 );
3062 }
3063
3064 #[test]
3065 fn try_call_wraps_non_fatal_error_in_err() {
3066 assert_eq!(
3070 say(r#"let r = try_call(fn() { return 1 / 0 })
3071print(match r {
3072 Result::Ok(_) => "ok",
3073 Result::Err(e) => e.message,
3074})"#),
3075 "Division by zero"
3076 );
3077 }
3078
3079 #[test]
3080 fn try_call_runtime_error_carries_line_number() {
3081 assert_eq!(
3084 say(r#"let r = try_call(fn() {
3085 let x = 1
3086 return x / 0
3087})
3088print(match r {
3089 Result::Ok(_) => -1,
3090 Result::Err(e) => e.line,
3091})"#),
3092 "3"
3093 );
3094 }
3095
3096 #[test]
3097 fn try_call_step_limit_error_is_fatal_and_bypasses_wrap() {
3098 let tight = NyblLimits {
3102 max_steps: 200,
3103 max_memory: 1 << 20,
3104 };
3105 let mut host = TestHost::new();
3106 let err = run(
3107 r#"let r = try_call(fn() {
3108 while true { }
3109})
3110print("should never run")"#,
3111 &mut host,
3112 &tight,
3113 )
3114 .unwrap_err();
3115 assert!(err.is_fatal, "expected fatal: {}", err.message);
3116 assert!(
3117 err.message.contains("too many steps"),
3118 "got: {}",
3119 err.message
3120 );
3121 assert!(host.prints.borrow().is_empty());
3124 }
3125
3126 #[test]
3127 fn try_call_plays_with_try_operator_to_chain_errors() {
3128 assert_eq!(
3133 say(r#"fn risky(x) {
3134 let arr = [1, 2]
3135 return arr[x] // out-of-bounds when x > 1
3136}
3137let r = try_call(fn() { return risky(5) })
3138print(match r {
3139 Result::Ok(_) => "ok",
3140 Result::Err(e) => e.message,
3141})"#),
3142 "Index 5 is out of bounds (array has 2 items)"
3143 );
3144 }
3145
3146 #[test]
3147 fn try_call_errors_on_wrong_arg_count() {
3148 let msg = run_err("try_call()");
3149 assert!(msg.contains("try_call` expects 1"), "got: {msg}");
3150 }
3151
3152 #[test]
3153 fn try_call_errors_on_non_function_arg() {
3154 let msg = run_err("try_call(42)");
3155 assert!(msg.contains("try_call` expects a function"), "got: {msg}");
3156 }
3157
3158 #[test]
3159 fn try_call_result_ok_is_matchable_even_without_declared_type() {
3160 assert_eq!(
3166 say(r#"let r = try_call(fn() { return "yay" })
3167print(match r {
3168 Result::Ok(v) => v + "!",
3169 Result::Err(_) => "bad",
3170})"#),
3171 "yay!"
3172 );
3173 }
3174
3175 #[test]
3176 fn try_call_nested_outer_sees_ok_of_inner_err() {
3177 assert_eq!(
3181 say(r#"let r = try_call(fn() {
3182 let inner = try_call(fn() { return 1 / 0 })
3183 return inner
3184})
3185print(match r {
3186 Result::Ok(Result::Err(e)) => e.message,
3187 Result::Ok(Result::Ok(_)) => "inner ok?",
3188 Result::Err(_) => "outer caught",
3189})"#),
3190 "Division by zero"
3191 );
3192 }
3193
3194 #[test]
3197 fn int_literal_produces_int_value() {
3198 assert_eq!(say("print(42.type())"), "int");
3199 assert_eq!(say("print((-3).type())"), "int");
3200 assert_eq!(say("print(0.type())"), "int");
3201 }
3202
3203 #[test]
3204 fn float_literal_produces_number_value() {
3205 assert_eq!(say("print(42.0.type())"), "number");
3206 assert_eq!(say("print(3.14.type())"), "number");
3207 assert_eq!(say("print((-0.5).type())"), "number");
3208 }
3209
3210 #[test]
3211 fn int_int_arithmetic_stays_int() {
3212 assert_eq!(say("print((1 + 2).type())"), "int");
3213 assert_eq!(say("print(1 + 2)"), "3");
3214 assert_eq!(say("print(10 - 4)"), "6");
3215 assert_eq!(say("print(3 * 4)"), "12");
3216 assert_eq!(say("print(10 % 3)"), "1");
3217 }
3218
3219 #[test]
3220 fn division_slash_always_returns_number() {
3221 assert_eq!(say("print((10 / 3).type())"), "number");
3225 assert_eq!(say("print(10 / 4)"), "2.5");
3226 assert_eq!(say("print((10 / 5).type())"), "number");
3227 }
3228
3229 #[test]
3230 fn int_division_via_int_of_quotient() {
3231 assert_eq!(say("print((10 / 3).to_int().type())"), "int");
3236 assert_eq!(say("print((10 / 3).to_int())"), "3");
3237 assert_eq!(say("print((-7 / 2).to_int())"), "-3");
3238 assert_eq!(say("print((10 / -3).to_int())"), "-3");
3239 }
3240
3241 #[test]
3242 fn int_number_mixed_widens_to_number() {
3243 assert_eq!(say("print((1 + 2.0).type())"), "number");
3244 assert_eq!(say("print(1 + 2.0)"), "3");
3245 assert_eq!(say("print(3 * 0.5)"), "1.5");
3246 assert_eq!(say("print((2.0 - 1).type())"), "number");
3247 }
3248
3249 #[test]
3250 fn int_comparison_uses_exact_integer_ordering() {
3251 assert_eq!(say("print(10 < 20)"), "true");
3252 assert_eq!(say("print(10 == 10)"), "true");
3253 assert_eq!(say("print(1 == 1.0)"), "true");
3256 assert_eq!(say("print(2 > 1.5)"), "true");
3257 }
3258
3259 #[test]
3260 fn division_by_zero_errors() {
3261 let msg = run_err("print(10 / 0)");
3262 assert!(msg.contains("Division by zero"), "got: {msg}");
3263 }
3264
3265 #[test]
3266 fn int_overflow_on_add_errors() {
3267 let msg = run_err("print(9223372036854775807 + 1)");
3270 assert!(msg.contains("Integer overflow"), "got: {msg}");
3271 }
3272
3273 #[test]
3274 fn i64_min_literal_is_an_exact_int_in_expressions_and_patterns() {
3275 assert_eq!(say("print(-9223372036854775808)"), "-9223372036854775808");
3276 assert_eq!(say("print((-9223372036854775808).type())"), "int");
3277 assert_eq!(
3278 say("print(-9223372036854775808 == (-9223372036854775807 - 1))"),
3279 "true"
3280 );
3281 assert_eq!(
3282 say("print(-9223372036854775808 < -9223372036854775807)"),
3283 "true"
3284 );
3285 assert_eq!(
3286 say("print(-9223372036854775808 + 1)"),
3287 "-9223372036854775807"
3288 );
3289 assert_eq!(
3290 say(r#"let min = -9223372036854775808
3291print(match min {
3292 -9223372036854775808 => "minimum",
3293 _ => "other",
3294})"#,),
3295 "minimum"
3296 );
3297 }
3298
3299 #[test]
3300 fn int_overflow_on_neg_of_i64_min_errors() {
3301 for source in [
3302 "print(--9223372036854775808)",
3303 "print(-9223372036854775808 - 1)",
3304 ] {
3305 let msg = run_err(source);
3306 assert_eq!(msg, "Integer overflow in `-`", "source: {source}");
3307 }
3308 }
3309
3310 #[test]
3311 fn int_builtin_converts_to_int() {
3312 assert_eq!(say("print(3.7.to_int())"), "3");
3313 assert_eq!(say("print(3.7.to_int().type())"), "int");
3314 assert_eq!(say(r#"print("42".to_int())"#), "42");
3315 assert_eq!(say(r#"print("42".to_int().type())"#), "int");
3316 assert_eq!(say(r#"print("3.7".to_int())"#), "3");
3318 }
3319
3320 #[test]
3321 fn float_builtin_converts_to_number() {
3322 assert_eq!(say("print(42.to_float())"), "42");
3323 assert_eq!(say("print(42.to_float().type())"), "number");
3324 assert_eq!(say(r#"print("3.14".to_float())"#), "3.14");
3325 }
3326
3327 #[test]
3328 fn len_returns_int() {
3329 assert_eq!(say(r#"print("hi".len().type())"#), "int");
3330 assert_eq!(say("print([1, 2, 3].len().type())"), "int");
3331 }
3332
3333 #[test]
3334 fn range_produces_int_elements() {
3335 assert_eq!(say("print((range(3)[0]).type())"), "int");
3336 }
3337
3338 #[test]
3339 fn array_index_accepts_int_and_float() {
3340 assert_eq!(say("let a = [10, 20]\nprint(a[0])"), "10");
3343 assert_eq!(say("let a = [10, 20]\nprint(a[0.0])"), "10");
3344 }
3345
3346 #[test]
3347 fn int_match_literal_pattern() {
3348 assert_eq!(
3349 say(r#"let x = 2
3350print(match x {
3351 1 => "one",
3352 2 => "two",
3353 _ => "other",
3354})"#),
3355 "two"
3356 );
3357 }
3358
3359 #[test]
3360 fn repeat_accepts_int() {
3361 assert_eq!(
3362 say(r#"let n = 0
3363repeat 5 { n = n + 1 }
3364print(n)"#),
3365 "5"
3366 );
3367 }
3368
3369 #[test]
3370 fn int_overflow_literal_parse_errors() {
3371 let msg = parse_err("let x = 99999999999999999999");
3374 assert!(msg.contains("out of range"), "got: {msg}");
3375 }
3376
3377 #[test]
3378 fn signed_integer_literal_boundaries_report_the_owning_column() {
3379 let cases = [
3380 ("let x = 9223372036854775808", 9),
3381 ("let x = 9223372036854775809", 9),
3382 ("let x = -9223372036854775809", 10),
3383 ];
3384 for (source, column) in cases {
3385 let error = parse_err_full(source);
3386 assert_eq!(error.line, Some(1), "source: {source}");
3387 assert_eq!(error.column, Some(column), "source: {source}");
3388 assert!(error.message.contains("out of range"), "error: {error:?}");
3389 }
3390 }
3391
3392 struct ModuleHost {
3399 prints: RefCell<Vec<String>>,
3400 modules: std::collections::HashMap<String, String>,
3401 resolve_counts: RefCell<std::collections::HashMap<String, u32>>,
3402 }
3403
3404 impl ModuleHost {
3405 fn new(modules: &[(&str, &str)]) -> Self {
3406 let mut map = std::collections::HashMap::new();
3407 for (name, source) in modules {
3408 map.insert((*name).to_string(), (*source).to_string());
3409 }
3410 Self {
3411 prints: RefCell::new(Vec::new()),
3412 modules: map,
3413 resolve_counts: RefCell::new(std::collections::HashMap::new()),
3414 }
3415 }
3416
3417 fn prints(&self) -> Vec<String> {
3418 self.prints.borrow().clone()
3419 }
3420
3421 fn resolve_count(&self, name: &str) -> u32 {
3422 *self.resolve_counts.borrow().get(name).unwrap_or(&0)
3423 }
3424 }
3425
3426 impl NyblHost for ModuleHost {
3427 fn call(
3428 &mut self,
3429 _name: &str,
3430 _args: &[Value],
3431 _line: u32,
3432 ) -> Option<Result<Value, NyblError>> {
3433 None
3434 }
3435
3436 fn on_print(&mut self, message: &str) {
3437 self.prints.borrow_mut().push(message.to_string());
3438 }
3439
3440 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
3441 *self
3442 .resolve_counts
3443 .borrow_mut()
3444 .entry(name.to_string())
3445 .or_insert(0) += 1;
3446 self.modules.get(name).cloned().map(Ok)
3447 }
3448 }
3449
3450 #[test]
3451 fn import_brings_let_binding_into_scope() {
3452 let mut host = ModuleHost::new(&[("math", "let pi = 3")]);
3453 run(
3454 r#"use math
3455print(pi)"#,
3456 &mut host,
3457 &NyblLimits::standard(),
3458 )
3459 .unwrap();
3460 assert_eq!(host.prints(), vec!["3"]);
3461 }
3462
3463 #[test]
3464 fn import_brings_fn_into_scope() {
3465 let mut host = ModuleHost::new(&[(
3466 "math",
3467 r#"fn square(n) { return n * n }
3468let pi = 3"#,
3469 )]);
3470 run(
3471 r#"use math
3472print(square(5))
3473print(pi)"#,
3474 &mut host,
3475 &NyblLimits::standard(),
3476 )
3477 .unwrap();
3478 assert_eq!(host.prints(), vec!["25", "3"]);
3479 }
3480
3481 #[test]
3482 fn import_dotted_path_passes_through_to_host() {
3483 let mut host = ModuleHost::new(&[("std.math", "let e = 2")]);
3484 run(
3485 r#"use std.math
3486print(e)"#,
3487 &mut host,
3488 &NyblLimits::standard(),
3489 )
3490 .unwrap();
3491 assert_eq!(host.prints(), vec!["2"]);
3492 assert_eq!(host.resolve_count("std.math"), 1);
3494 }
3495
3496 #[test]
3497 fn import_module_not_found_errors() {
3498 let mut host = ModuleHost::new(&[]);
3499 let err = run("use nope", &mut host, &NyblLimits::standard()).unwrap_err();
3500 assert!(
3501 err.message.contains("Module `nope` not found"),
3502 "got: {}",
3503 err.message
3504 );
3505 }
3506
3507 #[test]
3508 fn import_cache_resolves_once() {
3509 let mut host = ModuleHost::new(&[("m", "let x = 1")]);
3512 run(
3513 r#"use m
3514use m
3515print(x)"#,
3516 &mut host,
3517 &NyblLimits::standard(),
3518 )
3519 .unwrap();
3520 assert_eq!(host.prints(), vec!["1"]);
3521 assert_eq!(host.resolve_count("m"), 1);
3522 }
3523
3524 #[test]
3525 fn import_module_can_import_other_modules() {
3526 let mut host = ModuleHost::new(&[
3527 ("a", "use b\nlet doubled_pi = pi + pi"),
3528 ("b", "let pi = 3"),
3529 ]);
3530 run(
3531 r#"use a
3532print(doubled_pi)"#,
3533 &mut host,
3534 &NyblLimits::standard(),
3535 )
3536 .unwrap();
3537 assert_eq!(host.prints(), vec!["6"]);
3538 }
3539
3540 #[test]
3541 fn imported_module_parse_error_renders_against_module_source() {
3542 let module_source = "let okay = 1\nlet broken =";
3543 let root_source = "use bad";
3544 let mut host = ModuleHost::new(&[("bad", module_source)]);
3545
3546 let error = run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
3547 let rendered = error.render(root_source);
3548
3549 assert_eq!(
3550 error
3551 .source_context
3552 .as_ref()
3553 .map(|context| context.module_path.as_str()),
3554 Some("bad")
3555 );
3556 assert!(rendered.contains("in module `bad` at line 2"));
3557 assert!(rendered.contains("let broken ="));
3558 assert!(!rendered.contains("1 | use bad"));
3559 }
3560
3561 #[test]
3562 fn transitive_module_parse_error_preserves_leaf_identity() {
3563 let root_source = "use outer";
3564 let inner_source = "let okay = 1\nlet broken =";
3565 let mut host = ModuleHost::new(&[
3566 ("outer", "use inner\nlet outer = 1"),
3567 ("inner", inner_source),
3568 ]);
3569
3570 let error = run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
3571 let context = error.source_context.as_ref().expect("module context");
3572
3573 assert_eq!(context.module_path, "inner");
3574 assert_eq!(context.source.as_deref(), Some(inner_source));
3575 assert!(
3576 error
3577 .render(root_source)
3578 .contains("in module `inner` at line 2")
3579 );
3580 }
3581
3582 #[test]
3583 fn import_circular_detected() {
3584 let mut host = ModuleHost::new(&[("a", "use b\nlet x = 1"), ("b", "use a\nlet y = 2")]);
3585 let err = run("use a", &mut host, &NyblLimits::standard()).unwrap_err();
3586 assert!(
3587 err.message.contains("Circular import"),
3588 "got: {}",
3589 err.message
3590 );
3591 }
3592
3593 #[test]
3594 fn glob_use_shadowing_is_a_warning_first_wins() {
3595 let mut host = ModuleHost::new(&[("m", "let x = 99")]);
3602 run(
3603 r#"let x = 1
3604use m
3605print(x)"#,
3606 &mut host,
3607 &NyblLimits::standard(),
3608 )
3609 .expect("run ok");
3610 assert_eq!(host.prints(), vec!["1".to_string()]);
3611 }
3612
3613 #[test]
3614 fn use_selective_form_pulls_only_listed_names() {
3615 let mut host = ModuleHost::new(&[("m", "let a = 1\nlet b = 2\nlet c = 3")]);
3616 run(
3617 r#"use m.{a, c}
3618print(a)
3619print(c)"#,
3620 &mut host,
3621 &NyblLimits::standard(),
3622 )
3623 .expect("run ok");
3624 assert_eq!(host.prints(), vec!["1".to_string(), "3".to_string()]);
3625 }
3626
3627 #[test]
3628 fn use_selective_unknown_name_errors() {
3629 let mut host = ModuleHost::new(&[("m", "let a = 1")]);
3630 let err = run(r#"use m.{b}"#, &mut host, &NyblLimits::standard()).unwrap_err();
3631 assert!(
3632 err.message.contains("isn't exported"),
3633 "got: {}",
3634 err.message
3635 );
3636 }
3637
3638 #[test]
3639 fn use_alias_binds_module_value() {
3640 let mut host = ModuleHost::new(&[("m", "let pi = 3\nfn double(n) { return n + n }")]);
3641 run(
3642 r#"use m as m
3643print(m.pi)
3644print(m.double(7))"#,
3645 &mut host,
3646 &NyblLimits::standard(),
3647 )
3648 .expect("run ok");
3649 assert_eq!(host.prints(), vec!["3".to_string(), "14".to_string()]);
3650 }
3651
3652 #[test]
3653 fn use_alias_selective_form() {
3654 let mut host = ModuleHost::new(&[("m", "let a = 1\nlet b = 2\nlet c = 3")]);
3655 run(
3656 r#"use m.{a, c} as m
3657print(m.a)
3658print(m.c)"#,
3659 &mut host,
3660 &NyblLimits::standard(),
3661 )
3662 .expect("run ok");
3663 assert_eq!(host.prints(), vec!["1".to_string(), "3".to_string()]);
3664 }
3665
3666 #[test]
3667 fn use_alias_rejects_missing_module_field() {
3668 let mut host = ModuleHost::new(&[("m", "let a = 1")]);
3669 let err = run(
3670 r#"use m as m
3671print(m.b)"#,
3672 &mut host,
3673 &NyblLimits::standard(),
3674 )
3675 .unwrap_err();
3676 assert!(
3677 err.message.contains("isn't exported"),
3678 "got: {}",
3679 err.message
3680 );
3681 }
3682
3683 #[test]
3684 fn glob_skips_underscore_prefixed_exports() {
3685 let mut host = ModuleHost::new(&[("m", "let public = 1\nlet _private = 2")]);
3688 let err = run(
3689 r#"use m
3690print(_private)"#,
3691 &mut host,
3692 &NyblLimits::standard(),
3693 )
3694 .unwrap_err();
3695 assert!(
3698 err.message.contains("_private"),
3699 "expected `_private not found`, got: {}",
3700 err.message
3701 );
3702 }
3703
3704 #[test]
3705 fn selective_form_can_reach_underscore_prefixed_names() {
3706 let mut host = ModuleHost::new(&[("m", "let _private = 42")]);
3709 run(
3710 r#"use m.{_private}
3711print(_private)"#,
3712 &mut host,
3713 &NyblLimits::standard(),
3714 )
3715 .expect("run ok");
3716 assert_eq!(host.prints(), vec!["42".to_string()]);
3717 }
3718
3719 #[test]
3720 fn alias_exposes_underscore_prefixed_names() {
3721 let mut host = ModuleHost::new(&[("m", "let _private = 7")]);
3725 run(
3726 r#"use m as m
3727print(m._private)"#,
3728 &mut host,
3729 &NyblLimits::standard(),
3730 )
3731 .expect("run ok");
3732 assert_eq!(host.prints(), vec!["7".to_string()]);
3733 }
3734
3735 #[test]
3736 fn alias_namespaced_struct_literal() {
3737 let mut host = ModuleHost::new(&[(
3738 "g",
3739 "struct Entity { id, hp }\nfn spawn(id) { return Entity { id: id, hp: 100 } }",
3740 )]);
3741 run(
3742 r#"use g as g
3743let e = g.Entity { id: 1, hp: 50 }
3744print(e.id)
3745print(e.hp)"#,
3746 &mut host,
3747 &NyblLimits::standard(),
3748 )
3749 .expect("run ok");
3750 assert_eq!(host.prints(), vec!["1".to_string(), "50".to_string()]);
3751 }
3752
3753 #[test]
3754 fn alias_namespaced_variant_ctor() {
3755 let mut host = ModuleHost::new(&[("r", "enum Result { Ok(v), Err(e) }")]);
3756 run(
3757 r#"use r as r
3758let v = r.Result::Ok(42)
3759match v {
3760 r.Result::Ok(n) => print(n),
3761 r.Result::Err(_) => print("err"),
3762}"#,
3763 &mut host,
3764 &NyblLimits::standard(),
3765 )
3766 .expect("run ok");
3767 assert_eq!(host.prints(), vec!["42".to_string()]);
3768 }
3769
3770 #[test]
3771 fn alias_module_value_is_a_module_type() {
3772 let mut host = ModuleHost::new(&[("m", "let x = 1")]);
3773 run(
3774 r#"use m as mm
3775print(mm.type())"#,
3776 &mut host,
3777 &NyblLimits::standard(),
3778 )
3779 .expect("run ok");
3780 assert_eq!(host.prints(), vec!["module".to_string()]);
3781 }
3782
3783 #[test]
3786 fn struct_decl_and_construct() {
3787 assert_eq!(
3788 say(r#"struct Point { x, y }
3789let p = Point { x: 3, y: 4 }
3790print(p.x)
3791print(p.y)"#),
3792 "4"
3793 );
3794 }
3795
3796 #[test]
3797 fn struct_display_shows_type_name_and_fields() {
3798 assert_eq!(
3799 say(r#"struct Point { x, y }
3800let p = Point { x: 3, y: 4 }
3801print(p)"#),
3802 "Point { x: 3, y: 4 }"
3803 );
3804 }
3805
3806 #[test]
3807 fn struct_fields_respect_declaration_order() {
3808 assert_eq!(
3812 say(r#"struct Point { x, y }
3813let p = Point { y: 4, x: 3 }
3814print(p)"#),
3815 "Point { x: 3, y: 4 }"
3816 );
3817 }
3818
3819 #[test]
3820 fn struct_equality_is_structural() {
3821 assert_eq!(
3822 say(r#"struct Point { x, y }
3823let a = Point { x: 1, y: 2 }
3824let b = Point { x: 1, y: 2 }
3825print(a == b)"#),
3826 "true"
3827 );
3828 assert_eq!(
3829 say(r#"struct Point { x, y }
3830let a = Point { x: 1, y: 2 }
3831let b = Point { x: 1, y: 3 }
3832print(a == b)"#),
3833 "false"
3834 );
3835 }
3836
3837 #[test]
3838 fn struct_different_types_never_equal() {
3839 assert_eq!(
3840 say(r#"struct A { x }
3841struct B { x }
3842let a = A { x: 1 }
3843let b = B { x: 1 }
3844print(a == b)"#),
3845 "false"
3846 );
3847 }
3848
3849 #[test]
3850 fn struct_type_name_is_struct() {
3851 assert_eq!(
3855 say(r#"struct Foo { a }
3856print(Foo { a: 1 }.type())"#),
3857 "struct"
3858 );
3859 }
3860
3861 #[test]
3862 fn struct_missing_field_errors() {
3863 let err = run_err(
3864 r#"struct Point { x, y }
3865let p = Point { x: 1 }"#,
3866 );
3867 assert!(err.contains("Missing field"), "got: {err}");
3868 }
3869
3870 #[test]
3871 fn struct_extra_field_errors() {
3872 let err = run_err(
3873 r#"struct Point { x, y }
3874let p = Point { x: 1, y: 2, z: 3 }"#,
3875 );
3876 assert!(err.contains("has no field"), "got: {err}");
3877 }
3878
3879 #[test]
3880 fn struct_duplicate_field_errors() {
3881 let err = run_err(
3882 r#"struct Point { x, y }
3883let p = Point { x: 1, x: 2, y: 3 }"#,
3884 );
3885 assert!(err.contains("specified twice"), "got: {err}");
3886 }
3887
3888 #[test]
3889 fn struct_undeclared_type_errors() {
3890 let err = run_err(r#"let p = Nope { x: 1 }"#);
3891 assert!(err.contains("not declared"), "got: {err}");
3892 }
3893
3894 #[test]
3895 fn struct_field_access_missing_errors() {
3896 let err = run_err(
3897 r#"struct Point { x, y }
3898let p = Point { x: 1, y: 2 }
3899print(p.z)"#,
3900 );
3901 assert!(err.contains("no field"), "got: {err}");
3902 }
3903
3904 #[test]
3905 fn struct_field_access_on_non_struct_errors() {
3906 let err = run_err("let x = 42\nprint(x.value)");
3907 assert!(err.contains("Can't read field"), "got: {err}");
3908 }
3909
3910 #[test]
3911 fn struct_duplicate_decl_errors() {
3912 let err = run_err(
3913 r#"struct Foo { x }
3914struct Foo { y }"#,
3915 );
3916 assert!(err.contains("already declared"), "got: {err}");
3917 }
3918
3919 #[test]
3920 fn struct_nested() {
3921 assert_eq!(
3922 say(r#"struct Inner { v }
3923struct Outer { name, inner }
3924let o = Outer { name: "nest", inner: Inner { v: 42 } }
3925print(o.inner.v)"#),
3926 "42"
3927 );
3928 }
3929
3930 #[test]
3931 fn struct_in_array_and_iteration() {
3932 assert_eq!(
3933 say(r#"struct Item { name, qty }
3934let cart = [Item { name: "apple", qty: 3 }, Item { name: "banana", qty: 2 }]
3935let total = 0
3936for i in cart { total += i.qty }
3937print(total)"#),
3938 "5"
3939 );
3940 }
3941
3942 #[test]
3943 fn struct_literal_disallowed_in_if_condition_parses() {
3944 let err = run_err("if Foo { print(\"hi\") }");
3950 assert!(err.contains("not found"), "got: {err}");
3951 }
3952
3953 #[test]
3954 fn struct_literal_disallowed_in_for_iterable() {
3955 assert_eq!(
3961 say("let arr = [1, 2, 3]\nlet sum = 0\nfor x in arr { sum += x }\nprint(sum)"),
3962 "6"
3963 );
3964 }
3965
3966 #[test]
3967 fn struct_literals_parse_inside_condition_delimiters() {
3968 let mut host = TestHost::new();
3969 run(
3970 r#"struct Point { x, y }
3971fn get_x(point) { return point.x }
3972let choices = [false, true]
3973
3974if get_x(Point { x: 1, y: 2 }) == 1 { print("call") }
3975if (Point { x: 2, y: 3 }).x == 2 { print("paren") }
3976if choices[Point { x: 1, y: 0 }.x] { print("index") }
3977if [Point { x: 3, y: 0 }][0].x == 3 { print("array") }
3978if {"point": Point { x: 4, y: 0 }}["point"].x == 4 { print("dict") }
3979if Ok(Point { x: 5, y: 0 }).is_ok() { print("result") }
3980if match 1 {
3981 value if Point { x: value, y: 0 }.x == 1 => Point { x: 6, y: 0 }.x,
3982 _ => 0,
3983} == 6 { print("match") }
3984if (if true { Point { x: 7, y: 0 }.x } else { 0 }) == 7 { print("if-expr") }
3985if fn() { return Point { x: 8, y: 0 }.x }() == 8 { print("lambda") }"#,
3986 &mut host,
3987 &test_limits(),
3988 )
3989 .expect("delimiter-scoped struct literals should run");
3990 assert_eq!(
3991 host.prints.borrow().clone(),
3992 [
3993 "call", "paren", "index", "array", "dict", "result", "match", "if-expr", "lambda",
3994 ]
3995 );
3996 }
3997
3998 #[test]
3999 fn control_flow_head_braces_remain_disambiguated() {
4000 assert_eq!(
4001 say(r#"const CONDITION = false
4002const ITEMS = [1, 2]
4003const COUNT = 0
4004const VALUE = 1
4005if CONDITION { print("bad-if") }
4006while CONDITION { print("bad-while") }
4007for item in ITEMS { print(item) }
4008repeat COUNT { print("bad-repeat") }
4009print(match VALUE { _ => "ok" })"#,),
4010 "ok"
4011 );
4012 }
4013
4014 #[test]
4015 fn struct_literal_ok_in_let_rhs() {
4016 assert_eq!(
4020 say(r#"struct P { x }
4021let p = P { x: 7 }
4022print(p.x)"#),
4023 "7"
4024 );
4025 }
4026
4027 #[test]
4028 fn struct_field_assign_basic() {
4029 assert_eq!(
4030 say(r#"struct Point { x, y }
4031let p = Point { x: 1, y: 2 }
4032p.x = 99
4033print(p.x)
4034print(p.y)"#),
4035 "2"
4036 );
4037 }
4038
4039 #[test]
4040 fn struct_field_compound_assign() {
4041 assert_eq!(
4042 say(r#"struct Counter { n }
4043let c = Counter { n: 10 }
4044c.n += 5
4045c.n *= 2
4046print(c.n)"#),
4047 "30"
4048 );
4049 }
4050
4051 #[test]
4052 fn struct_field_assign_unknown_field_errors() {
4053 let err = run_err(
4054 r#"struct P { x }
4055let p = P { x: 1 }
4056p.y = 99"#,
4057 );
4058 assert!(err.contains("no field"), "got: {err}");
4059 }
4060
4061 #[test]
4062 fn struct_field_assign_on_non_struct_errors() {
4063 let err = run_err(
4064 r#"let x = 5
4065x.field = 1"#,
4066 );
4067 assert!(err.contains("Can't assign to field"), "got: {err}");
4068 }
4069
4070 #[test]
4071 fn struct_field_assign_chain_via_intermediate_var() {
4072 assert_eq!(
4076 say(r#"struct Inner { v }
4077struct Outer { inner }
4078let o = Outer { inner: Inner { v: 1 } }
4079let i = o.inner
4080i.v = 99
4081o.inner = i
4082print(o.inner.v)"#),
4083 "99"
4084 );
4085 }
4086
4087 #[test]
4090 fn enum_unit_variant_basic() {
4091 assert_eq!(
4092 say(r#"enum Shape { Empty, Circle(r), Square(s) }
4093let s = Shape::Empty
4094print(s)"#),
4095 "Shape::Empty"
4096 );
4097 }
4098
4099 #[test]
4100 fn enum_tuple_variant() {
4101 assert_eq!(
4102 say(r#"enum Shape { Empty, Circle(r), Pair(x, y) }
4103let p = Shape::Pair(3, 4)
4104print(p)"#),
4105 "Shape::Pair(3, 4)"
4106 );
4107 }
4108
4109 #[test]
4110 fn enum_struct_variant() {
4111 assert_eq!(
4112 say(r#"enum Shape { Rectangle { width, height }, Empty }
4113let r = Shape::Rectangle { width: 4, height: 3 }
4114print(r)
4115print(r.width)
4116print(r.height)"#),
4117 "3"
4118 );
4119 }
4120
4121 #[test]
4122 fn enum_equality_same_variant() {
4123 assert_eq!(
4124 say(r#"enum E { A, B(x) }
4125print(E::A == E::A)
4126print(E::B(1) == E::B(1))
4127print(E::B(1) == E::B(2))
4128print(E::A == E::B(1))"#),
4129 "false"
4130 );
4131 }
4132
4133 #[test]
4134 fn enum_different_types_not_equal() {
4135 assert_eq!(
4136 say(r#"enum A { X }
4137enum B { X }
4138print(A::X == B::X)"#),
4139 "false"
4140 );
4141 }
4142
4143 #[test]
4144 fn enum_variant_mismatch_unit_given_args() {
4145 let err = run_err(
4146 r#"enum E { A }
4147let x = E::A(1)"#,
4148 );
4149 assert!(err.contains("no payload"), "got: {err}");
4150 }
4151
4152 #[test]
4153 fn enum_variant_mismatch_tuple_arity() {
4154 let err = run_err(
4155 r#"enum E { P(x, y) }
4156let p = E::P(1)"#,
4157 );
4158 assert!(err.contains("expects 2 argument"), "got: {err}");
4159 }
4160
4161 #[test]
4162 fn enum_variant_mismatch_struct_missing_field() {
4163 let err = run_err(
4164 r#"enum E { R { w, h } }
4165let r = E::R { w: 1 }"#,
4166 );
4167 assert!(err.contains("Missing field"), "got: {err}");
4168 }
4169
4170 #[test]
4171 fn enum_variant_mismatch_struct_extra_field() {
4172 let err = run_err(
4173 r#"enum E { R { w, h } }
4174let r = E::R { w: 1, h: 2, extra: 3 }"#,
4175 );
4176 assert!(err.contains("no field"), "got: {err}");
4177 }
4178
4179 #[test]
4180 fn enum_undeclared_variant_errors() {
4181 let err = run_err(
4182 r#"enum E { A }
4183let x = E::Z"#,
4184 );
4185 assert!(err.contains("no variant"), "got: {err}");
4186 }
4187
4188 #[test]
4189 fn enum_undeclared_type_errors() {
4190 let err = run_err("let x = Nope::V");
4191 assert!(err.contains("not declared"), "got: {err}");
4192 }
4193
4194 #[test]
4195 fn enum_struct_variant_field_access() {
4196 assert_eq!(
4197 say(r#"enum Shape { Rect { w, h }, Empty }
4198let r = Shape::Rect { w: 10, h: 3 }
4199print(r.w * r.h)"#),
4200 "30"
4201 );
4202 }
4203
4204 #[test]
4205 fn enum_used_in_if_condition() {
4206 assert_eq!(
4211 say(r#"enum E { V }
4212if E::V == E::V {
4213 print("yes")
4214} else {
4215 print("no")
4216}"#),
4217 "yes"
4218 );
4219 }
4220
4221 #[test]
4222 fn enum_type_name_is_enum() {
4223 assert_eq!(
4224 say(r#"enum E { V }
4225print((E::V).type())"#),
4226 "enum"
4227 );
4228 }
4229
4230 #[test]
4231 fn enum_in_array_of_values() {
4232 assert_eq!(
4233 say(r#"enum Color { Red, Green, Blue }
4234let palette = [Color::Red, Color::Green, Color::Blue]
4235print(palette)"#),
4236 "[Color::Red, Color::Green, Color::Blue]"
4237 );
4238 }
4239
4240 #[test]
4241 fn enum_duplicate_decl_errors() {
4242 let err = run_err(
4243 r#"enum E { A }
4244enum E { B }"#,
4245 );
4246 assert!(err.contains("already declared"), "got: {err}");
4247 }
4248
4249 #[test]
4252 fn method_on_struct_basic() {
4253 assert_eq!(
4254 say(r#"struct Point { x, y }
4255fn Point.sum(self) { return self.x + self.y }
4256let p = Point { x: 3, y: 4 }
4257print(p.sum())"#),
4258 "7"
4259 );
4260 }
4261
4262 #[test]
4263 fn method_with_extra_args() {
4264 assert_eq!(
4265 say(r#"struct Counter { n }
4266fn Counter.add(self, delta) { return Counter { n: self.n + delta } }
4267let c = Counter { n: 10 }
4268let c2 = c.add(5)
4269print(c2.n)
4270print(c.n)"#),
4271 "10"
4272 );
4273 }
4274
4275 #[test]
4276 fn value_method_receiver_cannot_be_mutated() {
4277 let error = parse_err(
4278 r#"struct Counter { n }
4279fn Counter.bump(self) { self.n = self.n + 1 }"#,
4280 );
4281 assert!(error.contains("can't mutate value receiver `self`"));
4282 }
4283
4284 #[test]
4285 fn method_on_enum_dispatches_on_type() {
4286 assert_eq!(
4287 say(r#"enum Shape { Circle(r), Rect { w, h }, Empty }
4288fn Shape.name(self) { return "shape" }
4289print(Shape::Circle(3).name())
4290print(Shape::Rect { w: 4, h: 3 }.name())
4291print(Shape::Empty.name())"#),
4292 "shape"
4293 );
4294 }
4295
4296 #[test]
4297 fn method_overrides_builtin() {
4298 assert_eq!(
4301 say(r#"struct Wrapper { data }
4302fn Wrapper.len(self) { return 99 }
4303let w = Wrapper { data: [1, 2, 3] }
4304print(w.len())"#),
4305 "99"
4306 );
4307 }
4308
4309 #[test]
4310 fn method_unknown_on_struct_errors() {
4311 let err = run_err(
4312 r#"struct P { x }
4313let p = P { x: 1 }
4314p.nope()"#,
4315 );
4316 assert!(err.contains(".nope()"), "got: {err}");
4317 }
4318
4319 #[test]
4320 fn method_wrong_arg_count_errors() {
4321 let err = run_err(
4322 r#"struct P { x }
4323fn P.set(self, v) { return P { x: v } }
4324let p = P { x: 1 }
4325p.set(1, 2)"#,
4326 );
4327 assert!(err.contains("expects"), "got: {err}");
4328 }
4329
4330 #[test]
4331 fn method_chain_user_defined() {
4332 assert_eq!(
4333 say(r#"struct Adder { n }
4334fn Adder.then(self, m) { return Adder { n: self.n + m } }
4335let result = Adder { n: 1 }.then(2).then(3).then(4)
4336print(result.n)"#),
4337 "10"
4338 );
4339 }
4340
4341 #[test]
4342 fn method_self_is_clone() {
4343 assert_eq!(
4347 say(r#"struct P { x }
4348fn P.identity(self) { return self }
4349let a = P { x: 7 }
4350let b = a.identity()
4351print(a == b)
4352print(b.x)"#),
4353 "7"
4354 );
4355 }
4356
4357 #[test]
4358 fn method_on_enum_reads_payload_field() {
4359 assert_eq!(
4360 say(r#"enum Shape { Circle(r), Rect { w, h } }
4361fn Shape.label(self, prefix) {
4362 return prefix + "-shape"
4363}
4364let c = Shape::Circle(5)
4365print(c.label("small"))"#),
4366 "small-shape"
4367 );
4368 }
4369
4370 #[test]
4371 fn enum_duplicate_variant_errors() {
4372 let err = run_err(r#"enum E { A, A }"#);
4373 assert!(err.contains("duplicate variant"), "got: {err}");
4374 }
4375
4376 #[test]
4377 fn struct_empty() {
4378 assert_eq!(
4379 say(r#"struct Unit { }
4380let u = Unit { }
4381print(u)"#),
4382 "Unit {}"
4383 );
4384 }
4385
4386 #[test]
4387 fn import_module_does_not_see_importer_scope() {
4388 let mut host = ModuleHost::new(&[("m", "fn leak() { return outer }")]);
4391 let err = run(
4392 r#"let outer = 42
4393use m
4394print(leak())"#,
4395 &mut host,
4396 &NyblLimits::standard(),
4397 )
4398 .unwrap_err();
4399 assert!(
4400 err.message.contains("outer"),
4401 "expected 'outer' not-found error, got: {}",
4402 err.message
4403 );
4404 }
4405
4406 #[test]
4414 fn const_declares_an_immutable_binding() {
4415 assert_eq!(say("const PI = 3\nprint(PI)"), "3");
4416 }
4417
4418 #[test]
4419 fn const_can_reference_another_const() {
4420 assert_eq!(
4421 say("const PI = 3\nconst DIAMETER = PI * 2\nprint(DIAMETER)"),
4422 "6"
4423 );
4424 }
4425
4426 #[test]
4427 fn const_reassignment_is_refused_at_parse_time() {
4428 let err = run_err("const PI = 3\nPI = 4");
4429 assert!(
4430 err.contains("can't reassign") && err.contains("constant"),
4431 "expected const-reassignment error, got: {err}"
4432 );
4433 }
4434
4435 #[test]
4436 fn const_container_assignment_is_refused_at_parse_time() {
4437 let cases = [
4438 ("const VALUES = [1, 2]\nVALUES[0] = 9", "VALUES", 2),
4439 ("const VALUES = [1, 2]\nVALUES[0] += 9", "VALUES", 2),
4440 ("const LOOKUP = {\"n\": 1}\nLOOKUP[\"n\"] = 9", "LOOKUP", 2),
4441 ("const LOOKUP = {\"n\": 1}\nLOOKUP[\"n\"] += 9", "LOOKUP", 2),
4442 (
4443 "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\nCOUNTER.n = 9",
4444 "COUNTER",
4445 3,
4446 ),
4447 (
4448 "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\nCOUNTER.n += 9",
4449 "COUNTER",
4450 3,
4451 ),
4452 ];
4453
4454 for (source, name, line) in cases {
4455 let err = parse(source).unwrap_err();
4456 assert_eq!(
4457 err.message,
4458 format!("can't reassign `{name}` — it's a constant"),
4459 "source: {source}"
4460 );
4461 assert_eq!(err.line, Some(line), "source: {source}");
4462 assert_eq!(
4463 err.friendly_hint.as_deref(),
4464 Some("constants are immutable. Use `let` if you want a mutable binding."),
4465 "source: {source}"
4466 );
4467 }
4468 }
4469
4470 #[test]
4471 fn const_assignment_finds_grouped_and_nested_place_roots() {
4472 let cases = [
4473 "const VALUES = [1, 2]\n(VALUES)[0] = 9",
4474 "const VALUES = [1, 2]\n((VALUES))[0] += 9",
4475 "const GRID = [[1]]\nGRID[0][0] = 9",
4476 "struct Counter { n }\nconst COUNTER = Counter { n: 1 }\n(COUNTER).n = 9",
4477 ];
4478
4479 for source in cases {
4480 let err = parse(source).unwrap_err();
4481 assert!(
4482 err.message.contains("can't reassign") && err.message.contains("constant"),
4483 "source: {source}\nerror: {err}"
4484 );
4485 }
4486 }
4487
4488 #[test]
4489 fn const_array_mutating_methods_use_the_canonical_constant_error() {
4490 let cases = [
4491 "VALUES.push(4)",
4492 "VALUES.pop()",
4493 "VALUES.insert(0, 4)",
4494 "VALUES.remove(0)",
4495 "VALUES.reverse()",
4496 "(VALUES).sort()",
4497 ];
4498
4499 for call in cases {
4500 let source = format!("const VALUES = [3, 1, 2]\n{call}");
4501 let err = run_err_full(&source);
4502 assert_eq!(
4503 err.message, "can't reassign `VALUES` — it's a constant",
4504 "source: {source}"
4505 );
4506 assert_eq!(err.line, Some(2), "source: {source}");
4507 assert_eq!(
4508 err.friendly_hint.as_deref(),
4509 Some(error_messages::CONSTANT_MUTATION_HINT),
4510 "source: {source}"
4511 );
4512 }
4513
4514 let err = run_err_full(
4515 r#"fn mutate() {
4516 const VALUES = [3, 1, 2]
4517 VALUES.sort()
4518}
4519mutate()"#,
4520 );
4521 assert_eq!(err.message, "can't reassign `VALUES` — it's a constant");
4522 assert_eq!(err.line, Some(3));
4523 }
4524
4525 #[test]
4526 fn const_non_array_receivers_keep_ordinary_method_dispatch() {
4527 assert_eq!(
4528 say(r#"struct Accumulator { total }
4529fn Accumulator.push(self, value) { return self.total + value }
4530fn Accumulator.pop(self) { return self.total }
4531const ACCUMULATOR = Accumulator { total: 7 }
4532const LOOKUP = {"n": 1}
4533print([ACCUMULATOR.push(5), ACCUMULATOR.pop(), LOOKUP.keys()])"#),
4534 r#"[12, 7, ["n"]]"#
4535 );
4536
4537 assert_eq!(
4538 run_err(
4539 r#"const LOOKUP = {"n": 1}
4540LOOKUP.remove("n")"#
4541 ),
4542 "Dict doesn't have a .remove() method"
4543 );
4544 }
4545
4546 #[test]
4547 fn lowercase_array_mutating_methods_remain_valid() {
4548 assert_eq!(
4549 say(r#"let values = [3, 1, 2]
4550values.sort()
4551values.reverse()
4552values.insert(1, 4)
4553values.remove(0)
4554values.push(5)
4555values.pop()
4556print(values)"#),
4557 "[4, 2, 1]"
4558 );
4559 }
4560
4561 #[test]
4562 fn const_declarations_remain_declarations_not_assignments() {
4563 assert_eq!(
4566 say("const VALUE = [1]\nconst VALUE = [2]\nprint(VALUE[0])"),
4567 "2"
4568 );
4569 }
4570
4571 #[test]
4572 fn const_names_remain_readable_inside_mutable_assignment_targets() {
4573 assert_eq!(
4574 say("const INDEX = 0\nlet values = [1]\nvalues[INDEX] += 2\nprint(values)"),
4575 "[3]"
4576 );
4577 }
4578
4579 #[test]
4580 fn let_name_must_start_lowercase() {
4581 let err = run_err("let Foo = 1");
4582 assert!(err.to_lowercase().contains("value"), "got: {err}");
4583 }
4584
4585 #[test]
4586 fn let_with_all_caps_suggests_const() {
4587 let err = run_err("let MAX = 1");
4588 assert!(
4589 err.contains("const"),
4590 "expected hint to suggest `const`, got: {err}"
4591 );
4592 }
4593
4594 #[test]
4595 fn struct_name_must_start_uppercase() {
4596 let err = run_err("struct entity { id }");
4597 assert!(err.to_lowercase().contains("type"), "got: {err}");
4598 }
4599
4600 #[test]
4601 fn enum_variants_start_uppercase() {
4602 let err = run_err("enum Event { spawn, damage }");
4603 assert!(err.to_lowercase().contains("type"), "got: {err}");
4604 }
4605
4606 #[test]
4607 fn enum_with_all_caps_variants_is_allowed() {
4608 assert_eq!(
4611 say("enum Dir { N, E, S, W }\nlet d = Dir::E\nprint(\"ok\")"),
4612 "ok"
4613 );
4614 }
4615
4616 #[test]
4617 fn fn_name_must_start_lowercase() {
4618 let err = run_err("fn Greet() { return 1 }");
4619 assert!(err.to_lowercase().contains("value"), "got: {err}");
4620 }
4621
4622 #[test]
4623 fn fn_params_must_start_lowercase() {
4624 let err = run_err("fn greet(Name) { return Name }");
4625 assert!(err.to_lowercase().contains("value"), "got: {err}");
4626 }
4627
4628 #[test]
4629 fn all_function_forms_use_canonical_parameter_name_diagnostics() {
4630 for (source, site, name, line, column) in [
4631 ("fn run(BAD) { none }", "function parameter", "BAD", 1, 8),
4632 (
4633 "fn Thing.run(BAD) { none }",
4634 "method parameter",
4635 "BAD",
4636 1,
4637 14,
4638 ),
4639 (
4640 "let f = fn(BAD) { none }",
4641 "function parameter",
4642 "BAD",
4643 1,
4644 12,
4645 ),
4646 (
4647 "let f = fn(\n good,\n AlsoBad\n) { return good }",
4648 "function parameter",
4649 "AlsoBad",
4650 3,
4651 3,
4652 ),
4653 ] {
4654 let error = parse_err_full(source);
4655 assert_eq!(error.line, Some(line), "source: {source}");
4656 assert_eq!(error.column, Some(column), "source: {source}");
4657 assert_eq!(
4658 error.message,
4659 format!(
4660 "{site} `{name}` looks like a {}, but a value name is required here",
4661 if name == "BAD" { "constant" } else { "type" }
4662 ),
4663 "source: {source}"
4664 );
4665 assert!(error.friendly_hint.is_some(), "source: {source}");
4666 }
4667
4668 let reserved = parse_err_full("let f = fn(if) { none }");
4669 assert_eq!(reserved.line, Some(1));
4670 assert_eq!(reserved.column, Some(12));
4671 assert_eq!(reserved.message, "`if` is a reserved word in Nybl");
4672 assert!(reserved.friendly_hint.is_some());
4673 }
4674
4675 #[test]
4676 fn valid_lambda_params_keep_function_binding_semantics() {
4677 let source = r#"fn make(value) { return fn(value) { return value } }
4678let outer = 40
4679let pick = fn(_ignored, value, value) { return outer + value }
4680print(pick(1, 2, 3))
4681print(make(4)(5))"#;
4682 let mut host = TestHost::new();
4683 run(source, &mut host, &test_limits()).unwrap();
4684 assert_eq!(host.prints.borrow().as_slice(), ["43", "5"]);
4685 }
4686
4687 #[test]
4688 fn for_loop_var_must_start_lowercase() {
4689 let err = run_err("for I in range(3) { print(I) }");
4690 assert!(err.to_lowercase().contains("value"), "got: {err}");
4691 }
4692
4693 #[test]
4694 fn const_name_must_be_all_caps() {
4695 let err = run_err("const Pi = 3");
4696 assert!(err.to_lowercase().contains("constant"), "got: {err}");
4697 }
4698
4699 #[test]
4700 fn underscore_prefix_is_allowed_for_all_buckets() {
4701 assert_eq!(
4703 say(r#"
4704 let _hidden = 1
4705 const _DEBUG = true
4706 struct _Internal { _counter }
4707 let s = _Internal { _counter: _hidden }
4708 print(s._counter)
4709 "#),
4710 "1"
4711 );
4712 }
4713
4714 #[test]
4719 fn two_modules_can_declare_same_type_name_with_different_shapes() {
4720 let mut host = crate::host::StringModuleHost::new([
4726 ("paint", "enum Color { Red, Blue }"),
4727 ("other", "enum Color { Red, Green, Yellow }"),
4728 ]);
4729 run(
4730 r#"use paint as p
4731use other as o
4732let a = p.Color::Red
4733let b = o.Color::Red
4734print(a == b)
4735print(a == a)
4736print(a)
4737print(b)"#,
4738 &mut host,
4739 &NyblLimits::standard(),
4740 )
4741 .unwrap();
4742 assert_eq!(host.output(), "false\ntrue\nColor::Red\nColor::Red");
4748 }
4749
4750 #[test]
4751 fn namespaced_pattern_matches_only_same_module_value() {
4752 let mut host = crate::host::StringModuleHost::new([
4757 ("paint", "enum Color { Red, Blue }"),
4758 ("other", "enum Color { Red, Green, Yellow }"),
4759 ]);
4760 run(
4761 r#"use paint as p
4762use other as o
4763fn label(c) {
4764 return match c {
4765 p.Color::Red => "paint red",
4766 o.Color::Red => "other red",
4767 _ => "other",
4768 }
4769}
4770print(label(p.Color::Red))
4771print(label(o.Color::Red))
4772print(label(o.Color::Green))"#,
4773 &mut host,
4774 &NyblLimits::standard(),
4775 )
4776 .unwrap();
4777 assert_eq!(host.output(), "paint red\nother red\nother");
4778 }
4779
4780 #[test]
4781 fn string_module_host_runs_use_end_to_end() {
4782 let mut host = crate::host::StringModuleHost::new([(
4787 "greetings",
4788 "fn hello(name) { print(\"hi \" + name) }",
4789 )]);
4790 run(
4791 "use greetings\nhello(\"nybl\")",
4792 &mut host,
4793 &NyblLimits::standard(),
4794 )
4795 .unwrap();
4796 assert_eq!(host.output(), "hi nybl");
4797 }
4798
4799 #[test]
4800 fn explicit_public_surfaces_filter_values_functions_and_types() {
4801 let module = r#"
4802let visible = 1
4803let hidden = 2
4804let _shown = 3
4805struct Visible { value }
4806struct Hidden { value }
4807fn read_hidden() { return hidden }
4808pub { visible, _shown, read_hidden, Visible }
4809"#;
4810 let mut host = crate::host::StringModuleHost::new([("surface", module)]);
4811 run(
4812 r#"
4813use surface as module
4814use surface
4815print([module.visible, visible, _shown, module.read_hidden(), Visible { value: 4 }])
4816"#,
4817 &mut host,
4818 &NyblLimits::standard(),
4819 )
4820 .unwrap();
4821 assert_eq!(host.output(), "[1, 1, 3, 2, Visible { value: 4 }]");
4822
4823 let mut hidden_host = crate::host::StringModuleHost::new([("surface", module)]);
4824 let hidden = run(
4825 "use surface as module\nprint(module.hidden)",
4826 &mut hidden_host,
4827 &NyblLimits::standard(),
4828 )
4829 .unwrap_err();
4830 assert!(hidden.message.contains("isn't exported"), "got: {hidden:?}");
4831
4832 let mut type_host = crate::host::StringModuleHost::new([("surface", module)]);
4833 let hidden_type = run(
4834 "use surface.{Hidden}",
4835 &mut type_host,
4836 &NyblLimits::standard(),
4837 )
4838 .unwrap_err();
4839 assert!(
4840 hidden_type.message.contains("isn't exported"),
4841 "got: {hidden_type:?}"
4842 );
4843 }
4844
4845 #[test]
4846 fn modules_without_public_surfaces_keep_legacy_private_access() {
4847 let mut host = crate::host::StringModuleHost::new([("legacy", "let _private = 9")]);
4848 run(
4849 "use legacy.{_private}\nprint(_private)",
4850 &mut host,
4851 &NyblLimits::standard(),
4852 )
4853 .unwrap();
4854 assert_eq!(host.output(), "9");
4855 }
4856
4857 #[test]
4860 fn runtime_error_carries_column_for_undefined_ident() {
4861 let err = run_err_full("let x = 1\nprint(undefined)");
4867 assert_eq!(err.line, Some(2), "line");
4868 assert!(
4869 err.column.is_some(),
4870 "expected runtime error to carry column info, got None"
4871 );
4872 }
4873
4874 #[test]
4875 fn runtime_error_column_renders_with_caret() {
4876 let src = "let x = 1\nprint(undefined)";
4880 let err = run_err_full(src);
4881 let rendered = err.render(src);
4882 assert!(
4883 rendered.contains("--> line 2:"),
4884 "rendered should include line+col header, got:\n{rendered}"
4885 );
4886 assert!(
4887 rendered.contains("^"),
4888 "rendered should draw a caret, got:\n{rendered}"
4889 );
4890 }
4891
4892 #[test]
4893 fn resolve_from_map_returns_none_for_unknown_modules() {
4894 let resolver = crate::host::resolve_from_map([("m", "let x = 1")]);
4899 assert!(resolver("m").is_some());
4900 assert!(resolver("other").is_none());
4901 }
4902
4903 fn repl_eval(
4906 session: &mut ReplSession,
4907 src: &str,
4908 host: &mut TestHost,
4909 ) -> Result<Option<Value>, NyblError> {
4910 session.eval(src, host, &test_limits())
4911 }
4912
4913 #[test]
4914 fn session_let_binding_survives_between_evals() {
4915 let mut session = ReplSession::new();
4916 let mut host = TestHost::new();
4917 repl_eval(&mut session, "let x = 5", &mut host).unwrap();
4918 repl_eval(&mut session, "print(x)", &mut host).unwrap();
4919 assert_eq!(host.last_print(), "5");
4920 }
4921
4922 #[test]
4923 fn session_mutated_let_reflects_in_next_eval() {
4924 let mut session = ReplSession::new();
4925 let mut host = TestHost::new();
4926 repl_eval(&mut session, "let counter = 0", &mut host).unwrap();
4927 repl_eval(&mut session, "counter = counter + 1", &mut host).unwrap();
4928 repl_eval(&mut session, "counter = counter + 1", &mut host).unwrap();
4929 repl_eval(&mut session, "print(counter)", &mut host).unwrap();
4930 assert_eq!(host.last_print(), "2");
4931 }
4932
4933 #[test]
4934 fn session_fn_declared_on_one_eval_callable_next() {
4935 let mut session = ReplSession::new();
4936 let mut host = TestHost::new();
4937 repl_eval(&mut session, "fn double(x) { return x + x }", &mut host).unwrap();
4938 repl_eval(&mut session, "print(double(21))", &mut host).unwrap();
4939 assert_eq!(host.last_print(), "42");
4940 }
4941
4942 #[test]
4943 fn session_struct_and_method_survive() {
4944 let mut session = ReplSession::new();
4949 let mut host = TestHost::new();
4950 repl_eval(
4951 &mut session,
4952 "struct Point { x, y }\nfn Point.sum(self) { return self.x + self.y }",
4953 &mut host,
4954 )
4955 .unwrap();
4956 repl_eval(
4957 &mut session,
4958 "let p = Point { x: 3, y: 4 }\nprint(p.sum())",
4959 &mut host,
4960 )
4961 .unwrap();
4962 assert_eq!(host.last_print(), "7");
4963 }
4964
4965 #[test]
4966 fn session_bare_expression_returns_value() {
4967 let mut session = ReplSession::new();
4971 let mut host = TestHost::new();
4972 assert!(
4973 repl_eval(&mut session, "let x = 5", &mut host)
4974 .unwrap()
4975 .is_none()
4976 );
4977 let v = repl_eval(&mut session, "x + 1", &mut host).unwrap();
4978 match v {
4979 Some(Value::Int(n)) => assert_eq!(n, 6),
4980 other => panic!("expected Int(6), got: {other:?}"),
4981 }
4982 }
4983
4984 #[test]
4985 fn session_errors_preserve_earlier_effects() {
4986 let mut session = ReplSession::new();
4990 let mut host = TestHost::new();
4991 let err = repl_eval(
4992 &mut session,
4993 "let kept = 1\nlet bad = undefined\nlet skipped = 3",
4994 &mut host,
4995 );
4996 assert!(err.is_err(), "expected runtime error");
4997 assert!(session.get("kept").is_some());
4999 assert!(session.get("skipped").is_none());
5000 }
5001
5002 #[test]
5003 fn session_normalises_scope_depth_after_block_error() {
5004 let mut session = ReplSession::new();
5009 let mut host = TestHost::new();
5010 let _ = repl_eval(
5011 &mut session,
5012 "if true {\n let y = undefined\n}",
5013 &mut host,
5014 );
5015 repl_eval(&mut session, "let after = 7", &mut host).unwrap();
5018 let v = repl_eval(&mut session, "after", &mut host).unwrap();
5019 match v {
5020 Some(Value::Int(n)) => assert_eq!(n, 7),
5021 other => panic!("expected Int(7), got: {other:?}"),
5022 }
5023 }
5024
5025 #[test]
5026 fn session_binding_names_surfaces_lets_and_fns() {
5027 let mut session = ReplSession::new();
5031 let mut host = TestHost::new();
5032 repl_eval(&mut session, "let alpha = 1", &mut host).unwrap();
5033 repl_eval(&mut session, "fn beta() { return 2 }", &mut host).unwrap();
5034 let names = session.binding_names();
5035 assert!(names.contains(&"alpha".to_string()));
5036 assert!(names.contains(&"beta".to_string()));
5037 }
5038
5039 #[test]
5040 fn session_use_carries_imports_across_evals() {
5041 struct ModHost {
5046 prints: std::cell::RefCell<Vec<String>>,
5047 }
5048 impl NyblHost for ModHost {
5049 fn call(&mut self, _: &str, _: &[Value], _: u32) -> Option<Result<Value, NyblError>> {
5050 None
5051 }
5052 fn on_print(&mut self, message: &str) {
5053 self.prints.borrow_mut().push(message.to_string());
5054 }
5055 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
5056 match name {
5057 "m" => Some(Ok("fn greet() { return \"hi\" }".to_string())),
5058 _ => None,
5059 }
5060 }
5061 }
5062 let mut host = ModHost {
5063 prints: std::cell::RefCell::new(Vec::new()),
5064 };
5065 let mut session = ReplSession::new();
5066 session.eval("use m", &mut host, &test_limits()).unwrap();
5067 session
5068 .eval("print(greet())", &mut host, &test_limits())
5069 .unwrap();
5070 let prints = host.prints.borrow();
5071 assert_eq!(prints.last().map(|s| s.as_str()), Some("hi"));
5072 }
5073}