Coverage Report

Created: 2025-12-14 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/proc-macro2-1.0.103/src/parse.rs
Line
Count
Source
1
use crate::fallback::{
2
    self, is_ident_continue, is_ident_start, Group, Ident, LexError, Literal, Span, TokenStream,
3
    TokenStreamBuilder,
4
};
5
use crate::{Delimiter, Punct, Spacing, TokenTree};
6
use core::char;
7
use core::str::{Bytes, CharIndices, Chars};
8
9
#[derive(Copy, Clone, Eq, PartialEq)]
10
pub(crate) struct Cursor<'a> {
11
    pub(crate) rest: &'a str,
12
    #[cfg(span_locations)]
13
    pub(crate) off: u32,
14
}
15
16
impl<'a> Cursor<'a> {
17
27.0M
    pub(crate) fn advance(&self, bytes: usize) -> Cursor<'a> {
18
27.0M
        let (_front, rest) = self.rest.split_at(bytes);
19
27.0M
        Cursor {
20
27.0M
            rest,
21
27.0M
            #[cfg(span_locations)]
22
27.0M
            off: self.off + _front.chars().count() as u32,
23
27.0M
        }
24
27.0M
    }
25
26
240M
    pub(crate) fn starts_with(&self, s: &str) -> bool {
27
240M
        self.rest.starts_with(s)
28
240M
    }
29
30
4.07k
    pub(crate) fn starts_with_char(&self, ch: char) -> bool {
31
4.07k
        self.rest.starts_with(ch)
32
4.07k
    }
33
34
0
    pub(crate) fn starts_with_fn<Pattern>(&self, f: Pattern) -> bool
35
0
    where
36
0
        Pattern: FnMut(char) -> bool,
37
    {
38
0
        self.rest.starts_with(f)
39
0
    }
40
41
21.5M
    pub(crate) fn is_empty(&self) -> bool {
42
21.5M
        self.rest.is_empty()
43
21.5M
    }
44
45
5.44M
    fn len(&self) -> usize {
46
5.44M
        self.rest.len()
47
5.44M
    }
48
49
21.5M
    fn as_bytes(&self) -> &'a [u8] {
50
21.5M
        self.rest.as_bytes()
51
21.5M
    }
52
53
29.9M
    fn bytes(&self) -> Bytes<'a> {
54
29.9M
        self.rest.bytes()
55
29.9M
    }
56
57
30.3M
    fn chars(&self) -> Chars<'a> {
58
30.3M
        self.rest.chars()
59
30.3M
    }
60
61
1.36M
    fn char_indices(&self) -> CharIndices<'a> {
62
1.36M
        self.rest.char_indices()
63
1.36M
    }
64
65
84.2M
    fn parse(&self, tag: &str) -> Result<Cursor<'a>, Reject> {
66
84.2M
        if self.starts_with(tag) {
67
188k
            Ok(self.advance(tag.len()))
68
        } else {
69
84.0M
            Err(Reject)
70
        }
71
84.2M
    }
72
}
73
74
pub(crate) struct Reject;
75
type PResult<'a, O> = Result<(Cursor<'a>, O), Reject>;
76
77
20.0M
fn skip_whitespace(input: Cursor) -> Cursor {
78
20.0M
    let mut s = input;
79
80
21.5M
    while !s.is_empty() {
81
21.5M
        let byte = s.as_bytes()[0];
82
21.5M
        if byte == b'/' {
83
141k
            if s.starts_with("//")
84
19.0k
                && (!s.starts_with("///") || s.starts_with("////"))
85
17.7k
                && !s.starts_with("//!")
86
            {
87
7.92k
                let (cursor, _) = take_until_newline_or_eof(s);
88
7.92k
                s = cursor;
89
7.92k
                continue;
90
133k
            } else if s.starts_with("/**/") {
91
21
                s = s.advance(4);
92
21
                continue;
93
133k
            } else if s.starts_with("/*")
94
146
                && (!s.starts_with("/**") || s.starts_with("/***"))
95
86
                && !s.starts_with("/*!")
96
            {
97
42
                match block_comment(s) {
98
34
                    Ok((rest, _)) => {
99
34
                        s = rest;
100
34
                        continue;
101
                    }
102
8
                    Err(Reject) => return s,
103
                }
104
133k
            }
105
21.3M
        }
106
20.0M
        match byte {
107
21.3M
            b' ' | 0x09..=0x0d => {
108
1.44M
                s = s.advance(1);
109
1.44M
                continue;
110
            }
111
20.0M
            b if b.is_ascii() => {}
112
            _ => {
113
476
                let ch = s.chars().next().unwrap();
114
476
                if is_whitespace(ch) {
115
298
                    s = s.advance(ch.len_utf8());
116
298
                    continue;
117
178
                }
118
            }
119
        }
120
20.0M
        return s;
121
    }
122
154
    s
123
20.0M
}
124
125
146
fn block_comment(input: Cursor) -> PResult<&str> {
126
146
    if !input.starts_with("/*") {
127
0
        return Err(Reject);
128
146
    }
129
130
146
    let mut depth = 0usize;
131
146
    let bytes = input.as_bytes();
132
146
    let mut i = 0usize;
133
146
    let upper = bytes.len() - 1;
134
135
10.9M
    while i < upper {
136
10.9M
        if bytes[i] == b'/' && bytes[i + 1] == b'*' {
137
1.96M
            depth += 1;
138
1.96M
            i += 1; // eat '*'
139
8.99M
        } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
140
25.4k
            depth -= 1;
141
25.4k
            if depth == 0 {
142
129
                return Ok((input.advance(i + 2), &input.rest[..i + 2]));
143
25.3k
            }
144
25.3k
            i += 1; // eat '/'
145
8.96M
        }
146
10.9M
        i += 1;
147
    }
148
149
17
    Err(Reject)
150
146
}
151
152
476
fn is_whitespace(ch: char) -> bool {
153
    // Rust treats left-to-right mark and right-to-left mark as whitespace
154
476
    ch.is_whitespace() || ch == '\u{200e}' || ch == '\u{200f}'
155
476
}
156
157
2.05M
fn word_break(input: Cursor) -> Result<Cursor, Reject> {
158
2.05M
    match input.chars().next() {
159
2.05M
        Some(ch) if is_ident_continue(ch) => Err(Reject),
160
2.05M
        Some(_) | None => Ok(input),
161
    }
162
2.05M
}
163
164
// Rustc's representation of a macro expansion error in expression position or
165
// type position.
166
const ERROR: &str = "(/*ERROR*/)";
167
168
420
pub(crate) fn token_stream(mut input: Cursor) -> Result<TokenStream, LexError> {
169
420
    let mut trees = TokenStreamBuilder::new();
170
420
    let mut stack = Vec::new();
171
172
    loop {
173
20.0M
        input = skip_whitespace(input);
174
175
20.0M
        if let Ok((rest, ())) = doc_comment(input, &mut trees) {
176
11.1k
            input = rest;
177
11.1k
            continue;
178
20.0M
        }
179
180
        #[cfg(span_locations)]
181
        let lo = input.off;
182
183
20.0M
        let first = match input.bytes().next() {
184
20.0M
            Some(first) => first,
185
154
            None => match stack.last() {
186
134
                None => return Ok(trees.build()),
187
                #[cfg(span_locations)]
188
                Some((lo, _frame)) => {
189
                    return Err(LexError {
190
                        span: Span { lo: *lo, hi: *lo },
191
                    })
192
                }
193
                #[cfg(not(span_locations))]
194
20
                Some(_frame) => return Err(LexError { span: Span {} }),
195
            },
196
        };
197
198
8.98M
        if let Some(open_delimiter) = match first {
199
1.59M
            b'(' if !input.starts_with(ERROR) => Some(Delimiter::Parenthesis),
200
7.39M
            b'[' => Some(Delimiter::Bracket),
201
3.83k
            b'{' => Some(Delimiter::Brace),
202
11.0M
            _ => None,
203
8.98M
        } {
204
8.98M
            input = input.advance(1);
205
8.98M
            let frame = (open_delimiter, trees);
206
8.98M
            #[cfg(span_locations)]
207
8.98M
            let frame = (lo, frame);
208
8.98M
            stack.push(frame);
209
8.98M
            trees = TokenStreamBuilder::new();
210
11.0M
        } else if let Some(close_delimiter) = match first {
211
500k
            b')' => Some(Delimiter::Parenthesis),
212
4.62k
            b']' => Some(Delimiter::Bracket),
213
99
            b'}' => Some(Delimiter::Brace),
214
10.5M
            _ => None,
215
        } {
216
505k
            let frame = match stack.pop() {
217
505k
                Some(frame) => frame,
218
4
                None => return Err(lex_error(input)),
219
            };
220
            #[cfg(span_locations)]
221
            let (lo, frame) = frame;
222
505k
            let (open_delimiter, outer) = frame;
223
505k
            if open_delimiter != close_delimiter {
224
4
                return Err(lex_error(input));
225
505k
            }
226
505k
            input = input.advance(1);
227
505k
            let mut g = Group::new(open_delimiter, trees.build());
228
505k
            g.set_span(Span {
229
505k
                #[cfg(span_locations)]
230
505k
                lo,
231
505k
                #[cfg(span_locations)]
232
505k
                hi: input.off,
233
505k
            });
234
505k
            trees = outer;
235
505k
            trees.push_token_from_parser(TokenTree::Group(crate::Group::_new_fallback(g)));
236
        } else {
237
10.5M
            let (rest, mut tt) = match leaf_token(input) {
238
10.5M
                Ok((rest, tt)) => (rest, tt),
239
258
                Err(Reject) => return Err(lex_error(input)),
240
            };
241
10.5M
            tt.set_span(crate::Span::_new_fallback(Span {
242
10.5M
                #[cfg(span_locations)]
243
10.5M
                lo,
244
10.5M
                #[cfg(span_locations)]
245
10.5M
                hi: rest.off,
246
10.5M
            }));
247
10.5M
            trees.push_token_from_parser(tt);
248
10.5M
            input = rest;
249
        }
250
    }
251
420
}
252
253
266
fn lex_error(cursor: Cursor) -> LexError {
254
    #[cfg(not(span_locations))]
255
266
    let _ = cursor;
256
266
    LexError {
257
266
        span: Span {
258
266
            #[cfg(span_locations)]
259
266
            lo: cursor.off,
260
266
            #[cfg(span_locations)]
261
266
            hi: cursor.off,
262
266
        },
263
266
    }
264
266
}
265
266
10.5M
fn leaf_token(input: Cursor) -> PResult<TokenTree> {
267
10.5M
    if let Ok((input, l)) = literal(input) {
268
        // must be parsed before ident
269
2.10M
        Ok((input, TokenTree::Literal(crate::Literal::_new_fallback(l))))
270
8.46M
    } else if let Ok((input, p)) = punct(input) {
271
7.24M
        Ok((input, TokenTree::Punct(p)))
272
1.22M
    } else if let Ok((input, i)) = ident(input) {
273
1.22M
        Ok((input, TokenTree::Ident(i)))
274
489
    } else if input.starts_with(ERROR) {
275
231
        let rest = input.advance(ERROR.len());
276
231
        let repr = crate::Literal::_new_fallback(Literal::_new(ERROR.to_owned()));
277
231
        Ok((rest, TokenTree::Literal(repr)))
278
    } else {
279
258
        Err(Reject)
280
    }
281
10.5M
}
282
283
1.22M
fn ident(input: Cursor) -> PResult<crate::Ident> {
284
1.22M
    if [
285
1.22M
        "r\"", "r#\"", "r##", "b\"", "b\'", "br\"", "br#", "c\"", "cr\"", "cr#",
286
1.22M
    ]
287
1.22M
    .iter()
288
12.2M
    .any(|prefix| input.starts_with(prefix))
289
    {
290
68
        Err(Reject)
291
    } else {
292
1.22M
        ident_any(input)
293
    }
294
1.22M
}
295
296
1.22M
fn ident_any(input: Cursor) -> PResult<crate::Ident> {
297
1.22M
    let raw = input.starts_with("r#");
298
1.22M
    let rest = input.advance((raw as usize) << 1);
299
300
1.22M
    let (rest, sym) = ident_not_raw(rest)?;
301
302
1.22M
    if !raw {
303
1.22M
        let ident =
304
1.22M
            crate::Ident::_new_fallback(Ident::new_unchecked(sym, fallback::Span::call_site()));
305
1.22M
        return Ok((rest, ident));
306
2.63k
    }
307
308
2.63k
    match sym {
309
2.63k
        "_" | "super" | "self" | "Self" | "crate" => return Err(Reject),
310
2.63k
        _ => {}
311
    }
312
313
2.63k
    let ident =
314
2.63k
        crate::Ident::_new_fallback(Ident::new_raw_unchecked(sym, fallback::Span::call_site()));
315
2.63k
    Ok((rest, ident))
316
1.22M
}
317
318
1.28M
fn ident_not_raw(input: Cursor) -> PResult<&str> {
319
1.28M
    let mut chars = input.char_indices();
320
321
1.28M
    match chars.next() {
322
1.28M
        Some((_, ch)) if is_ident_start(ch) => {}
323
58.4k
        _ => return Err(Reject),
324
    }
325
326
1.22M
    let mut end = input.len();
327
18.5M
    for (i, ch) in chars {
328
18.5M
        if !is_ident_continue(ch) {
329
1.22M
            end = i;
330
1.22M
            break;
331
17.3M
        }
332
    }
333
334
1.22M
    Ok((input.advance(end), &input.rest[..end]))
335
1.28M
}
336
337
10.5M
pub(crate) fn literal(input: Cursor) -> PResult<Literal> {
338
10.5M
    let rest = literal_nocapture(input)?;
339
2.10M
    let end = input.len() - rest.len();
340
2.10M
    Ok((rest, Literal::_new(input.rest[..end].to_string())))
341
10.5M
}
342
343
10.5M
fn literal_nocapture(input: Cursor) -> Result<Cursor, Reject> {
344
10.5M
    if let Ok(ok) = string(input) {
345
57.0k
        Ok(ok)
346
10.5M
    } else if let Ok(ok) = byte_string(input) {
347
91
        Ok(ok)
348
10.5M
    } else if let Ok(ok) = c_string(input) {
349
153
        Ok(ok)
350
10.5M
    } else if let Ok(ok) = byte(input) {
351
113
        Ok(ok)
352
10.5M
    } else if let Ok(ok) = character(input) {
353
731
        Ok(ok)
354
10.5M
    } else if let Ok(ok) = float(input) {
355
738k
        Ok(ok)
356
9.77M
    } else if let Ok(ok) = int(input) {
357
1.31M
        Ok(ok)
358
    } else {
359
8.46M
        Err(Reject)
360
    }
361
10.5M
}
362
363
58.1k
fn literal_suffix(input: Cursor) -> Cursor {
364
58.1k
    match ident_not_raw(input) {
365
122
        Ok((input, _)) => input,
366
58.0k
        Err(Reject) => input,
367
    }
368
58.1k
}
369
370
10.5M
fn string(input: Cursor) -> Result<Cursor, Reject> {
371
10.5M
    if let Ok(input) = input.parse("\"") {
372
56.9k
        cooked_string(input)
373
10.5M
    } else if let Ok(input) = input.parse("r") {
374
127k
        raw_string(input)
375
    } else {
376
10.3M
        Err(Reject)
377
    }
378
10.5M
}
379
380
56.9k
fn cooked_string(mut input: Cursor) -> Result<Cursor, Reject> {
381
56.9k
    let mut chars = input.char_indices();
382
383
6.11M
    while let Some((i, ch)) = chars.next() {
384
6.11M
        match ch {
385
            '"' => {
386
56.9k
                let input = input.advance(i + 1);
387
56.9k
                return Ok(literal_suffix(input));
388
            }
389
370
            '\r' => match chars.next() {
390
366
                Some((_, '\n')) => {}
391
4
                _ => break,
392
            },
393
626
            '\\' => match chars.next() {
394
                Some((_, 'x')) => {
395
246
                    backslash_x_char(&mut chars)?;
396
                }
397
334
                Some((_, 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0')) => {}
398
                Some((_, 'u')) => {
399
1
                    backslash_u(&mut chars)?;
400
                }
401
41
                Some((newline, ch @ ('\n' | '\r'))) => {
402
41
                    input = input.advance(newline + 1);
403
41
                    trailing_backslash(&mut input, ch as u8)?;
404
40
                    chars = input.char_indices();
405
                }
406
4
                _ => break,
407
            },
408
6.06M
            _ch => {}
409
        }
410
    }
411
15
    Err(Reject)
412
56.9k
}
413
414
127k
fn raw_string(input: Cursor) -> Result<Cursor, Reject> {
415
127k
    let (input, delimiter) = delimiter_of_raw_string(input)?;
416
109
    let mut bytes = input.bytes().enumerate();
417
5.02M
    while let Some((i, byte)) = bytes.next() {
418
3.28k
        match byte {
419
3.28k
            b'"' if input.rest[i + 1..].starts_with(delimiter) => {
420
99
                let rest = input.advance(i + 1 + delimiter.len());
421
99
                return Ok(literal_suffix(rest));
422
            }
423
118
            b'\r' => match bytes.next() {
424
116
                Some((_, b'\n')) => {}
425
2
                _ => break,
426
            },
427
5.02M
            _ => {}
428
        }
429
    }
430
10
    Err(Reject)
431
127k
}
432
433
10.5M
fn byte_string(input: Cursor) -> Result<Cursor, Reject> {
434
10.5M
    if let Ok(input) = input.parse("b\"") {
435
49
        cooked_byte_string(input)
436
10.5M
    } else if let Ok(input) = input.parse("br") {
437
675
        raw_byte_string(input)
438
    } else {
439
10.5M
        Err(Reject)
440
    }
441
10.5M
}
442
443
49
fn cooked_byte_string(mut input: Cursor) -> Result<Cursor, Reject> {
444
49
    let mut bytes = input.bytes().enumerate();
445
4.30M
    while let Some((offset, b)) = bytes.next() {
446
4.27M
        match b {
447
            b'"' => {
448
32
                let input = input.advance(offset + 1);
449
32
                return Ok(literal_suffix(input));
450
            }
451
25.4k
            b'\r' => match bytes.next() {
452
25.4k
                Some((_, b'\n')) => {}
453
1
                _ => break,
454
            },
455
458
            b'\\' => match bytes.next() {
456
                Some((_, b'x')) => {
457
258
                    backslash_x_byte(&mut bytes)?;
458
                }
459
190
                Some((_, b'n' | b'r' | b't' | b'\\' | b'0' | b'\'' | b'"')) => {}
460
9
                Some((newline, b @ (b'\n' | b'\r'))) => {
461
9
                    input = input.advance(newline + 1);
462
9
                    trailing_backslash(&mut input, b)?;
463
8
                    bytes = input.bytes().enumerate();
464
                }
465
1
                _ => break,
466
            },
467
4.27M
            b if b.is_ascii() => {}
468
2
            _ => break,
469
        }
470
    }
471
10
    Err(Reject)
472
49
}
473
474
128k
fn delimiter_of_raw_string(input: Cursor) -> PResult<&str> {
475
1.09M
    for (i, byte) in input.bytes().enumerate() {
476
1.09M
        match byte {
477
            b'"' => {
478
275
                if i > 255 {
479
                    // https://github.com/rust-lang/rust/pull/95251
480
2
                    return Err(Reject);
481
273
                }
482
273
                return Ok((input.advance(i + 1), &input.rest[..i]));
483
            }
484
969k
            b'#' => {}
485
128k
            _ => break,
486
        }
487
    }
488
128k
    Err(Reject)
489
128k
}
490
491
675
fn raw_byte_string(input: Cursor) -> Result<Cursor, Reject> {
492
675
    let (input, delimiter) = delimiter_of_raw_string(input)?;
493
66
    let mut bytes = input.bytes().enumerate();
494
2.34M
    while let Some((i, byte)) = bytes.next() {
495
129k
        match byte {
496
129k
            b'"' if input.rest[i + 1..].starts_with(delimiter) => {
497
59
                let rest = input.advance(i + 1 + delimiter.len());
498
59
                return Ok(literal_suffix(rest));
499
            }
500
11.3k
            b'\r' => match bytes.next() {
501
11.3k
                Some((_, b'\n')) => {}
502
2
                _ => break,
503
            },
504
2.33M
            other => {
505
2.33M
                if !other.is_ascii() {
506
1
                    break;
507
2.33M
                }
508
            }
509
        }
510
    }
511
7
    Err(Reject)
512
675
}
513
514
10.5M
fn c_string(input: Cursor) -> Result<Cursor, Reject> {
515
10.5M
    if let Ok(input) = input.parse("c\"") {
516
71
        cooked_c_string(input)
517
10.5M
    } else if let Ok(input) = input.parse("cr") {
518
698
        raw_c_string(input)
519
    } else {
520
10.5M
        Err(Reject)
521
    }
522
10.5M
}
523
524
698
fn raw_c_string(input: Cursor) -> Result<Cursor, Reject> {
525
698
    let (input, delimiter) = delimiter_of_raw_string(input)?;
526
98
    let mut bytes = input.bytes().enumerate();
527
1.21M
    while let Some((i, byte)) = bytes.next() {
528
158
        match byte {
529
158
            b'"' if input.rest[i + 1..].starts_with(delimiter) => {
530
88
                let rest = input.advance(i + 1 + delimiter.len());
531
88
                return Ok(literal_suffix(rest));
532
            }
533
19.2k
            b'\r' => match bytes.next() {
534
19.2k
                Some((_, b'\n')) => {}
535
2
                _ => break,
536
            },
537
6
            b'\0' => break,
538
1.19M
            _ => {}
539
        }
540
    }
541
10
    Err(Reject)
542
698
}
543
544
71
fn cooked_c_string(mut input: Cursor) -> Result<Cursor, Reject> {
545
71
    let mut chars = input.char_indices();
546
547
709k
    while let Some((i, ch)) = chars.next() {
548
709k
        match ch {
549
            '"' => {
550
65
                let input = input.advance(i + 1);
551
65
                return Ok(literal_suffix(input));
552
            }
553
1
            '\r' => match chars.next() {
554
0
                Some((_, '\n')) => {}
555
1
                _ => break,
556
            },
557
18
            '\\' => match chars.next() {
558
                Some((_, 'x')) => {
559
2
                    backslash_x_nonzero(&mut chars)?;
560
                }
561
4
                Some((_, 'n' | 'r' | 't' | '\\' | '\'' | '"')) => {}
562
                Some((_, 'u')) => {
563
0
                    if backslash_u(&mut chars)? == '\0' {
564
0
                        break;
565
0
                    }
566
                }
567
12
                Some((newline, ch @ ('\n' | '\r'))) => {
568
12
                    input = input.advance(newline + 1);
569
12
                    trailing_backslash(&mut input, ch as u8)?;
570
9
                    chars = input.char_indices();
571
                }
572
0
                _ => break,
573
            },
574
1
            '\0' => break,
575
709k
            _ch => {}
576
        }
577
    }
578
3
    Err(Reject)
579
71
}
580
581
10.5M
fn byte(input: Cursor) -> Result<Cursor, Reject> {
582
10.5M
    let input = input.parse("b'")?;
583
121
    let mut bytes = input.bytes().enumerate();
584
121
    let ok = match bytes.next().map(|(_, b)| b) {
585
109
        Some(b'\\') => match bytes.next().map(|(_, b)| b) {
586
85
            Some(b'x') => backslash_x_byte(&mut bytes).is_ok(),
587
24
            Some(b'n' | b'r' | b't' | b'\\' | b'0' | b'\'' | b'"') => true,
588
0
            _ => false,
589
        },
590
12
        b => b.is_some(),
591
    };
592
121
    if !ok {
593
0
        return Err(Reject);
594
121
    }
595
121
    let (offset, _) = bytes.next().ok_or(Reject)?;
596
119
    if !input.chars().as_str().is_char_boundary(offset) {
597
0
        return Err(Reject);
598
119
    }
599
119
    let input = input.advance(offset).parse("'")?;
600
113
    Ok(literal_suffix(input))
601
10.5M
}
602
603
10.5M
fn character(input: Cursor) -> Result<Cursor, Reject> {
604
10.5M
    let input = input.parse("'")?;
605
2.12k
    let mut chars = input.char_indices();
606
2.12k
    let ok = match chars.next().map(|(_, ch)| ch) {
607
399
        Some('\\') => match chars.next().map(|(_, ch)| ch) {
608
396
            Some('x') => backslash_x_char(&mut chars).is_ok(),
609
0
            Some('u') => backslash_u(&mut chars).is_ok(),
610
3
            Some('n' | 'r' | 't' | '\\' | '0' | '\'' | '"') => true,
611
0
            _ => false,
612
        },
613
1.72k
        ch => ch.is_some(),
614
    };
615
2.12k
    if !ok {
616
0
        return Err(Reject);
617
2.12k
    }
618
2.12k
    let (idx, _) = chars.next().ok_or(Reject)?;
619
2.12k
    let input = input.advance(idx).parse("'")?;
620
731
    Ok(literal_suffix(input))
621
10.5M
}
622
623
macro_rules! next_ch {
624
    ($chars:ident @ $pat:pat) => {
625
        match $chars.next() {
626
            Some((_, ch)) => match ch {
627
                $pat => ch,
628
                _ => return Err(Reject),
629
            },
630
            None => return Err(Reject),
631
        }
632
    };
633
}
634
635
642
fn backslash_x_char<I>(chars: &mut I) -> Result<(), Reject>
636
642
where
637
642
    I: Iterator<Item = (usize, char)>,
638
{
639
642
    next_ch!(chars @ '0'..='7');
640
642
    next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F');
641
642
    Ok(())
642
642
}
643
644
343
fn backslash_x_byte<I>(chars: &mut I) -> Result<(), Reject>
645
343
where
646
343
    I: Iterator<Item = (usize, u8)>,
647
{
648
343
    next_ch!(chars @ b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F');
649
339
    next_ch!(chars @ b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F');
650
337
    Ok(())
651
343
}
652
653
2
fn backslash_x_nonzero<I>(chars: &mut I) -> Result<(), Reject>
654
2
where
655
2
    I: Iterator<Item = (usize, char)>,
656
{
657
2
    let first = next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F');
658
2
    let second = next_ch!(chars @ '0'..='9' | 'a'..='f' | 'A'..='F');
659
2
    if first == '0' && second == '0' {
660
0
        Err(Reject)
661
    } else {
662
2
        Ok(())
663
    }
664
2
}
665
666
1
fn backslash_u<I>(chars: &mut I) -> Result<char, Reject>
667
1
where
668
1
    I: Iterator<Item = (usize, char)>,
669
{
670
1
    next_ch!(chars @ '{');
671
0
    let mut value = 0;
672
0
    let mut len = 0;
673
0
    for (_, ch) in chars {
674
0
        let digit = match ch {
675
0
            '0'..='9' => ch as u8 - b'0',
676
0
            'a'..='f' => 10 + ch as u8 - b'a',
677
0
            'A'..='F' => 10 + ch as u8 - b'A',
678
0
            '_' if len > 0 => continue,
679
0
            '}' if len > 0 => return char::from_u32(value).ok_or(Reject),
680
0
            _ => break,
681
        };
682
0
        if len == 6 {
683
0
            break;
684
0
        }
685
0
        value *= 0x10;
686
0
        value += u32::from(digit);
687
0
        len += 1;
688
    }
689
0
    Err(Reject)
690
1
}
691
692
62
fn trailing_backslash(input: &mut Cursor, mut last: u8) -> Result<(), Reject> {
693
62
    let mut whitespace = input.bytes().enumerate();
694
    loop {
695
4.72M
        if last == b'\r' && whitespace.next().map_or(true, |(_, b)| b != b'\n') {
696
4
            return Err(Reject);
697
4.72M
        }
698
4.72M
        match whitespace.next() {
699
4.72M
            Some((_, b @ (b' ' | b'\t' | b'\n' | b'\r'))) => {
700
4.72M
                last = b;
701
4.72M
            }
702
57
            Some((offset, _)) => {
703
57
                *input = input.advance(offset);
704
57
                return Ok(());
705
            }
706
1
            None => return Err(Reject),
707
        }
708
    }
709
62
}
710
711
10.5M
fn float(input: Cursor) -> Result<Cursor, Reject> {
712
10.5M
    let mut rest = float_digits(input)?;
713
738k
    if let Some(ch) = rest.chars().next() {
714
738k
        if is_ident_start(ch) {
715
2.44k
            rest = ident_not_raw(rest)?.0;
716
735k
        }
717
18
    }
718
738k
    word_break(rest)
719
10.5M
}
720
721
10.5M
fn float_digits(input: Cursor) -> Result<Cursor, Reject> {
722
10.5M
    let mut chars = input.chars().peekable();
723
10.5M
    match chars.next() {
724
10.5M
        Some(ch) if '0' <= ch && ch <= '9' => {}
725
8.46M
        _ => return Err(Reject),
726
    }
727
728
2.05M
    let mut len = 1;
729
2.05M
    let mut has_dot = false;
730
2.05M
    let mut has_exp = false;
731
21.3M
    while let Some(&ch) = chars.peek() {
732
21.3M
        match ch {
733
18.8M
            '0'..='9' | '_' => {
734
18.5M
                chars.next();
735
18.5M
                len += 1;
736
18.5M
            }
737
            '.' => {
738
1.30M
                if has_dot {
739
557k
                    break;
740
744k
                }
741
744k
                chars.next();
742
744k
                if chars
743
744k
                    .peek()
744
744k
                    .map_or(false, |&ch| ch == '.' || is_ident_start(ch))
745
                {
746
7.20k
                    return Err(Reject);
747
737k
                }
748
737k
                len += 1;
749
737k
                has_dot = true;
750
            }
751
            'e' | 'E' => {
752
1.21k
                chars.next();
753
1.21k
                len += 1;
754
1.21k
                has_exp = true;
755
1.21k
                break;
756
            }
757
1.48M
            _ => break,
758
        }
759
    }
760
761
2.04M
    if !(has_dot || has_exp) {
762
1.30M
        return Err(Reject);
763
738k
    }
764
765
738k
    if has_exp {
766
1.21k
        let token_before_exp = if has_dot {
767
159
            Ok(input.advance(len - 1))
768
        } else {
769
1.05k
            Err(Reject)
770
        };
771
1.21k
        let mut has_sign = false;
772
1.21k
        let mut has_exp_value = false;
773
1.83M
        while let Some(&ch) = chars.peek() {
774
1.83M
            match ch {
775
                '+' | '-' => {
776
267
                    if has_exp_value {
777
95
                        break;
778
172
                    }
779
172
                    if has_sign {
780
2
                        return token_before_exp;
781
170
                    }
782
170
                    chars.next();
783
170
                    len += 1;
784
170
                    has_sign = true;
785
                }
786
1.35M
                '0'..='9' => {
787
1.35M
                    chars.next();
788
1.35M
                    len += 1;
789
1.35M
                    has_exp_value = true;
790
1.35M
                }
791
481k
                '_' => {
792
481k
                    chars.next();
793
481k
                    len += 1;
794
481k
                }
795
1.10k
                _ => break,
796
            }
797
        }
798
1.20k
        if !has_exp_value {
799
577
            return token_before_exp;
800
632
        }
801
737k
    }
802
803
738k
    Ok(input.advance(len))
804
10.5M
}
805
806
9.77M
fn int(input: Cursor) -> Result<Cursor, Reject> {
807
9.77M
    let mut rest = digits(input)?;
808
1.31M
    if let Some(ch) = rest.chars().next() {
809
1.31M
        if is_ident_start(ch) {
810
2.33k
            rest = ident_not_raw(rest)?.0;
811
1.30M
        }
812
24
    }
813
1.31M
    word_break(rest)
814
9.77M
}
815
816
9.77M
fn digits(mut input: Cursor) -> Result<Cursor, Reject> {
817
9.77M
    let base = if input.starts_with("0x") {
818
75
        input = input.advance(2);
819
75
        16
820
9.77M
    } else if input.starts_with("0o") {
821
5
        input = input.advance(2);
822
5
        8
823
9.77M
    } else if input.starts_with("0b") {
824
572
        input = input.advance(2);
825
572
        2
826
    } else {
827
9.77M
        10
828
    };
829
830
9.77M
    let mut len = 0;
831
9.77M
    let mut empty = true;
832
22.9M
    for b in input.bytes() {
833
22.9M
        match b {
834
16.8M
            b'0'..=b'9' => {
835
8.40M
                let digit = (b - b'0') as u64;
836
8.40M
                if digit >= base {
837
0
                    return Err(Reject);
838
8.40M
                }
839
            }
840
1.36M
            b'a'..=b'f' => {
841
1.04M
                let digit = 10 + (b - b'a') as u64;
842
1.04M
                if digit >= base {
843
168k
                    break;
844
876k
                }
845
            }
846
5.00M
            b'A'..=b'F' => {
847
702k
                let digit = 10 + (b - b'A') as u64;
848
702k
                if digit >= base {
849
702k
                    break;
850
63
                }
851
            }
852
            b'_' => {
853
3.89M
                if empty && base == 10 {
854
371
                    return Err(Reject);
855
3.89M
                }
856
3.89M
                len += 1;
857
3.89M
                continue;
858
            }
859
8.90M
            _ => break,
860
        }
861
9.28M
        len += 1;
862
9.28M
        empty = false;
863
    }
864
9.77M
    if empty {
865
8.46M
        Err(Reject)
866
    } else {
867
1.31M
        Ok(input.advance(len))
868
    }
869
9.77M
}
870
871
8.46M
fn punct(input: Cursor) -> PResult<Punct> {
872
8.46M
    let (rest, ch) = punct_char(input)?;
873
7.24M
    if ch == '\'' {
874
1.39k
        let (after_lifetime, _ident) = ident_any(rest)?;
875
1.38k
        if after_lifetime.starts_with_char('\'')
876
1.38k
            || (after_lifetime.starts_with_char('#') && !rest.starts_with("r#"))
877
        {
878
6
            Err(Reject)
879
        } else {
880
1.38k
            Ok((rest, Punct::new('\'', Spacing::Joint)))
881
        }
882
    } else {
883
7.24M
        let kind = match punct_char(rest) {
884
4.04M
            Ok(_) => Spacing::Joint,
885
3.19M
            Err(Reject) => Spacing::Alone,
886
        };
887
7.24M
        Ok((rest, Punct::new(ch, kind)))
888
    }
889
8.46M
}
890
891
15.7M
fn punct_char(input: Cursor) -> PResult<char> {
892
15.7M
    if input.starts_with("//") || input.starts_with("/*") {
893
        // Do not accept `/` of a comment as a punct.
894
655
        return Err(Reject);
895
15.7M
    }
896
897
15.7M
    let mut chars = input.chars();
898
15.7M
    let first = match chars.next() {
899
15.7M
        Some(ch) => ch,
900
        None => {
901
15
            return Err(Reject);
902
        }
903
    };
904
15.7M
    let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
905
15.7M
    if recognized.contains(first) {
906
11.2M
        Ok((input.advance(first.len_utf8()), first))
907
    } else {
908
4.41M
        Err(Reject)
909
    }
910
15.7M
}
911
912
20.0M
fn doc_comment<'a>(input: Cursor<'a>, trees: &mut TokenStreamBuilder) -> PResult<'a, ()> {
913
    #[cfg(span_locations)]
914
    let lo = input.off;
915
20.0M
    let (rest, (comment, inner)) = doc_comment_contents(input)?;
916
11.2k
    let fallback_span = Span {
917
11.2k
        #[cfg(span_locations)]
918
11.2k
        lo,
919
11.2k
        #[cfg(span_locations)]
920
11.2k
        hi: rest.off,
921
11.2k
    };
922
11.2k
    let span = crate::Span::_new_fallback(fallback_span);
923
924
11.2k
    let mut scan_for_bare_cr = comment;
925
11.3k
    while let Some(cr) = scan_for_bare_cr.find('\r') {
926
150
        let rest = &scan_for_bare_cr[cr + 1..];
927
150
        if !rest.starts_with('\n') {
928
32
            return Err(Reject);
929
118
        }
930
118
        scan_for_bare_cr = rest;
931
    }
932
933
11.1k
    let mut pound = Punct::new('#', Spacing::Alone);
934
11.1k
    pound.set_span(span);
935
11.1k
    trees.push_token_from_parser(TokenTree::Punct(pound));
936
937
11.1k
    if inner {
938
9.83k
        let mut bang = Punct::new('!', Spacing::Alone);
939
9.83k
        bang.set_span(span);
940
9.83k
        trees.push_token_from_parser(TokenTree::Punct(bang));
941
9.83k
    }
942
943
11.1k
    let doc_ident = crate::Ident::_new_fallback(Ident::new_unchecked("doc", fallback_span));
944
11.1k
    let mut equal = Punct::new('=', Spacing::Alone);
945
11.1k
    equal.set_span(span);
946
11.1k
    let mut literal = crate::Literal::_new_fallback(Literal::string(comment));
947
11.1k
    literal.set_span(span);
948
11.1k
    let mut bracketed = TokenStreamBuilder::with_capacity(3);
949
11.1k
    bracketed.push_token_from_parser(TokenTree::Ident(doc_ident));
950
11.1k
    bracketed.push_token_from_parser(TokenTree::Punct(equal));
951
11.1k
    bracketed.push_token_from_parser(TokenTree::Literal(literal));
952
11.1k
    let group = Group::new(Delimiter::Bracket, bracketed.build());
953
11.1k
    let mut group = crate::Group::_new_fallback(group);
954
11.1k
    group.set_span(span);
955
11.1k
    trees.push_token_from_parser(TokenTree::Group(group));
956
957
11.1k
    Ok((rest, ()))
958
20.0M
}
959
960
20.0M
fn doc_comment_contents(input: Cursor) -> PResult<(&str, bool)> {
961
20.0M
    if input.starts_with("//!") {
962
9.80k
        let input = input.advance(3);
963
9.80k
        let (input, s) = take_until_newline_or_eof(input);
964
9.80k
        Ok((input, (s, true)))
965
20.0M
    } else if input.starts_with("/*!") {
966
44
        let (input, s) = block_comment(input)?;
967
36
        Ok((input, (&s[3..s.len() - 2], true)))
968
20.0M
    } else if input.starts_with("///") {
969
1.29k
        let input = input.advance(3);
970
1.29k
        if input.starts_with_char('/') {
971
0
            return Err(Reject);
972
1.29k
        }
973
1.29k
        let (input, s) = take_until_newline_or_eof(input);
974
1.29k
        Ok((input, (s, false)))
975
20.0M
    } else if input.starts_with("/**") && !input.rest[3..].starts_with('*') {
976
60
        let (input, s) = block_comment(input)?;
977
59
        Ok((input, (&s[3..s.len() - 2], false)))
978
    } else {
979
20.0M
        Err(Reject)
980
    }
981
20.0M
}
982
983
19.0k
fn take_until_newline_or_eof(input: Cursor) -> (Cursor, &str) {
984
19.0k
    let chars = input.char_indices();
985
986
28.7M
    for (i, ch) in chars {
987
28.7M
        if ch == '\n' {
988
13.8k
            return (input.advance(i), &input.rest[..i]);
989
28.6M
        } else if ch == '\r' && input.rest[i + 1..].starts_with('\n') {
990
5.10k
            return (input.advance(i + 1), &input.rest[..i]);
991
28.6M
        }
992
    }
993
994
61
    (input.advance(input.len()), input.rest)
995
19.0k
}