1
#![allow(clippy::identity_op)]
2

            
3
use alloc::{
4
    format,
5
    string::{String, ToString},
6
    vec::Vec,
7
};
8
use core::{
9
    char::from_u32 as char_from_u32,
10
    str::{self, from_utf8, FromStr, Utf8Error},
11
};
12

            
13
use unicode_ident::{is_xid_continue, is_xid_start};
14

            
15
use crate::{
16
    error::{Error, Position, Result, Span, SpannedError, SpannedResult},
17
    extensions::Extensions,
18
    value::Number,
19
};
20

            
21
2435055
const fn is_int_char(c: char) -> bool {
22
2435055
    c.is_ascii_hexdigit() || c == '_'
23
2435055
}
24

            
25
1336538
const fn is_float_char(c: char) -> bool {
26
1336538
    c.is_ascii_digit() || matches!(c, 'e' | 'E' | '.' | '+' | '-' | '_')
27
1336538
}
28

            
29
871793
pub fn is_ident_first_char(c: char) -> bool {
30
871793
    c == '_' || is_xid_start(c)
31
871793
}
32

            
33
4255414
pub fn is_ident_raw_char(c: char) -> bool {
34
4255414
    matches!(c, '.' | '+' | '-') | is_xid_continue(c)
35
4255414
}
36

            
37
5497764
pub const fn is_whitespace_char(c: char) -> bool {
38
3259426
    matches!(
39
5497764
        c,
40
        ' ' | '\t'
41
            | '\n'
42
            | '\r'
43
            | '\x0B'
44
            | '\x0C'
45
            | '\u{85}'
46
            | '\u{200E}'
47
            | '\u{200F}'
48
            | '\u{2028}'
49
            | '\u{2029}'
50
    )
51
5497764
}
52

            
53
#[cfg(feature = "integer128")]
54
pub(crate) type LargeUInt = u128;
55
#[cfg(not(feature = "integer128"))]
56
pub(crate) type LargeUInt = u64;
57
#[cfg(feature = "integer128")]
58
pub(crate) type LargeSInt = i128;
59
#[cfg(not(feature = "integer128"))]
60
pub(crate) type LargeSInt = i64;
61

            
62
pub struct Parser<'a> {
63
    /// Bits set according to the [`Extensions`] enum.
64
    pub exts: Extensions,
65
    src: &'a str,
66
    cursor: ParserCursor,
67
    prev_cursor: ParserCursor,
68
}
69

            
70
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
71
pub struct ParserCursor {
72
    cursor: usize,
73
    pre_ws_cursor: usize,
74
    last_ws_len: usize,
75
}
76

            
77
const WS_CURSOR_UNCLOSED_LINE: usize = usize::MAX;
78

            
79
impl PartialEq for ParserCursor {
80
8
    fn eq(&self, other: &Self) -> bool {
81
8
        self.cursor == other.cursor
82
8
    }
83
}
84

            
85
impl PartialOrd for ParserCursor {
86
3388
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
87
3388
        self.cursor.partial_cmp(&other.cursor)
88
3388
    }
89
}
90

            
91
/// constructor and parsing utilities
92
impl<'a> Parser<'a> {
93
544052
    pub fn new(src: &'a str) -> SpannedResult<Self> {
94
544052
        let mut parser = Parser {
95
544052
            exts: Extensions::empty(),
96
544052
            src,
97
544052
            cursor: ParserCursor {
98
544052
                cursor: 0,
99
544052
                pre_ws_cursor: 0,
100
544052
                last_ws_len: 0,
101
544052
            },
102
544052
            prev_cursor: ParserCursor {
103
544052
                cursor: 0,
104
544052
                pre_ws_cursor: 0,
105
544052
                last_ws_len: 0,
106
544052
            },
107
544052
        };
108

            
109
544052
        parser.skip_ws().map_err(|e| parser.span_error(e))?;
110

            
111
        // Loop over all extensions attributes
112
        loop {
113
578106
            let attribute = parser.extensions().map_err(|e| parser.span_error(e))?;
114

            
115
577576
            if attribute.is_empty() {
116
543244
                break;
117
34332
            }
118

            
119
34332
            parser.exts |= attribute;
120
34332
            parser.skip_ws().map_err(|e| parser.span_error(e))?;
121
        }
122

            
123
543244
        Ok(parser)
124
544052
    }
125

            
126
184573
    fn set_cursor(&mut self, cursor: ParserCursor) {
127
184573
        self.cursor = cursor;
128
184573
    }
129

            
130
110728
    pub fn span_error(&self, code: Error) -> SpannedError {
131
110728
        SpannedError {
132
110728
            code,
133
110728
            span: Span {
134
110728
                start: Position::from_src_end(&self.src[..self.prev_cursor.cursor]),
135
110728
                end: Position::from_src_end(&self.src[..self.cursor.cursor]),
136
110728
            },
137
110728
        }
138
110728
    }
139

            
140
6352893
    pub fn advance_bytes(&mut self, bytes: usize) {
141
6352893
        self.prev_cursor = self.cursor;
142
6352893
        self.cursor.cursor += bytes;
143
6352893
    }
144

            
145
966069
    pub fn next_char(&mut self) -> Result<char> {
146
966069
        let c = self.peek_char_or_eof()?;
147
965776
        self.cursor.cursor += c.len_utf8();
148
965776
        Ok(c)
149
966069
    }
150

            
151
38834
    pub fn skip_next_char(&mut self) {
152
38834
        core::mem::drop(self.next_char());
153
38834
    }
154

            
155
2969364
    pub fn peek_char(&self) -> Option<char> {
156
2969364
        self.src().chars().next()
157
2969364
    }
158

            
159
2219644
    pub fn peek_char_or_eof(&self) -> Result<char> {
160
2219644
        self.peek_char().ok_or(Error::Eof)
161
2219644
    }
162

            
163
6555654
    pub fn check_char(&self, c: char) -> bool {
164
6555654
        self.src().starts_with(c)
165
6555654
    }
166

            
167
13446086
    pub fn check_str(&self, s: &str) -> bool {
168
13446086
        self.src().starts_with(s)
169
13446086
    }
170

            
171
40285409
    pub fn src(&self) -> &'a str {
172
40285409
        &self.src[self.cursor.cursor..]
173
40285409
    }
174

            
175
25894
    pub fn pre_ws_src(&self) -> &'a str {
176
25894
        &self.src[self.cursor.pre_ws_cursor..]
177
25894
    }
178

            
179
1745962
    pub fn consume_str(&mut self, s: &str) -> bool {
180
1745962
        if self.check_str(s) {
181
519361
            self.advance_bytes(s.len());
182

            
183
519361
            true
184
        } else {
185
1226601
            false
186
        }
187
1745962
    }
188

            
189
5058538
    pub fn consume_char(&mut self, c: char) -> bool {
190
5058538
        if self.check_char(c) {
191
1535846
            self.advance_bytes(c.len_utf8());
192

            
193
1535846
            true
194
        } else {
195
3522692
            false
196
        }
197
5058538
    }
198

            
199
69209
    fn consume_all(&mut self, all: &[&str]) -> Result<bool> {
200
69209
        all.iter()
201
243004
            .map(|elem| {
202
243004
                if self.consume_str(elem) {
203
242941
                    self.skip_ws()?;
204

            
205
242941
                    Ok(true)
206
                } else {
207
63
                    Ok(false)
208
                }
209
243004
            })
210
243004
            .try_fold(true, |acc, x| x.map(|x| x && acc))
211
69209
    }
212

            
213
145653
    pub fn expect_char(&mut self, expected: char, error: Error) -> Result<()> {
214
145653
        if self.consume_char(expected) {
215
126422
            Ok(())
216
        } else {
217
19231
            Err(error)
218
        }
219
145653
    }
220

            
221
    #[must_use]
222
4136839
    pub fn next_chars_while_len(&self, condition: fn(char) -> bool) -> usize {
223
4136839
        self.next_chars_while_from_len(0, condition)
224
4136839
    }
225

            
226
    #[must_use]
227
5169970
    pub fn next_chars_while_from_len(&self, from: usize, condition: fn(char) -> bool) -> usize {
228
5169970
        self.src()[from..]
229
13658285
            .find(|c| !condition(c))
230
5169970
            .unwrap_or(self.src().len() - from)
231
5169970
    }
232
}
233

            
234
/// actual parsing of ron tokens
235
impl<'a> Parser<'a> {
236
218795
    fn parse_integer_digits<T: Num>(
237
218795
        &mut self,
238
218795
        s: &str,
239
218795
        base: u8,
240
218795
        f: fn(&mut T, u8) -> bool,
241
218795
    ) -> Result<T> {
242
218795
        let mut num_acc = T::from_u8(0);
243

            
244
531640
        for (i, c) in s.char_indices() {
245
531640
            if c == '_' {
246
6538
                continue;
247
525102
            }
248

            
249
525102
            if num_acc.checked_mul_ext(base) {
250
842
                self.advance_bytes(s.len());
251
842
                return Err(Error::IntegerOutOfBounds);
252
524260
            }
253

            
254
524260
            let digit = Self::decode_hex(c)?;
255

            
256
524260
            if digit >= base {
257
1946
                self.advance_bytes(i);
258
1946
                return Err(Error::InvalidIntegerDigit { digit: c, base });
259
522314
            }
260

            
261
522314
            if f(&mut num_acc, digit) {
262
3197
                self.advance_bytes(s.len());
263
3197
                return Err(Error::IntegerOutOfBounds);
264
519117
            }
265
        }
266

            
267
212810
        self.advance_bytes(s.len());
268

            
269
212810
        Ok(num_acc)
270
218795
    }
271

            
272
225781
    fn parse_integer<T: Num>(&mut self, sign: i8) -> Result<T> {
273
225781
        let base = match () {
274
225781
            () if self.consume_str("0b") => 2,
275
223279
            () if self.consume_str("0o") => 8,
276
221055
            () if self.consume_str("0x") => 16,
277
218553
            () => 10,
278
        };
279

            
280
225781
        let num_bytes = self.next_chars_while_len(is_int_char);
281

            
282
225781
        if num_bytes == 0 {
283
4484
            return Err(Error::ExpectedInteger);
284
221297
        }
285

            
286
221297
        if self.check_char('_') {
287
2502
            return Err(Error::UnderscoreAtBeginning);
288
218795
        }
289

            
290
218795
        let s = &self.src()[..num_bytes];
291

            
292
218795
        if sign > 0 {
293
204481
            self.parse_integer_digits(s, base, T::checked_add_ext)
294
        } else {
295
14314
            self.parse_integer_digits(s, base, T::checked_sub_ext)
296
        }
297
225781
    }
298

            
299
    #[allow(clippy::too_many_lines)]
300
322367
    pub fn integer<T: Integer>(&mut self) -> Result<T> {
301
322367
        let src_backup = self.src();
302

            
303
322367
        let is_negative = match self.peek_char_or_eof()? {
304
            '+' => {
305
28
                self.skip_next_char();
306
28
                false
307
            }
308
            '-' => {
309
4959
                self.skip_next_char();
310
4959
                true
311
            }
312
215176
            'b' if self.consume_str("b'") => {
313
                // Parse a byte literal
314
215176
                let byte = match self.next_char()? {
315
188762
                    '\\' => match self.parse_escape(EscapeEncoding::Binary, true)? {
316
                        // we know that this byte is an ASCII character
317
188484
                        EscapeCharacter::Ascii(b) => b,
318
                        EscapeCharacter::Utf8(_) => {
319
278
                            return Err(Error::InvalidEscape(
320
278
                                "Unexpected Unicode escape in byte literal",
321
278
                            ))
322
                        }
323
                    },
324
26414
                    b if b.is_ascii() => b as u8,
325
278
                    _ => return Err(Error::ExpectedByteLiteral),
326
                };
327

            
328
214620
                if !self.consume_char('\'') {
329
278
                    return Err(Error::ExpectedByteLiteral);
330
214342
                }
331

            
332
214342
                let bytes_ron = &src_backup[..src_backup.len() - self.src().len()];
333

            
334
214342
                return T::try_from_parsed_integer(ParsedInteger::U8(byte), bytes_ron);
335
            }
336
102204
            _ => false,
337
        };
338
107191
        let sign = if is_negative { -1 } else { 1 };
339

            
340
107191
        let num_bytes = self.next_chars_while_len(is_int_char);
341

            
342
107191
        if self.src()[num_bytes..].starts_with(['i', 'u']) {
343
11939
            let int_cursor = self.cursor;
344
11939
            self.advance_bytes(num_bytes);
345

            
346
            #[allow(clippy::never_loop)]
347
            loop {
348
11939
                let (res, suffix_bytes) = if self.consume_ident("i8") {
349
874
                    let suffix_bytes = self.src();
350
874
                    self.set_cursor(int_cursor);
351
874
                    (
352
874
                        self.parse_integer::<i8>(sign).map(ParsedInteger::I8),
353
874
                        suffix_bytes,
354
874
                    )
355
11065
                } else if self.consume_ident("i16") {
356
874
                    let suffix_bytes = self.src();
357
874
                    self.set_cursor(int_cursor);
358
874
                    (
359
874
                        self.parse_integer::<i16>(sign).map(ParsedInteger::I16),
360
874
                        suffix_bytes,
361
874
                    )
362
10191
                } else if self.consume_ident("i32") {
363
1156
                    let suffix_bytes = self.src();
364
1156
                    self.set_cursor(int_cursor);
365
1156
                    (
366
1156
                        self.parse_integer::<i32>(sign).map(ParsedInteger::I32),
367
1156
                        suffix_bytes,
368
1156
                    )
369
9035
                } else if self.consume_ident("i64") {
370
874
                    let suffix_bytes = self.src();
371
874
                    self.set_cursor(int_cursor);
372
874
                    (
373
874
                        self.parse_integer::<i64>(sign).map(ParsedInteger::I64),
374
874
                        suffix_bytes,
375
874
                    )
376
8161
                } else if self.consume_ident("u8") {
377
2260
                    let suffix_bytes = self.src();
378
2260
                    self.set_cursor(int_cursor);
379
2260
                    (
380
2260
                        self.parse_integer::<u8>(sign).map(ParsedInteger::U8),
381
2260
                        suffix_bytes,
382
2260
                    )
383
5901
                } else if self.consume_ident("u16") {
384
1156
                    let suffix_bytes = self.src();
385
1156
                    self.set_cursor(int_cursor);
386
1156
                    (
387
1156
                        self.parse_integer::<u16>(sign).map(ParsedInteger::U16),
388
1156
                        suffix_bytes,
389
1156
                    )
390
4745
                } else if self.consume_ident("u32") {
391
1156
                    let suffix_bytes = self.src();
392
1156
                    self.set_cursor(int_cursor);
393
1156
                    (
394
1156
                        self.parse_integer::<u32>(sign).map(ParsedInteger::U32),
395
1156
                        suffix_bytes,
396
1156
                    )
397
3589
                } else if self.consume_ident("u64") {
398
1156
                    let suffix_bytes = self.src();
399
1156
                    self.set_cursor(int_cursor);
400
1156
                    (
401
1156
                        self.parse_integer::<u64>(sign).map(ParsedInteger::U64),
402
1156
                        suffix_bytes,
403
1156
                    )
404
                } else {
405
                    #[cfg(feature = "integer128")]
406
1585
                    if self.consume_ident("i128") {
407
439
                        let suffix_bytes = self.src();
408
439
                        self.set_cursor(int_cursor);
409
439
                        (
410
439
                            self.parse_integer::<i128>(sign).map(ParsedInteger::I128),
411
439
                            suffix_bytes,
412
439
                        )
413
1146
                    } else if self.consume_ident("u128") {
414
580
                        let suffix_bytes = self.src();
415
580
                        self.set_cursor(int_cursor);
416
580
                        (
417
580
                            self.parse_integer::<u128>(sign).map(ParsedInteger::U128),
418
580
                            suffix_bytes,
419
580
                        )
420
                    } else {
421
566
                        break;
422
                    }
423
                    #[cfg(not(feature = "integer128"))]
424
                    {
425
848
                        break;
426
                    }
427
                };
428

            
429
10243
                if !matches!(
430
1829
                    &res,
431
                    Err(Error::UnderscoreAtBeginning | Error::InvalidIntegerDigit { .. })
432
10243
                ) {
433
10243
                    // Advance past the number suffix
434
10243
                    self.skip_identifier();
435
10243
                }
436

            
437
10525
                let integer_ron = &src_backup[..src_backup.len() - suffix_bytes.len()];
438

            
439
10525
                return res.and_then(|parsed| T::try_from_parsed_integer(parsed, integer_ron));
440
            }
441

            
442
1414
            self.set_cursor(int_cursor);
443
95252
        }
444

            
445
96666
        T::parse(self, sign)
446
322367
    }
447

            
448
307553
    pub fn any_number(&mut self) -> Result<Number> {
449
307553
        if self.next_bytes_is_float() {
450
10914
            return match self.float::<ParsedFloat>()? {
451
3384
                ParsedFloat::F32(v) => Ok(Number::F32(v.into())),
452
7530
                ParsedFloat::F64(v) => Ok(Number::F64(v.into())),
453
            };
454
296639
        }
455

            
456
296639
        let backup_cursor = self.cursor;
457

            
458
296639
        let (integer_err, integer_cursor) = match self.integer::<ParsedInteger>() {
459
293259
            Ok(integer) => {
460
293259
                return match integer {
461
846
                    ParsedInteger::I8(v) => Ok(Number::I8(v)),
462
560
                    ParsedInteger::I16(v) => Ok(Number::I16(v)),
463
560
                    ParsedInteger::I32(v) => Ok(Number::I32(v)),
464
560
                    ParsedInteger::I64(v) => Ok(Number::I64(v)),
465
                    #[cfg(feature = "integer128")]
466
558
                    ParsedInteger::I128(v) => Ok(Number::I128(v)),
467
287655
                    ParsedInteger::U8(v) => Ok(Number::U8(v)),
468
564
                    ParsedInteger::U16(v) => Ok(Number::U16(v)),
469
560
                    ParsedInteger::U32(v) => Ok(Number::U32(v)),
470
560
                    ParsedInteger::U64(v) => Ok(Number::U64(v)),
471
                    #[cfg(feature = "integer128")]
472
836
                    ParsedInteger::U128(v) => Ok(Number::U128(v)),
473
                }
474
            }
475
3380
            Err(err) => (err, self.cursor),
476
        };
477

            
478
3380
        self.set_cursor(backup_cursor);
479

            
480
        // Fall-back to parse an out-of-range integer as a float
481
3380
        match self.float::<ParsedFloat>() {
482
2816
            Ok(ParsedFloat::F32(v)) if self.cursor >= integer_cursor => Ok(Number::F32(v.into())),
483
564
            Ok(ParsedFloat::F64(v)) if self.cursor >= integer_cursor => Ok(Number::F64(v.into())),
484
            _ => {
485
                // Return the more precise integer error
486
1251
                self.set_cursor(integer_cursor);
487
1251
                Err(integer_err)
488
            }
489
        }
490
307553
    }
491

            
492
31008
    pub fn bool(&mut self) -> Result<bool> {
493
31008
        if self.consume_ident("true") {
494
17306
            Ok(true)
495
13702
        } else if self.consume_ident("false") {
496
13666
            Ok(false)
497
        } else {
498
36
            Err(Error::ExpectedBoolean)
499
        }
500
31008
    }
501

            
502
67815
    pub fn char(&mut self) -> Result<char> {
503
67815
        self.expect_char('\'', Error::ExpectedChar)?;
504

            
505
49144
        let c = self.next_char()?;
506

            
507
49144
        let c = if c == '\\' {
508
3626
            match self.parse_escape(EscapeEncoding::Utf8, true)? {
509
                // we know that this byte is an ASCII character
510
1680
                EscapeCharacter::Ascii(b) => char::from(b),
511
1112
                EscapeCharacter::Utf8(c) => c,
512
            }
513
        } else {
514
45518
            c
515
        };
516

            
517
48310
        self.expect_char('\'', Error::ExpectedChar)?;
518

            
519
48310
        Ok(c)
520
67815
    }
521

            
522
415805
    pub fn comma(&mut self) -> Result<bool> {
523
415805
        self.skip_ws()?;
524

            
525
415805
        if self.consume_char(',') {
526
240843
            self.skip_ws()?;
527

            
528
240843
            Ok(true)
529
        } else {
530
174962
            Ok(false)
531
        }
532
415805
    }
533

            
534
    /// Only returns true if the char after `ident` cannot belong
535
    /// to an identifier.
536
5712538
    pub fn check_ident(&mut self, ident: &str) -> bool {
537
5712538
        self.check_str(ident) && !self.check_ident_other_char(ident.len())
538
5712538
    }
539

            
540
247239
    fn check_ident_other_char(&self, index: usize) -> bool {
541
247239
        self.src()[index..]
542
247239
            .chars()
543
247239
            .next()
544
247239
            .map_or(false, is_xid_continue)
545
247239
    }
546

            
547
    /// Check which type of struct we are currently parsing. The parsing state
548
    ///  is only changed in case of an error, to provide a better position.
549
    ///
550
    /// [`NewtypeMode::NoParensMeanUnit`] detects (tuple) structs by a leading
551
    ///  opening bracket and reports a unit struct otherwise.
552
    /// [`NewtypeMode::InsideNewtype`] skips an initial check for unit structs,
553
    ///  and means that any leading opening bracket is not considered to open
554
    ///  a (tuple) struct but to be part of the structs inner contents.
555
    ///
556
    /// [`TupleMode::ImpreciseTupleOrNewtype`] only performs a cheap, O(1),
557
    ///  single-identifier lookahead check to distinguish tuple structs from
558
    ///  non-tuple structs.
559
    /// [`TupleMode::DifferentiateNewtype`] performs an expensive, O(N), look-
560
    ///  ahead over the entire next value tree, which can span the entirety of
561
    ///  the remaining document in the worst case.
562
86120
    pub fn check_struct_type(
563
86120
        &mut self,
564
86120
        newtype: NewtypeMode,
565
86120
        tuple: TupleMode,
566
86120
    ) -> Result<StructType> {
567
86120
        fn check_struct_type_inner(
568
86120
            parser: &mut Parser,
569
86120
            newtype: NewtypeMode,
570
86120
            tuple: TupleMode,
571
86120
        ) -> Result<StructType> {
572
86120
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && !parser.consume_char('(') {
573
12236
                return Ok(StructType::Unit);
574
73884
            }
575

            
576
73884
            parser.skip_ws()?;
577

            
578
            // Check for `Ident()`, which could be
579
            // - a zero-field struct or tuple (variant)
580
            // - an unwrapped newtype around a unit
581
73880
            if matches!(newtype, NewtypeMode::NoParensMeanUnit) && parser.check_char(')') {
582
834
                return Ok(StructType::EmptyTuple);
583
73046
            }
584

            
585
73046
            if parser.skip_identifier().is_some() {
586
54382
                parser.skip_ws()?;
587

            
588
54382
                match parser.peek_char() {
589
                    // Definitely a struct with named fields
590
48536
                    Some(':') => return Ok(StructType::Named),
591
                    // Definitely a tuple-like struct with fields
592
                    Some(',') => {
593
4178
                        parser.skip_next_char();
594
4178
                        parser.skip_ws()?;
595
4178
                        if parser.check_char(')') {
596
                            // A one-element tuple could be a newtype
597
                            return Ok(StructType::NewtypeTuple);
598
4178
                        }
599
                        // Definitely a tuple struct with more than one field
600
4178
                        return Ok(StructType::NonNewtypeTuple);
601
                    }
602
                    // Either a newtype or a tuple struct
603
1112
                    Some(')') => return Ok(StructType::NewtypeTuple),
604
                    // Something else, let's investigate further
605
556
                    Some(_) | None => (),
606
                };
607
18664
            }
608

            
609
19220
            if matches!(tuple, TupleMode::ImpreciseTupleOrNewtype) {
610
13089
                return Ok(StructType::AnyTuple);
611
6131
            }
612

            
613
6131
            let mut braces = 1_usize;
614
6131
            let mut more_than_one = false;
615

            
616
            // Skip ahead to see if the value is followed by another value
617
24231
            while braces > 0 {
618
                // Skip spurious braces in comments, strings, and characters
619
18671
                parser.skip_ws()?;
620
18671
                let cursor_backup = parser.cursor;
621
18671
                if parser.char().is_err() {
622
18671
                    parser.set_cursor(cursor_backup);
623
18671
                }
624
18671
                let cursor_backup = parser.cursor;
625
18671
                match parser.string() {
626
1112
                    Ok(_) => (),
627
                    // prevent quadratic complexity backtracking for unterminated string
628
                    Err(err @ (Error::ExpectedStringEnd | Error::Eof)) => return Err(err),
629
17559
                    Err(_) => parser.set_cursor(cursor_backup),
630
                }
631
18671
                let cursor_backup = parser.cursor;
632
                // we have already checked for strings, which subsume base64 byte strings
633
18671
                match parser.byte_string_no_base64() {
634
834
                    Ok(_) => (),
635
                    // prevent quadratic complexity backtracking for unterminated byte string
636
                    Err(err @ (Error::ExpectedStringEnd | Error::Eof)) => return Err(err),
637
17837
                    Err(_) => parser.set_cursor(cursor_backup),
638
                }
639

            
640
18671
                let c = parser.next_char()?;
641
18656
                if matches!(c, '(' | '[' | '{') {
642
1405
                    braces += 1;
643
17251
                } else if matches!(c, ')' | ']' | '}') {
644
6965
                    braces -= 1;
645
10301
                } else if c == ',' && braces == 1 {
646
556
                    parser.skip_ws()?;
647
556
                    more_than_one = !parser.check_char(')');
648
556
                    break;
649
9730
                }
650
            }
651

            
652
6116
            if more_than_one {
653
278
                Ok(StructType::NonNewtypeTuple)
654
            } else {
655
5838
                Ok(StructType::NewtypeTuple)
656
            }
657
86120
        }
658

            
659
        // Create a temporary working copy
660
86120
        let backup_cursor = self.cursor;
661

            
662
86120
        let result = check_struct_type_inner(self, newtype, tuple);
663

            
664
86120
        if result.is_ok() {
665
86101
            // Revert the parser to before the struct type check
666
86101
            self.set_cursor(backup_cursor);
667
86101
        }
668

            
669
86120
        result
670
86120
    }
671

            
672
    /// Only returns true if the char after `ident` cannot belong
673
    /// to an identifier.
674
5116033
    pub fn consume_ident(&mut self, ident: &str) -> bool {
675
5116033
        if self.check_ident(ident) {
676
115786
            self.advance_bytes(ident.len());
677

            
678
115786
            true
679
        } else {
680
5000247
            false
681
        }
682
5116033
    }
683

            
684
81284
    pub fn consume_struct_name(&mut self, ident: &'static str) -> Result<bool> {
685
81284
        if self.check_ident("") {
686
62329
            if self.exts.contains(Extensions::EXPLICIT_STRUCT_NAMES) {
687
834
                return Err(Error::ExpectedStructName(ident.to_string()));
688
61495
            }
689

            
690
61495
            return Ok(false);
691
18955
        }
692

            
693
18955
        let found_ident = match self.identifier() {
694
17009
            Ok(maybe_ident) => maybe_ident,
695
1390
            Err(Error::SuggestRawIdentifier(found_ident)) if found_ident == ident => {
696
278
                return Err(Error::SuggestRawIdentifier(found_ident))
697
            }
698
1668
            Err(_) => return Err(Error::ExpectedNamedStructLike(ident)),
699
        };
700

            
701
17009
        if ident.is_empty() {
702
308
            return Err(Error::ExpectedNamedStructLike(ident));
703
16701
        }
704

            
705
16701
        if found_ident != ident {
706
1680
            return Err(Error::ExpectedDifferentStructName {
707
1680
                expected: ident,
708
1680
                found: String::from(found_ident),
709
1680
            });
710
15021
        }
711

            
712
15021
        Ok(true)
713
81284
    }
714

            
715
    /// Returns the extensions bit mask.
716
578106
    fn extensions(&mut self) -> Result<Extensions> {
717
578106
        if !self.check_char('#') {
718
543244
            return Ok(Extensions::empty());
719
34862
        }
720

            
721
34862
        if !self.consume_all(&["#", "!", "[", "enable", "("])? {
722
12
            return Err(Error::ExpectedAttribute);
723
34850
        }
724

            
725
34850
        self.skip_ws()?;
726
34850
        let mut extensions = Extensions::empty();
727

            
728
        loop {
729
35128
            let ident = self.identifier()?;
730
35128
            let extension = Extensions::from_ident(ident)
731
35128
                .ok_or_else(|| Error::NoSuchExtension(ident.into()))?;
732

            
733
35113
            extensions |= extension;
734

            
735
35113
            let comma = self.comma()?;
736

            
737
            // If we have no comma but another item, return an error
738
35113
            if !comma && self.check_ident_other_char(0) {
739
488
                return Err(Error::ExpectedComma);
740
34625
            }
741

            
742
            // If there's no comma, assume the list ended.
743
            // If there is, it might be a trailing one, thus we only
744
            // continue the loop if we get an ident char.
745
34625
            if !comma || !self.check_ident_other_char(0) {
746
34347
                break;
747
278
            }
748
        }
749

            
750
34347
        self.skip_ws()?;
751

            
752
34347
        if self.consume_all(&[")", "]"])? {
753
34332
            Ok(extensions)
754
        } else {
755
15
            Err(Error::ExpectedAttributeEnd)
756
        }
757
578106
    }
758

            
759
15155
    pub fn float<T: Float>(&mut self) -> Result<T> {
760
        const F32_SUFFIX: &str = "f32";
761
        const F64_SUFFIX: &str = "f64";
762

            
763
102881
        for (literal, value_f32, value_f64) in &[
764
102881
            ("inf", f32::INFINITY, f64::INFINITY),
765
102881
            ("+inf", f32::INFINITY, f64::INFINITY),
766
102881
            ("-inf", f32::NEG_INFINITY, f64::NEG_INFINITY),
767
102881
            ("NaN", f32::NAN, f64::NAN),
768
102881
            ("+NaN", f32::NAN, f64::NAN),
769
102881
            ("-NaN", -f32::NAN, -f64::NAN),
770
102881
        ] {
771
88958
            if self.consume_ident(literal) {
772
88
                return T::parse(literal);
773
88870
            }
774

            
775
88870
            if let Some(suffix) = self.src().strip_prefix(literal) {
776
1156
                if let Some(post_suffix) = suffix.strip_prefix(F32_SUFFIX) {
777
576
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
778
572
                        let float_ron = &self.src()[..literal.len() + F32_SUFFIX.len()];
779
572
                        self.advance_bytes(literal.len() + F32_SUFFIX.len());
780
572
                        return T::try_from_parsed_float(ParsedFloat::F32(*value_f32), float_ron);
781
4
                    }
782
580
                }
783

            
784
584
                if let Some(post_suffix) = suffix.strip_prefix(F64_SUFFIX) {
785
576
                    if !post_suffix.chars().next().map_or(false, is_xid_continue) {
786
572
                        let float_ron = &self.src()[..literal.len() + F64_SUFFIX.len()];
787
572
                        self.advance_bytes(literal.len() + F64_SUFFIX.len());
788
572
                        return T::try_from_parsed_float(ParsedFloat::F64(*value_f64), float_ron);
789
4
                    }
790
8
                }
791
87714
            }
792
        }
793

            
794
13923
        let num_bytes = self.next_chars_while_len(is_float_char);
795

            
796
13923
        if num_bytes == 0 {
797
46
            return Err(Error::ExpectedFloat);
798
13877
        }
799

            
800
13877
        if self.check_char('_') {
801
4
            return Err(Error::UnderscoreAtBeginning);
802
13873
        }
803

            
804
13873
        let mut f = String::with_capacity(num_bytes);
805
13873
        let mut allow_underscore = false;
806

            
807
251457
        for (i, c) in self.src()[..num_bytes].char_indices() {
808
768
            match c {
809
760
                '_' if allow_underscore => continue,
810
                '_' => {
811
8
                    self.advance_bytes(i);
812
8
                    return Err(Error::FloatUnderscore);
813
                }
814
237111
                '0'..='9' | 'e' | 'E' => allow_underscore = true,
815
11369
                '.' => allow_underscore = false,
816
2209
                _ => (),
817
            }
818

            
819
            // we know that the byte is an ASCII character here
820
250689
            f.push(c);
821
        }
822

            
823
13865
        if self.src()[num_bytes..].starts_with('f') {
824
1982
            let backup_cursor = self.cursor;
825
1982
            self.advance_bytes(num_bytes);
826

            
827
            #[allow(clippy::never_loop)]
828
            loop {
829
1982
                let res = if self.consume_ident(F32_SUFFIX) {
830
1128
                    f32::from_str(&f).map(ParsedFloat::F32)
831
854
                } else if self.consume_ident(F64_SUFFIX) {
832
572
                    f64::from_str(&f).map(ParsedFloat::F64)
833
                } else {
834
282
                    break;
835
                };
836

            
837
1700
                let parsed = if let Ok(parsed) = res {
838
1692
                    parsed
839
                } else {
840
8
                    self.set_cursor(backup_cursor);
841
8
                    return Err(Error::ExpectedFloat);
842
                };
843

            
844
1692
                let float_ron = &self.src[backup_cursor.cursor..self.cursor.cursor];
845

            
846
1692
                return T::try_from_parsed_float(parsed, float_ron);
847
            }
848

            
849
282
            self.set_cursor(backup_cursor);
850
11883
        }
851

            
852
12165
        let value = T::parse(&f)?;
853

            
854
12145
        self.advance_bytes(num_bytes);
855

            
856
12145
        Ok(value)
857
15155
    }
858

            
859
599053
    pub fn skip_identifier(&mut self) -> Option<&'a str> {
860
        #[allow(clippy::nonminimal_bool)]
861
599053
        if self.check_str("b\"") // byte string
862
597655
            || self.check_str("b'") // byte literal
863
383317
            || self.check_str("br#") // raw byte string
864
382483
            || self.check_str("br\"") // raw byte string
865
381649
            || self.check_str("r\"") // raw string
866
381093
            || self.check_str("r#\"") // raw string
867
380815
            || self.check_str("r##") // raw string
868
380537
            || false
869
        {
870
218516
            return None;
871
380537
        }
872

            
873
380537
        if self.check_str("r#") {
874
            // maybe a raw identifier
875
12
            let len = self.next_chars_while_from_len(2, is_ident_raw_char);
876
12
            if len > 0 {
877
4
                let ident = &self.src()[2..2 + len];
878
4
                self.advance_bytes(2 + len);
879
4
                return Some(ident);
880
8
            }
881
8
            return None;
882
380525
        }
883

            
884
380525
        if let Some(c) = self.peek_char() {
885
            // maybe a normal identifier
886
379135
            if is_ident_first_char(c) {
887
114175
                let len =
888
114175
                    c.len_utf8() + self.next_chars_while_from_len(c.len_utf8(), is_xid_continue);
889
114175
                let ident = &self.src()[..len];
890
114175
                self.advance_bytes(len);
891
114175
                return Some(ident);
892
264960
            }
893
1390
        }
894

            
895
266350
        None
896
599053
    }
897

            
898
315832
    pub fn identifier(&mut self) -> Result<&'a str> {
899
315832
        let first = self.peek_char_or_eof()?;
900
315832
        if !is_ident_first_char(first) {
901
2236
            if is_ident_raw_char(first) {
902
1112
                let ident_bytes = self.next_chars_while_len(is_ident_raw_char);
903
1112
                return Err(Error::SuggestRawIdentifier(
904
1112
                    self.src()[..ident_bytes].into(),
905
1112
                ));
906
1124
            }
907

            
908
1124
            return Err(Error::ExpectedIdentifier);
909
313596
        }
910

            
911
        // If the next 2-3 bytes signify the start of a (raw) (byte) string
912
        //  literal, return an error.
913
        #[allow(clippy::nonminimal_bool)]
914
313596
        if self.check_str("b\"") // byte string
915
313318
            || self.check_str("b'") // byte literal
916
313040
            || self.check_str("br#") // raw byte string
917
312762
            || self.check_str("br\"") // raw byte string
918
312484
            || self.check_str("r\"") // raw string
919
312206
            || self.check_str("r#\"") // raw string
920
311928
            || self.check_str("r##") // raw string
921
311650
            || false
922
        {
923
1946
            return Err(Error::ExpectedIdentifier);
924
311650
        }
925

            
926
311650
        let length = if self.check_str("r#") {
927
7256
            let cursor_backup = self.cursor;
928

            
929
7256
            self.advance_bytes(2);
930

            
931
            // Note: it's important to check this before advancing forward, so that
932
            // the value-type deserializer can fall back to parsing it differently.
933
7256
            if !matches!(self.peek_char(), Some(c) if is_ident_raw_char(c)) {
934
556
                self.set_cursor(cursor_backup);
935
556
                return Err(Error::ExpectedIdentifier);
936
6700
            }
937

            
938
6700
            self.next_chars_while_len(is_ident_raw_char)
939
304394
        } else if first == 'r' {
940
556
            let std_ident_length = self.next_chars_while_len(is_xid_continue);
941
556
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
942

            
943
556
            if raw_ident_length > std_ident_length {
944
278
                return Err(Error::SuggestRawIdentifier(
945
278
                    self.src()[..raw_ident_length].into(),
946
278
                ));
947
278
            }
948

            
949
278
            std_ident_length
950
        } else {
951
303838
            let std_ident_length = first.len_utf8()
952
303838
                + self.next_chars_while_from_len(first.len_utf8(), is_xid_continue);
953
303838
            let raw_ident_length = self.next_chars_while_len(is_ident_raw_char);
954

            
955
303838
            if raw_ident_length > std_ident_length {
956
834
                return Err(Error::SuggestRawIdentifier(
957
834
                    self.src()[..raw_ident_length].into(),
958
834
                ));
959
303004
            }
960

            
961
303004
            std_ident_length
962
        };
963

            
964
309982
        let ident = &self.src()[..length];
965
309982
        self.advance_bytes(length);
966

            
967
309982
        Ok(ident)
968
315832
    }
969

            
970
307557
    pub fn next_bytes_is_float(&mut self) -> bool {
971
307557
        if let Some(c) = self.peek_char() {
972
307553
            let skip = match c {
973
5086
                '+' | '-' => 1,
974
302467
                _ => 0,
975
            };
976
307553
            let valid_float_len = self.next_chars_while_from_len(skip, is_float_char);
977
307553
            let valid_int_len = self.next_chars_while_from_len(skip, is_int_char);
978
307553
            valid_float_len > valid_int_len
979
        } else {
980
4
            false
981
        }
982
307557
    }
983

            
984
3685532
    pub fn skip_ws(&mut self) -> Result<()> {
985
3685532
        if (self.cursor.last_ws_len != WS_CURSOR_UNCLOSED_LINE)
986
3684972
            && ((self.cursor.pre_ws_cursor + self.cursor.last_ws_len) < self.cursor.cursor)
987
2388643
        {
988
2388643
            // the last whitespace is disjoint from this one, we need to track a new one
989
2388643
            self.cursor.pre_ws_cursor = self.cursor.cursor;
990
2388643
        }
991

            
992
3685532
        if self.src().is_empty() {
993
431366
            return Ok(());
994
3254166
        }
995

            
996
        loop {
997
3282256
            self.advance_bytes(self.next_chars_while_len(is_whitespace_char));
998

            
999
3282256
            match self.skip_comment()? {
3252212
                None => break,
                Some(Comment::UnclosedLine) => {
1116
                    self.cursor.last_ws_len = WS_CURSOR_UNCLOSED_LINE;
1116
                    return Ok(());
                }
28090
                Some(Comment::ClosedLine | Comment::Block) => continue,
            }
        }
3252212
        self.cursor.last_ws_len = self.cursor.cursor - self.cursor.pre_ws_cursor;
3252212
        Ok(())
3685532
    }
17792
    pub fn has_unclosed_line_comment(&self) -> bool {
17792
        self.src().is_empty() && self.cursor.last_ws_len == WS_CURSOR_UNCLOSED_LINE
17792
    }
10608
    pub fn byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
8
        fn expected_byte_string_found_base64(
8
            base64_str: &ParsedStr,
8
            byte_str: &ParsedByteStr,
8
        ) -> Error {
8
            let byte_str = match &byte_str {
8
                ParsedByteStr::Allocated(b) => b.as_slice(),
                ParsedByteStr::Slice(b) => b,
            }
8
            .iter()
80
            .flat_map(|c| core::ascii::escape_default(*c))
8
            .map(char::from)
8
            .collect::<String>();
8
            let base64_str = match &base64_str {
                ParsedStr::Allocated(s) => s.as_str(),
8
                ParsedStr::Slice(s) => s,
            };
8
            Error::InvalidValueForType {
8
                expected: format!("the Rusty byte string b\"{}\"", byte_str),
8
                found: format!("the ambiguous base64 string {:?}", base64_str),
8
            }
8
        }
10608
        if self.consume_char('"') {
1676
            let base64_str = self.escaped_string()?;
1676
            let base64_result = ParsedByteStr::try_from_base64(&base64_str);
1676
            if cfg!(not(test)) {
                // FIXME @juntyr: remove in v0.10
                #[allow(deprecated)]
1668
                base64_result.map_err(Error::Base64Error)
            } else {
8
                match base64_result {
                    // FIXME @juntyr: enable in v0.10
4
                    Ok(byte_str) => Err(expected_byte_string_found_base64(&base64_str, &byte_str)),
4
                    Err(_) => Err(Error::ExpectedByteString),
                }
            }
8932
        } else if self.consume_char('r') {
286
            let base64_str = self.raw_string()?;
286
            let base64_result = ParsedByteStr::try_from_base64(&base64_str);
286
            if cfg!(not(test)) {
                // FIXME @juntyr: remove in v0.10
                #[allow(deprecated)]
278
                base64_result.map_err(Error::Base64Error)
            } else {
8
                match base64_result {
                    // FIXME @juntyr: enable in v0.10
4
                    Ok(byte_str) => Err(expected_byte_string_found_base64(&base64_str, &byte_str)),
4
                    Err(_) => Err(Error::ExpectedByteString),
                }
            }
        } else {
8646
            self.byte_string_no_base64()
        }
10608
    }
27317
    pub fn byte_string_no_base64(&mut self) -> Result<ParsedByteStr<'a>> {
27317
        if self.consume_str("b\"") {
5866
            self.escaped_byte_string()
21451
        } else if self.consume_str("br") {
3614
            self.raw_byte_string()
        } else {
17837
            Err(Error::ExpectedByteString)
        }
27317
    }
5866
    fn escaped_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
5866
        match self.escaped_byte_buf(EscapeEncoding::Binary) {
5310
            Ok((bytes, advance)) => {
5310
                self.advance_bytes(advance);
5310
                Ok(bytes)
            }
556
            Err(err) => Err(err),
        }
5866
    }
3614
    fn raw_byte_string(&mut self) -> Result<ParsedByteStr<'a>> {
3614
        match self.raw_byte_buf() {
3058
            Ok((bytes, advance)) => {
3058
                self.advance_bytes(advance);
3058
                Ok(bytes)
            }
278
            Err(Error::ExpectedString) => Err(Error::ExpectedByteString),
278
            Err(err) => Err(err),
        }
3614
    }
106847
    pub fn string(&mut self) -> Result<ParsedStr<'a>> {
106847
        if self.consume_char('"') {
84498
            self.escaped_string()
22349
        } else if self.consume_char('r') {
3110
            self.raw_string()
        } else {
19239
            Err(Error::ExpectedString)
        }
106847
    }
86174
    fn escaped_string(&mut self) -> Result<ParsedStr<'a>> {
86174
        match self.escaped_byte_buf(EscapeEncoding::Utf8) {
84213
            Ok((bytes, advance)) => {
84213
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
84213
                self.advance_bytes(advance);
84213
                Ok(string)
            }
1961
            Err(err) => Err(err),
        }
86174
    }
3396
    fn raw_string(&mut self) -> Result<ParsedStr<'a>> {
3396
        match self.raw_byte_buf() {
2836
            Ok((bytes, advance)) => {
2836
                let string = ParsedStr::try_from_bytes(bytes).map_err(Error::from)?;
2836
                self.advance_bytes(advance);
2836
                Ok(string)
            }
560
            Err(err) => Err(err),
        }
3396
    }
92040
    fn escaped_byte_buf(&mut self, encoding: EscapeEncoding) -> Result<(ParsedByteStr<'a>, usize)> {
        // Checking for '"' and '\\' separately is faster than searching for both at the same time
92040
        let str_end = self.src().find('"').ok_or(Error::ExpectedStringEnd)?;
91469
        let escape = self.src()[..str_end].find('\\');
91469
        if let Some(escape) = escape {
            // Now check if escaping is used inside the string
10882
            let mut i = escape;
10882
            let mut s = self.src().as_bytes()[..i].to_vec();
            loop {
24028
                self.advance_bytes(i + 1);
24028
                match self.parse_escape(encoding, false)? {
10398
                    EscapeCharacter::Ascii(c) => s.push(c),
11684
                    EscapeCharacter::Utf8(c) => match c.len_utf8() {
11120
                        1 => s.push(c as u8),
564
                        len => {
564
                            let start = s.len();
564
                            s.extend(core::iter::repeat(0).take(len));
564
                            c.encode_utf8(&mut s[start..]);
564
                        }
                    },
                }
                // Checking for '"' and '\\' separately is faster than searching for both at the same time
22082
                let new_str_end = self.src().find('"').ok_or(Error::ExpectedStringEnd)?;
22082
                let new_escape = self.src()[..new_str_end].find('\\');
22082
                if let Some(new_escape) = new_escape {
13146
                    s.extend_from_slice(&self.src().as_bytes()[..new_escape]);
13146
                    i = new_escape;
13146
                } else {
8936
                    s.extend_from_slice(&self.src().as_bytes()[..new_str_end]);
                    // Advance to the end of the string + 1 for the `"`.
8936
                    break Ok((ParsedByteStr::Allocated(s), new_str_end + 1));
                }
            }
        } else {
80587
            let s = &self.src().as_bytes()[..str_end];
            // Advance by the number of bytes of the string + 1 for the `"`.
80587
            Ok((ParsedByteStr::Slice(s), str_end + 1))
        }
92040
    }
7010
    fn raw_byte_buf(&mut self) -> Result<(ParsedByteStr<'a>, usize)> {
13734
        let num_hashes = self.next_chars_while_len(|c| c == '#');
7010
        let hashes = &self.src()[..num_hashes];
7010
        self.advance_bytes(num_hashes);
7010
        self.expect_char('"', Error::ExpectedString)?;
6450
        let ending = ["\"", hashes].concat();
6450
        let i = self.src().find(&ending).ok_or(Error::ExpectedStringEnd)?;
5894
        let s = &self.src().as_bytes()[..i];
        // Advance by the number of bytes of the byte string
        // + `num_hashes` + 1 for the `"`.
5894
        Ok((ParsedByteStr::Slice(s), i + num_hashes + 1))
7010
    }
196948
    fn decode_ascii_escape(&mut self) -> Result<u8> {
196948
        let mut n = 0;
590288
        for _ in 0..2 {
393896
            n <<= 4;
393896
            let byte = self.next_char()?;
393896
            let decoded = Self::decode_hex(byte)?;
393340
            n |= decoded;
        }
196392
        Ok(n)
196948
    }
    #[inline]
937060
    fn decode_hex(c: char) -> Result<u8> {
937060
        if !c.is_ascii() {
278
            return Err(Error::InvalidEscape("Non-hex digit found"));
936782
        }
        // c is an ASCII character that can be losslessly cast to u8
936782
        match c as u8 {
936504
            c @ b'0'..=b'9' => Ok(c - b'0'),
110152
            c @ b'a'..=b'f' => Ok(10 + c - b'a'),
55322
            c @ b'A'..=b'F' => Ok(10 + c - b'A'),
278
            _ => Err(Error::InvalidEscape("Non-hex digit found")),
        }
937060
    }
216416
    fn parse_escape(&mut self, encoding: EscapeEncoding, is_char: bool) -> Result<EscapeCharacter> {
216416
        let c = match self.next_char()? {
846
            '\'' => EscapeCharacter::Ascii(b'\''),
3360
            '"' => EscapeCharacter::Ascii(b'"'),
2502
            '\\' => EscapeCharacter::Ascii(b'\\'),
1390
            'n' => EscapeCharacter::Ascii(b'\n'),
556
            'r' => EscapeCharacter::Ascii(b'\r'),
556
            't' => EscapeCharacter::Ascii(b'\t'),
1668
            '0' => EscapeCharacter::Ascii(b'\0'),
            'x' => {
                // Fast exit for ascii escape in byte string
193862
                let b: u8 = self.decode_ascii_escape()?;
193306
                if let EscapeEncoding::Binary = encoding {
189684
                    return Ok(EscapeCharacter::Ascii(b));
3622
                }
                // Fast exit for ascii character in UTF-8 string
3622
                let mut bytes = [b, 0, 0, 0];
3622
                if let Ok(Some(c)) = from_utf8(&bytes[..=0]).map(|s| s.chars().next()) {
1668
                    return Ok(EscapeCharacter::Utf8(c));
1954
                }
1954
                if is_char {
                    // Character literals are not allowed to use multiple byte
                    //  escapes to build a unicode character
278
                    return Err(Error::InvalidEscape(
278
                        "Not a valid byte-escaped Unicode character",
278
                    ));
1676
                }
                // UTF-8 character needs up to four bytes and we have already
                //  consumed one, so at most three to go
4472
                for i in 1..4 {
4194
                    if !self.consume_str(r"\x") {
1112
                        return Err(Error::InvalidEscape(
1112
                            "Not a valid byte-escaped Unicode character",
1112
                        ));
3082
                    }
3082
                    bytes[i] = self.decode_ascii_escape()?;
                    // Check if we now have a valid UTF-8 character
3082
                    if let Ok(Some(c)) = from_utf8(&bytes[..=i]).map(|s| s.chars().next()) {
286
                        return Ok(EscapeCharacter::Utf8(c));
2796
                    }
                }
278
                return Err(Error::InvalidEscape(
278
                    "Not a valid byte-escaped Unicode character",
278
                ));
            }
            'u' => {
11398
                self.expect_char('{', Error::InvalidEscape("Missing { in Unicode escape"))?;
11398
                let mut bytes: u32 = 0;
11398
                let mut num_digits = 0;
30302
                while num_digits < 6 {
30302
                    let byte = self.peek_char_or_eof()?;
30302
                    if byte == '}' {
11398
                        break;
18904
                    }
18904
                    self.skip_next_char();
18904
                    num_digits += 1;
18904
                    let byte = Self::decode_hex(byte)?;
18904
                    bytes <<= 4;
18904
                    bytes |= u32::from(byte);
                }
11398
                if num_digits == 0 {
278
                    return Err(Error::InvalidEscape(
278
                        "Expected 1-6 digits, got 0 digits in Unicode escape",
278
                    ));
11120
                }
11120
                self.expect_char(
                    '}',
11120
                    Error::InvalidEscape("No } at the end of Unicode escape"),
                )?;
11120
                let c = char_from_u32(bytes).ok_or(Error::InvalidEscape(
11120
                    "Not a valid Unicode-escaped character",
11120
                ))?;
11120
                EscapeCharacter::Utf8(c)
            }
278
            _ => return Err(Error::InvalidEscape("Unknown escape character")),
        };
21998
        Ok(c)
216416
    }
3282256
    fn skip_comment(&mut self) -> Result<Option<Comment>> {
3282256
        if self.consume_char('/') {
30044
            match self.next_char()? {
                '/' => {
123936
                    let bytes = self.next_chars_while_len(|c| c != '\n');
8348
                    self.advance_bytes(bytes);
8348
                    if self.src().is_empty() {
1116
                        Ok(Some(Comment::UnclosedLine))
                    } else {
7232
                        Ok(Some(Comment::ClosedLine))
                    }
                }
                '*' => {
21418
                    let mut level = 1;
49504
                    while level > 0 {
194354
                        let bytes = self.next_chars_while_len(|c| !matches!(c, '/' | '*'));
28646
                        if self.src().is_empty() {
282
                            return Err(Error::UnclosedBlockComment);
28364
                        }
28364
                        self.advance_bytes(bytes);
                        // check whether / or * and take action
28364
                        if self.consume_str("/*") {
1946
                            level += 1;
26418
                        } else if self.consume_str("*/") {
22804
                            level -= 1;
22804
                        } else {
3614
                            self.next_char().map_err(|_| Error::UnclosedBlockComment)?;
                        }
                    }
20858
                    Ok(Some(Comment::Block))
                }
278
                c => Err(Error::UnexpectedChar(c)),
            }
        } else {
3252212
            Ok(None)
        }
3282256
    }
}
enum Comment {
    ClosedLine,
    UnclosedLine,
    Block,
}
pub trait Num {
    fn from_u8(x: u8) -> Self;
    /// Returns `true` on overflow
    fn checked_mul_ext(&mut self, x: u8) -> bool;
    /// Returns `true` on overflow
    fn checked_add_ext(&mut self, x: u8) -> bool;
    /// Returns `true` on overflow
    fn checked_sub_ext(&mut self, x: u8) -> bool;
}
macro_rules! impl_num {
    ($ty:ty) => {
        impl Num for $ty {
1266211
            fn from_u8(x: u8) -> Self {
1266211
                x as $ty
1266211
            }
525102
            fn checked_mul_ext(&mut self, x: u8) -> bool {
525102
                match self.checked_mul(Self::from_u8(x)) {
524260
                    Some(n) => {
524260
                        *self = n;
524260
                        false
                    }
842
                    None => true,
                }
525102
            }
437330
            fn checked_add_ext(&mut self, x: u8) -> bool {
437330
                match self.checked_add(Self::from_u8(x)) {
436913
                    Some(n) => {
436913
                        *self = n;
436913
                        false
                    }
417
                    None => true,
                }
437330
            }
84984
            fn checked_sub_ext(&mut self, x: u8) -> bool {
84984
                match self.checked_sub(Self::from_u8(x)) {
82204
                    Some(n) => {
82204
                        *self = n;
82204
                        false
                    }
2780
                    None => true,
                }
84984
            }
        }
    };
    ($($tys:ty)*) => {
        $( impl_num!($tys); )*
    };
}
impl_num! { i8 i16 i32 i64 u8 u16 u32 u64 }
#[cfg(feature = "integer128")]
impl_num! { i128 u128 }
pub trait Integer: Sized {
    fn parse(parser: &mut Parser, sign: i8) -> Result<Self>;
    fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self>;
}
macro_rules! impl_integer {
    ($wrap:ident($ty:ty)) => {
        impl Integer for $ty {
113317
            fn parse(parser: &mut Parser, sign: i8) -> Result<Self> {
113317
                parser.parse_integer(sign)
113317
            }
28356
            fn try_from_parsed_integer(parsed: ParsedInteger, ron: &str) -> Result<Self> {
28356
                match parsed {
7506
                    ParsedInteger::$wrap(v) => Ok(v),
                    _ => Err(Error::InvalidValueForType {
20850
                        expected: format!(
20850
                            "a{} {}-bit {}signed integer",
20850
                            if <$ty>::BITS == 8 { "n" } else { "n" },
                            <$ty>::BITS,
20850
                            if <$ty>::MIN == 0 { "un" } else { "" },
                        ),
20850
                        found: String::from(ron),
                    }),
                }
28356
            }
        }
    };
    ($($wraps:ident($tys:ty))*) => {
        $( impl_integer!($wraps($tys)); )*
    };
}
impl_integer! {
    I8(i8) I16(i16) I32(i32) I64(i64)
    U8(u8) U16(u16) U32(u32) U64(u64)
}
#[cfg(feature = "integer128")]
impl_integer! { I128(i128) U128(u128) }
pub enum ParsedInteger {
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    #[cfg(feature = "integer128")]
    I128(i128),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    #[cfg(feature = "integer128")]
    U128(u128),
}
impl Integer for ParsedInteger {
76046
    fn parse(parser: &mut Parser, sign: i8) -> Result<Self> {
76046
        if sign < 0 {
1996
            let signed = parser.parse_integer::<LargeSInt>(-1)?;
582
            return if let Ok(x) = i8::try_from(signed) {
290
                Ok(ParsedInteger::I8(x))
292
            } else if let Ok(x) = i16::try_from(signed) {
4
                Ok(ParsedInteger::I16(x))
288
            } else if let Ok(x) = i32::try_from(signed) {
4
                Ok(ParsedInteger::I32(x))
            } else {
                #[cfg(not(feature = "integer128"))]
                {
2
                    Ok(ParsedInteger::I64(signed))
                }
                #[cfg(feature = "integer128")]
282
                if let Ok(x) = i64::try_from(signed) {
2
                    Ok(ParsedInteger::I64(x))
                } else {
280
                    Ok(ParsedInteger::I128(signed))
                }
            };
74050
        }
74050
        let unsigned = parser.parse_integer::<LargeUInt>(1)?;
73335
        if let Ok(x) = u8::try_from(unsigned) {
72761
            Ok(ParsedInteger::U8(x))
574
        } else if let Ok(x) = u16::try_from(unsigned) {
8
            Ok(ParsedInteger::U16(x))
566
        } else if let Ok(x) = u32::try_from(unsigned) {
4
            Ok(ParsedInteger::U32(x))
        } else {
            #[cfg(not(feature = "integer128"))]
            {
2
                Ok(ParsedInteger::U64(unsigned))
            }
            #[cfg(feature = "integer128")]
560
            if let Ok(x) = u64::try_from(unsigned) {
2
                Ok(ParsedInteger::U64(x))
            } else {
558
                Ok(ParsedInteger::U128(unsigned))
            }
        }
76046
    }
219342
    fn try_from_parsed_integer(parsed: ParsedInteger, _ron: &str) -> Result<Self> {
219342
        Ok(parsed)
219342
    }
}
pub trait Float: Sized {
    fn parse(float: &str) -> Result<Self>;
    fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self>;
}
macro_rules! impl_float {
    ($wrap:ident($ty:ty: $bits:expr)) => {
        impl Float for $ty {
32249
            fn parse(float: &str) -> Result<Self> {
32249
                <$ty>::from_str(float).map_err(|_| Error::ExpectedFloat)
32249
            }
3892
            fn try_from_parsed_float(parsed: ParsedFloat, ron: &str) -> Result<Self> {
3892
                match parsed {
3336
                    ParsedFloat::$wrap(v) => Ok(v),
556
                    _ => Err(Error::InvalidValueForType {
556
                        expected: format!(
556
                            "a {}-bit floating point number", $bits,
556
                        ),
556
                        found: String::from(ron),
556
                    }),
                }
3892
            }
        }
    };
    ($($wraps:ident($tys:ty: $bits:expr))*) => {
        $( impl_float!($wraps($tys: $bits)); )*
    };
}
impl_float! { F32(f32: 32) F64(f64: 64) }
pub enum ParsedFloat {
    F32(f32),
    F64(f64),
}
impl Float for ParsedFloat {
11514
    fn parse(float: &str) -> Result<Self> {
11514
        let value = f64::from_str(float).map_err(|_| Error::ExpectedFloat)?;
        #[allow(clippy::cast_possible_truncation)]
11514
        if value.total_cmp(&f64::from(value as f32)).is_eq() {
4532
            Ok(ParsedFloat::F32(value as f32))
        } else {
6982
            Ok(ParsedFloat::F64(value))
        }
11514
    }
2780
    fn try_from_parsed_float(parsed: ParsedFloat, _ron: &str) -> Result<Self> {
2780
        Ok(parsed)
2780
    }
}
pub enum StructType {
    AnyTuple,
    EmptyTuple,
    NewtypeTuple,
    NonNewtypeTuple,
    Named,
    Unit,
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
pub enum NewtypeMode {
    NoParensMeanUnit,
    InsideNewtype,
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
pub enum TupleMode {
    ImpreciseTupleOrNewtype,
    DifferentiateNewtype,
}
pub enum ParsedStr<'a> {
    Allocated(String),
    Slice(&'a str),
}
pub enum ParsedByteStr<'a> {
    Allocated(Vec<u8>),
    Slice(&'a [u8]),
}
impl<'a> ParsedStr<'a> {
87049
    pub fn try_from_bytes(bytes: ParsedByteStr<'a>) -> Result<Self, Utf8Error> {
87049
        match bytes {
6136
            ParsedByteStr::Allocated(byte_buf) => Ok(ParsedStr::Allocated(
6136
                String::from_utf8(byte_buf).map_err(|e| e.utf8_error())?,
            )),
80913
            ParsedByteStr::Slice(bytes) => Ok(ParsedStr::Slice(from_utf8(bytes)?)),
        }
87049
    }
}
impl<'a> ParsedByteStr<'a> {
1962
    pub fn try_from_base64(str: &ParsedStr<'a>) -> Result<Self, base64::DecodeError> {
1962
        let base64_str = match str {
278
            ParsedStr::Allocated(string) => string.as_str(),
1684
            ParsedStr::Slice(str) => str,
        };
1962
        base64::engine::Engine::decode(&base64::engine::general_purpose::STANDARD, base64_str)
1962
            .map(ParsedByteStr::Allocated)
1962
    }
}
#[derive(Copy, Clone)] // GRCOV_EXCL_LINE
enum EscapeEncoding {
    Binary,
    Utf8,
}
enum EscapeCharacter {
    Ascii(u8),
    Utf8(char),
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
4
    fn decode_x10() {
4
        let mut bytes = Parser::new("10").unwrap();
4
        assert_eq!(bytes.decode_ascii_escape(), Ok(b'\x10'));
4
    }
    #[test]
4
    fn track_prior_ws() {
        const SOURCE: &str = "   /*hey*/ 42       /*bye*/ 24  ";
4
        let mut bytes = Parser::new(SOURCE).unwrap();
4
        assert_eq!(bytes.src(), "42       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        assert_eq!(bytes.src(), "       /*bye*/ 24  ");
4
        assert_eq!(bytes.pre_ws_src(), SOURCE);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "24  ");
4
        assert_eq!(bytes.pre_ws_src(), "       /*bye*/ 24  ");
4
        let mut bytes = Parser::new("42").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42");
4
        assert_eq!(bytes.pre_ws_src(), "42");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "");
4
        let mut bytes = Parser::new("  42  ").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42  ");
4
        assert_eq!(bytes.pre_ws_src(), "  42  ");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "  ");
4
        let mut bytes = Parser::new("  42  //").unwrap();
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "42  //");
4
        assert_eq!(bytes.pre_ws_src(), "  42  //");
4
        assert_eq!(bytes.integer::<u8>().unwrap(), 42);
4
        bytes.skip_ws().unwrap();
4
        bytes.skip_ws().unwrap();
4
        assert_eq!(bytes.src(), "");
4
        assert_eq!(bytes.pre_ws_src(), "  //");
4
    }
    #[test]
4
    fn parser_cursor_eq_cmp() {
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } == ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } != ParserCursor {
4
                cursor: 24,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } < ParserCursor {
4
                cursor: 43,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
        assert!(
4
            ParserCursor {
4
                cursor: 42,
4
                pre_ws_cursor: 42,
4
                last_ws_len: 42
4
            } > ParserCursor {
4
                cursor: 41,
4
                pre_ws_cursor: 24,
4
                last_ws_len: 24
4
            }
        );
4
    }
    #[test]
4
    fn empty_src_is_not_a_float() {
4
        assert!(!Parser::new("").unwrap().next_bytes_is_float());
4
    }
    #[test]
4
    fn v0_10_base64_deprecation_error() {
4
        let err = crate::from_str::<bytes::Bytes>("\"SGVsbG8gcm9uIQ==\"").unwrap_err();
4
        assert_eq!(
            err,
4
            SpannedError {
4
                code: Error::InvalidValueForType {
4
                    expected: String::from("the Rusty byte string b\"Hello ron!\""),
4
                    found: String::from("the ambiguous base64 string \"SGVsbG8gcm9uIQ==\"")
4
                },
4
                span: Span {
4
                    start: Position { line: 1, col: 2 },
4
                    end: Position { line: 1, col: 19 },
4
                }
4
            }
        );
4
        let err = crate::from_str::<bytes::Bytes>("r\"SGVsbG8gcm9uIQ==\"").unwrap_err();
4
        assert_eq!(format!("{}", err.code), "Expected the Rusty byte string b\"Hello ron!\" but found the ambiguous base64 string \"SGVsbG8gcm9uIQ==\" instead");
4
        assert_eq!(
4
            crate::from_str::<bytes::Bytes>("\"invalid=\"").unwrap_err(),
            SpannedError {
                code: Error::ExpectedByteString,
                span: Span {
                    start: Position { line: 1, col: 2 },
                    end: Position { line: 1, col: 11 },
                }
            }
        );
4
        assert_eq!(
4
            crate::from_str::<bytes::Bytes>("r\"invalid=\"").unwrap_err(),
            SpannedError {
                code: Error::ExpectedByteString,
                span: Span {
                    start: Position { line: 1, col: 3 },
                    end: Position { line: 1, col: 12 },
                }
            }
        );
4
    }
}