rustc_expand/
base.rs

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