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
use crate::constants::{EQUAL, NEWLINE, TILDE};
use crate::node_pool::NodeID;
use crate::parse::{parse_element, parse_object};
use crate::types::{Cursor, MarkupKind, MatchError, ParseOpts, Parseable, Parser, Result};
use crate::utils::verify_markup;

macro_rules! recursive_markup {
    ($name: tt) => {
        #[derive(Debug, Clone)]
        pub struct $name(pub Vec<NodeID>);

        impl<'a> Parseable<'a> for $name {
            fn parse(
                parser: &mut Parser<'a>,
                mut cursor: Cursor<'a>,
                parent: Option<NodeID>,
                mut parse_opts: ParseOpts,
            ) -> Result<NodeID> {
                if !verify_markup(cursor, false) {
                    return Err(MatchError::InvalidLogic);
                }
                let start = cursor.index;
                cursor.next();

                parse_opts.from_object = false;
                parse_opts.markup.insert(MarkupKind::$name);

                let mut content_vec: Vec<NodeID> = Vec::new();
                loop {
                    match parse_object(parser, cursor, parent, parse_opts) {
                        Ok(id) => {
                            cursor.index = parser.pool[id].end;
                            content_vec.push(id);
                        }
                        Err(MatchError::MarkupEnd(kind)) => {
                            if !kind.contains(MarkupKind::$name) || cursor.index < start + 2
                            // prevent ** from being Bold{}
                            {
                                return Err(MatchError::InvalidLogic);
                            }

                            // the markup is going to exist,
                            // so update the children's parents
                            let new_id = parser.pool.reserve_id();
                            for id in content_vec.iter_mut() {
                                parser.pool[*id].parent = Some(new_id)
                            }

                            return Ok(parser.alloc_with_id(
                                Self(content_vec),
                                start,
                                cursor.index + 1,
                                parent,
                                new_id,
                            ));
                        }
                        ret @ Err(_) => {
                            return ret;
                        }
                    }
                }
            }
        }
    };
}

/// $name is the name of the Markup object e.g. Code
/// $byte is the closing delimeter for the markup object, e.g. TILDE
macro_rules! plain_markup {
    ($name: tt, $byte: tt) => {

        #[derive(Debug, Clone, Copy)]
        pub struct $name<'a>(pub &'a str);

        impl<'a> Parseable<'a> for $name<'a> {
            fn parse(
                parser: &mut Parser<'a>,
                mut cursor: Cursor<'a>,
                parent: Option<NodeID>,
                mut parse_opts: ParseOpts,
            ) -> Result<NodeID> {
                if !verify_markup(cursor, false) {
                    return Err(MatchError::InvalidLogic);
                }

                // skip the opening character, we checked it's valid markup
                parse_opts.markup.insert(MarkupKind::$name);

                let start = cursor.index;
                cursor.next();

                loop {
                    match cursor.try_curr()? {
                        chr if parse_opts.markup.byte_match(chr) => {
                            if chr == $byte // check if our closer  is active
                                && cursor.index > start + 1 // prevent ~~ from being Bold{}
                                && verify_markup(cursor, true) {
                                break;
                            } else {
                                // FIXME: doesn't handle link end.
                                // [[___][~abc ] amc~ ]]
                                // won't make one cohesive code object, the rbrack will
                                // kill it
                                return Err(MatchError::MarkupEnd(parse_opts.markup));
                            }
                        }
                        NEWLINE => {
                            parse_opts.from_paragraph = true;
                            parse_opts.from_object = false;
                            parse_opts.list_line = false;
                            match parse_element(parser, cursor.adv_copy(1), parent, parse_opts) {
                                Ok(_) => return Err(MatchError::InvalidLogic),
                                Err(MatchError::InvalidLogic) => {
                                    cursor.next();
                                }
                                ret @ Err(_) => return ret,
                            }
                        }
                        _ => {
                            cursor.next();
                        }
                    }
                }

                Ok(parser.alloc(
                    Self(cursor.clamp_backwards(start + 1)),
                    start,
                    cursor.index + 1,
                    parent,
                ))
            }
        }
    };
}

recursive_markup!(Italic);
recursive_markup!(Bold);
recursive_markup!(StrikeThrough);
recursive_markup!(Underline);

plain_markup!(Code, TILDE);
plain_markup!(Verbatim, EQUAL);

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

    #[test]
    fn basic_verbatim() {
        let inp = "=hello_world=";

        dbg!(parse_org(inp));
    }

    #[test]
    fn basic_code() {
        let inp = "~hello_world~";

        dbg!(parse_org(inp));
    }
    #[test]
    fn basic_italic() {
        let inp = "/hello_world/";

        dbg!(parse_org(inp));
    }
    #[test]
    fn basic_bold() {
        let inp = "*hello_world*";

        dbg!(parse_org(inp));
    }
    #[test]
    fn basic_underline() {
        let inp = "_hello_world_";

        dbg!(parse_org(inp));
    }
    #[test]
    fn basic_strikethrough() {
        let inp = "+hello_world+";

        dbg!(parse_org(inp));
    }

    #[test]
    fn markup_recursive_empty() {
        let inp = "**";

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

    #[test]
    fn markup_plain_empty() {
        let inp = "~~";

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

    #[test]
    fn nested_markup() {
        let inp = "abc /one *two* three/ four";

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

    #[test]
    fn leaky_markup() {
        let inp = "abc /one *two thr/ ee* three four";

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

    #[test]
    fn mixed_plain_recursive_leaky_markup() {
        let inp = "abc /one ~two thr/ ee~ three four";

        let pool = parse_org(inp);
        pool.print_tree();
    }
    // #[test]
    // fn
    #[test]
    fn markup_not_fail_on_eof() {
        let inp = "/";
        let pool = parse_org(inp);

        pool.print_tree();
    }

    #[test]
    fn markup_plain_single_char() {
        // should be valid
        let inp = "~a~";
        let pool = parse_org(inp);

        pool.print_tree();
    }

    #[test]
    fn markup_recursive_single_char() {
        // should be valid
        let inp = "/a/";
        let pool = parse_org(inp);

        pool.print_tree();
    }
}