1use std::sync::Arc;
21
22use tatara_lisp::Span;
23
24use crate::error::{EvalError, Result};
25use crate::value::Value;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum Arity {
30 Exact(usize),
31 AtLeast(usize),
32 Range(usize, usize),
33 Any,
34}
35
36impl Arity {
37 pub fn check(&self, got: usize) -> std::result::Result<(), String> {
39 match *self {
40 Self::Exact(n) if got == n => Ok(()),
41 Self::Exact(n) => Err(format!("expected exactly {n}, got {got}")),
42 Self::AtLeast(n) if got >= n => Ok(()),
43 Self::AtLeast(n) => Err(format!("expected at least {n}, got {got}")),
44 Self::Range(lo, hi) if got >= lo && got <= hi => Ok(()),
45 Self::Range(lo, hi) => Err(format!("expected {lo}..={hi}, got {got}")),
46 Self::Any => Ok(()),
47 }
48 }
49}
50
51pub trait NativeCallable<H>: Send + Sync + 'static {
61 fn call(&self, args: &[Value], host: &mut H, call_span: Span) -> Result<Value>;
62}
63
64impl<H, F> NativeCallable<H> for F
65where
66 F: Fn(&[Value], &mut H, Span) -> Result<Value> + Send + Sync + 'static,
67{
68 fn call(&self, args: &[Value], host: &mut H, call_span: Span) -> Result<Value> {
69 (self)(args, host, call_span)
70 }
71}
72
73pub trait HigherOrderCallable<H>: Send + Sync + 'static {
77 fn call(
78 &self,
79 args: &[Value],
80 host: &mut H,
81 caller: &Caller<H>,
82 call_span: Span,
83 ) -> Result<Value>;
84}
85
86impl<H, F> HigherOrderCallable<H> for F
87where
88 F: Fn(&[Value], &mut H, &Caller<H>, Span) -> Result<Value> + Send + Sync + 'static,
89{
90 fn call(
91 &self,
92 args: &[Value],
93 host: &mut H,
94 caller: &Caller<H>,
95 call_span: Span,
96 ) -> Result<Value> {
97 (self)(args, host, caller, call_span)
98 }
99}
100
101pub struct Caller<'a, H> {
111 pub(crate) registry: &'a FnRegistry<H>,
112 pub(crate) expander: &'a tatara_lisp::SpannedExpander,
113}
114
115impl<'a, H: 'static> Caller<'a, H> {
116 pub fn apply_value(
121 &self,
122 callee: &Value,
123 args: Vec<Value>,
124 host: &mut H,
125 call_span: Span,
126 ) -> Result<Value> {
127 crate::eval::apply_external(callee, args, call_span, self.registry, self.expander, host)
128 }
129
130 pub fn expander(&self) -> &tatara_lisp::SpannedExpander {
133 self.expander
134 }
135
136 pub fn call1(&self, f: &Value, x: Value, host: &mut H, span: Span) -> Result<Value> {
139 self.apply_value(f, vec![x], host, span)
140 }
141
142 pub fn call2(&self, f: &Value, a: Value, b: Value, host: &mut H, span: Span) -> Result<Value> {
144 self.apply_value(f, vec![a, b], host, span)
145 }
146}
147
148pub trait AwaitableCallable<H>: Send + Sync + 'static {
177 fn ready(&self, args: &[Value], host: &H) -> bool;
182
183 fn call(&self, args: &[Value], host: &mut H, call_span: Span) -> Result<Value>;
185}
186
187pub struct Awaitable<R, C> {
189 pub ready: R,
190 pub call: C,
191}
192
193impl<H, R, C> AwaitableCallable<H> for Awaitable<R, C>
194where
195 R: Fn(&[Value], &H) -> bool + Send + Sync + 'static,
196 C: Fn(&[Value], &mut H, Span) -> Result<Value> + Send + Sync + 'static,
197{
198 fn ready(&self, args: &[Value], host: &H) -> bool {
199 (self.ready)(args, host)
200 }
201 fn call(&self, args: &[Value], host: &mut H, call_span: Span) -> Result<Value> {
202 (self.call)(args, host, call_span)
203 }
204}
205
206pub(crate) enum FnImpl<H> {
207 Native(Arc<dyn NativeCallable<H>>),
208 Higher(Arc<dyn HigherOrderCallable<H>>),
209 Awaitable(Arc<dyn AwaitableCallable<H>>),
210}
211
212impl<H> Clone for FnImpl<H> {
213 fn clone(&self) -> Self {
214 match self {
215 Self::Native(f) => Self::Native(Arc::clone(f)),
216 Self::Higher(f) => Self::Higher(Arc::clone(f)),
217 Self::Awaitable(f) => Self::Awaitable(Arc::clone(f)),
218 }
219 }
220}
221
222pub(crate) struct FnRegistry<H> {
224 entries: Vec<FnEntry<H>>,
225}
226
227pub(crate) struct FnEntry<H> {
228 pub name: Arc<str>,
229 #[allow(dead_code)]
232 pub arity: Arity,
233 pub callable: FnImpl<H>,
234}
235
236impl<H> Default for FnRegistry<H> {
237 fn default() -> Self {
238 Self {
239 entries: Vec::new(),
240 }
241 }
242}
243
244impl<H> FnRegistry<H> {
245 pub(crate) fn new() -> Self {
246 Self::default()
247 }
248
249 pub(crate) fn insert(&mut self, entry: FnEntry<H>) {
250 if let Some(slot) = self.entries.iter_mut().find(|e| e.name == entry.name) {
252 *slot = entry;
253 } else {
254 self.entries.push(entry);
255 }
256 }
257
258 pub(crate) fn lookup(&self, name: &str) -> Option<&FnEntry<H>> {
259 self.entries.iter().find(|e| &*e.name == name)
260 }
261}
262
263pub trait FromValue: Sized {
269 fn from_value(v: &Value, at: Span) -> Result<Self>;
270}
271
272impl FromValue for Value {
273 fn from_value(v: &Value, _at: Span) -> Result<Self> {
274 Ok(v.clone())
275 }
276}
277
278impl FromValue for i64 {
279 fn from_value(v: &Value, at: Span) -> Result<Self> {
280 match v {
281 Value::Int(n) => Ok(*n),
282 other => Err(EvalError::type_mismatch("integer", other.type_name(), at)),
283 }
284 }
285}
286
287impl FromValue for f64 {
288 fn from_value(v: &Value, at: Span) -> Result<Self> {
289 match v {
290 Value::Int(n) => Ok(*n as f64),
291 Value::Float(n) => Ok(*n),
292 other => Err(EvalError::type_mismatch("number", other.type_name(), at)),
293 }
294 }
295}
296
297impl FromValue for bool {
298 fn from_value(v: &Value, at: Span) -> Result<Self> {
299 match v {
300 Value::Bool(b) => Ok(*b),
301 other => Err(EvalError::type_mismatch("bool", other.type_name(), at)),
302 }
303 }
304}
305
306impl FromValue for String {
307 fn from_value(v: &Value, at: Span) -> Result<Self> {
308 match v {
309 Value::Str(s) => Ok(s.to_string()),
310 other => Err(EvalError::type_mismatch("string", other.type_name(), at)),
311 }
312 }
313}
314
315impl FromValue for Arc<str> {
316 fn from_value(v: &Value, at: Span) -> Result<Self> {
317 match v {
318 Value::Str(s) => Ok(s.clone()),
319 Value::Symbol(s) => Ok(s.clone()),
320 Value::Keyword(s) => Ok(s.clone()),
321 other => Err(EvalError::type_mismatch(
322 "string/symbol",
323 other.type_name(),
324 at,
325 )),
326 }
327 }
328}
329
330impl FromValue for Vec<Value> {
331 fn from_value(v: &Value, at: Span) -> Result<Self> {
332 match v {
333 Value::Nil => Ok(Vec::new()),
334 Value::List(xs) => Ok(xs.as_ref().clone()),
335 other => Err(EvalError::type_mismatch("list", other.type_name(), at)),
336 }
337 }
338}
339
340impl<T: FromValue> FromValue for Option<T> {
341 fn from_value(v: &Value, at: Span) -> Result<Self> {
342 match v {
343 Value::Nil => Ok(None),
344 other => T::from_value(other, at).map(Some),
345 }
346 }
347}
348
349pub trait IntoValue {
354 fn into_value(self) -> Value;
355}
356
357impl IntoValue for Value {
358 fn into_value(self) -> Value {
359 self
360 }
361}
362
363impl IntoValue for () {
364 fn into_value(self) -> Value {
365 Value::Nil
366 }
367}
368
369impl IntoValue for bool {
370 fn into_value(self) -> Value {
371 Value::Bool(self)
372 }
373}
374
375impl IntoValue for i64 {
376 fn into_value(self) -> Value {
377 Value::Int(self)
378 }
379}
380
381impl IntoValue for f64 {
382 fn into_value(self) -> Value {
383 Value::Float(self)
384 }
385}
386
387impl IntoValue for String {
388 fn into_value(self) -> Value {
389 Value::Str(Arc::from(self))
390 }
391}
392
393impl IntoValue for &str {
394 fn into_value(self) -> Value {
395 Value::Str(Arc::from(self))
396 }
397}
398
399impl IntoValue for Arc<str> {
400 fn into_value(self) -> Value {
401 Value::Str(self)
402 }
403}
404
405impl<T: IntoValue> IntoValue for Option<T> {
406 fn into_value(self) -> Value {
407 match self {
408 None => Value::Nil,
409 Some(x) => x.into_value(),
410 }
411 }
412}
413
414impl<T: IntoValue> IntoValue for Vec<T> {
415 fn into_value(self) -> Value {
416 Value::list(self.into_iter().map(IntoValue::into_value))
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423
424 #[test]
425 fn arity_check() {
426 assert!(Arity::Exact(2).check(2).is_ok());
427 assert!(Arity::Exact(2).check(3).is_err());
428 assert!(Arity::AtLeast(1).check(5).is_ok());
429 assert!(Arity::AtLeast(1).check(0).is_err());
430 assert!(Arity::Range(1, 3).check(2).is_ok());
431 assert!(Arity::Range(1, 3).check(4).is_err());
432 assert!(Arity::Any.check(0).is_ok());
433 assert!(Arity::Any.check(1000).is_ok());
434 }
435
436 #[test]
437 fn from_value_round_trips_primitives() {
438 let sp = Span::synthetic();
439 assert_eq!(i64::from_value(&Value::Int(42), sp).unwrap(), 42);
440 assert_eq!(f64::from_value(&Value::Float(1.5), sp).unwrap(), 1.5);
441 assert!(bool::from_value(&Value::Bool(true), sp).unwrap());
442 assert_eq!(
443 String::from_value(&Value::Str(Arc::from("hi")), sp).unwrap(),
444 "hi"
445 );
446 }
447
448 #[test]
449 fn from_value_int_to_float_coerces() {
450 let sp = Span::synthetic();
451 assert_eq!(f64::from_value(&Value::Int(3), sp).unwrap(), 3.0);
452 }
453
454 #[test]
455 fn from_value_option_nil_is_none() {
456 let sp = Span::synthetic();
457 assert_eq!(
458 <Option<i64> as FromValue>::from_value(&Value::Nil, sp).unwrap(),
459 None
460 );
461 assert_eq!(
462 <Option<i64> as FromValue>::from_value(&Value::Int(7), sp).unwrap(),
463 Some(7)
464 );
465 }
466
467 #[test]
468 fn from_value_type_mismatch_reports_expected_kind() {
469 let sp = Span::synthetic();
470 let err = i64::from_value(&Value::Str(Arc::from("x")), sp).unwrap_err();
471 assert!(matches!(
472 err,
473 EvalError::TypeMismatch {
474 expected: "integer",
475 ..
476 }
477 ));
478 }
479
480 #[test]
481 fn into_value_round_trips() {
482 assert!(matches!(42i64.into_value(), Value::Int(42)));
483 assert!(matches!(true.into_value(), Value::Bool(true)));
484 assert!(matches!(().into_value(), Value::Nil));
485 match String::from("hello").into_value() {
486 Value::Str(s) => assert_eq!(&*s, "hello"),
487 other => panic!("{other:?}"),
488 }
489 }
490
491 #[test]
492 fn into_value_vec_produces_list() {
493 let v: Vec<i64> = vec![1, 2, 3];
494 match v.into_value() {
495 Value::List(xs) => {
496 assert_eq!(xs.len(), 3);
497 assert!(matches!(&xs[0], Value::Int(1)));
498 }
499 other => panic!("{other:?}"),
500 }
501 }
502}