blots_core/
values.rs

1use anyhow::{Result, anyhow};
2use indexmap::IndexMap;
3use serde::{Deserialize, Serialize};
4use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc};
5
6use crate::{
7    ast::Expr,
8    functions::BuiltInFunction,
9    heap::{
10        Heap, HeapPointer, HeapValue, IterablePointer, LambdaPointer, ListPointer, RecordPointer,
11        StringPointer,
12    },
13};
14
15#[derive(Debug)]
16pub enum FunctionArity {
17    Exact(usize),
18    AtLeast(usize),
19    Between(usize, usize),
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
23pub enum LambdaArg {
24    Required(String),
25    Optional(String),
26    Rest(String),
27}
28
29impl LambdaArg {
30    pub fn get_name(&self) -> &str {
31        match self {
32            LambdaArg::Required(name) => name,
33            LambdaArg::Optional(name) => name,
34            LambdaArg::Rest(name) => name,
35        }
36    }
37
38    pub fn is_required(&self) -> bool {
39        matches!(self, LambdaArg::Required(_))
40    }
41
42    pub fn is_optional(&self) -> bool {
43        matches!(self, LambdaArg::Optional(_))
44    }
45
46    pub fn is_rest(&self) -> bool {
47        matches!(self, LambdaArg::Rest(_))
48    }
49
50    pub fn as_required(&self) -> Result<&str> {
51        match self {
52            LambdaArg::Required(name) => Ok(name),
53            _ => Err(anyhow!(
54                "expected a required argument, but got a {} one",
55                self.get_name()
56            )),
57        }
58    }
59
60    pub fn as_optional(&self) -> Result<&str> {
61        match self {
62            LambdaArg::Optional(name) => Ok(name),
63            _ => Err(anyhow!(
64                "expected an optional argument, but got a {} one",
65                self.get_name()
66            )),
67        }
68    }
69
70    pub fn as_rest(&self) -> Result<&str> {
71        match self {
72            LambdaArg::Rest(name) => Ok(name),
73            _ => Err(anyhow!(
74                "expected a rest argument, but got a {} one",
75                self.get_name()
76            )),
77        }
78    }
79}
80
81impl Display for LambdaArg {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        match self {
84            LambdaArg::Required(name) => write!(f, "{}", name),
85            LambdaArg::Optional(name) => write!(f, "{}?", name),
86            LambdaArg::Rest(name) => write!(f, "...{}", name),
87        }
88    }
89}
90
91#[derive(Debug, Clone, PartialEq)]
92pub struct LambdaDef {
93    pub name: Option<String>,
94    pub args: Vec<LambdaArg>,
95    pub body: Expr,
96    pub scope: HashMap<String, Value>,
97}
98
99impl LambdaDef {
100    pub fn set_name(&mut self, name: String, _value: Value) {
101        self.name = Some(name.clone());
102    }
103
104    pub fn get_arity(&self) -> FunctionArity {
105        let has_rest = self.args.iter().any(|arg| arg.is_rest());
106        let min = self.args.iter().filter(|arg| arg.is_required()).count();
107        let max = self.args.len();
108
109        if has_rest {
110            FunctionArity::AtLeast(min)
111        } else if min == max {
112            FunctionArity::Exact(min)
113        } else {
114            FunctionArity::Between(min, max)
115        }
116    }
117}
118
119impl PartialOrd for LambdaDef {
120    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
121        if self.args > other.args {
122            Some(std::cmp::Ordering::Greater)
123        } else if self.args < other.args {
124            Some(std::cmp::Ordering::Less)
125        } else {
126            Some(std::cmp::Ordering::Equal)
127        }
128    }
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
132pub struct SerializableLambdaDef {
133    pub name: Option<String>,
134    pub args: Vec<LambdaArg>,
135    pub body: String,
136    pub scope: Option<IndexMap<String, SerializableValue>>,
137}
138
139pub struct WithHeap<'h, T> {
140    pub value: &'h T,
141    pub heap: Rc<RefCell<Heap>>,
142}
143
144#[derive(Debug, Copy, Clone, PartialEq)]
145pub enum ReifiedIterableValue<'h> {
146    List(&'h Vec<Value>),
147    String(&'h String),
148    Record(&'h IndexMap<String, Value>),
149}
150
151#[derive(Debug, Clone, PartialEq)]
152pub enum ReifiedIterableValueType {
153    List,
154    String,
155    Record,
156}
157
158impl<'h> ReifiedIterableValue<'h> {
159    pub fn with_heap(&'h self, heap: Rc<RefCell<Heap>>) -> WithHeap<'h, ReifiedIterableValue<'h>> {
160        WithHeap { value: self, heap }
161    }
162
163    pub fn get_type(&self) -> ReifiedIterableValueType {
164        match self {
165            ReifiedIterableValue::List(_) => ReifiedIterableValueType::List,
166            ReifiedIterableValue::String(_) => ReifiedIterableValueType::String,
167            ReifiedIterableValue::Record(_) => ReifiedIterableValueType::Record,
168        }
169    }
170}
171
172impl<'h> IntoIterator for WithHeap<'h, ReifiedIterableValue<'h>> {
173    type Item = Value;
174    type IntoIter = std::vec::IntoIter<Self::Item>;
175
176    fn into_iter(self) -> Self::IntoIter {
177        match self.value {
178            // Yields an iterator over the values in the list.
179            ReifiedIterableValue::List(l) => (*l).clone().into_iter(),
180            // Yields an iterator over the characters in the string.
181            ReifiedIterableValue::String(s) => s
182                .chars()
183                .map(|c| self.heap.borrow_mut().insert_string(c.to_string()))
184                .collect::<Vec<Value>>()
185                .into_iter(),
186            // Yields an iterator over the [key, value] pairs of the record.
187            ReifiedIterableValue::Record(r) => r
188                .into_iter()
189                .map(|(k, v)| {
190                    let list = vec![self.heap.borrow_mut().insert_string(k.to_string()), *v];
191                    self.heap.borrow_mut().insert_list(list)
192                })
193                .collect::<Vec<Value>>()
194                .into_iter(),
195        }
196    }
197}
198
199impl<'h> IntoIterator for WithHeap<'h, ReifiedValue<'h>> {
200    type Item = Value;
201    type IntoIter = std::vec::IntoIter<Self::Item>;
202
203    fn into_iter(self) -> Self::IntoIter {
204        match self.value {
205            ReifiedValue::Spread(iterable, _) => iterable.with_heap(self.heap).into_iter(),
206            _ => vec![(*self.value).into()].into_iter(),
207        }
208    }
209}
210
211#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
212pub enum ValueType {
213    Number,
214    List,
215    Spread,
216    Bool,
217    Lambda,
218    BuiltIn,
219    String,
220    Record,
221    Null,
222}
223
224impl Display for ValueType {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        match self {
227            ValueType::Number => write!(f, "number"),
228            ValueType::List => write!(f, "list"),
229            ValueType::Spread => write!(f, "spread"),
230            ValueType::Bool => write!(f, "boolean"),
231            ValueType::Lambda => write!(f, "function"),
232            ValueType::BuiltIn => write!(f, "built-in function"),
233            ValueType::String => write!(f, "string"),
234            ValueType::Record => write!(f, "record"),
235            ValueType::Null => write!(f, "null"),
236        }
237    }
238}
239
240/// A value, after it has been "reified" (borrowed) from a pointer.
241#[derive(Debug, Copy, Clone, PartialEq)]
242pub enum ReifiedValue<'h> {
243    /// A number is a floating-point value.
244    Number(f64),
245    /// A boolean value is either true or false.
246    Bool(bool),
247    /// A null value represents the absence of a value.
248    Null,
249    /// A list is a sequence of values.
250    List(&'h Vec<Value>, ListPointer),
251    /// A string is a sequence of characters.
252    String(&'h str, StringPointer),
253    /// A record is a collection of key-value pairs.
254    Record(&'h IndexMap<String, Value>, RecordPointer),
255    /// A lambda is a function definition.
256    Lambda(&'h LambdaDef, LambdaPointer),
257    /// A spread value is "spread" into its container when it is used in a list, record, or function call. (internal only)
258    Spread(ReifiedIterableValue<'h>, IterablePointer),
259    /// A built-in function is a function that is implemented in Rust.
260    BuiltIn(BuiltInFunction),
261}
262
263impl<'h> ReifiedValue<'h> {
264    pub fn with_heap(&'h self, heap: Rc<RefCell<Heap>>) -> WithHeap<'h, ReifiedValue<'h>> {
265        WithHeap { value: self, heap }
266    }
267}
268
269impl From<ReifiedValue<'_>> for Value {
270    fn from(value: ReifiedValue) -> Self {
271        match value {
272            ReifiedValue::Number(n) => Value::Number(n),
273            ReifiedValue::Bool(b) => Value::Bool(b),
274            ReifiedValue::Null => Value::Null,
275            ReifiedValue::List(_, p) => Value::List(p),
276            ReifiedValue::String(_, p) => Value::String(p),
277            ReifiedValue::Record(_, p) => Value::Record(p),
278            ReifiedValue::Lambda(_, p) => Value::Lambda(p),
279            ReifiedValue::Spread(_, p) => Value::Spread(p),
280            ReifiedValue::BuiltIn(id) => Value::BuiltIn(id),
281        }
282    }
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
286pub enum SerializableIterableValue {
287    List(Vec<SerializableValue>),
288    String(String),
289    Record(IndexMap<String, SerializableValue>),
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
293pub enum SerializableValue {
294    Number(f64),
295    Bool(bool),
296    Null,
297    List(Vec<SerializableValue>),
298    String(String),
299    Record(IndexMap<String, SerializableValue>),
300    Lambda(SerializableLambdaDef),
301    BuiltIn(String),
302}
303
304impl SerializableValue {
305    /// Convert from serde_json::Value to SerializableValue
306    pub fn from_json(value: &serde_json::Value) -> SerializableValue {
307        match value {
308            serde_json::Value::Number(n) => SerializableValue::Number(n.as_f64().unwrap_or(0.0)),
309            serde_json::Value::Bool(b) => SerializableValue::Bool(*b),
310            serde_json::Value::Null => SerializableValue::Null,
311            serde_json::Value::String(s) => SerializableValue::String(s.clone()),
312            serde_json::Value::Array(arr) => {
313                SerializableValue::List(arr.iter().map(Self::from_json).collect())
314            }
315            serde_json::Value::Object(obj) => {
316                let map: IndexMap<String, SerializableValue> = obj
317                    .iter()
318                    .map(|(k, v)| (k.clone(), Self::from_json(v)))
319                    .collect();
320                SerializableValue::Record(map)
321            }
322        }
323    }
324
325    /// Convert SerializableValue to clean serde_json::Value
326    pub fn to_json(&self) -> serde_json::Value {
327        match self {
328            SerializableValue::Number(n) => serde_json::Value::Number(
329                serde_json::Number::from_f64(*n).unwrap_or_else(|| serde_json::Number::from(0)),
330            ),
331            SerializableValue::Bool(b) => serde_json::Value::Bool(*b),
332            SerializableValue::Null => serde_json::Value::Null,
333            SerializableValue::String(s) => serde_json::Value::String(s.clone()),
334            SerializableValue::List(items) => {
335                serde_json::Value::Array(items.iter().map(|v| v.to_json()).collect())
336            }
337            SerializableValue::Record(fields) => {
338                let map: serde_json::Map<String, serde_json::Value> = fields
339                    .iter()
340                    .map(|(k, v)| (k.clone(), v.to_json()))
341                    .collect();
342                serde_json::Value::Object(map)
343            }
344            SerializableValue::Lambda(_) => serde_json::Value::String("<function>".to_string()),
345            SerializableValue::BuiltIn(name) => {
346                serde_json::Value::String(format!("<builtin: {}>", name))
347            }
348        }
349    }
350
351    pub fn from_value(value: &Value, heap: &Heap) -> Result<SerializableValue> {
352        match value {
353            Value::Number(n) => Ok(SerializableValue::Number(*n)),
354            Value::Bool(b) => Ok(SerializableValue::Bool(*b)),
355            Value::Null => Ok(SerializableValue::Null),
356            Value::List(p) => {
357                let list = p.reify(heap).as_list()?;
358                let serialized_list = list
359                    .iter()
360                    .map(|v| SerializableValue::from_value(v, heap))
361                    .collect::<Result<Vec<SerializableValue>>>()?;
362                Ok(SerializableValue::List(serialized_list))
363            }
364            Value::String(p) => {
365                let string = p.reify(heap).as_string()?;
366                Ok(SerializableValue::String(string.to_string()))
367            }
368            Value::Record(p) => {
369                let record = p.reify(heap).as_record()?;
370                let serialized_record = record
371                    .iter()
372                    .map(|(k, v)| Ok((k.to_string(), SerializableValue::from_value(v, heap)?)))
373                    .collect::<Result<IndexMap<String, SerializableValue>>>()?;
374                Ok(SerializableValue::Record(serialized_record))
375            }
376            Value::Lambda(p) => {
377                let lambda = p.reify(heap).as_lambda()?;
378                Ok(SerializableValue::Lambda(SerializableLambdaDef {
379                    name: lambda.name.clone(),
380                    args: lambda.args.clone(),
381                    body: crate::ast_to_source::expr_to_source(&lambda.body),
382                    scope: Some(
383                        lambda
384                            .scope
385                            .clone()
386                            .into_iter()
387                            .map(|(k, v)| SerializableValue::from_value(&v, heap).map(|sv| (k, sv)))
388                            .collect::<Result<IndexMap<String, SerializableValue>>>()?,
389                    ),
390                }))
391            }
392            Value::BuiltIn(built_in) => Ok(SerializableValue::BuiltIn(built_in.name().to_string())),
393            Value::Spread(_) => Err(anyhow!("cannot serialize a spread value")),
394        }
395    }
396
397    pub fn to_value(&self, heap: &mut Heap) -> Result<Value> {
398        match self {
399            SerializableValue::Number(n) => Ok(Value::Number(*n)),
400            SerializableValue::Bool(b) => Ok(Value::Bool(*b)),
401            SerializableValue::Null => Ok(Value::Null),
402            SerializableValue::List(list) => {
403                let deserialized_list = list
404                    .iter()
405                    .map(|v| SerializableValue::to_value(v, heap))
406                    .collect::<Result<Vec<Value>>>()?;
407
408                Ok(heap.insert_list(deserialized_list))
409            }
410            SerializableValue::String(s) => Ok(heap.insert_string(s.to_string())),
411            SerializableValue::Record(record) => {
412                let deserialized_record = record
413                    .iter()
414                    .map(|(k, v)| Ok((k.to_string(), SerializableValue::to_value(v, heap)?)))
415                    .collect::<Result<IndexMap<String, Value>>>()?;
416                Ok(heap.insert_record(deserialized_record))
417            }
418            SerializableValue::Lambda(s_lambda) => {
419                let scope = if let Some(scope) = s_lambda.scope.clone() {
420                    scope
421                        .iter()
422                        .map(|(k, v)| Ok((k.to_string(), SerializableValue::to_value(v, heap)?)))
423                        .collect::<Result<HashMap<String, Value>>>()?
424                } else {
425                    HashMap::new()
426                };
427
428                // For now, parse the body string back to AST
429                // In a real implementation, we'd want to serialize/deserialize the AST properly
430                let body_ast = crate::expressions::pairs_to_expr(
431                    crate::parser::get_pairs(&s_lambda.body)?
432                        .next()
433                        .unwrap()
434                        .into_inner(),
435                )?;
436
437                let lambda = LambdaDef {
438                    name: s_lambda.name.clone(),
439                    args: s_lambda.args.clone(),
440                    body: body_ast,
441                    scope,
442                };
443
444                Ok(heap.insert_lambda(lambda))
445            }
446            SerializableValue::BuiltIn(ident) => BuiltInFunction::from_ident(ident)
447                .ok_or(anyhow!("built-in function with ident {} not found", ident))
448                .map(Value::BuiltIn),
449        }
450    }
451}
452
453#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
454pub enum PrimitiveValue {
455    Number(f64),
456    Bool(bool),
457    Null,
458}
459
460impl From<PrimitiveValue> for Value {
461    fn from(val: PrimitiveValue) -> Self {
462        match val {
463            PrimitiveValue::Number(n) => Value::Number(n),
464            PrimitiveValue::Bool(b) => Value::Bool(b),
465            PrimitiveValue::Null => Value::Null,
466        }
467    }
468}
469
470impl From<PrimitiveValue> for SerializableValue {
471    fn from(val: PrimitiveValue) -> Self {
472        match val {
473            PrimitiveValue::Number(n) => SerializableValue::Number(n),
474            PrimitiveValue::Bool(b) => SerializableValue::Bool(b),
475            PrimitiveValue::Null => SerializableValue::Null,
476        }
477    }
478}
479
480#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
481pub enum Value {
482    /// A number is a floating-point value.
483    Number(f64),
484    /// A boolean value is either true or false.
485    Bool(bool),
486    /// A null value represents the absence of a value.
487    Null,
488    /// A list is a sequence of values.
489    List(ListPointer),
490    /// A string is a sequence of characters.
491    String(StringPointer),
492    /// A record is a collection of key-value pairs.
493    Record(RecordPointer),
494    /// A lambda is a function definition.
495    Lambda(LambdaPointer),
496    /// A spread value is "spread" into its container when it is used in a list, record, or function call. (internal only)
497    Spread(IterablePointer),
498    /// A built-in function is a function that is implemented in Rust.
499    BuiltIn(BuiltInFunction),
500}
501
502impl Value {
503    /// Compare two values for equality by their actual content, not by reference
504    pub fn equals(&self, other: &Value, heap: &Heap) -> Result<bool> {
505        match (self, other) {
506            // Primitive types - compare directly
507            (Value::Number(a), Value::Number(b)) => Ok(a == b),
508            (Value::Bool(a), Value::Bool(b)) => Ok(a == b),
509            (Value::Null, Value::Null) => Ok(true),
510
511            // String comparison - compare content
512            (Value::String(a_ptr), Value::String(b_ptr)) => {
513                let a_str = a_ptr.reify(heap).as_string()?;
514                let b_str = b_ptr.reify(heap).as_string()?;
515                Ok(a_str == b_str)
516            }
517
518            // List comparison - compare elements recursively
519            (Value::List(a_ptr), Value::List(b_ptr)) => {
520                let a_list = a_ptr.reify(heap).as_list()?;
521                let b_list = b_ptr.reify(heap).as_list()?;
522
523                if a_list.len() != b_list.len() {
524                    return Ok(false);
525                }
526
527                for (a_elem, b_elem) in a_list.iter().zip(b_list.iter()) {
528                    if !a_elem.equals(b_elem, heap)? {
529                        return Ok(false);
530                    }
531                }
532                Ok(true)
533            }
534
535            // Record comparison - compare keys and values
536            (Value::Record(a_ptr), Value::Record(b_ptr)) => {
537                let a_record = a_ptr.reify(heap).as_record()?;
538                let b_record = b_ptr.reify(heap).as_record()?;
539
540                if a_record.len() != b_record.len() {
541                    return Ok(false);
542                }
543
544                for (key, a_value) in a_record.iter() {
545                    match b_record.get(key) {
546                        Some(b_value) => {
547                            if !a_value.equals(b_value, heap)? {
548                                return Ok(false);
549                            }
550                        }
551                        None => return Ok(false),
552                    }
553                }
554                Ok(true)
555            }
556
557            // Lambda comparison - compare by structure (AST equality)
558            (Value::Lambda(a_ptr), Value::Lambda(b_ptr)) => {
559                let a_lambda = a_ptr.reify(heap).as_lambda()?;
560                let b_lambda = b_ptr.reify(heap).as_lambda()?;
561
562                // Compare argument lists
563                if a_lambda.args != b_lambda.args {
564                    return Ok(false);
565                }
566
567                // Compare AST bodies
568                if a_lambda.body != b_lambda.body {
569                    return Ok(false);
570                }
571
572                // Note: We don't compare scopes because two functions with the same
573                // definition but different closures would have different behavior
574                // For now, we only compare structure, not captured variables
575                Ok(true)
576            }
577
578            // Built-in functions - compare by ID
579            (Value::BuiltIn(a), Value::BuiltIn(b)) => Ok(a == b),
580
581            // Spread values - compare the underlying iterable
582            (Value::Spread(a_ptr), Value::Spread(b_ptr)) => match (a_ptr, b_ptr) {
583                (IterablePointer::List(a), IterablePointer::List(b)) => {
584                    Value::List(*a).equals(&Value::List(*b), heap)
585                }
586                (IterablePointer::String(a), IterablePointer::String(b)) => {
587                    Value::String(*a).equals(&Value::String(*b), heap)
588                }
589                (IterablePointer::Record(a), IterablePointer::Record(b)) => {
590                    Value::Record(*a).equals(&Value::Record(*b), heap)
591                }
592                _ => Ok(false),
593            },
594
595            // Different types are never equal
596            _ => Ok(false),
597        }
598    }
599
600    /// Compare two values for ordering
601    pub fn compare(&self, other: &Value, heap: &Heap) -> Result<Option<std::cmp::Ordering>> {
602        match (self, other) {
603            // Numbers have natural ordering
604            (Value::Number(a), Value::Number(b)) => Ok(a.partial_cmp(b)),
605
606            // Booleans: false < true
607            (Value::Bool(a), Value::Bool(b)) => Ok(a.partial_cmp(b)),
608
609            // Strings compare lexicographically
610            (Value::String(a_ptr), Value::String(b_ptr)) => {
611                let a_str = a_ptr.reify(heap).as_string()?;
612                let b_str = b_ptr.reify(heap).as_string()?;
613                Ok(a_str.partial_cmp(b_str))
614            }
615
616            // Lists compare lexicographically
617            (Value::List(a_ptr), Value::List(b_ptr)) => {
618                let a_list = a_ptr.reify(heap).as_list()?;
619                let b_list = b_ptr.reify(heap).as_list()?;
620
621                for (a_elem, b_elem) in a_list.iter().zip(b_list.iter()) {
622                    match a_elem.compare(b_elem, heap)? {
623                        Some(std::cmp::Ordering::Equal) => continue,
624                        other => return Ok(other),
625                    }
626                }
627
628                // If all compared elements are equal, compare lengths
629                Ok(a_list.len().partial_cmp(&b_list.len()))
630            }
631
632            // Other types don't have a natural ordering
633            _ => Ok(None),
634        }
635    }
636
637    pub fn get_type(&self) -> ValueType {
638        match self {
639            Value::Number(_) => ValueType::Number,
640            Value::List(_) => ValueType::List,
641            Value::Spread(_) => ValueType::Spread,
642            Value::Bool(_) => ValueType::Bool,
643            Value::Lambda(_) => ValueType::Lambda,
644            Value::String(_) => ValueType::String,
645            Value::Null => ValueType::Null,
646            Value::BuiltIn(_) => ValueType::BuiltIn,
647            Value::Record(_) => ValueType::Record,
648        }
649    }
650
651    pub fn is_number(&self) -> bool {
652        matches!(self, Value::Number(_))
653    }
654
655    pub fn is_list(&self) -> bool {
656        matches!(self, Value::List(_))
657    }
658
659    pub fn is_spread(&self) -> bool {
660        matches!(self, Value::Spread(_))
661    }
662
663    pub fn is_bool(&self) -> bool {
664        matches!(self, Value::Bool(_))
665    }
666
667    pub fn is_lambda(&self) -> bool {
668        matches!(self, Value::Lambda(_))
669    }
670
671    pub fn is_string(&self) -> bool {
672        matches!(self, Value::String(_))
673    }
674
675    pub fn is_null(&self) -> bool {
676        matches!(self, Value::Null)
677    }
678
679    pub fn is_built_in(&self) -> bool {
680        matches!(self, Value::BuiltIn(_))
681    }
682
683    pub fn is_callable(&self) -> bool {
684        matches!(self, Value::BuiltIn(_) | Value::Lambda(_))
685    }
686
687    pub fn as_number(&self) -> Result<f64> {
688        match self {
689            Value::Number(n) => Ok(*n),
690            _ => Err(anyhow!("expected a number, but got a {}", self.get_type())),
691        }
692    }
693
694    pub fn as_list<'h>(&self, heap: &'h Heap) -> Result<&'h Vec<Value>> {
695        match self {
696            Value::List(l) => l.reify(heap).as_list(),
697            _ => Err(anyhow!("expected a list, but got a {}", self.get_type())),
698        }
699    }
700
701    pub fn as_spread<'h>(&self, heap: &'h Heap) -> Result<&'h HeapValue> {
702        match self {
703            Value::Spread(v) => Ok(v.reify(heap)),
704            _ => Err(anyhow!("expected a spread, but got a {}", self.get_type())),
705        }
706    }
707
708    pub fn as_bool(&self) -> Result<bool> {
709        match self {
710            Value::Bool(b) => Ok(*b),
711            _ => Err(anyhow!("expected a boolean, but got a {}", self.get_type())),
712        }
713    }
714
715    pub fn as_lambda<'h>(&self, heap: &'h Heap) -> Result<&'h LambdaDef> {
716        match self {
717            Value::Lambda(l) => l.reify(heap).as_lambda(),
718            _ => Err(anyhow!("expected a lambda, but got a {}", self.get_type())),
719        }
720    }
721
722    pub fn as_string<'h>(&self, heap: &'h Heap) -> Result<&'h str> {
723        match self {
724            Value::String(p) => p.reify(heap).as_string(),
725            _ => Err(anyhow!("expected a string, but got a {}", self.get_type())),
726        }
727    }
728
729    pub fn as_null(&self) -> Result<()> {
730        match self {
731            Value::Null => Ok(()),
732            _ => Err(anyhow!("expected a null, but got a {}", self.get_type())),
733        }
734    }
735
736    pub fn as_built_in(&self) -> Result<&str> {
737        match self {
738            Value::BuiltIn(built_in) => Ok(built_in.name()),
739            _ => Err(anyhow!(
740                "expected a built-in function, but got a {}",
741                self.get_type()
742            )),
743        }
744    }
745
746    pub fn as_record<'h>(&self, heap: &'h Heap) -> Result<&'h IndexMap<String, Value>> {
747        match self {
748            Value::Record(r) => r.reify(heap).as_record(),
749            _ => Err(anyhow!("expected a record, but got a {}", self.get_type())),
750        }
751    }
752
753    pub fn as_list_pointer(&self) -> Result<ListPointer> {
754        match self {
755            Value::List(p) => Ok(*p),
756            _ => Err(anyhow!("expected a list, but got a {}", self.get_type())),
757        }
758    }
759
760    pub fn as_string_pointer(&self) -> Result<StringPointer> {
761        match self {
762            Value::String(p) => Ok(*p),
763            _ => Err(anyhow!("expected a string, but got a {}", self.get_type())),
764        }
765    }
766
767    pub fn as_record_pointer(&self) -> Result<RecordPointer> {
768        match self {
769            Value::Record(p) => Ok(*p),
770            _ => Err(anyhow!("expected a record, but got a {}", self.get_type())),
771        }
772    }
773
774    pub fn as_lambda_pointer(&self) -> Result<LambdaPointer> {
775        match self {
776            Value::Lambda(p) => Ok(*p),
777            _ => Err(anyhow!("expected a lambda, but got a {}", self.get_type())),
778        }
779    }
780
781    pub fn as_iterable_pointer(&self) -> Result<IterablePointer> {
782        match self {
783            Value::Spread(p) => Ok(*p),
784            _ => Err(anyhow!("expected a spread, but got a {}", self.get_type())),
785        }
786    }
787
788    pub fn to_serializable_value(&self, heap: &Heap) -> Result<SerializableValue> {
789        SerializableValue::from_value(self, heap)
790    }
791
792    pub fn reify<'h>(&self, heap: &'h Heap) -> Result<ReifiedValue<'h>> {
793        match self {
794            Value::Number(n) => Ok(ReifiedValue::Number(*n)),
795            Value::List(p) => Ok(ReifiedValue::List(p.reify(heap).as_list()?, *p)),
796            Value::Spread(p) => Ok(ReifiedValue::Spread(p.reify(heap).as_iterable()?, *p)),
797            Value::Bool(b) => Ok(ReifiedValue::Bool(*b)),
798            Value::Lambda(p) => Ok(ReifiedValue::Lambda(p.reify(heap).as_lambda()?, *p)),
799            Value::String(p) => Ok(ReifiedValue::String(p.reify(heap).as_string()?, *p)),
800            Value::Null => Ok(ReifiedValue::Null),
801            Value::BuiltIn(id) => Ok(ReifiedValue::BuiltIn(*id)),
802            Value::Record(p) => Ok(ReifiedValue::Record(p.reify(heap).as_record()?, *p)),
803        }
804    }
805
806    /// Stringify the value. Returns the same thing as stringify, except for
807    /// Value::String, which is returned without wrapping quotes. Use this for string
808    /// concatenation, formatting, etc. Don't use this for displaying values to the user.
809    pub fn stringify_internal(&self, heap: &Heap) -> String {
810        self.stringify(heap, false)
811    }
812
813    pub fn stringify_external(&self, heap: &Heap) -> String {
814        self.stringify(heap, true)
815    }
816
817    fn stringify(&self, heap: &Heap, wrap_strings: bool) -> String {
818        match self {
819            Value::String(p) => p
820                .reify(heap)
821                .as_string()
822                .map(|s| {
823                    if wrap_strings {
824                        format!("\"{}\"", s)
825                    } else {
826                        s.to_string()
827                    }
828                })
829                .unwrap(),
830            Value::List(p) => {
831                let mut result = String::from("[");
832                let list = p.reify(heap).as_list().unwrap();
833
834                for (i, value) in list.iter().enumerate() {
835                    result.push_str(&value.stringify(heap, wrap_strings));
836                    if i < list.len() - 1 {
837                        result.push_str(", ");
838                    }
839                }
840                result.push(']');
841                result
842            }
843            Value::Record(p) => {
844                let mut result = String::from("{");
845                let record = p.reify(heap).as_record().unwrap();
846
847                for (i, (key, value)) in record.iter().enumerate() {
848                    result.push_str(&format!("{}: {}", key, value.stringify(heap, wrap_strings)));
849                    if i < record.len() - 1 {
850                        result.push_str(", ");
851                    }
852                }
853                result.push('}');
854                result
855            }
856            Value::Lambda(p) => {
857                let lambda = p.reify(heap).as_lambda().unwrap();
858                let mut result = String::from("(");
859                for (i, arg) in lambda.args.iter().enumerate() {
860                    result.push_str(&arg.to_string());
861                    if i < lambda.args.len() - 1 {
862                        result.push_str(", ");
863                    }
864                }
865                result.push_str(") => ");
866                result.push_str(&crate::ast_to_source::expr_to_source(&lambda.body));
867                result
868            }
869            Value::BuiltIn(built_in) => {
870                format!("{} (built-in)", built_in.name())
871            }
872            Value::Spread(p) => match p {
873                IterablePointer::List(l) => {
874                    let list = l.reify(heap).as_list().unwrap();
875                    let mut result = String::from("...");
876                    result.push_str(
877                        &list
878                            .iter()
879                            .map(|v| v.stringify(heap, wrap_strings))
880                            .collect::<String>(),
881                    );
882                    result
883                }
884                IterablePointer::String(s) => {
885                    let string = s.reify(heap).as_string().unwrap();
886                    format!("...{}", string)
887                }
888                IterablePointer::Record(r) => {
889                    let record = r.reify(heap).as_record().unwrap();
890                    let mut result = String::from("...");
891                    result.push('{');
892                    for (i, (key, value)) in record.iter().enumerate() {
893                        result.push_str(&format!(
894                            "{}: {}",
895                            key,
896                            value.stringify(heap, wrap_strings)
897                        ));
898                        if i < record.len() - 1 {
899                            result.push_str(", ");
900                        }
901                    }
902                    result.push('}');
903                    result
904                }
905            },
906            Value::Bool(_) | Value::Number(_) | Value::Null => format!("{}", self),
907        }
908    }
909}
910
911impl Display for Value {
912    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
913        match self {
914            Value::Number(n) => write!(f, "{}", n),
915            Value::List(p) => write!(f, "{}", p),
916            Value::Spread(p) => write!(f, "...{}", p),
917            Value::Bool(b) => write!(f, "{}", b),
918            Value::Lambda(p) => write!(f, "{}", p),
919            Value::String(p) => write!(f, "{}", p),
920            Value::Null => write!(f, "null"),
921            Value::BuiltIn(built_in) => write!(f, "{} (built-in)", built_in.name()),
922            Value::Record(p) => write!(f, "{}", p),
923        }
924    }
925}