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
340
341
342
343
344
345
346
347
348
349
350
use std::{ops::Range, path::Path};

use crate::{
    error::{ParseError, Result, Wanted, Warn},
    loader::{CachedFile, LogixLoader},
    span::SourceSpan,
    token::{parse_token, Brace, Delim, ParseRes, Token},
    type_trait::Value,
    types::ShortStr,
    LogixType,
};
use bstr::ByteSlice;
use logix_vfs::LogixVfs;

mod delimited;
pub use delimited::ParseDelimited;

#[derive(Clone)]
struct ParseState {
    cur_pos: usize,
    cur_col: usize,
    cur_ln: usize,
    last_was_newline: bool,
    eof: bool,
}

/// The parser used by the `LogixType` trait
pub struct LogixParser<'fs, 'f, FS: LogixVfs> {
    loader: &'fs mut LogixLoader<FS>,
    file: &'f CachedFile,
    state: ParseState,
}

impl<'fs, 'f, FS: LogixVfs> LogixParser<'fs, 'f, FS> {
    pub(crate) fn new(loader: &'fs mut LogixLoader<FS>, file: &'f CachedFile) -> Self {
        Self {
            loader,
            file,
            state: ParseState {
                cur_pos: 0,
                cur_col: 0,
                cur_ln: 1,
                last_was_newline: true,
                eof: false,
            },
        }
    }

    pub fn warning(&self, warning: Warn) -> Result<()> {
        // TODO(2023.10): Make it possible to allow warnings
        Err(ParseError::Warning(warning))
    }

    pub fn cur_span(&self) -> SourceSpan {
        self.calc_span(0..0)
    }

    fn calc_span(&self, range: Range<usize>) -> SourceSpan {
        SourceSpan::new(
            self.file,
            self.state.cur_pos + range.start,
            self.state.cur_ln,
            self.state.cur_col + range.start,
            range.len(),
        )
    }

    pub fn peek_token(&mut self) -> Result<(SourceSpan, Token<'f>)> {
        let mut fork = LogixParser {
            loader: self.loader,
            file: self.file,
            state: self.state.clone(),
        };
        fork.next_token()
    }

    pub fn next_token(&mut self) -> Result<(SourceSpan, Token<'f>)> {
        if self.state.eof {
            return Ok((self.calc_span(0..0), Token::Newline(true)));
        }

        'outer: loop {
            let last_was_newline = std::mem::take(&mut self.state.last_was_newline);

            'ignore_token: loop {
                let buf = &self.file.data()[self.state.cur_pos..];
                let (span, token) = {
                    let ParseRes {
                        len,
                        range,
                        lines,
                        token,
                    } = parse_token(buf);
                    let span = self.calc_span(range);

                    self.state.cur_pos += len;
                    if lines > 0 {
                        debug_assert_ne!(len, 0);

                        self.state.cur_ln += lines;
                        if len == 1 {
                            self.state.cur_col = 0;
                        } else {
                            self.state.cur_col = self.file.data()[..self.state.cur_pos]
                                .lines()
                                .next_back()
                                .unwrap()
                                .len();
                        }
                    } else {
                        self.state.cur_col += len;
                    }
                    (span, token)
                };

                return match token {
                    Ok(
                        token @ (Token::Ident(..)
                        | Token::Action(..)
                        | Token::Brace { .. }
                        | Token::Delim(..)
                        | Token::Literal(..)),
                    ) => Ok((span, token)),
                    Ok(Token::Newline(eof)) => {
                        self.state.last_was_newline = true;
                        if !eof && last_was_newline {
                            continue 'outer;
                        }
                        self.state.eof = eof;
                        Ok((span, Token::Newline(eof)))
                    }
                    Ok(Token::Comment(_)) => {
                        continue 'ignore_token;
                    }
                    Err(error) => Err(ParseError::TokenError { span, error }),
                };
            }
        }
    }

    // TODO(2023.10): Switch to using this where possible
    /// Create a new parser that must start with the given brace, and once it returns, must
    /// point to the ending brace
    pub fn req_wrapped<R>(
        &mut self,
        while_parsing: &'static str,
        brace: Brace,
        f: impl FnOnce(&mut LogixParser<FS>) -> Result<R>,
    ) -> Result<Value<R>> {
        let start = self.req_token(while_parsing, Token::Brace { start: true, brace })?;
        let value = f(self)?;
        let end = self.req_token(
            while_parsing,
            Token::Brace {
                start: false,
                brace,
            },
        )?;
        Ok(Value { value, span: start }.join_with_span(end))
    }

    /// Parse a list of items that may be delimited by comma, newline or both
    pub fn parse_delimited<'p, R: LogixType>(
        &'p mut self,
        while_parsing: &'static str,
    ) -> ParseDelimited<'p, 'fs, 'f, FS, R> {
        ParseDelimited::new(self, while_parsing)
    }

    pub fn req_token(
        &mut self,
        while_parsing: &'static str,
        want_token: Token<'static>,
    ) -> Result<SourceSpan> {
        let (span, got_token) = self.next_token()?;

        if want_token == got_token {
            Ok(span)
        } else {
            Err(ParseError::UnexpectedToken {
                span,
                while_parsing,
                wanted: Wanted::Token(want_token),
                got_token: got_token.token_type_name(),
            })
        }
    }

    pub fn read_key_value<T: LogixType>(
        &mut self,
        while_parsing: &'static str,
        end_brace: Brace,
    ) -> Result<Option<(Value<ShortStr>, Value<T>)>> {
        match self.next_token()? {
            (span, Token::Ident(key)) => {
                let key = Value {
                    value: ShortStr::from(key),
                    span,
                };

                self.req_token(while_parsing, Token::Delim(Delim::Colon))?;

                let value = T::logix_parse(self)?;

                self.req_newline(while_parsing)?;

                Ok(Some((key, value)))
            }
            (
                _,
                Token::Brace {
                    start: false,
                    brace,
                },
            ) if brace == end_brace => Ok(None),
            (span, got_token) => Err(ParseError::UnexpectedToken {
                span,
                while_parsing,
                wanted: Wanted::Ident,
                got_token: got_token.token_type_name(),
            }),
        }
    }

    pub fn req_newline(&mut self, while_parsing: &'static str) -> Result<()> {
        match self.next_token()? {
            (_, Token::Newline(..)) => Ok(()),
            (span, got_token) => Err(ParseError::UnexpectedToken {
                span,
                while_parsing,
                wanted: Wanted::Token(Token::Newline(false)),
                got_token: got_token.token_type_name(),
            }),
        }
    }

    pub(crate) fn open_file(
        &mut self,
        path: impl AsRef<Path>,
    ) -> Result<CachedFile, logix_vfs::Error> {
        self.loader.open_file(path)
    }

    /// Forks the parser and calls the specified function, if the return value
    /// is `Some(R)`, the parser is replaced by the fork.
    pub(crate) fn forked<R>(
        &mut self,
        f: impl FnOnce(&mut LogixParser<'_, 'f, FS>) -> Result<Option<R>>,
    ) -> Result<Option<R>> {
        let mut fork = LogixParser {
            loader: self.loader,
            file: self.file,
            state: self.state.clone(),
        };
        if let Some(ret) = f(&mut fork)? {
            let LogixParser {
                loader: _,
                file: _,
                state,
            } = fork;
            self.state = state;
            Ok(Some(ret))
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use logix_vfs::RelFs;

    use crate::token::{Brace, Literal, StrLit, StrTag};

    use super::*;

    pub(super) struct Tester<'f> {
        f: &'f CachedFile,
    }

    impl<'f> Tester<'f> {
        fn span(&self, pos: usize, ln: usize, start: usize, len: usize) -> SourceSpan {
            SourceSpan::new(self.f, pos, ln, start, len)
        }
    }

    pub(super) fn run_test<R>(
        src: &str,
        test_clb: impl FnOnce(&mut LogixParser<RelFs>, &Tester) -> R,
    ) -> R {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("test.logix"), src).unwrap();

        let mut loader = LogixLoader::new(RelFs::new(root.path()));
        let f = loader.open_file("test.logix").unwrap();

        test_clb(&mut LogixParser::new(&mut loader, &f), &Tester { f: &f })
    }

    #[test]
    fn basics() -> Result<()> {
        run_test("Hello { world: \"!!!\" }", |p, t| -> Result<()> {
            assert_eq!(p.next_token()?, (t.span(0, 1, 0, 5), Token::Ident("Hello")));
            assert_eq!(
                p.next_token()?,
                (
                    t.span(6, 1, 6, 1),
                    Token::Brace {
                        start: true,
                        brace: Brace::Curly
                    }
                )
            );
            assert_eq!(p.next_token()?, (t.span(8, 1, 8, 5), Token::Ident("world")));
            assert_eq!(
                p.next_token()?,
                (t.span(13, 1, 13, 1), Token::Delim(Delim::Colon))
            );
            assert_eq!(
                p.next_token()?,
                (
                    t.span(15, 1, 15, 5),
                    Token::Literal(Literal::Str(StrLit::new(StrTag::Raw, "!!!")))
                )
            );
            assert_eq!(
                p.next_token()?,
                (
                    t.span(21, 1, 21, 1),
                    Token::Brace {
                        start: false,
                        brace: Brace::Curly
                    }
                )
            );

            assert_eq!(
                p.next_token()?,
                (t.span(22, 1, 22, 0), Token::Newline(true))
            );

            assert_eq!(
                p.next_token()?,
                (t.span(22, 1, 22, 0), Token::Newline(true))
            );
            // A second time to trigger additional code
            Ok(())
        })
    }
}