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("join_lines", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
590 match &a[0] {
591 Value::List(items) => Ok(Value::Str(
592 items
593 .iter()
594 .map(render)
595 .collect::<Vec<_>>()
596 .join("\n")
597 .into(),
598 )),
599 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
600 }
601 });
602
603 interp.register_fn("unlines", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
604 match &a[0] {
605 Value::List(items) => Ok(Value::Str(
606 items
607 .iter()
608 .map(|v| render(v) + "\n")
609 .collect::<String>()
610 .into(),
611 )),
612 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
613 }
614 });
615
616 interp.register_fn("line_break", Arity::Exact(0), |_a: &[Value], _h: &mut H, _s| {
617 Ok(Value::Str("\n".into()))
618 });
619
620 interp.register_fn(
621 "contains?",
622 Arity::Exact(2),
623 |a: &[Value], _h: &mut H, s| {
624 Ok(Value::Bool(as_str(&a[0], s)?.contains(&as_str(&a[1], s)?)))
625 },
626 );
627
628 interp.register_fn(
629 "starts_with?",
630 Arity::Exact(2),
631 |a: &[Value], _h: &mut H, s| {
632 Ok(Value::Bool(
633 as_str(&a[0], s)?.starts_with(&as_str(&a[1], s)?),
634 ))
635 },
636 );
637
638 interp.register_fn(
639 "ends_with?",
640 Arity::Exact(2),
641 |a: &[Value], _h: &mut H, s| {
642 Ok(Value::Bool(as_str(&a[0], s)?.ends_with(&as_str(&a[1], s)?)))
643 },
644 );
645
646 interp.register_fn(
647 "text_index",
648 Arity::Exact(3),
649 |a: &[Value], _h: &mut H, s| {
650 Ok(Value::Int(text_index(
651 &as_str(&a[0], s)?,
652 &as_str(&a[1], s)?,
653 as_index(&a[2], s)?,
654 )))
655 },
656 );
657
658 interp.register_fn(
659 "text_last_index",
660 Arity::Exact(3),
661 |a: &[Value], _h: &mut H, s| {
662 Ok(Value::Int(text_last_index(
663 &as_str(&a[0], s)?,
664 &as_str(&a[1], s)?,
665 as_index(&a[2], s)?,
666 )))
667 },
668 );
669
670 interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
671 Ok(Value::Str(
672 as_str(&a[0], s)?
673 .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
674 .into(),
675 ))
676 });
677
678 interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
679 match &a[0] {
680 Value::List(items) => Ok(Value::list(items.iter().rev().cloned())),
681 other => Ok(Value::Str(
684 as_str(other, s)?.chars().rev().collect::<String>().into(),
685 )),
686 }
687 });
688
689 interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
690 Ok(list(
691 as_str(&a[0], s)?
692 .chars()
693 .map(|c| Value::Str(c.to_string().into()))
694 .collect(),
695 ))
696 });
697
698 interp.register_fn(
699 "text_bytes",
700 Arity::Exact(1),
701 |a: &[Value], _h: &mut H, s| {
702 Ok(list(
703 as_str(&a[0], s)?
704 .as_bytes()
705 .iter()
706 .map(|b| Value::Int(i64::from(*b)))
707 .collect(),
708 ))
709 },
710 );
711
712 interp.register_fn(
713 "bytes_text",
714 Arity::Exact(1),
715 |a: &[Value], _h: &mut H, s| {
716 let bytes = crate::crypto::message_bytes(&a[0])
717 .map_err(|e| EvalError::native_fn("bytes_text", e.to_string(), s))?;
718 Ok(match String::from_utf8(bytes) {
719 Ok(text) => Value::Str(text.into()),
720 Err(_) => Value::Nil,
721 })
722 },
723 );
724
725 interp.register_fn(
732 "to_int",
733 Arity::Exact(1),
734 |a: &[Value], _h: &mut H, s| match &a[0] {
735 Value::Int(n) => Ok(Value::Int(*n)),
736 Value::Float(x) => Ok(float_to_int(*x).map_or(Value::Nil, Value::Int)),
740 other => Ok(as_str(other, s)?
741 .trim()
742 .parse::<i64>()
743 .map_or(Value::Nil, Value::Int)),
744 },
745 );
746
747 interp.register_fn(
748 "to_int!",
749 Arity::Exact(1),
750 |a: &[Value], _h: &mut H, s| match &a[0] {
751 Value::Int(n) => Ok(Value::Int(*n)),
752 Value::Float(x) => float_to_int(*x)
753 .map(Value::Int)
754 .ok_or(EvalError::IntegerOverflow {
755 op: "to_int!",
756 at: s,
757 }),
758 other => {
759 let text = as_str(other, s)?;
760 text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
761 EvalError::native_fn(
762 "to_int!",
763 "`".to_string() + &text + "` is not an integer",
764 s,
765 )
766 .into()
767 })
768 }
769 },
770 );
771
772 interp.register_fn(
773 "to_float",
774 Arity::Exact(1),
775 |a: &[Value], _h: &mut H, s| match &a[0] {
776 Value::Float(x) => Ok(Value::Float(*x)),
777 Value::Int(n) => Ok(Value::Float(*n as f64)),
778 other => Ok(as_str(other, s)?
779 .trim()
780 .parse::<f64>()
781 .map_or(Value::Nil, Value::Float)),
782 },
783 );
784
785 interp.register_fn(
786 "abs",
787 Arity::Exact(1),
788 |a: &[Value], _h: &mut H, s| match &a[0] {
789 Value::Int(n) => n
792 .checked_abs()
793 .map(Value::Int)
794 .ok_or(EvalError::IntegerOverflow { op: "abs", at: s }),
795 Value::Float(x) => Ok(Value::Float(x.abs())),
796 other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
797 },
798 );
799
800 interp.register_fn("range", Arity::Range(1, 3), |a: &[Value], _h: &mut H, s| {
821 let (start, end, step) = match a.len() {
822 1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
823 2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
824 _ => (a[0].clone(), a[1].clone(), a[2].clone()),
825 };
826 range_list(start, &end, &step, s)
827 });
828
829 interp.register_fn(
836 "write_stdout",
837 Arity::Exact(1),
838 |a: &[Value], _h: &mut H, s| {
839 use std::io::Write;
840 let text = as_str(&a[0], s)?;
841 let mut out = std::io::stdout().lock();
842 out.write_all(text.as_bytes())
843 .and_then(|()| out.flush())
844 .map_err(|e| EvalError::native_fn("write_stdout", e.to_string(), s))?;
845 Ok(Value::Nil)
846 },
847 );
848 interp.register_fn(
849 "write_stderr",
850 Arity::Exact(1),
851 |a: &[Value], _h: &mut H, s| {
852 use std::io::Write;
853 let text = as_str(&a[0], s)?;
854 let mut err = std::io::stderr().lock();
855 err.write_all(text.as_bytes())
856 .and_then(|()| err.flush())
857 .map_err(|e| EvalError::native_fn("write_stderr", e.to_string(), s))?;
858 Ok(Value::Nil)
859 },
860 );
861
862 interp.register_higher_order_fn(
869 "sort_keyed",
870 Arity::Exact(2),
871 |a: &[Value], host: &mut H, caller: &tatara_lisp_eval::ffi::Caller<H>, s| {
872 let xs = match &a[1] {
873 Value::List(xs) => xs.to_vec(),
874 Value::Nil => Vec::new(),
875 other => {
876 return Err(EvalError::type_mismatch("a list", other.type_name(), s));
877 }
878 };
879 let mut keyed = Vec::with_capacity(xs.len());
880 for x in xs {
881 keyed.push((caller.apply_value(&a[0], vec![x.clone()], host, s)?, x));
882 }
883 Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
884 },
885 );
886
887 interp.register_fn(
888 "error_message",
889 Arity::Exact(1),
890 |a: &[Value], _h: &mut H, s| match &a[0] {
891 Value::Error(e) => Ok(Value::Str(e.message.clone())),
892 other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
893 },
894 );
895
896 interp.register_fn(
897 "error_kind",
898 Arity::Exact(1),
899 |a: &[Value], _h: &mut H, s| match &a[0] {
900 Value::Error(e) => Ok(Value::Keyword(e.tag.clone())),
901 other => Err(EvalError::type_mismatch("an error", other.type_name(), s)),
902 },
903 );
904
905 interp.register_fn(
906 "map_entries",
907 Arity::Exact(1),
908 |a: &[Value], _h: &mut H, s| match &a[0] {
909 Value::Map(m) => {
910 let keyed = m
911 .iter()
912 .map(|(k, v)| (k.to_value(), list(vec![k.to_value(), v.clone()])))
913 .collect();
914 Ok(list(tatara_lisp_eval::hof::sort_keyed_values(keyed, s)?))
915 }
916 Value::Nil => Ok(list(Vec::new())),
917 other => Err(EvalError::type_mismatch("a map", other.type_name(), s)),
918 },
919 );
920}
921
922fn as_index(v: &Value, span: tatara_lisp::Span) -> Result<i64, EvalError> {
923 match v {
924 Value::Int(n) => Ok(*n),
925 other => Err(EvalError::type_mismatch(
926 "an integer",
927 other.type_name(),
928 span,
929 )),
930 }
931}
932
933fn text_index(text: &str, sub: &str, from: i64) -> i64 {
934 let from = usize::try_from(from.max(0)).unwrap_or(usize::MAX);
935 let start = match text.char_indices().nth(from) {
936 Some((b, _)) => b,
937 None if text.chars().count() == from => text.len(),
938 None => return -1,
939 };
940 text[start..].find(sub).map_or(-1, |b| {
941 i64::try_from(from + text[start..start + b].chars().count()).unwrap_or(i64::MAX)
942 })
943}
944
945fn text_last_index(text: &str, sub: &str, from: i64) -> i64 {
946 let Ok(from) = usize::try_from(from) else {
947 return -1;
948 };
949 let total = text.chars().count();
950 let width = sub.chars().count();
951 if width > total {
952 return -1;
953 }
954 let limit = from.min(total - width);
955 let end = text
956 .char_indices()
957 .nth(limit + width)
958 .map_or(text.len(), |(b, _)| b);
959 text[..end].rfind(sub).map_or(-1, |b| {
960 i64::try_from(text[..b].chars().count()).unwrap_or(i64::MAX)
961 })
962}
963
964fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
966 match v {
967 Value::Int(n) => Ok(*n as f64),
968 Value::Float(x) => Ok(*x),
969 other => Err(EvalError::native_fn(
970 "range",
971 "expected a number, got ".to_string() + other.type_name(),
972 s,
973 )),
974 }
975}
976
977fn float_to_int(x: f64) -> Option<i64> {
980 const LIMIT: f64 = 9_223_372_036_854_775_808.0;
981 let t = x.trunc();
982 #[allow(clippy::cast_possible_truncation)]
983 (t.is_finite() && (-LIMIT..LIMIT).contains(&t)).then(|| t as i64)
984}
985
986fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
989 match (a, b) {
990 (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
991 EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
992 }),
993 _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
994 }
995}
996
997fn range_list(
998 start: Value,
999 end: &Value,
1000 step: &Value,
1001 s: tatara_lisp::Span,
1002) -> Result<Value, EvalError> {
1003 let end_f = range_num(end, s)?;
1004 let step_f = range_num(step, s)?;
1005 range_num(&start, s)?;
1006 if step_f == 0.0 {
1007 return Err(EvalError::native_fn(
1008 "range",
1009 "a step of zero never reaches the end",
1010 s,
1011 ));
1012 }
1013 let mut out = Vec::new();
1014 let mut cur = start;
1015 loop {
1016 let c = range_num(&cur, s)?;
1017 if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
1018 break;
1019 }
1020 let next = range_add(&cur, step, s)?;
1021 out.push(cur);
1022 cur = next;
1023 }
1024 Ok(list(out))
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029 use super::*;
1030
1031 #[test]
1032 fn sort_keyed_is_stable_keyed_and_deep() {
1033 assert_eq!(
1035 ints("map(fn(p) last(p) end, sort_keyed(fn(p) first(p) end, [[2, 1], [1, 2], [2, 3], [1, 4]]))"),
1036 vec![2, 4, 1, 3]
1037 );
1038 assert_eq!(
1040 i("first(sort_keyed(fn(x) x end, reverse(range(0, 20000))))"),
1041 0
1042 );
1043 assert_eq!(i("last(sort_keyed(fn(x) 0 - x end, range(0, 20000)))"), 0);
1044 assert_eq!(ints("sort_keyed(fn(x) x end, [])"), Vec::<i64>::new());
1046 assert!(crate::run("sort_keyed(fn(x) x end, [1, \"a\"])").is_err());
1047 }
1048
1049 #[test]
1050 fn distinct_is_native_and_keeps_tataras_meaning() {
1051 assert!(matches!(
1052 crate::interpreter_hostless().lookup_global("distinct"),
1053 Some(Value::NativeFn(_))
1054 ));
1055 let corpus = eval(
1056 "[1, 1.0, 0, -0.0, 0.0, 9007199254740993, 9007199254740992, 9007199254740992.0, \
1057 \"a\", :a, \"a\", nil, nil, true, false, true, [1, 2], [1, 2.0], [2], \
1058 {a: 1}, {a: 1.0}, 2.5, 2.5, -1, -1.0, \"\", \"\"]",
1059 );
1060 let Value::List(xs) = &corpus else {
1061 panic!("{corpus:?}")
1062 };
1063 let mut naive: Vec<Value> = Vec::new();
1064 for x in xs.iter() {
1065 if !naive.iter().any(|k| blue_equal(k, x)) {
1066 naive.push(x.clone());
1067 }
1068 }
1069 let fast = distinct(xs.iter());
1070 assert_eq!(fast.len(), naive.len());
1071 assert!(fast.iter().zip(&naive).all(|(a, b)| blue_equal(a, b)));
1072 assert_eq!(
1073 i("length(distinct(map((x) -> x % 997, range(300000))))"),
1074 997
1075 );
1076 assert_eq!(i("length(distinct(nil))"), 0);
1077 }
1078
1079 #[test]
1080 fn frequencies_is_native_and_counts_as_tatara_does() {
1081 assert!(matches!(
1082 crate::interpreter_hostless().lookup_global("frequencies"),
1083 Some(Value::NativeFn(_))
1084 ));
1085 let corpus = "(list 1 1.0 1 \"a\" 'a :a \"a\" #t #f #t 2.5 2.5 -0.0 0.0 0)";
1086 let mut upstream = tatara_lisp_eval::Interpreter::<()>::new();
1087 tatara_lisp_eval::install_full_stdlib_with(&mut upstream, &mut ());
1088 let forms = tatara_lisp::read_spanned(&format!("(frequencies {corpus})")).expect("reads");
1089 let expected = upstream
1090 .eval_program(&forms, &mut ())
1091 .expect("upstream counts");
1092 let Value::List(xs) = upstream
1093 .eval_program(&tatara_lisp::read_spanned(corpus).expect("reads"), &mut ())
1094 .expect("corpus")
1095 else {
1096 panic!("a list")
1097 };
1098 let ours = frequencies(xs.iter(), tatara_lisp::Span::synthetic()).expect("counts");
1099 assert!(blue_equal(&ours, &expected), "{ours:?} vs {expected:?}");
1100 assert!(crate::run("frequencies([[1]])").is_err());
1101 assert_eq!(
1102 i("get(frequencies(map((x) -> x % 7, range(70000))), 3)"),
1103 10000
1104 );
1105 }
1106
1107 fn eval(src: &str) -> Value {
1108 crate::run(src)
1109 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
1110 .value
1111 }
1112
1113 fn s(src: &str) -> String {
1114 match eval(src) {
1115 Value::Str(v) => v.to_string(),
1116 other => panic!("{src:?} produced {other:?}"),
1117 }
1118 }
1119
1120 fn i(src: &str) -> i64 {
1121 match eval(src) {
1122 Value::Int(v) => v,
1123 other => panic!("{src:?} produced {other:?}"),
1124 }
1125 }
1126
1127 fn ints(src: &str) -> Vec<i64> {
1128 match eval(src) {
1129 Value::List(xs) => xs
1130 .iter()
1131 .map(|v| match v {
1132 Value::Int(n) => *n,
1133 other => panic!("{src:?} produced a non-Int element {other:?}"),
1134 })
1135 .collect(),
1136 other => panic!("{src:?} produced {other:?}"),
1137 }
1138 }
1139
1140 #[test]
1143 fn range_answers_as_the_lisp_definition_did() {
1144 assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
1145 assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
1146 assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
1147 assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
1148 assert!(ints("range(5, 5)").is_empty());
1149 assert!(ints("range(5, 2)").is_empty());
1150 assert!(ints("range(0)").is_empty());
1151 match eval("range(0, 1, 0.5)") {
1153 Value::List(xs) => {
1154 assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
1155 assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
1156 assert_eq!(xs.len(), 2);
1157 }
1158 other => panic!("{other:?}"),
1159 }
1160 }
1161
1162 #[test]
1168 fn range_builds_long_lists_without_recursing() {
1169 assert_eq!(i("length(range(0, 200000))"), 200_000);
1170 assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
1171 }
1172
1173 #[test]
1176 fn range_refuses_a_zero_step_and_a_non_number() {
1177 assert!(crate::run("range(0, 5, 0)").is_err());
1178 assert!(crate::run("range(0, \"x\")").is_err());
1179 }
1180
1181 #[test]
1185 fn length_counts_characters_not_bytes() {
1186 assert_eq!(i("length(\"hello\")"), 5);
1187 assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
1189 assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
1191 }
1192
1193 #[test]
1196 fn a_combining_sequence_counts_scalars_not_graphemes() {
1197 assert_eq!(
1199 i("length(\"e\\u{301}\")"),
1200 2,
1201 "blue counts scalar values; Elixir's String.length would say 1"
1202 );
1203 }
1204
1205 #[test]
1206 fn length_also_works_on_a_list() {
1207 assert_eq!(i("length([1, 2, 3])"), 3);
1208 }
1209
1210 #[test]
1211 fn case_and_trim() {
1212 assert_eq!(s("upcase(\"abc\")"), "ABC");
1213 assert_eq!(s("downcase(\"ABC\")"), "abc");
1214 assert_eq!(s("trim(\" hi \")"), "hi");
1215 assert_eq!(s("upcase(\"é\")"), "É");
1217 }
1218
1219 #[test]
1220 fn concat_and_to_s() {
1221 assert_eq!(s("concat(\"a\", \"b\")"), "ab");
1222 assert_eq!(s("concat(\"n=\", 42)"), "n=42");
1223 assert_eq!(s("to_s(42)"), "42");
1224 assert_eq!(s("to_s(true)"), "true");
1225 }
1226
1227 #[test]
1231 fn plus_is_not_string_concatenation() {
1232 assert!(
1233 crate::run("\"a\" + \"b\"").is_err(),
1234 "`+` must not silently concatenate — use concat"
1235 );
1236 }
1237
1238 #[test]
1239 fn split_and_join() {
1240 assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
1241 assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
1242 assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
1244 }
1245
1246 #[test]
1247 fn predicates() {
1248 assert!(matches!(
1249 eval("contains?(\"hello\", \"ell\")"),
1250 Value::Bool(true)
1251 ));
1252 assert!(matches!(
1253 eval("contains?(\"hello\", \"xyz\")"),
1254 Value::Bool(false)
1255 ));
1256 assert!(matches!(
1257 eval("starts_with?(\"hello\", \"he\")"),
1258 Value::Bool(true)
1259 ));
1260 assert!(matches!(
1261 eval("ends_with?(\"hello\", \"lo\")"),
1262 Value::Bool(true)
1263 ));
1264 }
1265
1266 fn refused(src: &str) -> String {
1267 match crate::run(src) {
1268 Ok(v) => panic!("{src:?} should fail, produced {:?}", v.value),
1269 Err(e) => e.to_string(),
1270 }
1271 }
1272
1273 #[test]
1274 fn text_bytes_and_bytes_text_are_utf8_both_ways() {
1275 assert_eq!(ints("text_bytes(\"abc\")"), vec![97, 98, 99]);
1276 assert_eq!(ints("text_bytes(\"é\")"), vec![195, 169]);
1277 assert!(ints("text_bytes(\"\")").is_empty());
1278 assert_eq!(s("bytes_text([104, 195, 169])"), "hé");
1279 assert_eq!(s("bytes_text(text_bytes(\"€ x\"))"), "€ x");
1280 assert_eq!(s("bytes_text([])"), "");
1281 assert!(matches!(eval("bytes_text([195])"), Value::Nil));
1282 assert!(matches!(eval("bytes_text([255, 97])"), Value::Nil));
1283 assert!(refused("bytes_text([256])").contains("outside 0..=255"));
1284 assert!(refused("bytes_text(nil)").contains("string or a list of bytes"));
1285 assert!(refused("text_bytes(5)").contains("string"));
1286 }
1287
1288 #[test]
1289 fn trim_without_options_cuts_whitespace_at_both_ends() {
1290 assert_eq!(s("trim(\" a b \\n\")"), "a b");
1291 assert_eq!(s("trim(\" a \", nil)"), "a");
1292 assert_eq!(s("trim(\" a \", {})"), "a");
1293 assert_eq!(s("trim(\"\")"), "");
1294 assert_eq!(s("trim(\" \")"), "");
1295 assert_eq!(s("trim(\"\", {side: :start})"), "");
1296 }
1297
1298 #[test]
1299 fn trim_side_keeps_the_other_end() {
1300 assert_eq!(s("trim(\" a \", {side: :both})"), "a");
1301 assert_eq!(s("trim(\" a \", {side: :start})"), "a ");
1302 assert_eq!(s("trim(\" a \", {side: :end})"), " a");
1303 }
1304
1305 #[test]
1306 fn trim_chars_replaces_whitespace_as_the_set_to_cut() {
1307 assert_eq!(s("trim(\"--a-b--\", {chars: \"-\"})"), "a-b");
1308 assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :start})"), "a+-");
1309 assert_eq!(s("trim(\"-+a+-\", {chars: \"-+\", side: :end})"), "-+a");
1310 assert_eq!(s("trim(\" a \", {chars: \"-\"})"), " a ");
1311 assert_eq!(s("trim(\"aaa\", {chars: \"a\"})"), "");
1312 assert_eq!(s("trim(\"héé\", {chars: \"é\", side: :end})"), "h");
1313 assert_eq!(s("trim(\" a \", {chars: \"\"})"), " a ");
1314 }
1315
1316 #[test]
1317 fn trim_refuses_what_it_does_not_take() {
1318 assert!(refused("trim(\"a\", {sid: :end})").contains("bad_option"));
1319 assert!(refused("trim(\"a\", {sid: :end})").contains("side, chars"));
1320 assert!(refused("trim(\"a\", {side: :middle})").contains("side must be"));
1321 assert!(refused("trim(\"a\", {side: \"end\"})").contains("bad_option"));
1322 assert!(refused("trim(\"a\", {chars: 1})").contains("chars must be text"));
1323 assert!(refused("trim(\"a\", 5)").contains("options must be a map"));
1324 assert!(refused("trim(\"a\", {}, {})").contains("1 to 2"));
1325 assert!(refused("trim()").contains("1 to 2"));
1326 assert!(refused("trim(5)").contains("string"));
1327 }
1328
1329 #[test]
1330 fn trim_is_still_a_value_other_functions_take() {
1331 assert_eq!(s("join(map(trim, [\" a\", \"b \"]), \",\")"), "a,b");
1332 }
1333
1334 #[test]
1335 fn text_index_answers_character_positions() {
1336 assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 0)"), 2);
1337 assert_eq!(i("text_index(\"héllo héllo\", \"llo\", 3)"), 8);
1338 assert_eq!(i("text_index(\"héllo\", \"x\", 0)"), -1);
1339 assert_eq!(i("text_index(\"abc\", \"\", 3)"), 3);
1340 assert_eq!(i("text_index(\"abc\", \"\", 4)"), -1);
1341 assert_eq!(i("text_index(\"abc\", \"a\", -5)"), 0);
1342 assert_eq!(i("text_index(\"\", \"a\", 0)"), -1);
1343 }
1344
1345 #[test]
1346 fn text_last_index_finds_the_last_start_at_or_before_from() {
1347 assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 99)"), 8);
1348 assert_eq!(i("text_last_index(\"héllo héllo\", \"llo\", 7)"), 2);
1349 assert_eq!(i("text_last_index(\"aaa\", \"aa\", 1)"), 1);
1350 assert_eq!(i("text_last_index(\"aaa\", \"aa\", 0)"), 0);
1351 assert_eq!(i("text_last_index(\"abc\", \"x\", 2)"), -1);
1352 assert_eq!(i("text_last_index(\"abc\", \"a\", -1)"), -1);
1353 assert_eq!(i("text_last_index(\"ab\", \"abc\", 0)"), -1);
1354 assert_eq!(i("text_last_index(\"abc\", \"\", 9)"), 3);
1355 }
1356
1357 #[test]
1358 fn replace_and_chars() {
1359 assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
1360 assert_eq!(i("length(chars(\"abc\"))"), 3);
1361 }
1362
1363 #[test]
1366 fn reverse_is_character_wise() {
1367 assert_eq!(s("reverse(\"abc\")"), "cba");
1368 assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
1369 }
1370
1371 #[test]
1372 fn reverse_also_works_on_a_list() {
1373 assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
1374 }
1375
1376 #[test]
1381 fn to_int_is_nil_on_garbage_rather_than_zero() {
1382 assert_eq!(i("to_int(\"42\")"), 42);
1383 assert!(
1384 matches!(eval("to_int(\"banana\")"), Value::Nil),
1385 "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
1386 );
1387 assert!(
1388 matches!(eval("to_int(\"0\")"), Value::Int(0)),
1389 "and a real 0 is still a real 0 — the two must stay distinguishable"
1390 );
1391 }
1392
1393 #[test]
1394 fn to_int_bang_raises_on_garbage() {
1395 assert_eq!(i("to_int!(\"42\")"), 42);
1396 let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
1397 assert!(err.to_string().contains("banana"), "must name it: {err}");
1398 }
1399
1400 #[test]
1401 fn numeric_conversions_and_abs() {
1402 assert_eq!(i("to_int(3.9)"), 3);
1403 assert_eq!(i("abs(0 - 5)"), 5);
1404 assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
1405 assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
1406 }
1407
1408 #[test]
1410 fn a_non_string_argument_is_a_type_error() {
1411 assert!(crate::run("upcase([1, 2])").is_err());
1412 assert!(crate::run("join(\"not a list\", \",\")").is_err());
1413 }
1414}