1use std::any::Any;
9use std::fmt;
10use std::sync::Arc;
11
12use tatara_lisp::{Sexp, Span, Spanned};
13
14use crate::env::Env;
15use crate::ffi::Arity;
16use crate::persist::{List, Map};
17
18#[derive(Clone)]
20pub enum Value {
21 Nil,
22 Bool(bool),
23 Int(i64),
24 Float(f64),
25 Str(Arc<str>),
26 Symbol(Arc<str>),
27 Keyword(Arc<str>),
28 List(Arc<List>),
29 Map(Arc<Map>),
33 Closure(Arc<Closure>),
34 NativeFn(Arc<NativeFn>),
35 Promise(Arc<std::sync::Mutex<PromiseState>>),
41 Error(Arc<ErrorObj>),
46 Sexp(Sexp, Span),
49 Foreign(Arc<dyn Any + Send + Sync>),
53}
54
55#[derive(Debug, Clone)]
60pub struct ErrorObj {
61 pub tag: Arc<str>,
62 pub message: Arc<str>,
63 pub data: Vec<(Value, Value)>,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub enum MapKey {
74 Nil,
75 Bool(bool),
76 Int(i64),
77 Float(u64),
78 Str(Arc<str>),
79 Symbol(Arc<str>),
80 Keyword(Arc<str>),
81}
82
83impl MapKey {
84 pub fn from_value(v: &Value) -> Option<Self> {
88 Some(match v {
89 Value::Nil => Self::Nil,
90 Value::Bool(b) => Self::Bool(*b),
91 Value::Int(n) => Self::Int(*n),
92 Value::Float(n) => Self::Float(n.to_bits()),
93 Value::Str(s) => Self::Str(s.clone()),
94 Value::Symbol(s) => Self::Symbol(s.clone()),
95 Value::Keyword(s) => Self::Keyword(s.clone()),
96 _ => return None,
97 })
98 }
99
100 pub fn to_value(&self) -> Value {
103 match self {
104 Self::Nil => Value::Nil,
105 Self::Bool(b) => Value::Bool(*b),
106 Self::Int(n) => Value::Int(*n),
107 Self::Float(b) => Value::Float(f64::from_bits(*b)),
108 Self::Str(s) => Value::Str(s.clone()),
109 Self::Symbol(s) => Value::Symbol(s.clone()),
110 Self::Keyword(s) => Value::Keyword(s.clone()),
111 }
112 }
113}
114
115impl fmt::Display for MapKey {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 write!(f, "{}", self.to_value())
118 }
119}
120
121pub enum PromiseState {
126 Pending(Arc<Closure>),
127 Forced(Value),
128}
129
130impl fmt::Debug for PromiseState {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 match self {
133 Self::Pending(_) => f.write_str("Pending(…)"),
134 Self::Forced(v) => write!(f, "Forced({v:?})"),
135 }
136 }
137}
138
139pub struct Closure {
141 pub params: Vec<Arc<str>>,
142 pub rest: Option<Arc<str>>,
145 pub body: Vec<Spanned>,
148 pub captured_env: Env,
149 pub source: Span,
150 pub name: Option<Arc<str>>,
153}
154
155#[derive(Clone, Debug)]
160pub struct NativeFn {
161 pub name: Arc<str>,
162 pub arity: Arity,
163}
164
165impl Value {
168 pub fn symbol(s: impl Into<Arc<str>>) -> Self {
169 Self::Symbol(s.into())
170 }
171
172 pub fn keyword(s: impl Into<Arc<str>>) -> Self {
173 Self::Keyword(s.into())
174 }
175
176 pub fn string(s: impl Into<Arc<str>>) -> Self {
177 Self::Str(s.into())
178 }
179
180 pub fn list<I: IntoIterator<Item = Value>>(xs: I) -> Self {
181 Self::List(Arc::new(xs.into_iter().collect()))
182 }
183
184 pub fn map<I: IntoIterator<Item = (MapKey, Value)>>(entries: I) -> Self {
186 Self::Map(Arc::new(entries.into_iter().collect()))
187 }
188
189 pub fn is_truthy(&self) -> bool {
190 !matches!(self, Self::Nil | Self::Bool(false))
191 }
192
193 #[must_use]
217 pub fn is_unique(&self) -> bool {
218 fn solo<T: ?Sized>(a: &Arc<T>) -> bool {
219 Arc::strong_count(a) == 1 && Arc::weak_count(a) == 0
220 }
221 match self {
222 Self::Nil | Self::Bool(_) | Self::Int(_) | Self::Float(_) => true,
223 Self::Str(s) | Self::Symbol(s) | Self::Keyword(s) => solo(s),
224 Self::List(xs) => solo(xs),
225 Self::Map(m) => solo(m),
226 Self::Closure(c) => solo(c),
227 Self::NativeFn(f) => solo(f),
228 Self::Promise(p) => solo(p),
229 Self::Error(e) => solo(e),
230 Self::Sexp(..) => false,
231 Self::Foreign(f) => solo(f),
232 }
233 }
234
235 pub fn type_name(&self) -> &'static str {
237 match self {
238 Self::Nil => "nil",
239 Self::Bool(_) => "bool",
240 Self::Int(_) => "int",
241 Self::Float(_) => "float",
242 Self::Str(_) => "string",
243 Self::Symbol(_) => "symbol",
244 Self::Keyword(_) => "keyword",
245 Self::List(_) => "list",
246 Self::Map(_) => "map",
247 Self::Closure(_) => "closure",
248 Self::NativeFn(_) => "native-fn",
249 Self::Promise(_) => "promise",
250 Self::Error(_) => "error",
251 Self::Sexp(..) => "sexp",
252 Self::Foreign(_) => "foreign",
253 }
254 }
255}
256
257impl fmt::Debug for Value {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 match self {
262 Self::Nil => f.write_str("Nil"),
263 Self::Bool(b) => write!(f, "Bool({b})"),
264 Self::Int(n) => write!(f, "Int({n})"),
265 Self::Float(n) => write!(f, "Float({n})"),
266 Self::Str(s) => write!(f, "Str({s:?})"),
267 Self::Symbol(s) => write!(f, "Symbol({s})"),
268 Self::Keyword(s) => write!(f, "Keyword(:{s})"),
269 Self::List(xs) => f.debug_list().entries(xs.iter()).finish(),
270 Self::Map(m) => write!(f, "Map({} entries)", m.len()),
271 Self::Closure(_) => f.write_str("Closure(…)"),
272 Self::NativeFn(n) => write!(f, "NativeFn({})", n.name),
273 Self::Promise(_) => f.write_str("Promise(…)"),
274 Self::Error(e) => write!(f, "Error({}: {})", e.tag, e.message),
275 Self::Sexp(s, sp) => write!(f, "Sexp({s} @ {sp})"),
276 Self::Foreign(_) => f.write_str("Foreign(…)"),
277 }
278 }
279}
280
281impl fmt::Display for Value {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 match self {
284 Self::Nil => f.write_str("()"),
285 Self::Bool(true) => f.write_str("#t"),
286 Self::Bool(false) => f.write_str("#f"),
287 Self::Int(n) => write!(f, "{n}"),
288 Self::Float(n) => write!(f, "{n}"),
289 Self::Str(s) => write!(f, "{s:?}"),
290 Self::Symbol(s) => f.write_str(s),
291 Self::Keyword(s) => write!(f, ":{s}"),
292 Self::List(xs) => {
293 f.write_str("(")?;
294 for (i, v) in xs.iter().enumerate() {
295 if i > 0 {
296 f.write_str(" ")?;
297 }
298 write!(f, "{v}")?;
299 }
300 f.write_str(")")
301 }
302 Self::Map(m) => {
303 f.write_str("{")?;
307 for (i, (k, v)) in m.iter().enumerate() {
308 if i > 0 {
309 f.write_str(", ")?;
310 }
311 write!(f, "{k} {v}")?;
312 }
313 f.write_str("}")
314 }
315 Self::Closure(c) => {
316 write!(f, "#<closure")?;
317 if !c.params.is_empty() {
318 write!(f, " ({}", c.params.join(" "))?;
319 if let Some(rest) = &c.rest {
320 write!(f, " . {rest}")?;
321 }
322 write!(f, ")")?;
323 }
324 write!(f, ">")
325 }
326 Self::NativeFn(n) => write!(f, "#<native {}>", n.name),
327 Self::Promise(p) => {
328 let state = p.lock().unwrap();
329 match &*state {
330 PromiseState::Pending(_) => f.write_str("#<promise pending>"),
331 PromiseState::Forced(v) => write!(f, "#<promise {v}>"),
332 }
333 }
334 Self::Error(e) => {
335 write!(f, "#<error :{} {:?}", e.tag, e.message.as_ref())?;
336 if !e.data.is_empty() {
337 f.write_str(" {")?;
338 for (i, (k, v)) in e.data.iter().enumerate() {
339 if i > 0 {
340 f.write_str(" ")?;
341 }
342 write!(f, "{k} {v}")?;
343 }
344 f.write_str("}")?;
345 }
346 f.write_str(">")
347 }
348 Self::Sexp(s, _) => write!(f, "'{s}"),
349 Self::Foreign(_) => f.write_str("#<foreign>"),
350 }
351 }
352}
353
354impl From<bool> for Value {
357 fn from(b: bool) -> Self {
358 Self::Bool(b)
359 }
360}
361
362impl From<i64> for Value {
363 fn from(n: i64) -> Self {
364 Self::Int(n)
365 }
366}
367
368impl From<f64> for Value {
369 fn from(n: f64) -> Self {
370 Self::Float(n)
371 }
372}
373
374impl From<String> for Value {
375 fn from(s: String) -> Self {
376 Self::Str(Arc::from(s))
377 }
378}
379
380impl From<&str> for Value {
381 fn from(s: &str) -> Self {
382 Self::Str(Arc::from(s))
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn truthiness() {
392 assert!(Value::Bool(true).is_truthy());
393 assert!(!Value::Bool(false).is_truthy());
394 assert!(!Value::Nil.is_truthy());
395 assert!(Value::Int(0).is_truthy(), "zero is truthy (Scheme-ish)");
396 assert!(Value::list(std::iter::empty::<Value>()).is_truthy());
397 }
398
399 #[test]
400 fn display_primitives() {
401 assert_eq!(Value::Int(42).to_string(), "42");
402 assert_eq!(Value::Bool(true).to_string(), "#t");
403 assert_eq!(Value::Bool(false).to_string(), "#f");
404 assert_eq!(Value::symbol("foo").to_string(), "foo");
405 assert_eq!(Value::keyword("k").to_string(), ":k");
406 assert_eq!(Value::Nil.to_string(), "()");
407 }
408
409 #[test]
410 fn display_list() {
411 let v = Value::list([Value::Int(1), Value::Int(2), Value::Int(3)]);
412 assert_eq!(v.to_string(), "(1 2 3)");
413 }
414
415 #[test]
416 fn type_names() {
417 assert_eq!(Value::Int(0).type_name(), "int");
418 assert_eq!(Value::Str(Arc::from("x")).type_name(), "string");
419 assert_eq!(Value::Nil.type_name(), "nil");
420 }
421}