1use tatara_lisp_eval::ffi::Arity;
36use tatara_lisp_eval::{EvalError, Interpreter, Value};
37
38fn as_str(v: &Value, span: tatara_lisp::Span) -> Result<String, EvalError> {
39 match v {
40 Value::Str(s) => Ok(s.to_string()),
41 Value::Symbol(s) | Value::Keyword(s) => Ok(s.to_string()),
44 other => Err(EvalError::type_mismatch(
45 "a string",
46 other.type_name(),
47 span,
48 )),
49 }
50}
51
52fn render(v: &Value) -> String {
54 match v {
55 Value::Nil => String::new(),
56 Value::Bool(b) => b.to_string(),
57 Value::Int(n) => n.to_string(),
58 Value::Float(x) => x.to_string(),
59 Value::Str(s) | Value::Symbol(s) | Value::Keyword(s) => s.to_string(),
60 Value::List(items) => items.iter().map(render).collect::<Vec<_>>().join(" "),
61 other => other.type_name().to_string(),
62 }
63}
64
65fn list(items: Vec<Value>) -> Value {
66 Value::List(std::sync::Arc::new(items))
67}
68
69pub fn install_blue_stdlib<H: 'static>(interp: &mut Interpreter<H>) {
71 interp.register_fn(
76 "length",
77 Arity::Exact(1),
78 |a: &[Value], _h: &mut H, span| match &a[0] {
79 Value::List(items) => Ok(Value::Int(items.len() as i64)),
80 other => Ok(Value::Int(as_str(other, span)?.chars().count() as i64)),
81 },
82 );
83
84 interp.register_fn("to_s", Arity::Exact(1), |a: &[Value], _h: &mut H, _s| {
85 Ok(Value::Str(render(&a[0]).into()))
86 });
87
88 interp.register_fn("upcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
89 Ok(Value::Str(as_str(&a[0], s)?.to_uppercase().into()))
90 });
91
92 interp.register_fn("downcase", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
93 Ok(Value::Str(as_str(&a[0], s)?.to_lowercase().into()))
94 });
95
96 interp.register_fn("trim", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
97 Ok(Value::Str(as_str(&a[0], s)?.trim().into()))
98 });
99
100 interp.register_fn("concat", Arity::Exact(2), |a: &[Value], _h: &mut H, _s| {
105 let mut out = render(&a[0]);
106 out.push_str(&render(&a[1]));
107 Ok(Value::Str(out.into()))
108 });
109
110 interp.register_fn("split", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
111 let text = as_str(&a[0], s)?;
112 let sep = as_str(&a[1], s)?;
113 let parts: Vec<Value> = if sep.is_empty() {
117 text.chars()
118 .map(|c| Value::Str(c.to_string().into()))
119 .collect()
120 } else {
121 text.split(sep.as_str())
122 .map(|p| Value::Str(p.into()))
123 .collect()
124 };
125 Ok(list(parts))
126 });
127
128 interp.register_fn("join", Arity::Exact(2), |a: &[Value], _h: &mut H, s| {
129 let sep = as_str(&a[1], s)?;
130 match &a[0] {
131 Value::List(items) => Ok(Value::Str(
132 items
133 .iter()
134 .map(render)
135 .collect::<Vec<_>>()
136 .join(&sep)
137 .into(),
138 )),
139 other => Err(EvalError::type_mismatch("a list", other.type_name(), s).into()),
140 }
141 });
142
143 interp.register_fn(
144 "contains?",
145 Arity::Exact(2),
146 |a: &[Value], _h: &mut H, s| {
147 Ok(Value::Bool(as_str(&a[0], s)?.contains(&as_str(&a[1], s)?)))
148 },
149 );
150
151 interp.register_fn(
152 "starts_with?",
153 Arity::Exact(2),
154 |a: &[Value], _h: &mut H, s| {
155 Ok(Value::Bool(
156 as_str(&a[0], s)?.starts_with(&as_str(&a[1], s)?),
157 ))
158 },
159 );
160
161 interp.register_fn(
162 "ends_with?",
163 Arity::Exact(2),
164 |a: &[Value], _h: &mut H, s| {
165 Ok(Value::Bool(as_str(&a[0], s)?.ends_with(&as_str(&a[1], s)?)))
166 },
167 );
168
169 interp.register_fn("replace", Arity::Exact(3), |a: &[Value], _h: &mut H, s| {
170 Ok(Value::Str(
171 as_str(&a[0], s)?
172 .replace(&as_str(&a[1], s)?, &as_str(&a[2], s)?)
173 .into(),
174 ))
175 });
176
177 interp.register_fn("reverse", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
178 match &a[0] {
179 Value::List(items) => {
180 let mut v = items.as_ref().clone();
181 v.reverse();
182 Ok(list(v))
183 }
184 other => Ok(Value::Str(
187 as_str(other, s)?.chars().rev().collect::<String>().into(),
188 )),
189 }
190 });
191
192 interp.register_fn("chars", Arity::Exact(1), |a: &[Value], _h: &mut H, s| {
193 Ok(list(
194 as_str(&a[0], s)?
195 .chars()
196 .map(|c| Value::Str(c.to_string().into()))
197 .collect(),
198 ))
199 });
200
201 interp.register_fn(
208 "to_int",
209 Arity::Exact(1),
210 |a: &[Value], _h: &mut H, s| match &a[0] {
211 Value::Int(n) => Ok(Value::Int(*n)),
212 Value::Float(x) => Ok(Value::Int(*x as i64)),
213 other => Ok(as_str(other, s)?
214 .trim()
215 .parse::<i64>()
216 .map_or(Value::Nil, Value::Int)),
217 },
218 );
219
220 interp.register_fn(
221 "to_int!",
222 Arity::Exact(1),
223 |a: &[Value], _h: &mut H, s| match &a[0] {
224 Value::Int(n) => Ok(Value::Int(*n)),
225 Value::Float(x) => Ok(Value::Int(*x as i64)),
226 other => {
227 let text = as_str(other, s)?;
228 text.trim().parse::<i64>().map(Value::Int).map_err(|_| {
229 EvalError::native_fn(
230 "to_int!",
231 "`".to_string() + &text + "` is not an integer",
232 s,
233 )
234 .into()
235 })
236 }
237 },
238 );
239
240 interp.register_fn(
241 "to_float",
242 Arity::Exact(1),
243 |a: &[Value], _h: &mut H, s| match &a[0] {
244 Value::Float(x) => Ok(Value::Float(*x)),
245 Value::Int(n) => Ok(Value::Float(*n as f64)),
246 other => Ok(as_str(other, s)?
247 .trim()
248 .parse::<f64>()
249 .map_or(Value::Nil, Value::Float)),
250 },
251 );
252
253 interp.register_fn(
254 "abs",
255 Arity::Exact(1),
256 |a: &[Value], _h: &mut H, s| match &a[0] {
257 Value::Int(n) => Ok(Value::Int(n.abs())),
258 Value::Float(x) => Ok(Value::Float(x.abs())),
259 other => Err(EvalError::type_mismatch("a number", other.type_name(), s).into()),
260 },
261 );
262
263 interp.register_fn(
284 "range",
285 Arity::Range(1, 3),
286 |a: &[Value], _h: &mut H, s| {
287 let (start, end, step) = match a.len() {
288 1 => (Value::Int(0), a[0].clone(), Value::Int(1)),
289 2 => (a[0].clone(), a[1].clone(), Value::Int(1)),
290 _ => (a[0].clone(), a[1].clone(), a[2].clone()),
291 };
292 range_list(start, &end, &step, s)
293 },
294 );
295}
296
297fn range_num(v: &Value, s: tatara_lisp::Span) -> Result<f64, EvalError> {
299 match v {
300 Value::Int(n) => Ok(*n as f64),
301 Value::Float(x) => Ok(*x),
302 other => Err(EvalError::native_fn(
303 "range",
304 "expected a number, got ".to_string() + other.type_name(),
305 s,
306 )),
307 }
308}
309
310fn range_add(a: &Value, b: &Value, s: tatara_lisp::Span) -> Result<Value, EvalError> {
313 match (a, b) {
314 (Value::Int(x), Value::Int(y)) => x.checked_add(*y).map(Value::Int).ok_or_else(|| {
315 EvalError::native_fn("range", "an element overflowed a 64-bit integer", s)
316 }),
317 _ => Ok(Value::Float(range_num(a, s)? + range_num(b, s)?)),
318 }
319}
320
321fn range_list(
322 start: Value,
323 end: &Value,
324 step: &Value,
325 s: tatara_lisp::Span,
326) -> Result<Value, EvalError> {
327 let end_f = range_num(end, s)?;
328 let step_f = range_num(step, s)?;
329 range_num(&start, s)?;
330 if step_f == 0.0 {
331 return Err(EvalError::native_fn(
332 "range",
333 "a step of zero never reaches the end",
334 s,
335 ));
336 }
337 let mut out = Vec::new();
338 let mut cur = start;
339 loop {
340 let c = range_num(&cur, s)?;
341 if (step_f > 0.0 && c >= end_f) || (step_f < 0.0 && c <= end_f) {
342 break;
343 }
344 let next = range_add(&cur, step, s)?;
345 out.push(cur);
346 cur = next;
347 }
348 Ok(list(out))
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 fn eval(src: &str) -> Value {
356 crate::run(src)
357 .unwrap_or_else(|e| panic!("{src:?}: {e}"))
358 .value
359 }
360
361 fn s(src: &str) -> String {
362 match eval(src) {
363 Value::Str(v) => v.to_string(),
364 other => panic!("{src:?} produced {other:?}"),
365 }
366 }
367
368 fn i(src: &str) -> i64 {
369 match eval(src) {
370 Value::Int(v) => v,
371 other => panic!("{src:?} produced {other:?}"),
372 }
373 }
374
375 fn ints(src: &str) -> Vec<i64> {
376 match eval(src) {
377 Value::List(xs) => xs
378 .iter()
379 .map(|v| match v {
380 Value::Int(n) => *n,
381 other => panic!("{src:?} produced a non-Int element {other:?}"),
382 })
383 .collect(),
384 other => panic!("{src:?} produced {other:?}"),
385 }
386 }
387
388 #[test]
391 fn range_answers_as_the_lisp_definition_did() {
392 assert_eq!(ints("range(5)"), vec![0, 1, 2, 3, 4]);
393 assert_eq!(ints("range(2, 6)"), vec![2, 3, 4, 5]);
394 assert_eq!(ints("range(0, 10, 2)"), vec![0, 2, 4, 6, 8]);
395 assert_eq!(ints("range(10, 0, 0 - 2)"), vec![10, 8, 6, 4, 2]);
396 assert!(ints("range(5, 5)").is_empty());
397 assert!(ints("range(5, 2)").is_empty());
398 assert!(ints("range(0)").is_empty());
399 match eval("range(0, 1, 0.5)") {
401 Value::List(xs) => {
402 assert!(matches!(xs[0], Value::Int(0)), "{xs:?}");
403 assert!(matches!(xs[1], Value::Float(x) if x == 0.5), "{xs:?}");
404 assert_eq!(xs.len(), 2);
405 }
406 other => panic!("{other:?}"),
407 }
408 }
409
410 #[test]
416 fn range_builds_long_lists_without_recursing() {
417 assert_eq!(i("length(range(0, 200000))"), 200_000);
418 assert_eq!(i("nth(199999, range(0, 200000))"), 199_999);
419 }
420
421 #[test]
424 fn range_refuses_a_zero_step_and_a_non_number() {
425 assert!(crate::run("range(0, 5, 0)").is_err());
426 assert!(crate::run("range(0, \"x\")").is_err());
427 }
428
429 #[test]
433 fn length_counts_characters_not_bytes() {
434 assert_eq!(i("length(\"hello\")"), 5);
435 assert_eq!(i("length(\"héllo\")"), 5, "must not be 6");
437 assert_eq!(i("length(\"😀\")"), 1, "must not be 4");
439 }
440
441 #[test]
444 fn a_combining_sequence_counts_scalars_not_graphemes() {
445 assert_eq!(
447 i("length(\"e\\u{301}\")"),
448 2,
449 "blue counts scalar values; Elixir's String.length would say 1"
450 );
451 }
452
453 #[test]
454 fn length_also_works_on_a_list() {
455 assert_eq!(i("length([1, 2, 3])"), 3);
456 }
457
458 #[test]
459 fn case_and_trim() {
460 assert_eq!(s("upcase(\"abc\")"), "ABC");
461 assert_eq!(s("downcase(\"ABC\")"), "abc");
462 assert_eq!(s("trim(\" hi \")"), "hi");
463 assert_eq!(s("upcase(\"é\")"), "É");
465 }
466
467 #[test]
468 fn concat_and_to_s() {
469 assert_eq!(s("concat(\"a\", \"b\")"), "ab");
470 assert_eq!(s("concat(\"n=\", 42)"), "n=42");
471 assert_eq!(s("to_s(42)"), "42");
472 assert_eq!(s("to_s(true)"), "true");
473 }
474
475 #[test]
479 fn plus_is_not_string_concatenation() {
480 assert!(
481 crate::run("\"a\" + \"b\"").is_err(),
482 "`+` must not silently concatenate — use concat"
483 );
484 }
485
486 #[test]
487 fn split_and_join() {
488 assert_eq!(i("length(split(\"a,b,c\", \",\"))"), 3);
489 assert_eq!(s("join(split(\"a,b,c\", \",\"), \"-\")"), "a-b-c");
490 assert_eq!(i("length(split(\"abc\", \"\"))"), 3);
492 }
493
494 #[test]
495 fn predicates() {
496 assert!(matches!(
497 eval("contains?(\"hello\", \"ell\")"),
498 Value::Bool(true)
499 ));
500 assert!(matches!(
501 eval("contains?(\"hello\", \"xyz\")"),
502 Value::Bool(false)
503 ));
504 assert!(matches!(
505 eval("starts_with?(\"hello\", \"he\")"),
506 Value::Bool(true)
507 ));
508 assert!(matches!(
509 eval("ends_with?(\"hello\", \"lo\")"),
510 Value::Bool(true)
511 ));
512 }
513
514 #[test]
515 fn replace_and_chars() {
516 assert_eq!(s("replace(\"a-b-c\", \"-\", \"+\")"), "a+b+c");
517 assert_eq!(i("length(chars(\"abc\"))"), 3);
518 }
519
520 #[test]
523 fn reverse_is_character_wise() {
524 assert_eq!(s("reverse(\"abc\")"), "cba");
525 assert_eq!(s("reverse(\"héllo\")"), "olléh", "must not corrupt the é");
526 }
527
528 #[test]
529 fn reverse_also_works_on_a_list() {
530 assert_eq!(s("join(reverse([1, 2, 3]), \",\")"), "3,2,1");
531 }
532
533 #[test]
538 fn to_int_is_nil_on_garbage_rather_than_zero() {
539 assert_eq!(i("to_int(\"42\")"), 42);
540 assert!(
541 matches!(eval("to_int(\"banana\")"), Value::Nil),
542 "Ruby would say 0 here; a falsy nil cannot be mistaken for a result"
543 );
544 assert!(
545 matches!(eval("to_int(\"0\")"), Value::Int(0)),
546 "and a real 0 is still a real 0 — the two must stay distinguishable"
547 );
548 }
549
550 #[test]
551 fn to_int_bang_raises_on_garbage() {
552 assert_eq!(i("to_int!(\"42\")"), 42);
553 let err = crate::run("to_int!(\"banana\")").expect_err("must raise");
554 assert!(err.to_string().contains("banana"), "must name it: {err}");
555 }
556
557 #[test]
558 fn numeric_conversions_and_abs() {
559 assert_eq!(i("to_int(3.9)"), 3);
560 assert_eq!(i("abs(0 - 5)"), 5);
561 assert!(matches!(eval("to_float(\"1.5\")"), Value::Float(_)));
562 assert!(matches!(eval("to_float(\"nope\")"), Value::Nil));
563 }
564
565 #[test]
567 fn a_non_string_argument_is_a_type_error() {
568 assert!(crate::run("upcase([1, 2])").is_err());
569 assert!(crate::run("join(\"not a list\", \",\")").is_err());
570 }
571}