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
use crate::*;
use derive_more::Display;
use unicode_segmentation::UnicodeSegmentation;

#[derive(Debug, Display, Clone)]
enum LexerError {
    #[display(fmt = "I expected `{}`", _0)]
    UnexpectedToken(&'static str),
}

pub mod utf {
    use super::*;

    pub trait StateExt {
        fn peek_nth(&mut self, len: usize) -> Span;

        fn nth(&mut self, len: usize) -> Span;

        fn next(&mut self) -> Span;

        fn peek(&mut self, len: usize) -> Span;

        fn chomp(&mut self, len: usize) -> Span;

        fn chomp_while(&mut self, f: impl Fn(&str) -> bool) -> Span;
    }

    impl StateExt for State {
        fn peek_nth(&mut self, len: usize) -> Span {
            peek_nth(len).parse(self)
        }

        fn nth(&mut self, len: usize) -> Span {
            nth(len).parse(self)
        }

        fn next(&mut self) -> Span {
            next().parse(self)
        }

        fn peek(&mut self, len: usize) -> Span {
            peek(len).parse(self)
        }

        fn chomp(&mut self, len: usize) -> Span {
            chomp(len).parse(self)
        }

        fn chomp_while(&mut self, f: impl Fn(&str) -> bool) -> Span {
            chomp_while(f).parse(self)
        }
    }

    pub fn peek_nth(len: usize) -> impl Parser<Span> {
        move |state: &mut State| {
            let mut iter = state.input.graphemes_idx();

            let (offset, len) = iter.nth(len).map(|(o, g)| (o, g.len())).unwrap_or_default();

            let mut output = state.input.clone();
            output.range.0 += offset;
            output.range.1 = len;

            output
        }
    }

    pub fn nth(len: usize) -> impl Parser<Span> {
        move |state: &mut State| {
            let output = peek_nth(len).parse(state);
            state.input.range.0 += output.range.0 + output.range.1;
            state.input.range.1 -= output.range.0 + output.range.1;

            output
        }
    }

    pub fn next() -> impl Parser<Span> {
        nth(0)
    }

    pub fn peek(len: usize) -> impl Parser<Span> {
        move |state: &mut State| {
            let iter = state.input.graphemes_idx();
            let (offset, grapheme) = iter.take(len).last().unwrap_or_default();
            let mut output = state.input.clone();
            let len = offset + grapheme.len();
            output.range.1 = len;
            output
        }
    }

    pub fn chomp(len: usize) -> impl Parser<Span> {
        move |state: &mut State| {
            let output = peek(len).parse(state);
            state.input.range.0 += output.range.1;
            state.input.range.1 -= output.range.1;
            output
        }
    }

    pub fn chomp_if(f: impl Fn(&str) -> bool) -> impl Parser<Span> {
        move |state: &mut State| {
            let current = peek_nth(0).parse(state);
            let current = match current.as_ref() {
                "" => return chomp(0).parse(state),
                c => c,
            };
            let len = if f(current) { 1 } else { 0 };
            chomp(len).parse(state)
        }
    }

    pub fn chomp_until(f: impl Fn(&str) -> bool) -> impl Parser<Span> {
        chomp_while(move |c| !f(c))
    }

    pub fn chomp_until_eof() -> impl Parser<Span> {
        chomp_until(move |c| c == "")
    }

    pub fn chomp_while(f: impl Fn(&str) -> bool) -> impl Parser<Span> {
        move |state: &mut State| {
            let mut len = 0usize;
            loop {
                let current = peek_nth(len).parse(state);
                let current = match current.as_ref() {
                    "" => return chomp(len).parse(state),
                    c => c,
                };
                let valid = f(current);
                if valid {
                    len += 1;
                } else {
                    return chomp(len).parse(state);
                }
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use test_case::test_case;
        const INPUT: &str = "a\u{310}e\u{301}o\u{308}\u{332}\r\n";

        #[test_case(peek_nth(0), "a\u{310}", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(peek_nth(1), "e\u{301}", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(peek_nth(3), "\r\n", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(peek_nth(4), "", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(nth(0), "a\u{310}", "e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(nth(1), "e\u{301}", "o\u{308}\u{332}\r\n")]
        #[test_case(nth(3), "\r\n", "")]
        #[test_case(nth(4), "", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(next(), "a\u{310}", "e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(peek(0), "", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(peek(1), "a\u{310}", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(
            peek(3),
            "a\u{310}e\u{301}o\u{308}\u{332}",
            "a\u{310}e\u{301}o\u{308}\u{332}\r\n"
        )]
        #[test_case(
            peek(99),
            "a\u{310}e\u{301}o\u{308}\u{332}\r\n",
            "a\u{310}e\u{301}o\u{308}\u{332}\r\n"
        )]
        #[test_case(chomp(0), "", "a\u{310}e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(chomp(1), "a\u{310}", "e\u{301}o\u{308}\u{332}\r\n")]
        #[test_case(chomp(3), "a\u{310}e\u{301}o\u{308}\u{332}", "\r\n")]
        #[test_case(chomp(99), "a\u{310}e\u{301}o\u{308}\u{332}\r\n", "")]
        #[test_case(chomp_while(|c| { c != "\n" && c != "\r\n" }),               "a\u{310}e\u{301}o\u{308}\u{332}",  "\r\n")]
        #[test_case(chomp_until(|c| { c == "\n" || c == "\r\n" }),               "a\u{310}e\u{301}o\u{308}\u{332}",  "\r\n")]
        fn test_parser(p: impl Parser<Span>, expected: &'static str, expected_rest: &'static str) {
            let mut state: State = INPUT.into();
            let actual = p.parse(&mut state);
            assert_eq!(actual.as_ref(), expected);
            let rest = state.input;
            assert_eq!(rest.as_ref(), expected_rest);
        }
    }
}

impl Parser for &'static str {
    fn parse(&self, state: &mut State) -> Node {
        token(self).parse(state)
    }
}

impl Parser<Span> for &'static str {
    fn parse(&self, state: &mut State) -> Span {
        let token_len = self.graphemes(true).count();

        let output = utf::peek(token_len).parse(state);
        match output {
            n if n.as_ref() == *self => utf::chomp(token_len).parse(state),
            _ => utf::chomp(0).parse(state),
        }
    }
}

pub fn token(token: &'static str) -> impl Parser {
    let token_len = token.graphemes(true).count();

    move |state: &mut State| {
        let output = utf::peek(token_len).parse(state);
        match output {
            n if n.as_ref() == token => {
                utf::chomp(token_len).parse(state);
                Node::token(n)
            }
            n => raise(LexerError::UnexpectedToken(token), n.len()).parse(state),
        }
    }
}

pub fn recognize1(
    name: NodeId,
    parser: impl Parser<Span>,
    problem: impl Problem + Clone + 'static,
) -> impl Parser {
    move |state: &mut State| {
        let output = parser.parse(state);

        match output {
            result if !result.is_empty() => Node {
                name,
                span: result,
                children: vec![],
                alias: vec![],
            },
            _ => raise(problem.clone(), 0).parse(state),
        }
    }
}

pub fn recognize(name: NodeId, parser: impl Parser<Span>) -> impl Parser {
    move |state: &mut State| {
        let output = parser.parse(state);

        match output {
            result if !result.is_empty() => Node {
                name,
                span: result,
                children: vec![],
                alias: vec![],
            },
            _ => none().parse(state),
        }
    }
}