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
use std::borrow::Cow;

use serde_json::Value;
use unic_segment::Graphemes;

use crate::renderer::stack_frame::Val;

/// Enumerates the two types of for loops
#[derive(Debug, PartialEq)]
pub enum ForLoopKind {
    /// Loop over values, eg an `Array`
    Value,
    /// Loop over key value pairs, eg a `HashMap` or `Object` style iteration
    KeyValue,
}

/// Enumerates the states of a for loop
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ForLoopState {
    /// State during iteration
    Normal,
    /// State on encountering *break* statement
    Break,
    /// State on encountering *continue* statement
    Continue,
}

/// Enumerates on the types of values to be iterated, scalars and pairs
#[derive(Debug)]
pub enum ForLoopValues<'a> {
    /// Values for an array style iteration
    Array(Val<'a>),
    /// Values for a per-character iteration on a string
    String(Val<'a>),
    /// Values for an object style iteration
    Object(Vec<(String, Val<'a>)>),
}

impl<'a> ForLoopValues<'a> {
    pub fn current_key(&self, i: usize) -> String {
        match *self {
            ForLoopValues::Array(_) | ForLoopValues::String(_) => {
                unreachable!("No key in array list or string")
            }
            ForLoopValues::Object(ref values) => {
                values.get(i).expect("Failed getting current key").0.clone()
            }
        }
    }
    pub fn current_value(&self, i: usize) -> Val<'a> {
        match *self {
            ForLoopValues::Array(ref values) => match *values {
                Cow::Borrowed(v) => {
                    Cow::Borrowed(v.as_array().expect("Is array").get(i).expect("Value"))
                }
                Cow::Owned(_) => {
                    Cow::Owned(values.as_array().expect("Is array").get(i).expect("Value").clone())
                }
            },
            ForLoopValues::String(ref values) => {
                let mut graphemes = Graphemes::new(values.as_str().expect("Is string"));
                Cow::Owned(Value::String(graphemes.nth(i).expect("Value").to_string()))
            }
            ForLoopValues::Object(ref values) => values.get(i).expect("Value").1.clone(),
        }
    }
}

// We need to have some data in the renderer for when we are in a ForLoop
// For example, accessing the local variable would fail when
// looking it up in the global context
#[derive(Debug)]
pub struct ForLoop<'a> {
    /// The key name when iterate as a Key-Value, ie in `{% for i, person in people %}` it would be `i`
    pub key_name: Option<String>,
    /// The value name, ie in `{% for person in people %}` it would be `person`
    pub value_name: String,
    /// What's the current loop index (0-indexed)
    pub current: usize,
    /// A list of (key, value) for the forloop. The key is `None` for `ForLoopKind::Value`
    pub values: ForLoopValues<'a>,
    /// Value or KeyValue?
    pub kind: ForLoopKind,
    /// Has the for loop encountered break or continue?
    pub state: ForLoopState,
}

impl<'a> ForLoop<'a> {
    pub fn from_array(value_name: &str, values: Val<'a>) -> Self {
        ForLoop {
            key_name: None,
            value_name: value_name.to_string(),
            current: 0,
            values: ForLoopValues::Array(values),
            kind: ForLoopKind::Value,
            state: ForLoopState::Normal,
        }
    }

    pub fn from_string(value_name: &str, values: Val<'a>) -> Self {
        ForLoop {
            key_name: None,
            value_name: value_name.to_string(),
            current: 0,
            values: ForLoopValues::String(values),
            kind: ForLoopKind::Value,
            state: ForLoopState::Normal,
        }
    }

    pub fn from_object(key_name: &str, value_name: &str, object: &'a Value) -> Self {
        let object_values = object.as_object().unwrap();
        let mut values = Vec::with_capacity(object_values.len());
        for (k, v) in object_values {
            values.push((k.to_string(), Cow::Borrowed(v)));
        }

        ForLoop {
            key_name: Some(key_name.to_string()),
            value_name: value_name.to_string(),
            current: 0,
            values: ForLoopValues::Object(values),
            kind: ForLoopKind::KeyValue,
            state: ForLoopState::Normal,
        }
    }

    pub fn from_object_owned(key_name: &str, value_name: &str, object: Value) -> Self {
        let object_values = match object {
            Value::Object(c) => c,
            _ => unreachable!(
                "Tried to create a Forloop from an object owned but it wasn't an object"
            ),
        };
        let mut values = Vec::with_capacity(object_values.len());
        for (k, v) in object_values {
            values.push((k.to_string(), Cow::Owned(v)));
        }

        ForLoop {
            key_name: Some(key_name.to_string()),
            value_name: value_name.to_string(),
            current: 0,
            values: ForLoopValues::Object(values),
            kind: ForLoopKind::KeyValue,
            state: ForLoopState::Normal,
        }
    }

    #[inline]
    pub fn increment(&mut self) {
        self.current += 1;
        self.state = ForLoopState::Normal;
    }

    pub fn is_key_value(&self) -> bool {
        self.kind == ForLoopKind::KeyValue
    }

    #[inline]
    pub fn break_loop(&mut self) {
        self.state = ForLoopState::Break;
    }

    #[inline]
    pub fn continue_loop(&mut self) {
        self.state = ForLoopState::Continue;
    }

    #[inline]
    pub fn get_current_value(&self) -> Val<'a> {
        self.values.current_value(self.current)
    }

    /// Only called in `ForLoopKind::KeyValue`
    #[inline]
    pub fn get_current_key(&self) -> String {
        self.values.current_key(self.current)
    }

    /// Checks whether the key string given is the variable used as key for
    /// the current forloop
    pub fn is_key(&self, name: &str) -> bool {
        if self.kind == ForLoopKind::Value {
            return false;
        }

        if let Some(ref key_name) = self.key_name {
            return key_name == name;
        }

        false
    }

    pub fn len(&self) -> usize {
        match self.values {
            ForLoopValues::Array(ref values) => values.as_array().expect("Value is array").len(),
            ForLoopValues::String(ref values) => {
                values.as_str().expect("Value is string").chars().count()
            }
            ForLoopValues::Object(ref values) => values.len(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use serde_json::Value;

    use super::ForLoop;

    #[test]
    fn test_that_iterating_on_string_yields_grapheme_clusters() {
        let text = "a\u{310}e\u{301}o\u{308}\u{332}".to_string();
        let string = Value::String(text.clone());
        let mut string_loop = ForLoop::from_string("whatever", Cow::Borrowed(&string));
        assert_eq!(*string_loop.get_current_value(), text[0..3]);
        string_loop.increment();
        assert_eq!(*string_loop.get_current_value(), text[3..6]);
        string_loop.increment();
        assert_eq!(*string_loop.get_current_value(), text[6..]);
    }
}