1use 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 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
102pub 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#[derive(PartialEq, Eq, Hash)]
140enum EqualKey<'a> {
141 Nil,
142 Bool(bool),
143 Number(u64),
144 Str(&'a str),
145 Symbol(&'a str),
146 Keyword(&'a str),
147}
148
149fn number_key(n: f64) -> Option<EqualKey<'static>> {
150 (!n.is_nan()).then(|| EqualKey::Number(if n == 0.0 { 0 } else { n.to_bits() }))
151}
152
153fn equal_key(v: &Value) -> Option<EqualKey<'_>> {
154 match v {
155 Value::Nil => Some(EqualKey::Nil),
156 Value::Bool(b) => Some(EqualKey::Bool(*b)),
157 Value::Int(i) => number_key(*i as f64),
158 Value::Float(f) => number_key(*f),
159 Value::Str(s) => Some(EqualKey::Str(s)),
160 Value::Symbol(s) => Some(EqualKey::Symbol(s)),
161 Value::Keyword(s) => Some(EqualKey::Keyword(s)),
162 _ => None,
163 }
164}
165
166pub fn frequencies<'a>(
174 xs: impl Iterator<Item = &'a Value>,
175 span: tatara_lisp::Span,
176) -> Result<Value, EvalError> {
177 let mut counts = tatara_lisp_eval::Map::new();
178 for x in xs {
179 let key = tatara_lisp_eval::value::MapKey::from_value(x).ok_or_else(|| {
180 EvalError::native_fn(
181 "hash-map",
182 format!("non-hashable key kind: {}", x.type_name()),
183 span,
184 )
185 })?;
186 let n = match counts.get(&key) {
187 Some(Value::Int(n)) => n + 1,
188 _ => 1,
189 };
190 counts.insert(key, Value::Int(n));
191 }
192 Ok(Value::Map(std::sync::Arc::new(counts)))
193}
194
195pub fn distinct<'a>(xs: impl Iterator<Item = &'a Value>) -> Vec<Value> {
202 let mut kept: Vec<Value> = Vec::new();
203 let mut buckets: std::collections::HashMap<EqualKey<'a>, Vec<usize>> =
204 std::collections::HashMap::new();
205 let mut keyless: Vec<usize> = Vec::new();
206 for x in xs {
207 let seen = match equal_key(x) {
208 Some(k) => buckets.entry(k).or_default(),
209 None => &mut keyless,
210 };
211 if !seen.iter().any(|&i| blue_equal(&kept[i], x)) {
212 seen.push(kept.len());
213 kept.push(x.clone());
214 }
215 }
216 kept
217}
218
219fn chain_rules_value() -> Value {
224 use blue_lang_check::chains::{cases, Case, Kind, RULES};
225 let sym = |s: &str| Value::Symbol(std::sync::Arc::from(s));
226 let text = |s: &str| Value::Str(std::sync::Arc::from(s));
227 let hole = |n: usize| (0..n).map(|_| sym("x")).collect::<Vec<_>>();
228 let lambda = |body: Value| Value::list([sym("lambda"), Value::list([sym("x")]), body]);
229 let call = |name: &str, args: Vec<Value>| Value::list(std::iter::once(sym(name)).chain(args));
230 Value::list(RULES.iter().map(|rule| {
231 let rows = cases(rule).into_iter().map(|case| match case {
232 Case::Call { inner, argc } => {
233 let inner_call = call(inner, hole(argc));
234 Value::list([
235 text(&format!("{}({}(x))", rule.outer, inner)),
236 Value::Nil,
237 lambda(call(rule.outer, vec![inner_call.clone()])),
238 lambda(inner_call),
239 ])
240 }
241 Case::Literal(kind) => Value::list([
242 text(&format!("{}(<literal>)", rule.outer)),
243 Value::Keyword(std::sync::Arc::from(match kind {
244 Kind::Text => "text",
245 Kind::Int => "int",
246 Kind::Float => "float",
247 })),
248 lambda(call(rule.outer, vec![sym("x")])),
249 lambda(sym("x")),
250 ]),
251 });
252 Value::list([
253 text(rule.id),
254 text(rule.slug),
255 text(rule.outer),
256 text(rule.soundness),
257 Value::list(rows),
258 ])
259 }))
260}
261
262fn render(v: &Value) -> String {
263 match v {
264 Value::Nil => String::new(),
265 Value::Str(s) | Value::Symbol(s) | Value::Keyword(s) => s.to_string(),
266 Value::Error(e) => crate::errors::describe(e),
267 other => literal(other),
268 }
269}
270
271fn literal(v: &Value) -> String {
275 match v {
276 Value::Nil => "nil".into(),
277 Value::Bool(b) => b.to_string(),
278 Value::Int(n) => n.to_string(),
279 Value::Float(x) => float_text(*x),
280 Value::Str(s) => quoted(s),
281 Value::Symbol(s) => s.to_string(),
282 Value::Keyword(s) => format!(":{s}"),
283 Value::List(items) => {
284 let parts: Vec<String> = items.iter().map(literal).collect();
285 format!("[{}]", parts.join(", "))
286 }
287 Value::Map(m) => {
288 let mut entries: Vec<String> = m
289 .iter()
290 .map(|(k, v)| format!("{} {}", key_text(k), literal(v)))
291 .collect();
292 entries.sort();
293 format!("{{{}}}", entries.join(", "))
294 }
295 other => other.type_name().to_string(),
296 }
297}
298
299fn key_text(k: &tatara_lisp_eval::value::MapKey) -> String {
302 use tatara_lisp_eval::value::MapKey;
303 match k {
304 MapKey::Keyword(s) | MapKey::Symbol(s) => format!("{s}:"),
305 MapKey::Str(s) => format!("{} =>", quoted(s)),
306 MapKey::Int(n) => format!("{n} =>"),
307 MapKey::Float(bits) => format!("{} =>", float_text(f64::from_bits(*bits))),
308 MapKey::Bool(b) => format!("{b} =>"),
309 MapKey::Nil => "nil =>".into(),
310 }
311}
312
313fn float_text(x: f64) -> String {
315 if x.is_finite() && x.fract() == 0.0 && x.abs() < 1e16 {
316 format!("{x:.1}")
317 } else {
318 format!("{x}")
319 }
320}
321
322fn quoted(s: &str) -> String {
323 let mut out = String::with_capacity(s.len() + 2);
324 out.push('"');
325 for c in s.chars() {
326 match c {
327 '"' => out.push_str("\\\""),
328 '\\' => out.push_str("\\\\"),
329 '\n' => out.push_str("\\n"),
330 '\t' => out.push_str("\\t"),
331 c => out.push(c),
332 }
333 }
334 out.push('"');
335 out
336}
337
338fn list(items: Vec<Value>) -> Value {
339 Value::list(items)
340}
341
342pub fn install_blue_stdlib<H: 'static>(interp: &mut Interpreter<H>) {
344 crate::errors::install(interp);
345 crate::paths::install(interp);
346 crate::spread::install(interp);
347 crate::collection::install(interp);
348 interp.register_fn(
353 "length",
354 Arity::Exact(1),
355 |a: &[Value], _h: &mut H, span| match &a[0] {
356 Value::List(items) => Ok(Value::Int(items.len() as i64)),
357 other => Ok(Value::Int(as_str(other, span)?.chars().count() as i64)),
358 },
359 );
360
361 interp.register_fn(
364 "builtin_names",
365 Arity::Exact(0),
366 |_a: &[Value], _h: &mut H, _s| {
367 Ok(Value::list(
368 crate::docs::NAMES
369 .iter()
370 .map(|n| Value::Str(std::sync::Arc::from(n.name))),
371 ))
372 },
373 );
374 interp.register_fn(
375 "chain_rules",
376 Arity::Exact(0),
377 |_a: &[Value], _h: &mut H, _s| Ok(chain_rules_value()),
378 );
379 interp.register_fn("to_s", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
380 Ok(Value::Str(render(&a[0]).into()))
381 });
382
383 interp.register_fn("upcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
384 Ok(Value::Str(as_str(&a[0], s)?.to_uppercase().into()))
385 });
386
387 interp.register_fn("downcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
388 Ok(Value::Str(as_str(&a[0], s)?.to_lowercase().into()))
389 });
390
391 interp.register_fn("trim", Arity::Range(1, 2), |a: &[Value], _h: &mut H, s| {
392 let text = as_str(&a[0], s)?;
393 trim_with(&text, a.get(1).unwrap_or(&Value::Nil), s)
394 });
395
396 interp.register_fn(
397 blue_lang_syntax::LOWERED_OPTIONAL_ARITY,
398 Arity::Exact(4),
399 |a: &[Value], _h: &mut H, s| {
400 let name = as_str(&a[0], s)?;
401 let (Value::List(rest), Value::Int(required), Value::Int(most)) = (&a[1], &a[2], &a[3])
402 else {
403 return Err(EvalError::native_fn(
404 blue_lang_syntax::LOWERED_OPTIONAL_ARITY,
405 "expects a name, the rest list and two counts",
406 s,
407 ));
408 };
409 if rest.len() as i64 > *most {
410 let want = Arity::Range(*required as usize, (*required + *most) as usize);
411 return Err(EvalError::native_fn(
412 name.as_str(),
413 format!(
414 "takes {}, got {}",
415 crate::messages::arguments(&want),
416 *required as usize + rest.len()
417 ),
418 s,
419 ));
420 }
421 Ok(Value::Nil)
422 },
423 );
424
425 interp.register_fn(
426 blue_lang_syntax::LOWERED_OPTIONAL_ARG,
427 Arity::Exact(2),
428 |a: &[Value], _h: &mut H, s| match (&a[0], &a[1]) {
429 (Value::List(rest), Value::Int(i)) => {
430 Ok(rest.get(*i as usize).cloned().unwrap_or(Value::Nil))
431 }
432 _ => Err(EvalError::native_fn(
433 blue_lang_syntax::LOWERED_OPTIONAL_ARG,
434 "expects the rest list and an index",
435 s,
436 )),
437 },
438 );
439
440 interp.register_fn(
447 "concat",
448 Arity::AtLeast(1),
449 |a: &[Value], _h: &mut H, _s| {
450 Ok(Value::Str(a.iter().map(render).collect::<String>().into()))
451 },
452 );
453
454 interp.register_fn("equal?", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
459 Ok(Value::Bool(blue_equal(&a[0], &a[1])))
460 });
461 interp.register_fn("not=", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
462 Ok(Value::Bool(!blue_equal(&a[0], &a[1])))
463 });
464 interp.register_fn(
465 "distinct",
466 Arity::Exact(1),
467 |a: &[Value], _h: &mut H, span| match &a[0] {
468 Value::Nil => Ok(Value::list(std::iter::empty())),
469 Value::List(xs) => Ok(Value::list(distinct(xs.iter()))),
470 other => Err(EvalError::type_mismatch("a list", other.type_name(), span)),
471 },
472 );
473 interp.register_fn(
474 "frequencies",
475 Arity::Exact(1),
476 |a: &[Value], _h: &mut H, span| match &a[0] {
477 Value::Nil => Ok(frequencies(std::iter::empty(), span)?),
478 Value::List(xs) => Ok(frequencies(xs.iter(), span)?),
479 other => Err(EvalError::type_mismatch("a list", other.type_name(), span)),
480 },
481 );
482
483 interp.register_fn("nil?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
489 Ok(Value::Bool(matches!(a[0], Value::Nil)))
490 });
491 interp.register_fn("list?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
492 Ok(Value::Bool(matches!(a[0], Value::List(_))))
493 });
494 interp.register_fn("map?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
495 Ok(Value::Bool(matches!(a[0], Value::Map(_))))
496 });
497 interp.register_fn("float?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
498 Ok(Value::Bool(matches!(a[0], Value::Float(_))))
499 });
500 interp.register_fn("bool?", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
501 Ok(Value::Bool(matches!(a[0], Value::Bool(_))))
502 });
503
504 interp.register_fn("cdr", Arity::Exact(1), |a: &[Value], _h: &mut H, span| {
509 match &a[0] {
510 Value::List(xs) if !xs.is_empty() => Ok(Value::List(std::sync::Arc::new(xs.skip(1)))),
512 Value::Nil | Value::List(_) => Err(EvalError::native_fn(
513 std::sync::Arc::<str>::from("cdr"),
514 "cdr of empty list",
515 span,
516 )),
517 other => Err(EvalError::type_mismatch("pair", other.type_name(), span)),
518 }
519 });
520 interp.register_owned_fn("append", Arity::Any, |a: Vec<Value>, _h: &mut H, span| {
521 let mut lists = Vec::with_capacity(a.len());
528 for v in a {
529 match v {
530 Value::Nil => {}
531 Value::List(xs) => lists.push(xs),
532 other => return Err(EvalError::type_mismatch("list", other.type_name(), span)),
533 }
534 }
535 let mut lists = lists.into_iter();
536 let Some(mut out) = lists.next() else {
537 return Ok(Value::List(std::sync::Arc::new(
538 tatara_lisp_eval::List::new(),
539 )));
540 };
541 let acc = std::sync::Arc::make_mut(&mut out);
542 for xs in lists {
543 acc.append(
544 std::sync::Arc::try_unwrap(xs)
545 .unwrap_or_else(|shared| tatara_lisp_eval::List::clone(&shared)),
546 );
547 }
548 Ok(Value::List(out))
549 });
550
551 interp.register_fn("split", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
552 let text = as_str(&a[0], s)?;
553 let sep = as_str(&a[1], s)?;
554 let parts: Vec<Value> = if sep.is_empty() {
563 text.chars()
564 .map(|c| Value::Str(c.to_string().into()))
565 .collect()
566 } else {
567 text.split(sep.as_str())
568 .map(|p| Value::Str(p.into()))
569 .collect()
570 };
571 Ok(list(parts))
572 });
573
574 interp.register_fn("join", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
575 let sep = as_str(&a[1], s)?;
576 match &a[0] {
577 Value::List(items) => Ok(Value::Str(
578 items
579 .iter()
580 .map(render)
581 .collect::<Vec<_>>()
582 .join(&sep)
583 .into(),
584 )),
585 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
586 }
587 });
588
589 interp.register_fn(
590 "join_lines",
591 Arity::Exact(1),
592 |a: &[Value], _h: &mut H, s| match &a[0] {
593 Value::List(items) => Ok(Value::Str(
594 items
595 .iter()
596 .map(render)
597 .collect::<Vec<_>>()
598 .join("\n")
599 .into(),
600 )),
601 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
602 },
603 );
604
605 interp.register_fn(
606 "unlines",
607 Arity::Exact(1),
608 |a: &[Value], _h: &mut H, s| match &a[0] {
609 Value::List(items) => Ok(Value::Str(
610 items
611 .iter()
612 .map(|v| render(v) + "\n")
613 .collect::<String>()
614 .into(),
615 )),
616 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
617 },
618 );
619
620 interp.register_fn(
621 "line_break",
622 Arity::Exact(0),
623 |_a: &[Value], _h: &mut H, _s| Ok(Value::Str("\n".into())),
624 );
625
626 interp.register_fn(
627 "contains?",
628 Arity::Exact(2),
629 |a: &[Value], _h: &mut H, s| {
630 Ok(Value::Bool(as_str(&a[0], s)?.contains(&as_str(&a[1], s)?)))
631 },
632 );
633
634 interp.register_fn(
635 "starts_with?",
636 Arity::Exact(2),
637 |a: &[Value], _h: &mut H, s| {
638 Ok(Value::Bool(
639 as_str(&a[0], s)?.starts_with(&as_str(&a[1], s)?),
640 ))
641 },
642 );
643
644 interp.register_fn(
645 "ends_with?",
646 Arity::Exact(2),
647 |a: &[Value], _h: &mut H, s| {
648 Ok(Value::Bool(as_str(&a[0], s)?.ends_with(&as_str(&a[1], s)?)))
649 },
650 );
651
652 interp.register_fn(
653 "text_index",
654 Arity::Exact(3),
655 |a: &[Value], _h: &mut H, s| {
656 Ok(Value::Int(text_index(
657 &as_str(&a[0], s)?,
658 &as_str(&a[1], s)?,
659 as_index(&a[2], s)?,
660 )))
661 },
662 );
663
664 interp.register_fn(
665 "text_last_index",
666 Arity::Exact(3),
667 |a: &[Value], _h: &mut H, s| {
668 Ok(Value::Int(text_last_index(
669 &as_str(&a[0], s)?,
670 &as_str(&a[1], s)?,
671 as_index(&a[2], s)?,
672 )))
673 },
674 );
675
676 interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
677 Ok(Value::Str(
678 as_str(&a[0], s)?
679 .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
680 .into(),
681 ))
682 });
683
684 interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
685 match &a[0] {
686 Value::List(items) => Ok(Value::list(items.iter().rev().cloned())),
687 other => Ok(Value::Str(
690 as_str(other, s)?.chars().rev().collect::<String>().into(),
691 )),
692 }
693 });
694
695 interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
696 Ok(list(
697 as_str(&a[0], s)?
698 .chars()
699 .map(|c| Value::Str(c.to_string().into()))
700 .collect(),
701 ))
702 });
703
704 interp.register_fn(
705 "text_bytes",
706 Arity::Exact(1),
707 |a: &[Value], _h: &mut H, s| {
708 Ok(list(
709 as_str(&a[0], s)?
710 .as_bytes()
711 .iter()
712 .map(|b| Value::Int(i64::from(*b)))
713 .collect(),
714 ))
715 },
716 );
717
718 interp.register_fn(
719 "bytes_text",
720 Arity::Exact(1),
721 |a: &[Value], _h: &mut H, s| {
722 let bytes = crate::crypto::message_bytes(&a[0])
723 .map_err(|e| EvalError::native_fn("bytes_text", e.to_string(), s))?;
724 Ok(match String::from_utf8(bytes) {
725 Ok(text) => Value::Str(text.into()),
726 Err(_) => Value::Nil,
727 })
728 },
729 );
730
731 interp.register_fn(
738 "to_int",
739 Arity::Exact(1),
740 |a: &[Value], _h: &mut H, s| match &a[0] {
741 Value::Int(n) => Ok(Value::Int(*n)),
742 Value::Float(x) => Ok(float_to_int(*x).map_or(Value::Nil, Value::Int)),
746 other => Ok(as_str(other, s)?
747 .trim()
748 .parse::<i64>()
749 .map_or(Value::Nil, Value::Int)),
750 },
751 );
752
753 interp.register_fn(
754 "to_int!",
755 Arity::Exact(1),
756 |a: &[Value], _h: &mut H, s| match &a[0] {
757 Value::Int(n) => Ok(Value::Int(*n)),
758 Value::Float(x) => float_to_int(*x)
759 .map(Value::Int)
760 .ok_or(EvalError::IntegerOverflow {
761 op: "to_int!",
762 at: s,
763 }),
764 other => {
765 let text = as_str(other, s)?;
766 text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
767 EvalError::native_fn(
768 "to_int!",
769 "`".to_string() + &text + "` is not an integer",
770 s,
771 )
772 .into()
773 })
774 }
775 },
776 );
777
778 interp.register_fn(
779 "to_float",
780 Arity::Exact(1),
781 |a: &[Value], _h: &mut H, s| match &a[0] {
782 Value::Float(x) => Ok(Value::Float(*x)),
783 Value::Int(n) => Ok(Value::Float(*n as f64)),
784 other => Ok(as_str(other, s)?
785 .trim()
786 .parse::<f64>()
787 .map_or(Value::Nil, Value::Float)),
788 },
789 );
790
791 interp.register_fn(
792 "abs",
793 Arity::Exact(1),
794 |a: &[Value], _h: &mut H, s| match &a[0] {
795 Value::Int(n) => n
798 .checked_abs()
799 .map(Value::Int)
800 .ok_or(EvalError::IntegerOverflow { op: "abs", at: s }),
801 Value::Float(x) => Ok(Value::Float(x.abs())),
802 other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
803 },
804 );
805
806 interp.register_fn("range", Arity::Range(1, 3), |a: &[Value], _h: &mut H, s| {
827 let (start, end, step) = match a.len() {
828 1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
829 2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
830 _ => (a[0].clone(), a[1].clone(), a[2].clone()),
831 };
832 range_list(start, &end, &step, s)
833 });
834
835 interp.register_fn(
842 "write_stdout",
843 Arity::Exact(1),
844 |a: &[Value], _h: &mut H, s| {
845 use std::io::Write;
846 let text = as_str(&a[0], s)?;
847 let mut out = std::io::stdout().lock();
848 out.write_all(text.as_bytes())
849 .and_then(|()| out.flush())
850 .map_err(|e| EvalError::native_fn("write_stdout", e.to_string(), s))?;
851 Ok(Value::Nil)
852 },
853 );
854 interp.register_fn(
855 "write_stderr",
856 Arity::Exact(1),
857 |a: &[Value], _h: &mut H, s| {
858 use std::io::Write;
859 let text = as_str(&a[0], s)?;
860 let mut err = std::io::stderr().lock();
861 err.write_all(text.as_bytes())
862 .and_then(|()| err.flush())
863 .map_err(|e| EvalError::native_fn("write_stderr", e.to_string(), s))?;
864 Ok(Value::Nil)
865 },
866 );
867
868 interp.register_higher_order_fn(
875 "sort_keyed",
876 Arity::Exact(2),
877 |a: &[Value], host: &mut H, caller: &tatara_lisp_eval::ffi::Caller<H>, s| {
878 let xs = match &a[1] {
879 Value::List(xs) => xs.to_vec(),
880 Value::Nil => Vec::new(),
881 other => {
882 return Err(EvalError::type_mismatch("a list", other.type_name(), s));
883 }
884 };
885 let mut keyed = Vec::with_capacity(xs.len());
886 for x in xs {
887 keyed.push((caller.apply_value(&a[0], vec![x.clone()], host, s)?, x));
888 }
889 Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
890 },
891 );
892
893 interp.register_fn(
894 "error_message",
895 Arity::Exact(1),
896 |a: &[Value], _h: &mut H, s| match &a[0] {
897 Value::Error(e) => Ok(Value::Str(e.message.clone())),
898 other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
899 },
900 );
901
902 interp.register_fn(
903 "error_kind",
904 Arity::Exact(1),
905 |a: &[Value], _h: &mut H, s| match &a[0] {
906 Value::Error(e) => Ok(Value::Keyword(e.tag.clone())),
907 other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
908 },
909 );
910
911 interp.register_fn(
912 "map_entries",
913 Arity::Exact(1),
914 |a: &[Value], _h: &mut H, s| match &a[0] {
915 Value::Map(m) => {
916 let keyed = m
917 .iter()
918 .map(|(k, v)| (k.to_value(), list(vec![k.to_value(), v.clone()])))
919 .collect();
920 Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
921 }
922 Value::Nil => Ok(list(Vec::new())),
923 other => Err(EvalError::type_mismatch("a map", other.type_name(), s)),
924 },
925 );
926}
927
928fn as_index(v: &Value, span: tatara_lisp::Span) -> Result<i64, EvalError> {
929 match v {
930 Value::Int(n) => Ok(*n),
931 other => Err(EvalError::type_mismatch(
932 "an integer",
933 other.type_name(),
934 span,
935 )),
936 }
937}
938
939fn text_index(text: &str, sub: &str, from: i64) -> i64 {
940 let from = usize::try_from(from.max(0)).unwrap_or(usize::MAX);
941 let start = match text.char_indices().nth(from) {
942 Some((b, _)) => b,
943 None if text.chars().count() == from => text.len(),
944 None => return -1,
945 };
946 text[start..].find(sub).map_or(-1, |b| {
947 i64::try_from(from + text[start..start + b].chars().count()).unwrap_or(i64::MAX)
948 })
949}
950
951fn text_last_index(text: &str, sub: &str, from: i64) -> i64 {
952 let Ok(from) = usize::try_from(from) else {
953 return -1;
954 };
955 let total = text.chars().count();
956 let width = sub.chars().count();
957 if width > total {
958 return -1;
959 }
960 let limit = from.min(total - width);
961 let end = text
962 .char_indices()
963 .nth(limit + width)
964 .map_or(text.len(), |(b, _)| b);
965 text[..end].rfind(sub).map_or(-1, |b| {
966 i64::try_from(text[..b].chars().count()).unwrap_or(i64::MAX)
967 })
968}
969
970fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
972 match v {
973 Value::Int(n) => Ok(*n as f64),
974 Value::Float(x) => Ok(*x),
975 other => Err(EvalError::native_fn(
976 "range",
977 "expected a number, got ".to_string() + other.type_name(),
978 s,
979 )),
980 }
981}
982
983fn float_to_int(x: f64) -> Option<i64> {
986 const LIMIT: f64 = 9_223_372_036_854_775_808.0;
987 let t = x.trunc();
988 #[allow(clippy::cast_possible_truncation)]
989 (t.is_finite() && (-LIMIT..LIMIT).contains(&t)).then(|| t as i64)
990}
991
992fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
995 match (a, b) {
996 (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
997 EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
998 }),
999 _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
1000 }
1001}
1002
1003fn range_list(
1004 start: Value,
1005 end: &Value,
1006 step: &Value,
1007 s: tatara_lisp::Span,
1008) -> Result<Value, EvalError> {
1009 let end_f = range_num(end, s)?;
1010 let step_f = range_num(step, s)?;
1011 range_num(&start, s)?;
1012 if step_f == 0.0 {
1013 return Err(EvalError::native_fn(
1014 "range",
1015 "a step of zero never reaches the end",
1016 s,
1017 ));
1018 }
1019 let mut out = Vec::new();
1020 let mut cur = start;
1021 loop {
1022 let c = range_num(&cur, s)?;
1023 if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
1024 break;
1025 }
1026 let next = range_add(&cur, step, s)?;
1027 out.push(cur);
1028 cur = next;
1029 }
1030 Ok(list(out))
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035 use super::*;
1036
1037 #[test]
1038 fn sort_keyed_is_stable_keyed_and_deep() {
1039 assert_eq!(
1041 ints("map(fn(p) last(p) end, sort_keyed(fn(p) first(p) end, [[2, 1], [1, 2], [2, 3], [1, 4]]))"),
1042 vec![2, 4, 1, 3]
1043 );
1044 assert_eq!(
1046 i("first(sort_keyed(fn(x) x end, reverse(range(0, 20000))))"),
1047 0
1048 );
1049 assert_eq!(i("last(sort_keyed(fn(x) 0 - x end, range(0, 20000)))"), 0);
1050 assert_eq!(ints("sort_keyed(fn(x) x end, [])"), Vec::<i64>::new());
1052 assert!(crate::run("sort_keyed(fn(x) x end, [1, \"a\"])").is_err());
1053 }
1054
1055 #[test]
1056 fn distinct_is_native_and_keeps_tataras_meaning() {
1057 assert!(matches!(
1058 crate::interpreter_hostless().lookup_global("distinct"),
1059 Some(Value::NativeFn(_))
1060 ));
1061 let corpus = eval(
1062 "[1, 1.0, 0, -0.0, 0.0, 9007199254740993, 9007199254740992, 9007199254740992.0, \
1063 \"a\", :a, \"a\", nil, nil, true, false, true, [1, 2], [1, 2.0], [2], \
1064 {a: 1}, {a: 1.0}, 2.5, 2.5, -1, -1.0, \"\", \"\"]",
1065 );
1066 let Value::List(xs) = &corpus else {
1067 panic!("{corpus:?}")
1068 };
1069 let mut naive: Vec<Value> = Vec::new();
1070 for x in xs.iter() {
1071 if !naive.iter().any(|k| blue_equal(k, x)) {
1072 naive.push(x.clone());
1073 }
1074 }
1075 let fast = distinct(xs.iter());
1076 assert_eq!(fast.len(), naive.len());
1077 assert!(fast.iter().zip(&naive).all(|(a, b)| blue_equal(a, b)));
1078 assert_eq!(
1079 i("length(distinct(map((x) -> x % 997, range(300000))))"),
1080 997
1081 );
1082 assert_eq!(i("length(distinct(nil))"), 0);
1083 }
1084
1085 #[test]
1086 fn frequencies_is_native_and_counts_as_tatara_does() {
1087 assert!(matches!(
1088 crate::interpreter_hostless().lookup_global("frequencies"),
1089 Some(Value::NativeFn(_))
1090 ));
1091 let corpus = "(list 1 1.0 1 \"a\" 'a :a \"a\" #t #f #t 2.5 2.5 -0.0 0.0 0)";
1092 let mut upstream = tatara_lisp_eval::Interpreter::<()>::new();
1093 tatara_lisp_eval::install_full_stdlib_with(&mut upstream, &mut ());
1094 let forms = tatara_lisp::read_spanned(&format!("(frequencies {corpus})")).expect("reads");
1095 let expected = upstream
1096 .eval_program(&forms, &mut ())
1097 .expect("upstream counts");
1098 let Value::List(xs) = upstream
1099 .eval_program(&tatara_lisp::read_spanned(corpus).expect("reads"), &mut ())
1100 .expect("corpus")
1101 else {
1102 panic!("a list")
1103 };
1104 let ours = frequencies(xs.iter(), tatara_lisp::Span::synthetic()).expect("counts");
1105 assert!(blue_equal(&ours, &expected), "{ours:?} vs {expected:?}");
1106 assert!(crate::run("frequencies([[1]])").is_err());
1107 assert_eq!(
1108 i("get(frequencies(map((x) -> x % 7, range(70000))), 3)"),
1109 10000
1110 );
1111 }
1112
1113 fn eval(src: &str) -> Value {
1114 crate::run(src)
1115 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
1116 .value
1117 }
1118
1119 fn s(src: &str) -> String {
1120 match eval(src) {
1121 Value::Str(v) => v.to_string(),
1122 other => panic!("{src:?} produced {other:?}"),
1123 }
1124 }
1125
1126 fn i(src: &str) -> i64 {
1127 match eval(src) {
1128 Value::Int(v) => v,
1129 other => panic!("{src:?} produced {other:?}"),
1130 }
1131 }
1132
1133 fn ints(src: &str) -> Vec<i64> {
1134 match eval(src) {
1135 Value::List(xs) => xs
1136 .iter()
1137 .map(|v| match v {
1138 Value::Int(n) => *n,
1139 other => panic!("{src:?} produced a non-Int element {other:?}"),
1140 })
1141 .collect(),
1142 other => panic!("{src:?} produced {other:?}"),
1143 }
1144 }
1145
1146 #[test]
1149 fn range_answers_as_the_lisp_definition_did() {
1150 assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
1151 assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
1152 assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
1153 assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
1154 assert!(ints("range(5, 5)").is_empty());
1155 assert!(ints("range(5, 2)").is_empty());
1156 assert!(ints("range(0)").is_empty());
1157 match eval("range(0, 1, 0.5)") {
1159 Value::List(xs) => {
1160 assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
1161 assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
1162 assert_eq!(xs.len(), 2);
1163 }
1164 other => panic!("{other:?}"),
1165 }
1166 }
1167
1168 #[test]
1174 fn range_builds_long_lists_without_recursing() {
1175 assert_eq!(i("length(range(0, 200000))"), 200_000);
1176 assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
1177 }
1178
1179 #[test]
1182 fn range_refuses_a_zero_step_and_a_non_number() {
1183 assert!(crate::run("range(0, 5, 0)").is_err());
1184 assert!(crate::run("range(0, \"x\")").is_err());
1185 }
1186
1187 #[test]
1191 fn length_counts_characters_not_bytes() {
1192 assert_eq!(i("length(\"hello\")"), 5);
1193 assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
1195 assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
1197 }
1198
1199 #[test]
1202 fn a_combining_sequence_counts_scalars_not_graphemes() {
1203 assert_eq!(
1205 i("length(\"e\\u{301}\")"),
1206 2,
1207 "blue counts scalar values; Elixir's String.length would say 1"
1208 );
1209 }
1210
1211 #[test]
1212 fn length_also_works_on_a_list() {
1213 assert_eq!(i("length([1, 2, 3])"), 3);
1214 }
1215
1216 #[test]
1217 fn case_and_trim() {
1218 assert_eq!(s("upcase(\"abc\")"), "ABC");
1219 assert_eq!(s("downcase(\"ABC\")"), "abc");
1220 assert_eq!(s("trim(\" hi \")"), "hi");
1221 assert_eq!(s("upcase(\"é\")"), "É");
1223 }
1224
1225 #[test]
1226 fn concat_and_to_s() {
1227 assert_eq!(s("concat(\"a\", \"b\")"), "ab");
1228 assert_eq!(s("concat(\"n=\", 42)"), "n=42");
1229 assert_eq!(s("to_s(42)"), "42");
1230 assert_eq!(s("to_s(true)"), "true");
1231 }
1232
1233 #[test]
1237 fn plus_is_not_string_concatenation() {
1238 assert!(
1239 crate::run("\"a\" + \"b\"").is_err(),
1240 "`+` must not silently concatenate — use concat"
1241 );
1242 }
1243
1244 #[test]
1245 fn split_and_join() {
1246 assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
1247 assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
1248 assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
1250 }
1251
1252 #[test]
1253 fn predicates() {
1254 assert!(matches!(
1255 eval("contains?(\"hello\", \"ell\")"),
1256 Value::Bool(true)
1257 ));
1258 assert!(matches!(
1259 eval("contains?(\"hello\", \"xyz\")"),
1260 Value::Bool(false)
1261 ));
1262 assert!(matches!(
1263 eval("starts_with?(\"hello\", \"he\")"),
1264 Value::Bool(true)
1265 ));
1266 assert!(matches!(
1267 eval("ends_with?(\"hello\", \"lo\")"),
1268 Value::Bool(true)
1269 ));
1270 }
1271
1272 fn refused(src: &str) -> String {
1273 match crate::run(src) {
1274 Ok(v) => panic!("{src:?} should fail, produced {:?}", v.value),
1275 Err(e) => e.to_string(),
1276 }
1277 }
1278
1279 #[test]
1280 fn text_bytes_and_bytes_text_are_utf8_both_ways() {
1281 assert_eq!(ints("text_bytes(\"abc\")"), vec![97, 98, 99]);
1282 assert_eq!(ints("text_bytes(\"é\")"), vec![195, 169]);
1283 assert!(ints("text_bytes(\"\")").is_empty());
1284 assert_eq!(s("bytes_text([104, 195, 169])"), "hé");
1285 assert_eq!(s("bytes_text(text_bytes(\"€ x\"))"), "€ x");
1286 assert_eq!(s("bytes_text([])"), "");
1287 assert!(matches!(eval("bytes_text([195])"), Value::Nil));
1288 assert!(matches!(eval("bytes_text([255, 97])"), Value::Nil));
1289 assert!(refused("bytes_text([256])").contains("outside 0..=255"));
1290 assert!(refused("bytes_text(nil)").contains("string or a list of bytes"));
1291 assert!(refused("text_bytes(5)").contains("string"));
1292 }
1293
1294 #[test]
1295 fn trim_without_options_cuts_whitespace_at_both_ends() {
1296 assert_eq!(s("trim(\" a b \\n\")"), "a b");
1297 assert_eq!(s("trim(\" a \", nil)"), "a");
1298 assert_eq!(s("trim(\" a \", {})"), "a");
1299 assert_eq!(s("trim(\"\")"), "");
1300 assert_eq!(s("trim(\" \")"), "");
1301 assert_eq!(s("trim(\"\", {side: :start})"), "");
1302 }
1303
1304 #[test]
1305 fn trim_side_keeps_the_other_end() {
1306 assert_eq!(s("trim(\" a \", {side: :both})"), "a");
1307 assert_eq!(s("trim(\" a \", {side: :start})"), "a ");
1308 assert_eq!(s("trim(\" a \", {side: :end})"), " a");
1309 }
1310
1311 #[test]
1312 fn trim_chars_replaces_whitespace_as_the_set_to_cut() {
1313 assert_eq!(s("trim(\"--a-b--\", {chars: \"-\"})"), "a-b");
1314 assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :start})"), "a+-");
1315 assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :end})"), "-+a");
1316 assert_eq!(s("trim(\" a \", {chars: \"-\"})"), " a ");
1317 assert_eq!(s("trim(\"aaa\", {chars: \"a\"})"), "");
1318 assert_eq!(s("trim(\"héé\", {chars: \"é\", side: :end})"), "h");
1319 assert_eq!(s("trim(\" a \", {chars: \"\"})"), " a ");
1320 }
1321
1322 #[test]
1323 fn trim_refuses_what_it_does_not_take() {
1324 assert!(refused("trim(\"a\", {sid: :end})").contains("bad_option"));
1325 assert!(refused("trim(\"a\", {sid: :end})").contains("side, chars"));
1326 assert!(refused("trim(\"a\", {side: :middle})").contains("side must be"));
1327 assert!(refused("trim(\"a\", {side: \"end\"})").contains("bad_option"));
1328 assert!(refused("trim(\"a\", {chars: 1})").contains("chars must be text"));
1329 assert!(refused("trim(\"a\", 5)").contains("options must be a map"));
1330 assert!(refused("trim(\"a\", {}, {})").contains("1 to 2"));
1331 assert!(refused("trim()").contains("1 to 2"));
1332 assert!(refused("trim(5)").contains("string"));
1333 }
1334
1335 #[test]
1336 fn trim_is_still_a_value_other_functions_take() {
1337 assert_eq!(s("join(map(trim, [\" a\", \"b \"]), \",\")"), "a,b");
1338 }
1339
1340 #[test]
1341 fn text_index_answers_character_positions() {
1342 assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 0)"), 2);
1343 assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 3)"), 8);
1344 assert_eq!(i("text_index(\"héllo\", \"x\", 0)"), -1);
1345 assert_eq!(i("text_index(\"abc\", \"\", 3)"), 3);
1346 assert_eq!(i("text_index(\"abc\", \"\", 4)"), -1);
1347 assert_eq!(i("text_index(\"abc\", \"a\", -5)"), 0);
1348 assert_eq!(i("text_index(\"\", \"a\", 0)"), -1);
1349 }
1350
1351 #[test]
1352 fn text_last_index_finds_the_last_start_at_or_before_from() {
1353 assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 99)"), 8);
1354 assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 7)"), 2);
1355 assert_eq!(i("text_last_index(\"aaa\", \"aa\", 1)"), 1);
1356 assert_eq!(i("text_last_index(\"aaa\", \"aa\", 0)"), 0);
1357 assert_eq!(i("text_last_index(\"abc\", \"x\", 2)"), -1);
1358 assert_eq!(i("text_last_index(\"abc\", \"a\", -1)"), -1);
1359 assert_eq!(i("text_last_index(\"ab\", \"abc\", 0)"), -1);
1360 assert_eq!(i("text_last_index(\"abc\", \"\", 9)"), 3);
1361 }
1362
1363 #[test]
1364 fn replace_and_chars() {
1365 assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
1366 assert_eq!(i("length(chars(\"abc\"))"), 3);
1367 }
1368
1369 #[test]
1372 fn reverse_is_character_wise() {
1373 assert_eq!(s("reverse(\"abc\")"), "cba");
1374 assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
1375 }
1376
1377 #[test]
1378 fn reverse_also_works_on_a_list() {
1379 assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
1380 }
1381
1382 #[test]
1387 fn to_int_is_nil_on_garbage_rather_than_zero() {
1388 assert_eq!(i("to_int(\"42\")"), 42);
1389 assert!(
1390 matches!(eval("to_int(\"banana\")"), Value::Nil),
1391 "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
1392 );
1393 assert!(
1394 matches!(eval("to_int(\"0\")"), Value::Int(0)),
1395 "and a real 0 is still a real 0 — the two must stay distinguishable"
1396 );
1397 }
1398
1399 #[test]
1400 fn to_int_bang_raises_on_garbage() {
1401 assert_eq!(i("to_int!(\"42\")"), 42);
1402 let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
1403 assert!(err.to_string().contains("banana"), "must name it: {err}");
1404 }
1405
1406 #[test]
1407 fn numeric_conversions_and_abs() {
1408 assert_eq!(i("to_int(3.9)"), 3);
1409 assert_eq!(i("abs(0 - 5)"), 5);
1410 assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
1411 assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
1412 }
1413
1414 #[test]
1416 fn a_non_string_argument_is_a_type_error() {
1417 assert!(crate::run("upcase([1, 2])").is_err());
1418 assert!(crate::run("join(\"not a list\", \",\")").is_err());
1419 }
1420}