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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! List object
use super::{BoxedObject, Iter, Object, RefValue};
use tokay_macros::tokay_method;
extern crate self as tokay;

/// Alias for the inner list definition
type InnerList = Vec<RefValue>;

/// List object type
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct List {
    list: InnerList,
}

impl Object for List {
    fn severity(&self) -> u8 {
        30
    }

    fn name(&self) -> &'static str {
        "list"
    }

    fn repr(&self) -> String {
        let mut ret = "(".to_string();
        for item in self.iter() {
            if ret.len() > 1 {
                ret.push_str(", ");
            }

            ret.push_str(&item.borrow().repr());
        }

        if self.len() == 1 {
            ret.push_str(", ");
        }

        ret.push(')');
        ret
    }

    fn is_true(&self) -> bool {
        self.len() > 0
    }

    fn is_mutable(&self) -> bool {
        true
    }
}

impl List {
    pub fn new() -> Self {
        Self {
            list: InnerList::new(),
        }
    }

    pub fn with_capacity(len: usize) -> Self {
        Self {
            list: InnerList::with_capacity(len),
        }
    }

    tokay_method!("list : @*args", {
        let list = if args.len() == 1 {
            // In case of an iter, use the collect-method
            if args[0].is("iter") {
                return Ok(args[0]
                    .call_method("collect", context, Vec::new())?
                    .unwrap());
            }
            // Otherwise, create a list with one item
            else {
                List::from(args[0].clone())
            }
        }
        // When multiple items are provided, turn these into list items
        else {
            List { list: args }
        };

        Ok(RefValue::from(list))
    });

    tokay_method!("list_len : @list", {
        let list = list.borrow();

        Ok(RefValue::from(if let Some(list) = list.object::<List>() {
            list.len()
        } else {
            1
        }))
    });

    tokay_method!("list_get_item : @list, item, default=void", {
        // In case list is not a list, make it a list.
        if !list.is("list") {
            list = Self::list(vec![list], None)?;
        }

        let list = list.borrow();

        if let Ok(item) = item.to_usize() {
            if let Some(value) = list.object::<List>().unwrap().get(item) {
                return Ok(value.clone());
            }
        }

        Ok(default)
    });

    tokay_method!("list_set_item : @list, item, value=void", {
        // In case list is not a list, make it a list.
        if !list.is("list") {
            list = Self::list(vec![list], None)?;
        }

        let mut list = list.borrow_mut();
        let list = list.object_mut::<List>().unwrap();

        let item = item.to_usize()?;
        let len = list.len();

        if item >= len {
            return Err(format!(
                "{} assignment index {} beyond list sized {}",
                __function, item, len
            )
            .into());
        }

        if value.is_void() {
            value = list.remove(item);
        } else {
            list[item] = value.clone();
        }

        Ok(value)
    });

    tokay_method!("list_flatten : @list", {
        if let Some(list) = list.borrow().object::<List>() {
            let mut ret = List::with_capacity(list.len());

            for item in list.iter() {
                if let Some(list) = item.borrow().object::<List>() {
                    for item in list.iter() {
                        ret.push(item.clone());
                    }
                } else {
                    ret.push(item.clone());
                }
            }

            return Ok(RefValue::from(ret));
        }

        Ok(RefValue::from(crate::value!([list])))
    });

    tokay_method!("list_iadd : @list, append", {
        // Don't append void
        if append.is_void() {
            return Ok(list);
        }

        // In case list is not a list, make it a list.
        if !list.is("list") {
            let item = RefValue::from(list.borrow().clone());
            list = Self::list(vec![item], None)?;
        }

        // Extend in-place when possible.
        if let (Ok(mut inner), Ok(to_append)) = (list.try_borrow_mut(), append.try_borrow()) {
            let inner = inner.object_mut::<List>().unwrap();

            // When append is a list, append all items to list
            if let Some(append) = to_append.object::<List>() {
                inner.reserve(append.len());

                for item in append.iter() {
                    inner.push(item.clone());
                }
            // Otherwise, just push append to the list.
            } else {
                inner.push(append.clone());
            }

            return Ok(list.clone());
        }

        // Otherwise, perform ordinary add first, then re-assign to list
        let new = Self::list_add(vec![list.clone(), append.clone()], None)?;
        *list.borrow_mut() = new.into();

        Ok(list)
    });

    tokay_method!("list_add : @list, append", {
        // Don't append void
        if append.is_void() {
            return Ok(list);
        }

        // In case list is not a list, make it a list.
        if !list.is("list") {
            list = Self::list(vec![list], None)?;
        }

        let mut list = list.borrow().object::<List>().unwrap().clone();

        // When append is a list, append all items to list
        if let Some(append) = append.borrow().object::<List>() {
            list.reserve(append.len());

            for item in append.iter() {
                list.push(item.clone());
            }
        // Otherwise, just push append to the list.
        } else {
            list.push(append.clone());
        }

        Ok(RefValue::from(list))
    });

    tokay_method!("list_push : @list, item, index=void", {
        // Don't push void
        if item.is_void() {
            return Ok(list);
        }

        // In case list is not a list, make it a list.
        if !list.is("list") {
            list = Self::list(vec![list], None)?;
        }

        // list_push returns the list itself, therefore this block.
        {
            let mut list = list.borrow_mut();
            let list = list.object_mut::<List>().unwrap();

            if index.is_void() {
                list.push(item);
            } else {
                let index = index.to_usize()?;
                let len = list.len();

                if index > len {
                    return Err(format!(
                        "{} provided index {} out of range in list sized {}",
                        __function, index, len
                    )
                    .into());
                }

                list.insert(index, item);
            }
        }

        Ok(list)
    });

    tokay_method!("list_pop : @list, index=void", {
        let index = if index.is_void() {
            None
        } else {
            Some(index.to_usize()?)
        };

        if !list.is("list") {
            if index.is_none() {
                return Ok(list); // "pops" the list, which is not a list
            }

            return Err(format!(
                "{} provided index {} out of range",
                __function,
                index.unwrap()
            )
            .into());
        }

        let mut list = list.borrow_mut();
        let list = list.object_mut::<List>().unwrap();

        // Either pop or remove, regarding index setting.
        match index {
            None => match list.pop() {
                Some(item) => Ok(item),
                None => {
                    return Err(format!("{} can't pop off empty list", __function).into());
                }
            },
            Some(index) => {
                let len = list.len();

                if index >= len {
                    return Err(format!(
                        "{} provided index {} out of range of list sized {}",
                        __function, index, len
                    )
                    .into());
                }

                Ok(list.remove(index))
            }
        }
    });

    tokay_method!("list_sort : @list", {
        if !list.is("list") {
            return Ok(Self::list(vec![list], None)?);
        }

        {
            let mut list = list.borrow_mut();
            let list = list.object_mut::<List>().unwrap();
            list.sort();
        }

        Ok(list)
    });
}

impl std::ops::Deref for List {
    type Target = InnerList;

    fn deref(&self) -> &Self::Target {
        &self.list
    }
}

impl std::ops::DerefMut for List {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.list
    }
}

impl std::iter::IntoIterator for List {
    type Item = RefValue;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.list.into_iter()
    }
}

impl From<RefValue> for List {
    fn from(refvalue: RefValue) -> Self {
        match refvalue.name() {
            "iter" => {
                let mut iter = refvalue.borrow_mut();
                let iter = iter.object_mut::<Iter>().unwrap();
                let mut list = InnerList::new();

                for item in iter {
                    list.push(item);
                }

                Self { list }
            }
            "list" => {
                let list = refvalue.borrow();
                let list = list.object::<List>().unwrap();
                (*list).clone()
            }
            _ => Self {
                list: vec![refvalue.clone()],
            },
        }
    }
}

impl From<&RefValue> for List {
    fn from(refvalue: &RefValue) -> Self {
        List::from(refvalue.clone())
    }
}

impl From<List> for RefValue {
    fn from(value: List) -> Self {
        RefValue::from(Box::new(value) as BoxedObject)
    }
}

impl From<InnerList> for RefValue {
    fn from(list: InnerList) -> Self {
        RefValue::from(List { list })
    }
}