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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use std::{
    cmp::Ordering,
    collections::VecDeque,
    sync::{Mutex, MutexGuard, PoisonError},
};

use crate::{symbol::Symbol, DynamicValue, FaultKind, PoppedValues, Value};

/// A List type for Bud, which wraps a [`VecDeque<Value>`].
///
/// This type uses a [`Mutex`] for interior mutability, allowing lists to be
/// cheaply moved around by reference. Each interaction with this type locks the
/// Mutex.
///
/// [`VecDeque`] was chosen to allow users ultimate flexibility in
/// pushing/popping without worry about performance concerns.
#[derive(Debug)]
pub struct List(Mutex<VecDeque<Value>>);

impl Clone for List {
    fn clone(&self) -> Self {
        Self(Mutex::new(self.list().clone()))
    }
}

impl List {
    fn list(&self) -> MutexGuard<'_, VecDeque<Value>> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Extracts the contained collection type.
    pub fn into_inner(self) -> VecDeque<Value> {
        self.0.into_inner().unwrap_or_else(PoisonError::into_inner)
    }

    /// Pushes `value` to the front of the list.
    pub fn push_front(&self, value: Value) {
        self.list().push_front(value);
    }

    /// Pushes `value` to the back of the list.
    pub fn push_back(&self, value: Value) {
        self.list().push_back(value);
    }

    /// Removes the first value in the list.
    pub fn pop_front(&self) -> Option<Value> {
        self.list().pop_front()
    }

    /// Removes the last value in the list.
    pub fn pop_back(&self) -> Option<Value> {
        self.list().pop_back()
    }

    /// Returns the number of values contained in the list.
    pub fn len(&self) -> usize {
        self.list().len()
    }

    /// Returns true if this list contains no values.
    pub fn is_empty(&self) -> bool {
        self.list().is_empty()
    }

    /// Returns the value contained at `index`, or `None` if `index` is outside
    /// of the bounds of this list.
    pub fn get(&self, index: usize) -> Option<Value> {
        self.list().get(index).cloned()
    }

    /// Removes the value contained at `index`, or `None` if `index` is outside
    /// of the bounds of this list.
    pub fn remove(&self, index: usize) -> Option<Value> {
        let mut list = self.list();
        list.remove(index)
    }
}

impl DynamicValue for List {
    fn is_truthy(&self) -> bool {
        !self.list().is_empty()
    }

    fn kind(&self) -> Symbol {
        Symbol::from("List")
    }

    fn partial_eq(&self, other: &Value) -> Option<bool> {
        let other = other.as_dynamic::<Self>()?;
        let lhs = self.list();
        let rhs = other.list();

        Some(*lhs == *rhs)
    }

    fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
        let other = other.as_dynamic::<Self>()?;
        let other = other.list();
        let mut other = other.iter();

        let rhs = self.list();
        for lhs in rhs.iter() {
            let rhs = match other.next() {
                Some(rhs) => rhs,
                None => return Some(Ordering::Greater),
            };
            match lhs.partial_cmp(rhs) {
                Some(Ordering::Equal) => continue,
                non_equal => return non_equal,
            }
        }
        Some(if other.next().is_some() {
            Ordering::Less
        } else {
            Ordering::Equal
        })
    }

    fn call(&self, name: &Symbol, args: &mut PoppedValues<'_>) -> Result<Value, FaultKind> {
        match name.as_str() {
            "count" => {
                args.verify_empty()?;
                let len = i64::try_from(self.list().len())
                    .map_err(|_| FaultKind::ValueOutOfRange("count"))?;
                Ok(Value::Integer(len))
            }
            "push" => {
                let arg = args.next_argument("value")?;
                args.verify_empty()?;
                let mut list = self.list();
                list.push_back(arg.clone());
                Ok(arg)
            }
            "pop" => {
                args.verify_empty()?;
                let mut list = self.list();
                Ok(list.pop_back().unwrap_or_default())
            }
            "push_front" => {
                let arg = args.next_argument("value")?;
                args.verify_empty()?;
                let mut list = self.list();
                list.push_front(arg.clone());
                Ok(arg)
            }
            "pop_front" => {
                args.verify_empty()?;
                let mut list = self.list();
                Ok(list.pop_front().unwrap_or_default())
            }
            "remove" => {
                let index = args.next_argument("value")?;
                args.verify_empty()?;
                let index = index.as_i64().ok_or_else(|| {
                    FaultKind::invalid_type("index must be an integer", index.clone())
                })?;
                Ok(self
                    .remove(usize::try_from(index).unwrap_or(usize::MAX))
                    .unwrap_or_default())
            }
            _ => Err(FaultKind::UnknownFunction {
                kind: super::ValueKind::Dynamic(self.kind()),
                name: name.clone(),
            }),
        }
    }

    fn to_source(&self) -> Option<String> {
        None
    }

    fn hash<H>(&self, state: &mut H) -> bool
    where
        H: std::hash::Hasher,
    {
        let list = self.list();
        for value in list.iter() {
            if !value.try_hash(state) {
                return false;
            }
        }

        true
    }
}

impl FromIterator<Value> for List {
    fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
        Self(Mutex::new(VecDeque::from_iter(iter)))
    }
}