atoms 2.2.3

S-expression parser and pretty-printer.
Documentation
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! Functions related to parsing of input

#![deny(unused_must_use)]

use value::{Value, StringValue};
use error::{ParseError, ParseResult};
use std::io::{Read, BufRead, BufReader};
use std::str::FromStr;
use std::cmp::max;
use std::collections::VecDeque;

use unescape::unescape;

macro_rules! parse_err {
    ( $name:ident, $me:ident ) => {
        Err(ParseError::$name($me.line, $me.get_col()))
    }
}

macro_rules! cons_side {
    ( $me:ident, $default:block, $($catch:pat => $catch_result:block),*) => {{
        try!($me.consume_comments());
        if let Some(&c) = try!($me.peek()) {
            match c {
                $($catch => $catch_result),*
                _ => $default,
            }
        } else {
            end_of_file!($me)
        }
    }}
}

macro_rules! cons_err {
    ( $me:ident, $($err:pat => $err_name:ident),*) => {{
        try!($me.consume_comments());
        if let Some(&c) = try!($me.peek()) {
            match c {
                $($err => parse_err!($err_name, $me),),*
                _ => $me.parse_expression(),
            }
        } else {
            end_of_file!($me)
        }
    }}
}

macro_rules! end_of_file {
    ( $me:ident ) => {parse_err!(EndOfFile, $me)}
}

/**
 * A parser for a particular `str`
 *
 * Parsing expressions requires a parser to be attached to the given string.
 * 
 * ```rust
 * use atoms::{Parser, StringValue};
 * let text = "(this is a series of symbols)";
 * let parser = Parser::new(&text);
 * let parsed = parser.parse_basic().unwrap();
 * assert_eq!(
 *     StringValue::into_list(
 *         vec!["this", "is", "a", "series", "of", "symbols"], 
 *         |s| StringValue::symbol(s).unwrap()
 *     ),
 *     parsed
 * );
 * ```
 * 
 * The type parameter given to `Parser::parse` is to inform the parser of 
 * how to evaluate symbols. Any type that implements `ToString` and `FromStr`
 * reflexively can be used here. `String` is just one such, however it would 
 * be trivial to create an `enum` that restricted parsing to pre-defined
 * symbols.
 *
 * A parser has to be attached to a particular `str` to parse it. Really, this
 * is to allow us to make sane error messages.
 */
pub struct Parser<R> {
    reader: BufReader<R>,
    buffer: VecDeque<char>,
    line: usize,
    col: isize,
}

impl<'a> Parser<&'a [u8]> {
    /**
     * Create a new parser for a single expression
     */
    pub fn new<'b>(source: &'b AsRef<[u8]>) -> Parser<&'b [u8]> {
        Parser::reader(source.as_ref())
    }
}

impl<R: Read> Parser<R> {
    /**
     * Create a new parser for a reader.
     *
     * The reader can can be a source of series of discrete expressions,
     * each to be read one at a time.
     */
    pub fn reader(source: R) -> Parser<R> {
        Parser {
            reader: BufReader::new(source),
            buffer: VecDeque::new(),
            line: 1usize,
            col: -1isize,
        }
    }

    /**
     * Read the next expression.
     * 
     * ```rust
     * use atoms::{Parser, Value};
     * let text = r#"
     *     (this is a series of symbols)
     *     (this is another sexpression)
     *     mono ;Single expression on its own line
     *     (this expression
     *           spans lines)
     *     (these expressions) (share lines)
     * "#;
     * let mut parser = Parser::new(&text);
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::into_list(
     *         vec!["this", "is", "a", "series", "of", "symbols"], 
     *         |s| Value::symbol(s).unwrap()
     *     )
     * );
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::into_list(
     *         vec!["this", "is", "another", "sexpression"], 
     *         |s| Value::symbol(s).unwrap()
     *     )
     * );
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::symbol("mono").unwrap()
     * );
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::into_list(
     *         vec!["this", "expression", "spans", "lines"], 
     *         |s| Value::symbol(s).unwrap()
     *     )
     * );
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::into_list(
     *         vec!["these", "expressions"], 
     *         |s| Value::symbol(s).unwrap()
     *     )
     * );
     * assert_eq!(
     *     parser.read::<String>().unwrap(),
     *     Value::into_list(
     *         vec!["share", "lines"], 
     *         |s| Value::symbol(s).unwrap()
     *     )
     * );
     * ```
     *
     * This parser must be informed of how to represent symbols when they are
     * parsed. The `Sym` type parameter must implement `FromStr` and `ToString`
     * reflexively (i.e. the output of `ToString::to_string` for a given value
     * **must** produce the same value when used with `FromStr::from_str` and
     * visa versa such that the value can be encoded and decoded the same way).
     * If no special treatment of symbols is required, `parse_basic` should be
     * used.
     *
     * This will produce parsing errors when `FromStr::from_str` fails when
     * being used to create symbols.
     */
    pub fn read<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        // Consume the comments
        try!(self.consume_comments());
        self.parse_expression()
    }

    /**
     * Parse the given expression. Consumes the parser.
     *
     * If you want to pass a series of expressions, use `read` instead.
     * 
     * ```rust
     * use atoms::{Parser, Value};
     * let text = "(this is a series of symbols)";
     * let parser = Parser::new(&text);
     * let parsed = parser.parse::<String>().unwrap();
     * assert_eq!(
     *     Value::into_list(
     *         vec!["this", "is", "a", "series", "of", "symbols"], 
     *         |s| Value::symbol(s).unwrap()
     *     ),
     *     parsed
     * );
     * ```
     *
     * Similar to `read`, the parser must be informed of the type to be used
     * for expressing symbols.
     */
    pub fn parse<Sym: FromStr>(mut self) -> ParseResult<Value<Sym>> {

        // Remove leading whitespace
        try!(self.consume_comments());

        let result = try!(self.parse_expression());

        // Remove trailing whitespace
        try!(self.consume_comments());

        if let Some(_) = try!(self.next()) {
            parse_err!(TrailingGarbage, self)
        } else {
            Ok(result)
        }
    }

    /**
     * Parse the given `str` storing symbols as `String`s. Consumes the parser.
     * 
     * ```rust
     * use atoms::{Parser, StringValue};
     * let text = "(this is a series of symbols)";
     * let parser = Parser::new(&text);
     * let parsed = parser.parse::<String>().unwrap();
     * assert_eq!(
     *     StringValue::into_list(
     *         vec!["this", "is", "a", "series", "of", "symbols"], 
     *         |s| StringValue::symbol(s).unwrap()
     *     ),
     *     parsed
     * );
     * ```
     *
     * In cases where no special behaviour for symbols is needed, `parse_basic`
     * will resolve all symbols as `String`s.
     */
    pub fn parse_basic(self) -> ParseResult<StringValue> {
        self.parse()
    }

    /**
     * Get the column
     */
    fn get_col(&self) -> usize {
        max(self.col, 0) as usize
    }

    /**
     * Peek at the next value in the buffer
     */
    fn peek(&mut self) -> ParseResult<Option<&char>> {
        if self.buffer.len() <= 0 {
            try!(self.extend_buffer());
        } 

        Ok(self.buffer.get(0))
    }

    /**
     * Get the next value
     */
    fn next(&mut self) -> ParseResult<Option<char>> {
        if self.buffer.len() <= 0 {
            try!(self.extend_buffer());
        } 

        let next_c = self.buffer.pop_front();

        // Advance position if possible
        if let Some(c) = next_c {
            if c == '\n' {
                self.line +=  1;
                self.col   = -1;
            } else {
                self.col  +=  1;
            }
            Ok(Some(c))
        } else {
            Ok(None)
        }
    }

    /**
     * Get the next line and add to queue
     */
    fn extend_buffer(&mut self) -> ParseResult<()> {
        let mut line = String::new();
        match self.reader.read_line(&mut line) {
            Ok(_) => {
                for t in line.chars() {
                    self.buffer.push_back(t);
                }
                Ok(())
            },
            Err(e) => Err(ParseError::BufferError(self.line, self.get_col(), e))
        }
    }

    /**
     * Parse a single sexpression
     */
    fn parse_expression<Sym: FromStr>(&mut self) 
        -> ParseResult<Value<Sym>> {
        
        // Consume leading comments
        try!(self.consume_comments());

        self.parse_immediate()
    }

    /**
     * Parse the next immediate expression
     */
    fn parse_immediate<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        if let Some(&c) = try!(self.peek()) {
            match c {
                // String literal
                '"' => self.parse_quoted(),
                // Start of cons 
                '(' => {
                    try!(self.next());
                    self.parse_cons()
                },
                // End of Cons
                ')' => {
                    try!(self.next());
                    parse_err!(ClosingParen, self)
                },
                // Extension
                '#' => {
                    try!(self.next());
                    parse_err!(NoExtensions, self)
                },
                // Quoting
                '\'' => {
                    try!(self.next());
                    Ok(Value::data(try!(self.parse_immediate())))
                },
                '`' => {
                    try!(self.next());
                    Ok(Value::data(try!(self.parse_immediate())))
                },
                ',' => {
                    try!(self.next());
                    Ok(Value::code(try!(self.parse_immediate())))
                },
                // Automatic value
                _   => self.parse_value(),
            }
        } else {
            end_of_file!(self)
        }
    }

    /**
     * Parse a Cons
     */
    fn parse_cons<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        let left = try!(cons_side!(self, {self.parse_immediate()}, 
            ')' => {
                try!(self.next());
                return Ok(Value::Nil)
            }
        ));

        // Get right half of cons
        let right = try!(cons_side!(self, {self.parse_cons()},
            // Nil if immediate close
            ')' => {
                try!(self.next());
                Ok(Value::Nil)
            },

            // Might be cons pair if starting with .
            '.' => {
                self.parse_cons_rest()
            }
        ));

        Ok(Value::cons(left, right))
    }

    fn parse_cons_rest<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        let next_val = try!(self.unescape_value());

        if next_val == "." {
            // Cons join
            try!(self.consume_comments());
            let value = cons_err!(self, 
                ')' => ConsWithoutRight 
            );
            try!(self.consume_comments());
            if let Some(c) = try!(self.next()) {
                if c != ')' {
                    parse_err!(ConsWithoutClose, self)
                } else {
                    value
                }
            } else {
                end_of_file!(self)
            }
        } else {
            // List
            Ok(Value::cons(
                try!(self.value_from_string(&next_val)),
                try!(self.parse_cons())
            ))
        }
    }

    /**
     * Extract a value up until the given delimiter. Does not consume delimiter.
     */
    fn extract_delimited(&mut self, delimiter: &Fn(char) -> bool, allow_eof: bool) 
        -> ParseResult<String> {
        let mut value = String::new();

        // Push each following character into the parsed string
        while let Some(&preview) = try!(self.peek()) {
            if preview == '\\' {
                let c = try!(self.next()).unwrap();
                value.push(c);
                if let Some(follower) = try!(self.next()) {
                    value.push(follower);
                } else {
                    return end_of_file!(self);
                }
            } else if delimiter(preview) {
                return Ok(value);
            } else {
                let c = try!(self.next()).unwrap();
                value.push(c);
            }
        }

        // Throw an error if we aren't expecting an end of file
        if allow_eof {
            Ok(value)
        } else {
            end_of_file!(self)
        }
    }

    /**
     * Parse a quoted value
     */
    fn parse_quoted<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        // remove leading quote
        try!(self.next()).unwrap();

        // parsed string value
        let unquoted = try!(self.extract_delimited(&(|c| c == '"'), false));

        // remove trailing quote
        try!(self.next()).unwrap();

        Ok(Value::string(try!(self.parse_text(&unquoted))))
    }

    /**
     * Extract a single string escaped value
     */
    fn unescape_value(&mut self) -> ParseResult<String> {
        let text = try!(self.extract_delimited(&default_delimit, true)).escape_special();
        self.parse_text(&text)
    }

    /**
     * Parse a an escaped text (symbol or string)
     */
    fn parse_text(&mut self, s: &AsRef<str>) -> ParseResult<String> {
        if let Some(parsed) = unescape(s.as_ref()) {
            Ok(parsed)
        } else {
            parse_err!(StringLiteral, self)
        }
    }

    /**
     * Parse the next value into a type
     */
    fn parse_value<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> {
        let text = try!(self.unescape_value());
        self.value_from_string(&text)
    }

    /**
     * Parse a string into a value
     */
    fn value_from_string<Sym: FromStr>(&mut self, text: &str) -> ParseResult<Value<Sym>> {
        // Try make an integer
        match i64::from_str(&text) {
            Ok(i) => return Ok(Value::int(i)),
            _     => {},
        }

        // Try make a float
        match f64::from_str(&text) {
            Ok(f) => return Ok(Value::float(f)),
            _     => {},
        }

        // Try make a symbol
        if text.len() == 0usize {
            parse_err!(EmptySymbol, self)
        } else if let Some(sym) = Value::symbol(&text) {
            Ok(sym)
        } else {
            parse_err!(SymbolEncode, self)
        }
    }

    /**
     * Consume whitespace
     */
    fn consume_whitespace(&mut self) -> ParseResult<()> {
        while let Some(&c) = try!(self.peek()) {
            if c.is_whitespace() {
                try!(self.next());
            } else {
                return Ok(());
            }
        }

        Ok(())
    }
    
    /**
     * Consume the remaining line of text
     */
    fn consume_line(&mut self) -> ParseResult<()> {
        while let Some(c) = try!(self.next()) {
            if c == '\n' { return Ok(()); }
        }

        Ok(())
    }
    
    /**
     * Consume blocks of comments
     */
    fn consume_comments(&mut self) -> ParseResult<()> {
        try!(self.consume_whitespace());
        while let Some(&c) = try!(self.peek()) {
            if c == ';' {
                try!(self.consume_line());
            } else if c.is_whitespace() {
                try!(self.consume_whitespace());
            } else {
                return Ok(());
            }
        }

        Ok(())
    }
}

/**
 * Additional characters to escape in strings
 */
trait EscapeSpecial {
    fn escape_special(self) -> Self;
}

impl EscapeSpecial for String {
    fn escape_special(self) -> String {
        self.replace("\\ ", " ")
            .replace("\\;", ";")
            .replace("\\(", "(")
            .replace("\\)", ")")
            .replace("\\\"", "\"")
            .replace("\\\'", "\'")
            .replace("\\`", "`")
            .replace("\\,", ",")
            .replace("\\\\", "\\")
    }
}

/**
 * Default predicate for delimitation is whitespace
 */
fn default_delimit(c: char) -> bool { 
    c.is_whitespace() || c == ';' || c == '(' || c == ')' || c == '"' 
}

#[test]
fn single_element() {
    let text = "(one)";
    let output = Value::list(vec![Value::symbol("one").unwrap()]);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn unary_test() {
    fn unary(text: &'static str, output: Value<String>) {
        let parser = Parser::new(&text);
        assert_eq!(parser.parse().unwrap(), output);
    }
    unary("()", Value::Nil);
    unary("one", Value::symbol("one").unwrap());
    unary("2", Value::int(2));
    unary("3.0", Value::float(3.0));
    unary("\"four\"", Value::string("four"));
}

#[test]
fn integer_test() {
    let text = "(1 2 3 4 5)";
    let nums = vec![1, 2, 3, 4, 5].iter().map(|i| Value::int(*i)).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn float_test() {
    let text = "(1.0 2.0 3.0 4.0 5.0)";
    let nums = vec![1.0, 2.0, 3.0, 4.0, 5.0].iter().map(|f| Value::float(*f)).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn string_test() {
    let text = "(\"one\" \"two\" \"three\" \"four\" \"five\")";
    let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::string(*s)).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn symbol_test() {
    let text = "(one two three four five)";
    let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn nesting_test() {
    let text = "(one (two three) (four five))";
    let inner_one = Value::list(vec!["two", "three"].iter().map(|s| Value::symbol(*s).unwrap()).collect());
    let inner_two = Value::list(vec!["four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect());
    let output = Value::list(vec![Value::symbol("one").unwrap(), inner_one, inner_two]);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn space_escape_test() {
    let text = "(one\\ two\\ three\\ four\\ five)";
    let output = Value::list(vec![Value::symbol("one two three four five").unwrap()]);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn comment_test() {
    let text = "  ;comment\n (one;comment\n two ;;;comment with space\n three four five) ;trailing comment\n ;end";
    let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn skip_whitespace_test() {
    let text = "   \n  \t (  \n\t   one    two   \n\t    three    \n\t   four five    \t   \n )   \n   \t";
    let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect();
    let output = Value::list(nums);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn trailing_garbage_test() {
    let text = "(one two three four five) ;not garbage\n garbage";
    let parser = Parser::new(&text);
    assert!(parser.parse::<String>().is_err());
}

#[test]
fn escape_parsing_test() {
    let text = "(one\\ two 3 4 \"five\\\\is\\ta\\rless\\nmagic\\\'number\\\"\")";
    let output = Value::list(vec![
        Value::symbol("one two").unwrap(),
        Value::int(3),
        Value::int(4),
        Value::string("five\\is\ta\rless\nmagic\'number\"")
    ]);
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn cons_parsing() {
    let text = "(one . (two . (three . four)))";
    let output = Value::cons(
        Value::symbol("one").unwrap(), 
        Value::cons(
            Value::symbol("two").unwrap(),
            Value::cons(
                Value::symbol("three").unwrap(),
                Value::symbol("four").unwrap(),
            ),
        ),
    );
    let parser = Parser::new(&text);
    assert_eq!(parser.parse::<String>().unwrap(), output);
}

#[test]
fn trailing_cons() {
    let text = "(one two three . four)";
    let output = Value::cons(
        Value::symbol("one").unwrap(), 
        Value::cons(
            Value::symbol("two").unwrap(),
            Value::cons(
                Value::symbol("three").unwrap(),
                Value::symbol("four").unwrap(),
            ),
        ),
    );
    let two = StringValue::symbol("one").unwrap();
    let output_short = s_tree!(StringValue: (two . ([two] . ([three] . [four]))));
    let parsed = Parser::new(&text).parse::<String>().unwrap();
    assert_eq!(parsed, output);
    assert_eq!(parsed, output_short);
}

#[test]
fn split_cons() {
    let text = "(one . two . three . four)";
    let parser = Parser::new(&text);
    assert!(parser.parse::<String>().is_err());
}

#[test]
fn github_issues() {
    fn parse_text(text: &'static str) -> ParseResult<StringValue> {
        let parser = Parser::new(&text);
        parser.parse::<String>()
    }
    assert!(parse_text("(a #;(c d) e)").is_err());
    assert_eq!(
        parse_text("(a . ()  \n \t)").unwrap(), 
        s_tree!(StringValue: ([a]))
    );
    assert_eq!(
        parse_text("(((())))").unwrap(), 
        s_tree!(StringValue: (((()))))
    );
}

#[test]
fn quasiquoting() {
    fn parse_text(text: &'static str) -> StringValue {
        let parser = Parser::new(&text);
        parser.parse::<String>().unwrap()
    }

    assert_eq!(
        parse_text("(this is 'data)"), 
        s_tree!(StringValue: ([this] [is] [d:[data]]))
    );
    assert_eq!(
        parse_text("'(this is 'data)"), 
        s_tree!(StringValue: [d:([this] [is] [d:[data]])])
    );
    assert_eq!(
        parse_text("'(this is ,quasiquoted ,(data that is '2 layers 'deep))"), 
        s_tree!(StringValue: 
            [d:([this] [is] [c:[quasiquoted]] [c:(
                [data] [that] [is] [d:2] [layers] [d:[deep]]
            )])]
        )
    );
    assert_eq!(
        parse_text("('this \n;comment here for effect\nshould probably work...)"), 
        s_tree!(StringValue: ([d:[this]] [should] [probably][s:"work..."]))
    );
    assert_eq!(
        parse_text("('\\;comment \nshould probably work...)"), 
        s_tree!(StringValue: ([d:[s:";comment"]] [should] [probably] [s:"work..."]))
    );
    assert_eq!(
        parse_text("`,`,`,`,`,data"), 
        s_tree!(StringValue: [d:[c:[d:[c:[d:[c:[d:[c:[d:[c:[data]]]]]]]]]]])
    );
    assert_eq!(
        parse_text("`,`,`,`,`,data").unwrap_full(), 
        s_tree!(StringValue: [data])
    );
    assert_eq!(
        parse_text("`(,(left `right . `last) ,middle end)").unwrap_full(), 
        s_tree!(StringValue: (([left] . ([right] . [last])) [middle] [end]))
    );
}

#[test]
fn symmetric_encoding() {
    fn check(text: &'static str) {
        assert_eq!(
            Parser::new(&text).parse::<String>().unwrap().to_string(),
            text
        );
    }
    check("one");
    check("12");
    check("3.152");
    check("3.0");
    check("-1.0");
    check("(a b c d)");
    check("(a b c . d)");
    check("this\\;uses\\\"odd\\(chars\\)\\ space");
}