ess 0.4.2

An s-expression parser targeted at language implementation.
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! Functions to parse s-expressions and expression atoms.
//!
//! This module contains the core parsing machinery.
//!
//! * If you're interested in getting a parsed s-expression that you can use,
//!   then looking at [`parse`] and [`parse_one`] are your best bet.
//! * If you want to write your own parsers that contain s-expressions,
//!   [`ParseResult`] and [`parse_expression`] will be the most useful to you.
//!
//! [`parse`]: fn.parse.html
//! [`parse_one`]: fn.parse_one.html
//! [`ParseResult`]: enum.ParseResult.html
//! [`parse_expression`]: fn.parse_expression.html

use sexp::Sexp;
use span::{ByteSpan, Span};

// Parsing Types ///////////////////////////////////////////////////////////////

/// Represents what to do next in partially completed parsing.
///
/// `ParseResult` is returned from all intermediate parsers. If you just want to
/// get back parsed s-expressions, you won't need to worry about this type since
/// the top level parsers just return a `Result`.
///
/// If the parser failed to produce a result, it will return `Error`, and if it
/// succeeded we'll get the `Done` variant containing the value produced and the
/// rest of the text to work on.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParseResult<'a, T, E> {
    /// The parser succeeded, this contains first the un-consumed portion of the
    /// input then the result produced by parsing.
    Done(&'a str, T),
    /// The parser failed, the `E` represents the reason for the failure.
    Error(E),
}

/// Indicates how parsing failed.
///
/// Most `ParseError` variants contain a `Box<ParseError>` that represents the
/// cause of that error. Using this, `ParseError` variants can be chained to
/// produce a more complete picture of what exactly went wrong during parsing.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParseError<Loc = ByteSpan>
where
    Loc: Span,
{
    /// Parsing reached the end of input where not expecting to, usually this
    /// will be contained inside another `ParseError` like `String(box
    /// UnexpectedEof, ...)` which indicates that the closing quote was never
    /// found.
    UnexpectedEof,
    /// Some problem occurred while parsing a list, along with the cause of that
    /// error.
    List(Box<ParseError>, Loc),
    /// Some problem occurred while parsing an s-expression. This will only be
    /// generated if EOF is reached unexpectedly at the beginning of
    /// `parse_expression`, so it should probably be removed.
    Sexp(Box<ParseError>, Loc),
    /// Some problem occurred while parsing a character literal, along with the
    /// cause of the error.
    Char(Box<ParseError>, Loc),
    /// Some problem occurred while parsing a string literal, along with the
    /// cause of the error.
    String(Box<ParseError>, Loc),
    /// Some problem occurred while parsing a symbol, along with the cause of
    /// the error.
    Symbol(Box<ParseError>, Loc),
    /// Some problem occurred while parsing a number literal, along with the
    /// cause of the error.
    Number(Box<ParseError>, Loc),
    /// An unexpected character was found. This will usually be the root cause
    /// in some chain of `ParseError`s.
    Unexpected(char, Loc::Begin),
}
use self::ParseResult::*;

// Parsing Utilities ///////////////////////////////////////////////////////////

trait IsDelimeter {
    fn is_delimiter(&self) -> bool;
}

impl IsDelimeter for char {
    fn is_delimiter(&self) -> bool {
        let delim_chars = r#";()[]{}"\`,"#;
        self.is_whitespace() || delim_chars.contains(*self)
    }
}

fn consume_whitespace<'a>(input: &'a str, start_loc: usize) -> (&'a str, usize) {
    let mut buffer = input;
    let mut loc = start_loc;
    while !buffer.is_empty() && (buffer.starts_with(char::is_whitespace) || buffer.starts_with(';'))
    {
        if let Some(pos) = buffer.find(|c: char| !c.is_whitespace()) {
            buffer = &buffer[pos..];
            loc += pos;
        } else {
            buffer = &buffer[buffer.len()..];
            loc += buffer.len();
        }

        if buffer.starts_with(';') {
            if let Some(pos) = buffer.find('\n') {
                buffer = &buffer[pos + 1..];
                loc += pos + 1;
            } else {
                buffer = &buffer[buffer.len()..];
                loc += buffer.len();
            }
        }
    }
    (&buffer, loc)
}

macro_rules! consume_whitespace {
    ($input:expr, $start_loc:expr, $ErrorFn:expr) => {{
        let (text, loc) = consume_whitespace($input, $start_loc);
        if text.is_empty() {
            return Error($ErrorFn(Box::new(ParseError::UnexpectedEof), (loc, loc)));
        } else {
            (text, loc)
        }
    }};
}

// Top Level Parsers ///////////////////////////////////////////////////////////

/// Parse a sequence of s-expressions.
///
/// This function returns `(Vec<Sexp>, Option<ParseError>)` so that it can
/// return partial results, for when some component parses successfully and a
/// later part fails.
///
/// # Errors
///
/// If the text contains an invalid s-expression (imbalanced parenthesis,
/// quotes, invalid numbers like 123q, etc.) then the parser will stop and
/// return an error. Every s-expression before that point that successfully
/// parsed will still be returned.
///
/// # Examples
///
/// We can get useful partial results
///
/// ```rust
/// # use ess::parser::parse;
/// let (exprs, err) = parse("1 2 3 ( 4");
/// assert_eq!(exprs.len(), 3);
/// assert!(err.is_some());
/// ```
pub fn parse(mut input: &str) -> (Vec<Sexp>, Option<ParseError>) {
    let mut start_loc = 0;
    let mut results = Vec::new();
    loop {
        match parse_expression(input, start_loc) {
            Done(rest, result) => {
                let (rest, loc) = consume_whitespace(rest, result.get_loc().1);
                input = rest;
                start_loc = loc;
                results.push(result);
                if rest.trim() == "" {
                    return (results, None);
                }
            }
            Error(err) => {
                return (results, Some(err));
            }
        }
    }
}

/// Parses a single s-expression, ignoring any trailing text.
///
/// This function returns a pair of the parsed s-expression and the tail of the text.
///
/// # Errors
///
/// If the text begins with an invalid s-expression (imbalanced parenthesis,
/// quotes, invalid numbers like 123q, etc.) then the parser will return an
/// error. Any text after the first s-expression doesn't affect the parsing.

///
/// # Examples
///
/// ```rust
/// # use ess::parser::parse_one;
/// let (expr, rest) = parse_one("1 (").unwrap();
/// assert_eq!(rest, " (");
/// ```
pub fn parse_one(input: &str) -> Result<(Sexp, &str), ParseError> {
    match parse_expression(input, 0) {
        Done(rest, result) => Ok((result, rest)),
        Error(err) => Err(err),
    }
}

// Core Parsers ////////////////////////////////////////////////////////////////

// TODO: All of these parsers deserve docs, but since they're somewhat internal
// parsers, it's less critical than the rest of the API.

#[allow(missing_docs)]
pub fn parse_expression(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Sexp);

    match input.chars().next() {
        Some('0'...'9') => parse_number(input, start_loc),
        Some('(') | Some('{') | Some('[') => parse_list(input, start_loc),
        Some('#') => parse_character(input, start_loc),
        Some('"') => parse_string(input, start_loc),
        Some('\'') => match parse_expression(&input[1..], start_loc + 1) {
            Done(rest, result) => {
                let span = *result.get_loc();
                let quote_span = (0, 1).offset(start_loc);
                Done(
                    rest,
                    Sexp::List(
                        vec![Sexp::Sym("quote".into(), quote_span), result],
                        quote_span.union(&span),
                    ),
                )
            }
            err => err,
        },
        Some('`') => match parse_expression(&input[1..], start_loc + 1) {
            Done(rest, result) => {
                let span = *result.get_loc();
                let quote_span = (0, 1).offset(start_loc);
                Done(
                    rest,
                    Sexp::List(
                        vec![Sexp::Sym("quasiquote".into(), quote_span), result],
                        quote_span.union(&span),
                    ),
                )
            }
            err => err,
        },
        Some(',') => {
            if input[1..].starts_with('@') {
                match parse_expression(&input[2..], start_loc + 2) {
                    Done(rest, result) => {
                        let span = *result.get_loc();
                        let quote_span = (0, 2).offset(start_loc);
                        Done(
                            rest,
                            Sexp::List(
                                vec![Sexp::Sym("unquote-splicing".into(), quote_span), result],
                                quote_span.union(&span),
                            ),
                        )
                    }
                    err => err,
                }
            } else {
                match parse_expression(&input[1..], start_loc + 1) {
                    Done(rest, result) => {
                        let span = *result.get_loc();
                        let quote_span = (0, 1).offset(start_loc);
                        Done(
                            rest,
                            Sexp::List(
                                vec![Sexp::Sym("unquote".into(), quote_span), result],
                                quote_span.union(&span),
                            ),
                        )
                    }
                    err => err,
                }
            }
        }
        Some(_) => parse_symbol(input, start_loc),
        None => unreachable!(),
    }
}

#[allow(missing_docs)]
pub fn parse_list(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::List);

    let first_char = match input.chars().nth(0) {
        Some(c @ '(') | Some(c @ '{') | Some(c @ '[') => c,
        Some(c) => {
            return Error(ParseError::List(
                Box::new(ParseError::Unexpected(c, 0)),
                (0, 0).offset(start_loc),
            ))
        }
        None => unreachable!(),
    };

    let mut input = &input[1..];
    let mut loc = start_loc + 1;
    let mut members = Vec::new();
    loop {
        {
            let (new_input, new_loc) = consume_whitespace!(input, loc, ParseError::List);
            input = new_input;
            loc = new_loc;
        }

        match input.chars().nth(0) {
            Some(c @ ')') | Some(c @ '}') | Some(c @ ']') => match (first_char, c) {
                ('(', ')') | ('{', '}') | ('[', ']') => {
                    return Done(&input[1..], Sexp::List(members, (start_loc, loc + 1)))
                }
                _ => {
                    return Error(ParseError::List(
                        Box::new(ParseError::Unexpected(c, loc)),
                        (start_loc, loc),
                    ))
                }
            },
            Some(_) => (),
            None => unreachable!(),
        }

        match parse_expression(input, loc) {
            Done(new_input, member) => {
                loc = member.get_loc().1;
                members.push(member);
                input = new_input;
            }
            Error(err) => return Error(ParseError::List(Box::new(err), (0, 0).offset(loc))),
        }
    }
}

#[allow(missing_docs)]
pub fn parse_number(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Number);

    match input.chars().next() {
        Some(c) if !c.is_digit(10) => {
            return Error(ParseError::Number(
                Box::new(ParseError::Unexpected(c, start_loc)),
                (0, c.len_utf8()).offset(start_loc),
            ));
        }
        None => {
            return Error(ParseError::Number(
                Box::new(ParseError::UnexpectedEof),
                (0, 0).offset(start_loc),
            ))
        }
        _ => (),
    }

    let base = 10;

    let mut end = 0;
    // Before the decimal point
    for (i, c) in input.char_indices() {
        if c == '.' {
            end = i + 1;
            break;
        }

        if c.is_delimiter() {
            return Done(
                &input[i..],
                Sexp::Int(
                    input[..i].parse().expect("Already matched digits"),
                    (0, i).offset(start_loc),
                ),
            );
        }

        if !c.is_digit(base) {
            return Error(ParseError::Number(
                Box::new(ParseError::Unexpected(c, start_loc + i)),
                (i, i).offset(start_loc),
            ));
        }

        end = i + c.len_utf8();
    }

    if input[end..].is_empty() {
        return Done(
            &input[end..],
            Sexp::Int(
                input.parse().expect("Already matched digits"),
                (0, end).offset(start_loc),
            ),
        );
    }

    // After the decimal point
    for (i, c) in input[end..].char_indices() {
        if c.is_delimiter() {
            return Done(
                &input[i + end..],
                Sexp::Float(
                    input[..end + i]
                        .parse()
                        .expect("Already matched digits.digits"),
                    (0, end + i).offset(start_loc),
                ),
            );
        }

        if !c.is_digit(base) {
            return Error(ParseError::Number(
                Box::new(ParseError::Unexpected(c, start_loc + i + end)),
                (i + end, i + end).offset(start_loc),
            ));
        }
    }

    Done(
        &input[input.len()..],
        Sexp::Float(
            input.parse().expect("Already matched digits.digits"),
            (0, input.len()).offset(start_loc),
        ),
    )
}

#[allow(missing_docs)]
pub fn parse_symbol(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Symbol);

    match input.chars().next() {
        Some(c @ '#') | Some(c @ ':') | Some(c @ '0'...'9') => {
            return Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected(c, start_loc)),
                (0, 0).offset(start_loc),
            ))
        }
        Some(c) if c.is_delimiter() => {
            return Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected(c, start_loc)),
                (0, 0).offset(start_loc),
            ))
        }
        Some(_) => (),
        None => unreachable!(),
    }

    for (i, c) in input.char_indices() {
        if c.is_delimiter() {
            return Done(
                &input[i..],
                Sexp::Sym(input[..i].into(), (0, i).offset(start_loc)),
            );
        }
    }

    Done(
        &input[input.len()..],
        Sexp::Sym(input.into(), (0, input.len()).offset(start_loc)),
    )
}

#[allow(missing_docs)]
pub fn parse_string(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::String);

    match input.chars().next() {
        Some('"') => (),
        Some(c) => {
            return Error(ParseError::String(
                Box::new(ParseError::Unexpected(c, start_loc)),
                (0, 0).offset(start_loc),
            ))
        }
        None => unreachable!(),
    }

    for (i, c) in input[1..].char_indices() {
        if c == '"' {
            return Done(
                &input[2 + i..],
                Sexp::Str(input[1..=i].into(), (0, i + 2).offset(start_loc)),
            );
        }
    }

    Error(ParseError::String(
        Box::new(ParseError::UnexpectedEof),
        (0, input.len()).offset(start_loc),
    ))
}

#[allow(missing_docs)]
pub fn parse_character(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
    let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Char);

    match input.chars().nth(0) {
        Some('#') => (),
        Some(c) => {
            return Error(ParseError::Char(
                Box::new(ParseError::Unexpected(c, start_loc)),
                (0, 0).offset(start_loc),
            ))
        }
        None => {
            return Error(ParseError::Char(
                Box::new(ParseError::UnexpectedEof),
                (0, 0).offset(start_loc),
            ))
        }
    }

    match input.chars().nth(1) {
        Some('\\') => (),
        Some(c) => {
            return Error(ParseError::Char(
                Box::new(ParseError::Unexpected(c, start_loc + 1)),
                (1, 1).offset(start_loc),
            ))
        }
        None => {
            return Error(ParseError::Char(
                Box::new(ParseError::UnexpectedEof),
                (1, 1).offset(start_loc),
            ))
        }
    }

    match input.chars().nth(2) {
        Some(c) => Done(&input[3..], Sexp::Char(c, (0, 3).offset(start_loc))),
        None => Error(ParseError::Char(
            Box::new(ParseError::UnexpectedEof),
            (2, 2).offset(start_loc),
        )),
    }
}

// Tests ///////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod test {
    use parser::ParseResult::*;
    use parser::*;
    use sexp::Sexp;
    use span::Span;

    #[test]
    fn test_parse() {
        assert_eq!(
            parse("1 2 3"),
            (
                vec![
                    Sexp::Int(1, (0, 1)),
                    Sexp::Int(2, (2, 3)),
                    Sexp::Int(3, (4, 5))
                ],
                None
            )
        );
        assert_eq!(
            parse("1 2 )"),
            (
                vec![Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3))],
                Some(ParseError::Symbol(
                    Box::new(ParseError::Unexpected(')', 4)),
                    (4, 4)
                ))
            )
        );
    }

    #[test]
    fn test_parse_one() {
        assert_eq!(parse_one("1 2"), Ok((Sexp::Int(1, (0, 1)), " 2")));
    }

    #[test]
    fn test_parse_expression() {
        assert_eq!(parse_expression("	1", 0), Done("", Sexp::Int(1, (1, 2))));
        assert_eq!(
            parse_expression("2.2", 0),
            Done("", Sexp::Float(2.2, (0, 3)))
        );
        assert_eq!(
            parse_expression(" a", 0),
            Done("", Sexp::Sym("a".into(), (1, 2)))
        );
        assert_eq!(
            parse_expression("#\\c", 0),
            Done("", Sexp::Char('c', (0, 3)))
        );
        assert_eq!(
            parse_expression(r#""hi""#, 0),
            Done("", Sexp::Str("hi".into(), (0, 4)))
        );
        assert_eq!(
            parse_expression("()", 0),
            Done("", Sexp::List(vec![], (0, 2)))
        );
        assert_eq!(
            parse_expression("( 1 2 3 )", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Int(1, (2, 3)),
                        Sexp::Int(2, (4, 5)),
                        Sexp::Int(3, (6, 7)),
                    ],
                    (0, 9)
                )
            )
        );

        assert_eq!(
            parse_expression("", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (0, 0)
            ))
        );
    }

    #[test]
    fn test_parse_expr_quote() {
        assert_eq!(
            parse_expression("'a", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quote".into(), (0, 1)),
                        Sexp::Sym("a".into(), (1, 2)),
                    ],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression("'1", 0),
            Done(
                "",
                Sexp::List(
                    vec![Sexp::Sym("quote".into(), (0, 1)), Sexp::Int(1, (1, 2)),],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression("' (1 2 3)", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quote".into(), (0, 1)),
                        Sexp::List(
                            vec![
                                Sexp::Int(1, (3, 4)),
                                Sexp::Int(2, (5, 6)),
                                Sexp::Int(3, (7, 8)),
                            ],
                            (2, 9)
                        ),
                    ],
                    (0, 9)
                )
            )
        );

        assert_eq!(
            parse_expression("'", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (1, 1)
            ))
        );
        assert_eq!(
            parse_expression("`'", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (2, 2)
            ))
        );
    }

    #[test]
    fn test_parse_expr_quasiquote() {
        assert_eq!(
            parse_expression("`a", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quasiquote".into(), (0, 1)),
                        Sexp::Sym("a".into(), (1, 2)),
                    ],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression("`1", 0),
            Done(
                "",
                Sexp::List(
                    vec![Sexp::Sym("quasiquote".into(), (0, 1)), Sexp::Int(1, (1, 2)),],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression("` (1 2 3)", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quasiquote".into(), (0, 1)),
                        Sexp::List(
                            vec![
                                Sexp::Int(1, (3, 4)),
                                Sexp::Int(2, (5, 6)),
                                Sexp::Int(3, (7, 8)),
                            ],
                            (2, 9)
                        ),
                    ],
                    (0, 9)
                )
            )
        );
        assert_eq!(
            parse_expression("`'a", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quasiquote".into(), (0, 1)),
                        Sexp::List(
                            vec![
                                Sexp::Sym("quote".into(), (1, 2)),
                                Sexp::Sym("a".into(), (2, 3)),
                            ],
                            (1, 3)
                        ),
                    ],
                    (0, 3)
                )
            )
        );

        assert_eq!(
            parse_expression("`", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (1, 1)
            ))
        );
    }

    #[test]
    fn test_parse_expr_unquote() {
        assert_eq!(
            parse_expression(",a", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("unquote".into(), (0, 1)),
                        Sexp::Sym("a".into(), (1, 2)),
                    ],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression(",1", 0),
            Done(
                "",
                Sexp::List(
                    vec![Sexp::Sym("unquote".into(), (0, 1)), Sexp::Int(1, (1, 2)),],
                    (0, 2)
                )
            )
        );
        assert_eq!(
            parse_expression(", (1 2 3)", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("unquote".into(), (0, 1)),
                        Sexp::List(
                            vec![
                                Sexp::Int(1, (3, 4)),
                                Sexp::Int(2, (5, 6)),
                                Sexp::Int(3, (7, 8)),
                            ],
                            (2, 9)
                        ),
                    ],
                    (0, 9)
                )
            )
        );
        assert_eq!(
            parse_expression("`,a", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quasiquote".into(), (0, 1)),
                        Sexp::List(
                            vec![
                                Sexp::Sym("unquote".into(), (1, 2)),
                                Sexp::Sym("a".into(), (2, 3)),
                            ],
                            (1, 3)
                        ),
                    ],
                    (0, 3)
                )
            )
        );
        assert_eq!(
            parse_expression("`(,@a)", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Sym("quasiquote".into(), (0, 1)),
                        Sexp::List(
                            vec![Sexp::List(
                                vec![
                                    Sexp::Sym("unquote-splicing".into(), (2, 4)),
                                    Sexp::Sym("a".into(), (4, 5)),
                                ],
                                (2, 5)
                            ),],
                            (1, 6)
                        ),
                    ],
                    (0, 6)
                )
            )
        );

        assert_eq!(
            parse_expression(",", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (1, 1)
            ))
        );
        assert_eq!(
            parse_expression(",@", 0),
            Error(ParseError::Sexp(
                Box::new(ParseError::UnexpectedEof),
                (2, 2)
            ))
        );
    }

    #[test]
    fn test_parse_list() {
        assert_eq!(parse_list("()", 0), Done("", Sexp::List(vec![], (0, 2))));
        assert_eq!(
            parse_list("(1)", 0),
            Done("", Sexp::List(vec![Sexp::Int(1, (1, 2))], (0, 3)))
        );
        assert_eq!(
            parse_list("  ( 1    2  3 a )", 0),
            Done(
                "",
                Sexp::List(
                    vec![
                        Sexp::Int(1, (4, 5)),
                        Sexp::Int(2, (9, 10)),
                        Sexp::Int(3, (12, 13)),
                        Sexp::Sym("a".into(), (14, 15)),
                    ],
                    (2, 17)
                )
            )
        );
    }

    #[test]
    fn test_parse_number() {
        assert_eq!(parse_number("1", 0), Done("", Sexp::Int(1, (0, 1))));
        assert_eq!(parse_number(" 13", 0), Done("", Sexp::Int(13, (1, 3))));
        assert_eq!(parse_number("1.2", 0), Done("", Sexp::Float(1.2, (0, 3))));
        assert_eq!(
            parse_number("\u{3000}4.2", 0),
            Done("", Sexp::Float(4.2, (0, 3).offset('\u{3000}'.len_utf8())))
        );
        assert_eq!(parse_number(" 	42 ", 0), Done(" ", Sexp::Int(42, (2, 4))));
        assert_eq!(
            parse_number(" 4.2  ", 0),
            Done("  ", Sexp::Float(4.2, (1, 4)))
        );
        assert_eq!(parse_number("1()", 0), Done("()", Sexp::Int(1, (0, 1))));
        assert_eq!(
            parse_number("3.6()", 0),
            Done("()", Sexp::Float(3.6, (0, 3)))
        );

        assert_eq!(
            parse_number("", 0),
            Error(ParseError::Number(
                Box::new(ParseError::UnexpectedEof),
                (0, 0)
            ))
        );
        assert_eq!(
            parse_number("123a", 0),
            Error(ParseError::Number(
                Box::new(ParseError::Unexpected('a', 3)),
                (3, 3)
            ))
        );
        assert_eq!(
            parse_number("66.6+", 0),
            Error(ParseError::Number(
                Box::new(ParseError::Unexpected('+', 4)),
                (4, 4)
            ))
        );
    }

    #[test]
    fn test_parse_ident() {
        assert_eq!(
            parse_symbol("+", 0),
            Done("", Sexp::Sym("+".into(), (0, 1)))
        );
        assert_eq!(
            parse_symbol(" nil?", 0),
            Done("", Sexp::Sym("nil?".into(), (1, 5)))
        );
        assert_eq!(
            parse_symbol(" ->socket", 0),
            Done("", Sexp::Sym("->socket".into(), (1, 9)))
        );
        assert_eq!(
            parse_symbol("fib(", 0),
            Done("(", Sexp::Sym("fib".into(), (0, 3)))
        );
        assert_eq!(
            parse_symbol("foo2", 0),
            Done("", Sexp::Sym("foo2".into(), (0, 4)))
        );

        // We reserve #foo for the implementation to do as it wishes
        assert_eq!(
            parse_symbol("#hi", 0),
            Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected('#', 0)),
                (0, 0)
            ))
        );
        // We reserve :foo for keywords
        assert_eq!(
            parse_symbol(":hi", 0),
            Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected(':', 0)),
                (0, 0)
            ))
        );

        assert_eq!(
            parse_symbol("", 0),
            Error(ParseError::Symbol(
                Box::new(ParseError::UnexpectedEof),
                (0, 0)
            ))
        );
        assert_eq!(
            parse_symbol("0", 0),
            Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected('0', 0)),
                (0, 0)
            ))
        );
        assert_eq!(
            parse_symbol("()", 0),
            Error(ParseError::Symbol(
                Box::new(ParseError::Unexpected('(', 0)),
                (0, 0)
            ))
        );
    }

    #[test]
    fn test_parse_string() {
        assert_eq!(
            parse_string(r#""""#, 0),
            Done("", Sexp::Str("".into(), (0, 2)))
        );
        assert_eq!(
            parse_string(r#""hello""#, 0),
            Done("", Sexp::Str("hello".into(), (0, 7)))
        );
        assert_eq!(
            parse_string(
                r#"  "this is a nice string
with 0123 things in it""#,
                0
            ),
            Done(
                "",
                Sexp::Str(
                    "this is a nice string\nwith 0123 things in it".into(),
                    (2, 48)
                )
            )
        );

        assert_eq!(
            parse_string("", 0),
            Error(ParseError::String(
                Box::new(ParseError::UnexpectedEof),
                (0, 0)
            ))
        );
        assert_eq!(
            parse_string(r#""hi"#, 0),
            Error(ParseError::String(
                Box::new(ParseError::UnexpectedEof),
                (0, 3)
            ))
        );
    }

    #[test]
    fn test_parse_char() {
        assert_eq!(
            parse_character(r#"#\""#, 0),
            Done("", Sexp::Char('"', (0, 3)))
        );
        assert_eq!(
            parse_character(r#"#\ "#, 0),
            Done("", Sexp::Char(' ', (0, 3)))
        );
        assert_eq!(
            parse_character(r#"  #\\"#, 0),
            Done("", Sexp::Char('\\', (2, 5)))
        );

        assert_eq!(
            parse_character("", 0),
            Error(ParseError::Char(
                Box::new(ParseError::UnexpectedEof),
                (0, 0)
            ))
        );
        assert_eq!(
            parse_character("#", 0),
            Error(ParseError::Char(
                Box::new(ParseError::UnexpectedEof),
                (1, 1)
            ))
        );
        assert_eq!(
            parse_character("#\\", 0),
            Error(ParseError::Char(
                Box::new(ParseError::UnexpectedEof),
                (2, 2)
            ))
        );
        assert_eq!(
            parse_character("a", 0),
            Error(ParseError::Char(
                Box::new(ParseError::Unexpected('a', 0)),
                (0, 0)
            ))
        );
    }

    #[test]
    fn test_parse_comments() {
        assert_eq!(
            parse(
                r#"(;hello
    ;hi
;hey ;how are you doing?
) ;hi"#
            ),
            (vec![Sexp::List(vec![], (0, 42))], None)
        )
    }
}