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
use crate::constants::{HYPHEN, NEWLINE};
use crate::node_pool::NodeID;
use crate::object::TableCell;
use crate::types::{Cursor, Expr, MarkupKind, ParseOpts, Parseable, Parser, Result};

/// A table consisting of a collection of [`TableRow`]s
///
/// | one | two |
/// | three | four |
#[derive(Debug, Clone)]
pub struct Table {
    pub rows: usize,
    pub cols: usize,
    pub children: Vec<NodeID>,
}

/// A row of a [`Table`] consisting of [`TableCell`]s or a [`TableRow::Rule`].
///
/// A [`TableRow::Rule`] occurs when a row begins with a hyphen:
///
/// ```text
/// |1|2|
/// |---|
/// |3|4|
/// ```
///
/// This table's rows are:
///
/// ```text
/// TableRow::Standard(TableCell, TableCell)
/// TableRow::Rule
/// TableRow::Standard(TableCell, TableCell)
/// ```
#[derive(Debug, Clone)]
pub enum TableRow {
    Rule, // hrule
    Standard(Vec<NodeID>),
}

impl<'a> Parseable<'a> for Table {
    fn parse(
        parser: &mut Parser<'a>,
        mut cursor: Cursor<'a>,
        parent: Option<NodeID>,
        mut parse_opts: ParseOpts,
    ) -> Result<NodeID> {
        let start = cursor.index;

        // we are a table now
        parse_opts.markup.insert(MarkupKind::Table);
        let reserve_id = parser.pool.reserve_id();
        let mut children: Vec<NodeID> = Vec::new();
        let mut rows = 0;
        let mut cols = 0;
        while let Ok(row_id) = TableRow::parse(parser, cursor, Some(reserve_id), parse_opts) {
            let obj = &parser.pool[row_id];

            children.push(row_id);
            rows += 1;
            if let Expr::TableRow(TableRow::Standard(node_ids)) = &obj.obj {
                cols = cols.max(node_ids.len());
            }

            cursor.index = parser.pool[row_id].end;
        }

        Ok(parser.alloc_with_id(
            Self {
                rows,
                cols,
                children,
            },
            start,
            cursor.index,
            parent,
            reserve_id,
        ))
    }
}

impl<'a> Parseable<'a> for TableRow {
    fn parse(
        parser: &mut Parser<'a>,
        mut cursor: Cursor<'a>,
        parent: Option<NodeID>,
        parse_opts: ParseOpts,
    ) -> Result<NodeID> {
        let start = cursor.index;

        // TODO: doesn't play well with lists
        // should break if the indentation is not even for the next element in the list
        // but shouldn't break otherwise
        cursor.is_index_valid()?;
        cursor.skip_ws();
        cursor.word("|")?;

        // implies horizontal rule
        // |-
        if cursor.try_curr()? == HYPHEN {
            // adv_till_byte handles eof
            cursor.adv_till_byte(b'\n');
            // cursor.index + 1 to start at the next | on the next line
            return Ok(parser
                .pool
                .alloc(Self::Rule, start, cursor.index + 1, parent));
        }

        let mut children: Vec<NodeID> = Vec::new();
        while let Ok(table_cell_id) = TableCell::parse(parser, cursor, parent, parse_opts) {
            let node_item = &parser.pool[table_cell_id];
            children.push(table_cell_id);

            cursor.index = node_item.end;
            // REVIEW: use try_curr in case of table ending at eof?
            if cursor.curr() == NEWLINE {
                cursor.next();
                break;
            }
        }

        Ok(parser
            .pool
            .alloc(Self::Standard(children), start, cursor.index, parent))
    }
}

#[cfg(test)]
mod tests {
    use crate::parse_org;

    #[test]
    fn basic_table() {
        let input = r"
|one|two|
|three|four|
";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_eof_1() {
        let input = r"
|one|two|
|three|four|
";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    #[should_panic]
    // we don't handle the eof case for table cells /shrug/
    fn table_eof_2() {
        let input = r"
|one|two|
|three|four|";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_no_nl() {
        let input = r"
|one|two
|three|four

";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_with_hrule() {
        let input = r"
|one|two
|--------|
|three|four

";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_markup_1() {
        let input = r"
|one|tw *o*                                      |
|three|four|
";
        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_empty_cells() {
        let input = r"
||a|
|b||
";
        let pool = parse_org(input);

        pool.print_tree();
    }

    /// test that alignment spaces are removed
    #[test]
    fn table_aligned_cells() {
        let input = r"
|one two |three|
|s       |     |
";

        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_uneven_cols() {
        let input = r"
|one two |three|||||
|s       |     |
";

        let pool = parse_org(input);

        pool.print_tree();
    }

    #[test]
    fn table_indented() {
        let input = r"
word
        |one two |three|
        |s       |     |
        |four | five|
word

";

        let pool = parse_org(input);
        pool.print_tree();
    }

    #[test]
    fn table_indented_list() {
        let input = r"
- one
   - two
        |one two |three|
        |s       |     |
        |four | five|
- three
";

        let pool = parse_org(input);

        pool.print_tree();
    }

    // #[test]
    // #[should_panic]
    // fn table_no_start() {
    //     let input = r"|";

    //     let pool = parse_org(input);

    //     pool.pool.root().print_tree(&pool);
    // }
}