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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#![deny(missing_docs)]

/*!
This crate contains a parser for [scopes list notation (SLN)](https://scopes.readthedocs.io/en/latest/dataformat/).

The parser is also configurable, so you can change, how the format of the file you want to parse looks like.
**/

use std::cmp::Ordering;
use std::fmt;
use token_parser::{
    Parser as TokenParser,
    Unit::{self, Parser as ParserUnit, Symbol},
};

#[derive(PartialEq)]
/// Represents all kinds of errors, which can occur during parsing.
pub enum ErrorKind {
    /// Specified brackets don't match.
    UnmatchedBrackets(char, char),
    /// Some bracket is not closed.
    UnclosedBracket,
    /// Some closing bracket has no matching opening bracket.
    TooManyBrackets,
    /// A string is not closed.
    UnclosedString,
    /// A the prefix of a multiline string does not have the expected length.
    MultilinePrefixLength,
    /// The indentation is invalid.
    Indentation,
    /// Some unescapeable character is being escaped.
    UnescapeableCharacter(char),
}

impl fmt::Debug for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ErrorKind::*;
        match self {
            UnmatchedBrackets(left, right) => write!(f, "Brackets '{}' and '{}' don't match", left, right),
            UnclosedBracket => write!(f, "Bracket not closed"),
            TooManyBrackets => write!(f, "Too many brackets"),
            UnclosedString => write!(f, "String not closed"),
            MultilinePrefixLength => write!(f, "Prefix for multiline string has to consist of exactly 4 string delimiters, but has 3"),
            Indentation => write!(f, "Indentation not allowed"),
            UnescapeableCharacter(c) => write!(f, "Tried to escape unescapeable chararter {}", c),
        }
    }
}

/// Represents the error, which might occur during parsing.
pub struct Error {
    /// Indicates in which line the error occured.
    pub line: usize,
    /// Indicates in which column of that line the error occured.
    pub column: usize,
    /// Indicates the kind of error, which was found.
    pub kind: ErrorKind,
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}: {:?}", self.line, self.column, self.kind)
    }
}

/// Represents the result type for parsing.
pub type Result<T> = std::result::Result<T, Error>;

impl ErrorKind {
    fn error(self, line: usize, column: usize) -> Error {
        Error {
            line,
            column,
            kind: self,
        }
    }
}

struct BracketPair {
    left: char,
    right: char,
    prefix: Option<String>,
}

struct StringDelimiter {
    delimiter: char,
    prefix: Option<String>,
}

/// Represents the parser.
pub struct Parser {
    indent: u8,
    unpack_single: bool,
    allow_multi_indent: bool,
    strings: Vec<StringDelimiter>,
    brackets: Vec<BracketPair>,
    comments: Vec<char>,
    separator: Vec<char>,
    symbol_characters: Vec<char>,
}

impl Parser {
    /// Creates a new parser with minimal enabled features.
    pub fn new() -> Self {
        Self {
            indent: 0,
            unpack_single: false,
            allow_multi_indent: false,
            strings: Vec::new(),
            brackets: Vec::new(),
            comments: Vec::new(),
            separator: Vec::new(),
            symbol_characters: Vec::new(),
        }
    }

    /// Creates a new parser with all the features of SLN.
    pub fn scopes() -> Self {
        Self::new()
            .indent(4)
            .unpack_single(true)
            .with_strings('"', Some("string".into()))
            .with_brackets('(', ')', None)
            .with_brackets('[', ']', Some("square-list".into()))
            .with_brackets('{', '}', Some("curly-list".into()))
            .with_comments('#')
            .with_separator(';')
            .with_symbol_character(',')
    }

    /// Returns the parser with the indent changed.
    /// If indent is zero, indentation based nesting is disabled.
    pub fn indent(self, indent: u8) -> Self {
        Self { indent, ..self }
    }

    /// Returns the parser with unpacking of single elements in lines enabled or disabled.
    /// If enabled, a line, which contains only a single element, is not interpreted as list.
    pub fn unpack_single(self, unpack_single: bool) -> Self {
        Self {
            unpack_single,
            ..self
        }
    }

    /// Returns the parser with more multi indent enabled or disabled.
    /// If enabled, more than one additional indentation per line is allowed.
    pub fn allow_multi_indent(self, allow_multi_indent: bool) -> Self {
        Self {
            allow_multi_indent,
            ..self
        }
    }

    /// Returns the parser with a new string delimiter added.
    /// The string might be parsed as list prefixed by a symbol.
    pub fn with_strings(mut self, delimiter: char, prefix: Option<String>) -> Self {
        self.strings.push(StringDelimiter { delimiter, prefix });
        self
    }

    /// Returns the parser with string parsing disabled.
    pub fn without_strings(self) -> Self {
        Self {
            strings: Vec::new(),
            ..self
        }
    }

    /// Returns the parser with a new allowed bracket pair.
    /// Lists created by specific bracket pairs might be prefixed by a symbol.
    pub fn with_brackets(mut self, left: char, right: char, prefix: Option<String>) -> Self {
        self.brackets.push(BracketPair {
            left,
            right,
            prefix,
        });
        self
    }

    /// Returns the parser with no support for brackets.
    pub fn without_brackets(self) -> Self {
        Self {
            brackets: Vec::new(),
            ..self
        }
    }

    /// Returns the parser with a new character for indicating comments added.
    /// A comment might apply to multiple lines.
    pub fn with_comments(mut self, comments: char) -> Self {
        self.comments.push(comments);
        self
    }

    /// Returns the parser with no support for comments.
    pub fn without_comments(self) -> Self {
        Self {
            comments: Vec::new(),
            ..self
        }
    }

    /// Returns the parser with a new character as separator added.
    /// A separator makes it possible to write multiple lists per line without the need of brackets.
    pub fn with_separator(mut self, separator: char) -> Self {
        self.separator.push(separator);
        self
    }

    /// Returns the parser with no support for separators.
    pub fn without_separator(self) -> Self {
        Self {
            separator: Vec::new(),
            ..self
        }
    }

    /// Returns the parser with a new character as symbol character added.
    /// Symbol characters will always be parsed as single characters, even if there is no whitespace before or after them.
    pub fn with_symbol_character(mut self, separator: char) -> Self {
        self.symbol_characters.push(separator);
        self
    }

    /// Returns the parser with no support for symbol characters.
    pub fn without_symbol_character(self) -> Self {
        Self {
            symbol_characters: Vec::new(),
            ..self
        }
    }

    /// Parses the text into a token parser, which can be used to parse all kinds of data structures.
    pub fn parse(&self, chars: impl IntoIterator<Item = char>) -> Result<TokenParser> {
        fn string_unit(name: String, prefix: Option<String>) -> Unit {
            if let Some(prefix) = prefix {
                ParserUnit(TokenParser::new(vec![Symbol(prefix), Symbol(name)]))
            } else {
                Symbol(name)
            }
        }

        enum Mode {
            Default,
            Newline,
            Comment(usize),
            Symbol(String),
            String {
                prefix: Option<String>,
                delimiter: char,
                content: String,
                escape: bool,
            },
            MultilinePrefix {
                prefix: Option<String>,
                delimiter: char,
                count: usize,
            },
            MultilineString {
                prefix: Option<String>,
                content: String,
                column: usize,
            },
        }

        impl Default for Mode {
            fn default() -> Self {
                Self::Newline
            }
        }

        impl Mode {
            #[must_use]
            fn finish(self, units: &mut Vec<Unit>, line: usize, column: usize) -> Result<()> {
                Ok(match self {
                    Mode::Symbol(name) => units.push(Symbol(name)),
                    Mode::String {
                        content, prefix, ..
                    } => units.push(string_unit(content, prefix)),
                    Mode::MultilineString {
                        content, prefix, ..
                    } => units.push(string_unit(content.trim_end_matches('\n').into(), prefix)),
                    Mode::MultilinePrefix { count, prefix, .. } => {
                        if count == 2 {
                            units.push(string_unit(String::new(), prefix));
                        } else {
                            return Err(ErrorKind::MultilinePrefixLength.error(line, column));
                        }
                    }
                    _ => (),
                })
            }
        }

        let mut chars = chars.into_iter();

        #[derive(Default)]
        struct UnitStack {
            current: Vec<Unit>,
            stack: Vec<Vec<Unit>>,
        }

        impl UnitStack {
            fn pop_stack(&mut self, unpack_single: bool) {
                if let Some(next) = self.stack.pop() {
                    let mut child_units = std::mem::replace(&mut self.current, next);
                    let unit = if unpack_single && child_units.len() == 1 {
                        child_units.pop().unwrap()
                    } else {
                        ParserUnit(TokenParser::new(child_units))
                    };
                    self.current.push(unit);
                }
            }

            fn push_stack(&mut self) {
                self.stack
                    .push(std::mem::replace(&mut self.current, Vec::new()));
            }
        }

        #[derive(Default)]
        struct ParsingData {
            mode: Mode,
            line: usize,
            column: usize,
            units: UnitStack,
            list_stack: Vec<char>,
        }

        let mut data = ParsingData::default();
        data.units.push_stack();

        fn parse_character(parser: &Parser, c: char, mut data: ParsingData) -> Result<ParsingData> {
            if c == '\n' {
                match data.mode {
                    Mode::Comment(_) => (),
                    Mode::MultilineString {
                        mut content,
                        column,
                        prefix,
                    } => {
                        content.push('\n');
                        data.mode = Mode::MultilineString {
                            content,
                            column,
                            prefix,
                        };
                    }
                    Mode::String { .. } => {
                        return Err(ErrorKind::UnclosedString.error(data.line, data.column))
                    }
                    _ => {
                        data.mode
                            .finish(&mut data.units.current, data.line, data.column)?;
                        data.mode = Mode::Newline;
                    }
                }
                data.column = 0;
                data.line += 1;
                return Ok(data);
            }
            if let Mode::Comment(column) = data.mode {
                if data.column > column {
                    return Ok(data);
                }
            }
            for &comment_char in &parser.comments {
                if c == comment_char {
                    data.mode
                        .finish(&mut data.units.current, data.line, data.column)?;
                    data.mode = Mode::Comment(data.column);
                    data.column += 1;
                    return Ok(data);
                }
            }
            if let Mode::Newline | Mode::Comment(_) = data.mode {
                if parser.indent > 0 && data.list_stack.is_empty() {
                    if c == ' ' {
                        data.column += 1;
                        return Ok(data);
                    }
                    data.mode = Mode::Default;
                    let old_level = data.units.stack.len().saturating_sub(1);
                    let mut level = 0;
                    loop {
                        match data.column.cmp(&(level * parser.indent as usize)) {
                            Ordering::Greater => level += 1,
                            Ordering::Less => {
                                return Err(ErrorKind::Indentation.error(data.line, data.column))
                            }
                            Ordering::Equal => break,
                        }
                    }

                    let cmp = level.cmp(&old_level);
                    if cmp == Ordering::Less {
                        for _ in 0..(old_level - level) {
                            data.units.pop_stack(parser.unpack_single);
                        }
                    }
                    if cmp == Ordering::Greater {
                        let additional = level - old_level;
                        if !parser.allow_multi_indent && additional > 1 {
                            return Err(ErrorKind::Indentation.error(data.line, data.column));
                        }
                        for _ in 0..additional {
                            data.units.push_stack();
                        }
                    } else {
                        if !data.units.current.is_empty() {
                            data.units.pop_stack(parser.unpack_single);
                            data.units.push_stack();
                        }
                    }
                }
            }
            data.column += 1;

            let mut default_parsing = false;
            data.mode = match data.mode {
                Mode::String {
                    delimiter,
                    mut content,
                    escape,
                    prefix,
                } => {
                    if escape {
                        content.push(match c {
                            'n' => '\n',
                            'r' => '\r',
                            't' => '\t',
                            '\\' => '\\',
                            _ => {
                                if c != delimiter {
                                    return Err(ErrorKind::UnescapeableCharacter(c)
                                        .error(data.line, data.column));
                                }
                                c
                            }
                        });
                        Mode::String {
                            delimiter,
                            content,
                            escape: false,
                            prefix,
                        }
                    } else {
                        match c {
                            '\\' => Mode::String {
                                delimiter,
                                content,
                                escape: true,
                                prefix,
                            },
                            _ => {
                                if c == delimiter {
                                    if content.is_empty() {
                                        Mode::MultilinePrefix {
                                            delimiter,
                                            count: 2,
                                            prefix,
                                        }
                                    } else {
                                        data.units.current.push(string_unit(content, prefix));
                                        Mode::Default
                                    }
                                } else {
                                    content.push(c);
                                    Mode::String {
                                        delimiter,
                                        content,
                                        escape,
                                        prefix,
                                    }
                                }
                            }
                        }
                    }
                }
                Mode::MultilinePrefix {
                    delimiter,
                    count,
                    prefix,
                } => {
                    if c == delimiter {
                        let count = count + 1;
                        if count == 4 {
                            Mode::MultilineString {
                                content: String::new(),
                                column: data.column,
                                prefix,
                            }
                        } else {
                            Mode::MultilinePrefix {
                                delimiter,
                                count,
                                prefix,
                            }
                        }
                    } else {
                        if count == 2 {
                            data.units.current.push(string_unit(String::new(), prefix));
                            default_parsing = true;
                            Mode::Default
                        } else {
                            return Err(
                                ErrorKind::MultilinePrefixLength.error(data.line, data.column)
                            );
                        }
                    }
                }
                Mode::MultilineString {
                    mut content,
                    column,
                    prefix,
                } => {
                    if data.column <= column {
                        default_parsing = true;
                    } else {
                        content.push(c);
                    }
                    Mode::MultilineString {
                        content,
                        column,
                        prefix,
                    }
                }
                _ => {
                    let mut mode = data.mode;
                    default_parsing = true;
                    for &StringDelimiter {
                        delimiter,
                        ref prefix,
                    } in &parser.strings
                    {
                        if c == delimiter {
                            mode.finish(&mut data.units.current, data.line, data.column)?;
                            mode = Mode::String {
                                delimiter: c,
                                content: String::new(),
                                escape: false,
                                prefix: prefix.clone(),
                            };
                            default_parsing = false;
                            break;
                        }
                    }
                    mode
                }
            };
            if default_parsing {
                if let Mode::MultilineString { .. } = data.mode {
                    if c == ' ' {
                        return Ok(data);
                    }
                }
                for &separator in &parser.separator {
                    if c == separator {
                        data.mode
                            .finish(&mut data.units.current, data.line, data.column)?;
                        data.mode = Mode::Default;
                        data.units.pop_stack(false);
                        data.units.push_stack();
                        return Ok(data);
                    }
                }
                for &symbol_character in &parser.symbol_characters {
                    if c == symbol_character {
                        data.mode
                            .finish(&mut data.units.current, data.line, data.column)?;
                        let mut name = String::new();
                        name.push(c);
                        data.units.current.push(Symbol(name));
                        data.mode = Mode::Default;
                        return Ok(data);
                    }
                }
                let mut bracket = None;
                for pair in &parser.brackets {
                    let &BracketPair { left, right, .. } = pair;
                    if c == left {
                        bracket = Some((true, pair));
                    } else if c == right {
                        bracket = Some((false, pair));
                    } else {
                        continue;
                    }
                    break;
                }
                if c == ' ' || bracket.is_some() {
                    data.mode
                        .finish(&mut data.units.current, data.line, data.column)?;
                    data.mode = Mode::Default;
                } else {
                    if let Mode::Symbol(name) = &mut data.mode {
                        name.push(c);
                    } else {
                        let mut name = String::new();
                        name.push(c);
                        data.mode
                            .finish(&mut data.units.current, data.line, data.column)?;
                        data.mode = Mode::Symbol(name)
                    }
                }

                if let Some((open, pair)) = bracket {
                    if open {
                        data.units.push_stack();
                        data.list_stack.push(pair.left);
                    } else {
                        if let Some(bracket) = data.list_stack.pop() {
                            if bracket != pair.left {
                                return Err(ErrorKind::UnmatchedBrackets(bracket, pair.right)
                                    .error(data.line, data.column));
                            }
                        } else {
                            return Err(ErrorKind::TooManyBrackets.error(data.line, data.column));
                        }
                        if let Some(prefix) = &pair.prefix {
                            data.units.current.insert(0, Symbol(prefix.clone()));
                        }
                        data.units.pop_stack(false);
                    }
                }
            }
            Ok(data)
        }
        while let Some(c) = chars.next() {
            data = parse_character(&self, c, data)?
        }
        if !data.list_stack.is_empty() {
            return Err(ErrorKind::UnclosedBracket.error(data.line, data.column));
        }
        if let Mode::String { .. } = data.mode {
            return Err(ErrorKind::UnclosedString.error(data.line, data.column));
        }
        data.mode
            .finish(&mut data.units.current, data.line, data.column)?;
        if data.units.current.is_empty() {
            if let Some(next) = data.units.stack.pop() {
                data.units.current = next;
            } else {
                return Ok(TokenParser::new(data.units.current));
            }
        } else {
            data.units.pop_stack(self.unpack_single);
        }
        while !data.units.stack.is_empty() {
            data.units.pop_stack(false);
        }

        //data.units.current();
        Ok(TokenParser::new(data.units.current))
    }
}