proc_macro2_fallback/
fallback.rs

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