Coverage Report

Created: 2025-07-18 06:51

/rust/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.95/src/fallback.rs
Line
Count
Source (jump to first uncovered line)
1
#[cfg(wrap_proc_macro)]
2
use crate::imp;
3
#[cfg(span_locations)]
4
use crate::location::LineColumn;
5
use crate::parse::{self, Cursor};
6
use crate::rcvec::{RcVec, RcVecBuilder, RcVecIntoIter, RcVecMut};
7
use crate::{Delimiter, Spacing, TokenTree};
8
#[cfg(all(span_locations, not(fuzzing)))]
9
use alloc::collections::BTreeMap;
10
#[cfg(all(span_locations, not(fuzzing)))]
11
use core::cell::RefCell;
12
#[cfg(span_locations)]
13
use core::cmp;
14
use core::fmt::{self, Debug, Display, Write};
15
use core::mem::ManuallyDrop;
16
#[cfg(span_locations)]
17
use core::ops::Range;
18
use core::ops::RangeBounds;
19
use core::ptr;
20
use core::str;
21
#[cfg(feature = "proc-macro")]
22
use core::str::FromStr;
23
use std::ffi::CStr;
24
#[cfg(wrap_proc_macro)]
25
use std::panic;
26
#[cfg(procmacro2_semver_exempt)]
27
use std::path::PathBuf;
28
29
/// Force use of proc-macro2's fallback implementation of the API for now, even
30
/// if the compiler's implementation is available.
31
0
pub fn force() {
32
0
    #[cfg(wrap_proc_macro)]
33
0
    crate::detection::force_fallback();
34
0
}
35
36
/// Resume using the compiler's implementation of the proc macro API if it is
37
/// available.
38
0
pub fn unforce() {
39
0
    #[cfg(wrap_proc_macro)]
40
0
    crate::detection::unforce_fallback();
41
0
}
42
43
#[derive(Clone)]
44
pub(crate) struct TokenStream {
45
    inner: RcVec<TokenTree>,
46
}
47
48
#[derive(Debug)]
49
pub(crate) struct LexError {
50
    pub(crate) span: Span,
51
}
52
53
impl LexError {
54
0
    pub(crate) fn span(&self) -> Span {
55
0
        self.span
56
0
    }
57
58
0
    pub(crate) fn call_site() -> Self {
59
0
        LexError {
60
0
            span: Span::call_site(),
61
0
        }
62
0
    }
63
}
64
65
impl TokenStream {
66
0
    pub(crate) fn new() -> Self {
67
0
        TokenStream {
68
0
            inner: RcVecBuilder::new().build(),
69
0
        }
70
0
    }
71
72
380
    pub(crate) fn from_str_checked(src: &str) -> Result<Self, LexError> {
73
380
        // Create a dummy file & add it to the source map
74
380
        let mut cursor = get_cursor(src);
75
76
        // Strip a byte order mark if present
77
        const BYTE_ORDER_MARK: &str = "\u{feff}";
78
380
        if cursor.starts_with(BYTE_ORDER_MARK) {
79
0
            cursor = cursor.advance(BYTE_ORDER_MARK.len());
80
380
        }
81
82
380
        parse::token_stream(cursor)
83
380
    }
84
85
    #[cfg(feature = "proc-macro")]
86
0
    pub(crate) fn from_str_unchecked(src: &str) -> Self {
87
0
        Self::from_str_checked(src).unwrap()
88
0
    }
89
90
0
    pub(crate) fn is_empty(&self) -> bool {
91
0
        self.inner.len() == 0
92
0
    }
93
94
0
    fn take_inner(self) -> RcVecBuilder<TokenTree> {
95
0
        let nodrop = ManuallyDrop::new(self);
96
0
        unsafe { ptr::read(&nodrop.inner) }.make_owned()
97
0
    }
98
}
99
100
0
fn push_token_from_proc_macro(mut vec: RcVecMut<TokenTree>, token: TokenTree) {
101
    // https://github.com/dtolnay/proc-macro2/issues/235
102
0
    match token {
103
        TokenTree::Literal(crate::Literal {
104
            #[cfg(wrap_proc_macro)]
105
0
                inner: crate::imp::Literal::Fallback(literal),
106
            #[cfg(not(wrap_proc_macro))]
107
                inner: literal,
108
            ..
109
0
        }) if literal.repr.starts_with('-') => {
110
0
            push_negative_literal(vec, literal);
111
0
        }
112
0
        _ => vec.push(token),
113
    }
114
115
    #[cold]
116
0
    fn push_negative_literal(mut vec: RcVecMut<TokenTree>, mut literal: Literal) {
117
0
        literal.repr.remove(0);
118
0
        let mut punct = crate::Punct::new('-', Spacing::Alone);
119
0
        punct.set_span(crate::Span::_new_fallback(literal.span));
120
0
        vec.push(TokenTree::Punct(punct));
121
0
        vec.push(TokenTree::Literal(crate::Literal::_new_fallback(literal)));
122
0
    }
123
0
}
124
125
// Nonrecursive to prevent stack overflow.
126
impl Drop for TokenStream {
127
1.05M
    fn drop(&mut self) {
128
1.05M
        let mut stack = Vec::new();
129
1.05M
        let mut current = match self.inner.get_mut() {
130
1.05M
            Some(inner) => inner.take().into_iter(),
131
0
            None => return,
132
        };
133
        loop {
134
6.45M
            while let Some(token) = current.next() {
135
5.00M
                let group = match token {
136
393k
                    TokenTree::Group(group) => group.inner,
137
4.61M
                    _ => continue,
138
                };
139
                #[cfg(wrap_proc_macro)]
140
393k
                let group = match group {
141
393k
                    crate::imp::Group::Fallback(group) => group,
142
0
                    crate::imp::Group::Compiler(_) => continue,
143
                };
144
393k
                let mut group = group;
145
393k
                if let Some(inner) = group.stream.inner.get_mut() {
146
393k
                    stack.push(current);
147
393k
                    current = inner.take().into_iter();
148
393k
                }
149
            }
150
1.44M
            match stack.pop() {
151
393k
                Some(next) => current = next,
152
1.05M
                None => return,
153
            }
154
        }
155
1.05M
    }
156
}
157
158
pub(crate) struct TokenStreamBuilder {
159
    inner: RcVecBuilder<TokenTree>,
160
}
161
162
impl TokenStreamBuilder {
163
3.61M
    pub(crate) fn new() -> Self {
164
3.61M
        TokenStreamBuilder {
165
3.61M
            inner: RcVecBuilder::new(),
166
3.61M
        }
167
3.61M
    }
168
169
362k
    pub(crate) fn with_capacity(cap: usize) -> Self {
170
362k
        TokenStreamBuilder {
171
362k
            inner: RcVecBuilder::with_capacity(cap),
172
362k
        }
173
362k
    }
174
175
10.9M
    pub(crate) fn push_token_from_parser(&mut self, tt: TokenTree) {
176
10.9M
        self.inner.push(tt);
177
10.9M
    }
178
179
1.05M
    pub(crate) fn build(self) -> TokenStream {
180
1.05M
        TokenStream {
181
1.05M
            inner: self.inner.build(),
182
1.05M
        }
183
1.05M
    }
184
}
185
186
#[cfg(span_locations)]
187
fn get_cursor(src: &str) -> Cursor {
188
    #[cfg(fuzzing)]
189
    return Cursor { rest: src, off: 1 };
190
191
    // Create a dummy file & add it to the source map
192
    #[cfg(not(fuzzing))]
193
    SOURCE_MAP.with(|sm| {
194
        let mut sm = sm.borrow_mut();
195
        let span = sm.add_file(src);
196
        Cursor {
197
            rest: src,
198
            off: span.lo,
199
        }
200
    })
201
}
202
203
#[cfg(not(span_locations))]
204
380
fn get_cursor(src: &str) -> Cursor {
205
380
    Cursor { rest: src }
206
380
}
207
208
impl Display for LexError {
209
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210
0
        f.write_str("cannot parse string into token stream")
211
0
    }
212
}
213
214
impl Display for TokenStream {
215
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
216
0
        let mut joint = false;
217
0
        for (i, tt) in self.inner.iter().enumerate() {
218
0
            if i != 0 && !joint {
219
0
                write!(f, " ")?;
220
0
            }
221
0
            joint = false;
222
0
            match tt {
223
0
                TokenTree::Group(tt) => Display::fmt(tt, f),
224
0
                TokenTree::Ident(tt) => Display::fmt(tt, f),
225
0
                TokenTree::Punct(tt) => {
226
0
                    joint = tt.spacing() == Spacing::Joint;
227
0
                    Display::fmt(tt, f)
228
                }
229
0
                TokenTree::Literal(tt) => Display::fmt(tt, f),
230
0
            }?;
231
        }
232
233
0
        Ok(())
234
0
    }
235
}
236
237
impl Debug for TokenStream {
238
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239
0
        f.write_str("TokenStream ")?;
240
0
        f.debug_list().entries(self.clone()).finish()
241
0
    }
242
}
243
244
#[cfg(feature = "proc-macro")]
245
impl From<proc_macro::TokenStream> for TokenStream {
246
0
    fn from(inner: proc_macro::TokenStream) -> Self {
247
0
        TokenStream::from_str_unchecked(&inner.to_string())
248
0
    }
249
}
250
251
#[cfg(feature = "proc-macro")]
252
impl From<TokenStream> for proc_macro::TokenStream {
253
0
    fn from(inner: TokenStream) -> Self {
254
0
        proc_macro::TokenStream::from_str_unchecked(&inner.to_string())
255
0
    }
256
}
257
258
impl From<TokenTree> for TokenStream {
259
0
    fn from(tree: TokenTree) -> Self {
260
0
        let mut stream = RcVecBuilder::new();
261
0
        push_token_from_proc_macro(stream.as_mut(), tree);
262
0
        TokenStream {
263
0
            inner: stream.build(),
264
0
        }
265
0
    }
266
}
267
268
impl FromIterator<TokenTree> for TokenStream {
269
0
    fn from_iter<I: IntoIterator<Item = TokenTree>>(tokens: I) -> Self {
270
0
        let mut stream = TokenStream::new();
271
0
        stream.extend(tokens);
272
0
        stream
273
0
    }
274
}
275
276
impl FromIterator<TokenStream> for TokenStream {
277
0
    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
278
0
        let mut v = RcVecBuilder::new();
279
280
0
        for stream in streams {
281
0
            v.extend(stream.take_inner());
282
0
        }
283
284
0
        TokenStream { inner: v.build() }
285
0
    }
286
}
287
288
impl Extend<TokenTree> for TokenStream {
289
0
    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, tokens: I) {
290
0
        let mut vec = self.inner.make_mut();
291
0
        tokens
292
0
            .into_iter()
293
0
            .for_each(|token| push_token_from_proc_macro(vec.as_mut(), token));
294
0
    }
295
}
296
297
impl Extend<TokenStream> for TokenStream {
298
0
    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
299
0
        self.inner.make_mut().extend(streams.into_iter().flatten());
300
0
    }
301
}
302
303
pub(crate) type TokenTreeIter = RcVecIntoIter<TokenTree>;
304
305
impl IntoIterator for TokenStream {
306
    type Item = TokenTree;
307
    type IntoIter = TokenTreeIter;
308
309
0
    fn into_iter(self) -> TokenTreeIter {
310
0
        self.take_inner().into_iter()
311
0
    }
312
}
313
314
#[cfg(all(span_locations, not(fuzzing)))]
315
thread_local! {
316
    static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap {
317
        // Start with a single dummy file which all call_site() and def_site()
318
        // spans reference.
319
        files: vec![FileInfo {
320
            source_text: String::new(),
321
            span: Span { lo: 0, hi: 0 },
322
            lines: vec![0],
323
            char_index_to_byte_offset: BTreeMap::new(),
324
        }],
325
    });
326
}
327
328
#[cfg(span_locations)]
329
pub(crate) fn invalidate_current_thread_spans() {
330
    #[cfg(not(fuzzing))]
331
    SOURCE_MAP.with(|sm| sm.borrow_mut().files.truncate(1));
332
}
333
334
#[cfg(all(span_locations, not(fuzzing)))]
335
struct FileInfo {
336
    source_text: String,
337
    span: Span,
338
    lines: Vec<usize>,
339
    char_index_to_byte_offset: BTreeMap<usize, usize>,
340
}
341
342
#[cfg(all(span_locations, not(fuzzing)))]
343
impl FileInfo {
344
    fn offset_line_column(&self, offset: usize) -> LineColumn {
345
        assert!(self.span_within(Span {
346
            lo: offset as u32,
347
            hi: offset as u32,
348
        }));
349
        let offset = offset - self.span.lo as usize;
350
        match self.lines.binary_search(&offset) {
351
            Ok(found) => LineColumn {
352
                line: found + 1,
353
                column: 0,
354
            },
355
            Err(idx) => LineColumn {
356
                line: idx,
357
                column: offset - self.lines[idx - 1],
358
            },
359
        }
360
    }
361
362
    fn span_within(&self, span: Span) -> bool {
363
        span.lo >= self.span.lo && span.hi <= self.span.hi
364
    }
365
366
    fn byte_range(&mut self, span: Span) -> Range<usize> {
367
        let lo_char = (span.lo - self.span.lo) as usize;
368
369
        // Look up offset of the largest already-computed char index that is
370
        // less than or equal to the current requested one. We resume counting
371
        // chars from that point.
372
        let (&last_char_index, &last_byte_offset) = self
373
            .char_index_to_byte_offset
374
            .range(..=lo_char)
375
            .next_back()
376
            .unwrap_or((&0, &0));
377
378
        let lo_byte = if last_char_index == lo_char {
379
            last_byte_offset
380
        } else {
381
            let total_byte_offset = match self.source_text[last_byte_offset..]
382
                .char_indices()
383
                .nth(lo_char - last_char_index)
384
            {
385
                Some((additional_offset, _ch)) => last_byte_offset + additional_offset,
386
                None => self.source_text.len(),
387
            };
388
            self.char_index_to_byte_offset
389
                .insert(lo_char, total_byte_offset);
390
            total_byte_offset
391
        };
392
393
        let trunc_lo = &self.source_text[lo_byte..];
394
        let char_len = (span.hi - span.lo) as usize;
395
        lo_byte..match trunc_lo.char_indices().nth(char_len) {
396
            Some((offset, _ch)) => lo_byte + offset,
397
            None => self.source_text.len(),
398
        }
399
    }
400
401
    fn source_text(&mut self, span: Span) -> String {
402
        let byte_range = self.byte_range(span);
403
        self.source_text[byte_range].to_owned()
404
    }
405
}
406
407
/// Computes the offsets of each line in the given source string
408
/// and the total number of characters
409
#[cfg(all(span_locations, not(fuzzing)))]
410
fn lines_offsets(s: &str) -> (usize, Vec<usize>) {
411
    let mut lines = vec![0];
412
    let mut total = 0;
413
414
    for ch in s.chars() {
415
        total += 1;
416
        if ch == '\n' {
417
            lines.push(total);
418
        }
419
    }
420
421
    (total, lines)
422
}
423
424
#[cfg(all(span_locations, not(fuzzing)))]
425
struct SourceMap {
426
    files: Vec<FileInfo>,
427
}
428
429
#[cfg(all(span_locations, not(fuzzing)))]
430
impl SourceMap {
431
    fn next_start_pos(&self) -> u32 {
432
        // Add 1 so there's always space between files.
433
        //
434
        // We'll always have at least 1 file, as we initialize our files list
435
        // with a dummy file.
436
        self.files.last().unwrap().span.hi + 1
437
    }
438
439
    fn add_file(&mut self, src: &str) -> Span {
440
        let (len, lines) = lines_offsets(src);
441
        let lo = self.next_start_pos();
442
        let span = Span {
443
            lo,
444
            hi: lo + (len as u32),
445
        };
446
447
        self.files.push(FileInfo {
448
            source_text: src.to_owned(),
449
            span,
450
            lines,
451
            // Populated lazily by source_text().
452
            char_index_to_byte_offset: BTreeMap::new(),
453
        });
454
455
        span
456
    }
457
458
    #[cfg(procmacro2_semver_exempt)]
459
    fn filepath(&self, span: Span) -> String {
460
        for (i, file) in self.files.iter().enumerate() {
461
            if file.span_within(span) {
462
                return if i == 0 {
463
                    "<unspecified>".to_owned()
464
                } else {
465
                    format!("<parsed string {}>", i)
466
                };
467
            }
468
        }
469
        unreachable!("Invalid span with no related FileInfo!");
470
    }
471
472
    fn fileinfo(&self, span: Span) -> &FileInfo {
473
        for file in &self.files {
474
            if file.span_within(span) {
475
                return file;
476
            }
477
        }
478
        unreachable!("Invalid span with no related FileInfo!");
479
    }
480
481
    fn fileinfo_mut(&mut self, span: Span) -> &mut FileInfo {
482
        for file in &mut self.files {
483
            if file.span_within(span) {
484
                return file;
485
            }
486
        }
487
        unreachable!("Invalid span with no related FileInfo!");
488
    }
489
}
490
491
#[derive(Clone, Copy, PartialEq, Eq)]
492
pub(crate) struct Span {
493
    #[cfg(span_locations)]
494
    pub(crate) lo: u32,
495
    #[cfg(span_locations)]
496
    pub(crate) hi: u32,
497
}
498
499
impl Span {
500
    #[cfg(not(span_locations))]
501
10.6M
    pub(crate) fn call_site() -> Self {
502
10.6M
        Span {}
503
10.6M
    }
504
505
    #[cfg(span_locations)]
506
    pub(crate) fn call_site() -> Self {
507
        Span { lo: 0, hi: 0 }
508
    }
509
510
0
    pub(crate) fn mixed_site() -> Self {
511
0
        Span::call_site()
512
0
    }
513
514
    #[cfg(procmacro2_semver_exempt)]
515
    pub(crate) fn def_site() -> Self {
516
        Span::call_site()
517
    }
518
519
0
    pub(crate) fn resolved_at(&self, _other: Span) -> Span {
520
0
        // Stable spans consist only of line/column information, so
521
0
        // `resolved_at` and `located_at` only select which span the
522
0
        // caller wants line/column information from.
523
0
        *self
524
0
    }
525
526
0
    pub(crate) fn located_at(&self, other: Span) -> Span {
527
0
        other
528
0
    }
529
530
    #[cfg(span_locations)]
531
    pub(crate) fn byte_range(&self) -> Range<usize> {
532
        #[cfg(fuzzing)]
533
        return 0..0;
534
535
        #[cfg(not(fuzzing))]
536
        {
537
            if self.is_call_site() {
538
                0..0
539
            } else {
540
                SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).byte_range(*self))
541
            }
542
        }
543
    }
544
545
    #[cfg(span_locations)]
546
    pub(crate) fn start(&self) -> LineColumn {
547
        #[cfg(fuzzing)]
548
        return LineColumn { line: 0, column: 0 };
549
550
        #[cfg(not(fuzzing))]
551
        SOURCE_MAP.with(|sm| {
552
            let sm = sm.borrow();
553
            let fi = sm.fileinfo(*self);
554
            fi.offset_line_column(self.lo as usize)
555
        })
556
    }
557
558
    #[cfg(span_locations)]
559
    pub(crate) fn end(&self) -> LineColumn {
560
        #[cfg(fuzzing)]
561
        return LineColumn { line: 0, column: 0 };
562
563
        #[cfg(not(fuzzing))]
564
        SOURCE_MAP.with(|sm| {
565
            let sm = sm.borrow();
566
            let fi = sm.fileinfo(*self);
567
            fi.offset_line_column(self.hi as usize)
568
        })
569
    }
570
571
    #[cfg(procmacro2_semver_exempt)]
572
    pub(crate) fn file(&self) -> String {
573
        #[cfg(fuzzing)]
574
        return "<unspecified>".to_owned();
575
576
        #[cfg(not(fuzzing))]
577
        SOURCE_MAP.with(|sm| {
578
            let sm = sm.borrow();
579
            sm.filepath(*self)
580
        })
581
    }
582
583
    #[cfg(procmacro2_semver_exempt)]
584
    pub(crate) fn local_file(&self) -> Option<PathBuf> {
585
        None
586
    }
587
588
    #[cfg(not(span_locations))]
589
0
    pub(crate) fn join(&self, _other: Span) -> Option<Span> {
590
0
        Some(Span {})
591
0
    }
592
593
    #[cfg(span_locations)]
594
    pub(crate) fn join(&self, other: Span) -> Option<Span> {
595
        #[cfg(fuzzing)]
596
        return {
597
            let _ = other;
598
            None
599
        };
600
601
        #[cfg(not(fuzzing))]
602
        SOURCE_MAP.with(|sm| {
603
            let sm = sm.borrow();
604
            // If `other` is not within the same FileInfo as us, return None.
605
            if !sm.fileinfo(*self).span_within(other) {
606
                return None;
607
            }
608
            Some(Span {
609
                lo: cmp::min(self.lo, other.lo),
610
                hi: cmp::max(self.hi, other.hi),
611
            })
612
        })
613
    }
614
615
    #[cfg(not(span_locations))]
616
0
    pub(crate) fn source_text(&self) -> Option<String> {
617
0
        None
618
0
    }
619
620
    #[cfg(span_locations)]
621
    pub(crate) fn source_text(&self) -> Option<String> {
622
        #[cfg(fuzzing)]
623
        return None;
624
625
        #[cfg(not(fuzzing))]
626
        {
627
            if self.is_call_site() {
628
                None
629
            } else {
630
                Some(SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).source_text(*self)))
631
            }
632
        }
633
    }
634
635
    #[cfg(not(span_locations))]
636
0
    pub(crate) fn first_byte(self) -> Self {
637
0
        self
638
0
    }
639
640
    #[cfg(span_locations)]
641
    pub(crate) fn first_byte(self) -> Self {
642
        Span {
643
            lo: self.lo,
644
            hi: cmp::min(self.lo.saturating_add(1), self.hi),
645
        }
646
    }
647
648
    #[cfg(not(span_locations))]
649
0
    pub(crate) fn last_byte(self) -> Self {
650
0
        self
651
0
    }
652
653
    #[cfg(span_locations)]
654
    pub(crate) fn last_byte(self) -> Self {
655
        Span {
656
            lo: cmp::max(self.hi.saturating_sub(1), self.lo),
657
            hi: self.hi,
658
        }
659
    }
660
661
    #[cfg(span_locations)]
662
    fn is_call_site(&self) -> bool {
663
        self.lo == 0 && self.hi == 0
664
    }
665
}
666
667
impl Debug for Span {
668
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
669
0
        #[cfg(span_locations)]
670
0
        return write!(f, "bytes({}..{})", self.lo, self.hi);
671
0
672
0
        #[cfg(not(span_locations))]
673
0
        write!(f, "Span")
674
0
    }
675
}
676
677
0
pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
678
0
    #[cfg(span_locations)]
679
0
    {
680
0
        if span.is_call_site() {
681
0
            return;
682
0
        }
683
0
    }
684
0
685
0
    if cfg!(span_locations) {
686
0
        debug.field("span", &span);
687
0
    }
688
0
}
689
690
#[derive(Clone)]
691
pub(crate) struct Group {
692
    delimiter: Delimiter,
693
    stream: TokenStream,
694
    span: Span,
695
}
696
697
impl Group {
698
1.05M
    pub(crate) fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
699
1.05M
        Group {
700
1.05M
            delimiter,
701
1.05M
            stream,
702
1.05M
            span: Span::call_site(),
703
1.05M
        }
704
1.05M
    }
705
706
0
    pub(crate) fn delimiter(&self) -> Delimiter {
707
0
        self.delimiter
708
0
    }
709
710
0
    pub(crate) fn stream(&self) -> TokenStream {
711
0
        self.stream.clone()
712
0
    }
713
714
0
    pub(crate) fn span(&self) -> Span {
715
0
        self.span
716
0
    }
717
718
0
    pub(crate) fn span_open(&self) -> Span {
719
0
        self.span.first_byte()
720
0
    }
721
722
0
    pub(crate) fn span_close(&self) -> Span {
723
0
        self.span.last_byte()
724
0
    }
725
726
1.05M
    pub(crate) fn set_span(&mut self, span: Span) {
727
1.05M
        self.span = span;
728
1.05M
    }
729
}
730
731
impl Display for Group {
732
    // We attempt to match libproc_macro's formatting.
733
    // Empty parens: ()
734
    // Nonempty parens: (...)
735
    // Empty brackets: []
736
    // Nonempty brackets: [...]
737
    // Empty braces: { }
738
    // Nonempty braces: { ... }
739
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
740
0
        let (open, close) = match self.delimiter {
741
0
            Delimiter::Parenthesis => ("(", ")"),
742
0
            Delimiter::Brace => ("{ ", "}"),
743
0
            Delimiter::Bracket => ("[", "]"),
744
0
            Delimiter::None => ("", ""),
745
        };
746
747
0
        f.write_str(open)?;
748
0
        Display::fmt(&self.stream, f)?;
749
0
        if self.delimiter == Delimiter::Brace && !self.stream.inner.is_empty() {
750
0
            f.write_str(" ")?;
751
0
        }
752
0
        f.write_str(close)?;
753
754
0
        Ok(())
755
0
    }
756
}
757
758
impl Debug for Group {
759
0
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
760
0
        let mut debug = fmt.debug_struct("Group");
761
0
        debug.field("delimiter", &self.delimiter);
762
0
        debug.field("stream", &self.stream);
763
0
        debug_span_field_if_nontrivial(&mut debug, self.span);
764
0
        debug.finish()
765
0
    }
766
}
767
768
#[derive(Clone)]
769
pub(crate) struct Ident {
770
    sym: Box<str>,
771
    span: Span,
772
    raw: bool,
773
}
774
775
impl Ident {
776
    #[track_caller]
777
0
    pub(crate) fn new_checked(string: &str, span: Span) -> Self {
778
0
        validate_ident(string);
779
0
        Ident::new_unchecked(string, span)
780
0
    }
781
782
1.96M
    pub(crate) fn new_unchecked(string: &str, span: Span) -> Self {
783
1.96M
        Ident {
784
1.96M
            sym: Box::from(string),
785
1.96M
            span,
786
1.96M
            raw: false,
787
1.96M
        }
788
1.96M
    }
789
790
    #[track_caller]
791
0
    pub(crate) fn new_raw_checked(string: &str, span: Span) -> Self {
792
0
        validate_ident_raw(string);
793
0
        Ident::new_raw_unchecked(string, span)
794
0
    }
795
796
1.91k
    pub(crate) fn new_raw_unchecked(string: &str, span: Span) -> Self {
797
1.91k
        Ident {
798
1.91k
            sym: Box::from(string),
799
1.91k
            span,
800
1.91k
            raw: true,
801
1.91k
        }
802
1.91k
    }
803
804
0
    pub(crate) fn span(&self) -> Span {
805
0
        self.span
806
0
    }
807
808
1.56M
    pub(crate) fn set_span(&mut self, span: Span) {
809
1.56M
        self.span = span;
810
1.56M
    }
811
}
812
813
4.32M
pub(crate) fn is_ident_start(c: char) -> bool {
814
4.32M
    c == '_' || unicode_ident::is_xid_start(c)
815
4.32M
}
816
817
20.4M
pub(crate) fn is_ident_continue(c: char) -> bool {
818
20.4M
    unicode_ident::is_xid_continue(c)
819
20.4M
}
820
821
#[track_caller]
822
0
fn validate_ident(string: &str) {
823
0
    if string.is_empty() {
824
0
        panic!("Ident is not allowed to be empty; use Option<Ident>");
825
0
    }
826
0
827
0
    if string.bytes().all(|digit| b'0' <= digit && digit <= b'9') {
828
0
        panic!("Ident cannot be a number; use Literal instead");
829
0
    }
830
831
0
    fn ident_ok(string: &str) -> bool {
832
0
        let mut chars = string.chars();
833
0
        let first = chars.next().unwrap();
834
0
        if !is_ident_start(first) {
835
0
            return false;
836
0
        }
837
0
        for ch in chars {
838
0
            if !is_ident_continue(ch) {
839
0
                return false;
840
0
            }
841
        }
842
0
        true
843
0
    }
844
845
0
    if !ident_ok(string) {
846
0
        panic!("{:?} is not a valid Ident", string);
847
0
    }
848
0
}
849
850
#[track_caller]
851
0
fn validate_ident_raw(string: &str) {
852
0
    validate_ident(string);
853
0
854
0
    match string {
855
0
        "_" | "super" | "self" | "Self" | "crate" => {
856
0
            panic!("`r#{}` cannot be a raw identifier", string);
857
        }
858
0
        _ => {}
859
0
    }
860
0
}
861
862
impl PartialEq for Ident {
863
0
    fn eq(&self, other: &Ident) -> bool {
864
0
        self.sym == other.sym && self.raw == other.raw
865
0
    }
866
}
867
868
impl<T> PartialEq<T> for Ident
869
where
870
    T: ?Sized + AsRef<str>,
871
{
872
0
    fn eq(&self, other: &T) -> bool {
873
0
        let other = other.as_ref();
874
0
        if self.raw {
875
0
            other.starts_with("r#") && *self.sym == other[2..]
876
        } else {
877
0
            *self.sym == *other
878
        }
879
0
    }
880
}
881
882
impl Display for Ident {
883
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
884
0
        if self.raw {
885
0
            f.write_str("r#")?;
886
0
        }
887
0
        Display::fmt(&self.sym, f)
888
0
    }
889
}
890
891
#[allow(clippy::missing_fields_in_debug)]
892
impl Debug for Ident {
893
    // Ident(proc_macro), Ident(r#union)
894
    #[cfg(not(span_locations))]
895
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896
0
        let mut debug = f.debug_tuple("Ident");
897
0
        debug.field(&format_args!("{}", self));
898
0
        debug.finish()
899
0
    }
900
901
    // Ident {
902
    //     sym: proc_macro,
903
    //     span: bytes(128..138)
904
    // }
905
    #[cfg(span_locations)]
906
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
907
        let mut debug = f.debug_struct("Ident");
908
        debug.field("sym", &format_args!("{}", self));
909
        debug_span_field_if_nontrivial(&mut debug, self.span);
910
        debug.finish()
911
    }
912
}
913
914
#[derive(Clone)]
915
pub(crate) struct Literal {
916
    pub(crate) repr: String,
917
    span: Span,
918
}
919
920
macro_rules! suffixed_numbers {
921
    ($($name:ident => $kind:ident,)*) => ($(
922
0
        pub(crate) fn $name(n: $kind) -> Literal {
923
0
            Literal::_new(format!(concat!("{}", stringify!($kind)), n))
924
0
        }
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u8_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u16_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u32_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u64_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u128_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::usize_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i8_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i16_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i32_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i64_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i128_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::isize_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::f32_suffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::f64_suffixed
925
    )*)
926
}
927
928
macro_rules! unsuffixed_numbers {
929
    ($($name:ident => $kind:ident,)*) => ($(
930
0
        pub(crate) fn $name(n: $kind) -> Literal {
931
0
            Literal::_new(n.to_string())
932
0
        }
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u8_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u16_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u32_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u64_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::u128_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::usize_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i8_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i16_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i32_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i64_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::i128_unsuffixed
Unexecuted instantiation: <proc_macro2::fallback::Literal>::isize_unsuffixed
933
    )*)
934
}
935
936
impl Literal {
937
1.92M
    pub(crate) fn _new(repr: String) -> Self {
938
1.92M
        Literal {
939
1.92M
            repr,
940
1.92M
            span: Span::call_site(),
941
1.92M
        }
942
1.92M
    }
943
944
0
    pub(crate) fn from_str_checked(repr: &str) -> Result<Self, LexError> {
945
0
        let mut cursor = get_cursor(repr);
946
0
        #[cfg(span_locations)]
947
0
        let lo = cursor.off;
948
0
949
0
        let negative = cursor.starts_with_char('-');
950
0
        if negative {
951
0
            cursor = cursor.advance(1);
952
0
            if !cursor.starts_with_fn(|ch| ch.is_ascii_digit()) {
953
0
                return Err(LexError::call_site());
954
0
            }
955
0
        }
956
957
0
        if let Ok((rest, mut literal)) = parse::literal(cursor) {
958
0
            if rest.is_empty() {
959
0
                if negative {
960
0
                    literal.repr.insert(0, '-');
961
0
                }
962
0
                literal.span = Span {
963
0
                    #[cfg(span_locations)]
964
0
                    lo,
965
0
                    #[cfg(span_locations)]
966
0
                    hi: rest.off,
967
0
                };
968
0
                return Ok(literal);
969
0
            }
970
0
        }
971
0
        Err(LexError::call_site())
972
0
    }
973
974
0
    pub(crate) unsafe fn from_str_unchecked(repr: &str) -> Self {
975
0
        Literal::_new(repr.to_owned())
976
0
    }
977
978
    suffixed_numbers! {
979
        u8_suffixed => u8,
980
        u16_suffixed => u16,
981
        u32_suffixed => u32,
982
        u64_suffixed => u64,
983
        u128_suffixed => u128,
984
        usize_suffixed => usize,
985
        i8_suffixed => i8,
986
        i16_suffixed => i16,
987
        i32_suffixed => i32,
988
        i64_suffixed => i64,
989
        i128_suffixed => i128,
990
        isize_suffixed => isize,
991
992
        f32_suffixed => f32,
993
        f64_suffixed => f64,
994
    }
995
996
    unsuffixed_numbers! {
997
        u8_unsuffixed => u8,
998
        u16_unsuffixed => u16,
999
        u32_unsuffixed => u32,
1000
        u64_unsuffixed => u64,
1001
        u128_unsuffixed => u128,
1002
        usize_unsuffixed => usize,
1003
        i8_unsuffixed => i8,
1004
        i16_unsuffixed => i16,
1005
        i32_unsuffixed => i32,
1006
        i64_unsuffixed => i64,
1007
        i128_unsuffixed => i128,
1008
        isize_unsuffixed => isize,
1009
    }
1010
1011
0
    pub(crate) fn f32_unsuffixed(f: f32) -> Literal {
1012
0
        let mut s = f.to_string();
1013
0
        if !s.contains('.') {
1014
0
            s.push_str(".0");
1015
0
        }
1016
0
        Literal::_new(s)
1017
0
    }
1018
1019
0
    pub(crate) fn f64_unsuffixed(f: f64) -> Literal {
1020
0
        let mut s = f.to_string();
1021
0
        if !s.contains('.') {
1022
0
            s.push_str(".0");
1023
0
        }
1024
0
        Literal::_new(s)
1025
0
    }
1026
1027
362k
    pub(crate) fn string(string: &str) -> Literal {
1028
362k
        let mut repr = String::with_capacity(string.len() + 2);
1029
362k
        repr.push('"');
1030
362k
        escape_utf8(string, &mut repr);
1031
362k
        repr.push('"');
1032
362k
        Literal::_new(repr)
1033
362k
    }
1034
1035
0
    pub(crate) fn character(ch: char) -> Literal {
1036
0
        let mut repr = String::new();
1037
0
        repr.push('\'');
1038
0
        if ch == '"' {
1039
0
            // escape_debug turns this into '\"' which is unnecessary.
1040
0
            repr.push(ch);
1041
0
        } else {
1042
0
            repr.extend(ch.escape_debug());
1043
0
        }
1044
0
        repr.push('\'');
1045
0
        Literal::_new(repr)
1046
0
    }
1047
1048
0
    pub(crate) fn byte_character(byte: u8) -> Literal {
1049
0
        let mut repr = "b'".to_string();
1050
0
        #[allow(clippy::match_overlapping_arm)]
1051
0
        match byte {
1052
0
            b'\0' => repr.push_str(r"\0"),
1053
0
            b'\t' => repr.push_str(r"\t"),
1054
0
            b'\n' => repr.push_str(r"\n"),
1055
0
            b'\r' => repr.push_str(r"\r"),
1056
0
            b'\'' => repr.push_str(r"\'"),
1057
0
            b'\\' => repr.push_str(r"\\"),
1058
0
            b'\x20'..=b'\x7E' => repr.push(byte as char),
1059
0
            _ => {
1060
0
                let _ = write!(repr, r"\x{:02X}", byte);
1061
0
            }
1062
        }
1063
0
        repr.push('\'');
1064
0
        Literal::_new(repr)
1065
0
    }
1066
1067
0
    pub(crate) fn byte_string(bytes: &[u8]) -> Literal {
1068
0
        let mut repr = "b\"".to_string();
1069
0
        let mut bytes = bytes.iter();
1070
0
        while let Some(&b) = bytes.next() {
1071
            #[allow(clippy::match_overlapping_arm)]
1072
0
            match b {
1073
0
                b'\0' => repr.push_str(match bytes.as_slice().first() {
1074
                    // circumvent clippy::octal_escapes lint
1075
0
                    Some(b'0'..=b'7') => r"\x00",
1076
0
                    _ => r"\0",
1077
                }),
1078
0
                b'\t' => repr.push_str(r"\t"),
1079
0
                b'\n' => repr.push_str(r"\n"),
1080
0
                b'\r' => repr.push_str(r"\r"),
1081
0
                b'"' => repr.push_str("\\\""),
1082
0
                b'\\' => repr.push_str(r"\\"),
1083
0
                b'\x20'..=b'\x7E' => repr.push(b as char),
1084
0
                _ => {
1085
0
                    let _ = write!(repr, r"\x{:02X}", b);
1086
0
                }
1087
            }
1088
        }
1089
0
        repr.push('"');
1090
0
        Literal::_new(repr)
1091
0
    }
1092
1093
0
    pub(crate) fn c_string(string: &CStr) -> Literal {
1094
0
        let mut repr = "c\"".to_string();
1095
0
        let mut bytes = string.to_bytes();
1096
0
        while !bytes.is_empty() {
1097
0
            let (valid, invalid) = match str::from_utf8(bytes) {
1098
0
                Ok(all_valid) => {
1099
0
                    bytes = b"";
1100
0
                    (all_valid, bytes)
1101
                }
1102
0
                Err(utf8_error) => {
1103
0
                    let (valid, rest) = bytes.split_at(utf8_error.valid_up_to());
1104
0
                    let valid = str::from_utf8(valid).unwrap();
1105
0
                    let invalid = utf8_error
1106
0
                        .error_len()
1107
0
                        .map_or(rest, |error_len| &rest[..error_len]);
1108
0
                    bytes = &bytes[valid.len() + invalid.len()..];
1109
0
                    (valid, invalid)
1110
                }
1111
            };
1112
0
            escape_utf8(valid, &mut repr);
1113
0
            for &byte in invalid {
1114
0
                let _ = write!(repr, r"\x{:02X}", byte);
1115
0
            }
1116
        }
1117
0
        repr.push('"');
1118
0
        Literal::_new(repr)
1119
0
    }
1120
1121
0
    pub(crate) fn span(&self) -> Span {
1122
0
        self.span
1123
0
    }
1124
1125
1.92M
    pub(crate) fn set_span(&mut self, span: Span) {
1126
1.92M
        self.span = span;
1127
1.92M
    }
1128
1129
0
    pub(crate) fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1130
0
        #[cfg(not(span_locations))]
1131
0
        {
1132
0
            let _ = range;
1133
0
            None
1134
0
        }
1135
0
1136
0
        #[cfg(span_locations)]
1137
0
        {
1138
0
            use core::ops::Bound;
1139
0
1140
0
            let lo = match range.start_bound() {
1141
0
                Bound::Included(start) => {
1142
0
                    let start = u32::try_from(*start).ok()?;
1143
0
                    self.span.lo.checked_add(start)?
1144
0
                }
1145
0
                Bound::Excluded(start) => {
1146
0
                    let start = u32::try_from(*start).ok()?;
1147
0
                    self.span.lo.checked_add(start)?.checked_add(1)?
1148
0
                }
1149
0
                Bound::Unbounded => self.span.lo,
1150
0
            };
1151
0
            let hi = match range.end_bound() {
1152
0
                Bound::Included(end) => {
1153
0
                    let end = u32::try_from(*end).ok()?;
1154
0
                    self.span.lo.checked_add(end)?.checked_add(1)?
1155
0
                }
1156
0
                Bound::Excluded(end) => {
1157
0
                    let end = u32::try_from(*end).ok()?;
1158
0
                    self.span.lo.checked_add(end)?
1159
0
                }
1160
0
                Bound::Unbounded => self.span.hi,
1161
0
            };
1162
0
            if lo <= hi && hi <= self.span.hi {
1163
0
                Some(Span { lo, hi })
1164
0
            } else {
1165
0
                None
1166
0
            }
1167
0
        }
1168
0
    }
1169
}
1170
1171
impl Display for Literal {
1172
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1173
0
        Display::fmt(&self.repr, f)
1174
0
    }
1175
}
1176
1177
impl Debug for Literal {
1178
0
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1179
0
        let mut debug = fmt.debug_struct("Literal");
1180
0
        debug.field("lit", &format_args!("{}", self.repr));
1181
0
        debug_span_field_if_nontrivial(&mut debug, self.span);
1182
0
        debug.finish()
1183
0
    }
1184
}
1185
1186
362k
fn escape_utf8(string: &str, repr: &mut String) {
1187
362k
    let mut chars = string.chars();
1188
20.2M
    while let Some(ch) = chars.next() {
1189
19.8M
        if ch == '\0' {
1190
1.43M
            repr.push_str(
1191
1.43M
                if chars
1192
1.43M
                    .as_str()
1193
1.43M
                    .starts_with(|next| '0' <= next && next <= '7')
1194
                {
1195
                    // circumvent clippy::octal_escapes lint
1196
2.55k
                    r"\x00"
1197
                } else {
1198
1.42M
                    r"\0"
1199
                },
1200
            );
1201
18.4M
        } else if ch == '\'' {
1202
42.1k
            // escape_debug turns this into "\'" which is unnecessary.
1203
42.1k
            repr.push(ch);
1204
18.4M
        } else {
1205
18.4M
            repr.extend(ch.escape_debug());
1206
18.4M
        }
1207
    }
1208
362k
}
1209
1210
#[cfg(feature = "proc-macro")]
1211
pub(crate) trait FromStr2: FromStr<Err = proc_macro::LexError> {
1212
    #[cfg(wrap_proc_macro)]
1213
    fn valid(src: &str) -> bool;
1214
1215
    #[cfg(wrap_proc_macro)]
1216
0
    fn from_str_checked(src: &str) -> Result<Self, imp::LexError> {
1217
0
        // Validate using fallback parser, because rustc is incapable of
1218
0
        // returning a recoverable Err for certain invalid token streams, and
1219
0
        // will instead permanently poison the compilation.
1220
0
        if !Self::valid(src) {
1221
0
            return Err(imp::LexError::CompilerPanic);
1222
0
        }
1223
1224
        // Catch panic to work around https://github.com/rust-lang/rust/issues/58736.
1225
0
        match panic::catch_unwind(|| Self::from_str(src)) {
Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_checked::{closure#0}
Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_checked::{closure#0}
1226
0
            Ok(Ok(ok)) => Ok(ok),
1227
0
            Ok(Err(lex)) => Err(imp::LexError::Compiler(lex)),
1228
0
            Err(_panic) => Err(imp::LexError::CompilerPanic),
1229
        }
1230
0
    }
Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_checked
Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_checked
1231
1232
0
    fn from_str_unchecked(src: &str) -> Self {
1233
0
        Self::from_str(src).unwrap()
1234
0
    }
Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_unchecked
Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_unchecked
1235
}
1236
1237
#[cfg(feature = "proc-macro")]
1238
impl FromStr2 for proc_macro::TokenStream {
1239
    #[cfg(wrap_proc_macro)]
1240
0
    fn valid(src: &str) -> bool {
1241
0
        TokenStream::from_str_checked(src).is_ok()
1242
0
    }
1243
}
1244
1245
#[cfg(feature = "proc-macro")]
1246
impl FromStr2 for proc_macro::Literal {
1247
    #[cfg(wrap_proc_macro)]
1248
0
    fn valid(src: &str) -> bool {
1249
0
        Literal::from_str_checked(src).is_ok()
1250
0
    }
1251
}