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                // Check if this is a function object
317                if let Some(func_value) = obj.get("__blots_function") {
318                    if let Some(func_str) = func_value.as_str() {
319                        // Try to parse as a built-in function first (just a name)
320                        if crate::functions::BuiltInFunction::from_ident(func_str).is_some() {
321                            return SerializableValue::BuiltIn(func_str.to_string());
322                        }
323
324                        // Otherwise, parse as a lambda function
325                        // We need to parse the function source and convert it to a SerializableLambdaDef
326                        if let Ok(lambda_def) = Self::parse_function_source(func_str) {
327                            return SerializableValue::Lambda(lambda_def);
328                        }
329                    }
330                }
331
332                // Regular record
333                let map: IndexMap<String, SerializableValue> = obj
334                    .iter()
335                    .map(|(k, v)| (k.clone(), Self::from_json(v)))
336                    .collect();
337                SerializableValue::Record(map)
338            }
339        }
340    }
341
342    /// Parse a function source string into a SerializableLambdaDef
343    fn parse_function_source(source: &str) -> Result<SerializableLambdaDef> {
344        use crate::parser::get_pairs;
345        use crate::expressions::pairs_to_expr;
346
347        // Parse the source as an expression
348        let pairs = get_pairs(source)?;
349
350        // Extract the lambda expression from the parsed pairs
351        for pair in pairs {
352            if let crate::parser::Rule::statement = pair.as_rule() {
353                if let Some(inner_pair) = pair.into_inner().next() {
354                    if let crate::parser::Rule::expression = inner_pair.as_rule() {
355                        // Parse the expression to get an AST
356                        let expr = pairs_to_expr(inner_pair.into_inner())?;
357
358                        // Check if it's a lambda
359                        if let crate::ast::Expr::Lambda { args, body } = expr {
360                            // Since the function is already inlined (no scope needed),
361                            // we create a SerializableLambdaDef with the source as the body
362                            return Ok(SerializableLambdaDef {
363                                name: None,
364                                args,
365                                body: crate::ast_to_source::expr_to_source(&body),
366                                scope: None, // Functions from JSON have no scope - they're already inlined
367                            });
368                        }
369                    }
370                }
371            }
372        }
373
374        Err(anyhow!("Failed to parse function source: {}", source))
375    }
376
377    /// Convert SerializableValue to clean serde_json::Value
378    pub fn to_json(&self) -> serde_json::Value {
379        match self {
380            SerializableValue::Number(n) => serde_json::Value::Number(
381                serde_json::Number::from_f64(*n).unwrap_or_else(|| serde_json::Number::from(0)),
382            ),
383            SerializableValue::Bool(b) => serde_json::Value::Bool(*b),
384            SerializableValue::Null => serde_json::Value::Null,
385            SerializableValue::String(s) => serde_json::Value::String(s.clone()),
386            SerializableValue::List(items) => {
387                serde_json::Value::Array(items.iter().map(|v| v.to_json()).collect())
388            }
389            SerializableValue::Record(fields) => {
390                let map: serde_json::Map<String, serde_json::Value> = fields
391                    .iter()
392                    .map(|(k, v)| (k.clone(), v.to_json()))
393                    .collect();
394                serde_json::Value::Object(map)
395            }
396            SerializableValue::Lambda(lambda_def) => {
397                // We can't inline scope values from SerializableLambdaDef because the body is already a string
398                // For now, output the function as a JSON object with the source code
399                let mut map = serde_json::Map::new();
400
401                // Build the function source with arguments
402                let args_str: Vec<String> = lambda_def.args.iter().map(|arg| match arg {
403                    LambdaArg::Required(name) => name.clone(),
404                    LambdaArg::Optional(name) => format!("{}?", name),
405                    LambdaArg::Rest(name) => format!("...{}", name),
406                }).collect();
407
408                let function_source = format!("({}) => {}", args_str.join(", "), lambda_def.body);
409
410                map.insert("__blots_function".to_string(), serde_json::Value::String(function_source));
411                serde_json::Value::Object(map)
412            }
413            SerializableValue::BuiltIn(name) => {
414                // Output built-in functions in the same format as lambdas
415                let mut map = serde_json::Map::new();
416                map.insert("__blots_function".to_string(), serde_json::Value::String(name.clone()));
417                serde_json::Value::Object(map)
418            }
419        }
420    }
421
422    pub fn from_value(value: &Value, heap: &Heap) -> Result<SerializableValue> {
423        match value {
424            Value::Number(n) => Ok(SerializableValue::Number(*n)),
425            Value::Bool(b) => Ok(SerializableValue::Bool(*b)),
426            Value::Null => Ok(SerializableValue::Null),
427            Value::List(p) => {
428                let list = p.reify(heap).as_list()?;
429                let serialized_list = list
430                    .iter()
431                    .map(|v| SerializableValue::from_value(v, heap))
432                    .collect::<Result<Vec<SerializableValue>>>()?;
433                Ok(SerializableValue::List(serialized_list))
434            }
435            Value::String(p) => {
436                let string = p.reify(heap).as_string()?;
437                Ok(SerializableValue::String(string.to_string()))
438            }
439            Value::Record(p) => {
440                let record = p.reify(heap).as_record()?;
441                let serialized_record = record
442                    .iter()
443                    .map(|(k, v)| Ok((k.to_string(), SerializableValue::from_value(v, heap)?)))
444                    .collect::<Result<IndexMap<String, SerializableValue>>>()?;
445                Ok(SerializableValue::Record(serialized_record))
446            }
447            Value::Lambda(p) => {
448                let lambda = p.reify(heap).as_lambda()?;
449
450                // Convert the scope to SerializableValues
451                let serializable_scope: IndexMap<String, SerializableValue> = lambda
452                    .scope
453                    .clone()
454                    .into_iter()
455                    .map(|(k, v)| SerializableValue::from_value(&v, heap).map(|sv| (k, sv)))
456                    .collect::<Result<IndexMap<String, SerializableValue>>>()?;
457
458                // Generate the body with inlined scope values
459                let body_with_inlined_scope = crate::ast_to_source::expr_to_source_with_scope(&lambda.body, &serializable_scope);
460
461                Ok(SerializableValue::Lambda(SerializableLambdaDef {
462                    name: lambda.name.clone(),
463                    args: lambda.args.clone(),
464                    body: body_with_inlined_scope,
465                    scope: Some(serializable_scope),
466                }))
467            }
468            Value::BuiltIn(built_in) => Ok(SerializableValue::BuiltIn(built_in.name().to_string())),
469            Value::Spread(_) => Err(anyhow!("cannot serialize a spread value")),
470        }
471    }
472
473    pub fn to_value(&self, heap: &mut Heap) -> Result<Value> {
474        match self {
475            SerializableValue::Number(n) => Ok(Value::Number(*n)),
476            SerializableValue::Bool(b) => Ok(Value::Bool(*b)),
477            SerializableValue::Null => Ok(Value::Null),
478            SerializableValue::List(list) => {
479                let deserialized_list = list
480                    .iter()
481                    .map(|v| SerializableValue::to_value(v, heap))
482                    .collect::<Result<Vec<Value>>>()?;
483
484                Ok(heap.insert_list(deserialized_list))
485            }
486            SerializableValue::String(s) => Ok(heap.insert_string(s.to_string())),
487            SerializableValue::Record(record) => {
488                let deserialized_record = record
489                    .iter()
490                    .map(|(k, v)| Ok((k.to_string(), SerializableValue::to_value(v, heap)?)))
491                    .collect::<Result<IndexMap<String, Value>>>()?;
492                Ok(heap.insert_record(deserialized_record))
493            }
494            SerializableValue::Lambda(s_lambda) => {
495                let scope = if let Some(scope) = s_lambda.scope.clone() {
496                    scope
497                        .iter()
498                        .map(|(k, v)| Ok((k.to_string(), SerializableValue::to_value(v, heap)?)))
499                        .collect::<Result<HashMap<String, Value>>>()?
500                } else {
501                    HashMap::new()
502                };
503
504                // For now, parse the body string back to AST
505                // In a real implementation, we'd want to serialize/deserialize the AST properly
506                let body_ast = crate::expressions::pairs_to_expr(
507                    crate::parser::get_pairs(&s_lambda.body)?
508                        .next()
509                        .unwrap()
510                        .into_inner(),
511                )?;
512
513                let lambda = LambdaDef {
514                    name: s_lambda.name.clone(),
515                    args: s_lambda.args.clone(),
516                    body: body_ast,
517                    scope,
518                };
519
520                Ok(heap.insert_lambda(lambda))
521            }
522            SerializableValue::BuiltIn(ident) => BuiltInFunction::from_ident(ident)
523                .ok_or(anyhow!("built-in function with ident {} not found", ident))
524                .map(Value::BuiltIn),
525        }
526    }
527}
528
529#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
530pub enum PrimitiveValue {
531    Number(f64),
532    Bool(bool),
533    Null,
534}
535
536impl From<PrimitiveValue> for Value {
537    fn from(val: PrimitiveValue) -> Self {
538        match val {
539            PrimitiveValue::Number(n) => Value::Number(n),
540            PrimitiveValue::Bool(b) => Value::Bool(b),
541            PrimitiveValue::Null => Value::Null,
542        }
543    }
544}
545
546impl From<PrimitiveValue> for SerializableValue {
547    fn from(val: PrimitiveValue) -> Self {
548        match val {
549            PrimitiveValue::Number(n) => SerializableValue::Number(n),
550            PrimitiveValue::Bool(b) => SerializableValue::Bool(b),
551            PrimitiveValue::Null => SerializableValue::Null,
552        }
553    }
554}
555
556#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
557pub enum Value {
558    /// A number is a floating-point value.
559    Number(f64),
560    /// A boolean value is either true or false.
561    Bool(bool),
562    /// A null value represents the absence of a value.
563    Null,
564    /// A list is a sequence of values.
565    List(ListPointer),
566    /// A string is a sequence of characters.
567    String(StringPointer),
568    /// A record is a collection of key-value pairs.
569    Record(RecordPointer),
570    /// A lambda is a function definition.
571    Lambda(LambdaPointer),
572    /// A spread value is "spread" into its container when it is used in a list, record, or function call. (internal only)
573    Spread(IterablePointer),
574    /// A built-in function is a function that is implemented in Rust.
575    BuiltIn(BuiltInFunction),
576}
577
578impl Value {
579    /// Compare two values for equality by their actual content, not by reference
580    pub fn equals(&self, other: &Value, heap: &Heap) -> Result<bool> {
581        match (self, other) {
582            // Primitive types - compare directly
583            (Value::Number(a), Value::Number(b)) => Ok(a == b),
584            (Value::Bool(a), Value::Bool(b)) => Ok(a == b),
585            (Value::Null, Value::Null) => Ok(true),
586
587            // String comparison - compare content
588            (Value::String(a_ptr), Value::String(b_ptr)) => {
589                let a_str = a_ptr.reify(heap).as_string()?;
590                let b_str = b_ptr.reify(heap).as_string()?;
591                Ok(a_str == b_str)
592            }
593
594            // List comparison - compare elements recursively
595            (Value::List(a_ptr), Value::List(b_ptr)) => {
596                let a_list = a_ptr.reify(heap).as_list()?;
597                let b_list = b_ptr.reify(heap).as_list()?;
598
599                if a_list.len() != b_list.len() {
600                    return Ok(false);
601                }
602
603                for (a_elem, b_elem) in a_list.iter().zip(b_list.iter()) {
604                    if !a_elem.equals(b_elem, heap)? {
605                        return Ok(false);
606                    }
607                }
608                Ok(true)
609            }
610
611            // Record comparison - compare keys and values
612            (Value::Record(a_ptr), Value::Record(b_ptr)) => {
613                let a_record = a_ptr.reify(heap).as_record()?;
614                let b_record = b_ptr.reify(heap).as_record()?;
615
616                if a_record.len() != b_record.len() {
617                    return Ok(false);
618                }
619
620                for (key, a_value) in a_record.iter() {
621                    match b_record.get(key) {
622                        Some(b_value) => {
623                            if !a_value.equals(b_value, heap)? {
624                                return Ok(false);
625                            }
626                        }
627                        None => return Ok(false),
628                    }
629                }
630                Ok(true)
631            }
632
633            // Lambda comparison - compare by structure (AST equality)
634            (Value::Lambda(a_ptr), Value::Lambda(b_ptr)) => {
635                let a_lambda = a_ptr.reify(heap).as_lambda()?;
636                let b_lambda = b_ptr.reify(heap).as_lambda()?;
637
638                // Compare argument lists
639                if a_lambda.args != b_lambda.args {
640                    return Ok(false);
641                }
642
643                // Compare AST bodies
644                if a_lambda.body != b_lambda.body {
645                    return Ok(false);
646                }
647
648                // Note: We don't compare scopes because two functions with the same
649                // definition but different closures would have different behavior
650                // For now, we only compare structure, not captured variables
651                Ok(true)
652            }
653
654            // Built-in functions - compare by ID
655            (Value::BuiltIn(a), Value::BuiltIn(b)) => Ok(a == b),
656
657            // Spread values - compare the underlying iterable
658            (Value::Spread(a_ptr), Value::Spread(b_ptr)) => match (a_ptr, b_ptr) {
659                (IterablePointer::List(a), IterablePointer::List(b)) => {
660                    Value::List(*a).equals(&Value::List(*b), heap)
661                }
662                (IterablePointer::String(a), IterablePointer::String(b)) => {
663                    Value::String(*a).equals(&Value::String(*b), heap)
664                }
665                (IterablePointer::Record(a), IterablePointer::Record(b)) => {
666                    Value::Record(*a).equals(&Value::Record(*b), heap)
667                }
668                _ => Ok(false),
669            },
670
671            // Different types are never equal
672            _ => Ok(false),
673        }
674    }
675
676    /// Compare two values for ordering
677    pub fn compare(&self, other: &Value, heap: &Heap) -> Result<Option<std::cmp::Ordering>> {
678        match (self, other) {
679            // Numbers have natural ordering
680            (Value::Number(a), Value::Number(b)) => Ok(a.partial_cmp(b)),
681
682            // Booleans: false < true
683            (Value::Bool(a), Value::Bool(b)) => Ok(a.partial_cmp(b)),
684
685            // Strings compare lexicographically
686            (Value::String(a_ptr), Value::String(b_ptr)) => {
687                let a_str = a_ptr.reify(heap).as_string()?;
688                let b_str = b_ptr.reify(heap).as_string()?;
689                Ok(a_str.partial_cmp(b_str))
690            }
691
692            // Lists compare lexicographically
693            (Value::List(a_ptr), Value::List(b_ptr)) => {
694                let a_list = a_ptr.reify(heap).as_list()?;
695                let b_list = b_ptr.reify(heap).as_list()?;
696
697                for (a_elem, b_elem) in a_list.iter().zip(b_list.iter()) {
698                    match a_elem.compare(b_elem, heap)? {
699                        Some(std::cmp::Ordering::Equal) => continue,
700                        other => return Ok(other),
701                    }
702                }
703
704                // If all compared elements are equal, compare lengths
705                Ok(a_list.len().partial_cmp(&b_list.len()))
706            }
707
708            // Other types don't have a natural ordering
709            _ => Ok(None),
710        }
711    }
712
713    pub fn get_type(&self) -> ValueType {
714        match self {
715            Value::Number(_) => ValueType::Number,
716            Value::List(_) => ValueType::List,
717            Value::Spread(_) => ValueType::Spread,
718            Value::Bool(_) => ValueType::Bool,
719            Value::Lambda(_) => ValueType::Lambda,
720            Value::String(_) => ValueType::String,
721            Value::Null => ValueType::Null,
722            Value::BuiltIn(_) => ValueType::BuiltIn,
723            Value::Record(_) => ValueType::Record,
724        }
725    }
726
727    pub fn is_number(&self) -> bool {
728        matches!(self, Value::Number(_))
729    }
730
731    pub fn is_list(&self) -> bool {
732        matches!(self, Value::List(_))
733    }
734
735    pub fn is_spread(&self) -> bool {
736        matches!(self, Value::Spread(_))
737    }
738
739    pub fn is_bool(&self) -> bool {
740        matches!(self, Value::Bool(_))
741    }
742
743    pub fn is_lambda(&self) -> bool {
744        matches!(self, Value::Lambda(_))
745    }
746
747    pub fn is_string(&self) -> bool {
748        matches!(self, Value::String(_))
749    }
750
751    pub fn is_null(&self) -> bool {
752        matches!(self, Value::Null)
753    }
754
755    pub fn is_built_in(&self) -> bool {
756        matches!(self, Value::BuiltIn(_))
757    }
758
759    pub fn is_callable(&self) -> bool {
760        matches!(self, Value::BuiltIn(_) | Value::Lambda(_))
761    }
762
763    pub fn as_number(&self) -> Result<f64> {
764        match self {
765            Value::Number(n) => Ok(*n),
766            _ => Err(anyhow!("expected a number, but got a {}", self.get_type())),
767        }
768    }
769
770    pub fn as_list<'h>(&self, heap: &'h Heap) -> Result<&'h Vec<Value>> {
771        match self {
772            Value::List(l) => l.reify(heap).as_list(),
773            _ => Err(anyhow!("expected a list, but got a {}", self.get_type())),
774        }
775    }
776
777    pub fn as_spread<'h>(&self, heap: &'h Heap) -> Result<&'h HeapValue> {
778        match self {
779            Value::Spread(v) => Ok(v.reify(heap)),
780            _ => Err(anyhow!("expected a spread, but got a {}", self.get_type())),
781        }
782    }
783
784    pub fn as_bool(&self) -> Result<bool> {
785        match self {
786            Value::Bool(b) => Ok(*b),
787            _ => Err(anyhow!("expected a boolean, but got a {}", self.get_type())),
788        }
789    }
790
791    pub fn as_lambda<'h>(&self, heap: &'h Heap) -> Result<&'h LambdaDef> {
792        match self {
793            Value::Lambda(l) => l.reify(heap).as_lambda(),
794            _ => Err(anyhow!("expected a lambda, but got a {}", self.get_type())),
795        }
796    }
797
798    pub fn as_string<'h>(&self, heap: &'h Heap) -> Result<&'h str> {
799        match self {
800            Value::String(p) => p.reify(heap).as_string(),
801            _ => Err(anyhow!("expected a string, but got a {}", self.get_type())),
802        }
803    }
804
805    pub fn as_null(&self) -> Result<()> {
806        match self {
807            Value::Null => Ok(()),
808            _ => Err(anyhow!("expected a null, but got a {}", self.get_type())),
809        }
810    }
811
812    pub fn as_built_in(&self) -> Result<&str> {
813        match self {
814            Value::BuiltIn(built_in) => Ok(built_in.name()),
815            _ => Err(anyhow!(
816                "expected a built-in function, but got a {}",
817                self.get_type()
818            )),
819        }
820    }
821
822    pub fn as_record<'h>(&self, heap: &'h Heap) -> Result<&'h IndexMap<String, Value>> {
823        match self {
824            Value::Record(r) => r.reify(heap).as_record(),
825            _ => Err(anyhow!("expected a record, but got a {}", self.get_type())),
826        }
827    }
828
829    pub fn as_list_pointer(&self) -> Result<ListPointer> {
830        match self {
831            Value::List(p) => Ok(*p),
832            _ => Err(anyhow!("expected a list, but got a {}", self.get_type())),
833        }
834    }
835
836    pub fn as_string_pointer(&self) -> Result<StringPointer> {
837        match self {
838            Value::String(p) => Ok(*p),
839            _ => Err(anyhow!("expected a string, but got a {}", self.get_type())),
840        }
841    }
842
843    pub fn as_record_pointer(&self) -> Result<RecordPointer> {
844        match self {
845            Value::Record(p) => Ok(*p),
846            _ => Err(anyhow!("expected a record, but got a {}", self.get_type())),
847        }
848    }
849
850    pub fn as_lambda_pointer(&self) -> Result<LambdaPointer> {
851        match self {
852            Value::Lambda(p) => Ok(*p),
853            _ => Err(anyhow!("expected a lambda, but got a {}", self.get_type())),
854        }
855    }
856
857    pub fn as_iterable_pointer(&self) -> Result<IterablePointer> {
858        match self {
859            Value::Spread(p) => Ok(*p),
860            _ => Err(anyhow!("expected a spread, but got a {}", self.get_type())),
861        }
862    }
863
864    pub fn to_serializable_value(&self, heap: &Heap) -> Result<SerializableValue> {
865        SerializableValue::from_value(self, heap)
866    }
867
868    pub fn reify<'h>(&self, heap: &'h Heap) -> Result<ReifiedValue<'h>> {
869        match self {
870            Value::Number(n) => Ok(ReifiedValue::Number(*n)),
871            Value::List(p) => Ok(ReifiedValue::List(p.reify(heap).as_list()?, *p)),
872            Value::Spread(p) => Ok(ReifiedValue::Spread(p.reify(heap).as_iterable()?, *p)),
873            Value::Bool(b) => Ok(ReifiedValue::Bool(*b)),
874            Value::Lambda(p) => Ok(ReifiedValue::Lambda(p.reify(heap).as_lambda()?, *p)),
875            Value::String(p) => Ok(ReifiedValue::String(p.reify(heap).as_string()?, *p)),
876            Value::Null => Ok(ReifiedValue::Null),
877            Value::BuiltIn(id) => Ok(ReifiedValue::BuiltIn(*id)),
878            Value::Record(p) => Ok(ReifiedValue::Record(p.reify(heap).as_record()?, *p)),
879        }
880    }
881
882    /// Stringify the value. Returns the same thing as stringify, except for
883    /// Value::String, which is returned without wrapping quotes. Use this for string
884    /// concatenation, formatting, etc. Don't use this for displaying values to the user.
885    pub fn stringify_internal(&self, heap: &Heap) -> String {
886        self.stringify(heap, false)
887    }
888
889    pub fn stringify_external(&self, heap: &Heap) -> String {
890        self.stringify(heap, true)
891    }
892
893    fn stringify(&self, heap: &Heap, wrap_strings: bool) -> String {
894        match self {
895            Value::String(p) => p
896                .reify(heap)
897                .as_string()
898                .map(|s| {
899                    if wrap_strings {
900                        format!("\"{}\"", s)
901                    } else {
902                        s.to_string()
903                    }
904                })
905                .unwrap(),
906            Value::List(p) => {
907                let mut result = String::from("[");
908                let list = p.reify(heap).as_list().unwrap();
909
910                for (i, value) in list.iter().enumerate() {
911                    result.push_str(&value.stringify(heap, wrap_strings));
912                    if i < list.len() - 1 {
913                        result.push_str(", ");
914                    }
915                }
916                result.push(']');
917                result
918            }
919            Value::Record(p) => {
920                let mut result = String::from("{");
921                let record = p.reify(heap).as_record().unwrap();
922
923                for (i, (key, value)) in record.iter().enumerate() {
924                    result.push_str(&format!("{}: {}", key, value.stringify(heap, wrap_strings)));
925                    if i < record.len() - 1 {
926                        result.push_str(", ");
927                    }
928                }
929                result.push('}');
930                result
931            }
932            Value::Lambda(p) => {
933                let lambda = p.reify(heap).as_lambda().unwrap();
934                let mut result = String::from("(");
935                for (i, arg) in lambda.args.iter().enumerate() {
936                    result.push_str(&arg.to_string());
937                    if i < lambda.args.len() - 1 {
938                        result.push_str(", ");
939                    }
940                }
941                result.push_str(") => ");
942                result.push_str(&crate::ast_to_source::expr_to_source(&lambda.body));
943                result
944            }
945            Value::BuiltIn(built_in) => {
946                format!("{} (built-in)", built_in.name())
947            }
948            Value::Spread(p) => match p {
949                IterablePointer::List(l) => {
950                    let list = l.reify(heap).as_list().unwrap();
951                    let mut result = String::from("...");
952                    result.push_str(
953                        &list
954                            .iter()
955                            .map(|v| v.stringify(heap, wrap_strings))
956                            .collect::<String>(),
957                    );
958                    result
959                }
960                IterablePointer::String(s) => {
961                    let string = s.reify(heap).as_string().unwrap();
962                    format!("...{}", string)
963                }
964                IterablePointer::Record(r) => {
965                    let record = r.reify(heap).as_record().unwrap();
966                    let mut result = String::from("...");
967                    result.push('{');
968                    for (i, (key, value)) in record.iter().enumerate() {
969                        result.push_str(&format!(
970                            "{}: {}",
971                            key,
972                            value.stringify(heap, wrap_strings)
973                        ));
974                        if i < record.len() - 1 {
975                            result.push_str(", ");
976                        }
977                    }
978                    result.push('}');
979                    result
980                }
981            },
982            Value::Bool(_) | Value::Number(_) | Value::Null => format!("{}", self),
983        }
984    }
985}
986
987impl Display for Value {
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        match self {
990            Value::Number(n) => write!(f, "{}", n),
991            Value::List(p) => write!(f, "{}", p),
992            Value::Spread(p) => write!(f, "...{}", p),
993            Value::Bool(b) => write!(f, "{}", b),
994            Value::Lambda(p) => write!(f, "{}", p),
995            Value::String(p) => write!(f, "{}", p),
996            Value::Null => write!(f, "null"),
997            Value::BuiltIn(built_in) => write!(f, "{} (built-in)", built_in.name()),
998            Value::Record(p) => write!(f, "{}", p),
999        }
1000    }
1001}