Skip to main content

blue_lang_runtime/
stdlib.rs

1//! blue's string and number core.
2//!
3//! tatara-lisp ships arithmetic, comparison, list and trig primitives and
4//! **no string operations at all** — no length, no concatenation, no case
5//! conversion, no number parsing. For a language whose surface is Ruby's, that
6//! is the largest parity gap there is: `String` is the most-used type in Ruby
7//! by a wide margin.
8//!
9//! # Why these live in blue and not in tatara-lisp
10//!
11//! The fleet rule is to extend the substrate rather than re-implement, and
12//! generic helpers belong upstream. These are not generic: the *semantics* are
13//! blue's, and they are Ruby's semantics specifically.
14//!
15//! The clearest case is `length`. Ruby's `String#length` counts **characters**;
16//! Rust's `str::len` counts **bytes**; Elixir's `String.length/1` counts
17//! grapheme clusters. Three languages, three answers, all defensible. Blue owes
18//! its users Ruby's answer, and encoding that choice into tatara-lisp would push
19//! one language's convention onto every other consumer of the substrate.
20//!
21//! Promoting a genuinely encoding-neutral core upstream later stays open; the
22//! character-counting ones are blue's by right.
23//!
24//! # Character, not byte, not grapheme
25//!
26//! Every index and length here is in **Unicode scalar values** (Rust `char`).
27//! That matches Ruby for the overwhelming majority of text and is stated rather
28//! than left to be discovered — a `length` that silently returns bytes is the
29//! bug that only appears once a user types a non-ASCII character.
30//!
31//! Grapheme clusters (Elixir's choice) would need a segmentation table; where
32//! the two differ — a family emoji, a combining accent — blue reports scalar
33//! values. `a_combining_sequence_counts_scalars_not_graphemes` pins it.
34
35use tatara_lisp_eval::ffi::Arity;
36use tatara_lisp_eval::{EvalError, Interpreter, Value};
37
38const TRIM_OPTIONS: &[&str] = &["side", "chars"];
39
40fn trim_with(text: &str, opts: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
41    let bad = |message: String| crate::errors::raise_kind("bad_option", message, s);
42    let mut side = "both".to_string();
43    let mut chars: Option<Vec<char>> = None;
44    match opts {
45        Value::Nil => {}
46        Value::Map(m) => {
47            for (k, v) in m.iter() {
48                let key = match k {
49                    tatara_lisp_eval::MapKey::Keyword(n)
50                    | tatara_lisp_eval::MapKey::Symbol(n)
51                    | tatara_lisp_eval::MapKey::Str(n) => n.to_string(),
52                    _ => String::new(),
53                };
54                match (key.as_str(), v) {
55                    ("side", Value::Keyword(k)) if matches!(&**k, "both" | "start" | "end") => {
56                        side = k.to_string();
57                    }
58                    ("side", _) => return Err(bad("side must be :both, :start or :end".into())),
59                    ("chars", Value::Str(c)) => chars = Some(c.chars().collect()),
60                    ("chars", _) => return Err(bad("chars must be text".into())),
61                    _ => {
62                        return Err(bad(format!(
63                            "unknown option {key}; this verb takes {}",
64                            TRIM_OPTIONS.join(", ")
65                        )))
66                    }
67                }
68            }
69        }
70        other => {
71            return Err(bad(format!(
72                "options must be a map, got {}",
73                other.type_name()
74            )))
75        }
76    }
77    let out = match (&chars, side.as_str()) {
78        (None, "both") => text.trim(),
79        (None, "start") => text.trim_start(),
80        (None, _) => text.trim_end(),
81        (Some(set), "both") => text.trim_matches(|c| set.contains(&c)),
82        (Some(set), "start") => text.trim_start_matches(|c| set.contains(&c)),
83        (Some(set), _) => text.trim_end_matches(|c| set.contains(&c)),
84    };
85    Ok(Value::Str(out.into()))
86}
87
88fn as_str(v: &Value, span: tatara_lisp::Span) -> Result<String, EvalError> {
89    match v {
90        Value::Str(s) => Ok(s.to_string()),
91        // A symbol is text the author wrote; accepting it makes `upcase(:ok)`
92        // work the way a Ruby programmer expects of a symbol.
93        Value::Symbol(s) | Value::Keyword(s) => Ok(s.to_string()),
94        other => Err(EvalError::type_mismatch(
95            "a string",
96            other.type_name(),
97            span,
98        )),
99    }
100}
101
102/// blue's one equality — what `==`, `!=`, `contains`, `index_of`, `count_of`
103/// and `distinct` all mean (okite D0001–D0003).
104///
105/// Ruby's answer: numbers compare by value across Int and Float (`4 == 4.0`),
106/// strings, symbols and keywords by text (each only with its own kind), lists
107/// element by element, maps by their entries whatever order they were built in,
108/// nil only with nil (not with `[]`, D0004), functions by identity. Until
109/// 2026-09-27 `==` was tatara's Scheme `equal?`, under which `4 == 4.0` was
110/// false and two equal maps were unequal unless they were the same object.
111/// tatara keeps Scheme's `equal?` for its own programs; blue redefines the
112/// name in its interpreter, and tatara's own `member?`, `position` and
113/// `distinct` call `equal?` by name, so they follow.
114pub fn blue_equal(a: &Value, b: &Value) -> bool {
115    match (a, b) {
116        (Value::Nil, Value::Nil) => true,
117        (Value::Bool(x), Value::Bool(y)) => x == y,
118        (Value::Int(x), Value::Int(y)) => x == y,
119        (Value::Float(x), Value::Float(y)) => x == y,
120        (Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => (*x as f64) == *y,
121        (Value::Str(x), Value::Str(y))
122        | (Value::Symbol(x), Value::Symbol(y))
123        | (Value::Keyword(x), Value::Keyword(y)) => x == y,
124        (Value::List(x), Value::List(y)) => {
125            x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| blue_equal(p, q))
126        }
127        (Value::Map(x), Value::Map(y)) => {
128            x.len() == y.len()
129                && x.iter()
130                    .all(|(k, v)| y.get(k).is_some_and(|w| blue_equal(v, w)))
131        }
132        (Value::Closure(x), Value::Closure(y)) => std::sync::Arc::ptr_eq(x, y),
133        (Value::NativeFn(x), Value::NativeFn(y)) => x.name == y.name,
134        (Value::Sexp(x, _), Value::Sexp(y, _)) => x == y,
135        _ => false,
136    }
137}
138
139/// `to_s` (okite D0005, D0006): text for a person. A string, symbol or keyword
140/// is its own text and nil is empty, as in Ruby; every other value is its blue
141/// literal. Until 2026-09-27 a map rendered as the word `map`, a list lost its
142/// brackets (`[1, {a: 2}]` came out `1 map`) and `1.0` came out `1`.
143fn chain_rules_value() -> Value {
144    use blue_lang_check::chains::{cases, Case, Kind, RULES};
145    let sym = |s: &str| Value::Symbol(std::sync::Arc::from(s));
146    let text = |s: &str| Value::Str(std::sync::Arc::from(s));
147    let hole = |n: usize| (0..n).map(|_| sym("x")).collect::<Vec<_>>();
148    let lambda = |body: Value| Value::list([sym("lambda"), Value::list([sym("x")]), body]);
149    let call = |name: &str, args: Vec<Value>| Value::list(std::iter::once(sym(name)).chain(args));
150    Value::list(RULES.iter().map(|rule| {
151        let rows = cases(rule).into_iter().map(|case| match case {
152            Case::Call { inner, argc } => {
153                let inner_call = call(inner, hole(argc));
154                Value::list([
155                    text(&format!("{}({}(x))", rule.outer, inner)),
156                    Value::Nil,
157                    lambda(call(rule.outer, vec![inner_call.clone()])),
158                    lambda(inner_call),
159                ])
160            }
161            Case::Literal(kind) => Value::list([
162                text(&format!("{}(<literal>)", rule.outer)),
163                Value::Keyword(std::sync::Arc::from(match kind {
164                    Kind::Text => "text",
165                    Kind::Int => "int",
166                    Kind::Float => "float",
167                })),
168                lambda(call(rule.outer, vec![sym("x")])),
169                lambda(sym("x")),
170            ]),
171        });
172        Value::list([
173            text(rule.id),
174            text(rule.slug),
175            text(rule.outer),
176            text(rule.soundness),
177            Value::list(rows),
178        ])
179    }))
180}
181
182fn render(v: &Value) -> String {
183    match v {
184        Value::Nil => String::new(),
185        Value::Str(s) | Value::Symbol(s) | Value::Keyword(s) => s.to_string(),
186        Value::Error(e) => crate::errors::describe(e),
187        other => literal(other),
188    }
189}
190
191/// A value as blue source writes it: `[1, "a", nil]`, `{a: 1, b: 2.0}`.
192/// Map entries are sorted by key, since a map has no order of its own and the
193/// text must be the same for equal maps (D0006).
194fn literal(v: &Value) -> String {
195    match v {
196        Value::Nil => "nil".into(),
197        Value::Bool(b) => b.to_string(),
198        Value::Int(n) => n.to_string(),
199        Value::Float(x) => float_text(*x),
200        Value::Str(s) => quoted(s),
201        Value::Symbol(s) => s.to_string(),
202        Value::Keyword(s) => format!(":{s}"),
203        Value::List(items) => {
204            let parts: Vec<String> = items.iter().map(literal).collect();
205            format!("[{}]", parts.join(", "))
206        }
207        Value::Map(m) => {
208            let mut entries: Vec<String> = m
209                .iter()
210                .map(|(k, v)| format!("{} {}", key_text(k), literal(v)))
211                .collect();
212            entries.sort();
213            format!("{{{}}}", entries.join(", "))
214        }
215        other => other.type_name().to_string(),
216    }
217}
218
219/// A map key as it is written before its value: `a:` for a keyword or symbol,
220/// `"a" =>` / `1 =>` for anything else.
221fn key_text(k: &tatara_lisp_eval::value::MapKey) -> String {
222    use tatara_lisp_eval::value::MapKey;
223    match k {
224        MapKey::Keyword(s) | MapKey::Symbol(s) => format!("{s}:"),
225        MapKey::Str(s) => format!("{} =>", quoted(s)),
226        MapKey::Int(n) => format!("{n} =>"),
227        MapKey::Float(bits) => format!("{} =>", float_text(f64::from_bits(*bits))),
228        MapKey::Bool(b) => format!("{b} =>"),
229        MapKey::Nil => "nil =>".into(),
230    }
231}
232
233/// A float keeps its point, as in Ruby: `1.0`, `2.5`.
234fn float_text(x: f64) -> String {
235    if x.is_finite() && x.fract() == 0.0 && x.abs() < 1e16 {
236        format!("{x:.1}")
237    } else {
238        format!("{x}")
239    }
240}
241
242fn quoted(s: &str) -> String {
243    let mut out = String::with_capacity(s.len() + 2);
244    out.push('"');
245    for c in s.chars() {
246        match c {
247            '"' => out.push_str("\\\""),
248            '\\' => out.push_str("\\\\"),
249            '\n' => out.push_str("\\n"),
250            '\t' => out.push_str("\\t"),
251            c => out.push(c),
252        }
253    }
254    out.push('"');
255    out
256}
257
258fn list(items: Vec<Value>) -> Value {
259    Value::list(items)
260}
261
262/// Install blue's string and number core.
263pub fn install_blue_stdlib<H: 'static>(interp: &mut Interpreter<H>) {
264    crate::errors::install(interp);
265    crate::paths::install(interp);
266    crate::spread::install(interp);
267    // ── text ──────────────────────────────────────────────────────────
268
269    // `length` counts CHARACTERS, per Ruby. Also accepts a list, where it is
270    // the element count — Ruby's `Array#length`.
271    interp.register_fn(
272        "length",
273        Arity::Exact(1),
274        |a: &[Value], _h: &mut H, span| match &a[0] {
275            Value::List(items) => Ok(Value::Int(items.len() as i64)),
276            other => Ok(Value::Int(as_str(other, span)?.chars().count() as i64)),
277        },
278    );
279
280    // The documented builtins, for a program that reasons about names (the
281    // catalogue's "shares a builtin's name" column).
282    interp.register_fn(
283        "builtin_names",
284        Arity::Exact(0),
285        |_a: &[Value], _h: &mut H, _s| {
286            Ok(Value::list(
287                crate::docs::NAMES
288                    .iter()
289                    .map(|n| Value::Str(std::sync::Arc::from(n.name))),
290            ))
291        },
292    );
293    interp.register_fn(
294        "chain_rules",
295        Arity::Exact(0),
296        |_a: &[Value], _h: &mut H, _s| Ok(chain_rules_value()),
297    );
298    interp.register_fn("to_s", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
299        Ok(Value::Str(render(&a[0]).into()))
300    });
301
302    interp.register_fn("upcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
303        Ok(Value::Str(as_str(&a[0], s)?.to_uppercase().into()))
304    });
305
306    interp.register_fn("downcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
307        Ok(Value::Str(as_str(&a[0], s)?.to_lowercase().into()))
308    });
309
310    interp.register_fn("trim", Arity::Range(1, 2), |a: &[Value], _h: &mut H, s| {
311        let text = as_str(&a[0], s)?;
312        trim_with(&text, a.get(1).unwrap_or(&Value::Nil), s)
313    });
314
315    interp.register_fn(
316        blue_lang_syntax::LOWERED_OPTIONAL_ARITY,
317        Arity::Exact(4),
318        |a: &[Value], _h: &mut H, s| {
319            let name = as_str(&a[0], s)?;
320            let (Value::List(rest), Value::Int(required), Value::Int(most)) = (&a[1], &a[2], &a[3])
321            else {
322                return Err(EvalError::native_fn(
323                    blue_lang_syntax::LOWERED_OPTIONAL_ARITY,
324                    "expects a name, the rest list and two counts",
325                    s,
326                ));
327            };
328            if rest.len() as i64 > *most {
329                let want = Arity::Range(*required as usize, (*required + *most) as usize);
330                return Err(EvalError::native_fn(
331                    name.as_str(),
332                    format!(
333                        "takes {}, got {}",
334                        crate::messages::arguments(&want),
335                        *required as usize + rest.len()
336                    ),
337                    s,
338                ));
339            }
340            Ok(Value::Nil)
341        },
342    );
343
344    interp.register_fn(
345        blue_lang_syntax::LOWERED_OPTIONAL_ARG,
346        Arity::Exact(2),
347        |a: &[Value], _h: &mut H, s| match (&a[0], &a[1]) {
348            (Value::List(rest), Value::Int(i)) => {
349                Ok(rest.get(*i as usize).cloned().unwrap_or(Value::Nil))
350            }
351            _ => Err(EvalError::native_fn(
352                blue_lang_syntax::LOWERED_OPTIONAL_ARG,
353                "expects the rest list and an index",
354                s,
355            )),
356        },
357    );
358
359    // `concat(a, …)` joins the text of one or more arguments, left to right
360    // (okite D0007; Ruby's String#concat takes many). Two-only until
361    // 2026-09-27, which made `concat(a, b, c)` an arity error. `+` stays
362    // arithmetic: Ruby overloads `+` on String, but blue's `+` lowers to
363    // tatara's numeric `+`, and making it polymorphic would make a type error
364    // at a seam disappear into a string.
365    interp.register_fn(
366        "concat",
367        Arity::AtLeast(1),
368        |a: &[Value], _h: &mut H, _s| {
369            Ok(Value::Str(a.iter().map(render).collect::<String>().into()))
370        },
371    );
372
373    // ── equality and kinds (okite D0001–D0004, D0010) ─────────────────────
374    //
375    // `==` lowers to `equal?` and `!=` to `not=`; both are redefined here so
376    // blue's interpreter has one equality. See `blue_equal`.
377    interp.register_fn("equal?", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
378        Ok(Value::Bool(blue_equal(&a[0], &a[1])))
379    });
380    interp.register_fn("not=", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
381        Ok(Value::Bool(!blue_equal(&a[0], &a[1])))
382    });
383
384    // One predicate per kind, and exactly one holds of any value (D0010).
385    // tatara's `nil?` is its Scheme alias for `null?`, true of `[]` as well,
386    // and its `list?` is true of nil; blue's nil is absent and `[]` is an empty
387    // list (D0004), so blue redefines both. tatara's own library ends its
388    // recursion with `null?`, which is untouched.
389    interp.register_fn("nil?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
390        Ok(Value::Bool(matches!(a[0], Value::Nil)))
391    });
392    interp.register_fn("list?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
393        Ok(Value::Bool(matches!(a[0], Value::List(_))))
394    });
395    interp.register_fn("map?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
396        Ok(Value::Bool(matches!(a[0], Value::Map(_))))
397    });
398    interp.register_fn("float?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
399        Ok(Value::Bool(matches!(a[0], Value::Float(_))))
400    });
401    interp.register_fn("bool?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
402        Ok(Value::Bool(matches!(a[0], Value::Bool(_))))
403    });
404
405    // The empty list is always `[]`, never nil (D0011). tatara's `cdr` (and so
406    // `rest`, which is `cdr`) and `append` returned nil for an empty result,
407    // Scheme's convention, which under D0004 made `rest([1]) == []` false.
408    // Same contracts otherwise: `cdr` of an empty list is still an error.
409    interp.register_fn("cdr", Arity::Exact(1), |a: &[Value], _h: &mut H, span| {
410        match &a[0] {
411            // Shares the tail's structure: O(log n), not a copy of it.
412            Value::List(xs) if !xs.is_empty() => Ok(Value::List(std::sync::Arc::new(xs.skip(1)))),
413            Value::Nil | Value::List(_) => Err(EvalError::native_fn(
414                std::sync::Arc::<str>::from("cdr"),
415                "cdr of empty list",
416                span,
417            )),
418            other => Err(EvalError::type_mismatch("pair", other.type_name(), span)),
419        }
420    });
421    interp.register_owned_fn("append", Arity::Any, |a: Vec<Value>, _h: &mut H, span| {
422        // Persistent concatenation: each operand's structure is shared, so
423        // building a list by `append(acc, [x])` is linear overall, not
424        // quadratic (G7). The arguments arrive by value, so an accumulator
425        // the caller holds alone (tatara-lisp-eval runs a tail call to an
426        // owned primitive after releasing the caller's frame) is extended in
427        // its own allocation by `Arc::make_mut` instead of copied at the tail.
428        let mut lists = Vec::with_capacity(a.len());
429        for v in a {
430            match v {
431                Value::Nil => {}
432                Value::List(xs) => lists.push(xs),
433                other => return Err(EvalError::type_mismatch("list", other.type_name(), span)),
434            }
435        }
436        let mut lists = lists.into_iter();
437        let Some(mut out) = lists.next() else {
438            return Ok(Value::List(std::sync::Arc::new(
439                tatara_lisp_eval::List::new(),
440            )));
441        };
442        let acc = std::sync::Arc::make_mut(&mut out);
443        for xs in lists {
444            acc.append(
445                std::sync::Arc::try_unwrap(xs)
446                    .unwrap_or_else(|shared| tatara_lisp_eval::List::clone(&shared)),
447            );
448        }
449        Ok(Value::List(out))
450    });
451
452    interp.register_fn("split", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
453        let text = as_str(&a[0], s)?;
454        let sep = as_str(&a[1], s)?;
455        // An empty separator splits into characters, as Ruby's `split("")`
456        // does. Rust's `split("")` yields leading/trailing empties instead,
457        // which is the wrong answer here.
458        // Every field is kept: n separators give n + 1 fields, so `join` undoes
459        // `split` exactly (okite D0012). A deliberate deviation from Ruby, which
460        // drops trailing empty fields: tried on 2026-09-27, it broke nisshi's
461        // hash chain, kueri's scripts and moji's `lines`, because a parser whose
462        // split loses a field loses data and still reports success.
463        let parts: Vec<Value> = if sep.is_empty() {
464            text.chars()
465                .map(|c| Value::Str(c.to_string().into()))
466                .collect()
467        } else {
468            text.split(sep.as_str())
469                .map(|p| Value::Str(p.into()))
470                .collect()
471        };
472        Ok(list(parts))
473    });
474
475    interp.register_fn("join", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
476        let sep = as_str(&a[1], s)?;
477        match &a[0] {
478            Value::List(items) => Ok(Value::Str(
479                items
480                    .iter()
481                    .map(render)
482                    .collect::<Vec<_>>()
483                    .join(&sep)
484                    .into(),
485            )),
486            other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
487        }
488    });
489
490    interp.register_fn(
491        "contains?",
492        Arity::Exact(2),
493        |a: &[Value], _h: &mut H, s| {
494            Ok(Value::Bool(as_str(&a[0], s)?.contains(&as_str(&a[1], s)?)))
495        },
496    );
497
498    interp.register_fn(
499        "starts_with?",
500        Arity::Exact(2),
501        |a: &[Value], _h: &mut H, s| {
502            Ok(Value::Bool(
503                as_str(&a[0], s)?.starts_with(&as_str(&a[1], s)?),
504            ))
505        },
506    );
507
508    interp.register_fn(
509        "ends_with?",
510        Arity::Exact(2),
511        |a: &[Value], _h: &mut H, s| {
512            Ok(Value::Bool(as_str(&a[0], s)?.ends_with(&as_str(&a[1], s)?)))
513        },
514    );
515
516    interp.register_fn(
517        "text_index",
518        Arity::Exact(3),
519        |a: &[Value], _h: &mut H, s| {
520            Ok(Value::Int(text_index(
521                &as_str(&a[0], s)?,
522                &as_str(&a[1], s)?,
523                as_index(&a[2], s)?,
524            )))
525        },
526    );
527
528    interp.register_fn(
529        "text_last_index",
530        Arity::Exact(3),
531        |a: &[Value], _h: &mut H, s| {
532            Ok(Value::Int(text_last_index(
533                &as_str(&a[0], s)?,
534                &as_str(&a[1], s)?,
535                as_index(&a[2], s)?,
536            )))
537        },
538    );
539
540    interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
541        Ok(Value::Str(
542            as_str(&a[0], s)?
543                .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
544                .into(),
545        ))
546    });
547
548    interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
549        match &a[0] {
550            Value::List(items) => Ok(Value::list(items.iter().rev().cloned())),
551            // Reversed by CHARACTER, so a multi-byte character survives. A
552            // byte-wise reverse produces invalid UTF-8.
553            other => Ok(Value::Str(
554                as_str(other, s)?.chars().rev().collect::<String>().into(),
555            )),
556        }
557    });
558
559    interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
560        Ok(list(
561            as_str(&a[0], s)?
562                .chars()
563                .map(|c| Value::Str(c.to_string().into()))
564                .collect(),
565        ))
566    });
567
568    // ── numbers ───────────────────────────────────────────────────────
569
570    // `to_int` RETURNS NIL on unparseable input rather than raising. Ruby's
571    // `String#to_i` answers 0 for garbage, which silently turns a parse failure
572    // into a plausible number; nil is falsy and cannot be mistaken for a
573    // result. `to_int!` is the raising form for callers who want the failure.
574    interp.register_fn(
575        "to_int",
576        Arity::Exact(1),
577        |a: &[Value], _h: &mut H, s| match &a[0] {
578            Value::Int(n) => Ok(Value::Int(*n)),
579            // A float with no Int (non-finite, or past i64) is nil like any
580            // other unconvertible input; `as i64` saturated it to a plausible
581            // wrong number.
582            Value::Float(x) => Ok(float_to_int(*x).map_or(Value::Nil, Value::Int)),
583            other => Ok(as_str(other, s)?
584                .trim()
585                .parse::<i64>()
586                .map_or(Value::Nil, Value::Int)),
587        },
588    );
589
590    interp.register_fn(
591        "to_int!",
592        Arity::Exact(1),
593        |a: &[Value], _h: &mut H, s| match &a[0] {
594            Value::Int(n) => Ok(Value::Int(*n)),
595            Value::Float(x) => float_to_int(*x)
596                .map(Value::Int)
597                .ok_or(EvalError::IntegerOverflow {
598                    op: "to_int!",
599                    at: s,
600                }),
601            other => {
602                let text = as_str(other, s)?;
603                text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
604                    EvalError::native_fn(
605                        "to_int!",
606                        "`".to_string() + &text + "` is not an integer",
607                        s,
608                    )
609                    .into()
610                })
611            }
612        },
613    );
614
615    interp.register_fn(
616        "to_float",
617        Arity::Exact(1),
618        |a: &[Value], _h: &mut H, s| match &a[0] {
619            Value::Float(x) => Ok(Value::Float(*x)),
620            Value::Int(n) => Ok(Value::Float(*n as f64)),
621            other => Ok(as_str(other, s)?
622                .trim()
623                .parse::<f64>()
624                .map_or(Value::Nil, Value::Float)),
625        },
626    );
627
628    interp.register_fn(
629        "abs",
630        Arity::Exact(1),
631        |a: &[Value], _h: &mut H, s| match &a[0] {
632            // Checked, as tatara's `abs` is (G5): |i64::MIN| does not fit, and
633            // `n.abs()` wrapped in release and panicked in debug.
634            Value::Int(n) => n
635                .checked_abs()
636                .map(Value::Int)
637                .ok_or(EvalError::IntegerOverflow { op: "abs", at: s }),
638            Value::Float(x) => Ok(Value::Float(x.abs())),
639            other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
640        },
641    );
642
643    // ── ranges ────────────────────────────────────────────────────────
644
645    // `range` is a LOOP here, not a recursion. tatara-lisp's stdlib defines it
646    // in Lisp (`lisp_stdlib.tlisp`, where `range-impl` conses one frame per
647    // element), so `range(0, 5000)` overflowed the 8 MiB main stack and
648    // aborted the process. Everything built on it inherited the ceiling:
649    // retsu's `indexes`, `zip_with` and `enumerate`, and shomei's
650    // `chain_first_break`, which could not verify a 5,000-entry chain
651    // (measured 2026-09-24: 4,000 elements fine, 5,000 aborted).
652    //
653    // Same arities and answers as the Lisp definition: (end), (start, end),
654    // (start, end, step), ascending for a positive step, descending for a
655    // negative one, and each next element is the previous plus the step under
656    // the ordinary number rules (Int + Int is Int; a Float anywhere makes the
657    // rest Float). Two refusals the Lisp version lacked: a zero step, which
658    // recursed forever, and a wrong arity, which printed a message and
659    // returned nil.
660    //
661    // The destination is upstream: when tatara-lisp's own `range` is a loop,
662    // this registration is deleted.
663    interp.register_fn("range", Arity::Range(1, 3), |a: &[Value], _h: &mut H, s| {
664        let (start, end, step) = match a.len() {
665            1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
666            2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
667            _ => (a[0].clone(), a[1].clone(), a[2].clone()),
668        };
669        range_list(start, &end, &step, s)
670    });
671
672    // `write_stdout(s)` / `write_stderr(s)`: the text exactly, no quotes, no
673    // newline added. `print`, `println` and `display` all render a string
674    // with its quotes (a value printer, right for a REPL and wrong for a
675    // command's output), so until these a blue command-line tool could not
676    // print plain text. Output only, like `println`; anything else is not a
677    // string and is refused.
678    interp.register_fn(
679        "write_stdout",
680        Arity::Exact(1),
681        |a: &[Value], _h: &mut H, s| {
682            use std::io::Write;
683            let text = as_str(&a[0], s)?;
684            let mut out = std::io::stdout().lock();
685            out.write_all(text.as_bytes())
686                .and_then(|()| out.flush())
687                .map_err(|e| EvalError::native_fn("write_stdout", e.to_string(), s))?;
688            Ok(Value::Nil)
689        },
690    );
691    interp.register_fn(
692        "write_stderr",
693        Arity::Exact(1),
694        |a: &[Value], _h: &mut H, s| {
695            use std::io::Write;
696            let text = as_str(&a[0], s)?;
697            let mut err = std::io::stderr().lock();
698            err.write_all(text.as_bytes())
699                .and_then(|()| err.flush())
700                .map_err(|e| EvalError::native_fn("write_stderr", e.to_string(), s))?;
701            Ok(Value::Nil)
702        },
703    );
704
705    // `sort_keyed(key, xs)`: xs ordered by key(x), stably, in O(n log n),
706    // under `compare`'s rules. Every sort written in blue (junjo's) recurses
707    // per element and aborts the process near 600 elements; this is
708    // tatara-lisp's `sort-by-key` (0.3.60), which blue cannot name because
709    // it is kebab-case, bound to a name blue can. The engine is upstream,
710    // `hof::sort_keyed_values`; only the spelling lives here.
711    interp.register_higher_order_fn(
712        "sort_keyed",
713        Arity::Exact(2),
714        |a: &[Value], host: &mut H, caller: &tatara_lisp_eval::ffi::Caller<H>, s| {
715            let xs = match &a[1] {
716                Value::List(xs) => xs.to_vec(),
717                Value::Nil => Vec::new(),
718                other => {
719                    return Err(EvalError::type_mismatch("a list", other.type_name(), s));
720                }
721            };
722            let mut keyed = Vec::with_capacity(xs.len());
723            for x in xs {
724                keyed.push((caller.apply_value(&a[0], vec![x.clone()], host, s)?, x));
725            }
726            Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
727        },
728    );
729
730    interp.register_fn(
731        "error_message",
732        Arity::Exact(1),
733        |a: &[Value], _h: &mut H, s| match &a[0] {
734            Value::Error(e) => Ok(Value::Str(e.message.clone())),
735            other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
736        },
737    );
738
739    interp.register_fn(
740        "error_kind",
741        Arity::Exact(1),
742        |a: &[Value], _h: &mut H, s| match &a[0] {
743            Value::Error(e) => Ok(Value::Keyword(e.tag.clone())),
744            other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
745        },
746    );
747
748    interp.register_fn(
749        "map_entries",
750        Arity::Exact(1),
751        |a: &[Value], _h: &mut H, s| match &a[0] {
752            Value::Map(m) => {
753                let keyed = m
754                    .iter()
755                    .map(|(k, v)| (k.to_value(), list(vec![k.to_value(), v.clone()])))
756                    .collect();
757                Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
758            }
759            Value::Nil => Ok(list(Vec::new())),
760            other => Err(EvalError::type_mismatch("a map", other.type_name(), s)),
761        },
762    );
763}
764
765fn as_index(v: &Value, span: tatara_lisp::Span) -> Result<i64, EvalError> {
766    match v {
767        Value::Int(n) => Ok(*n),
768        other => Err(EvalError::type_mismatch(
769            "an integer",
770            other.type_name(),
771            span,
772        )),
773    }
774}
775
776fn text_index(text: &str, sub: &str, from: i64) -> i64 {
777    let from = usize::try_from(from.max(0)).unwrap_or(usize::MAX);
778    let start = match text.char_indices().nth(from) {
779        Some((b, _)) => b,
780        None if text.chars().count() == from => text.len(),
781        None => return -1,
782    };
783    text[start..].find(sub).map_or(-1, |b| {
784        i64::try_from(from + text[start..start + b].chars().count()).unwrap_or(i64::MAX)
785    })
786}
787
788fn text_last_index(text: &str, sub: &str, from: i64) -> i64 {
789    let Ok(from) = usize::try_from(from) else {
790        return -1;
791    };
792    let total = text.chars().count();
793    let width = sub.chars().count();
794    if width > total {
795        return -1;
796    }
797    let limit = from.min(total - width);
798    let end = text
799        .char_indices()
800        .nth(limit + width)
801        .map_or(text.len(), |(b, _)| b);
802    text[..end].rfind(sub).map_or(-1, |b| {
803        i64::try_from(text[..b].chars().count()).unwrap_or(i64::MAX)
804    })
805}
806
807/// A number's value as a float, or a type error naming `range`.
808fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
809    match v {
810        Value::Int(n) => Ok(*n as f64),
811        Value::Float(x) => Ok(*x),
812        other => Err(EvalError::native_fn(
813            "range",
814            "expected a number, got ".to_string() + other.type_name(),
815            s,
816        )),
817    }
818}
819
820/// A float's integer part as an `i64`, or `None` when it is not finite or
821/// does not fit. `as i64` saturates instead.
822fn float_to_int(x: f64) -> Option<i64> {
823    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
824    let t = x.trunc();
825    #[allow(clippy::cast_possible_truncation)]
826    (t.is_finite() && (-LIMIT..LIMIT).contains(&t)).then(|| t as i64)
827}
828
829/// `a + b` under the number rules the Lisp `range` used: Int + Int stays Int,
830/// anything with a Float is Float.
831fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
832    match (a, b) {
833        (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
834            EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
835        }),
836        _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
837    }
838}
839
840fn range_list(
841    start: Value,
842    end: &Value,
843    step: &Value,
844    s: tatara_lisp::Span,
845) -> Result<Value, EvalError> {
846    let end_f = range_num(end, s)?;
847    let step_f = range_num(step, s)?;
848    range_num(&start, s)?;
849    if step_f == 0.0 {
850        return Err(EvalError::native_fn(
851            "range",
852            "a step of zero never reaches the end",
853            s,
854        ));
855    }
856    let mut out = Vec::new();
857    let mut cur = start;
858    loop {
859        let c = range_num(&cur, s)?;
860        if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
861            break;
862        }
863        let next = range_add(&cur, step, s)?;
864        out.push(cur);
865        cur = next;
866    }
867    Ok(list(out))
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873
874    #[test]
875    fn sort_keyed_is_stable_keyed_and_deep() {
876        // Ties keep input order; the key is computed per element.
877        assert_eq!(
878            ints("map(fn(p) last(p) end, sort_keyed(fn(p) first(p) end, [[2, 1], [1, 2], [2, 3], [1, 4]]))"),
879            vec![2, 4, 1, 3]
880        );
881        // 20,000 in reverse: every blue-written sort aborts far below this.
882        assert_eq!(
883            i("first(sort_keyed(fn(x) x end, reverse(range(0, 20000))))"),
884            0
885        );
886        assert_eq!(i("last(sort_keyed(fn(x) 0 - x end, range(0, 20000)))"), 0);
887        // The empty case, and a refusal for keys that cannot be ordered.
888        assert_eq!(ints("sort_keyed(fn(x) x end, [])"), Vec::<i64>::new());
889        assert!(crate::run("sort_keyed(fn(x) x end, [1, \"a\"])").is_err());
890    }
891
892    fn eval(src: &str) -> Value {
893        crate::run(src)
894            .unwrap_or_else(|e| panic!("{src:?}: {e}"))
895            .value
896    }
897
898    fn s(src: &str) -> String {
899        match eval(src) {
900            Value::Str(v) => v.to_string(),
901            other => panic!("{src:?} produced {other:?}"),
902        }
903    }
904
905    fn i(src: &str) -> i64 {
906        match eval(src) {
907            Value::Int(v) => v,
908            other => panic!("{src:?} produced {other:?}"),
909        }
910    }
911
912    fn ints(src: &str) -> Vec<i64> {
913        match eval(src) {
914            Value::List(xs) => xs
915                .iter()
916                .map(|v| match v {
917                    Value::Int(n) => *n,
918                    other => panic!("{src:?} produced a non-Int element {other:?}"),
919                })
920                .collect(),
921            other => panic!("{src:?} produced {other:?}"),
922        }
923    }
924
925    /// **`range` gives the Lisp definition's answers**, arity by arity,
926    /// including the descending form and the empty cases.
927    #[test]
928    fn range_answers_as_the_lisp_definition_did() {
929        assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
930        assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
931        assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
932        assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
933        assert!(ints("range(5, 5)").is_empty());
934        assert!(ints("range(5, 2)").is_empty());
935        assert!(ints("range(0)").is_empty());
936        // A float step makes the elements after the first floats, as `+` did.
937        match eval("range(0, 1, 0.5)") {
938            Value::List(xs) => {
939                assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
940                assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
941                assert_eq!(xs.len(), 2);
942            }
943            other => panic!("{other:?}"),
944        }
945    }
946
947    /// **`range` is a loop, not a recursion.** The Lisp definition consed one
948    /// stack frame per element and aborted the process near 5,000 elements on
949    /// an 8 MiB stack. This runs on the test harness's 2 MiB thread, where the
950    /// Lisp one died sooner still. Red run, 2026-09-24: with the registration
951    /// removed, this test aborted the test binary with a stack overflow.
952    #[test]
953    fn range_builds_long_lists_without_recursing() {
954        assert_eq!(i("length(range(0, 200000))"), 200_000);
955        assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
956    }
957
958    /// A zero step never reaches the end: refused, where the Lisp definition
959    /// recursed until the stack gave out. A non-number is a named error.
960    #[test]
961    fn range_refuses_a_zero_step_and_a_non_number() {
962        assert!(crate::run("range(0, 5, 0)").is_err());
963        assert!(crate::run("range(0, \"x\")").is_err());
964    }
965
966    /// **`length` counts CHARACTERS, as Ruby does — not bytes.** A `length`
967    /// that returns bytes is the bug that only surfaces once a user types a
968    /// non-ASCII character, which is exactly when it is hardest to trace.
969    #[test]
970    fn length_counts_characters_not_bytes() {
971        assert_eq!(i("length(\"hello\")"), 5);
972        // "héllo" is 6 bytes, 5 characters.
973        assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
974        // An emoji is 4 bytes, 1 character.
975        assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
976    }
977
978    /// blue reports **scalar values**, not grapheme clusters. Elixir would say
979    /// 1 here; blue says 2. Stated and pinned rather than left to surprise.
980    #[test]
981    fn a_combining_sequence_counts_scalars_not_graphemes() {
982        // "e" + U+0301 COMBINING ACUTE — one grapheme, two scalars.
983        assert_eq!(
984            i("length(\"e\\u{301}\")"),
985            2,
986            "blue counts scalar values; Elixir's String.length would say 1"
987        );
988    }
989
990    #[test]
991    fn length_also_works_on_a_list() {
992        assert_eq!(i("length([1, 2, 3])"), 3);
993    }
994
995    #[test]
996    fn case_and_trim() {
997        assert_eq!(s("upcase(\"abc\")"), "ABC");
998        assert_eq!(s("downcase(\"ABC\")"), "abc");
999        assert_eq!(s("trim(\"  hi  \")"), "hi");
1000        // Non-ASCII case works, which a byte-wise implementation would botch.
1001        assert_eq!(s("upcase(\"é\")"), "É");
1002    }
1003
1004    #[test]
1005    fn concat_and_to_s() {
1006        assert_eq!(s("concat(\"a\", \"b\")"), "ab");
1007        assert_eq!(s("concat(\"n=\", 42)"), "n=42");
1008        assert_eq!(s("to_s(42)"), "42");
1009        assert_eq!(s("to_s(true)"), "true");
1010    }
1011
1012    /// **`+` stays arithmetic.** Ruby overloads it on String, but blue's `+`
1013    /// lowers to tatara's numeric `+`; making it polymorphic would let a type
1014    /// error at a seam disappear into a string.
1015    #[test]
1016    fn plus_is_not_string_concatenation() {
1017        assert!(
1018            crate::run("\"a\" + \"b\"").is_err(),
1019            "`+` must not silently concatenate — use concat"
1020        );
1021    }
1022
1023    #[test]
1024    fn split_and_join() {
1025        assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
1026        assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
1027        // Ruby's `split("")` yields characters.
1028        assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
1029    }
1030
1031    #[test]
1032    fn predicates() {
1033        assert!(matches!(
1034            eval("contains?(\"hello\", \"ell\")"),
1035            Value::Bool(true)
1036        ));
1037        assert!(matches!(
1038            eval("contains?(\"hello\", \"xyz\")"),
1039            Value::Bool(false)
1040        ));
1041        assert!(matches!(
1042            eval("starts_with?(\"hello\", \"he\")"),
1043            Value::Bool(true)
1044        ));
1045        assert!(matches!(
1046            eval("ends_with?(\"hello\", \"lo\")"),
1047            Value::Bool(true)
1048        ));
1049    }
1050
1051    fn refused(src: &str) -> String {
1052        match crate::run(src) {
1053            Ok(v) => panic!("{src:?} should fail, produced {:?}", v.value),
1054            Err(e) => e.to_string(),
1055        }
1056    }
1057
1058    #[test]
1059    fn trim_without_options_cuts_whitespace_at_both_ends() {
1060        assert_eq!(s("trim(\"  a b \\n\")"), "a b");
1061        assert_eq!(s("trim(\"  a \", nil)"), "a");
1062        assert_eq!(s("trim(\"  a \", {})"), "a");
1063        assert_eq!(s("trim(\"\")"), "");
1064        assert_eq!(s("trim(\"   \")"), "");
1065        assert_eq!(s("trim(\"\", {side: :start})"), "");
1066    }
1067
1068    #[test]
1069    fn trim_side_keeps_the_other_end() {
1070        assert_eq!(s("trim(\"  a  \", {side: :both})"), "a");
1071        assert_eq!(s("trim(\"  a  \", {side: :start})"), "a  ");
1072        assert_eq!(s("trim(\"  a  \", {side: :end})"), "  a");
1073    }
1074
1075    #[test]
1076    fn trim_chars_replaces_whitespace_as_the_set_to_cut() {
1077        assert_eq!(s("trim(\"--a-b--\", {chars: \"-\"})"), "a-b");
1078        assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :start})"), "a+-");
1079        assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :end})"), "-+a");
1080        assert_eq!(s("trim(\" a \", {chars: \"-\"})"), " a ");
1081        assert_eq!(s("trim(\"aaa\", {chars: \"a\"})"), "");
1082        assert_eq!(s("trim(\"héé\", {chars: \"é\", side: :end})"), "h");
1083        assert_eq!(s("trim(\"  a  \", {chars: \"\"})"), "  a  ");
1084    }
1085
1086    #[test]
1087    fn trim_refuses_what_it_does_not_take() {
1088        assert!(refused("trim(\"a\", {sid: :end})").contains("bad_option"));
1089        assert!(refused("trim(\"a\", {sid: :end})").contains("side, chars"));
1090        assert!(refused("trim(\"a\", {side: :middle})").contains("side must be"));
1091        assert!(refused("trim(\"a\", {side: \"end\"})").contains("bad_option"));
1092        assert!(refused("trim(\"a\", {chars: 1})").contains("chars must be text"));
1093        assert!(refused("trim(\"a\", 5)").contains("options must be a map"));
1094        assert!(refused("trim(\"a\", {}, {})").contains("1 to 2"));
1095        assert!(refused("trim()").contains("1 to 2"));
1096        assert!(refused("trim(5)").contains("string"));
1097    }
1098
1099    #[test]
1100    fn trim_is_still_a_value_other_functions_take() {
1101        assert_eq!(s("join(map(trim, [\" a\", \"b \"]), \",\")"), "a,b");
1102    }
1103
1104    #[test]
1105    fn text_index_answers_character_positions() {
1106        assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 0)"), 2);
1107        assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 3)"), 8);
1108        assert_eq!(i("text_index(\"héllo\", \"x\", 0)"), -1);
1109        assert_eq!(i("text_index(\"abc\", \"\", 3)"), 3);
1110        assert_eq!(i("text_index(\"abc\", \"\", 4)"), -1);
1111        assert_eq!(i("text_index(\"abc\", \"a\", -5)"), 0);
1112        assert_eq!(i("text_index(\"\", \"a\", 0)"), -1);
1113    }
1114
1115    #[test]
1116    fn text_last_index_finds_the_last_start_at_or_before_from() {
1117        assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 99)"), 8);
1118        assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 7)"), 2);
1119        assert_eq!(i("text_last_index(\"aaa\", \"aa\", 1)"), 1);
1120        assert_eq!(i("text_last_index(\"aaa\", \"aa\", 0)"), 0);
1121        assert_eq!(i("text_last_index(\"abc\", \"x\", 2)"), -1);
1122        assert_eq!(i("text_last_index(\"abc\", \"a\", -1)"), -1);
1123        assert_eq!(i("text_last_index(\"ab\", \"abc\", 0)"), -1);
1124        assert_eq!(i("text_last_index(\"abc\", \"\", 9)"), 3);
1125    }
1126
1127    #[test]
1128    fn replace_and_chars() {
1129        assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
1130        assert_eq!(i("length(chars(\"abc\"))"), 3);
1131    }
1132
1133    /// Reversed by character, so a multi-byte character survives. A byte-wise
1134    /// reverse produces invalid UTF-8.
1135    #[test]
1136    fn reverse_is_character_wise() {
1137        assert_eq!(s("reverse(\"abc\")"), "cba");
1138        assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
1139    }
1140
1141    #[test]
1142    fn reverse_also_works_on_a_list() {
1143        assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
1144    }
1145
1146    /// **`to_int` answers nil on garbage, not 0.** Ruby's `String#to_i` returns
1147    /// 0, which silently turns a parse failure into a plausible number — a
1148    /// deliberate divergence, and the reason `to_int!` exists for callers who
1149    /// want the failure loudly.
1150    #[test]
1151    fn to_int_is_nil_on_garbage_rather_than_zero() {
1152        assert_eq!(i("to_int(\"42\")"), 42);
1153        assert!(
1154            matches!(eval("to_int(\"banana\")"), Value::Nil),
1155            "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
1156        );
1157        assert!(
1158            matches!(eval("to_int(\"0\")"), Value::Int(0)),
1159            "and a real 0 is still a real 0 — the two must stay distinguishable"
1160        );
1161    }
1162
1163    #[test]
1164    fn to_int_bang_raises_on_garbage() {
1165        assert_eq!(i("to_int!(\"42\")"), 42);
1166        let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
1167        assert!(err.to_string().contains("banana"), "must name it: {err}");
1168    }
1169
1170    #[test]
1171    fn numeric_conversions_and_abs() {
1172        assert_eq!(i("to_int(3.9)"), 3);
1173        assert_eq!(i("abs(0 - 5)"), 5);
1174        assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
1175        assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
1176    }
1177
1178    /// A wrong-typed argument is a typed error, not a silent coercion.
1179    #[test]
1180    fn a_non_string_argument_is_a_type_error() {
1181        assert!(crate::run("upcase([1, 2])").is_err());
1182        assert!(crate::run("join(\"not a list\", \",\")").is_err());
1183    }
1184}