swamp_script_core_extra/
value.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use crate::extra::{SparseValueId, SparseValueMap};
6use crate::grid::Grid;
7use crate::map2::Map2;
8use crate::map2::print_grid;
9use core::any::Any;
10use fixed32::Fp;
11use seq_map::SeqMap;
12use std::cell::Ref;
13use std::cell::RefCell;
14use std::fmt::{Debug, Display};
15use std::hash::Hash;
16use std::rc::Rc;
17use swamp_script_semantic::{
18    Expression, ExternalFunctionDefinitionRef, FormatSpecifierKind, InternalFunctionDefinitionRef,
19    PrecisionType, VariableRef,
20};
21use swamp_script_types::prelude::*;
22
23pub type ValueRef = Rc<RefCell<Value>>;
24
25pub trait RustType: Any + Debug + Display + QuickSerialize {
26    fn as_any(&self) -> &dyn Any;
27    fn as_any_mut(&mut self) -> &mut dyn Any;
28    fn eq_dyn(&self, other: &dyn RustType) -> bool;
29}
30
31// Blanket implementation
32impl<T: Any + Debug + Display + QuickSerialize + PartialEq> RustType for T {
33    fn as_any(&self) -> &dyn Any {
34        self
35    }
36
37    fn as_any_mut(&mut self) -> &mut dyn Any {
38        self
39    }
40
41    fn eq_dyn(&self, other: &dyn RustType) -> bool {
42        // Check if `other` is the same concrete type as `self`
43        other
44            .as_any()
45            .downcast_ref::<T>()
46            .map_or(false, |other_t| self == other_t)
47    }
48}
49
50pub trait QuickSerialize {
51    fn quick_serialize(&self, _octets: &mut [u8]) -> usize {
52        0
53    }
54}
55
56pub trait QuickDeserialize {
57    fn quick_deserialize(octets: &[u8]) -> (Self, usize)
58    where
59        Self: Sized;
60}
61
62impl<'a, T: QuickSerialize + ?Sized> QuickSerialize for Ref<'a, T> {
63    fn quick_serialize(&self, octets: &mut [u8]) -> usize {
64        (**self).quick_serialize(octets)
65    }
66}
67
68impl<T: QuickSerialize> QuickSerialize for Box<T> {
69    fn quick_serialize(&self, octets: &mut [u8]) -> usize {
70        // Delegate serialization to the inner T
71        (**self).quick_serialize(octets)
72    }
73}
74
75impl QuickSerialize for Rc<RefCell<dyn RustType>> {
76    fn quick_serialize(&self, octets: &mut [u8]) -> usize {
77        self.borrow().quick_serialize(octets)
78    }
79}
80
81#[derive(Debug, Default)]
82pub enum Value {
83    Int(i32),
84    Float(Fp),
85    String(String),
86    Bool(bool),
87    #[default]
88    Unit, // Means 'no value' ()
89
90    Slice(Type, Vec<ValueRef>),
91    SlicePair(Type, SeqMap<Value, ValueRef>), // Do not change to HashMap, the order is important for it to be deterministic
92
93    Option(Option<ValueRef>),
94
95    // Containers
96    Vec(Type, Vec<ValueRef>),
97    Map(Type, SeqMap<Value, ValueRef>), // Do not change to HashMap, the order is important for it to be deterministic
98    Tuple(Vec<Type>, Vec<ValueRef>),
99    Grid(Grid<ValueRef>),
100    Map2(Map2<Value, Value, ValueRef>),
101
102    Sparse(Type, SparseValueMap),
103    NamedStruct(NamedStructType, Vec<ValueRef>), // type of the struct, and the fields themselves in strict order
104    AnonymousStruct(AnonymousStructType, Vec<ValueRef>), // type of the struct, and the fields themselves in strict order
105
106    EnumVariantSimple(EnumType, EnumVariantSimpleType),
107    EnumVariantTuple(EnumType, EnumVariantTupleType, Vec<ValueRef>),
108    EnumVariantStruct(EnumType, EnumVariantStructType, Vec<ValueRef>),
109
110    // Higher order
111    InternalFunction(InternalFunctionDefinitionRef),
112    ExternalFunction(ExternalFunctionDefinitionRef),
113
114    // Other
115    RustValue(ExternalType, Rc<RefCell<Box<dyn RustType>>>),
116    Lambda(Vec<VariableRef>, Box<Expression>),
117}
118
119#[allow(unused)]
120fn quick_serialize_values(values: &[Value], buffer: &mut [u8], depth: usize) -> usize {
121    let mut offset = 0;
122
123    for value in values {
124        let bytes_written = value.quick_serialize(&mut buffer[offset..], depth + 1);
125        offset += bytes_written;
126    }
127
128    offset
129}
130
131impl Value {
132    /// Serialize as quickly as possible
133    /// Endian format is undefined. It is only used for serializing during a running application
134    ///
135    #[allow(clippy::too_many_lines)]
136    #[inline]
137    pub fn quick_serialize(&self, octets: &mut [u8], depth: usize) -> usize {
138        match self {
139            Self::Int(x) => {
140                let value_octets = x.to_le_bytes();
141                octets[..value_octets.len()].copy_from_slice(&value_octets);
142                value_octets.len()
143            }
144            Self::Float(fp) => {
145                let value_octets = fp.inner().to_le_bytes();
146                octets[..value_octets.len()].copy_from_slice(&value_octets);
147                value_octets.len()
148            }
149            Self::String(s) => {
150                let len = s.len() as u16;
151                let len_bytes = len.to_le_bytes();
152                octets[..len_bytes.len()].copy_from_slice(&len_bytes);
153                let mut offset = len_bytes.len();
154
155                // Serialize the string bytes
156                octets[offset..offset + len as usize].copy_from_slice(s.as_bytes());
157                offset += len as usize;
158                offset
159            }
160
161            Self::Bool(b) => {
162                octets[0] = u8::from(*b);
163                1
164            }
165            Self::Lambda(_, _) => todo!(),
166            Self::Unit => 0,
167            Self::Option(maybe_value) => match maybe_value {
168                None => {
169                    octets[0] = 0;
170                    1
171                }
172                Some(inner_value) => {
173                    octets[0] = 1;
174                    let inner_size = inner_value
175                        .borrow()
176                        .quick_serialize(&mut octets[1..], depth + 1);
177                    1 + inner_size
178                }
179            },
180            Self::Vec(_array_ref, values) => {
181                let mut offset = 0;
182
183                let count: u16 = values.len() as u16;
184                let count_octets = count.to_le_bytes();
185                octets[offset..offset + 2].copy_from_slice(&count_octets);
186                offset += count_octets.len();
187
188                for value in values {
189                    let size = value
190                        .borrow()
191                        .quick_serialize(&mut octets[offset..], depth + 1);
192
193                    offset += size;
194                }
195                offset
196            }
197            Self::Map(_key, values) => {
198                let mut offset = 0;
199
200                let count: u16 = values.len() as u16;
201                let count_octets = count.to_le_bytes();
202                octets[offset..offset + count_octets.len()].copy_from_slice(&count_octets);
203                offset += count_octets.len();
204
205                for (key, value_ref) in values {
206                    offset += key.quick_serialize(&mut octets[offset..], depth + 1);
207
208                    let value_val = value_ref.borrow();
209                    offset += value_val.quick_serialize(&mut octets[offset..], depth + 1);
210                }
211
212                offset
213            }
214
215            Self::Tuple(_tuple_type_ref, values) => {
216                let mut offset = 0;
217                for value in values {
218                    let size = value
219                        .borrow()
220                        .quick_serialize(&mut octets[offset..], depth + 1);
221                    offset += size;
222                }
223                offset
224            }
225
226            Self::NamedStruct(_struct_type, values) => {
227                let mut offset = 0;
228                for value in values {
229                    let size = value
230                        .borrow()
231                        .quick_serialize(&mut octets[offset..], depth + 1);
232                    offset += size;
233                }
234                offset
235            }
236
237            Self::AnonymousStruct(_anon, _values) => {
238                todo!("anonymous structs not supported")
239            }
240
241            Self::Grid(_grid) => {
242                todo!("grid not supported")
243            }
244            Self::Map2(_map2) => {
245                todo!("map2 not supported")
246            }
247            Self::EnumVariantSimple(_, enum_variant) => {
248                octets[0] = enum_variant.common.container_index;
249                1
250            }
251            Self::EnumVariantTuple(_, enum_tuple_ref, values) => {
252                let mut offset = 0;
253                octets[offset] = enum_tuple_ref.common.container_index;
254                offset += 1;
255                for value in values {
256                    let size = value
257                        .borrow()
258                        .quick_serialize(&mut octets[offset..], depth + 1);
259                    offset += size;
260                }
261                offset
262            }
263            Self::EnumVariantStruct(_, enum_struct_ref, values) => {
264                let mut offset = 0;
265                octets[offset] = enum_struct_ref.common.container_index;
266                offset += 1;
267                for value in values {
268                    let size = value
269                        .borrow()
270                        .quick_serialize(&mut octets[offset..], depth + 1);
271                    offset += size;
272                }
273                offset
274            }
275
276            Self::SlicePair(_key, _values) => {
277                panic!("slice pair is not supported ")
278            }
279
280            Self::Slice(_element_type, _values) => {
281                panic!("slice is not supported ")
282            }
283
284            Self::InternalFunction(_) => {
285                todo!("internal_functions are not supported yet")
286            }
287            Self::ExternalFunction(_) => {
288                todo!("external_functions are not supported yet")
289            }
290
291            Self::RustValue(_rust_value, rust_value) => rust_value.borrow().quick_serialize(octets),
292            Self::Sparse(_, _) => todo!(),
293        }
294    }
295}
296
297impl Clone for Value {
298    fn clone(&self) -> Self {
299        match self {
300            Self::Int(i) => Self::Int(*i),
301            Self::Float(f) => Self::Float(*f),
302            Self::String(s) => Self::String(s.clone()),
303            Self::Bool(b) => Self::Bool(*b),
304            Self::Unit => Self::Unit,
305            Self::Lambda(a, b) => Self::Lambda(a.clone(), b.clone()),
306
307            Self::Option(opt) => {
308                let cloned_opt = opt.as_ref().map(std::clone::Clone::clone);
309                Self::Option(cloned_opt)
310            }
311
312            // Containers
313            Self::Vec(resolved_ref, vec_refs) => {
314                Self::Vec(resolved_ref.clone(), deep_clone_valrefs(vec_refs))
315            }
316
317            Self::Map(key, seq_map) => {
318                let cloned_seq_map = seq_map
319                    .iter()
320                    .map(|(key, val_ref)| (key.clone(), deep_clone_valref(val_ref)))
321                    .collect();
322
323                Self::Map(key.clone(), cloned_seq_map)
324            }
325            Self::Map2(map2) => Self::Map2(map2.clone()),
326
327            Self::Grid(grid) => Self::Grid(grid.clone()),
328
329            Self::Slice(resolved_ref, vec_refs) => {
330                Self::Slice(resolved_ref.clone(), deep_clone_valrefs(vec_refs))
331            }
332
333            Self::SlicePair(key, seq_map) => {
334                let cloned_seq_map = seq_map
335                    .iter()
336                    .map(|(key, val_ref)| (key.clone(), deep_clone_valref(val_ref)))
337                    .collect();
338
339                Self::SlicePair(key.clone(), cloned_seq_map)
340            }
341
342            Self::Tuple(resolved_ref, vec_refs) => {
343                Self::Tuple(resolved_ref.clone(), deep_clone_valrefs(vec_refs))
344            }
345
346            Self::NamedStruct(resolved_ref, vec_refs) => {
347                Self::NamedStruct(resolved_ref.clone(), deep_clone_valrefs(vec_refs))
348            }
349            Self::AnonymousStruct(resolved_ref, vec_refs) => {
350                Self::AnonymousStruct(resolved_ref.clone(), deep_clone_valrefs(vec_refs))
351            }
352
353            Self::EnumVariantSimple(enum_type, resolved_ref) => {
354                Self::EnumVariantSimple(enum_type.clone(), resolved_ref.clone())
355            }
356
357            Self::EnumVariantTuple(enum_type, resolved_ref, vec_values) => {
358                Self::EnumVariantTuple(enum_type.clone(), resolved_ref.clone(), vec_values.clone())
359            }
360
361            Self::EnumVariantStruct(enum_type, resolved_ref, vec_values) => {
362                Self::EnumVariantStruct(enum_type.clone(), resolved_ref.clone(), vec_values.clone())
363            }
364
365            Self::InternalFunction(resolved_def_ref) => {
366                Self::InternalFunction(resolved_def_ref.clone())
367            }
368
369            Self::ExternalFunction(external_fn) => Self::ExternalFunction(external_fn.clone()),
370
371            Self::RustValue(resolved_rust_ref, rust_type_rc) => {
372                Self::RustValue(resolved_rust_ref.clone(), rust_type_rc.clone())
373            }
374            Self::Sparse(_, _) => todo!(),
375        }
376    }
377}
378
379#[inline]
380fn deep_clone_valrefs(vec_values: &[ValueRef]) -> Vec<ValueRef> {
381    vec_values.iter().map(deep_clone_valref).collect()
382}
383
384#[inline]
385fn deep_clone_valref(val_ref: &ValueRef) -> ValueRef {
386    let cloned_value = val_ref.borrow().clone();
387    Rc::new(RefCell::new(cloned_value))
388}
389
390pub fn to_rust_value<T: RustType + 'static>(type_ref: ExternalType, value: T) -> Value {
391    Value::RustValue(
392        type_ref,
393        Rc::new(RefCell::new(Box::new(value) as Box<dyn RustType>)),
394    )
395}
396
397#[derive(Debug, PartialEq, Eq)]
398pub enum ValueError {
399    NotAnIterator,
400    NotSparseMap,
401    CanNotCoerceToIterator,
402    ConversionError(String),
403    WrongNumberOfArguments { expected: usize, got: usize },
404    TypeError(String),
405}
406
407//pub const SPARSE_TYPE_ID: TypeNumber = 999;
408//pub const SPARSE_ID_TYPE_ID: TypeNumber = 998;
409
410// Iterators
411
412impl Value {
413    /// # Errors
414    ///
415    /// # Panics
416    ///
417    #[allow(clippy::should_implement_trait)] // TODO: Fix this
418    pub fn into_iter(self) -> Result<Box<dyn Iterator<Item = Self>>, ValueError> {
419        match self {
420            // TODO: Self::Reference(value_ref) => value_ref.borrow().clone().into_iter(is_mutable),
421            Self::Vec(_, values) => Ok(Box::new(
422                values.into_iter().map(|item| item.borrow().clone()),
423            )),
424
425            Self::String(values) => Ok(Box::new(
426                values
427                    .chars()
428                    .map(|item| Self::String(item.to_string()))
429                    .collect::<Vec<Self>>()
430                    .into_iter(),
431            )),
432            Self::Map(_key, seq_map) => Ok(Box::new(
433                seq_map.into_values().map(|item| item.borrow().clone()),
434            )),
435            Self::Sparse(_x, sparse_map) => {
436                let values: Vec<_> = sparse_map
437                    .values()
438                    .iter()
439                    .map(|item| item.borrow().clone())
440                    .collect();
441                Ok(Box::new(values.into_iter()))
442            }
443            Self::RustValue(ref _rust_type_ref, _) => {
444                todo!()
445            }
446            Self::NamedStruct(struct_type, fields) => {
447                // assume it is Range
448                debug_assert_eq!(struct_type.assigned_name, "Range");
449                let start = fields[0].borrow().expect_int()?;
450                let end = fields[1].borrow().expect_int()?;
451                let is_inclusive = fields[2].borrow().expect_bool()?;
452                generate_range_value_iterator(start, end, is_inclusive)
453            }
454            _ => Err(ValueError::CanNotCoerceToIterator),
455        }
456    }
457
458    /// # Errors
459    ///
460    /// # Panics
461    ///
462    pub fn into_iter_pairs(self) -> Result<Box<dyn Iterator<Item = (Self, Self)>>, ValueError> {
463        let values = match self {
464            Self::Map(_, seq_map) => {
465                Box::new(seq_map.into_iter().map(|(k, v)| (k, v.borrow().clone())))
466            }
467            Self::Tuple(_type_ref, elements) => {
468                let iter = elements
469                    .into_iter()
470                    .enumerate()
471                    .map(move |(i, v)| (Self::Int(i as i32), v.borrow().clone()));
472                Box::new(iter) as Box<dyn Iterator<Item = (Self, Self)>>
473            }
474            Self::Vec(_type_ref, array) => {
475                let iter = array
476                    .into_iter()
477                    .enumerate()
478                    .map(move |(i, v)| (Self::Int(i as i32), v.borrow().clone()));
479                Box::new(iter) as Box<dyn Iterator<Item = (Self, Self)>>
480            }
481            Self::String(string) => {
482                let iter = string
483                    .chars()
484                    .enumerate()
485                    .map(|(i, v)| (Self::Int(i as i32), Self::String(v.to_string())))
486                    .collect::<Vec<(Self, Self)>>()
487                    .into_iter();
488                Box::new(iter) as Box<dyn Iterator<Item = (Self, Self)> + 'static>
489            }
490            Self::Sparse(ref _rust_type_ref, ref sparse_map) => {
491                let id_type_ref = sparse_map.rust_type_ref_for_id.clone();
492
493                let pairs: Vec<_> = sparse_map
494                    .iter()
495                    .map(|(k, v)| {
496                        (
497                            Self::RustValue(
498                                id_type_ref.clone(),
499                                Rc::new(RefCell::new(Box::new(SparseValueId(k)))),
500                            ),
501                            v.borrow().clone(),
502                        )
503                    })
504                    .collect();
505
506                Box::new(pairs.into_iter()) as Box<dyn Iterator<Item = (Self, Self)>>
507            }
508
509            _ => return Err(ValueError::NotAnIterator),
510        };
511
512        Ok(values)
513    }
514
515    #[must_use]
516    pub fn convert_to_string_if_needed(&self) -> String {
517        match self {
518            Self::String(string) => string.clone(),
519            _ => self.to_string(),
520        }
521    }
522
523    /// # Errors
524    ///
525    pub fn expect_string(&self) -> Result<String, ValueError> {
526        match self {
527            Self::String(s) => Ok(s.clone()),
528            _ => Err(ValueError::ConversionError("Expected string value".into())),
529        }
530    }
531
532    pub fn expect_struct(&self) -> Result<(NamedStructType, &Vec<ValueRef>), ValueError> {
533        match self {
534            Self::NamedStruct(struct_ref, fields) => Ok((struct_ref.clone(), fields)),
535            _ => Err(ValueError::ConversionError("Expected struct value".into())),
536        }
537    }
538
539    pub fn expect_anon_struct(&self) -> Result<(AnonymousStructType, &Vec<ValueRef>), ValueError> {
540        match self {
541            Self::NamedStruct(struct_ref, fields) => {
542                Ok((struct_ref.anon_struct_type.clone(), fields))
543            }
544            Self::AnonymousStruct(anon_struct_type, fields) => {
545                Ok((anon_struct_type.clone(), fields))
546            }
547            _ => Err(ValueError::ConversionError("Expected struct value".into())),
548        }
549    }
550
551    pub fn expect_array(&self) -> Result<(Type, &Vec<ValueRef>), ValueError> {
552        match self {
553            Self::Vec(resolved_array_ref, fields) => Ok((resolved_array_ref.clone(), fields)),
554            _ => Err(ValueError::ConversionError("Expected array value".into())),
555        }
556    }
557
558    pub fn expect_map(&self) -> Result<(Type, &SeqMap<Value, ValueRef>), ValueError> {
559        match self {
560            Self::Map(key, seq_map) => Ok((key.clone(), seq_map)),
561            _ => Err(ValueError::ConversionError("Expected map value".into())),
562        }
563    }
564
565    pub fn expect_map_mut(&mut self) -> Result<(Type, &mut SeqMap<Value, ValueRef>), ValueError> {
566        match self {
567            Self::Map(key, seq_map) => Ok((key.clone(), seq_map)),
568            _ => Err(ValueError::ConversionError("Expected map value".into())),
569        }
570    }
571
572    /// # Errors
573    ///
574    pub fn expect_int(&self) -> Result<i32, ValueError> {
575        match self {
576            Self::Int(v) => Ok(*v),
577            _ => Err(ValueError::ConversionError("Expected int value".into())),
578        }
579    }
580
581    /// # Errors
582    ///
583    pub fn expect_bool(&self) -> Result<bool, ValueError> {
584        match self {
585            Self::Bool(v) => Ok(*v),
586            _ => Err(ValueError::ConversionError("Expected bool value".into())),
587        }
588    }
589
590    /// # Errors
591    ///
592    pub fn expect_slice(&self) -> Result<(Type, Vec<ValueRef>), ValueError> {
593        match self {
594            Self::Slice(ty, items) => Ok((ty.clone(), items.to_vec())),
595            _ => Err(ValueError::ConversionError("Expected slice value".into())),
596        }
597    }
598
599    /// # Errors
600    ///
601    pub fn expect_slice_pair(&self) -> Result<(Type, &SeqMap<Value, ValueRef>), ValueError> {
602        match self {
603            Self::SlicePair(ty, seq_map) => Ok((ty.clone(), seq_map)),
604            _ => Err(ValueError::ConversionError(
605                "Expected slice_pair value".into(),
606            )),
607        }
608    }
609
610    /// # Errors
611    ///
612    pub fn expect_float(&self) -> Result<Fp, ValueError> {
613        match self {
614            Self::Float(v) => Ok(*v),
615            _ => Err(ValueError::ConversionError("Expected float value".into())),
616        }
617    }
618
619    /// # Errors
620    ///
621    pub fn as_bool(&self) -> Result<bool, ValueError> {
622        match self {
623            Self::Bool(b) => Ok(*b),
624            _ => Err(ValueError::ConversionError("Expected bool value".into())),
625        }
626    }
627
628    /// # Errors
629    ///
630    pub fn is_truthy(&self) -> Result<bool, ValueError> {
631        let v = match self {
632            Self::Bool(b) => *b,
633            _ => {
634                return Err(ValueError::ConversionError(format!(
635                    "Expected bool value {}",
636                    self
637                )));
638            }
639        };
640
641        Ok(v)
642    }
643
644    /// # Errors
645    ///
646    #[must_use]
647    pub fn downcast_rust<T: RustType + 'static>(&self) -> Option<Rc<RefCell<Box<T>>>> {
648        match self {
649            Self::RustValue(_rust_type_ref, rc) => {
650                let type_matches = {
651                    let guard = rc.borrow();
652                    (**guard).as_any().is::<T>()
653                };
654
655                if type_matches {
656                    Some(unsafe { std::mem::transmute(rc.clone()) })
657                } else {
658                    None
659                }
660            }
661            _ => None,
662        }
663    }
664
665    #[must_use]
666    pub fn downcast_hidden_rust<T: RustType + 'static>(&self) -> Option<Rc<RefCell<Box<T>>>> {
667        match self {
668            Self::NamedStruct(_struct_ref, fields) => fields[0].borrow().downcast_rust(),
669            _ => None,
670        }
671    }
672
673    pub fn new_rust_value<T: RustType + 'static + PartialEq>(
674        rust_type_ref: ExternalType,
675        value: T,
676    ) -> Self {
677        let boxed = Box::new(Box::new(value)) as Box<dyn RustType>;
678        Self::RustValue(rust_type_ref, Rc::new(RefCell::new(boxed)))
679    }
680
681    pub fn new_hidden_rust_struct<T: RustType + 'static + PartialEq>(
682        struct_type: NamedStructType,
683        rust_description: ExternalType,
684        value: T,
685    ) -> Self {
686        let rust_value = Rc::new(RefCell::new(Self::new_rust_value(rust_description, value)));
687        Self::NamedStruct(struct_type, vec![rust_value])
688    }
689}
690
691fn generate_range_int_iterator(
692    start: i32,
693    end: i32,
694    is_inclusive: bool,
695) -> Box<dyn Iterator<Item = i32>> {
696    if start > end {
697        if is_inclusive {
698            Box::new((end..=start).rev())
699        } else {
700            Box::new((end.saturating_add(1)..=start).rev())
701        }
702    } else if is_inclusive {
703        Box::new(start..=end)
704    } else {
705        Box::new(start..end)
706    }
707}
708
709fn generate_range_value_iterator(
710    start: i32,
711    exclusive_end: i32,
712    is_inclusive: bool,
713) -> Result<Box<dyn Iterator<Item = Value>>, ValueError> {
714    Ok(Box::new(
715        generate_range_int_iterator(start, exclusive_end, is_inclusive).map(Value::Int),
716    ))
717}
718
719impl Display for Value {
720    #[allow(clippy::too_many_lines)]
721    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
722        match self {
723            Self::Int(n) => write!(f, "{n}"),
724            Self::Float(n) => write!(f, "{n}"),
725            Self::String(s) => write!(f, "\"{s}\""),
726            Self::Bool(b) => write!(f, "{b}"),
727            Self::Vec(_item_type, arr) => {
728                write!(f, "[")?;
729                for (i, val) in arr.iter().enumerate() {
730                    if i > 0 {
731                        write!(f, ", ")?;
732                    }
733                    write!(f, "{}", val.borrow())?;
734                }
735                write!(f, "]")
736            }
737            Self::Lambda(a, b) => {
738                writeln!(f, "lambda")
739            }
740            Self::Grid(grid) => {
741                writeln!(f, "[grid:")?;
742                for row in grid.rows() {
743                    write!(f, "[")?;
744                    for (i, val) in row.iter().enumerate() {
745                        if i > 0 {
746                            write!(f, ", ")?;
747                        }
748                        write!(f, "{}", val.borrow())?;
749                    }
750                    writeln!(f, "]")?;
751                }
752                writeln!(f, "]")
753            }
754            Self::Map2(map2) => {
755                print_grid(map2);
756                Ok(())
757            }
758            Self::Map(_key, items) => {
759                write!(f, "[")?;
760                for (i, (key, val)) in items.iter().enumerate() {
761                    if i > 0 {
762                        write!(f, ", ")?;
763                    }
764                    write!(f, "{key}: {}", val.borrow())?;
765                }
766                write!(f, "]")
767            }
768
769            Self::Slice(_slice_type, arr) => {
770                write!(f, "Slice[")?;
771                for (i, val) in arr.iter().enumerate() {
772                    if i > 0 {
773                        write!(f, ", ")?;
774                    }
775                    write!(f, "{}", val.borrow())?;
776                }
777                write!(f, "]")
778            }
779            Self::SlicePair(_ty, items) => {
780                write!(f, "SlicePair[")?;
781                for (i, (key, val)) in items.iter().enumerate() {
782                    if i > 0 {
783                        write!(f, ", ")?;
784                    }
785                    write!(f, "{key}: {}", val.borrow())?;
786                }
787                write!(f, "]")
788            }
789
790            Self::Tuple(_tuple_type, arr) => {
791                write!(f, "(")?;
792                for (i, val) in arr.iter().enumerate() {
793                    if i > 0 {
794                        write!(f, ", ")?;
795                    }
796                    write!(f, "{}", val.borrow())?;
797                }
798                write!(f, ")")
799            }
800            Self::NamedStruct(struct_type_ref, fields_in_strict_order) => {
801                write!(f, "{} {{ ", struct_type_ref.assigned_name)?;
802
803                let fields = struct_type_ref
804                    .anon_struct_type
805                    .field_name_sorted_fields
806                    .keys()
807                    .cloned()
808                    .collect::<Vec<_>>();
809                for (i, val) in fields_in_strict_order.iter().enumerate() {
810                    if i > 0 {
811                        write!(f, ", ")?;
812                    }
813                    let field_name = &fields[i];
814                    write!(f, "{field_name}: {}", val.borrow())?;
815                }
816                write!(f, " }}")
817            }
818            Self::AnonymousStruct(anonymous_struct, fields_in_strict_order) => {
819                write!(f, "{{ ")?;
820
821                let fields = anonymous_struct
822                    .field_name_sorted_fields
823                    .keys()
824                    .cloned()
825                    .collect::<Vec<_>>();
826                for (i, val) in fields_in_strict_order.iter().enumerate() {
827                    if i > 0 {
828                        write!(f, ", ")?;
829                    }
830                    let field_name = &fields[i];
831                    write!(f, "{field_name}: {}", val.borrow())?;
832                }
833                write!(f, " }}")
834            }
835            Self::InternalFunction(internal_fn) => write!(f, "[fn {}]", internal_fn.assigned_name),
836            Self::Unit => write!(f, "()"),
837
838            Self::ExternalFunction(external_function) => {
839                write!(f, "[external_fn {}]", external_function.assigned_name)
840            }
841
842            // Enums ----
843            Self::EnumVariantTuple(enum_type, enum_name, fields_in_order) => {
844                write!(
845                    f,
846                    "{}::{}(",
847                    enum_type.assigned_name, enum_name.common.assigned_name,
848                )?;
849
850                for (index, field) in fields_in_order.iter().enumerate() {
851                    if index > 0 {
852                        write!(f, ", ")?;
853                    }
854                    write!(f, "{}", field.borrow())?;
855                }
856
857                write!(f, ")")?;
858
859                Ok(())
860            }
861            Self::EnumVariantStruct(enum_type, struct_variant, values) => {
862                let decorated_values: Vec<(String, ValueRef)> = struct_variant
863                    .anon_struct
864                    .field_name_sorted_fields
865                    .keys()
866                    .cloned()
867                    .zip(values.clone())
868                    .collect();
869
870                write!(
871                    f,
872                    "{}::{}{{",
873                    enum_type.assigned_name, struct_variant.common.assigned_name,
874                )?;
875
876                for (index, (field_name, value)) in decorated_values.iter().enumerate() {
877                    if index > 0 {
878                        write!(f, ", ")?;
879                    }
880                    write!(f, "{field_name}: {}", value.borrow())?;
881                }
882
883                write!(f, "}}")?;
884                Ok(())
885            }
886            Self::EnumVariantSimple(enum_type, enum_variant_type_ref) => {
887                write!(
888                    f,
889                    "{}::{}",
890                    enum_type.assigned_name, enum_variant_type_ref.common.assigned_name,
891                )
892            }
893            Self::RustValue(_rust_type, rust_type_pointer) => {
894                write!(f, "{}", rust_type_pointer.borrow())
895            }
896            Self::Option(maybe_val) => {
897                let inner_str = if let Some(inner_value) = maybe_val {
898                    &*inner_value.borrow().to_string()
899                } else {
900                    "none"
901                };
902                write!(f, "Option({inner_str})")
903            }
904            Self::Sparse(_, _) => todo!(),
905        }
906    }
907}
908
909impl PartialEq for Value {
910    fn eq(&self, other: &Self) -> bool {
911        match (self, other) {
912            // Regular value comparisons
913            (Self::Int(a), Self::Int(b)) => a == b,
914            (Self::Float(a), Self::Float(b)) => a == b,
915            (Self::String(a), Self::String(b)) => a == b,
916            (Self::Bool(a), Self::Bool(b)) => a == b,
917            (Self::Unit, Self::Unit) => true,
918            (Self::EnumVariantSimple(_enum_type, a), Self::EnumVariantSimple(_enum_type_b, b)) => {
919                a == b
920            }
921            (
922                Self::EnumVariantTuple(_enum_type, a, a_values),
923                Self::EnumVariantTuple(_enum_type_b, b, b_values),
924            ) => (a == b) && a_values == b_values,
925            (
926                Self::EnumVariantStruct(_enum_type, a, a_values),
927                Self::EnumVariantStruct(_enum_type_b, b, b_values),
928            ) => (a == b) && a_values == b_values,
929            (Self::Option(a), Self::Option(b)) => a == b,
930            (Self::Vec(a, a_values), Self::Vec(b, b_values)) => (a == b) && a_values == b_values,
931            (Self::Map(a, a_values), Self::Map(b, b_values)) => (a == b) && a_values == b_values,
932            (Self::Tuple(a, a_values), Self::Tuple(b, b_values)) => {
933                (a == b) && a_values == b_values
934            }
935            (Self::NamedStruct(a, a_values), Self::NamedStruct(b, b_values)) => {
936                (a == b) && a_values == b_values
937            }
938            (Self::AnonymousStruct(a, a_values), Self::AnonymousStruct(b, b_values)) => {
939                (a == b) && a_values == b_values
940            }
941            (Self::InternalFunction(a), Self::InternalFunction(b)) => a == b,
942            (Self::ExternalFunction(a), Self::ExternalFunction(b)) => a.id == b.id,
943            (Self::RustValue(_a, a_val), Self::RustValue(_b, b_val)) => {
944                a_val.borrow().eq_dyn(&**b_val.borrow())
945            }
946
947            _ => false,
948        }
949    }
950}
951
952impl Eq for Value {}
953
954impl Hash for Value {
955    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
956        match self {
957            Self::Int(n) => n.hash(state),
958            Self::Float(f) => f.hash(state),
959            Self::String(s) => s.hash(state),
960            Self::Bool(b) => b.hash(state),
961            Self::Unit => (),
962            Self::Option(wrapped) => {
963                if let Some(found) = wrapped {
964                    1.hash(state);
965                    found.borrow().hash(state);
966                } else {
967                    0.hash(state);
968                }
969            }
970            Self::Lambda(a, b) => {
971                todo!()
972            }
973            Self::Vec(_, _arr) => {}
974            Self::Grid(_) => {}
975            Self::Slice(_, _arr) => {}
976            Self::NamedStruct(type_ref, values) => {
977                type_ref.name().span.hash(state);
978                for v in values {
979                    v.borrow().hash(state);
980                }
981            }
982            Self::AnonymousStruct(_type_ref, values) => {
983                // TODO: Not correct hash
984                for v in values {
985                    v.borrow().hash(state);
986                }
987            }
988            Self::Map(_, values) => {
989                for (key, val) in values {
990                    key.hash(state);
991                    val.borrow().hash(state);
992                }
993            }
994            Self::Map2(items) => {}
995            Self::SlicePair(_, _items) => {}
996            Self::Tuple(_, values) => {
997                for v in values {
998                    v.borrow().hash(state);
999                }
1000            }
1001            Self::EnumVariantSimple(_, _) => (),
1002            Self::EnumVariantTuple(_, _, _fields) => todo!(),
1003            Self::EnumVariantStruct(_, _, _fields) => todo!(),
1004            Self::RustValue(_rust_type, _rust_val) => (),
1005            Self::InternalFunction(_) => (),
1006            Self::ExternalFunction(_) => (),
1007            Self::Sparse(_, _) => todo!(),
1008        }
1009    }
1010}
1011
1012/// # Errors
1013///
1014pub fn format_value(value: &Value, spec: &FormatSpecifierKind) -> Result<String, String> {
1015    match (value, spec) {
1016        (Value::Int(n), FormatSpecifierKind::LowerHex) => Ok(format!("{n:x}")),
1017        (Value::Int(n), FormatSpecifierKind::UpperHex) => Ok(format!("{n:X}")),
1018        (Value::Int(n), FormatSpecifierKind::Binary) => Ok(format!("{n:b}")),
1019
1020        (Value::Float(f), FormatSpecifierKind::Float) => Ok(format!("{f}")),
1021        (Value::Float(f), FormatSpecifierKind::Precision(prec, _node, PrecisionType::Float)) => {
1022            Ok(format!("{:.*}", *prec as usize, f))
1023        }
1024
1025        (
1026            Value::String(s),
1027            FormatSpecifierKind::Precision(prec, _node, PrecisionType::String, ..),
1028        ) => Ok(format!("{:.*}", *prec as usize, s)),
1029
1030        _ => Err(format!(
1031            "Unsupported format specifier {spec:?} for value type {value:?}"
1032        )),
1033    }
1034}
1035
1036#[must_use]
1037pub fn convert_vec_to_rc_refcell(vec: Vec<Value>) -> Vec<Rc<RefCell<Value>>> {
1038    vec.into_iter().map(|v| Rc::new(RefCell::new(v))).collect()
1039}