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
38fn as_str(v: &Value, span: tatara_lisp::Span) -> Result<String, EvalError> {
39    match v {
40        Value::Str(s) => Ok(s.to_string()),
41        // A symbol is text the author wrote; accepting it makes `upcase(:ok)`
42        // work the way a Ruby programmer expects of a symbol.
43        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
52/// blue's one equality — what `==`, `!=`, `contains`, `index_of`, `count_of`
53/// and `distinct` all mean (okite D0001–D0003).
54///
55/// Ruby's answer: numbers compare by value across Int and Float (`4 == 4.0`),
56/// strings, symbols and keywords by text (each only with its own kind), lists
57/// element by element, maps by their entries whatever order they were built in,
58/// nil only with nil (not with `[]`, D0004), functions by identity. Until
59/// 2026-09-27 `==` was tatara's Scheme `equal?`, under which `4 == 4.0` was
60/// false and two equal maps were unequal unless they were the same object.
61/// tatara keeps Scheme's `equal?` for its own programs; blue redefines the
62/// name in its interpreter, and tatara's own `member?`, `position` and
63/// `distinct` call `equal?` by name, so they follow.
64pub 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
89/// `to_s` (okite D0005, D0006): text for a person. A string, symbol or keyword
90/// is its own text and nil is empty, as in Ruby; every other value is its blue
91/// literal. Until 2026-09-27 a map rendered as the word `map`, a list lost its
92/// brackets (`[1, {a: 2}]` came out `1 map`) and `1.0` came out `1`.
93fn 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
101/// A value as blue source writes it: `[1, "a", nil]`, `{a: 1, b: 2.0}`.
102/// Map entries are sorted by key, since a map has no order of its own and the
103/// text must be the same for equal maps (D0006).
104fn 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
129/// A map key as it is written before its value: `a:` for a keyword or symbol,
130/// `"a" =>` / `1 =>` for anything else.
131fn 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
143/// A float keeps its point, as in Ruby: `1.0`, `2.5`.
144fn 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
172/// Install blue's string and number core.
173pub fn install_blue_stdlib<H: 'static>(interp: &mut Interpreter<H>) {
174    // ── text ──────────────────────────────────────────────────────────
175
176    // `length` counts CHARACTERS, per Ruby. Also accepts a list, where it is
177    // the element count — Ruby's `Array#length`.
178    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    // The documented builtins, for a program that reasons about names (the
188    // catalogue's "shares a builtin's name" column).
189    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    // `concat(a, …)` joins the text of one or more arguments, left to right
217    // (okite D0007; Ruby's String#concat takes many). Two-only until
218    // 2026-09-27, which made `concat(a, b, c)` an arity error. `+` stays
219    // arithmetic: Ruby overloads `+` on String, but blue's `+` lowers to
220    // tatara's numeric `+`, and making it polymorphic would make a type error
221    // at a seam disappear into a string.
222    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    // ── equality and kinds (okite D0001–D0004, D0010) ─────────────────────
231    //
232    // `==` lowers to `equal?` and `!=` to `not=`; both are redefined here so
233    // blue's interpreter has one equality. See `blue_equal`.
234    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    // One predicate per kind, and exactly one holds of any value (D0010).
242    // tatara's `nil?` is its Scheme alias for `null?`, true of `[]` as well,
243    // and its `list?` is true of nil; blue's nil is absent and `[]` is an empty
244    // list (D0004), so blue redefines both. tatara's own library ends its
245    // recursion with `null?`, which is untouched.
246    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    // The empty list is always `[]`, never nil (D0011). tatara's `cdr` (and so
263    // `rest`, which is `cdr`) and `append` returned nil for an empty result,
264    // Scheme's convention, which under D0004 made `rest([1]) == []` false.
265    // Same contracts otherwise: `cdr` of an empty list is still an error.
266    interp.register_fn("cdr", Arity::Exact(1), |a: &[Value], _h: &mut H, span| {
267        match &a[0] {
268            // Shares the tail's structure: O(log n), not a copy of it.
269            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        // Persistent concatenation: each operand's structure is shared, so
280        // building a list by `append(acc, [x])` is linear overall, not
281        // quadratic (G7). The arguments arrive by value, so an accumulator
282        // the caller holds alone (tatara-lisp-eval runs a tail call to an
283        // owned primitive after releasing the caller's frame) is extended in
284        // its own allocation by `Arc::make_mut` instead of copied at the tail.
285        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        // An empty separator splits into characters, as Ruby's `split("")`
313        // does. Rust's `split("")` yields leading/trailing empties instead,
314        // which is the wrong answer here.
315        // Every field is kept: n separators give n + 1 fields, so `join` undoes
316        // `split` exactly (okite D0012). A deliberate deviation from Ruby, which
317        // drops trailing empty fields: tried on 2026-09-27, it broke nisshi's
318        // hash chain, kueri's scripts and moji's `lines`, because a parser whose
319        // split loses a field loses data and still reports success.
320        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(
374        "text_index",
375        Arity::Exact(3),
376        |a: &[Value], _h: &mut H, s| {
377            Ok(Value::Int(text_index(
378                &as_str(&a[0], s)?,
379                &as_str(&a[1], s)?,
380                as_index(&a[2], s)?,
381            )))
382        },
383    );
384
385    interp.register_fn(
386        "text_last_index",
387        Arity::Exact(3),
388        |a: &[Value], _h: &mut H, s| {
389            Ok(Value::Int(text_last_index(
390                &as_str(&a[0], s)?,
391                &as_str(&a[1], s)?,
392                as_index(&a[2], s)?,
393            )))
394        },
395    );
396
397    interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
398        Ok(Value::Str(
399            as_str(&a[0], s)?
400                .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
401                .into(),
402        ))
403    });
404
405    interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
406        match &a[0] {
407            Value::List(items) => Ok(Value::list(items.iter().rev().cloned())),
408            // Reversed by CHARACTER, so a multi-byte character survives. A
409            // byte-wise reverse produces invalid UTF-8.
410            other => Ok(Value::Str(
411                as_str(other, s)?.chars().rev().collect::<String>().into(),
412            )),
413        }
414    });
415
416    interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
417        Ok(list(
418            as_str(&a[0], s)?
419                .chars()
420                .map(|c| Value::Str(c.to_string().into()))
421                .collect(),
422        ))
423    });
424
425    // ── numbers ───────────────────────────────────────────────────────
426
427    // `to_int` RETURNS NIL on unparseable input rather than raising. Ruby's
428    // `String#to_i` answers 0 for garbage, which silently turns a parse failure
429    // into a plausible number; nil is falsy and cannot be mistaken for a
430    // result. `to_int!` is the raising form for callers who want the failure.
431    interp.register_fn(
432        "to_int",
433        Arity::Exact(1),
434        |a: &[Value], _h: &mut H, s| match &a[0] {
435            Value::Int(n) => Ok(Value::Int(*n)),
436            // A float with no Int (non-finite, or past i64) is nil like any
437            // other unconvertible input; `as i64` saturated it to a plausible
438            // wrong number.
439            Value::Float(x) => Ok(float_to_int(*x).map_or(Value::Nil, Value::Int)),
440            other => Ok(as_str(other, s)?
441                .trim()
442                .parse::<i64>()
443                .map_or(Value::Nil, Value::Int)),
444        },
445    );
446
447    interp.register_fn(
448        "to_int!",
449        Arity::Exact(1),
450        |a: &[Value], _h: &mut H, s| match &a[0] {
451            Value::Int(n) => Ok(Value::Int(*n)),
452            Value::Float(x) => float_to_int(*x)
453                .map(Value::Int)
454                .ok_or(EvalError::IntegerOverflow {
455                    op: "to_int!",
456                    at: s,
457                }),
458            other => {
459                let text = as_str(other, s)?;
460                text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
461                    EvalError::native_fn(
462                        "to_int!",
463                        "`".to_string() + &text + "` is not an integer",
464                        s,
465                    )
466                    .into()
467                })
468            }
469        },
470    );
471
472    interp.register_fn(
473        "to_float",
474        Arity::Exact(1),
475        |a: &[Value], _h: &mut H, s| match &a[0] {
476            Value::Float(x) => Ok(Value::Float(*x)),
477            Value::Int(n) => Ok(Value::Float(*n as f64)),
478            other => Ok(as_str(other, s)?
479                .trim()
480                .parse::<f64>()
481                .map_or(Value::Nil, Value::Float)),
482        },
483    );
484
485    interp.register_fn(
486        "abs",
487        Arity::Exact(1),
488        |a: &[Value], _h: &mut H, s| match &a[0] {
489            // Checked, as tatara's `abs` is (G5): |i64::MIN| does not fit, and
490            // `n.abs()` wrapped in release and panicked in debug.
491            Value::Int(n) => n
492                .checked_abs()
493                .map(Value::Int)
494                .ok_or(EvalError::IntegerOverflow { op: "abs", at: s }),
495            Value::Float(x) => Ok(Value::Float(x.abs())),
496            other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
497        },
498    );
499
500    // ── ranges ────────────────────────────────────────────────────────
501
502    // `range` is a LOOP here, not a recursion. tatara-lisp's stdlib defines it
503    // in Lisp (`lisp_stdlib.tlisp`, where `range-impl` conses one frame per
504    // element), so `range(0, 5000)` overflowed the 8 MiB main stack and
505    // aborted the process. Everything built on it inherited the ceiling:
506    // retsu's `indexes`, `zip_with` and `enumerate`, and shomei's
507    // `chain_first_break`, which could not verify a 5,000-entry chain
508    // (measured 2026-09-24: 4,000 elements fine, 5,000 aborted).
509    //
510    // Same arities and answers as the Lisp definition: (end), (start, end),
511    // (start, end, step), ascending for a positive step, descending for a
512    // negative one, and each next element is the previous plus the step under
513    // the ordinary number rules (Int + Int is Int; a Float anywhere makes the
514    // rest Float). Two refusals the Lisp version lacked: a zero step, which
515    // recursed forever, and a wrong arity, which printed a message and
516    // returned nil.
517    //
518    // The destination is upstream: when tatara-lisp's own `range` is a loop,
519    // this registration is deleted.
520    interp.register_fn("range", Arity::Range(1, 3), |a: &[Value], _h: &mut H, s| {
521        let (start, end, step) = match a.len() {
522            1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
523            2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
524            _ => (a[0].clone(), a[1].clone(), a[2].clone()),
525        };
526        range_list(start, &end, &step, s)
527    });
528
529    // `write_stdout(s)` / `write_stderr(s)`: the text exactly, no quotes, no
530    // newline added. `print`, `println` and `display` all render a string
531    // with its quotes (a value printer, right for a REPL and wrong for a
532    // command's output), so until these a blue command-line tool could not
533    // print plain text. Output only, like `println`; anything else is not a
534    // string and is refused.
535    interp.register_fn(
536        "write_stdout",
537        Arity::Exact(1),
538        |a: &[Value], _h: &mut H, s| {
539            use std::io::Write;
540            let text = as_str(&a[0], s)?;
541            let mut out = std::io::stdout().lock();
542            out.write_all(text.as_bytes())
543                .and_then(|()| out.flush())
544                .map_err(|e| EvalError::native_fn("write_stdout", e.to_string(), s))?;
545            Ok(Value::Nil)
546        },
547    );
548    interp.register_fn(
549        "write_stderr",
550        Arity::Exact(1),
551        |a: &[Value], _h: &mut H, s| {
552            use std::io::Write;
553            let text = as_str(&a[0], s)?;
554            let mut err = std::io::stderr().lock();
555            err.write_all(text.as_bytes())
556                .and_then(|()| err.flush())
557                .map_err(|e| EvalError::native_fn("write_stderr", e.to_string(), s))?;
558            Ok(Value::Nil)
559        },
560    );
561
562    // `sort_keyed(key, xs)`: xs ordered by key(x), stably, in O(n log n),
563    // under `compare`'s rules. Every sort written in blue (junjo's) recurses
564    // per element and aborts the process near 600 elements; this is
565    // tatara-lisp's `sort-by-key` (0.3.60), which blue cannot name because
566    // it is kebab-case, bound to a name blue can. The engine is upstream,
567    // `hof::sort_keyed_values`; only the spelling lives here.
568    interp.register_higher_order_fn(
569        "sort_keyed",
570        Arity::Exact(2),
571        |a: &[Value], host: &mut H, caller: &tatara_lisp_eval::ffi::Caller<H>, s| {
572            let xs = match &a[1] {
573                Value::List(xs) => xs.to_vec(),
574                Value::Nil => Vec::new(),
575                other => {
576                    return Err(EvalError::type_mismatch("a list", other.type_name(), s));
577                }
578            };
579            let mut keyed = Vec::with_capacity(xs.len());
580            for x in xs {
581                keyed.push((caller.apply_value(&a[0], vec![x.clone()], host, s)?, x));
582            }
583            Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
584        },
585    );
586
587    interp.register_fn(
588        "error_message",
589        Arity::Exact(1),
590        |a: &[Value], _h: &mut H, s| match &a[0] {
591            Value::Error(e) => Ok(Value::Str(e.message.clone())),
592            other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
593        },
594    );
595
596    interp.register_fn(
597        "error_kind",
598        Arity::Exact(1),
599        |a: &[Value], _h: &mut H, s| match &a[0] {
600            Value::Error(e) => Ok(Value::Keyword(e.tag.clone())),
601            other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
602        },
603    );
604
605    interp.register_fn(
606        "map_entries",
607        Arity::Exact(1),
608        |a: &[Value], _h: &mut H, s| match &a[0] {
609            Value::Map(m) => {
610                let keyed = m
611                    .iter()
612                    .map(|(k, v)| (k.to_value(), list(vec![k.to_value(), v.clone()])))
613                    .collect();
614                Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
615            }
616            Value::Nil => Ok(list(Vec::new())),
617            other => Err(EvalError::type_mismatch("a map", other.type_name(), s)),
618        },
619    );
620}
621
622fn as_index(v: &Value, span: tatara_lisp::Span) -> Result<i64, EvalError> {
623    match v {
624        Value::Int(n) => Ok(*n),
625        other => Err(EvalError::type_mismatch(
626            "an integer",
627            other.type_name(),
628            span,
629        )),
630    }
631}
632
633fn text_index(text: &str, sub: &str, from: i64) -> i64 {
634    let from = usize::try_from(from.max(0)).unwrap_or(usize::MAX);
635    let start = match text.char_indices().nth(from) {
636        Some((b, _)) => b,
637        None if text.chars().count() == from => text.len(),
638        None => return -1,
639    };
640    text[start..].find(sub).map_or(-1, |b| {
641        i64::try_from(from + text[start..start + b].chars().count()).unwrap_or(i64::MAX)
642    })
643}
644
645fn text_last_index(text: &str, sub: &str, from: i64) -> i64 {
646    let Ok(from) = usize::try_from(from) else {
647        return -1;
648    };
649    let total = text.chars().count();
650    let width = sub.chars().count();
651    if width > total {
652        return -1;
653    }
654    let limit = from.min(total - width);
655    let end = text
656        .char_indices()
657        .nth(limit + width)
658        .map_or(text.len(), |(b, _)| b);
659    text[..end].rfind(sub).map_or(-1, |b| {
660        i64::try_from(text[..b].chars().count()).unwrap_or(i64::MAX)
661    })
662}
663
664/// A number's value as a float, or a type error naming `range`.
665fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
666    match v {
667        Value::Int(n) => Ok(*n as f64),
668        Value::Float(x) => Ok(*x),
669        other => Err(EvalError::native_fn(
670            "range",
671            "expected a number, got ".to_string() + other.type_name(),
672            s,
673        )),
674    }
675}
676
677/// A float's integer part as an `i64`, or `None` when it is not finite or
678/// does not fit. `as i64` saturates instead.
679fn float_to_int(x: f64) -> Option<i64> {
680    const LIMIT: f64 = 9_223_372_036_854_775_808.0;
681    let t = x.trunc();
682    #[allow(clippy::cast_possible_truncation)]
683    (t.is_finite() && (-LIMIT..LIMIT).contains(&t)).then(|| t as i64)
684}
685
686/// `a + b` under the number rules the Lisp `range` used: Int + Int stays Int,
687/// anything with a Float is Float.
688fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
689    match (a, b) {
690        (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
691            EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
692        }),
693        _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
694    }
695}
696
697fn range_list(
698    start: Value,
699    end: &Value,
700    step: &Value,
701    s: tatara_lisp::Span,
702) -> Result<Value, EvalError> {
703    let end_f = range_num(end, s)?;
704    let step_f = range_num(step, s)?;
705    range_num(&start, s)?;
706    if step_f == 0.0 {
707        return Err(EvalError::native_fn(
708            "range",
709            "a step of zero never reaches the end",
710            s,
711        ));
712    }
713    let mut out = Vec::new();
714    let mut cur = start;
715    loop {
716        let c = range_num(&cur, s)?;
717        if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
718            break;
719        }
720        let next = range_add(&cur, step, s)?;
721        out.push(cur);
722        cur = next;
723    }
724    Ok(list(out))
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn sort_keyed_is_stable_keyed_and_deep() {
733        // Ties keep input order; the key is computed per element.
734        assert_eq!(
735            ints("map(fn(p) last(p) end, sort_keyed(fn(p) first(p) end, [[2, 1], [1, 2], [2, 3], [1, 4]]))"),
736            vec![2, 4, 1, 3]
737        );
738        // 20,000 in reverse: every blue-written sort aborts far below this.
739        assert_eq!(
740            i("first(sort_keyed(fn(x) x end, reverse(range(0, 20000))))"),
741            0
742        );
743        assert_eq!(i("last(sort_keyed(fn(x) 0 - x end, range(0, 20000)))"), 0);
744        // The empty case, and a refusal for keys that cannot be ordered.
745        assert_eq!(ints("sort_keyed(fn(x) x end, [])"), Vec::<i64>::new());
746        assert!(crate::run("sort_keyed(fn(x) x end, [1, \"a\"])").is_err());
747    }
748
749    fn eval(src: &str) -> Value {
750        crate::run(src)
751            .unwrap_or_else(|e| panic!("{src:?}: {e}"))
752            .value
753    }
754
755    fn s(src: &str) -> String {
756        match eval(src) {
757            Value::Str(v) => v.to_string(),
758            other => panic!("{src:?} produced {other:?}"),
759        }
760    }
761
762    fn i(src: &str) -> i64 {
763        match eval(src) {
764            Value::Int(v) => v,
765            other => panic!("{src:?} produced {other:?}"),
766        }
767    }
768
769    fn ints(src: &str) -> Vec<i64> {
770        match eval(src) {
771            Value::List(xs) => xs
772                .iter()
773                .map(|v| match v {
774                    Value::Int(n) => *n,
775                    other => panic!("{src:?} produced a non-Int element {other:?}"),
776                })
777                .collect(),
778            other => panic!("{src:?} produced {other:?}"),
779        }
780    }
781
782    /// **`range` gives the Lisp definition's answers**, arity by arity,
783    /// including the descending form and the empty cases.
784    #[test]
785    fn range_answers_as_the_lisp_definition_did() {
786        assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
787        assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
788        assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
789        assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
790        assert!(ints("range(5, 5)").is_empty());
791        assert!(ints("range(5, 2)").is_empty());
792        assert!(ints("range(0)").is_empty());
793        // A float step makes the elements after the first floats, as `+` did.
794        match eval("range(0, 1, 0.5)") {
795            Value::List(xs) => {
796                assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
797                assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
798                assert_eq!(xs.len(), 2);
799            }
800            other => panic!("{other:?}"),
801        }
802    }
803
804    /// **`range` is a loop, not a recursion.** The Lisp definition consed one
805    /// stack frame per element and aborted the process near 5,000 elements on
806    /// an 8 MiB stack. This runs on the test harness's 2 MiB thread, where the
807    /// Lisp one died sooner still. Red run, 2026-09-24: with the registration
808    /// removed, this test aborted the test binary with a stack overflow.
809    #[test]
810    fn range_builds_long_lists_without_recursing() {
811        assert_eq!(i("length(range(0, 200000))"), 200_000);
812        assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
813    }
814
815    /// A zero step never reaches the end: refused, where the Lisp definition
816    /// recursed until the stack gave out. A non-number is a named error.
817    #[test]
818    fn range_refuses_a_zero_step_and_a_non_number() {
819        assert!(crate::run("range(0, 5, 0)").is_err());
820        assert!(crate::run("range(0, \"x\")").is_err());
821    }
822
823    /// **`length` counts CHARACTERS, as Ruby does — not bytes.** A `length`
824    /// that returns bytes is the bug that only surfaces once a user types a
825    /// non-ASCII character, which is exactly when it is hardest to trace.
826    #[test]
827    fn length_counts_characters_not_bytes() {
828        assert_eq!(i("length(\"hello\")"), 5);
829        // "héllo" is 6 bytes, 5 characters.
830        assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
831        // An emoji is 4 bytes, 1 character.
832        assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
833    }
834
835    /// blue reports **scalar values**, not grapheme clusters. Elixir would say
836    /// 1 here; blue says 2. Stated and pinned rather than left to surprise.
837    #[test]
838    fn a_combining_sequence_counts_scalars_not_graphemes() {
839        // "e" + U+0301 COMBINING ACUTE — one grapheme, two scalars.
840        assert_eq!(
841            i("length(\"e\\u{301}\")"),
842            2,
843            "blue counts scalar values; Elixir's String.length would say 1"
844        );
845    }
846
847    #[test]
848    fn length_also_works_on_a_list() {
849        assert_eq!(i("length([1, 2, 3])"), 3);
850    }
851
852    #[test]
853    fn case_and_trim() {
854        assert_eq!(s("upcase(\"abc\")"), "ABC");
855        assert_eq!(s("downcase(\"ABC\")"), "abc");
856        assert_eq!(s("trim(\"  hi  \")"), "hi");
857        // Non-ASCII case works, which a byte-wise implementation would botch.
858        assert_eq!(s("upcase(\"é\")"), "É");
859    }
860
861    #[test]
862    fn concat_and_to_s() {
863        assert_eq!(s("concat(\"a\", \"b\")"), "ab");
864        assert_eq!(s("concat(\"n=\", 42)"), "n=42");
865        assert_eq!(s("to_s(42)"), "42");
866        assert_eq!(s("to_s(true)"), "true");
867    }
868
869    /// **`+` stays arithmetic.** Ruby overloads it on String, but blue's `+`
870    /// lowers to tatara's numeric `+`; making it polymorphic would let a type
871    /// error at a seam disappear into a string.
872    #[test]
873    fn plus_is_not_string_concatenation() {
874        assert!(
875            crate::run("\"a\" + \"b\"").is_err(),
876            "`+` must not silently concatenate — use concat"
877        );
878    }
879
880    #[test]
881    fn split_and_join() {
882        assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
883        assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
884        // Ruby's `split("")` yields characters.
885        assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
886    }
887
888    #[test]
889    fn predicates() {
890        assert!(matches!(
891            eval("contains?(\"hello\", \"ell\")"),
892            Value::Bool(true)
893        ));
894        assert!(matches!(
895            eval("contains?(\"hello\", \"xyz\")"),
896            Value::Bool(false)
897        ));
898        assert!(matches!(
899            eval("starts_with?(\"hello\", \"he\")"),
900            Value::Bool(true)
901        ));
902        assert!(matches!(
903            eval("ends_with?(\"hello\", \"lo\")"),
904            Value::Bool(true)
905        ));
906    }
907
908    #[test]
909    fn text_index_answers_character_positions() {
910        assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 0)"), 2);
911        assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 3)"), 8);
912        assert_eq!(i("text_index(\"héllo\", \"x\", 0)"), -1);
913        assert_eq!(i("text_index(\"abc\", \"\", 3)"), 3);
914        assert_eq!(i("text_index(\"abc\", \"\", 4)"), -1);
915        assert_eq!(i("text_index(\"abc\", \"a\", -5)"), 0);
916        assert_eq!(i("text_index(\"\", \"a\", 0)"), -1);
917    }
918
919    #[test]
920    fn text_last_index_finds_the_last_start_at_or_before_from() {
921        assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 99)"), 8);
922        assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 7)"), 2);
923        assert_eq!(i("text_last_index(\"aaa\", \"aa\", 1)"), 1);
924        assert_eq!(i("text_last_index(\"aaa\", \"aa\", 0)"), 0);
925        assert_eq!(i("text_last_index(\"abc\", \"x\", 2)"), -1);
926        assert_eq!(i("text_last_index(\"abc\", \"a\", -1)"), -1);
927        assert_eq!(i("text_last_index(\"ab\", \"abc\", 0)"), -1);
928        assert_eq!(i("text_last_index(\"abc\", \"\", 9)"), 3);
929    }
930
931    #[test]
932    fn replace_and_chars() {
933        assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
934        assert_eq!(i("length(chars(\"abc\"))"), 3);
935    }
936
937    /// Reversed by character, so a multi-byte character survives. A byte-wise
938    /// reverse produces invalid UTF-8.
939    #[test]
940    fn reverse_is_character_wise() {
941        assert_eq!(s("reverse(\"abc\")"), "cba");
942        assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
943    }
944
945    #[test]
946    fn reverse_also_works_on_a_list() {
947        assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
948    }
949
950    /// **`to_int` answers nil on garbage, not 0.** Ruby's `String#to_i` returns
951    /// 0, which silently turns a parse failure into a plausible number — a
952    /// deliberate divergence, and the reason `to_int!` exists for callers who
953    /// want the failure loudly.
954    #[test]
955    fn to_int_is_nil_on_garbage_rather_than_zero() {
956        assert_eq!(i("to_int(\"42\")"), 42);
957        assert!(
958            matches!(eval("to_int(\"banana\")"), Value::Nil),
959            "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
960        );
961        assert!(
962            matches!(eval("to_int(\"0\")"), Value::Int(0)),
963            "and a real 0 is still a real 0 — the two must stay distinguishable"
964        );
965    }
966
967    #[test]
968    fn to_int_bang_raises_on_garbage() {
969        assert_eq!(i("to_int!(\"42\")"), 42);
970        let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
971        assert!(err.to_string().contains("banana"), "must name it: {err}");
972    }
973
974    #[test]
975    fn numeric_conversions_and_abs() {
976        assert_eq!(i("to_int(3.9)"), 3);
977        assert_eq!(i("abs(0 - 5)"), 5);
978        assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
979        assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
980    }
981
982    /// A wrong-typed argument is a typed error, not a silent coercion.
983    #[test]
984    fn a_non_string_argument_is_a_type_error() {
985        assert!(crate::run("upcase([1, 2])").is_err());
986        assert!(crate::run("join(\"not a list\", \",\")").is_err());
987    }
988}