Skip to main content

rustc_expand/
proc_macro_server.rs

1use std::ops::{Bound, Range};
2
3use rustc_ast as ast;
4use rustc_ast::token as tk;
5use rustc_ast::tokenstream::{self, DelimSpacing, Spacing, TokenStream};
6use rustc_ast::util::literal::escape_byte_str_symbol;
7use rustc_ast_pretty::pprust;
8use rustc_data_structures::fx::FxHashMap;
9use rustc_errors::{Diag, ErrorGuaranteed, MultiSpan};
10use rustc_parse::lexer::{StripTokens, nfc_normalize};
11use rustc_parse::parser::Parser;
12use rustc_parse::{exp, new_parser_from_source_str, source_str_to_stream};
13use rustc_proc_macro::bridge::{
14    DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, server,
15};
16use rustc_proc_macro::{Delimiter, Level};
17use rustc_session::Session;
18use rustc_session::parse::ParseSess;
19use rustc_span::def_id::CrateNum;
20use rustc_span::{BytePos, FileName, Pos, Span, Symbol, sym};
21use smallvec::{SmallVec, smallvec};
22
23use crate::base::ExtCtxt;
24
25trait FromInternal<T> {
26    fn from_internal(x: T) -> Self;
27}
28
29trait ToInternal<T> {
30    fn to_internal(self) -> T;
31}
32
33impl FromInternal<tk::Delimiter> for Delimiter {
34    fn from_internal(delim: tk::Delimiter) -> Delimiter {
35        match delim {
36            tk::Delimiter::Parenthesis => Delimiter::Parenthesis,
37            tk::Delimiter::Brace => Delimiter::Brace,
38            tk::Delimiter::Bracket => Delimiter::Bracket,
39            tk::Delimiter::Invisible(_) => Delimiter::None,
40        }
41    }
42}
43
44impl ToInternal<tk::Delimiter> for Delimiter {
45    fn to_internal(self) -> tk::Delimiter {
46        match self {
47            Delimiter::Parenthesis => tk::Delimiter::Parenthesis,
48            Delimiter::Brace => tk::Delimiter::Brace,
49            Delimiter::Bracket => tk::Delimiter::Bracket,
50            Delimiter::None => tk::Delimiter::Invisible(tk::InvisibleOrigin::ProcMacro),
51        }
52    }
53}
54
55impl FromInternal<tk::LitKind> for LitKind {
56    fn from_internal(kind: tk::LitKind) -> Self {
57        match kind {
58            tk::Byte => LitKind::Byte,
59            tk::Char => LitKind::Char,
60            tk::Integer => LitKind::Integer,
61            tk::Float => LitKind::Float,
62            tk::Str => LitKind::Str,
63            tk::StrRaw(n) => LitKind::StrRaw(n),
64            tk::ByteStr => LitKind::ByteStr,
65            tk::ByteStrRaw(n) => LitKind::ByteStrRaw(n),
66            tk::CStr => LitKind::CStr,
67            tk::CStrRaw(n) => LitKind::CStrRaw(n),
68            tk::Err(_guar) => {
69                // This is the only place a `rustc_proc_macro::bridge::LitKind::ErrWithGuar`
70                // is constructed. Note that an `ErrorGuaranteed` is available,
71                // as required. See the comment in `to_internal`.
72                LitKind::ErrWithGuar
73            }
74            tk::Bool => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
75        }
76    }
77}
78
79impl ToInternal<tk::LitKind> for LitKind {
80    fn to_internal(self) -> tk::LitKind {
81        match self {
82            LitKind::Byte => tk::Byte,
83            LitKind::Char => tk::Char,
84            LitKind::Integer => tk::Integer,
85            LitKind::Float => tk::Float,
86            LitKind::Str => tk::Str,
87            LitKind::StrRaw(n) => tk::StrRaw(n),
88            LitKind::ByteStr => tk::ByteStr,
89            LitKind::ByteStrRaw(n) => tk::ByteStrRaw(n),
90            LitKind::CStr => tk::CStr,
91            LitKind::CStrRaw(n) => tk::CStrRaw(n),
92            LitKind::ErrWithGuar => {
93                // This is annoying but valid. `LitKind::ErrWithGuar` would
94                // have an `ErrorGuaranteed` except that type isn't available
95                // in that crate. So we have to fake one. And we don't want to
96                // use a delayed bug because there might be lots of these,
97                // which would be expensive.
98                #[allow(deprecated)]
99                let guar = ErrorGuaranteed::unchecked_error_guaranteed();
100                tk::Err(guar)
101            }
102        }
103    }
104}
105
106impl FromInternal<TokenStream> for Vec<TokenTree<TokenStream, Span, Symbol>> {
107    fn from_internal(stream: TokenStream) -> Self {
108        // Estimate the capacity as `stream.len()` rounded up to the next power
109        // of two to limit the number of required reallocations.
110        let mut trees = Vec::with_capacity(stream.len().next_power_of_two());
111
112        for tree in stream.iter() {
113            let (tk::Token { kind, span }, joint) = match tree.clone() {
114                tokenstream::TokenTree::Delimited(span, _, mut delim, mut stream) => {
115                    // In `mk_delimited` we avoid nesting invisible delimited
116                    // of the same `MetaVarKind`. Here we do the same but
117                    // ignore the `MetaVarKind` because it is discarded when we
118                    // convert it to a `Group`.
119                    while let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = delim
120                        && stream.len() == 1
121                        && let tree = stream.get(0).unwrap()
122                        && let tokenstream::TokenTree::Delimited(_, _, delim2, stream2) = tree
123                        && let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = delim2
124                    {
125                        delim = *delim2;
126                        stream = stream2.clone();
127                    }
128
129                    trees.push(TokenTree::Group(Group {
130                        delimiter: rustc_proc_macro::Delimiter::from_internal(delim),
131                        stream: Some(stream),
132                        span: DelimSpan {
133                            open: span.open,
134                            close: span.close,
135                            entire: span.entire(),
136                        },
137                    }));
138                    continue;
139                }
140                tokenstream::TokenTree::Token(token, spacing) => {
141                    // Do not be tempted to check here that the `spacing`
142                    // values are "correct" w.r.t. the token stream (e.g. that
143                    // `Spacing::Joint` is actually followed by a `Punct` token
144                    // tree). Because the problem in #76399 was introduced that
145                    // way.
146                    //
147                    // This is where the `Hidden` in `JointHidden` applies,
148                    // because the jointness is effectively hidden from proc
149                    // macros.
150                    let joint = match spacing {
151                        Spacing::Alone | Spacing::JointHidden => false,
152                        Spacing::Joint => true,
153                    };
154                    (token, joint)
155                }
156            };
157
158            // Split the operator into one or more `Punct`s, one per character.
159            // The final one inherits the jointness of the original token. Any
160            // before that get `joint = true`.
161            let mut op = |s: &str| {
162                if !s.is_ascii() {
    ::core::panicking::panic("assertion failed: s.is_ascii()")
};assert!(s.is_ascii());
163                trees.extend(s.bytes().enumerate().map(|(i, ch)| {
164                    let is_final = i == s.len() - 1;
165                    // Split the token span into single chars. Unless the span
166                    // is an unusual one, e.g. due to proc macro expansion. We
167                    // determine this by assuming any span with a length that
168                    // matches the operator length is a normal one, and any
169                    // span with a different length is an unusual one.
170                    let span = if (span.hi() - span.lo()).to_usize() == s.len() {
171                        let lo = span.lo() + BytePos::from_usize(i);
172                        let hi = lo + BytePos::from_usize(1);
173                        span.with_lo(lo).with_hi(hi)
174                    } else {
175                        span
176                    };
177                    let joint = if is_final { joint } else { true };
178                    TokenTree::Punct(Punct { ch, joint, span })
179                }));
180            };
181
182            match kind {
183                tk::Eq => op("="),
184                tk::Lt => op("<"),
185                tk::Le => op("<="),
186                tk::EqEq => op("=="),
187                tk::Ne => op("!="),
188                tk::Ge => op(">="),
189                tk::Gt => op(">"),
190                tk::AndAnd => op("&&"),
191                tk::OrOr => op("||"),
192                tk::Bang => op("!"),
193                tk::Tilde => op("~"),
194                tk::Plus => op("+"),
195                tk::Minus => op("-"),
196                tk::Star => op("*"),
197                tk::Slash => op("/"),
198                tk::Percent => op("%"),
199                tk::Caret => op("^"),
200                tk::And => op("&"),
201                tk::Or => op("|"),
202                tk::Shl => op("<<"),
203                tk::Shr => op(">>"),
204                tk::PlusEq => op("+="),
205                tk::MinusEq => op("-="),
206                tk::StarEq => op("*="),
207                tk::SlashEq => op("/="),
208                tk::PercentEq => op("%="),
209                tk::CaretEq => op("^="),
210                tk::AndEq => op("&="),
211                tk::OrEq => op("|="),
212                tk::ShlEq => op("<<="),
213                tk::ShrEq => op(">>="),
214                tk::At => op("@"),
215                tk::Dot => op("."),
216                tk::DotDot => op(".."),
217                tk::DotDotDot => op("..."),
218                tk::DotDotEq => op("..="),
219                tk::Comma => op(","),
220                tk::Semi => op(";"),
221                tk::Colon => op(":"),
222                tk::PathSep => op("::"),
223                tk::RArrow => op("->"),
224                tk::LArrow => op("<-"),
225                tk::FatArrow => op("=>"),
226                tk::Pound => op("#"),
227                tk::Dollar => op("$"),
228                tk::Question => op("?"),
229                tk::SingleQuote => op("'"),
230
231                tk::Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident {
232                    sym,
233                    is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    tk::IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, tk::IdentIsRaw::Yes),
234                    span,
235                })),
236                tk::NtIdent(ident, is_raw) => trees.push(TokenTree::Ident(Ident {
237                    sym: ident.name,
238                    is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    tk::IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, tk::IdentIsRaw::Yes),
239                    span: ident.span,
240                })),
241
242                tk::Lifetime(name, is_raw) => {
243                    let ident = rustc_span::Ident::new(name, span).without_first_quote();
244                    trees.extend([
245                        TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
246                        TokenTree::Ident(Ident {
247                            sym: ident.name,
248                            is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    tk::IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, tk::IdentIsRaw::Yes),
249                            span,
250                        }),
251                    ]);
252                }
253                tk::NtLifetime(ident, is_raw) => {
254                    let stream =
255                        TokenStream::token_alone(tk::Lifetime(ident.name, is_raw), ident.span);
256                    trees.push(TokenTree::Group(Group {
257                        delimiter: rustc_proc_macro::Delimiter::None,
258                        stream: Some(stream),
259                        span: DelimSpan::from_single(span),
260                    }))
261                }
262
263                tk::Literal(tk::Lit { kind, symbol, suffix }) => {
264                    trees.push(TokenTree::Literal(self::Literal {
265                        kind: FromInternal::from_internal(kind),
266                        symbol,
267                        suffix,
268                        span,
269                    }));
270                }
271                tk::DocComment(_, attr_style, data) => {
272                    let mut escaped = String::new();
273                    for ch in data.as_str().chars() {
274                        escaped.extend(ch.escape_debug());
275                    }
276                    let stream = [
277                        tk::Ident(sym::doc, tk::IdentIsRaw::No),
278                        tk::Eq,
279                        tk::TokenKind::lit(tk::Str, Symbol::intern(&escaped), None),
280                    ]
281                    .into_iter()
282                    .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
283                    .collect();
284                    trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
285                    if attr_style == ast::AttrStyle::Inner {
286                        trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
287                    }
288                    trees.push(TokenTree::Group(Group {
289                        delimiter: rustc_proc_macro::Delimiter::Bracket,
290                        stream: Some(stream),
291                        span: DelimSpan::from_single(span),
292                    }));
293                }
294
295                tk::OpenParen
296                | tk::CloseParen
297                | tk::OpenBrace
298                | tk::CloseBrace
299                | tk::OpenBracket
300                | tk::CloseBracket
301                | tk::OpenInvisible(_)
302                | tk::CloseInvisible(_)
303                | tk::Eof => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
304            }
305        }
306        trees
307    }
308}
309
310// We use a `SmallVec` because the output size is always one or two `TokenTree`s.
311impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
312    for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>)
313{
314    fn to_internal(self) -> SmallVec<[tokenstream::TokenTree; 2]> {
315        // The code below is conservative, using `token_alone`/`Spacing::Alone`
316        // in most places. It's hard in general to do better when working at
317        // the token level. When the resulting code is pretty-printed by
318        // `print_tts` the `space_between` function helps avoid a lot of
319        // unnecessary whitespace, so the results aren't too bad.
320        let (tree, rustc) = self;
321        match tree {
322            TokenTree::Punct(Punct { ch, joint, span }) => {
323                let kind = match ch {
324                    b'=' => tk::Eq,
325                    b'<' => tk::Lt,
326                    b'>' => tk::Gt,
327                    b'!' => tk::Bang,
328                    b'~' => tk::Tilde,
329                    b'+' => tk::Plus,
330                    b'-' => tk::Minus,
331                    b'*' => tk::Star,
332                    b'/' => tk::Slash,
333                    b'%' => tk::Percent,
334                    b'^' => tk::Caret,
335                    b'&' => tk::And,
336                    b'|' => tk::Or,
337                    b'@' => tk::At,
338                    b'.' => tk::Dot,
339                    b',' => tk::Comma,
340                    b';' => tk::Semi,
341                    b':' => tk::Colon,
342                    b'#' => tk::Pound,
343                    b'$' => tk::Dollar,
344                    b'?' => tk::Question,
345                    b'\'' => tk::SingleQuote,
346                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
347                };
348                // We never produce `tk::Spacing::JointHidden` here, which
349                // means the pretty-printing of code produced by proc macros is
350                // ugly, with lots of whitespace between tokens. This is
351                // unavoidable because `proc_macro::Spacing` only applies to
352                // `Punct` token trees.
353                {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(if joint {
                tokenstream::TokenTree::token_joint(kind, span)
            } else { tokenstream::TokenTree::token_alone(kind, span) });
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [if joint {
                                tokenstream::TokenTree::token_joint(kind, span)
                            } else {
                                tokenstream::TokenTree::token_alone(kind, span)
                            }])))
    }
}smallvec![if joint {
354                    tokenstream::TokenTree::token_joint(kind, span)
355                } else {
356                    tokenstream::TokenTree::token_alone(kind, span)
357                }]
358            }
359            TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
360                {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(tokenstream::TokenTree::Delimited(tokenstream::DelimSpan {
                    open,
                    close,
                }, DelimSpacing::new(Spacing::Alone, Spacing::Alone),
                delimiter.to_internal(), stream.unwrap_or_default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [tokenstream::TokenTree::Delimited(tokenstream::DelimSpan {
                                    open,
                                    close,
                                }, DelimSpacing::new(Spacing::Alone, Spacing::Alone),
                                delimiter.to_internal(), stream.unwrap_or_default())])))
    }
}smallvec![tokenstream::TokenTree::Delimited(
361                    tokenstream::DelimSpan { open, close },
362                    DelimSpacing::new(Spacing::Alone, Spacing::Alone),
363                    delimiter.to_internal(),
364                    stream.unwrap_or_default(),
365                )]
366            }
367            TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
368                rustc.psess().symbol_gallery.insert(sym, span);
369                {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(tokenstream::TokenTree::token_alone(tk::Ident(sym,
                    is_raw.into()), span));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [tokenstream::TokenTree::token_alone(tk::Ident(sym,
                                    is_raw.into()), span)])))
    }
}smallvec![tokenstream::TokenTree::token_alone(tk::Ident(sym, is_raw.into()), span)]
370            }
371            TokenTree::Literal(self::Literal {
372                kind: self::LitKind::Integer,
373                symbol,
374                suffix,
375                span,
376            }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => {
377                let symbol = Symbol::intern(symbol);
378                let integer = tk::TokenKind::lit(tk::Integer, symbol, suffix);
379                let a = tokenstream::TokenTree::token_joint_hidden(tk::Minus, span);
380                let b = tokenstream::TokenTree::token_alone(integer, span);
381                {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(a);
        vec.push(b);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [a, b])))
    }
}smallvec![a, b]
382            }
383            TokenTree::Literal(self::Literal {
384                kind: self::LitKind::Float,
385                symbol,
386                suffix,
387                span,
388            }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => {
389                let symbol = Symbol::intern(symbol);
390                let float = tk::TokenKind::lit(tk::Float, symbol, suffix);
391                let a = tokenstream::TokenTree::token_joint_hidden(tk::Minus, span);
392                let b = tokenstream::TokenTree::token_alone(float, span);
393                {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(a);
        vec.push(b);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [a, b])))
    }
}smallvec![a, b]
394            }
395            TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
396                {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(tokenstream::TokenTree::token_alone(tk::TokenKind::lit(kind.to_internal(),
                    symbol, suffix), span));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [tokenstream::TokenTree::token_alone(tk::TokenKind::lit(kind.to_internal(),
                                    symbol, suffix), span)])))
    }
}smallvec![tokenstream::TokenTree::token_alone(
397                    tk::TokenKind::lit(kind.to_internal(), symbol, suffix),
398                    span,
399                )]
400            }
401        }
402    }
403}
404
405impl ToInternal<rustc_errors::Level> for Level {
406    fn to_internal(self) -> rustc_errors::Level {
407        match self {
408            Level::Error => rustc_errors::Level::Error,
409            Level::Warning => rustc_errors::Level::Warning,
410            Level::Note => rustc_errors::Level::Note,
411            Level::Help => rustc_errors::Level::Help,
412            _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unknown proc_macro::Level variant: {0:?}", self)));
}unreachable!("unknown proc_macro::Level variant: {:?}", self),
413        }
414    }
415}
416
417fn cancel_diags_into_string(diags: Vec<Diag<'_>>) -> String {
418    let mut messages = diags.into_iter().flat_map(Diag::cancel_into_message);
419    let msg = messages.next().expect("no diagnostic has a message");
420    messages.for_each(|_| ()); // consume iterator to cancel the remaining diagnostics
421    msg
422}
423
424pub(crate) struct Rustc<'a, 'b> {
425    ecx: &'a mut ExtCtxt<'b>,
426    def_site: Span,
427    call_site: Span,
428    mixed_site: Span,
429    krate: CrateNum,
430    rebased_spans: FxHashMap<usize, Span>,
431}
432
433impl<'a, 'b> Rustc<'a, 'b> {
434    pub(crate) fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
435        let expn_data = ecx.current_expansion.id.expn_data();
436        Rustc {
437            def_site: ecx.with_def_site_ctxt(expn_data.def_site),
438            call_site: ecx.with_call_site_ctxt(expn_data.call_site),
439            mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
440            krate: expn_data.macro_def_id.unwrap().krate,
441            rebased_spans: FxHashMap::default(),
442            ecx,
443        }
444    }
445
446    fn sess(&self) -> &Session {
447        &self.ecx.sess
448    }
449
450    fn psess(&self) -> &ParseSess {
451        self.ecx.psess()
452    }
453}
454
455impl server::Server for Rustc<'_, '_> {
456    type TokenStream = TokenStream;
457    type Span = Span;
458    type Symbol = Symbol;
459
460    fn globals(&mut self) -> ExpnGlobals<Self::Span> {
461        ExpnGlobals {
462            def_site: self.def_site,
463            call_site: self.call_site,
464            mixed_site: self.mixed_site,
465        }
466    }
467
468    fn intern_symbol(string: &str) -> Self::Symbol {
469        Symbol::intern(string)
470    }
471
472    fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {
473        f(symbol.as_str())
474    }
475
476    fn injected_env_var(&mut self, var: &str) -> Option<String> {
477        self.ecx.sess.opts.logical_env.get(var).cloned()
478    }
479
480    fn track_env_var(&mut self, var: &str, value: Option<&str>) {
481        self.ecx
482            .sess
483            .env_depinfo
484            .borrow_mut()
485            .insert((Symbol::intern(var), value.map(Symbol::intern)));
486    }
487
488    fn track_path(&mut self, path: &str) {
489        self.ecx.sess.file_depinfo.borrow_mut().insert(Symbol::intern(path));
490    }
491
492    fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, String> {
493        let name = FileName::proc_macro_source_code(s);
494
495        let mut parser = rustc_errors::catch_fatal_errors(|| {
496            new_parser_from_source_str(self.psess(), name, s.to_owned(), StripTokens::Nothing)
497        })
498        .map_err(|_| String::from("failed to parse to literal"))?
499        .map_err(cancel_diags_into_string)?;
500
501        let first_span = parser.token.span.data();
502        let minus_present = parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Minus,
    token_type: ::rustc_parse::parser::token_type::TokenType::Minus,
}exp!(Minus));
503
504        let lit_span = parser.token.span.data();
505        let tk::Literal(mut lit) = parser.token.kind else {
506            return Err("not a literal".to_string());
507        };
508
509        // Check no comment or whitespace surrounding the (possibly negative)
510        // literal, or more tokens after it.
511        if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
512            return Err("comment or whitespace around literal".to_string());
513        }
514
515        if minus_present {
516            // If minus is present, check no comment or whitespace in between it
517            // and the literal token.
518            if first_span.hi.0 != lit_span.lo.0 {
519                return Err("comment or whitespace after minus".to_string());
520            }
521
522            // Check literal is a kind we allow to be negated in a proc macro token.
523            match lit.kind {
524                tk::LitKind::Bool
525                | tk::LitKind::Byte
526                | tk::LitKind::Char
527                | tk::LitKind::Str
528                | tk::LitKind::StrRaw(_)
529                | tk::LitKind::ByteStr
530                | tk::LitKind::ByteStrRaw(_)
531                | tk::LitKind::CStr
532                | tk::LitKind::CStrRaw(_)
533                | tk::LitKind::Err(_) => {
534                    return Err("non-numeric literal may not be negated".to_string());
535                }
536                tk::LitKind::Integer | tk::LitKind::Float => {}
537            }
538
539            // Synthesize a new symbol that includes the minus sign.
540            let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
541            lit = tk::Lit::new(lit.kind, symbol, lit.suffix);
542        }
543        let tk::Lit { kind, symbol, suffix } = lit;
544        Ok(Literal {
545            kind: FromInternal::from_internal(kind),
546            symbol,
547            suffix,
548            span: self.call_site,
549        })
550    }
551
552    fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
553        let message = rustc_errors::DiagMessage::from(diagnostic.message);
554        let mut diag: Diag<'_, ()> =
555            Diag::new(self.psess().dcx(), diagnostic.level.to_internal(), message);
556        diag.span(MultiSpan::from_spans(diagnostic.spans));
557        for child in diagnostic.children {
558            diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));
559        }
560        diag.emit();
561    }
562
563    fn ts_drop(&mut self, stream: Self::TokenStream) {
564        drop(stream);
565    }
566
567    fn ts_clone(&mut self, stream: &Self::TokenStream) -> Self::TokenStream {
568        stream.clone()
569    }
570
571    fn ts_is_empty(&mut self, stream: &Self::TokenStream) -> bool {
572        stream.is_empty()
573    }
574
575    fn ts_from_str(&mut self, src: &str) -> Result<Self::TokenStream, String> {
576        rustc_errors::catch_fatal_errors(|| {
577            source_str_to_stream(
578                self.psess(),
579                FileName::proc_macro_source_code(src),
580                src.to_string(),
581                Some(self.call_site),
582            )
583        })
584        .map_err(|_| String::from("failed to parse to tokenstream"))?
585        .map_err(cancel_diags_into_string)
586    }
587
588    fn ts_to_string(&mut self, stream: &Self::TokenStream) -> String {
589        pprust::tts_to_string(stream)
590    }
591
592    fn ts_expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
593        // Parse the expression from our tokenstream.
594        let expr = try {
595            let mut p = Parser::new(self.psess(), stream.clone(), Some("proc_macro expand expr"));
596            let expr = p.parse_expr()?;
597            if p.token != tk::Eof {
598                p.unexpected()?;
599            }
600            expr
601        };
602        let expr = expr.map_err(|err| {
603            err.emit();
604        })?;
605
606        // Perform eager expansion on the expression.
607        let expr = self
608            .ecx
609            .expander()
610            .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
611            .make_expr();
612
613        // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
614        // This may be relaxed in the future.
615        // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
616        // be recovered in the general case.
617        match &expr.kind {
618            ast::ExprKind::Lit(token_lit) if token_lit.kind == tk::Bool => {
619                Ok(tokenstream::TokenStream::token_alone(
620                    tk::Ident(token_lit.symbol, tk::IdentIsRaw::No),
621                    expr.span,
622                ))
623            }
624            ast::ExprKind::Lit(token_lit) => {
625                Ok(tokenstream::TokenStream::token_alone(tk::Literal(*token_lit), expr.span))
626            }
627            ast::ExprKind::IncludedBytes(byte_sym) => {
628                let lit =
629                    tk::Lit::new(tk::ByteStr, escape_byte_str_symbol(byte_sym.as_byte_str()), None);
630                Ok(tokenstream::TokenStream::token_alone(tk::TokenKind::Literal(lit), expr.span))
631            }
632            ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
633                ast::ExprKind::Lit(token_lit) => match token_lit {
634                    tk::Lit { kind: tk::Integer | tk::Float, .. } => {
635                        Ok(Self::TokenStream::from_iter([
636                            // FIXME: The span of the `-` token is lost when
637                            // parsing, so we cannot faithfully recover it here.
638                            tokenstream::TokenTree::token_joint_hidden(tk::Minus, e.span),
639                            tokenstream::TokenTree::token_alone(tk::Literal(*token_lit), e.span),
640                        ]))
641                    }
642                    _ => Err(()),
643                },
644                _ => Err(()),
645            },
646            _ => Err(()),
647        }
648    }
649
650    fn ts_from_token_tree(
651        &mut self,
652        tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
653    ) -> Self::TokenStream {
654        Self::TokenStream::new((tree, &mut *self).to_internal().into_iter().collect::<Vec<_>>())
655    }
656
657    fn ts_concat_trees(
658        &mut self,
659        base: Option<Self::TokenStream>,
660        trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
661    ) -> Self::TokenStream {
662        let mut stream = base.unwrap_or_default();
663        for tree in trees {
664            for tt in (tree, &mut *self).to_internal() {
665                stream.push_tree_with_gluing(tt);
666            }
667        }
668        stream
669    }
670
671    fn ts_concat_streams(
672        &mut self,
673        base: Option<Self::TokenStream>,
674        streams: Vec<Self::TokenStream>,
675    ) -> Self::TokenStream {
676        let mut stream = base.unwrap_or_default();
677        for s in streams {
678            stream.push_stream_with_gluing(s);
679        }
680        stream
681    }
682
683    fn ts_into_trees(
684        &mut self,
685        stream: Self::TokenStream,
686    ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
687        FromInternal::from_internal(stream)
688    }
689
690    fn span_debug(&mut self, span: Self::Span) -> String {
691        if self.ecx.ecfg.span_debug {
692            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", span))
    })format!("{span:?}")
693        } else {
694            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?} bytes({1}..{2})",
                span.ctxt(), span.lo().0, span.hi().0))
    })format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
695        }
696    }
697
698    fn span_file(&mut self, span: Self::Span) -> String {
699        self.psess()
700            .source_map()
701            .lookup_char_pos(span.lo())
702            .file
703            .name
704            .prefer_remapped_unconditionally()
705            .to_string()
706    }
707
708    fn span_local_file(&mut self, span: Self::Span) -> Option<String> {
709        self.psess()
710            .source_map()
711            .lookup_char_pos(span.lo())
712            .file
713            .name
714            .clone()
715            .into_local_path()
716            .map(|p| {
717                p.to_str()
718                    .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
719                    .to_string()
720            })
721    }
722
723    fn span_parent(&mut self, span: Self::Span) -> Option<Self::Span> {
724        span.parent_callsite()
725    }
726
727    fn span_source(&mut self, span: Self::Span) -> Self::Span {
728        span.source_callsite()
729    }
730
731    fn span_byte_range(&mut self, span: Self::Span) -> Range<usize> {
732        let source_map = self.psess().source_map();
733
734        let relative_start_pos = source_map.lookup_byte_offset(span.lo()).pos;
735        let relative_end_pos = source_map.lookup_byte_offset(span.hi()).pos;
736
737        Range { start: relative_start_pos.0 as usize, end: relative_end_pos.0 as usize }
738    }
739    fn span_start(&mut self, span: Self::Span) -> Self::Span {
740        span.shrink_to_lo()
741    }
742
743    fn span_end(&mut self, span: Self::Span) -> Self::Span {
744        span.shrink_to_hi()
745    }
746
747    fn span_line(&mut self, span: Self::Span) -> usize {
748        let loc = self.psess().source_map().lookup_char_pos(span.lo());
749        loc.line
750    }
751
752    fn span_column(&mut self, span: Self::Span) -> usize {
753        let loc = self.psess().source_map().lookup_char_pos(span.lo());
754        loc.col.to_usize() + 1
755    }
756
757    fn span_join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
758        let self_loc = self.psess().source_map().lookup_char_pos(first.lo());
759        let other_loc = self.psess().source_map().lookup_char_pos(second.lo());
760
761        if self_loc.file.stable_id != other_loc.file.stable_id {
762            return None;
763        }
764
765        Some(first.to(second))
766    }
767
768    fn span_subspan(
769        &mut self,
770        span: Self::Span,
771        start: Bound<usize>,
772        end: Bound<usize>,
773    ) -> Option<Self::Span> {
774        let length = span.hi().to_usize() - span.lo().to_usize();
775
776        let start = match start {
777            Bound::Included(lo) => lo,
778            Bound::Excluded(lo) => lo.checked_add(1)?,
779            Bound::Unbounded => 0,
780        };
781
782        let end = match end {
783            Bound::Included(hi) => hi.checked_add(1)?,
784            Bound::Excluded(hi) => hi,
785            Bound::Unbounded => length,
786        };
787
788        // Bounds check the values, preventing addition overflow and OOB spans.
789        if start > u32::MAX as usize
790            || end > u32::MAX as usize
791            || (u32::MAX - start as u32) < span.lo().to_u32()
792            || (u32::MAX - end as u32) < span.lo().to_u32()
793            || start >= end
794            || end > length
795        {
796            return None;
797        }
798
799        let new_lo = span.lo() + BytePos::from_usize(start);
800        let new_hi = span.lo() + BytePos::from_usize(end);
801        Some(span.with_lo(new_lo).with_hi(new_hi))
802    }
803
804    fn span_resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
805        span.with_ctxt(at.ctxt())
806    }
807
808    fn span_source_text(&mut self, span: Self::Span) -> Option<String> {
809        self.psess().source_map().span_to_snippet(span).ok()
810    }
811
812    /// Saves the provided span into the metadata of
813    /// *the crate we are currently compiling*, which must
814    /// be a proc-macro crate. This id can be passed to
815    /// `recover_proc_macro_span` when our current crate
816    /// is *run* as a proc-macro.
817    ///
818    /// Let's suppose that we have two crates - `my_client`
819    /// and `my_proc_macro`. The `my_proc_macro` crate
820    /// contains a procedural macro `my_macro`, which
821    /// is implemented as: `quote! { "hello" }`
822    ///
823    /// When we *compile* `my_proc_macro`, we will execute
824    /// the `quote` proc-macro. This will save the span of
825    /// "hello" into the metadata of `my_proc_macro`. As a result,
826    /// the body of `my_proc_macro` (after expansion) will end
827    /// up containing a call that looks like this:
828    /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
829    ///
830    /// where `0` is the id returned by this function.
831    /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
832    /// the call to `recover_proc_macro_span` will load the corresponding
833    /// span from the metadata of `my_proc_macro` (which we have access to,
834    /// since we've loaded `my_proc_macro` from disk in order to execute it).
835    /// In this way, we have obtained a span pointing into `my_proc_macro`
836    fn span_save_span(&mut self, span: Self::Span) -> usize {
837        self.sess().save_proc_macro_span(span)
838    }
839
840    fn span_recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
841        let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
842        *self.rebased_spans.entry(id).or_insert_with(|| {
843            // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
844            // replace it with a def-site context until we are encoding it properly.
845            resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
846        })
847    }
848
849    fn symbol_normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
850        let sym = nfc_normalize(string);
851        if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
852    }
853}