proc_macro2/
fallback.rs

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