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