Skip to main content

rustc_expand/
proc_macro_server.rs

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