1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use core::fmt::{self, Write};
use crate::runtime::Variant;
use crate::runtime::gc::{Gc, GcTrace};
use crate::runtime::strings::{StringValue, static_symbol};
use crate::runtime::types::{Type, MetaObject, IterState, UserIterator};
use crate::runtime::errors::{ExecResult, RuntimeError};

#[derive(Clone, Copy)]
pub enum Tuple {
    Empty,
    NonEmpty(Gc<[Variant]>),
}

impl Default for Tuple {
    fn default() -> Self { Self::Empty }
}

impl From<Box<[Variant]>> for Tuple {
    fn from(items: Box<[Variant]>) -> Self {
        if items.is_empty() {
            Self::Empty
        } else {
            Self::NonEmpty(Gc::from_box(items))
        }
    }
}

impl AsRef<[Variant]> for Tuple {
    fn as_ref(&self) -> &[Variant] {
        match self {
            Self::Empty => &[] as &[Variant],
            Self::NonEmpty(items) => &**items,
        }
    }
}

impl Tuple {
    pub fn trace(&self) {
        if let Self::NonEmpty(gc_items) = self {
            gc_items.mark_trace()
        }
    }
    
    pub fn len(&self) -> usize {
        match self {
            Self::Empty => 0,
            Self::NonEmpty(items) => items.len(),
        }
    }
    
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Empty => true,
            Self::NonEmpty(..) => false,
        }
    }
}

impl MetaObject for Tuple {
    fn type_tag(&self) -> Type { Type::Tuple }
    
    fn len(&self) -> Option<ExecResult<usize>> {
        Some(Ok(Tuple::len(self)))
    }
    
    fn iter_init(&self) -> Option<ExecResult<IterState>> {
        let iter: Box<dyn UserIterator> = Box::new(TupleIter(*self));
        let iter = Gc::from_box(iter);
        iter.iter_init()
    }
    
    fn fmt_echo(&self) -> ExecResult<StringValue> {
        match self {
            Self::Empty => Ok(StringValue::from(static_symbol!("()"))),
            
            Self::NonEmpty(items) => {
                let (first, rest) = items.split_first().unwrap(); // should never be empty
                
                let mut buf = String::new();
                
                write!(&mut buf, "({}", first.fmt_echo()?)
                    .map_err(|err| RuntimeError::other(err.to_string()))?;
                
                for item in rest.iter() {
                    write!(&mut buf, ", {}", item.fmt_echo()?)
                        .map_err(|err| RuntimeError::other(err.to_string()))?;
                }
                buf.push(')');

                
                Ok(StringValue::new_maybe_interned(buf))
            }
        }
    }
}

impl fmt::Debug for Tuple {
    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut tuple = fmt.debug_tuple("");
        for item in self.as_ref().iter() {
            tuple.field(item);
        }
        tuple.finish()
    }
}

// Tuple Iterator
#[derive(Debug)]
struct TupleIter(Tuple);

unsafe impl GcTrace for TupleIter {
    fn trace(&self) {
        self.0.trace()
    }
}

impl UserIterator for TupleIter {
    fn get_item(&self, state: &Variant) -> ExecResult<Variant> {
        let idx = usize::try_from(state.as_int()?)
            .map_err(|_| RuntimeError::invalid_value("invalid state"))?;
        
        let items = self.0.as_ref();
        Ok(items[idx])
    }
    
    fn next_state(&self, state: Option<&Variant>) -> ExecResult<Variant> {
        let next = match state {
            Some(state) => state.as_int()?
                .checked_add(1)
                .ok_or(RuntimeError::overflow_error())?,
            
            None => 0,
        };
        
        let next_idx = usize::try_from(next)
            .map_err(|_| RuntimeError::invalid_value("invalid state"))?;
        
        if next_idx >= self.0.len() {
            return Ok(Variant::Nil)
        }
        Ok(Variant::from(next))
    }
}