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
use {
    crate::{
        external_error, RuntimeError, Value, ValueList, ValueMap, ValueString, ValueTuple, Vm,
    },
    std::{
        fmt,
        sync::{Arc, Mutex},
    },
    unicode_segmentation::GraphemeCursor,
};

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IntRange {
    pub start: isize,
    pub end: isize,
}

impl IntRange {
    pub fn is_ascending(&self) -> bool {
        self.start <= self.end
    }
}

pub enum ValueIteratorOutput {
    Value(Value),
    ValuePair(Value, Value),
}

pub type ValueIteratorResult = Result<ValueIteratorOutput, RuntimeError>;

#[derive(Debug)]
pub enum Iterable {
    Range(IntRange),
    List(ValueList),
    Tuple(ValueTuple),
    Map(ValueMap),
    Str(ValueString),
    Generator(Box<Vm>),
    External(ExternalIterator),
}

pub struct ExternalIterator(
    Box<dyn FnMut() -> Option<ValueIteratorResult> + Send + Sync + 'static>,
);

impl Iterator for ExternalIterator {
    type Item = ValueIteratorResult;

    fn next(&mut self) -> Option<Self::Item> {
        (self.0)()
    }
}

impl fmt::Debug for ExternalIterator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ExternalIterator")
    }
}

#[derive(Debug)]
pub struct ValueIteratorInternals {
    index: usize,
    iterable: Iterable,
}

impl ValueIteratorInternals {
    fn new(iterable: Iterable) -> Self {
        Self { index: 0, iterable }
    }
}

impl Iterator for ValueIteratorInternals {
    type Item = ValueIteratorResult;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.iterable {
            Iterable::Range(range @ IntRange { .. }) => {
                use Value::Number;

                if range.is_ascending() {
                    let result = range.start + self.index as isize;
                    if result < range.end {
                        self.index += 1;
                        Some(Ok(ValueIteratorOutput::Value(Number(result.into()))))
                    } else {
                        None
                    }
                } else {
                    let result = range.start - self.index as isize;
                    if result > range.end {
                        self.index += 1;
                        Some(Ok(ValueIteratorOutput::Value(Number(result.into()))))
                    } else {
                        None
                    }
                }
            }
            Iterable::List(list) => {
                let result = list
                    .data()
                    .get(self.index)
                    .map(|value| Ok(ValueIteratorOutput::Value(value.clone())));
                self.index += 1;
                result
            }
            Iterable::Tuple(tuple) => {
                let result = tuple
                    .data()
                    .get(self.index)
                    .map(|value| Ok(ValueIteratorOutput::Value(value.clone())));
                self.index += 1;
                result
            }
            Iterable::Map(map) => {
                let result = match map.data().get_index(self.index) {
                    Some((key, value)) => Some(Ok(ValueIteratorOutput::ValuePair(
                        key.clone(),
                        value.clone(),
                    ))),
                    None => None,
                };

                self.index += 1;
                result
            }
            Iterable::Str(s) => {
                let remaining = &s[self.index..];
                match GraphemeCursor::new(0, remaining.len(), true)
                    .next_boundary(remaining, 0)
                    .unwrap() // complete chunk is provided to next_boundary
                {
                    Some(grapheme_end) => {
                        let result = s
                            .with_bounds(self.index..self.index + grapheme_end)
                            .unwrap(); // Some returned from next_boundary implies valid bounds
                        self.index += grapheme_end;
                        Some(Ok(ValueIteratorOutput::Value(Value::Str(result))))
                    }
                    None => None,
                }
            }
            Iterable::Generator(vm) => match vm.continue_running() {
                Ok(Value::Empty) => None,
                Ok(Value::TemporaryTuple(_)) => {
                    unreachable!("Yield shouldn't produce temporary tuples")
                }
                Ok(result) => Some(Ok(ValueIteratorOutput::Value(result))),
                Err(error) => Some(Err(error)),
            },
            Iterable::External(external_iterator) => external_iterator.next(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct ValueIterator(Arc<Mutex<ValueIteratorInternals>>);

impl ValueIterator {
    pub fn new(iterable: Iterable) -> Self {
        Self(Arc::new(Mutex::new(ValueIteratorInternals::new(iterable))))
    }

    pub fn with_range(range: IntRange) -> Self {
        Self::new(Iterable::Range(range))
    }

    pub fn with_list(list: ValueList) -> Self {
        Self::new(Iterable::List(list))
    }

    pub fn with_tuple(tuple: ValueTuple) -> Self {
        Self::new(Iterable::Tuple(tuple))
    }

    pub fn with_map(map: ValueMap) -> Self {
        Self::new(Iterable::Map(map))
    }

    pub fn with_string(s: ValueString) -> Self {
        Self::new(Iterable::Str(s))
    }

    pub fn with_vm(vm: Vm) -> Self {
        Self::new(Iterable::Generator(Box::new(vm)))
    }

    pub fn make_external(
        external: impl FnMut() -> Option<ValueIteratorResult> + Send + Sync + 'static,
    ) -> Self {
        Self::new(Iterable::External(ExternalIterator(Box::new(external))))
    }

    // For internal functions that want to perform repeated iterations with a single lock
    pub fn lock_internals(
        &mut self,
        mut f: impl FnMut(&mut ValueIteratorInternals) -> Option<ValueIteratorResult>,
    ) -> Option<ValueIteratorResult> {
        match self.0.lock() {
            Ok(mut internals) => f(&mut internals),
            Err(_) => Some(external_error!("Failed to access iterator internals")),
        }
    }
}

impl Iterator for ValueIterator {
    type Item = ValueIteratorResult;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.lock() {
            Ok(mut internals) => internals.next(),
            Err(_) => Some(external_error!("Failed to access iterator internals")),
        }
    }
}

pub fn make_iterator(value: &Value) -> Result<ValueIterator, ()> {
    use Value::*;
    let result = match value {
        Range(r) => ValueIterator::with_range(*r),
        List(l) => ValueIterator::with_list(l.clone()),
        Tuple(t) => ValueIterator::with_tuple(t.clone()),
        Map(m) => ValueIterator::with_map(m.clone()),
        Str(s) => ValueIterator::with_string(s.clone()),
        Iterator(i) => i.clone(),
        _ => return Err(()),
    };
    Ok(result)
}