Skip to main content

rustc_expand/
base.rs

1use std::any::Any;
2use std::default::Default;
3use std::iter;
4use std::path::Component::Prefix;
5use std::path::PathBuf;
6use std::rc::Rc;
7use std::sync::Arc;
8
9use rustc_ast::attr::MarkedAttrs;
10use rustc_ast::tokenstream::TokenStream;
11use rustc_ast::visit::{AssocCtxt, Visitor};
12use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind, Safety};
13use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
14use rustc_data_structures::sync;
15use rustc_errors::{BufferedEarlyLint, DiagCtxtHandle, ErrorGuaranteed, PResult};
16use rustc_feature::Features;
17use rustc_hir as hir;
18use rustc_hir::attrs::{CfgEntry, CollapseMacroDebuginfo, Deprecation};
19use rustc_hir::def::MacroKinds;
20use rustc_hir::limit::Limit;
21use rustc_hir::{Stability, find_attr};
22use rustc_lint_defs::RegisteredTools;
23use rustc_parse::MACRO_ARGUMENTS;
24use rustc_parse::parser::Parser;
25use rustc_session::Session;
26use rustc_session::parse::ParseSess;
27use rustc_span::def_id::{CrateNum, DefId, LocalDefId, ModId};
28use rustc_span::edition::Edition;
29use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind};
30use rustc_span::source_map::SourceMap;
31use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw};
32use smallvec::{SmallVec, smallvec};
33use thin_vec::ThinVec;
34
35use crate::diagnostics;
36use crate::expand::{self, AstFragment, Invocation};
37use crate::mbe::macro_rules::ParserAnyMacro;
38use crate::module::DirOwnership;
39use crate::stats::MacroStat;
40
41// When adding new variants, make sure to
42// adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
43// to use `assign_id!`
44#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Annotatable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Annotatable::Item(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
                    &__self_0),
            Annotatable::AssocItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AssocItem", __self_0, &__self_1),
            Annotatable::ForeignItem(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ForeignItem", &__self_0),
            Annotatable::Stmt(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Stmt",
                    &__self_0),
            Annotatable::Expr(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Expr",
                    &__self_0),
            Annotatable::Arm(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Arm",
                    &__self_0),
            Annotatable::ExprField(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ExprField", &__self_0),
            Annotatable::PatField(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PatField", &__self_0),
            Annotatable::GenericParam(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "GenericParam", &__self_0),
            Annotatable::Param(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
                    &__self_0),
            Annotatable::FieldDef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "FieldDef", &__self_0),
            Annotatable::Variant(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Variant", &__self_0),
            Annotatable::WherePredicate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "WherePredicate", &__self_0),
            Annotatable::Crate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Crate",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Annotatable {
    #[inline]
    fn clone(&self) -> Annotatable {
        match self {
            Annotatable::Item(__self_0) =>
                Annotatable::Item(::core::clone::Clone::clone(__self_0)),
            Annotatable::AssocItem(__self_0, __self_1) =>
                Annotatable::AssocItem(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Annotatable::ForeignItem(__self_0) =>
                Annotatable::ForeignItem(::core::clone::Clone::clone(__self_0)),
            Annotatable::Stmt(__self_0) =>
                Annotatable::Stmt(::core::clone::Clone::clone(__self_0)),
            Annotatable::Expr(__self_0) =>
                Annotatable::Expr(::core::clone::Clone::clone(__self_0)),
            Annotatable::Arm(__self_0) =>
                Annotatable::Arm(::core::clone::Clone::clone(__self_0)),
            Annotatable::ExprField(__self_0) =>
                Annotatable::ExprField(::core::clone::Clone::clone(__self_0)),
            Annotatable::PatField(__self_0) =>
                Annotatable::PatField(::core::clone::Clone::clone(__self_0)),
            Annotatable::GenericParam(__self_0) =>
                Annotatable::GenericParam(::core::clone::Clone::clone(__self_0)),
            Annotatable::Param(__self_0) =>
                Annotatable::Param(::core::clone::Clone::clone(__self_0)),
            Annotatable::FieldDef(__self_0) =>
                Annotatable::FieldDef(::core::clone::Clone::clone(__self_0)),
            Annotatable::Variant(__self_0) =>
                Annotatable::Variant(::core::clone::Clone::clone(__self_0)),
            Annotatable::WherePredicate(__self_0) =>
                Annotatable::WherePredicate(::core::clone::Clone::clone(__self_0)),
            Annotatable::Crate(__self_0) =>
                Annotatable::Crate(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
45pub enum Annotatable {
46    Item(Box<ast::Item>),
47    AssocItem(Box<ast::AssocItem>, AssocCtxt),
48    ForeignItem(Box<ast::ForeignItem>),
49    Stmt(Box<ast::Stmt>),
50    Expr(Box<ast::Expr>),
51    Arm(ast::Arm),
52    ExprField(ast::ExprField),
53    PatField(ast::PatField),
54    GenericParam(ast::GenericParam),
55    Param(ast::Param),
56    FieldDef(ast::FieldDef),
57    Variant(ast::Variant),
58    WherePredicate(ast::WherePredicate),
59    Crate(ast::Crate),
60}
61
62impl Annotatable {
63    pub fn span(&self) -> Span {
64        match self {
65            Annotatable::Item(item) => item.span,
66            Annotatable::AssocItem(assoc_item, _) => assoc_item.span,
67            Annotatable::ForeignItem(foreign_item) => foreign_item.span,
68            Annotatable::Stmt(stmt) => stmt.span,
69            Annotatable::Expr(expr) => expr.span,
70            Annotatable::Arm(arm) => arm.span,
71            Annotatable::ExprField(field) => field.span,
72            Annotatable::PatField(fp) => fp.pat.span,
73            Annotatable::GenericParam(gp) => gp.ident.span,
74            Annotatable::Param(p) => p.span,
75            Annotatable::FieldDef(sf) => sf.span,
76            Annotatable::Variant(v) => v.span,
77            Annotatable::WherePredicate(wp) => wp.span,
78            Annotatable::Crate(c) => c.spans.inner_span,
79        }
80    }
81
82    pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
83        match self {
84            Annotatable::Item(item) => item.visit_attrs(f),
85            Annotatable::AssocItem(assoc_item, _) => assoc_item.visit_attrs(f),
86            Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
87            Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
88            Annotatable::Expr(expr) => expr.visit_attrs(f),
89            Annotatable::Arm(arm) => arm.visit_attrs(f),
90            Annotatable::ExprField(field) => field.visit_attrs(f),
91            Annotatable::PatField(fp) => fp.visit_attrs(f),
92            Annotatable::GenericParam(gp) => gp.visit_attrs(f),
93            Annotatable::Param(p) => p.visit_attrs(f),
94            Annotatable::FieldDef(sf) => sf.visit_attrs(f),
95            Annotatable::Variant(v) => v.visit_attrs(f),
96            Annotatable::WherePredicate(wp) => wp.visit_attrs(f),
97            Annotatable::Crate(c) => c.visit_attrs(f),
98        }
99    }
100
101    pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) -> V::Result {
102        match self {
103            Annotatable::Item(item) => visitor.visit_item(item),
104            Annotatable::AssocItem(item, ctxt) => visitor.visit_assoc_item(item, *ctxt),
105            Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
106            Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
107            Annotatable::Expr(expr) => visitor.visit_expr(expr),
108            Annotatable::Arm(arm) => visitor.visit_arm(arm),
109            Annotatable::ExprField(field) => visitor.visit_expr_field(field),
110            Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
111            Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
112            Annotatable::Param(p) => visitor.visit_param(p),
113            Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
114            Annotatable::Variant(v) => visitor.visit_variant(v),
115            Annotatable::WherePredicate(wp) => visitor.visit_where_predicate(wp),
116            Annotatable::Crate(c) => visitor.visit_crate(c),
117        }
118    }
119
120    pub fn to_tokens(&self) -> TokenStream {
121        match self {
122            Annotatable::Item(node) => TokenStream::from_ast(node),
123            Annotatable::AssocItem(node, _) => TokenStream::from_ast(node),
124            Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
125            Annotatable::Stmt(node) => {
126                if !!#[allow(non_exhaustive_omitted_patterns)] match node.kind {
                ast::StmtKind::Empty => true,
                _ => false,
            } {
    ::core::panicking::panic("assertion failed: !matches!(node.kind, ast::StmtKind::Empty)")
};assert!(!matches!(node.kind, ast::StmtKind::Empty));
127                TokenStream::from_ast(node)
128            }
129            Annotatable::Expr(node) => TokenStream::from_ast(node),
130            Annotatable::Arm(..)
131            | Annotatable::ExprField(..)
132            | Annotatable::PatField(..)
133            | Annotatable::GenericParam(..)
134            | Annotatable::Param(..)
135            | Annotatable::FieldDef(..)
136            | Annotatable::Variant(..)
137            | Annotatable::WherePredicate(..)
138            | Annotatable::Crate(..) => { ::core::panicking::panic_fmt(format_args!("unexpected annotatable")); }panic!("unexpected annotatable"),
139        }
140    }
141
142    pub fn expect_item(self) -> Box<ast::Item> {
143        match self {
144            Annotatable::Item(i) => i,
145            _ => { ::core::panicking::panic_fmt(format_args!("expected Item")); }panic!("expected Item"),
146        }
147    }
148
149    pub fn expect_trait_item(self) -> Box<ast::AssocItem> {
150        match self {
151            Annotatable::AssocItem(i, AssocCtxt::Trait) => i,
152            _ => { ::core::panicking::panic_fmt(format_args!("expected trait item")); }panic!("expected trait item"),
153        }
154    }
155
156    pub fn expect_impl_item(self) -> Box<ast::AssocItem> {
157        match self {
158            Annotatable::AssocItem(i, AssocCtxt::Impl { .. }) => i,
159            _ => { ::core::panicking::panic_fmt(format_args!("expected impl item")); }panic!("expected impl item"),
160        }
161    }
162
163    pub fn expect_foreign_item(self) -> Box<ast::ForeignItem> {
164        match self {
165            Annotatable::ForeignItem(i) => i,
166            _ => { ::core::panicking::panic_fmt(format_args!("expected foreign item")); }panic!("expected foreign item"),
167        }
168    }
169
170    pub fn expect_stmt(self) -> ast::Stmt {
171        match self {
172            Annotatable::Stmt(stmt) => *stmt,
173            _ => { ::core::panicking::panic_fmt(format_args!("expected statement")); }panic!("expected statement"),
174        }
175    }
176
177    pub fn expect_expr(self) -> Box<ast::Expr> {
178        match self {
179            Annotatable::Expr(expr) => expr,
180            _ => { ::core::panicking::panic_fmt(format_args!("expected expression")); }panic!("expected expression"),
181        }
182    }
183
184    pub fn expect_arm(self) -> ast::Arm {
185        match self {
186            Annotatable::Arm(arm) => arm,
187            _ => { ::core::panicking::panic_fmt(format_args!("expected match arm")); }panic!("expected match arm"),
188        }
189    }
190
191    pub fn expect_expr_field(self) -> ast::ExprField {
192        match self {
193            Annotatable::ExprField(field) => field,
194            _ => { ::core::panicking::panic_fmt(format_args!("expected field")); }panic!("expected field"),
195        }
196    }
197
198    pub fn expect_pat_field(self) -> ast::PatField {
199        match self {
200            Annotatable::PatField(fp) => fp,
201            _ => { ::core::panicking::panic_fmt(format_args!("expected field pattern")); }panic!("expected field pattern"),
202        }
203    }
204
205    pub fn expect_generic_param(self) -> ast::GenericParam {
206        match self {
207            Annotatable::GenericParam(gp) => gp,
208            _ => { ::core::panicking::panic_fmt(format_args!("expected generic parameter")); }panic!("expected generic parameter"),
209        }
210    }
211
212    pub fn expect_param(self) -> ast::Param {
213        match self {
214            Annotatable::Param(param) => param,
215            _ => { ::core::panicking::panic_fmt(format_args!("expected parameter")); }panic!("expected parameter"),
216        }
217    }
218
219    pub fn expect_field_def(self) -> ast::FieldDef {
220        match self {
221            Annotatable::FieldDef(sf) => sf,
222            _ => { ::core::panicking::panic_fmt(format_args!("expected struct field")); }panic!("expected struct field"),
223        }
224    }
225
226    pub fn expect_variant(self) -> ast::Variant {
227        match self {
228            Annotatable::Variant(v) => v,
229            _ => { ::core::panicking::panic_fmt(format_args!("expected variant")); }panic!("expected variant"),
230        }
231    }
232
233    pub fn expect_where_predicate(self) -> ast::WherePredicate {
234        match self {
235            Annotatable::WherePredicate(wp) => wp,
236            _ => { ::core::panicking::panic_fmt(format_args!("expected where predicate")); }panic!("expected where predicate"),
237        }
238    }
239
240    pub fn expect_crate(self) -> ast::Crate {
241        match self {
242            Annotatable::Crate(krate) => krate,
243            _ => { ::core::panicking::panic_fmt(format_args!("expected krate")); }panic!("expected krate"),
244        }
245    }
246}
247
248/// Result of an expansion that may need to be retried.
249/// Consider using this for non-`MultiItemModifier` expanders as well.
250pub enum ExpandResult<T, U> {
251    /// Expansion produced a result (possibly dummy).
252    Ready(T),
253    /// Expansion could not produce a result and needs to be retried.
254    Retry(U),
255}
256
257impl<T, U> ExpandResult<T, U> {
258    pub fn map<E, F: FnOnce(T) -> E>(self, f: F) -> ExpandResult<E, U> {
259        match self {
260            ExpandResult::Ready(t) => ExpandResult::Ready(f(t)),
261            ExpandResult::Retry(u) => ExpandResult::Retry(u),
262        }
263    }
264}
265
266impl<'cx> MacroExpanderResult<'cx> {
267    /// Creates a [`MacroExpanderResult::Ready`] from a [`TokenStream`].
268    ///
269    /// The `TokenStream` is forwarded without any expansion.
270    pub fn from_tts(
271        cx: &'cx mut ExtCtxt<'_>,
272        tts: TokenStream,
273        site_span: Span,
274        arm_span: Span,
275        macro_ident: Ident,
276    ) -> Self {
277        let parser = ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, macro_ident, &[], &[]);
278        ExpandResult::Ready(Box::new(parser))
279    }
280}
281
282pub trait MultiItemModifier {
283    /// `meta_item` is the attribute, and `item` is the item being modified.
284    fn expand(
285        &self,
286        ecx: &mut ExtCtxt<'_>,
287        span: Span,
288        meta_item: &ast::MetaItem,
289        item: Annotatable,
290        is_derive_const: bool,
291    ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
292}
293
294impl<F> MultiItemModifier for F
295where
296    F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
297{
298    fn expand(
299        &self,
300        ecx: &mut ExtCtxt<'_>,
301        span: Span,
302        meta_item: &ast::MetaItem,
303        item: Annotatable,
304        _is_derive_const: bool,
305    ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
306        ExpandResult::Ready(self(ecx, span, meta_item, item))
307    }
308}
309
310pub trait BangProcMacro {
311    fn expand<'cx>(
312        &self,
313        ecx: &'cx mut ExtCtxt<'_>,
314        span: Span,
315        ts: TokenStream,
316    ) -> Result<TokenStream, ErrorGuaranteed>;
317}
318
319impl<F> BangProcMacro for F
320where
321    F: Fn(&mut ExtCtxt<'_>, Span, TokenStream) -> Result<TokenStream, ErrorGuaranteed>,
322{
323    fn expand<'cx>(
324        &self,
325        ecx: &'cx mut ExtCtxt<'_>,
326        span: Span,
327        ts: TokenStream,
328    ) -> Result<TokenStream, ErrorGuaranteed> {
329        // FIXME setup implicit context in TLS before calling self.
330        self(ecx, span, ts)
331    }
332}
333
334pub trait AttrProcMacro {
335    fn expand<'cx>(
336        &self,
337        ecx: &'cx mut ExtCtxt<'_>,
338        span: Span,
339        annotation: TokenStream,
340        annotated: TokenStream,
341    ) -> Result<TokenStream, ErrorGuaranteed>;
342
343    // Default implementation for safe attributes; override if the attribute can be unsafe.
344    fn expand_with_safety<'cx>(
345        &self,
346        ecx: &'cx mut ExtCtxt<'_>,
347        safety: Safety,
348        span: Span,
349        annotation: TokenStream,
350        annotated: TokenStream,
351    ) -> Result<TokenStream, ErrorGuaranteed> {
352        if let Safety::Unsafe(span) = safety {
353            ecx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute");
354        }
355        self.expand(ecx, span, annotation, annotated)
356    }
357}
358
359impl<F> AttrProcMacro for F
360where
361    F: Fn(TokenStream, TokenStream) -> TokenStream,
362{
363    fn expand<'cx>(
364        &self,
365        _ecx: &'cx mut ExtCtxt<'_>,
366        _span: Span,
367        annotation: TokenStream,
368        annotated: TokenStream,
369    ) -> Result<TokenStream, ErrorGuaranteed> {
370        // FIXME setup implicit context in TLS before calling self.
371        Ok(self(annotation, annotated))
372    }
373}
374
375/// Represents a thing that maps token trees to Macro Results
376pub trait TTMacroExpander: Any {
377    fn expand<'cx, 'a: 'cx>(
378        &'a self,
379        ecx: &'cx mut ExtCtxt<'_>,
380        span: Span,
381        input: TokenStream,
382    ) -> MacroExpanderResult<'cx>;
383}
384
385pub type MacroExpanderResult<'cx> = ExpandResult<Box<dyn MacResult + 'cx>, ()>;
386
387pub type MacroExpanderFn =
388    for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>;
389
390impl<F: 'static> TTMacroExpander for F
391where
392    F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>,
393{
394    fn expand<'cx, 'a: 'cx>(
395        &'a self,
396        ecx: &'cx mut ExtCtxt<'_>,
397        span: Span,
398        input: TokenStream,
399    ) -> MacroExpanderResult<'cx> {
400        self(ecx, span, input)
401    }
402}
403
404pub trait GlobDelegationExpander {
405    fn expand(&self, ecx: &mut ExtCtxt<'_>) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()>;
406}
407
408fn make_stmts_default(expr: Option<Box<ast::Expr>>) -> Option<SmallVec<[ast::Stmt; 1]>> {
409    expr.map(|e| {
410        {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(ast::Stmt {
                id: ast::DUMMY_NODE_ID,
                span: e.span,
                kind: ast::StmtKind::Expr(e),
            });
        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(),
                    [ast::Stmt {
                                id: ast::DUMMY_NODE_ID,
                                span: e.span,
                                kind: ast::StmtKind::Expr(e),
                            }])))
    }
}smallvec![ast::Stmt { id: ast::DUMMY_NODE_ID, span: e.span, kind: ast::StmtKind::Expr(e) }]
411    })
412}
413
414/// The result of a macro expansion. The return values of the various
415/// methods are spliced into the AST at the callsite of the macro.
416pub trait MacResult {
417    /// Creates an expression.
418    fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
419        None
420    }
421
422    /// Creates zero or more items.
423    fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
424        None
425    }
426
427    /// Creates zero or more impl items.
428    fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
429        None
430    }
431
432    /// Creates zero or more impl items.
433    fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
434        None
435    }
436
437    /// Creates zero or more trait items.
438    fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
439        None
440    }
441
442    /// Creates zero or more items in an `extern {}` block
443    fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
444        None
445    }
446
447    /// Creates a pattern.
448    fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
449        None
450    }
451
452    /// Creates zero or more statements.
453    ///
454    /// By default this attempts to create an expression statement,
455    /// returning None if that fails.
456    fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
457        make_stmts_default(self.make_expr())
458    }
459
460    fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
461        None
462    }
463
464    fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
465        None
466    }
467
468    fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
469        None
470    }
471
472    fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
473        None
474    }
475
476    fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
477        None
478    }
479
480    fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
481        None
482    }
483
484    fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
485        None
486    }
487
488    fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
489        None
490    }
491
492    fn make_where_predicates(self: Box<Self>) -> Option<SmallVec<[ast::WherePredicate; 1]>> {
493        None
494    }
495
496    fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
497        // Fn-like macros cannot produce a crate.
498        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
499    }
500}
501
502/// `MacResult` implementation for the common case where you've already
503/// built each form of AST that you might return.
504#[derive(#[automatically_derived]
impl ::core::default::Default for MacEager {
    #[inline]
    fn default() -> MacEager {
        MacEager {
            expr: ::core::default::Default::default(),
            items: ::core::default::Default::default(),
            ty: ::core::default::Default::default(),
        }
    }
}Default)]
505pub struct MacEager {
506    pub expr: Option<Box<ast::Expr>>,
507    pub items: Option<SmallVec<[Box<ast::Item>; 1]>>,
508    pub ty: Option<Box<ast::Ty>>,
509}
510
511impl MacEager {
512    pub fn expr(v: Box<ast::Expr>) -> Box<dyn MacResult> {
513        Box::new(MacEager { expr: Some(v), ..Default::default() })
514    }
515
516    pub fn items(v: SmallVec<[Box<ast::Item>; 1]>) -> Box<dyn MacResult> {
517        Box::new(MacEager { items: Some(v), ..Default::default() })
518    }
519
520    pub fn ty(v: Box<ast::Ty>) -> Box<dyn MacResult> {
521        Box::new(MacEager { ty: Some(v), ..Default::default() })
522    }
523}
524
525impl MacResult for MacEager {
526    fn make_expr(self: Box<Self>) -> Option<Box<ast::Expr>> {
527        self.expr
528    }
529
530    fn make_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
531        self.items
532    }
533
534    fn make_pat(self: Box<Self>) -> Option<Box<ast::Pat>> {
535        if let Some(e) = self.expr {
536            if #[allow(non_exhaustive_omitted_patterns)] match e.kind {
    ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_) => true,
    _ => false,
}matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
537                return Some(Box::new(ast::Pat {
538                    id: ast::DUMMY_NODE_ID,
539                    span: e.span,
540                    kind: PatKind::Expr(e),
541                }));
542            }
543        }
544        None
545    }
546
547    fn make_ty(self: Box<Self>) -> Option<Box<ast::Ty>> {
548        self.ty
549    }
550}
551
552/// Fill-in macro expansion result, to allow compilation to continue
553/// after hitting errors.
554#[derive(#[automatically_derived]
impl ::core::marker::Copy for DummyResult { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DummyResult {
    #[inline]
    fn clone(&self) -> DummyResult {
        let _: ::core::clone::AssertParamIsClone<Option<ErrorGuaranteed>>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone)]
555pub struct DummyResult {
556    guar: Option<ErrorGuaranteed>,
557    span: Span,
558}
559
560impl DummyResult {
561    /// Creates a default MacResult that can be anything.
562    ///
563    /// Use this as a return value after hitting any errors and
564    /// calling `span_err`.
565    pub fn any(span: Span, guar: ErrorGuaranteed) -> Box<dyn MacResult + 'static> {
566        Box::new(DummyResult { guar: Some(guar), span })
567    }
568
569    /// Same as `any`, but must be a valid fragment, not error.
570    pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
571        Box::new(DummyResult { guar: None, span })
572    }
573
574    /// A plain dummy expression.
575    pub fn raw_expr(sp: Span, guar: Option<ErrorGuaranteed>) -> Box<ast::Expr> {
576        Box::new(ast::Expr {
577            id: ast::DUMMY_NODE_ID,
578            kind: if let Some(guar) = guar {
579                ast::ExprKind::Err(guar)
580            } else {
581                ast::ExprKind::Tup(ThinVec::new())
582            },
583            span: sp,
584            attrs: ast::AttrVec::new(),
585            tokens: None,
586        })
587    }
588}
589
590impl MacResult for DummyResult {
591    fn make_expr(self: Box<DummyResult>) -> Option<Box<ast::Expr>> {
592        Some(DummyResult::raw_expr(self.span, self.guar))
593    }
594
595    fn make_pat(self: Box<DummyResult>) -> Option<Box<ast::Pat>> {
596        Some(Box::new(ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: self.span }))
597    }
598
599    fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::Item>; 1]>> {
600        Some(SmallVec::new())
601    }
602
603    fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
604        Some(SmallVec::new())
605    }
606
607    fn make_trait_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
608        Some(SmallVec::new())
609    }
610
611    fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
612        Some(SmallVec::new())
613    }
614
615    fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
616        Some(SmallVec::new())
617    }
618
619    fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
620        Some({
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(ast::Stmt {
                id: ast::DUMMY_NODE_ID,
                kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span,
                        self.guar)),
                span: self.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(),
                    [ast::Stmt {
                                id: ast::DUMMY_NODE_ID,
                                kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span,
                                        self.guar)),
                                span: self.span,
                            }])))
    }
}smallvec![ast::Stmt {
621            id: ast::DUMMY_NODE_ID,
622            kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.guar)),
623            span: self.span,
624        }])
625    }
626
627    fn make_ty(self: Box<DummyResult>) -> Option<Box<ast::Ty>> {
628        // FIXME(nnethercote): you might expect `ast::TyKind::Dummy` to be used here, but some
629        // values produced here end up being lowered to HIR, which `ast::TyKind::Dummy` does not
630        // support, so we use an empty tuple instead.
631        Some(Box::new(ast::Ty {
632            id: ast::DUMMY_NODE_ID,
633            kind: ast::TyKind::Tup(ThinVec::new()),
634            span: self.span,
635        }))
636    }
637
638    fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
639        Some(SmallVec::new())
640    }
641
642    fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
643        Some(SmallVec::new())
644    }
645
646    fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
647        Some(SmallVec::new())
648    }
649
650    fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
651        Some(SmallVec::new())
652    }
653
654    fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
655        Some(SmallVec::new())
656    }
657
658    fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
659        Some(SmallVec::new())
660    }
661
662    fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
663        Some(SmallVec::new())
664    }
665
666    fn make_crate(self: Box<DummyResult>) -> Option<ast::Crate> {
667        Some(ast::Crate {
668            attrs: Default::default(),
669            items: Default::default(),
670            spans: Default::default(),
671            id: ast::DUMMY_NODE_ID,
672            is_placeholder: Default::default(),
673        })
674    }
675}
676
677/// A syntax extension kind.
678#[derive(#[automatically_derived]
impl ::core::clone::Clone for SyntaxExtensionKind {
    #[inline]
    fn clone(&self) -> SyntaxExtensionKind {
        match self {
            SyntaxExtensionKind::MacroRules(__self_0) =>
                SyntaxExtensionKind::MacroRules(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::Bang(__self_0) =>
                SyntaxExtensionKind::Bang(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::LegacyBang(__self_0) =>
                SyntaxExtensionKind::LegacyBang(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::Attr(__self_0) =>
                SyntaxExtensionKind::Attr(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::LegacyAttr(__self_0) =>
                SyntaxExtensionKind::LegacyAttr(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::NonMacroAttr =>
                SyntaxExtensionKind::NonMacroAttr,
            SyntaxExtensionKind::Derive(__self_0) =>
                SyntaxExtensionKind::Derive(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::LegacyDerive(__self_0) =>
                SyntaxExtensionKind::LegacyDerive(::core::clone::Clone::clone(__self_0)),
            SyntaxExtensionKind::GlobDelegation(__self_0) =>
                SyntaxExtensionKind::GlobDelegation(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
679pub enum SyntaxExtensionKind {
680    /// A `macro_rules!` macro that can work as any `MacroKind`
681    MacroRules(Arc<crate::MacroRulesMacroExpander>),
682
683    /// A token-based function-like macro.
684    Bang(
685        /// An expander with signature TokenStream -> TokenStream.
686        Arc<dyn BangProcMacro + sync::DynSync + sync::DynSend>,
687    ),
688
689    /// An AST-based function-like macro.
690    LegacyBang(
691        /// An expander with signature TokenStream -> AST.
692        Arc<dyn TTMacroExpander + sync::DynSync + sync::DynSend>,
693    ),
694
695    /// A token-based attribute macro.
696    Attr(
697        /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
698        /// The first TokenStream is the attribute itself, the second is the annotated item.
699        /// The produced TokenStream replaces the input TokenStream.
700        Arc<dyn AttrProcMacro + sync::DynSync + sync::DynSend>,
701    ),
702
703    /// An AST-based attribute macro.
704    LegacyAttr(
705        /// An expander with signature (AST, AST) -> AST.
706        /// The first AST fragment is the attribute itself, the second is the annotated item.
707        /// The produced AST fragment replaces the input AST fragment.
708        Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
709    ),
710
711    /// A trivial attribute "macro" that does nothing,
712    /// only keeps the attribute and marks it as inert,
713    /// thus making it ineligible for further expansion.
714    /// E.g. `#[default]`, `#[rustfmt::skip]`.
715    NonMacroAttr,
716
717    /// A token-based derive macro.
718    Derive(
719        /// An expander with signature TokenStream -> TokenStream.
720        /// The produced TokenStream is appended to the input TokenStream.
721        ///
722        /// FIXME: The text above describes how this should work. Currently it
723        /// is handled identically to `LegacyDerive`. It should be migrated to
724        /// a token-based representation like `Bang` and `Attr`, instead of
725        /// using `MultiItemModifier`.
726        Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
727    ),
728
729    /// An AST-based derive macro.
730    LegacyDerive(
731        /// An expander with signature AST -> AST.
732        /// The produced AST fragment is appended to the input AST fragment.
733        Arc<dyn MultiItemModifier + sync::DynSync + sync::DynSend>,
734    ),
735
736    /// A glob delegation.
737    ///
738    /// This is for delegated function implementations, and has nothing to do with glob imports.
739    GlobDelegation(Arc<dyn GlobDelegationExpander + sync::DynSync + sync::DynSend>),
740}
741
742impl SyntaxExtensionKind {
743    /// Returns `Some(expander)` for a macro usable as a `LegacyBang`; otherwise returns `None`
744    ///
745    /// This includes a `MacroRules` with function-like rules.
746    pub fn as_legacy_bang(&self) -> Option<&(dyn TTMacroExpander + sync::DynSync + sync::DynSend)> {
747        match self {
748            SyntaxExtensionKind::LegacyBang(exp) => Some(exp.as_ref()),
749            SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::BANG) => {
750                Some(exp.as_ref())
751            }
752            _ => None,
753        }
754    }
755
756    /// Returns `Some(expander)` for a macro usable as an `Attr`; otherwise returns `None`
757    ///
758    /// This includes a `MacroRules` with `attr` rules.
759    pub fn as_attr(&self) -> Option<&(dyn AttrProcMacro + sync::DynSync + sync::DynSend)> {
760        match self {
761            SyntaxExtensionKind::Attr(exp) => Some(exp.as_ref()),
762            SyntaxExtensionKind::MacroRules(exp) if exp.kinds().contains(MacroKinds::ATTR) => {
763                Some(exp.as_ref())
764            }
765            _ => None,
766        }
767    }
768}
769
770/// A struct representing a macro definition in "lowered" form ready for expansion.
771pub struct SyntaxExtension {
772    /// A syntax extension kind.
773    pub kind: SyntaxExtensionKind,
774    /// Span of the macro definition.
775    pub span: Span,
776    /// List of unstable features that are treated as stable inside this macro.
777    pub allow_internal_unstable: Option<Arc<[Symbol]>>,
778    /// The macro's stability info.
779    pub stability: Option<Stability>,
780    /// The macro's deprecation info.
781    pub deprecation: Option<Deprecation>,
782    /// Names of helper attributes registered by this macro.
783    pub helper_attrs: Vec<Symbol>,
784    /// Edition of the crate in which this macro is defined.
785    pub edition: Edition,
786    /// Built-in macros have a couple of special properties like availability
787    /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
788    pub builtin_name: Option<Symbol>,
789    /// Suppresses the `unsafe_code` lint for code produced by this macro.
790    pub allow_internal_unsafe: bool,
791    /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
792    pub local_inner_macros: bool,
793    /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
794    /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
795    pub collapse_debuginfo: bool,
796    /// Prevents diagnostics pointing into this macro and suppresses the "this error originates in
797    /// the macro" note when a diagnostic points at this macro.
798    pub diagnostic_opaque: bool,
799}
800
801impl SyntaxExtension {
802    /// Returns which kinds of macro call this syntax extension.
803    pub fn macro_kinds(&self) -> MacroKinds {
804        match self.kind {
805            SyntaxExtensionKind::Bang(..)
806            | SyntaxExtensionKind::LegacyBang(..)
807            | SyntaxExtensionKind::GlobDelegation(..) => MacroKinds::BANG,
808            SyntaxExtensionKind::Attr(..)
809            | SyntaxExtensionKind::LegacyAttr(..)
810            | SyntaxExtensionKind::NonMacroAttr => MacroKinds::ATTR,
811            SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
812                MacroKinds::DERIVE
813            }
814            SyntaxExtensionKind::MacroRules(ref m) => m.kinds(),
815        }
816    }
817
818    /// Constructs a syntax extension with default properties.
819    pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
820        SyntaxExtension {
821            span: DUMMY_SP,
822            allow_internal_unstable: None,
823            stability: None,
824            deprecation: None,
825            helper_attrs: Vec::new(),
826            edition,
827            builtin_name: None,
828            kind,
829            allow_internal_unsafe: false,
830            local_inner_macros: false,
831            collapse_debuginfo: false,
832            diagnostic_opaque: false,
833        }
834    }
835
836    /// if-ext - if macro from different crate (related to callsite code)
837    /// | cmd \ attr    | no  | (unspecified) | external | yes |
838    /// | no            | no  | no            | no       | no  |
839    /// | (unspecified) | no  | if-ext        | if-ext   | yes |
840    /// | external      | no  | if-ext        | if-ext   | yes |
841    /// | yes           | yes | yes           | yes      | yes |
842    fn get_collapse_debuginfo(sess: &Session, attrs: &[hir::Attribute], ext: bool) -> bool {
843        let flag = sess.opts.cg.collapse_macro_debuginfo;
844        let attr = if let Some(info) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(CollapseDebugInfo(info)) => {
                    break 'done Some(info);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, CollapseDebugInfo(info) => info) {
845            *info
846        } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcBuiltinMacro { .. }) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcBuiltinMacro { .. }) {
847            CollapseMacroDebuginfo::Yes
848        } else {
849            CollapseMacroDebuginfo::Unspecified
850        };
851
852        #[rustfmt::skip]
853        let collapse_table = [
854            [false, false, false, false],
855            [false, ext,   ext,   true],
856            [false, ext,   ext,   true],
857            [true,  true,  true,  true],
858        ];
859        collapse_table[flag as usize][attr as usize]
860    }
861
862    /// Constructs a syntax extension with the given properties
863    /// and other properties converted from attributes.
864    pub fn new(
865        sess: &Session,
866        kind: SyntaxExtensionKind,
867        span: Span,
868        helper_attrs: Vec<Symbol>,
869        edition: Edition,
870        name: Symbol,
871        attrs: &[hir::Attribute],
872        is_local: bool,
873    ) -> SyntaxExtension {
874        let allow_internal_unstable = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(AllowInternalUnstable(i, _)) => {
                    break 'done Some(i);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, AllowInternalUnstable(i, _) => i)
875            .map(|i| i.as_slice())
876            .unwrap_or_default();
877        let allow_internal_unsafe = {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AllowInternalUnsafe(_)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, AllowInternalUnsafe(_));
878
879        let local_inner_macros =
880            *{
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(MacroExport {
                    local_inner_macros: l, .. }) => {
                    break 'done Some(l);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, MacroExport {local_inner_macros: l, ..} => l).unwrap_or(&false);
881        let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, !is_local);
882        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/base.rs:882",
                        "rustc_expand::base", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/base.rs"),
                        ::tracing_core::__macro_support::Option::Some(882u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_expand::base"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("name")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("name");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("local_inner_macros")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("local_inner_macros");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("collapse_debuginfo")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("collapse_debuginfo");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("allow_internal_unsafe")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("allow_internal_unsafe");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_inner_macros)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&collapse_debuginfo)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&allow_internal_unsafe)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
883
884        let (builtin_name, helper_attrs) = match {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcBuiltinMacro {
                    builtin_name, helper_attrs }) => {
                    break 'done Some((builtin_name, helper_attrs));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcBuiltinMacro { builtin_name, helper_attrs } => (builtin_name, helper_attrs))
885        {
886            // Override `helper_attrs` passed above if it's a built-in macro,
887            // marking `proc_macro_derive` macros as built-in is not a realistic use case.
888            Some((Some(name), helper_attrs)) => {
889                (Some(*name), helper_attrs.iter().copied().collect())
890            }
891            Some((None, _)) => (Some(name), Vec::new()),
892
893            // Not a built-in macro
894            None => (None, helper_attrs),
895        };
896        let diagnostic_opaque = builtin_name.is_some()
897            || (!sess.opts.unstable_opts.macro_backtrace && {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Opaque) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, Opaque));
898
899        let stability = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Stability { stability, .. }) => {
                    break 'done Some(*stability);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Stability { stability, .. } => *stability);
900
901        if let Some(sp) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcBodyStability { span, .. })
                    => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcBodyStability{ span, .. } => *span) {
902            sess.dcx().emit_err(diagnostics::MacroBodyStability {
903                span: sp,
904                head_span: sess.source_map().guess_head_span(span),
905            });
906        }
907
908        SyntaxExtension {
909            kind,
910            span,
911            allow_internal_unstable: (!allow_internal_unstable.is_empty())
912                // FIXME(jdonszelmann): avoid the into_iter/collect?
913                .then(|| allow_internal_unstable.iter().map(|i| i.0).collect::<Vec<_>>().into()),
914            stability,
915            deprecation: {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Deprecated { deprecation, .. })
                    => {
                    break 'done Some(*deprecation);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(
916                attrs,
917                Deprecated { deprecation, .. } => *deprecation
918            ),
919            helper_attrs,
920            edition,
921            builtin_name,
922            allow_internal_unsafe,
923            local_inner_macros,
924            collapse_debuginfo,
925            diagnostic_opaque,
926        }
927    }
928
929    /// A dummy bang macro `foo!()`.
930    pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
931        fn expand(
932            ecx: &mut ExtCtxt<'_>,
933            span: Span,
934            _ts: TokenStream,
935        ) -> Result<TokenStream, ErrorGuaranteed> {
936            Err(ecx.dcx().span_delayed_bug(span, "expanded a dummy bang macro"))
937        }
938        SyntaxExtension::default(SyntaxExtensionKind::Bang(Arc::new(expand)), edition)
939    }
940
941    /// A dummy derive macro `#[derive(Foo)]`.
942    pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
943        fn expander(
944            _: &mut ExtCtxt<'_>,
945            _: Span,
946            _: &ast::MetaItem,
947            _: Annotatable,
948        ) -> Vec<Annotatable> {
949            Vec::new()
950        }
951        SyntaxExtension::default(SyntaxExtensionKind::Derive(Arc::new(expander)), edition)
952    }
953
954    pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
955        SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
956    }
957
958    pub fn glob_delegation(
959        trait_def_id: DefId,
960        impl_def_id: LocalDefId,
961        star_span: Span,
962        edition: Edition,
963    ) -> SyntaxExtension {
964        struct GlobDelegationExpanderImpl {
965            trait_def_id: DefId,
966            impl_def_id: LocalDefId,
967            star_span: Span,
968        }
969        impl GlobDelegationExpander for GlobDelegationExpanderImpl {
970            fn expand(
971                &self,
972                ecx: &mut ExtCtxt<'_>,
973            ) -> ExpandResult<Vec<(Ident, Option<Ident>)>, ()> {
974                match ecx.resolver.glob_delegation_suffixes(
975                    self.trait_def_id,
976                    self.impl_def_id,
977                    self.star_span,
978                ) {
979                    Ok(suffixes) => ExpandResult::Ready(suffixes),
980                    Err(Indeterminate) if ecx.force_mode => ExpandResult::Ready(Vec::new()),
981                    Err(Indeterminate) => ExpandResult::Retry(()),
982                }
983            }
984        }
985
986        let expander = GlobDelegationExpanderImpl { trait_def_id, impl_def_id, star_span };
987        SyntaxExtension::default(SyntaxExtensionKind::GlobDelegation(Arc::new(expander)), edition)
988    }
989
990    pub fn expn_data(
991        &self,
992        parent: LocalExpnId,
993        call_site: Span,
994        descr: Symbol,
995        kind: MacroKind,
996        macro_def_id: Option<DefId>,
997        parent_module: Option<ModId>,
998    ) -> ExpnData {
999        ExpnData::new(
1000            ExpnKind::Macro(kind, descr),
1001            parent.to_expn_id(),
1002            call_site,
1003            self.span,
1004            self.allow_internal_unstable.clone(),
1005            self.edition,
1006            macro_def_id,
1007            parent_module,
1008            self.allow_internal_unsafe,
1009            self.local_inner_macros,
1010            self.collapse_debuginfo,
1011            self.diagnostic_opaque,
1012        )
1013    }
1014}
1015
1016/// Error type that denotes indeterminacy.
1017pub struct Indeterminate;
1018
1019pub struct DeriveResolution {
1020    pub path: ast::Path,
1021    pub item: Annotatable,
1022    // FIXME: currently this field is only used in `is_none`/`is_some` conditions. However, the
1023    // `Arc<SyntaxExtension>` will be used if the FIXME in `MacroExpander::fully_expand_fragment`
1024    // is completed.
1025    pub exts: Option<Arc<SyntaxExtension>>,
1026    pub is_const: bool,
1027}
1028
1029pub trait ResolverExpand {
1030    fn next_node_id(&mut self) -> NodeId;
1031    fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
1032
1033    fn resolve_dollar_crates(&self);
1034    fn visit_ast_fragment_with_placeholders(
1035        &mut self,
1036        expn_id: LocalExpnId,
1037        fragment: &AstFragment,
1038    );
1039    fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
1040
1041    fn expansion_for_ast_pass(
1042        &mut self,
1043        call_site: Span,
1044        pass: AstPass,
1045        features: &[Symbol],
1046        parent_module_id: Option<NodeId>,
1047    ) -> LocalExpnId;
1048
1049    fn resolve_imports(&mut self);
1050
1051    fn resolve_macro_invocation(
1052        &mut self,
1053        invoc: &Invocation,
1054        eager_expansion_root: LocalExpnId,
1055        force: bool,
1056    ) -> Result<Arc<SyntaxExtension>, Indeterminate>;
1057
1058    fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
1059
1060    fn check_unused_macros(&mut self);
1061
1062    // Resolver interfaces for specific built-in macros.
1063    /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
1064    fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
1065    /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Ord` inside it?
1066    fn has_derive_ord(&self, expn_id: LocalExpnId) -> bool;
1067    /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
1068    fn resolve_derives(
1069        &mut self,
1070        expn_id: LocalExpnId,
1071        force: bool,
1072        derive_paths: &dyn Fn() -> Vec<DeriveResolution>,
1073    ) -> Result<(), Indeterminate>;
1074    /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
1075    /// back from resolver.
1076    fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<Vec<DeriveResolution>>;
1077    /// Path resolution logic for `#[cfg_accessible(path)]`.
1078    fn cfg_accessible(
1079        &mut self,
1080        expn_id: LocalExpnId,
1081        path: &ast::Path,
1082    ) -> Result<bool, Indeterminate>;
1083    fn macro_accessible(
1084        &mut self,
1085        expn_id: LocalExpnId,
1086        path: &ast::Path,
1087    ) -> Result<bool, Indeterminate>;
1088
1089    /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
1090    /// No caching is performed.
1091    fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
1092
1093    /// The order of items in the HIR is unrelated to the order of
1094    /// items in the AST. However, we generate proc macro harnesses
1095    /// based on the AST order, and later refer to these harnesses
1096    /// from the HIR. This field keeps track of the order in which
1097    /// we generated proc macros harnesses, so that we can map
1098    /// HIR proc macros items back to their harness items.
1099    fn declare_proc_macro(&mut self, id: NodeId);
1100
1101    fn append_stripped_cfg_item(
1102        &mut self,
1103        parent_node: NodeId,
1104        ident: Ident,
1105        cfg: CfgEntry,
1106        cfg_span: Span,
1107    );
1108
1109    /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
1110    fn registered_tools(&self) -> &RegisteredTools;
1111
1112    /// Mark this invocation id as a glob delegation.
1113    fn register_glob_delegation(&mut self, invoc_id: LocalExpnId);
1114
1115    /// Names of specific methods to which glob delegation expands.
1116    fn glob_delegation_suffixes(
1117        &self,
1118        trait_def_id: DefId,
1119        impl_def_id: LocalDefId,
1120        star_span: Span,
1121    ) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate>;
1122
1123    /// Record the name of an opaque `Ty::ImplTrait` pre-expansion so that it can be used
1124    /// to generate an item name later that does not reference placeholder macros.
1125    fn insert_impl_trait_name(&mut self, id: NodeId, name: Symbol);
1126
1127    /// Mark the scope as having a compile error so that error for lookup in this scope
1128    /// should be suppressed
1129    fn mark_scope_with_compile_error(&mut self, parent_node: NodeId);
1130}
1131
1132pub trait LintStoreExpand {
1133    fn pre_expansion_lint(
1134        &self,
1135        sess: &Session,
1136        features: &Features,
1137        registered_tools: &RegisteredTools,
1138        node_id: NodeId,
1139        attrs: &[Attribute],
1140        items: &[Box<Item>],
1141        name: Symbol,
1142    );
1143}
1144
1145type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
1146
1147#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "ModuleData",
            "mod_path", &self.mod_path, "file_path_stack",
            &self.file_path_stack, "dir_path", &&self.dir_path)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for ModuleData {
    #[inline]
    fn default() -> ModuleData {
        ModuleData {
            mod_path: ::core::default::Default::default(),
            file_path_stack: ::core::default::Default::default(),
            dir_path: ::core::default::Default::default(),
        }
    }
}Default)]
1148pub struct ModuleData {
1149    /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
1150    pub mod_path: Vec<Ident>,
1151    /// Stack of paths to files loaded by out-of-line module items,
1152    /// used to detect and report recursive module inclusions.
1153    pub file_path_stack: Vec<PathBuf>,
1154    /// Directory to search child module files in,
1155    /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
1156    pub dir_path: PathBuf,
1157}
1158
1159impl ModuleData {
1160    pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
1161        ModuleData {
1162            mod_path: self.mod_path.clone(),
1163            file_path_stack: self.file_path_stack.clone(),
1164            dir_path,
1165        }
1166    }
1167}
1168
1169#[derive(#[automatically_derived]
impl ::core::clone::Clone for ExpansionData {
    #[inline]
    fn clone(&self) -> ExpansionData {
        ExpansionData {
            id: ::core::clone::Clone::clone(&self.id),
            depth: ::core::clone::Clone::clone(&self.depth),
            module: ::core::clone::Clone::clone(&self.module),
            dir_ownership: ::core::clone::Clone::clone(&self.dir_ownership),
            lint_node_id: ::core::clone::Clone::clone(&self.lint_node_id),
            is_trailing_mac: ::core::clone::Clone::clone(&self.is_trailing_mac),
        }
    }
}Clone)]
1170pub struct ExpansionData {
1171    pub id: LocalExpnId,
1172    pub depth: usize,
1173    pub module: Rc<ModuleData>,
1174    pub dir_ownership: DirOwnership,
1175    /// Some parent node that is close to this macro call
1176    pub lint_node_id: NodeId,
1177    pub is_trailing_mac: bool,
1178}
1179
1180/// One of these is made during expansion and incrementally updated as we go;
1181/// when a macro expansion occurs, the resulting nodes have the `backtrace()
1182/// -> expn_data` of their expansion context stored into their span.
1183pub struct ExtCtxt<'a> {
1184    pub sess: &'a Session,
1185    pub ecfg: expand::ExpansionConfig<'a>,
1186    pub num_standard_library_imports: usize,
1187    pub reduced_recursion_limit: Option<(Limit, ErrorGuaranteed)>,
1188    pub root_path: PathBuf,
1189    pub resolver: &'a mut dyn ResolverExpand,
1190    pub current_expansion: ExpansionData,
1191    /// Error recovery mode entered when expansion is stuck
1192    /// (or during eager expansion, but that's a hack).
1193    pub force_mode: bool,
1194    pub expansions: FxIndexMap<Span, Vec<String>>,
1195    /// Used for running pre-expansion lints on freshly loaded modules.
1196    pub(super) lint_store: LintStoreExpandDyn<'a>,
1197    /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1198    pub buffered_early_lint: Vec<BufferedEarlyLint>,
1199    /// When we 'expand' an inert attribute, we leave it
1200    /// in the AST, but insert it here so that we know
1201    /// not to expand it again.
1202    pub(super) expanded_inert_attrs: MarkedAttrs,
1203    /// `-Zmacro-stats` data.
1204    pub macro_stats: FxHashMap<(Symbol, MacroKind), MacroStat>,
1205    pub nb_macro_errors: usize,
1206}
1207
1208impl<'a> ExtCtxt<'a> {
1209    pub fn new(
1210        sess: &'a Session,
1211        ecfg: expand::ExpansionConfig<'a>,
1212        resolver: &'a mut dyn ResolverExpand,
1213        lint_store: LintStoreExpandDyn<'a>,
1214    ) -> ExtCtxt<'a> {
1215        ExtCtxt {
1216            sess,
1217            ecfg,
1218            num_standard_library_imports: 0,
1219            reduced_recursion_limit: None,
1220            resolver,
1221            lint_store,
1222            root_path: PathBuf::new(),
1223            current_expansion: ExpansionData {
1224                id: LocalExpnId::ROOT,
1225                depth: 0,
1226                module: Default::default(),
1227                dir_ownership: DirOwnership::Owned { relative: None },
1228                lint_node_id: ast::CRATE_NODE_ID,
1229                is_trailing_mac: false,
1230            },
1231            force_mode: false,
1232            expansions: FxIndexMap::default(),
1233            expanded_inert_attrs: MarkedAttrs::new(),
1234            buffered_early_lint: ::alloc::vec::Vec::new()vec![],
1235            macro_stats: Default::default(),
1236            nb_macro_errors: 0,
1237        }
1238    }
1239
1240    pub fn dcx(&self) -> DiagCtxtHandle<'a> {
1241        self.sess.dcx()
1242    }
1243
1244    /// Returns a `Folder` for deeply expanding all macros in an AST node.
1245    pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1246        expand::MacroExpander::new(self, false)
1247    }
1248
1249    /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1250    /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1251    pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1252        expand::MacroExpander::new(self, true)
1253    }
1254    pub fn new_parser_from_tts(&self, stream: TokenStream) -> Parser<'a> {
1255        Parser::new(&self.sess.psess, stream, MACRO_ARGUMENTS)
1256    }
1257    pub fn source_map(&self) -> &'a SourceMap {
1258        self.sess.psess.source_map()
1259    }
1260    pub fn psess(&self) -> &'a ParseSess {
1261        &self.sess.psess
1262    }
1263    pub fn call_site(&self) -> Span {
1264        self.current_expansion.id.expn_data().call_site
1265    }
1266
1267    /// Returns the current expansion kind's description.
1268    pub(crate) fn expansion_descr(&self) -> String {
1269        let expn_data = self.current_expansion.id.expn_data();
1270        expn_data.kind.descr()
1271    }
1272
1273    /// Equivalent of `Span::def_site` from the proc macro API,
1274    /// except that the location is taken from the span passed as an argument.
1275    pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1276        span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1277    }
1278
1279    /// Equivalent of `Span::call_site` from the proc macro API,
1280    /// except that the location is taken from the span passed as an argument.
1281    pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1282        span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1283    }
1284
1285    /// Equivalent of `Span::mixed_site` from the proc macro API,
1286    /// except that the location is taken from the span passed as an argument.
1287    pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1288        span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1289    }
1290
1291    /// Returns span for the macro which originally caused the current expansion to happen.
1292    ///
1293    /// Stops backtracing at include! boundary.
1294    pub fn expansion_cause(&self) -> Option<Span> {
1295        self.current_expansion.id.expansion_cause()
1296    }
1297
1298    /// This method increases the internal macro errors count and then call `trace_macros_diag`.
1299    pub fn macro_error_and_trace_macros_diag(&mut self) {
1300        self.nb_macro_errors += 1;
1301        self.trace_macros_diag();
1302    }
1303
1304    pub fn trace_macros_diag(&mut self) {
1305        for (span, notes) in self.expansions.iter() {
1306            let mut db = self.dcx().create_note(diagnostics::TraceMacro { span: *span });
1307            for note in notes {
1308                db.note(note.clone());
1309            }
1310            db.emit();
1311        }
1312        // Fixme: does this result in errors?
1313        self.expansions.clear();
1314    }
1315    pub fn trace_macros(&self) -> bool {
1316        self.ecfg.trace_mac
1317    }
1318    pub fn set_trace_macros(&mut self, x: bool) {
1319        self.ecfg.trace_mac = x
1320    }
1321    pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1322        let def_site = self.with_def_site_ctxt(DUMMY_SP);
1323        iter::once(Ident::new(kw::DollarCrate, def_site))
1324            .chain(components.iter().map(|&s| Ident::new(s, def_site)))
1325            .collect()
1326    }
1327    pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1328        let def_site = self.with_def_site_ctxt(DUMMY_SP);
1329        components.iter().map(|&s| Ident::new(s, def_site)).collect()
1330    }
1331
1332    pub fn check_unused_macros(&mut self) {
1333        self.resolver.check_unused_macros();
1334    }
1335}
1336
1337/// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1338///
1339/// This unifies the logic used for resolving `include_X!`.
1340pub fn resolve_path(sess: &Session, path: impl Into<PathBuf>, span: Span) -> PResult<'_, PathBuf> {
1341    let path = path.into();
1342
1343    // Relative paths are resolved relative to the file in which they are found
1344    // after macro expansion (that is, they are unhygienic).
1345    if !path.is_absolute() {
1346        let callsite = span.source_callsite();
1347        let source_map = sess.source_map();
1348        let Some(mut base_path) = source_map.span_to_filename(callsite).into_local_path() else {
1349            return Err(sess.dcx().create_err(diagnostics::ResolveRelativePath {
1350                span,
1351                path: source_map
1352                    .filename_for_diagnostics(&source_map.span_to_filename(callsite))
1353                    .to_string(),
1354            }));
1355        };
1356        base_path.pop();
1357        base_path.push(path);
1358        Ok(base_path)
1359    } else {
1360        // This ensures that Windows verbatim paths are fixed if mixed path separators are used,
1361        // which can happen when `concat!` is used to join paths.
1362        match path.components().next() {
1363            Some(Prefix(prefix)) if prefix.kind().is_verbatim() => Ok(path.components().collect()),
1364            _ => Ok(path),
1365        }
1366    }
1367}