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
// Copyright (C) 2022-2023 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the scale-value crate.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(clippy::enum_variant_names)]

use super::string_helpers;
use crate::value::{BitSequence, Composite, Primitive, Value, Variant};
use std::num::ParseIntError;
use yap::{types::StrTokens, IntoTokens, TokenLocation, Tokens};

/// A struct which will try to parse a string into a [`Value`].
/// This can be configured with custom parsers to extend what we're able
/// to parse into a [`Value`].
pub struct FromStrBuilder {
    custom_parsers: Vec<CustomParser>,
}

type CustomParser = Box<dyn Fn(&mut &str) -> Option<Result<Value<()>, ParseError>> + 'static>;

impl FromStrBuilder {
    pub(crate) fn new() -> Self {
        FromStrBuilder { custom_parsers: Vec::new() }
    }

    /// Add a custom parser. A custom parser is a function which is given a mutable string
    /// reference and will:
    ///
    /// - return `None` if the string given is not applicable,
    /// - return `Some(Ok(value))` if we can successfully parse a value from the string. In
    ///   this case, the parser should update the `&mut str` it's given to consume however
    ///   much was parsed.
    /// - return `Some(Err(error))` if the string given looks like a match, but something went
    ///   wrong in trying to properly parse it. In this case, parsing will stop immediately and
    ///   this error will be returned, so use this sparingly, as other parsers may be able to
    ///   successfully parse what this one has failed to parse. No additional tokens will be consumed
    ///   if an error occurs.
    pub fn add_custom_parser<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut &str) -> Option<Result<Value<()>, ParseError>> + 'static,
    {
        self.custom_parsers.push(Box::new(f));
        self
    }

    /// Attempt to parse the string provided into a value, returning any error that occurred while
    /// attempting to do so, as well as the rest of the string that was not consumed by this parsing.
    pub fn parse<'a>(&self, s: &'a str) -> (Result<Value<()>, ParseError>, &'a str) {
        let mut tokens = s.into_tokens();
        let res = parse_value(&mut tokens, &self.custom_parsers);
        let remaining = tokens.remaining();
        (res, remaining)
    }
}

/// An error parsing the provided string into a Value
#[derive(Debug, thiserror::Error)]
pub struct ParseError {
    /// Byte offset into the provided string that the error begins.
    pub start_loc: usize,
    /// Byte offset into the provided string that the error ends. Many errors begin at some
    /// point but do not have a known end position.
    pub end_loc: Option<usize>,
    /// Details about the error that occurred.
    pub err: ParseErrorKind,
}

impl ParseError {
    /// Construct a new `ParseError` for tokens at the given location.
    pub fn new_at<E: Into<ParseErrorKind>>(err: E, loc: usize) -> Self {
        Self { start_loc: loc, end_loc: None, err: err.into() }
    }
    /// Construct a new `ParseError` for tokens between the given locations.
    pub fn new_between<E: Into<ParseErrorKind>>(err: E, start: usize, end: usize) -> Self {
        Self { start_loc: start, end_loc: Some(end), err: err.into() }
    }
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(end_loc) = self.end_loc {
            write!(f, "Error from char {} to {}: {}", self.start_loc, end_loc, self.err)
        } else {
            write!(f, "Error at char {}: {}", self.start_loc, self.err)
        }
    }
}

// Add handy helper methods to error-kinds
macro_rules! at_between {
    ($ty:ident) => {
        impl $ty {
            /// Error at a specific location with no specific end
            pub fn at(self, loc: usize) -> ParseError {
                ParseError::new_at(self, loc)
            }
            /// Error at a specific location for the next character
            pub fn at_one(self, loc: usize) -> ParseError {
                ParseError::new_between(self, loc, loc + 1)
            }
            /// Error between two locations.
            pub fn between(self, start: usize, end: usize) -> ParseError {
                ParseError::new_between(self, start, end)
            }
        }
    };
}

/// Details about the error that occurred.
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseErrorKind {
    #[error("Expected a value")]
    ExpectedValue,
    #[error("{0}")]
    Complex(#[from] ParseComplexError),
    #[error("{0}")]
    Char(#[from] ParseCharError),
    #[error("{0}")]
    String(#[from] ParseStringError),
    #[error("{0}")]
    Number(#[from] ParseNumberError),
    #[error("{0}")]
    BitSequence(#[from] ParseBitSequenceError),
    #[error("{0}")]
    Custom(ParseCustomError),
}
at_between!(ParseErrorKind);

impl ParseErrorKind {
    /// Construct a custom error.
    pub fn custom<E: Into<ParseCustomError>>(e: E) -> Self {
        ParseErrorKind::Custom(e.into())
    }
}

/// An arbitrary custom error.
pub type ParseCustomError = Box<dyn std::error::Error + Send + Sync + 'static>;

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseComplexError {
    #[error("The first character in a field name should be alphabetic")]
    InvalidStartingCharacterInIdent,
    #[error("Field name is not valid (it should begin with an alphabetical char and then consist only of alphanumeric chars)")]
    InvalidFieldName,
    #[error("Missing field separator; expected {0}")]
    MissingFieldSeparator(char),
    #[error("Missing closing '{0}'")]
    ExpectedCloserToMatch(char, usize),
}
at_between!(ParseComplexError);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseCharError {
    #[error("Expected a single character")]
    ExpectedValidCharacter,
    #[error("Expected an escape code to follow the '\\'")]
    ExpectedValidEscapeCode,
    #[error("Expected a closing quote to match the opening quote at position {0}")]
    ExpectedClosingQuoteToMatch(usize),
}
at_between!(ParseCharError);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseStringError {
    #[error("Expected a closing quote to match the opening quote at position {0}")]
    ExpectedClosingQuoteToMatch(usize),
    #[error("Expected an escape code to follow the '\\'")]
    ExpectedValidEscapeCode,
}
at_between!(ParseStringError);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseNumberError {
    #[error("Expected one or more digits")]
    ExpectedDigit,
    #[error("Failed to parse digits into an integer: {0}")]
    ParsingFailed(ParseIntError),
}
at_between!(ParseNumberError);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseBitSequenceError {
    #[error("Expected a closing bracket ('>') to match the opening one at position {0}")]
    ExpectedClosingBracketToMatch(usize),
    #[error("Invalid character; expecting a 0 or 1")]
    InvalidCharacter,
}
at_between!(ParseBitSequenceError);

// Parse a value.
fn parse_value(
    t: &mut StrTokens,
    custom_parsers: &[CustomParser],
) -> Result<Value<()>, ParseError> {
    // Try any custom parsers first.
    if !custom_parsers.is_empty() {
        let s = t.remaining();
        let start_offset = t.offset();
        let cursor = &mut &*s;

        for parser in custom_parsers {
            if let Some(res) = parser(cursor) {
                match res {
                    Ok(value) => {
                        // Wind our StrTokens forward to take into account anything that
                        // was consumed. We do this rather than replacing it because we want
                        // to preserve the full string and offsets.
                        for _ in cursor.len()..s.len() {
                            t.next();
                        }
                        return Ok(value);
                    }
                    Err(e) => {
                        // Adjust locations in error to be relative to the big string,
                        // not the smaller slice that was passed to the custom parser.
                        return Err(ParseError {
                            start_loc: start_offset + e.start_loc,
                            end_loc: e.end_loc.map(|l| start_offset + l),
                            err: e.err,
                        });
                    }
                }
            }
        }
    }

    // Our parsers return `Result<Thing, Option<ParseError>>`, but in order to know
    // whether to try the next item, `one_of` expects `Option<T>`, so we transpose_err
    // to convert to the right shape.
    let val = yap::one_of!(t;
        transpose_err(parse_bool(t).map(Value::bool).ok_or(None)),
        transpose_err(parse_char(t).map(Value::char)),
        transpose_err(parse_string(t).map(Value::string)),
        transpose_err(parse_number(t).map(Value::primitive)),
        transpose_err(parse_named_composite(t, custom_parsers).map(|v| v.into())),
        transpose_err(parse_unnamed_composite(t, custom_parsers).map(|v| v.into())),
        transpose_err(parse_bit_sequence(t).map(Value::bit_sequence)),
        transpose_err(parse_variant(t, custom_parsers).map(|v| v.into())),
    );

    match val {
        Some(Ok(val)) => Ok(val),
        Some(Err(e)) => Err(e),
        None => Err(ParseError::new_at(ParseErrorKind::ExpectedValue, t.offset())),
    }
}

// Parse a named composite value like `{ foo: 123 }`.
//
// As with most of the parsers here, the error is optional. A `Some` error indicates that
// we're midway through parsing something and have run into an error. a `None` error indicates
// that we can see up front that the characters we're parsing aren't going to be the right shape,
// and can attempt to parse the characters into a different thing if we wish.
fn parse_named_composite(
    t: &mut StrTokens,
    custom_parsers: &[CustomParser],
) -> Result<Composite<()>, Option<ParseError>> {
    let start = t.offset();
    if !t.token('{') {
        return Err(None);
    }
    skip_whitespace(t);

    // No values? bail early.
    if t.token('}') {
        return Ok(Composite::Named(vec![]));
    }

    let vals = t
        .sep_by_err(
            |t| parse_field_name_and_value(t, custom_parsers),
            |t| skip_spaced_separator(t, ','),
        )
        .collect::<Result<_, _>>()?;

    skip_whitespace(t);
    if !t.token('}') {
        return Err(Some(ParseComplexError::ExpectedCloserToMatch('}', start).at_one(t.offset())));
    }
    Ok(Composite::Named(vals))
}

// Parse an unnamed composite value like `(true, 123)`
fn parse_unnamed_composite(
    t: &mut StrTokens,
    custom_parsers: &[CustomParser],
) -> Result<Composite<()>, Option<ParseError>> {
    let start = t.offset();
    if !t.token('(') {
        return Err(None);
    }
    skip_whitespace(t);

    // No values? bail early.
    if t.token(')') {
        return Ok(Composite::Unnamed(vec![]));
    }

    let vals = t
        .sep_by_err(|t| parse_value(t, custom_parsers), |t| skip_spaced_separator(t, ','))
        .collect::<Result<_, _>>()?;

    skip_whitespace(t);
    if !t.token(')') {
        return Err(Some(ParseComplexError::ExpectedCloserToMatch(')', start).at_one(t.offset())));
    }
    Ok(Composite::Unnamed(vals))
}

// Parse a variant like `Variant { hello: "there" }` or `Foo (123, true)`
fn parse_variant(
    t: &mut StrTokens,
    custom_parsers: &[CustomParser],
) -> Result<Variant<()>, Option<ParseError>> {
    let ident = match parse_optional_variant_ident(t) {
        Some(ident) => ident,
        None => return Err(None),
    };

    skip_whitespace(t);

    let composite = yap::one_of!(t;
        transpose_err(parse_named_composite(t, custom_parsers)),
        transpose_err(parse_unnamed_composite(t, custom_parsers))
    );

    match composite {
        Some(Ok(values)) => Ok(Variant { name: ident, values }),
        Some(Err(e)) => Err(Some(e)),
        None => Err(None),
    }
}

// Parse a sequence of bits like `<01101>` or `<>` into a bit sequence.
fn parse_bit_sequence(t: &mut StrTokens) -> Result<BitSequence, Option<ParseError>> {
    let start = t.offset();
    if !t.token('<') {
        return Err(None);
    }
    let bits = t.tokens_while(|&c| c == '0' || c == '1').map(|c| c == '1');
    let mut seq = BitSequence::new();
    for bit in bits {
        seq.push(bit);
    }
    if !t.token('>') {
        return Err(Some(
            ParseBitSequenceError::ExpectedClosingBracketToMatch(start)
                .between(t.offset(), t.offset() + 1),
        ));
    }
    Ok(seq)
}

// Parse a bool (`true` or `false`)
fn parse_bool(t: &mut StrTokens) -> Option<bool> {
    if t.tokens("true".chars()) {
        Some(true)
    } else if t.tokens("false".chars()) {
        Some(false)
    } else {
        None
    }
}

// Parse a char like `'a'`
fn parse_char(t: &mut StrTokens) -> Result<char, Option<ParseError>> {
    let start = t.offset();
    if !t.token('\'') {
        return Err(None);
    }
    let char = match t.next() {
        None => return Err(Some(ParseCharError::ExpectedValidCharacter.at_one(t.offset()))),
        Some(c) => c,
    };

    // If char is a backslash, it's an escape code and we
    // need to unescape it to find our inner char:
    let char = if char == '\\' {
        let escape_code = match t.next() {
            None => return Err(Some(ParseCharError::ExpectedValidEscapeCode.at_one(t.offset()))),
            Some(c) => c,
        };
        match string_helpers::from_escape_code(escape_code) {
            None => return Err(Some(ParseCharError::ExpectedValidEscapeCode.at_one(t.offset()))),
            Some(c) => c,
        }
    } else {
        char
    };

    if !t.token('\'') {
        return Err(Some(ParseCharError::ExpectedClosingQuoteToMatch(start).at_one(t.offset())));
    }
    Ok(char)
}

// Parse a number like `-123_456` or `234` or `+1234_5`
fn parse_number(t: &mut StrTokens) -> Result<Primitive, Option<ParseError>> {
    let start_loc = t.offset();
    let is_positive = t.token('+') || !t.token('-');

    // When we iterate numeric digits, prefix a sign as needed:
    let sign = if is_positive { "".chars() } else { "-".chars() };

    // Now, we expect a digit and then a mix of digits and underscores:
    let mut seen_n = false;
    let digits = t
        .tokens_while(|c| {
            if c.is_ascii_digit() {
                seen_n = true;
                true
            } else {
                seen_n && *c == '_'
            }
        })
        .filter(|c| c.is_ascii_digit());

    // Chain sign to digits and attempt to parse into a number.
    let n_str: String = sign.chain(digits).collect();
    let end_loc = t.offset();

    // Nothing was parsed; Return None.
    if end_loc == start_loc {
        return Err(None);
    }

    // No digits were parsed but a sign was; err.
    if !seen_n {
        return Err(Some(ParseNumberError::ExpectedDigit.between(end_loc, end_loc + 1)));
    }

    // Parse into a number as best we can:
    if is_positive {
        n_str
            .parse::<u128>()
            .map(Primitive::u128)
            .map_err(|e| Some(ParseNumberError::ParsingFailed(e).between(start_loc, end_loc)))
    } else {
        n_str
            .parse::<i128>()
            .map(Primitive::i128)
            .map_err(|e| Some(ParseNumberError::ParsingFailed(e).between(start_loc, end_loc)))
    }
}

// Parse a string like `"hello\n there"`
fn parse_string(t: &mut StrTokens) -> Result<String, Option<ParseError>> {
    let start = t.offset();
    if !t.token('"') {
        return Err(None);
    }

    let mut out: String = String::new();
    let mut next_is_escaped = false;
    loop {
        let pos = t.offset();
        let char = match t.next() {
            Some(c) => c,
            None => {
                return Err(Some(
                    ParseStringError::ExpectedClosingQuoteToMatch(start).at_one(t.offset()),
                ))
            }
        };

        match char {
            // Escape a char:
            '\\' if !next_is_escaped => {
                next_is_escaped = true;
            }
            // Handle escaped chars:
            c if next_is_escaped => match string_helpers::from_escape_code(c) {
                Some(c) => {
                    out.push(c);
                    next_is_escaped = false;
                }
                None => {
                    return Err(Some(
                        ParseStringError::ExpectedValidEscapeCode.between(pos, pos + 1),
                    ))
                }
            },
            // String has closed
            '"' => {
                break; // closing quote seen; done!
            }
            // All other chars pushed as-is.
            c => {
                out.push(c);
            }
        }
    }

    Ok(out)
}

// Parse a field in a named composite like `foo: 123` or `"hello there": 123`
fn parse_field_name_and_value(
    t: &mut StrTokens,
    custom_parsers: &[CustomParser],
) -> Result<(String, Value<()>), ParseError> {
    let name = parse_field_name(t)?;
    if !skip_spaced_separator(t, ':') {
        return Err(ParseComplexError::MissingFieldSeparator(':').at_one(t.offset()));
    }
    let value = parse_value(t, custom_parsers)?;
    Ok((name, value))
}

// Parse a field name in a named composite like `foo` or `"hello there"`
fn parse_field_name(t: &mut StrTokens) -> Result<String, ParseError> {
    let field_name = yap::one_of!(t;
        transpose_err(parse_string(t)),
        Some(parse_ident(t)),
    );

    match field_name {
        Some(Ok(name)) => Ok(name),
        Some(Err(e)) => Err(e),
        None => Err(ParseComplexError::InvalidFieldName.at(t.offset())),
    }
}

// Parse an ident used for the variant name, like `MyVariant` or the special case
// `i"My variant name"` for idents that are not normally valid variant names, but
// can be set in Value variants (this is to ensure that we can display and then parse
// as many user-generated Values as possible).
fn parse_optional_variant_ident(t: &mut StrTokens) -> Option<String> {
    fn parse_i_string(t: &mut StrTokens) -> Option<String> {
        if t.next()? != 'v' {
            return None;
        }
        parse_string(t).ok()
    }

    yap::one_of!(t;
        parse_i_string(t),
        parse_ident(t).ok()
    )
}

// Parse an ident like `foo` or `MyVariant`
fn parse_ident(t: &mut StrTokens) -> Result<String, ParseError> {
    let start = t.location();
    if t.skip_tokens_while(|c| c.is_alphabetic()) == 0 {
        return Err(ParseComplexError::InvalidStartingCharacterInIdent.at_one(start.offset()));
    }
    t.skip_tokens_while(|c| c.is_alphanumeric() || *c == '_');
    let end = t.location();

    let ident_str = t.slice(start, end).as_iter().collect();
    Ok(ident_str)
}

// Skip any whitespace characters
fn skip_whitespace(t: &mut StrTokens) {
    t.skip_tokens_while(|c| c.is_whitespace());
}

// Skip a provided separator, with optional spaces on either side
fn skip_spaced_separator(t: &mut StrTokens, s: char) -> bool {
    skip_whitespace(t);
    let is_sep = t.token(s);
    skip_whitespace(t);
    is_sep
}

// Turn a ` Result<T, Option<E>>` into `Option<Result<T, E>>`.
fn transpose_err<T, E>(r: Result<T, Option<E>>) -> Option<Result<T, E>> {
    match r {
        Ok(val) => Some(Ok(val)),
        Err(Some(e)) => Some(Err(e)),
        Err(None) => None,
    }
}

#[cfg(test)]
mod test {
    use super::*;

    // Wrap our error type to impl PartialEq on it for tests,
    // which we otherwise don't want to have to implement in
    // production code.
    #[derive(Debug)]
    pub struct E(ParseError);

    impl From<ParseError> for E {
        fn from(value: ParseError) -> Self {
            E(value)
        }
    }
    impl PartialEq for E {
        fn eq(&self, other: &Self) -> bool {
            let (a, b) = (&self.0, &other.0);

            // locations should match in tests.
            if (a.start_loc, a.end_loc) != (b.start_loc, b.end_loc) {
                return false;
            }

            // error kinds should match; only bother to impl the ones we want to compare for tests.
            match (&a.err, &b.err) {
                (ParseErrorKind::String(a), ParseErrorKind::String(b)) => a == b,
                (ParseErrorKind::Char(a), ParseErrorKind::Char(b)) => a == b,
                (ParseErrorKind::Number(a), ParseErrorKind::Number(b)) => a == b,
                (ParseErrorKind::Custom(a), ParseErrorKind::Custom(b)) => {
                    a.to_string() == b.to_string()
                }
                _ => {
                    panic!("PartialEq not implemented for these variants yet.")
                }
            }
        }
    }

    fn from(s: &str) -> Result<Value<()>, E> {
        let (res, remaining) = FromStrBuilder::new().parse(s);
        match res {
            Ok(value) => {
                assert_eq!(remaining.len(), 0, "was not expecting any unparsed output");
                Ok(value)
            }
            Err(e) => Err(E(e)),
        }
    }

    #[test]
    fn parse_bools() {
        assert_eq!(from("true"), Ok(Value::bool(true)));
        assert_eq!(from("false"), Ok(Value::bool(false)));
    }

    #[test]
    fn parse_numbers() {
        assert_eq!(from("123"), Ok(Value::u128(123)));
        assert_eq!(from("1_234_56"), Ok(Value::u128(123_456)));
        assert_eq!(from("+1_234_56"), Ok(Value::u128(123_456)));
        assert_eq!(from("-123_4"), Ok(Value::i128(-1234)));
        assert_eq!(from("-abc"), Err(E(ParseNumberError::ExpectedDigit.between(1, 2))));
    }

    #[test]
    fn parse_chars() {
        assert_eq!(from("'a'"), Ok(Value::char('a')));
        assert_eq!(from("'😀'"), Ok(Value::char('😀')));
        assert_eq!(from("'\\n'"), Ok(Value::char('\n')));
        assert_eq!(from("'\\t'"), Ok(Value::char('\t')));
        assert_eq!(from("'\\\"'"), Ok(Value::char('"')));
        assert_eq!(from("'\\\''"), Ok(Value::char('\'')));
        assert_eq!(from("'\\r'"), Ok(Value::char('\r')));
        assert_eq!(from("'\\\\'"), Ok(Value::char('\\')));
        assert_eq!(from("'\\0'"), Ok(Value::char('\0')));
        assert_eq!(from("'a"), Err(E(ParseCharError::ExpectedClosingQuoteToMatch(0).at_one(2))));
    }

    #[test]
    fn parse_strings() {
        assert_eq!(from("\"\\n \\r \\t \\0 \\\"\""), Ok(Value::string("\n \r \t \0 \"")));
        assert_eq!(from("\"Hello there 😀\""), Ok(Value::string("Hello there 😀")));
        assert_eq!(from("\"Hello\\n\\t there\""), Ok(Value::string("Hello\n\t there")));
        assert_eq!(from("\"Hello\\\\ there\""), Ok(Value::string("Hello\\ there")));
        assert_eq!(
            from("\"Hello\\p there\""),
            Err(E(ParseStringError::ExpectedValidEscapeCode.between(7, 8)))
        );
        assert_eq!(
            from("\"Hi"),
            Err(E(ParseStringError::ExpectedClosingQuoteToMatch(0).at_one(3)))
        );
    }

    #[test]
    fn parse_unnamed_composites() {
        assert_eq!(
            from("(  true, 1234 ,\t\n\t \"Hello!\" )"),
            Ok(Value::unnamed_composite(vec![
                Value::bool(true),
                Value::u128(1234),
                Value::string("Hello!")
            ]))
        );
        assert_eq!(from("()"), Ok(Value::unnamed_composite([])));
        assert_eq!(from("(\n\n\t\t\n)"), Ok(Value::unnamed_composite([])));
    }

    #[test]
    fn parse_named_composites() {
        assert_eq!(
            from(
                "{
            hello: true,
            foo: 1234,
            \"Hello there 😀\": \"Hello!\"
        }"
            ),
            Ok(Value::named_composite([
                ("hello", Value::bool(true)),
                ("foo", Value::u128(1234)),
                ("Hello there 😀", Value::string("Hello!"))
            ]))
        );
    }

    #[test]
    fn parse_variants() {
        assert_eq!(
            from(
                "MyVariant {
            hello: true,
            foo: 1234,
            \"Hello there 😀\": \"Hello!\"
        }"
            ),
            Ok(Value::named_variant(
                "MyVariant",
                [
                    ("hello", Value::bool(true)),
                    ("foo", Value::u128(1234)),
                    ("Hello there 😀", Value::string("Hello!"))
                ]
            ))
        );

        assert_eq!(
            from("Foo (  true, 1234 ,\t\n\t \"Hello!\" )"),
            Ok(Value::unnamed_variant(
                "Foo",
                vec![Value::bool(true), Value::u128(1234), Value::string("Hello!")]
            ))
        );

        assert_eq!(from("Foo()"), Ok(Value::unnamed_variant("Foo", [])));
        assert_eq!(from("Foo{}"), Ok(Value::named_variant::<_, String, _>("Foo", [])));
        assert_eq!(from("Foo( \t)"), Ok(Value::unnamed_variant("Foo", [])));
        assert_eq!(from("Foo{  }"), Ok(Value::named_variant::<_, String, _>("Foo", [])));

        // Parsing special "v" strings:
        assert_eq!(
            from("v\"variant name\" {  }"),
            Ok(Value::named_variant::<_, String, _>("variant name", []))
        );
    }

    #[test]
    fn parse_bit_sequences() {
        use scale_bits::bits;
        assert_eq!(
            from("<011010110101101>"),
            Ok(Value::bit_sequence(bits![0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1]))
        );
        assert_eq!(from("<01101>"), Ok(Value::bit_sequence(bits![0, 1, 1, 0, 1])));
        assert_eq!(from("<0>"), Ok(Value::bit_sequence(bits![0])));
        assert_eq!(from("<>"), Ok(Value::bit_sequence(bits![])));
    }

    #[test]
    fn custom_parsers() {
        let custom_parser = FromStrBuilder::new()
            // We add the ability to parse custom hex strings:
            .add_custom_parser(|s| {
                let mut toks = s.into_tokens();

                // Return None if this clearly isn't hex.
                if !toks.tokens("0x".chars()) {
                    return None;
                }

                let from = toks.location();
                let num_hex_chars = toks.skip_tokens_while(|c| {
                    c.is_numeric()
                        || ['a', 'b', 'c', 'd', 'e', 'f'].contains(&c.to_ascii_lowercase())
                });

                // Return an error if is _looks_ like hex but something isn't right about it.
                if num_hex_chars % 2 != 0 {
                    let e = ParseErrorKind::custom("Wrong number hex")
                        .between(from.offset(), toks.offset());
                    return Some(Err(e));
                }

                // For testing, we just dump the hex chars into a string.
                let hex: String = toks.slice(from, toks.location()).as_iter().collect();
                // Since we parsed stuff, we need to update the cursor to consume what we parsed.
                *s = toks.remaining();

                Some(Ok(Value::string(hex)))
            });

        let expected = [
            // Hex can be parsed as a part of values now!
            (
                "(1, 0x1234, true)",
                (
                    Ok(Value::unnamed_composite([
                        Value::u128(1),
                        Value::string("1234"),
                        Value::bool(true),
                    ])),
                    "",
                ),
            ),
            // Invalid hex emits the expected custom error:
            (
                "0x12345zzz",
                (Err(ParseErrorKind::custom("Wrong number hex").between(2, 7)), "0x12345zzz"),
            ),
            // Custom error locations are relative to the entire string:
            (
                "(true, 0x12345)",
                (Err(ParseErrorKind::custom("Wrong number hex").between(9, 14)), ", 0x12345)"),
            ),
        ];

        for (s, v) in expected {
            let (expected_res, expected_leftover) = (v.0.map_err(E), v.1);
            let (res, leftover) = custom_parser.parse(s);
            assert_eq!(res.map_err(E), expected_res, "result isn't what we expected for: {s}");
            assert_eq!(leftover, expected_leftover, "wrong number of leftover bytes for: {s}");
        }
    }
}