1use tatara_lisp_eval::ffi::Arity;
36use tatara_lisp_eval::{EvalError, Interpreter, Value};
37
38fn as_str(v: &Value, span: tatara_lisp::Span) -> Result<String, EvalError> {
39 match v {
40 Value::Str(s) => Ok(s.to_string()),
41 Value::Symbol(s) | Value::Keyword(s) => Ok(s.to_string()),
44 other => Err(EvalError::type_mismatch(
45 "a string",
46 other.type_name(),
47 span,
48 )),
49 }
50}
51
52pub fn blue_equal(a: &Value, b: &Value) -> bool {
65 match (a, b) {
66 (Value::Nil, Value::Nil) => true,
67 (Value::Bool(x), Value::Bool(y)) => x == y,
68 (Value::Int(x), Value::Int(y)) => x == y,
69 (Value::Float(x), Value::Float(y)) => x == y,
70 (Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => (*x as f64) == *y,
71 (Value::Str(x), Value::Str(y))
72 | (Value::Symbol(x), Value::Symbol(y))
73 | (Value::Keyword(x), Value::Keyword(y)) => x == y,
74 (Value::List(x), Value::List(y)) => {
75 x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| blue_equal(p, q))
76 }
77 (Value::Map(x), Value::Map(y)) => {
78 x.len() == y.len()
79 && x.iter()
80 .all(|(k, v)| y.get(k).is_some_and(|w| blue_equal(v, w)))
81 }
82 (Value::Closure(x), Value::Closure(y)) => std::sync::Arc::ptr_eq(x, y),
83 (Value::NativeFn(x), Value::NativeFn(y)) => x.name == y.name,
84 (Value::Sexp(x, _), Value::Sexp(y, _)) => x == y,
85 _ => false,
86 }
87}
88
89fn render(v: &Value) -> String {
94 match v {
95 Value::Nil => String::new(),
96 Value::Str(s) | Value::Symbol(s) | Value::Keyword(s) => s.to_string(),
97 other => literal(other),
98 }
99}
100
101fn literal(v: &Value) -> String {
105 match v {
106 Value::Nil => "nil".into(),
107 Value::Bool(b) => b.to_string(),
108 Value::Int(n) => n.to_string(),
109 Value::Float(x) => float_text(*x),
110 Value::Str(s) => quoted(s),
111 Value::Symbol(s) => s.to_string(),
112 Value::Keyword(s) => format!(":{s}"),
113 Value::List(items) => {
114 let parts: Vec<String> = items.iter().map(literal).collect();
115 format!("[{}]", parts.join(", "))
116 }
117 Value::Map(m) => {
118 let mut entries: Vec<String> = m
119 .iter()
120 .map(|(k, v)| format!("{} {}", key_text(k), literal(v)))
121 .collect();
122 entries.sort();
123 format!("{{{}}}", entries.join(", "))
124 }
125 other => other.type_name().to_string(),
126 }
127}
128
129fn key_text(k: &tatara_lisp_eval::value::MapKey) -> String {
132 use tatara_lisp_eval::value::MapKey;
133 match k {
134 MapKey::Keyword(s) | MapKey::Symbol(s) => format!("{s}:"),
135 MapKey::Str(s) => format!("{} =>", quoted(s)),
136 MapKey::Int(n) => format!("{n} =>"),
137 MapKey::Float(bits) => format!("{} =>", float_text(f64::from_bits(*bits))),
138 MapKey::Bool(b) => format!("{b} =>"),
139 MapKey::Nil => "nil =>".into(),
140 }
141}
142
143fn float_text(x: f64) -> String {
145 if x.is_finite() && x.fract() == 0.0 && x.abs() < 1e16 {
146 format!("{x:.1}")
147 } else {
148 format!("{x}")
149 }
150}
151
152fn quoted(s: &str) -> String {
153 let mut out = String::with_capacity(s.len() + 2);
154 out.push('"');
155 for c in s.chars() {
156 match c {
157 '"' => out.push_str("\\\""),
158 '\\' => out.push_str("\\\\"),
159 '\n' => out.push_str("\\n"),
160 '\t' => out.push_str("\\t"),
161 c => out.push(c),
162 }
163 }
164 out.push('"');
165 out
166}
167
168fn list(items: Vec<Value>) -> Value {
169 Value::list(items)
170}
171
172pub fn install_blue_stdlib<H: 'static>(interp: &mut Interpreter<H>) {
174 interp.register_fn(
179 "length",
180 Arity::Exact(1),
181 |a: &[Value], _h: &mut H, span| match &a[0] {
182 Value::List(items) => Ok(Value::Int(items.len() as i64)),
183 other => Ok(Value::Int(as_str(other, span)?.chars().count() as i64)),
184 },
185 );
186
187 interp.register_fn(
190 "builtin_names",
191 Arity::Exact(0),
192 |_a: &[Value], _h: &mut H, _s| {
193 Ok(Value::list(
194 crate::docs::NAMES
195 .iter()
196 .map(|n| Value::Str(std::sync::Arc::from(n.name))),
197 ))
198 },
199 );
200 interp.register_fn("to_s", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
201 Ok(Value::Str(render(&a[0]).into()))
202 });
203
204 interp.register_fn("upcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
205 Ok(Value::Str(as_str(&a[0], s)?.to_uppercase().into()))
206 });
207
208 interp.register_fn("downcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
209 Ok(Value::Str(as_str(&a[0], s)?.to_lowercase().into()))
210 });
211
212 interp.register_fn("trim", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
213 Ok(Value::Str(as_str(&a[0], s)?.trim().into()))
214 });
215
216 interp.register_fn(
223 "concat",
224 Arity::AtLeast(1),
225 |a: &[Value], _h: &mut H, _s| {
226 Ok(Value::Str(a.iter().map(render).collect::<String>().into()))
227 },
228 );
229
230 interp.register_fn("equal?", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
235 Ok(Value::Bool(blue_equal(&a[0], &a[1])))
236 });
237 interp.register_fn("not=", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
238 Ok(Value::Bool(!blue_equal(&a[0], &a[1])))
239 });
240
241 interp.register_fn("nil?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
247 Ok(Value::Bool(matches!(a[0], Value::Nil)))
248 });
249 interp.register_fn("list?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
250 Ok(Value::Bool(matches!(a[0], Value::List(_))))
251 });
252 interp.register_fn("map?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
253 Ok(Value::Bool(matches!(a[0], Value::Map(_))))
254 });
255 interp.register_fn("float?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
256 Ok(Value::Bool(matches!(a[0], Value::Float(_))))
257 });
258 interp.register_fn("bool?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
259 Ok(Value::Bool(matches!(a[0], Value::Bool(_))))
260 });
261
262 interp.register_fn("cdr", Arity::Exact(1), |a: &[Value], _h: &mut H, span| {
267 match &a[0] {
268 Value::List(xs) if !xs.is_empty() => Ok(Value::List(std::sync::Arc::new(xs.skip(1)))),
270 Value::Nil | Value::List(_) => Err(EvalError::native_fn(
271 std::sync::Arc::<str>::from("cdr"),
272 "cdr of empty list",
273 span,
274 )),
275 other => Err(EvalError::type_mismatch("pair", other.type_name(), span)),
276 }
277 });
278 interp.register_owned_fn("append", Arity::Any, |a: Vec<Value>, _h: &mut H, span| {
279 let mut lists = Vec::with_capacity(a.len());
286 for v in a {
287 match v {
288 Value::Nil => {}
289 Value::List(xs) => lists.push(xs),
290 other => return Err(EvalError::type_mismatch("list", other.type_name(), span)),
291 }
292 }
293 let mut lists = lists.into_iter();
294 let Some(mut out) = lists.next() else {
295 return Ok(Value::List(std::sync::Arc::new(
296 tatara_lisp_eval::List::new(),
297 )));
298 };
299 let acc = std::sync::Arc::make_mut(&mut out);
300 for xs in lists {
301 acc.append(
302 std::sync::Arc::try_unwrap(xs)
303 .unwrap_or_else(|shared| tatara_lisp_eval::List::clone(&shared)),
304 );
305 }
306 Ok(Value::List(out))
307 });
308
309 interp.register_fn("split", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
310 let text = as_str(&a[0], s)?;
311 let sep = as_str(&a[1], s)?;
312 let parts: Vec<Value> = if sep.is_empty() {
321 text.chars()
322 .map(|c| Value::Str(c.to_string().into()))
323 .collect()
324 } else {
325 text.split(sep.as_str())
326 .map(|p| Value::Str(p.into()))
327 .collect()
328 };
329 Ok(list(parts))
330 });
331
332 interp.register_fn("join", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
333 let sep = as_str(&a[1], s)?;
334 match &a[0] {
335 Value::List(items) => Ok(Value::Str(
336 items
337 .iter()
338 .map(render)
339 .collect::<Vec<_>>()
340 .join(&sep)
341 .into(),
342 )),
343 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
344 }
345 });
346
347 interp.register_fn(
348 "contains?",
349 Arity::Exact(2),
350 |a: &[Value], _h: &mut H, s| {
351 Ok(Value::Bool(as_str(&a[0], s)?.contains(&as_str(&a[1], s)?)))
352 },
353 );
354
355 interp.register_fn(
356 "starts_with?",
357 Arity::Exact(2),
358 |a: &[Value], _h: &mut H, s| {
359 Ok(Value::Bool(
360 as_str(&a[0], s)?.starts_with(&as_str(&a[1], s)?),
361 ))
362 },
363 );
364
365 interp.register_fn(
366 "ends_with?",
367 Arity::Exact(2),
368 |a: &[Value], _h: &mut H, s| {
369 Ok(Value::Bool(as_str(&a[0], s)?.ends_with(&as_str(&a[1], s)?)))
370 },
371 );
372
373 interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
374 Ok(Value::Str(
375 as_str(&a[0], s)?
376 .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
377 .into(),
378 ))
379 });
380
381 interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
382 match &a[0] {
383 Value::List(items) => Ok(Value::list(items.iter().rev().cloned())),
384 other => Ok(Value::Str(
387 as_str(other, s)?.chars().rev().collect::<String>().into(),
388 )),
389 }
390 });
391
392 interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
393 Ok(list(
394 as_str(&a[0], s)?
395 .chars()
396 .map(|c| Value::Str(c.to_string().into()))
397 .collect(),
398 ))
399 });
400
401 interp.register_fn(
408 "to_int",
409 Arity::Exact(1),
410 |a: &[Value], _h: &mut H, s| match &a[0] {
411 Value::Int(n) => Ok(Value::Int(*n)),
412 Value::Float(x) => Ok(float_to_int(*x).map_or(Value::Nil, Value::Int)),
416 other => Ok(as_str(other, s)?
417 .trim()
418 .parse::<i64>()
419 .map_or(Value::Nil, Value::Int)),
420 },
421 );
422
423 interp.register_fn(
424 "to_int!",
425 Arity::Exact(1),
426 |a: &[Value], _h: &mut H, s| match &a[0] {
427 Value::Int(n) => Ok(Value::Int(*n)),
428 Value::Float(x) => float_to_int(*x)
429 .map(Value::Int)
430 .ok_or(EvalError::IntegerOverflow {
431 op: "to_int!",
432 at: s,
433 }),
434 other => {
435 let text = as_str(other, s)?;
436 text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
437 EvalError::native_fn(
438 "to_int!",
439 "`".to_string() + &text + "` is not an integer",
440 s,
441 )
442 .into()
443 })
444 }
445 },
446 );
447
448 interp.register_fn(
449 "to_float",
450 Arity::Exact(1),
451 |a: &[Value], _h: &mut H, s| match &a[0] {
452 Value::Float(x) => Ok(Value::Float(*x)),
453 Value::Int(n) => Ok(Value::Float(*n as f64)),
454 other => Ok(as_str(other, s)?
455 .trim()
456 .parse::<f64>()
457 .map_or(Value::Nil, Value::Float)),
458 },
459 );
460
461 interp.register_fn(
462 "abs",
463 Arity::Exact(1),
464 |a: &[Value], _h: &mut H, s| match &a[0] {
465 Value::Int(n) => n
468 .checked_abs()
469 .map(Value::Int)
470 .ok_or(EvalError::IntegerOverflow { op: "abs", at: s }),
471 Value::Float(x) => Ok(Value::Float(x.abs())),
472 other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
473 },
474 );
475
476 interp.register_fn("range", Arity::Range(1, 3), |a: &[Value], _h: &mut H, s| {
497 let (start, end, step) = match a.len() {
498 1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
499 2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
500 _ => (a[0].clone(), a[1].clone(), a[2].clone()),
501 };
502 range_list(start, &end, &step, s)
503 });
504
505 interp.register_fn(
512 "write_stdout",
513 Arity::Exact(1),
514 |a: &[Value], _h: &mut H, s| {
515 use std::io::Write;
516 let text = as_str(&a[0], s)?;
517 let mut out = std::io::stdout().lock();
518 out.write_all(text.as_bytes())
519 .and_then(|()| out.flush())
520 .map_err(|e| EvalError::native_fn("write_stdout", e.to_string(), s))?;
521 Ok(Value::Nil)
522 },
523 );
524 interp.register_fn(
525 "write_stderr",
526 Arity::Exact(1),
527 |a: &[Value], _h: &mut H, s| {
528 use std::io::Write;
529 let text = as_str(&a[0], s)?;
530 let mut err = std::io::stderr().lock();
531 err.write_all(text.as_bytes())
532 .and_then(|()| err.flush())
533 .map_err(|e| EvalError::native_fn("write_stderr", e.to_string(), s))?;
534 Ok(Value::Nil)
535 },
536 );
537
538 interp.register_higher_order_fn(
545 "sort_keyed",
546 Arity::Exact(2),
547 |a: &[Value], host: &mut H, caller: &tatara_lisp_eval::ffi::Caller<H>, s| {
548 let xs = match &a[1] {
549 Value::List(xs) => xs.to_vec(),
550 Value::Nil => Vec::new(),
551 other => {
552 return Err(EvalError::type_mismatch("a list", other.type_name(), s));
553 }
554 };
555 let mut keyed = Vec::with_capacity(xs.len());
556 for x in xs {
557 keyed.push((caller.apply_value(&a[0], vec![x.clone()], host, s)?, x));
558 }
559 Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
560 },
561 );
562}
563
564fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
566 match v {
567 Value::Int(n) => Ok(*n as f64),
568 Value::Float(x) => Ok(*x),
569 other => Err(EvalError::native_fn(
570 "range",
571 "expected a number, got ".to_string() + other.type_name(),
572 s,
573 )),
574 }
575}
576
577fn float_to_int(x: f64) -> Option<i64> {
580 const LIMIT: f64 = 9_223_372_036_854_775_808.0;
581 let t = x.trunc();
582 #[allow(clippy::cast_possible_truncation)]
583 (t.is_finite() && (-LIMIT..LIMIT).contains(&t)).then(|| t as i64)
584}
585
586fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
589 match (a, b) {
590 (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
591 EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
592 }),
593 _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
594 }
595}
596
597fn range_list(
598 start: Value,
599 end: &Value,
600 step: &Value,
601 s: tatara_lisp::Span,
602) -> Result<Value, EvalError> {
603 let end_f = range_num(end, s)?;
604 let step_f = range_num(step, s)?;
605 range_num(&start, s)?;
606 if step_f == 0.0 {
607 return Err(EvalError::native_fn(
608 "range",
609 "a step of zero never reaches the end",
610 s,
611 ));
612 }
613 let mut out = Vec::new();
614 let mut cur = start;
615 loop {
616 let c = range_num(&cur, s)?;
617 if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
618 break;
619 }
620 let next = range_add(&cur, step, s)?;
621 out.push(cur);
622 cur = next;
623 }
624 Ok(list(out))
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 #[test]
632 fn sort_keyed_is_stable_keyed_and_deep() {
633 assert_eq!(
635 ints("map(fn(p) last(p) end, sort_keyed(fn(p) first(p) end, [[2, 1], [1, 2], [2, 3], [1, 4]]))"),
636 vec![2, 4, 1, 3]
637 );
638 assert_eq!(
640 i("first(sort_keyed(fn(x) x end, reverse(range(0, 20000))))"),
641 0
642 );
643 assert_eq!(i("last(sort_keyed(fn(x) 0 - x end, range(0, 20000)))"), 0);
644 assert_eq!(ints("sort_keyed(fn(x) x end, [])"), Vec::<i64>::new());
646 assert!(crate::run("sort_keyed(fn(x) x end, [1, \"a\"])").is_err());
647 }
648
649 fn eval(src: &str) -> Value {
650 crate::run(src)
651 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
652 .value
653 }
654
655 fn s(src: &str) -> String {
656 match eval(src) {
657 Value::Str(v) => v.to_string(),
658 other => panic!("{src:?} produced {other:?}"),
659 }
660 }
661
662 fn i(src: &str) -> i64 {
663 match eval(src) {
664 Value::Int(v) => v,
665 other => panic!("{src:?} produced {other:?}"),
666 }
667 }
668
669 fn ints(src: &str) -> Vec<i64> {
670 match eval(src) {
671 Value::List(xs) => xs
672 .iter()
673 .map(|v| match v {
674 Value::Int(n) => *n,
675 other => panic!("{src:?} produced a non-Int element {other:?}"),
676 })
677 .collect(),
678 other => panic!("{src:?} produced {other:?}"),
679 }
680 }
681
682 #[test]
685 fn range_answers_as_the_lisp_definition_did() {
686 assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
687 assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
688 assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
689 assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
690 assert!(ints("range(5, 5)").is_empty());
691 assert!(ints("range(5, 2)").is_empty());
692 assert!(ints("range(0)").is_empty());
693 match eval("range(0, 1, 0.5)") {
695 Value::List(xs) => {
696 assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
697 assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
698 assert_eq!(xs.len(), 2);
699 }
700 other => panic!("{other:?}"),
701 }
702 }
703
704 #[test]
710 fn range_builds_long_lists_without_recursing() {
711 assert_eq!(i("length(range(0, 200000))"), 200_000);
712 assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
713 }
714
715 #[test]
718 fn range_refuses_a_zero_step_and_a_non_number() {
719 assert!(crate::run("range(0, 5, 0)").is_err());
720 assert!(crate::run("range(0, \"x\")").is_err());
721 }
722
723 #[test]
727 fn length_counts_characters_not_bytes() {
728 assert_eq!(i("length(\"hello\")"), 5);
729 assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
731 assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
733 }
734
735 #[test]
738 fn a_combining_sequence_counts_scalars_not_graphemes() {
739 assert_eq!(
741 i("length(\"e\\u{301}\")"),
742 2,
743 "blue counts scalar values; Elixir's String.length would say 1"
744 );
745 }
746
747 #[test]
748 fn length_also_works_on_a_list() {
749 assert_eq!(i("length([1, 2, 3])"), 3);
750 }
751
752 #[test]
753 fn case_and_trim() {
754 assert_eq!(s("upcase(\"abc\")"), "ABC");
755 assert_eq!(s("downcase(\"ABC\")"), "abc");
756 assert_eq!(s("trim(\" hi \")"), "hi");
757 assert_eq!(s("upcase(\"é\")"), "É");
759 }
760
761 #[test]
762 fn concat_and_to_s() {
763 assert_eq!(s("concat(\"a\", \"b\")"), "ab");
764 assert_eq!(s("concat(\"n=\", 42)"), "n=42");
765 assert_eq!(s("to_s(42)"), "42");
766 assert_eq!(s("to_s(true)"), "true");
767 }
768
769 #[test]
773 fn plus_is_not_string_concatenation() {
774 assert!(
775 crate::run("\"a\" + \"b\"").is_err(),
776 "`+` must not silently concatenate — use concat"
777 );
778 }
779
780 #[test]
781 fn split_and_join() {
782 assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
783 assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
784 assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
786 }
787
788 #[test]
789 fn predicates() {
790 assert!(matches!(
791 eval("contains?(\"hello\", \"ell\")"),
792 Value::Bool(true)
793 ));
794 assert!(matches!(
795 eval("contains?(\"hello\", \"xyz\")"),
796 Value::Bool(false)
797 ));
798 assert!(matches!(
799 eval("starts_with?(\"hello\", \"he\")"),
800 Value::Bool(true)
801 ));
802 assert!(matches!(
803 eval("ends_with?(\"hello\", \"lo\")"),
804 Value::Bool(true)
805 ));
806 }
807
808 #[test]
809 fn replace_and_chars() {
810 assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
811 assert_eq!(i("length(chars(\"abc\"))"), 3);
812 }
813
814 #[test]
817 fn reverse_is_character_wise() {
818 assert_eq!(s("reverse(\"abc\")"), "cba");
819 assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
820 }
821
822 #[test]
823 fn reverse_also_works_on_a_list() {
824 assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
825 }
826
827 #[test]
832 fn to_int_is_nil_on_garbage_rather_than_zero() {
833 assert_eq!(i("to_int(\"42\")"), 42);
834 assert!(
835 matches!(eval("to_int(\"banana\")"), Value::Nil),
836 "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
837 );
838 assert!(
839 matches!(eval("to_int(\"0\")"), Value::Int(0)),
840 "and a real 0 is still a real 0 — the two must stay distinguishable"
841 );
842 }
843
844 #[test]
845 fn to_int_bang_raises_on_garbage() {
846 assert_eq!(i("to_int!(\"42\")"), 42);
847 let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
848 assert!(err.to_string().contains("banana"), "must name it: {err}");
849 }
850
851 #[test]
852 fn numeric_conversions_and_abs() {
853 assert_eq!(i("to_int(3.9)"), 3);
854 assert_eq!(i("abs(0 - 5)"), 5);
855 assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
856 assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
857 }
858
859 #[test]
861 fn a_non_string_argument_is_a_type_error() {
862 assert!(crate::run("upcase([1, 2])").is_err());
863 assert!(crate::run("join(\"not a list\", \",\")").is_err());
864 }
865}