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