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
//! # Spreadsheet
//!
//!
use crate::ast::{Node, VariableValue, Variables};
use crate::{Result, Row, Runtime};
use serde::{Deserialize, Serialize};
use std::collections;

mod display;

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Spreadsheet {
    pub rows: Vec<Row>,
}

impl Spreadsheet {
    /// Parse the spreadsheet section of a csv++ source file.
    pub fn parse(runtime: &Runtime) -> Result<Spreadsheet> {
        let mut csv_reader = Self::csv_reader(runtime);
        let mut rows: Vec<Row> = vec![];

        for (row_index, result) in csv_reader.records().enumerate() {
            let row = Row::parse(result, row_index, runtime)?;
            rows.push(row);
        }

        Ok(Spreadsheet { rows })
    }

    /// Extract all of the variables that were defined by cells contained in this spreadsheet
    //
    // NOTE: we could also store these in a HashMap on the Spreadsheet as we build it rather than
    // parsing them out at runtime
    pub fn variables(&self) -> Variables {
        let mut vars = collections::HashMap::new();

        for row in &self.rows {
            // does the row itself have a var?
            if let Some(var_id) = &row.modifier.var {
                let reference = if let Some(scope) = row.modifier.expand {
                    // if there's also an expand it's relative to that
                    Node::Variable {
                        name: var_id.clone(),
                        value: VariableValue::RowRelative {
                            scope,
                            row: row.row,
                        },
                    }
                } else {
                    // otherwise it's just relative to the single row where it was defined
                    Node::Variable {
                        name: var_id.clone(),
                        value: VariableValue::Row(row.row),
                    }
                };

                vars.insert(var_id.to_owned(), Box::new(reference));
            };

            row.cells.iter().for_each(|c| {
                if let Some(var_id) = &c.modifier.var {
                    let reference = if let Some(scope) = row.modifier.expand {
                        Node::Variable {
                            name: var_id.clone(),
                            value: VariableValue::ColumnRelative {
                                scope,
                                column: c.position.column,
                            },
                        }
                    } else {
                        Node::Variable {
                            name: var_id.clone(),
                            value: VariableValue::Absolute(c.position),
                        }
                    };

                    vars.insert(var_id.to_owned(), Box::new(reference));
                }
            });
        }

        vars
    }

    fn csv_reader(runtime: &Runtime) -> csv::Reader<&[u8]> {
        csv::ReaderBuilder::new()
            .has_headers(false)
            .flexible(true)
            .trim(csv::Trim::All)
            .from_reader(runtime.source_code.csv_section.as_bytes())
    }

    pub fn widest_row(&self) -> usize {
        self.rows
            .iter()
            .map(|row| row.cells.len())
            .max()
            .unwrap_or(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::modifier::TextFormat;
    use crate::test_utils::*;
    use crate::*;
    use a1_notation::Address;

    fn build_runtime(input: &str) -> Runtime {
        TestFile::new("csv", input).into()
    }

    #[test]
    fn parse_simple() {
        let runtime = build_runtime("foo,bar,baz\n1,2,3\n");
        let spreadsheet = Spreadsheet::parse(&runtime).unwrap();

        // 2 rows
        assert_eq!(spreadsheet.rows.len(), 2);

        // each row has 3 cells
        assert_eq!(spreadsheet.rows[0].cells.len(), 3);
        assert_eq!(spreadsheet.rows[1].cells.len(), 3);

        // the cells have the correct positions
        assert_eq!(spreadsheet.rows[0].cells[0].position.to_string(), "A1");
        assert_eq!(spreadsheet.rows[0].cells[1].position.to_string(), "B1");
        assert_eq!(spreadsheet.rows[0].cells[2].position.to_string(), "C1");
        assert_eq!(spreadsheet.rows[1].cells[0].position.to_string(), "A2");
        assert_eq!(spreadsheet.rows[1].cells[1].position.to_string(), "B2");
        assert_eq!(spreadsheet.rows[1].cells[2].position.to_string(), "C2");

        // each row has a parsed value
        assert_eq!(spreadsheet.rows[0].cells[0].value, "foo");
        assert_eq!(spreadsheet.rows[0].cells[1].value, "bar");
        assert_eq!(spreadsheet.rows[0].cells[2].value, "baz");
        assert_eq!(spreadsheet.rows[1].cells[0].value, "1");
        assert_eq!(spreadsheet.rows[1].cells[1].value, "2");
        assert_eq!(spreadsheet.rows[1].cells[2].value, "3");

        // none have ASTs (didn't start with `=`)
        assert!(spreadsheet.rows[0].cells[0].ast.is_none());
        assert!(spreadsheet.rows[0].cells[1].ast.is_none());
        assert!(spreadsheet.rows[0].cells[2].ast.is_none());
        assert!(spreadsheet.rows[1].cells[0].ast.is_none());
        assert!(spreadsheet.rows[1].cells[1].ast.is_none());
        assert!(spreadsheet.rows[1].cells[2].ast.is_none());
    }

    #[test]
    fn parse_with_asts() {
        let runtime = build_runtime("=1,=2 * 3,=foo\n");
        let spreadsheet = Spreadsheet::parse(&runtime).unwrap();

        assert!(spreadsheet.rows[0].cells[0].ast.is_some());
        assert!(spreadsheet.rows[0].cells[1].ast.is_some());
        assert!(spreadsheet.rows[0].cells[2].ast.is_some());
    }

    #[test]
    fn parse_trim_spaces() {
        let runtime = build_runtime("   foo   , bar\n");
        let spreadsheet = Spreadsheet::parse(&runtime).unwrap();

        assert_eq!(spreadsheet.rows[0].cells[0].value, "foo");
        assert_eq!(spreadsheet.rows[0].cells[1].value, "bar");
    }

    #[test]
    fn parse_with_modifiers() {
        let runtime = build_runtime("[[f=b / fs=20]]foo");
        let spreadsheet = Spreadsheet::parse(&runtime).unwrap();

        assert!(spreadsheet.rows[0].cells[0]
            .modifier
            .formats
            .contains(&TextFormat::Bold));
        assert_eq!(spreadsheet.rows[0].cells[0].modifier.font_size, Some(20))
    }

    #[test]
    fn parse_with_row_modifier() {
        let runtime = build_runtime("![[f=b]]foo,bar,baz");
        let spreadsheet = Spreadsheet::parse(&runtime).unwrap();

        assert!(spreadsheet.rows[0].cells[0]
            .modifier
            .formats
            .contains(&TextFormat::Bold));
        assert!(spreadsheet.rows[0].cells[1]
            .modifier
            .formats
            .contains(&TextFormat::Bold));
        assert!(spreadsheet.rows[0].cells[2]
            .modifier
            .formats
            .contains(&TextFormat::Bold));
    }

    #[test]
    fn variables_unscoped() {
        let spreadsheet = Spreadsheet {
            rows: vec![Row {
                row: 0.into(),
                modifier: RowModifier::default(),
                cells: vec![
                    Cell {
                        ast: None,
                        position: Address::new(0, 0),
                        modifier: Modifier {
                            var: Some("foo".to_string()),
                            ..Default::default()
                        },
                        value: "".to_string(),
                    },
                    Cell {
                        ast: None,
                        position: Address::new(1, 1),
                        modifier: Modifier {
                            var: Some("bar".to_string()),
                            ..Default::default()
                        },
                        value: "".to_string(),
                    },
                ],
            }],
        };

        let variables = spreadsheet.variables();
        assert_eq!(
            **variables.get("foo").unwrap(),
            Node::var("foo", VariableValue::Absolute(Address::new(0, 0)))
        );
        assert_eq!(
            **variables.get("bar").unwrap(),
            Node::var("bar", VariableValue::Absolute(Address::new(1, 1)))
        );
    }

    #[test]
    fn variables_with_scope() {
        let spreadsheet = Spreadsheet {
            rows: vec![
                Row {
                    row: 0.into(),
                    modifier: RowModifier {
                        expand: Some(Expand::new(0, Some(10))),
                        ..Default::default()
                    },
                    cells: vec![Cell {
                        ast: None,
                        position: (0, 0).into(),
                        modifier: Modifier {
                            var: Some("foo".to_string()),
                            ..Default::default()
                        },
                        value: "".to_string(),
                    }],
                },
                Row {
                    row: 1.into(),
                    modifier: RowModifier {
                        expand: Some(Expand::new(10, Some(100))),
                        ..Default::default()
                    },
                    cells: vec![Cell {
                        ast: None,
                        position: (1, 1).into(),
                        modifier: Modifier {
                            var: Some("bar".to_string()),
                            ..Default::default()
                        },
                        value: "".to_string(),
                    }],
                },
            ],
        };

        let variables = spreadsheet.variables();
        assert_eq!(
            **variables.get("foo").unwrap(),
            Node::var(
                "foo",
                VariableValue::ColumnRelative {
                    scope: Expand {
                        amount: Some(10),
                        start_row: 0.into()
                    },
                    column: 0.into(),
                }
            )
        );
        assert_eq!(
            **variables.get("bar").unwrap(),
            Node::var(
                "bar",
                VariableValue::ColumnRelative {
                    scope: Expand {
                        amount: Some(100),
                        start_row: 10.into()
                    },
                    column: 1.into(),
                }
            )
        );
    }

    #[test]
    fn widest_row() {
        let cell = Cell {
            ast: None,
            position: Address::new(0, 0),
            modifier: Modifier::default(),
            value: "foo".to_string(),
        };
        let spreadsheet = Spreadsheet {
            rows: vec![
                Row {
                    cells: vec![cell.clone()],
                    row: 0.into(),
                    modifier: RowModifier::default(),
                },
                Row {
                    cells: vec![cell.clone(), cell.clone()],
                    row: 1.into(),
                    modifier: RowModifier::default(),
                },
                Row {
                    cells: vec![cell.clone(), cell.clone(), cell.clone()],
                    row: 2.into(),
                    modifier: RowModifier::default(),
                },
            ],
        };

        assert_eq!(spreadsheet.widest_row(), 3);
    }
}