Skip to main content

hir_expand/
lib.rs

1//! `hir_expand` deals with macro expansion.
2//!
3//! Specifically, it implements a concept of `MacroFile` -- a file whose syntax
4//! tree originates not from the text of some `FileId`, but from some macro
5//! expansion.
6#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
7// It's useful to refer to code that is private in doc comments.
8#![allow(rustdoc::private_intra_doc_links)]
9
10pub use intern;
11
12pub mod attrs;
13pub mod builtin;
14pub mod change;
15pub mod declarative;
16pub mod eager;
17pub mod files;
18pub mod hygiene;
19pub mod inert_attr_macro;
20pub mod mod_path;
21pub mod name;
22pub mod proc_macro;
23pub mod span_map;
24
25mod cfg_process;
26mod fixup;
27mod prettify_macro_expansion_;
28
29use salsa::plumbing::{AsId, FromId};
30use thin_vec::ThinVec;
31use triomphe::Arc;
32
33use core::fmt;
34use std::{borrow::Cow, ops};
35
36use base_db::{Crate, SourceDatabase};
37use either::Either;
38use mbe::MatchedArmIndex;
39use span::{
40    AstIdMap, Edition, ErasedFileAstId, FileAstId, NO_DOWNMAP_ERASED_FILE_AST_ID_MARKER, Span,
41    SyntaxContext,
42};
43use syntax::{
44    Parse, SyntaxError, SyntaxNode, SyntaxToken, T, TextRange, TextSize,
45    ast::{self, AstNode},
46};
47use syntax_bridge::{DocCommentDesugarMode, syntax_node_to_token_tree};
48
49use crate::{
50    attrs::AttrId,
51    builtin::{
52        BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerExpander,
53        include_input_to_file_id, pseudo_derive_attr_expansion,
54    },
55    cfg_process::attr_macro_input_to_token_tree,
56    fixup::SyntaxFixupUndoInfo,
57    hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt, span_with_mixed_site_ctxt},
58    proc_macro::{CustomProcMacroExpander, ProcMacroKind, ProcMacros},
59    span_map::{ExpansionSpanMap, RealSpanMap, SpanMap},
60};
61
62pub use crate::{
63    files::{AstId, ErasedAstId, FileRange, InFile, InMacroFile, InRealFile},
64    prettify_macro_expansion_::prettify_macro_expansion,
65};
66
67pub use base_db::EditionedFileId;
68pub use mbe::{DeclarativeMacro, MacroCallStyle, MacroCallStyles, ValueResult};
69
70pub use tt;
71
72/// This is just to ensure the types of [`MacroCallId::macro_arg_considering_derives`]
73/// and [`MacroCallId::macro_arg`] are the same.
74type MacroArgResult = (tt::TopSubtree, SyntaxFixupUndoInfo, Span);
75
76/// Total limit on the number of tokens produced by any macro invocation.
77///
78/// If an invocation produces more tokens than this limit, it will not be stored in the database and
79/// an error will be emitted.
80///
81/// Actual max for `analysis-stats .` at some point: 30672.
82const TOKEN_LIMIT: usize = 2_097_152;
83
84#[macro_export]
85macro_rules! impl_intern_lookup {
86    ($id:ident, $loc:ident) => {
87        impl $crate::Intern for $loc {
88            type ID = $id;
89            fn intern(self, db: &dyn ::base_db::SourceDatabase) -> Self::ID {
90                $id::new(db, self)
91            }
92        }
93
94        impl $crate::Lookup for $id {
95            type Data = $loc;
96            fn lookup<'db>(&self, db: &'db dyn ::base_db::SourceDatabase) -> &'db Self::Data {
97                self.loc(db)
98            }
99        }
100    };
101}
102
103// ideally these would be defined in base-db, but the orphan rule doesn't let us
104pub trait Intern {
105    type ID;
106    fn intern(self, db: &dyn SourceDatabase) -> Self::ID;
107}
108
109pub trait Lookup {
110    type Data;
111    fn lookup<'db>(&self, db: &'db dyn SourceDatabase) -> &'db Self::Data;
112}
113
114impl_intern_lookup!(MacroCallId, MacroCallLoc);
115
116pub type ExpandResult<T> = ValueResult<T, ExpandError>;
117
118#[derive(Debug, PartialEq, Eq, Clone, Hash)]
119pub struct ExpandError {
120    inner: Arc<(ExpandErrorKind, Span)>,
121}
122
123impl ExpandError {
124    pub fn new(span: Span, kind: ExpandErrorKind) -> Self {
125        ExpandError { inner: Arc::new((kind, span)) }
126    }
127    pub fn other(span: Span, msg: impl Into<Box<str>>) -> Self {
128        ExpandError { inner: Arc::new((ExpandErrorKind::Other(msg.into()), span)) }
129    }
130    pub fn kind(&self) -> &ExpandErrorKind {
131        &self.inner.0
132    }
133    pub fn span(&self) -> Span {
134        self.inner.1
135    }
136
137    pub fn render_to_string(&self, db: &dyn SourceDatabase) -> RenderedExpandError {
138        self.inner.0.render_to_string(db)
139    }
140}
141
142#[derive(Debug, PartialEq, Eq, Clone, Hash)]
143pub enum ExpandErrorKind {
144    /// Attribute macro expansion is disabled.
145    ProcMacroAttrExpansionDisabled,
146    MissingProcMacroExpander(Crate),
147    /// The macro for this call is disabled.
148    MacroDisabled,
149    /// The macro definition has errors.
150    MacroDefinition,
151    Mbe(mbe::ExpandErrorKind),
152    RecursionOverflow,
153    Other(Box<str>),
154    ProcMacroPanic(Box<str>),
155}
156
157pub struct RenderedExpandError {
158    pub message: String,
159    pub error: bool,
160    pub kind: &'static str,
161}
162
163impl fmt::Display for RenderedExpandError {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        write!(f, "{}", self.message)
166    }
167}
168
169impl RenderedExpandError {
170    const GENERAL_KIND: &str = "macro-error";
171    const DISABLED: &str = "proc-macro-disabled";
172    const ATTR_EXP_DISABLED: &str = "attribute-expansion-disabled";
173}
174
175impl ExpandErrorKind {
176    pub fn render_to_string(&self, db: &dyn SourceDatabase) -> RenderedExpandError {
177        match self {
178            ExpandErrorKind::ProcMacroAttrExpansionDisabled => RenderedExpandError {
179                message: "procedural attribute macro expansion is disabled".to_owned(),
180                error: false,
181                kind: RenderedExpandError::ATTR_EXP_DISABLED,
182            },
183            ExpandErrorKind::MacroDisabled => RenderedExpandError {
184                message: "proc-macro is explicitly disabled".to_owned(),
185                error: false,
186                kind: RenderedExpandError::DISABLED,
187            },
188            &ExpandErrorKind::MissingProcMacroExpander(def_crate) => {
189                let crate_label = || match &def_crate.extra_data(db).display_name {
190                    Some(name) => format!("`{}` ({def_crate:?})", name.canonical_name()),
191                    None => format!("{def_crate:?}"),
192                };
193                match ProcMacros::get_for_crate(db, def_crate).map(|it| it.get_error()) {
194                    Some(Some(e)) => RenderedExpandError {
195                        message: e.to_string(),
196                        error: e.is_hard_error(),
197                        kind: RenderedExpandError::GENERAL_KIND,
198                    },
199                    // Loading can succeed even when the library does not export a macro
200                    // declared in the source we are analyzing.
201                    Some(None) => RenderedExpandError {
202                        message: format!(
203                            "proc-macro is missing from the loaded library for crate {}; \
204                             the source and compiled library may be out of sync, try rebuilding the proc-macro crate",
205                            crate_label()
206                        ),
207                        error: true,
208                        kind: RenderedExpandError::GENERAL_KIND,
209                    },
210                    None => RenderedExpandError {
211                        message: format!(
212                            "internal error: proc-macro map is missing entry for crate {}",
213                            crate_label()
214                        ),
215                        error: true,
216                        kind: RenderedExpandError::GENERAL_KIND,
217                    },
218                }
219            }
220            ExpandErrorKind::MacroDefinition => RenderedExpandError {
221                message: "macro definition has parse errors".to_owned(),
222                error: true,
223                kind: RenderedExpandError::GENERAL_KIND,
224            },
225            ExpandErrorKind::Mbe(e) => RenderedExpandError {
226                message: e.to_string(),
227                error: true,
228                kind: RenderedExpandError::GENERAL_KIND,
229            },
230            ExpandErrorKind::RecursionOverflow => RenderedExpandError {
231                message: "overflow expanding the original macro".to_owned(),
232                error: true,
233                kind: RenderedExpandError::GENERAL_KIND,
234            },
235            ExpandErrorKind::Other(e) => RenderedExpandError {
236                message: (**e).to_owned(),
237                error: true,
238                kind: RenderedExpandError::GENERAL_KIND,
239            },
240            ExpandErrorKind::ProcMacroPanic(e) => RenderedExpandError {
241                message: format!("proc-macro panicked: {e}"),
242                error: true,
243                kind: RenderedExpandError::GENERAL_KIND,
244            },
245        }
246    }
247}
248
249impl From<mbe::ExpandError> for ExpandError {
250    fn from(mbe: mbe::ExpandError) -> Self {
251        ExpandError { inner: Arc::new((ExpandErrorKind::Mbe(mbe.inner.1.clone()), mbe.inner.0)) }
252    }
253}
254#[derive(Debug, Clone, PartialEq, Eq, Hash)]
255pub struct MacroCallLoc {
256    pub def: MacroDefId,
257    pub krate: Crate,
258    pub kind: MacroCallKind,
259    pub ctxt: SyntaxContext,
260    /// The macro recursion depth of this expansion.
261    ///
262    /// Because macro expansions can cross `DefMap` boundaries, we must track this inside the expansion
263    /// to not recurse infinitely.
264    pub macro_depth: u32,
265}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268pub struct MacroDefId {
269    pub krate: Crate,
270    pub edition: Edition,
271    pub kind: MacroDefKind,
272    pub local_inner: bool,
273    pub allow_internal_unsafe: bool,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
277pub enum MacroDefKind {
278    Declarative(AstId<ast::Macro>, MacroCallStyles),
279    BuiltIn(AstId<ast::Macro>, BuiltinFnLikeExpander),
280    BuiltInAttr(AstId<ast::Macro>, BuiltinAttrExpander),
281    BuiltInDerive(AstId<ast::Macro>, BuiltinDeriveExpander),
282    BuiltInEager(AstId<ast::Macro>, EagerExpander),
283    UnimplementedBuiltIn(AstId<ast::Macro>),
284    ProcMacro(AstId<ast::Fn>, CustomProcMacroExpander, ProcMacroKind),
285}
286
287impl MacroDefKind {
288    #[inline]
289    pub fn is_declarative(&self) -> bool {
290        matches!(self, MacroDefKind::Declarative(..))
291    }
292
293    pub fn erased_ast_id(&self) -> ErasedAstId {
294        match *self {
295            MacroDefKind::ProcMacro(id, ..) => id.erase(),
296            MacroDefKind::BuiltIn(id, _)
297            | MacroDefKind::BuiltInAttr(id, _)
298            | MacroDefKind::BuiltInDerive(id, _)
299            | MacroDefKind::BuiltInEager(id, _)
300            | MacroDefKind::Declarative(id, ..)
301            | MacroDefKind::UnimplementedBuiltIn(id) => id.erase(),
302        }
303    }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq, Hash)]
307pub struct EagerCallInfo {
308    /// The expanded argument of the eager macro.
309    arg: tt::TopSubtree,
310    /// Call id of the eager macro's input file (this is the macro file for its fully expanded input).
311    arg_id: MacroCallId,
312    error: Option<ExpandError>,
313    /// The call site span of the eager macro
314    span: Span,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Hash)]
318pub enum MacroCallKind {
319    FnLike {
320        ast_id: AstId<ast::MacroCall>,
321        expand_to: ExpandTo,
322        /// Some if this is a macro call for an eager macro. Note that this is `None`
323        /// for the eager input macro file.
324        // FIXME: This is being interned, subtrees can vary quickly differing just slightly causing
325        // leakage problems here
326        eager: Option<Box<EagerCallInfo>>,
327    },
328    Derive {
329        ast_id: AstId<ast::Adt>,
330        /// Syntactical index of the invoking `#[derive]` attribute.
331        derive_attr_index: AttrId,
332        /// Index of the derive macro in the derive attribute
333        derive_index: u32,
334        /// The "parent" macro call.
335        /// We will resolve the same token tree for all derive macros in the same derive attribute.
336        derive_macro_id: MacroCallId,
337    },
338    Attr {
339        ast_id: AstId<ast::Item>,
340        // FIXME: This shouldn't be here, we can derive this from `invoc_attr_index`.
341        attr_args: Option<Box<tt::TopSubtree>>,
342        /// This contains the list of all *active* attributes (derives and attr macros) preceding this
343        /// attribute, including this attribute. You can retrieve the [`AttrId`] of the current attribute
344        /// by calling [`invoc_attr()`] on this.
345        ///
346        /// The macro should not see the attributes here.
347        ///
348        /// [`invoc_attr()`]: AttrMacroAttrIds::invoc_attr
349        censored_attr_ids: AttrMacroAttrIds,
350    },
351}
352
353#[derive(Debug, Clone, PartialEq, Eq, Hash)]
354pub struct AttrMacroAttrIds(AttrMacroAttrIdsRepr);
355
356impl AttrMacroAttrIds {
357    #[inline]
358    pub fn from_one(id: AttrId) -> Self {
359        Self(AttrMacroAttrIdsRepr::One(id))
360    }
361
362    #[inline]
363    pub fn from_many(ids: &[AttrId]) -> Self {
364        if let &[id] = ids {
365            Self(AttrMacroAttrIdsRepr::One(id))
366        } else {
367            Self(AttrMacroAttrIdsRepr::ManyDerives(ids.iter().copied().collect()))
368        }
369    }
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Hash)]
373enum AttrMacroAttrIdsRepr {
374    One(AttrId),
375    ManyDerives(ThinVec<AttrId>),
376}
377
378impl ops::Deref for AttrMacroAttrIds {
379    type Target = [AttrId];
380
381    #[inline]
382    fn deref(&self) -> &Self::Target {
383        match &self.0 {
384            AttrMacroAttrIdsRepr::One(one) => std::slice::from_ref(one),
385            AttrMacroAttrIdsRepr::ManyDerives(many) => many,
386        }
387    }
388}
389
390impl AttrMacroAttrIds {
391    #[inline]
392    pub fn invoc_attr(&self) -> AttrId {
393        match &self.0 {
394            AttrMacroAttrIdsRepr::One(it) => *it,
395            AttrMacroAttrIdsRepr::ManyDerives(it) => {
396                *it.last().expect("should always have at least one `AttrId`")
397            }
398        }
399    }
400}
401
402impl MacroCallKind {
403    pub(crate) fn call_style(&self) -> MacroCallStyle {
404        match self {
405            MacroCallKind::FnLike { .. } => MacroCallStyle::FnLike,
406            MacroCallKind::Derive { .. } => MacroCallStyle::Derive,
407            MacroCallKind::Attr { .. } => MacroCallStyle::Attr,
408        }
409    }
410}
411
412#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
413pub enum MacroKind {
414    /// `macro_rules!` or Macros 2.0 macro.
415    Declarative,
416    /// A built-in function-like macro.
417    DeclarativeBuiltIn,
418    /// A custom derive.
419    Derive,
420    /// A builtin-in derive.
421    DeriveBuiltIn,
422    /// A procedural attribute macro.
423    Attr,
424    /// A built-in attribute macro.
425    AttrBuiltIn,
426    /// A function-like procedural macro.
427    ProcMacro,
428}
429
430impl MacroCallId {
431    pub fn call_node(self, db: &dyn SourceDatabase) -> InFile<SyntaxNode> {
432        self.loc(db).to_node(db)
433    }
434    pub fn expansion_level(self, db: &dyn SourceDatabase) -> u32 {
435        let mut level = 0;
436        let mut macro_file = self;
437        loop {
438            let loc = macro_file.loc(db);
439
440            level += 1;
441            macro_file = match loc.kind.file_id() {
442                HirFileId::FileId(_) => break level,
443                HirFileId::MacroFile(it) => it,
444            };
445        }
446    }
447    pub fn parent(self, db: &dyn SourceDatabase) -> HirFileId {
448        self.loc(db).kind.file_id()
449    }
450
451    /// Return expansion information if it is a macro-expansion file
452    pub fn expansion_info(self, db: &dyn SourceDatabase) -> ExpansionInfo<'_> {
453        ExpansionInfo::new(db, self)
454    }
455
456    pub fn kind(self, db: &dyn SourceDatabase) -> MacroKind {
457        match self.loc(db).def.kind {
458            MacroDefKind::Declarative(..) => MacroKind::Declarative,
459            MacroDefKind::BuiltIn(..) | MacroDefKind::BuiltInEager(..) => {
460                MacroKind::DeclarativeBuiltIn
461            }
462            MacroDefKind::BuiltInDerive(..) => MacroKind::DeriveBuiltIn,
463            MacroDefKind::ProcMacro(_, _, ProcMacroKind::CustomDerive) => MacroKind::Derive,
464            MacroDefKind::ProcMacro(_, _, ProcMacroKind::Attr) => MacroKind::Attr,
465            MacroDefKind::ProcMacro(_, _, ProcMacroKind::Bang) => MacroKind::ProcMacro,
466            MacroDefKind::BuiltInAttr(..) => MacroKind::AttrBuiltIn,
467            MacroDefKind::UnimplementedBuiltIn(..) => MacroKind::Declarative,
468        }
469    }
470
471    pub fn is_include_macro(self, db: &dyn SourceDatabase) -> bool {
472        self.loc(db).def.is_include()
473    }
474
475    pub fn is_include_like_macro(self, db: &dyn SourceDatabase) -> bool {
476        self.loc(db).def.is_include_like()
477    }
478
479    pub fn is_env_or_option_env(self, db: &dyn SourceDatabase) -> bool {
480        self.loc(db).def.is_env_or_option_env()
481    }
482
483    pub fn is_eager(self, db: &dyn SourceDatabase) -> bool {
484        let loc = self.loc(db);
485        matches!(loc.def.kind, MacroDefKind::BuiltInEager(..))
486    }
487
488    pub fn eager_arg(self, db: &dyn SourceDatabase) -> Option<MacroCallId> {
489        let loc = self.loc(db);
490        match &loc.kind {
491            MacroCallKind::FnLike { eager, .. } => eager.as_ref().map(|it| it.arg_id),
492            _ => None,
493        }
494    }
495
496    pub fn is_derive_attr_pseudo_expansion(self, db: &dyn SourceDatabase) -> bool {
497        let loc = self.loc(db);
498        loc.def.is_attribute_derive()
499    }
500}
501
502#[salsa::tracked]
503impl MacroCallId {
504    /// Implementation of [`HirFileId::parse_or_expand`] for the macro case.
505    // FIXME: We should verify that the parsed node is one of the many macro node variants we expect
506    // instead of having it be untyped
507    #[salsa::tracked(returns(ref), lru = 512)]
508    pub fn parse_macro_expansion(
509        self,
510        db: &dyn SourceDatabase,
511    ) -> ExpandResult<(Parse<SyntaxNode>, ExpansionSpanMap)> {
512        let _p = tracing::info_span!("parse_macro_expansion").entered();
513        let loc = self.loc(db);
514        let expand_to = loc.expand_to();
515        let mbe::ValueResult { value: (tt, matched_arm), err } = self.macro_expand(db, loc);
516
517        let (parse, mut rev_token_map) = token_tree_to_syntax_node(db, &tt, expand_to);
518        rev_token_map.matched_arm = matched_arm;
519
520        ExpandResult { value: (parse, rev_token_map), err }
521    }
522
523    pub fn parse_macro_expansion_error(
524        self,
525        db: &dyn SourceDatabase,
526    ) -> Option<ExpandResult<Arc<[SyntaxError]>>> {
527        let e: ExpandResult<Arc<[SyntaxError]>> =
528            self.parse_macro_expansion(db).as_ref().map(|it| Arc::from(it.0.errors()));
529        if e.value.is_empty() && e.err.is_none() { None } else { Some(e) }
530    }
531
532    /// This resolves the [MacroCallId] to check if it is a derive macro if so get the [macro_arg] for the derive.
533    /// Other wise return the [macro_arg] for the macro_call_id.
534    ///
535    /// This is not connected to the database so it does not cache the result. However, the inner [macro_arg] query is
536    ///
537    /// [macro_arg]: Self::macro_arg
538    #[expect(deprecated, reason = "we are `macro_arg_considering_derives`")]
539    pub fn macro_arg_considering_derives<'db>(
540        self,
541        db: &'db dyn SourceDatabase,
542        kind: &MacroCallKind,
543    ) -> &'db MacroArgResult {
544        match kind {
545            // Get the macro arg for the derive macro
546            MacroCallKind::Derive { derive_macro_id, .. } => derive_macro_id.macro_arg(db),
547            // Normal macro arg
548            _ => self.macro_arg(db),
549        }
550    }
551
552    /// Lowers syntactic macro call to a token tree representation. That's a firewall
553    /// query, only typing in the macro call itself changes the returned
554    /// subtree.
555    #[salsa::tracked(returns(ref))]
556    #[deprecated = "calling this is incorrect, call `macro_arg_considering_derives` instead"]
557    fn macro_arg(self, db: &dyn SourceDatabase) -> MacroArgResult {
558        let loc = self.loc(db);
559
560        if let MacroCallLoc {
561            def: MacroDefId { kind: MacroDefKind::BuiltInEager(..), .. },
562            kind: MacroCallKind::FnLike { eager: Some(eager), .. },
563            ..
564        } = &loc
565        {
566            return (eager.arg.clone(), SyntaxFixupUndoInfo::NONE, eager.span);
567        }
568
569        let (parse, map) = loc.kind.file_id().parse_with_map(db);
570        let root = parse.syntax_node();
571
572        let (is_derive, censor_item_tree_attr_ids, item_node, span) = match &loc.kind {
573            MacroCallKind::FnLike { ast_id, .. } => {
574                let node = &ast_id.to_ptr(db).to_node(&root);
575                let path_range = node
576                    .path()
577                    .map_or_else(|| node.syntax().text_range(), |path| path.syntax().text_range());
578                let span = map.span_for_range(path_range);
579
580                let dummy_tt = |kind| {
581                    (
582                        tt::TopSubtree::from_token_trees(
583                            tt::Delimiter { open: span, close: span, kind },
584                            tt::TokenTreesView::empty(),
585                        ),
586                        SyntaxFixupUndoInfo::default(),
587                        span,
588                    )
589                };
590
591                let Some(tt) = node.token_tree() else {
592                    return dummy_tt(tt::DelimiterKind::Invisible);
593                };
594                let first = tt.left_delimiter_token().map(|it| it.kind()).unwrap_or(T!['(']);
595                let last = tt.right_delimiter_token().map(|it| it.kind()).unwrap_or(T![.]);
596
597                let mismatched_delimiters = !matches!(
598                    (first, last),
599                    (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}'])
600                );
601                if mismatched_delimiters {
602                    // Don't expand malformed (unbalanced) macro invocations. This is
603                    // less than ideal, but trying to expand unbalanced  macro calls
604                    // sometimes produces pathological, deeply nested code which breaks
605                    // all kinds of things.
606                    //
607                    // So instead, we'll return an empty subtree here
608                    cov_mark::hit!(issue9358_bad_macro_stack_overflow);
609
610                    let kind = match first {
611                        _ if loc.def.is_proc_macro() => tt::DelimiterKind::Invisible,
612                        T!['('] => tt::DelimiterKind::Parenthesis,
613                        T!['['] => tt::DelimiterKind::Bracket,
614                        T!['{'] => tt::DelimiterKind::Brace,
615                        _ => tt::DelimiterKind::Invisible,
616                    };
617                    return dummy_tt(kind);
618                }
619
620                let mut tt = syntax_bridge::syntax_node_to_token_tree(
621                    tt.syntax(),
622                    map,
623                    span,
624                    if loc.def.is_proc_macro() {
625                        DocCommentDesugarMode::ProcMacro
626                    } else {
627                        DocCommentDesugarMode::Mbe
628                    },
629                );
630                if loc.def.is_proc_macro() {
631                    // proc macros expect their inputs without parentheses, MBEs expect it with them included
632                    tt.set_top_subtree_delimiter_kind(tt::DelimiterKind::Invisible);
633                }
634                return (tt, SyntaxFixupUndoInfo::NONE, span);
635            }
636            // MacroCallKind::Derive should not be here. As we are getting the argument for the derive macro
637            MacroCallKind::Derive { .. } => {
638                unreachable!("`MacroCallId::macro_arg` called with `MacroCallKind::Derive`")
639            }
640            MacroCallKind::Attr { ast_id, censored_attr_ids: attr_ids, .. } => {
641                let node = ast_id.to_ptr(db).to_node(&root);
642                let (_, attr) =
643                    attr_ids.invoc_attr().find_attr_range_with_source(db, loc.krate, &node);
644                let range = attr
645                    .path()
646                    .map(|path| path.syntax().text_range())
647                    .unwrap_or_else(|| attr.syntax().text_range());
648                let span = map.span_for_range(range);
649
650                let is_derive = matches!(loc.def.kind, MacroDefKind::BuiltInAttr(_, expander) if expander.is_derive());
651                (is_derive, &**attr_ids, node, span)
652            }
653        };
654
655        let (mut tt, undo_info) = attr_macro_input_to_token_tree(
656            db,
657            item_node.syntax(),
658            map,
659            span,
660            is_derive,
661            censor_item_tree_attr_ids,
662            loc.krate,
663        );
664
665        if loc.def.is_proc_macro() {
666            // proc macros expect their inputs without parentheses, MBEs expect it with them included
667            tt.set_top_subtree_delimiter_kind(tt::DelimiterKind::Invisible);
668        }
669
670        (tt, undo_info, span)
671    }
672
673    fn macro_expand<'db>(
674        self,
675        db: &'db dyn SourceDatabase,
676        loc: &MacroCallLoc,
677    ) -> ExpandResult<(Cow<'db, tt::TopSubtree>, MatchedArmIndex)> {
678        let _p = tracing::info_span!("macro_expand").entered();
679
680        let (ExpandResult { value: (tt, matched_arm), err }, span) = match loc.def.kind {
681            MacroDefKind::ProcMacro(..) => {
682                return self.expand_proc_macro(db).as_ref().map(|it| (Cow::Borrowed(it), None));
683            }
684            _ => {
685                let (macro_arg, undo_info, span) =
686                    self.macro_arg_considering_derives(db, &loc.kind);
687                let span = *span;
688
689                let arg = macro_arg;
690                let res = match loc.def.kind {
691                    MacroDefKind::Declarative(id, _) => {
692                        id.decl_macro_expander(db, loc.def.krate).expand(db, arg, self, span)
693                    }
694                    MacroDefKind::BuiltIn(_, it) => {
695                        it.expand(db, self, arg, span).map_err(Into::into).zip_val(None)
696                    }
697                    MacroDefKind::BuiltInDerive(_, it) => {
698                        it.expand(db, self, arg, span).map_err(Into::into).zip_val(None)
699                    }
700                    MacroDefKind::UnimplementedBuiltIn(_) => {
701                        expand_unimplemented_builtin_macro(span).zip_val(None)
702                    }
703                    MacroDefKind::BuiltInEager(_, it) => {
704                        // This might look a bit odd, but we do not expand the inputs to eager macros here.
705                        // Eager macros inputs are expanded, well, eagerly when we collect the macro calls.
706                        // That kind of expansion uses the ast id map of an eager macros input though which goes through
707                        // the HirFileId machinery. As eager macro inputs are assigned a macro file id that query
708                        // will end up going through here again, whereas we want to just want to inspect the raw input.
709                        // As such we just return the input subtree here.
710                        let eager = match &loc.kind {
711                            MacroCallKind::FnLike { eager: None, .. } => {
712                                return ExpandResult::ok(Cow::Borrowed(macro_arg)).zip_val(None);
713                            }
714                            MacroCallKind::FnLike { eager: Some(eager), .. } => Some(&**eager),
715                            _ => None,
716                        };
717
718                        let mut res = it.expand(db, self, arg, span).map_err(Into::into);
719
720                        if let Some(EagerCallInfo { error, .. }) = eager {
721                            // FIXME: We should report both errors!
722                            res.err = error.clone().or(res.err);
723                        }
724                        res.zip_val(None)
725                    }
726                    MacroDefKind::BuiltInAttr(_, it) => {
727                        let mut res = it.expand(db, self, arg, span);
728                        fixup::reverse_fixups(&mut res.value, undo_info);
729                        res.zip_val(None)
730                    }
731                    MacroDefKind::ProcMacro(_, _, _) => unreachable!(),
732                };
733                (res, span)
734            }
735        };
736
737        // Skip checking token tree limit for include! macro call
738        if !loc.def.is_include() {
739            // Set a hard limit for the expanded tt
740            if let Err(value) = check_tt_count(&tt) {
741                return value
742                    .map(|()| Cow::Owned(tt::TopSubtree::empty(tt::DelimSpan::from_single(span))))
743                    .zip_val(matched_arm);
744            }
745        }
746
747        ExpandResult { value: (Cow::Owned(tt), matched_arm), err }
748    }
749
750    /// Special case of [`Self::macro_expand`] for procedural macros. We can't LRU
751    /// proc macros, since they are not deterministic in general, and
752    /// non-determinism breaks salsa in a very, very, very bad way.
753    /// @edwin0cheng heroically debugged this once! See #4315 for details
754    #[salsa::tracked(returns(ref))]
755    fn expand_proc_macro(self, db: &dyn SourceDatabase) -> ExpandResult<tt::TopSubtree> {
756        let loc = self.loc(db);
757        let (macro_arg, undo_info, span) = self.macro_arg_considering_derives(db, &loc.kind);
758
759        let (ast, expander) = match loc.def.kind {
760            MacroDefKind::ProcMacro(ast, expander, _) => (ast, expander),
761            _ => unreachable!(),
762        };
763
764        let attr_arg = match &loc.kind {
765            MacroCallKind::Attr { attr_args: Some(attr_args), .. } => Some(&**attr_args),
766            _ => None,
767        };
768
769        let ExpandResult { value: mut tt, err } = {
770            let span = proc_macro_span(db, ast);
771            expander.expand(
772                db,
773                loc.def.krate,
774                loc.krate,
775                macro_arg,
776                attr_arg,
777                span_with_def_site_ctxt(db, span, self.into(), loc.def.edition),
778                span_with_call_site_ctxt(db, span, self.into(), loc.def.edition),
779                span_with_mixed_site_ctxt(db, span, self.into(), loc.def.edition),
780            )
781        };
782
783        // Set a hard limit for the expanded tt
784        if let Err(value) = check_tt_count(&tt) {
785            return value.map(|()| tt::TopSubtree::empty(tt::DelimSpan::from_single(*span)));
786        }
787
788        fixup::reverse_fixups(&mut tt, undo_info);
789
790        ExpandResult { value: tt, err }
791    }
792}
793
794impl MacroCallId {
795    /// This expands the given macro call, but with different arguments. This is
796    /// used for completion, where we want to see what 'would happen' if we insert a
797    /// token. The `token_to_map` mapped down into the expansion, with the mapped
798    /// token(s) returned with their priority.
799    pub fn expand_speculative(
800        self,
801        db: &dyn SourceDatabase,
802        speculative_args: &SyntaxNode,
803        token_to_map: SyntaxToken,
804    ) -> Option<(SyntaxNode, Vec<(SyntaxToken, u8)>)> {
805        let loc = self.loc(db);
806        let (_, _, span) = *self.macro_arg_considering_derives(db, &loc.kind);
807
808        let span_map = RealSpanMap::absolute(span.anchor.file_id);
809        let span_map = SpanMap::RealSpanMap(&span_map);
810
811        // Build the subtree and token mapping for the speculative args
812        let (mut tt, undo_info) = match &loc.kind {
813            MacroCallKind::FnLike { .. } => (
814                syntax_bridge::syntax_node_to_token_tree(
815                    speculative_args,
816                    span_map,
817                    span,
818                    if loc.def.is_proc_macro() {
819                        DocCommentDesugarMode::ProcMacro
820                    } else {
821                        DocCommentDesugarMode::Mbe
822                    },
823                ),
824                SyntaxFixupUndoInfo::NONE,
825            ),
826            MacroCallKind::Attr { .. } if loc.def.is_attribute_derive() => (
827                syntax_bridge::syntax_node_to_token_tree(
828                    speculative_args,
829                    span_map,
830                    span,
831                    DocCommentDesugarMode::ProcMacro,
832                ),
833                SyntaxFixupUndoInfo::NONE,
834            ),
835            MacroCallKind::Derive { derive_macro_id, .. } => {
836                let MacroCallKind::Attr { censored_attr_ids: attr_ids, .. } =
837                    &derive_macro_id.loc(db).kind
838                else {
839                    unreachable!("`derive_macro_id` should be `MacroCallKind::Attr`");
840                };
841                attr_macro_input_to_token_tree(
842                    db,
843                    speculative_args,
844                    span_map,
845                    span,
846                    true,
847                    attr_ids,
848                    loc.krate,
849                )
850            }
851            MacroCallKind::Attr { censored_attr_ids: attr_ids, .. } => {
852                attr_macro_input_to_token_tree(
853                    db,
854                    speculative_args,
855                    span_map,
856                    span,
857                    false,
858                    attr_ids,
859                    loc.krate,
860                )
861            }
862        };
863
864        let attr_arg = match &loc.kind {
865            MacroCallKind::Attr { censored_attr_ids: attr_ids, .. } => {
866                if loc.def.is_attribute_derive() {
867                    // for pseudo-derive expansion we actually pass the attribute itself only
868                    ast::Attr::cast(speculative_args.clone())
869                        .and_then(|attr| {
870                            if let ast::Meta::TokenTreeMeta(meta) = attr.meta()? {
871                                meta.token_tree()
872                            } else {
873                                None
874                            }
875                        })
876                        .map(|token_tree| {
877                            let mut tree = syntax_node_to_token_tree(
878                                token_tree.syntax(),
879                                span_map,
880                                span,
881                                DocCommentDesugarMode::ProcMacro,
882                            );
883                            tree.set_top_subtree_delimiter_kind(tt::DelimiterKind::Invisible);
884                            tree.set_top_subtree_delimiter_span(tt::DelimSpan::from_single(span));
885                            tree
886                        })
887                } else {
888                    // Attributes may have an input token tree, build the subtree and map for this as well
889                    // then try finding a token id for our token if it is inside this input subtree.
890                    let item = ast::Item::cast(speculative_args.clone())?;
891                    let (_, meta) = attr_ids
892                        .invoc_attr()
893                        .find_attr_range_with_source_opt(db, loc.krate, &item)?;
894                    if let ast::Meta::TokenTreeMeta(meta) = meta
895                        && let Some(tt) = meta.token_tree()
896                    {
897                        let mut attr_arg = syntax_bridge::syntax_node_to_token_tree(
898                            tt.syntax(),
899                            span_map,
900                            span,
901                            DocCommentDesugarMode::ProcMacro,
902                        );
903                        attr_arg.set_top_subtree_delimiter_kind(tt::DelimiterKind::Invisible);
904                        Some(attr_arg)
905                    } else {
906                        None
907                    }
908                }
909            }
910            _ => None,
911        };
912
913        // Do the actual expansion, we need to directly expand the proc macro due to the attribute args
914        // Otherwise the expand query will fetch the non speculative attribute args and pass those instead.
915        let mut speculative_expansion = match loc.def.kind {
916            MacroDefKind::ProcMacro(ast, expander, _) => {
917                let span = proc_macro_span(db, ast);
918                tt.set_top_subtree_delimiter_kind(tt::DelimiterKind::Invisible);
919                tt.set_top_subtree_delimiter_span(tt::DelimSpan::from_single(span));
920                expander.expand(
921                    db,
922                    loc.def.krate,
923                    loc.krate,
924                    &tt,
925                    attr_arg.as_ref(),
926                    span_with_def_site_ctxt(db, span, self.into(), loc.def.edition),
927                    span_with_call_site_ctxt(db, span, self.into(), loc.def.edition),
928                    span_with_mixed_site_ctxt(db, span, self.into(), loc.def.edition),
929                )
930            }
931            MacroDefKind::BuiltInAttr(_, it) if it.is_derive() => {
932                pseudo_derive_attr_expansion(&tt, attr_arg.as_ref()?, span)
933            }
934            MacroDefKind::Declarative(it, _) => it
935                .decl_macro_expander(db, loc.krate)
936                .expand_unhygienic(db, &tt, loc.kind.call_style(), span),
937            MacroDefKind::BuiltIn(_, it) => it.expand(db, self, &tt, span).map_err(Into::into),
938            MacroDefKind::BuiltInDerive(_, it) => {
939                it.expand(db, self, &tt, span).map_err(Into::into)
940            }
941            MacroDefKind::BuiltInEager(_, it) => it.expand(db, self, &tt, span).map_err(Into::into),
942            MacroDefKind::BuiltInAttr(_, it) => it.expand(db, self, &tt, span),
943            MacroDefKind::UnimplementedBuiltIn(_) => expand_unimplemented_builtin_macro(span),
944        };
945
946        let expand_to = loc.expand_to();
947
948        fixup::reverse_fixups(&mut speculative_expansion.value, &undo_info);
949        let (node, rev_tmap) =
950            token_tree_to_syntax_node(db, &speculative_expansion.value, expand_to);
951
952        let syntax_node = node.syntax_node();
953        let token = rev_tmap
954            .ranges_with_span(span_map.span_for_range(token_to_map.text_range()))
955            .filter_map(|(range, ctx)| {
956                syntax_node.covering_element(range).into_token().zip(Some(ctx))
957            })
958            .map(|(t, ctx)| {
959                // prefer tokens of the same kind and text, as well as non opaque marked ones
960                // Note the inversion of the score here, as we want to prefer the first token in case
961                // of all tokens having the same score
962                let ranking = ctx.is_opaque(db) as u8
963                    + 2 * (t.kind() != token_to_map.kind()) as u8
964                    + 4 * ((t.text() != token_to_map.text()) as u8);
965                (t, ranking)
966            })
967            .collect();
968        Some((node.syntax_node(), token))
969    }
970}
971
972fn expand_unimplemented_builtin_macro(span: Span) -> ExpandResult<tt::TopSubtree> {
973    ExpandResult::new(
974        tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
975        ExpandError::other(span, "this built-in macro is not implemented"),
976    )
977}
978
979/// Retrieves the span to be used for a proc-macro expansions spans.
980/// This is a firewall query as it requires parsing the file, which we don't want proc-macros to
981/// directly depend on as that would cause to frequent invalidations, mainly because of the
982/// parse queries being LRU cached. If they weren't the invalidations would only happen if the
983/// user wrote in the file that defines the proc-macro.
984fn proc_macro_span(db: &dyn SourceDatabase, ast: AstId<ast::Fn>) -> Span {
985    #[salsa::tracked(returns(copy))]
986    fn proc_macro_span(db: &dyn SourceDatabase, ast: AstId<ast::Fn>, _: ()) -> Span {
987        let (parse, span_map) = ast.file_id.parse_with_map(db);
988        let root = parse.syntax_node();
989        let ast_id_map = ast.file_id.ast_id_map(db);
990
991        let node = ast_id_map.get(ast.value).to_node(&root);
992        let range = ast::HasName::name(&node)
993            .map_or_else(|| node.syntax().text_range(), |name| name.syntax().text_range());
994        span_map.span_for_range(range)
995    }
996    proc_macro_span(db, ast, ())
997}
998
999pub(crate) fn token_tree_to_syntax_node(
1000    db: &dyn SourceDatabase,
1001    tt: &tt::TopSubtree,
1002    expand_to: ExpandTo,
1003) -> (Parse<SyntaxNode>, ExpansionSpanMap) {
1004    let entry_point = match expand_to {
1005        ExpandTo::Statements => syntax_bridge::TopEntryPoint::MacroStmts,
1006        ExpandTo::Items => syntax_bridge::TopEntryPoint::MacroItems,
1007        ExpandTo::Pattern => syntax_bridge::TopEntryPoint::Pattern,
1008        ExpandTo::Type => syntax_bridge::TopEntryPoint::Type,
1009        ExpandTo::Expr => syntax_bridge::TopEntryPoint::Expr,
1010    };
1011    syntax_bridge::token_tree_to_syntax_node(tt, entry_point, &mut |ctx| ctx.edition(db))
1012}
1013
1014fn check_tt_count(tt: &tt::TopSubtree) -> Result<(), ExpandResult<()>> {
1015    let tt = tt.top_subtree();
1016    let count = tt.count();
1017    if count <= TOKEN_LIMIT {
1018        Ok(())
1019    } else {
1020        Err(ExpandResult {
1021            value: (),
1022            err: Some(ExpandError::other(
1023                tt.delimiter.open,
1024                format!(
1025                    "macro invocation exceeds token limit: produced {count} tokens, limit is {TOKEN_LIMIT}",
1026                ),
1027            )),
1028        })
1029    }
1030}
1031
1032impl MacroDefId {
1033    pub fn make_call(
1034        self,
1035        db: &dyn SourceDatabase,
1036        krate: Crate,
1037        kind: MacroCallKind,
1038        ctxt: SyntaxContext,
1039        macro_depth: u32,
1040    ) -> MacroCallId {
1041        MacroCallId::new(db, MacroCallLoc { def: self, krate, kind, ctxt, macro_depth })
1042    }
1043
1044    pub fn definition_range(&self, db: &dyn SourceDatabase) -> InFile<TextRange> {
1045        match self.kind {
1046            MacroDefKind::Declarative(id, _)
1047            | MacroDefKind::BuiltIn(id, _)
1048            | MacroDefKind::BuiltInAttr(id, _)
1049            | MacroDefKind::BuiltInDerive(id, _)
1050            | MacroDefKind::BuiltInEager(id, _)
1051            | MacroDefKind::UnimplementedBuiltIn(id) => {
1052                id.with_value(id.file_id.ast_id_map(db).get(id.value).text_range())
1053            }
1054            MacroDefKind::ProcMacro(id, _, _) => {
1055                id.with_value(id.file_id.ast_id_map(db).get(id.value).text_range())
1056            }
1057        }
1058    }
1059
1060    pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
1061        match self.kind {
1062            MacroDefKind::ProcMacro(id, ..) => Either::Right(id),
1063            MacroDefKind::Declarative(id, _)
1064            | MacroDefKind::BuiltIn(id, _)
1065            | MacroDefKind::BuiltInAttr(id, _)
1066            | MacroDefKind::BuiltInDerive(id, _)
1067            | MacroDefKind::BuiltInEager(id, _)
1068            | MacroDefKind::UnimplementedBuiltIn(id) => Either::Left(id),
1069        }
1070    }
1071
1072    pub fn is_proc_macro(&self) -> bool {
1073        matches!(self.kind, MacroDefKind::ProcMacro(..))
1074    }
1075
1076    pub fn is_attribute(&self) -> bool {
1077        match self.kind {
1078            MacroDefKind::BuiltInAttr(..)
1079            | MacroDefKind::ProcMacro(_, _, ProcMacroKind::Attr)
1080            | MacroDefKind::UnimplementedBuiltIn(_) => true,
1081            MacroDefKind::Declarative(_, styles) => styles.contains(MacroCallStyles::ATTR),
1082            _ => false,
1083        }
1084    }
1085
1086    pub fn is_derive(&self) -> bool {
1087        match self.kind {
1088            MacroDefKind::BuiltInDerive(..)
1089            | MacroDefKind::ProcMacro(_, _, ProcMacroKind::CustomDerive)
1090            | MacroDefKind::UnimplementedBuiltIn(_) => true,
1091            MacroDefKind::Declarative(_, styles) => styles.contains(MacroCallStyles::DERIVE),
1092            _ => false,
1093        }
1094    }
1095
1096    pub fn is_fn_like(&self) -> bool {
1097        matches!(
1098            self.kind,
1099            MacroDefKind::BuiltIn(..)
1100                | MacroDefKind::ProcMacro(_, _, ProcMacroKind::Bang)
1101                | MacroDefKind::BuiltInEager(..)
1102                | MacroDefKind::Declarative(..)
1103                | MacroDefKind::UnimplementedBuiltIn(_)
1104        )
1105    }
1106
1107    pub fn is_attribute_derive(&self) -> bool {
1108        matches!(self.kind, MacroDefKind::BuiltInAttr(_, expander) if expander.is_derive())
1109    }
1110
1111    pub fn is_include(&self) -> bool {
1112        matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_include())
1113    }
1114
1115    pub fn is_include_like(&self) -> bool {
1116        matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_include_like())
1117    }
1118
1119    pub fn is_env_or_option_env(&self) -> bool {
1120        matches!(self.kind, MacroDefKind::BuiltInEager(_, expander) if expander.is_env_or_option_env())
1121    }
1122}
1123
1124impl MacroCallLoc {
1125    pub fn to_node(&self, db: &dyn SourceDatabase) -> InFile<SyntaxNode> {
1126        match &self.kind {
1127            MacroCallKind::FnLike { ast_id, .. } => {
1128                ast_id.with_value(ast_id.to_node(db).syntax().clone())
1129            }
1130            MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
1131                let (_, attr) = derive_attr_index.find_attr_range(db, self.krate, *ast_id);
1132                ast_id.with_value(attr.syntax().clone())
1133            }
1134            MacroCallKind::Attr { ast_id, censored_attr_ids: attr_ids, .. } => {
1135                if self.def.is_attribute_derive() {
1136                    let (_, attr) = attr_ids.invoc_attr().find_attr_range(db, self.krate, *ast_id);
1137                    ast_id.with_value(attr.syntax().clone())
1138                } else {
1139                    ast_id.with_value(ast_id.to_node(db).syntax().clone())
1140                }
1141            }
1142        }
1143    }
1144
1145    pub fn to_node_item(&self, db: &dyn SourceDatabase) -> InFile<ast::Item> {
1146        match self.kind {
1147            MacroCallKind::FnLike { ast_id, .. } => {
1148                InFile::new(ast_id.file_id, ast_id.map(FileAstId::upcast).to_node(db))
1149            }
1150            MacroCallKind::Derive { ast_id, .. } => {
1151                InFile::new(ast_id.file_id, ast_id.map(FileAstId::upcast).to_node(db))
1152            }
1153            MacroCallKind::Attr { ast_id, .. } => InFile::new(ast_id.file_id, ast_id.to_node(db)),
1154        }
1155    }
1156
1157    fn expand_to(&self) -> ExpandTo {
1158        match self.kind {
1159            MacroCallKind::FnLike { expand_to, .. } => expand_to,
1160            MacroCallKind::Derive { .. } => ExpandTo::Items,
1161            MacroCallKind::Attr { .. } if self.def.is_attribute_derive() => ExpandTo::Items,
1162            MacroCallKind::Attr { .. } => {
1163                // FIXME(stmt_expr_attributes)
1164                ExpandTo::Items
1165            }
1166        }
1167    }
1168
1169    pub fn include_file_id(
1170        &self,
1171        db: &dyn SourceDatabase,
1172        macro_call_id: MacroCallId,
1173    ) -> Option<EditionedFileId> {
1174        if self.def.is_include()
1175            && let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind
1176            && let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg)
1177        {
1178            return Some(it);
1179        }
1180
1181        None
1182    }
1183}
1184
1185impl MacroCallKind {
1186    pub fn descr(&self) -> &'static str {
1187        match self {
1188            MacroCallKind::FnLike { .. } => "macro call",
1189            MacroCallKind::Derive { .. } => "derive macro",
1190            MacroCallKind::Attr { .. } => "attribute macro",
1191        }
1192    }
1193
1194    /// Returns the file containing the macro invocation.
1195    pub fn file_id(&self) -> HirFileId {
1196        match *self {
1197            MacroCallKind::FnLike { ast_id: InFile { file_id, .. }, .. }
1198            | MacroCallKind::Derive { ast_id: InFile { file_id, .. }, .. }
1199            | MacroCallKind::Attr { ast_id: InFile { file_id, .. }, .. } => file_id,
1200        }
1201    }
1202
1203    pub fn erased_ast_id(&self) -> ErasedFileAstId {
1204        match *self {
1205            MacroCallKind::FnLike { ast_id: InFile { value, .. }, .. } => value.erase(),
1206            MacroCallKind::Derive { ast_id: InFile { value, .. }, .. } => value.erase(),
1207            MacroCallKind::Attr { ast_id: InFile { value, .. }, .. } => value.erase(),
1208        }
1209    }
1210
1211    /// Returns the original file range that best describes the location of this macro call.
1212    ///
1213    /// This spans the entire macro call, including its input. That is for
1214    /// - fn_like! {}, it spans the path and token tree
1215    /// - #\[derive], it spans the `#[derive(...)]` attribute and the annotated item
1216    /// - #\[attr], it spans the `#[attr(...)]` attribute and the annotated item
1217    pub fn original_call_range_with_input(&self, db: &dyn SourceDatabase) -> FileRange {
1218        let get_range = |kind: &_| match kind {
1219            MacroCallKind::FnLike { ast_id, .. } => ast_id.erase(),
1220            MacroCallKind::Derive { ast_id, .. } => ast_id.erase(),
1221            MacroCallKind::Attr { ast_id, .. } => ast_id.erase(),
1222        };
1223
1224        let mut ast_id = get_range(self);
1225        let mut file_id = self.file_id();
1226        let file_id = loop {
1227            match file_id {
1228                HirFileId::MacroFile(file) => {
1229                    let kind = &file.loc(db).kind;
1230                    ast_id = get_range(kind);
1231                    file_id = kind.file_id();
1232                }
1233                HirFileId::FileId(file_id) => break file_id,
1234            }
1235        };
1236
1237        FileRange { range: ast_id.to_ptr(db).text_range(), file_id }
1238    }
1239
1240    /// Returns the original file range that best describes the location of this macro call.
1241    ///
1242    /// Here we try to roughly match what rustc does to improve diagnostics: fn-like macros
1243    /// get the macro path (rustc shows the whole `ast::MacroCall`), attribute macros get the
1244    /// attribute's range, and derives get only the specific derive that is being referred to.
1245    pub fn original_call_range(&self, db: &dyn SourceDatabase, krate: Crate) -> FileRange {
1246        let get_range = |kind: &_| match kind {
1247            MacroCallKind::FnLike { ast_id, .. } => {
1248                let node = ast_id.to_node(db);
1249                node.path()
1250                    .unwrap()
1251                    .syntax()
1252                    .text_range()
1253                    .cover(node.excl_token().unwrap().text_range())
1254            }
1255            MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
1256                // FIXME: should be the range of the macro name, not the whole derive
1257                derive_attr_index.find_attr_range(db, krate, *ast_id).1.syntax().text_range()
1258            }
1259            // FIXME: handle `cfg_attr`
1260            MacroCallKind::Attr { ast_id, censored_attr_ids: attr_ids, .. } => {
1261                attr_ids.invoc_attr().find_attr_range(db, krate, *ast_id).1.syntax().text_range()
1262            }
1263        };
1264
1265        let mut range = get_range(self);
1266        let mut file_id = self.file_id();
1267        let file_id = loop {
1268            match file_id {
1269                HirFileId::MacroFile(file) => {
1270                    let kind = &file.loc(db).kind;
1271                    range = get_range(kind);
1272                    file_id = kind.file_id();
1273                }
1274                HirFileId::FileId(file_id) => break file_id,
1275            }
1276        };
1277
1278        FileRange { range, file_id }
1279    }
1280
1281    fn arg(&self, db: &dyn SourceDatabase) -> InFile<Option<SyntaxNode>> {
1282        match self {
1283            MacroCallKind::FnLike { ast_id, .. } => {
1284                ast_id.to_in_file_node(db).map(|it| Some(it.token_tree()?.syntax().clone()))
1285            }
1286            MacroCallKind::Derive { ast_id, .. } => {
1287                ast_id.to_in_file_node(db).syntax().cloned().map(Some)
1288            }
1289            MacroCallKind::Attr { ast_id, .. } => {
1290                ast_id.to_in_file_node(db).syntax().cloned().map(Some)
1291            }
1292        }
1293    }
1294}
1295
1296/// ExpansionInfo mainly describes how to map text range between src and expanded macro
1297// FIXME: can be expensive to create, we should check the use sites and maybe replace them with
1298// simpler function calls if the map is only used once
1299#[derive(Clone, Debug, PartialEq, Eq)]
1300pub struct ExpansionInfo<'db> {
1301    expanded: InMacroFile<SyntaxNode>,
1302    /// The argument TokenTree or item for attributes
1303    arg: InFile<Option<SyntaxNode>>,
1304    exp_map: &'db ExpansionSpanMap,
1305    arg_map: SpanMap<'db>,
1306    loc: &'db MacroCallLoc,
1307}
1308
1309impl<'db> ExpansionInfo<'db> {
1310    pub fn expanded(&self) -> InMacroFile<SyntaxNode> {
1311        self.expanded.clone()
1312    }
1313
1314    pub fn arg(&self) -> InFile<Option<&SyntaxNode>> {
1315        self.arg.as_ref().map(|it| it.as_ref())
1316    }
1317
1318    pub fn call_file(&self) -> HirFileId {
1319        self.arg.file_id
1320    }
1321
1322    pub fn is_attr(&self) -> bool {
1323        matches!(
1324            self.loc.def.kind,
1325            MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, _, ProcMacroKind::Attr)
1326        )
1327    }
1328
1329    /// Maps the passed in file range down into a macro expansion if it is the input to a macro call.
1330    ///
1331    /// Note this does a linear search through the entire backing vector of the spanmap.
1332    // FIXME: Consider adding a reverse map to ExpansionInfo to get rid of the linear search which
1333    // potentially results in quadratic look ups (notably this might improve semantic highlighting perf)
1334    pub fn map_range_down_exact(
1335        &self,
1336        span: Span,
1337    ) -> Option<InMacroFile<impl Iterator<Item = (SyntaxToken, SyntaxContext)> + '_>> {
1338        if span.anchor.ast_id == NO_DOWNMAP_ERASED_FILE_AST_ID_MARKER {
1339            return None;
1340        }
1341
1342        let tokens = self.exp_map.ranges_with_span_exact(span).flat_map(move |(range, ctx)| {
1343            self.expanded.value.covering_element(range).into_token().zip(Some(ctx))
1344        });
1345
1346        Some(InMacroFile::new(self.expanded.file_id, tokens))
1347    }
1348
1349    /// Maps the passed in file range down into a macro expansion if it is the input to a macro call.
1350    /// Unlike [`ExpansionInfo::map_range_down_exact`], this will consider spans that contain the given span.
1351    ///
1352    /// Note this does a linear search through the entire backing vector of the spanmap.
1353    pub fn map_range_down(
1354        &self,
1355        span: Span,
1356    ) -> Option<InMacroFile<impl Iterator<Item = (SyntaxToken, SyntaxContext)> + '_>> {
1357        if span.anchor.ast_id == NO_DOWNMAP_ERASED_FILE_AST_ID_MARKER {
1358            return None;
1359        }
1360
1361        let tokens = self.exp_map.ranges_with_span(span).flat_map(move |(range, ctx)| {
1362            self.expanded.value.covering_element(range).into_token().zip(Some(ctx))
1363        });
1364
1365        Some(InMacroFile::new(self.expanded.file_id, tokens))
1366    }
1367
1368    /// Looks up the span at the given offset.
1369    pub fn span_for_offset(
1370        &self,
1371        db: &dyn SourceDatabase,
1372        offset: TextSize,
1373    ) -> (FileRange, SyntaxContext) {
1374        debug_assert!(self.expanded.value.text_range().contains(offset));
1375        span_for_offset(db, self.exp_map, offset)
1376    }
1377
1378    /// Maps up the text range out of the expansion hierarchy back into the original file its from.
1379    pub fn map_node_range_up(
1380        &self,
1381        db: &dyn SourceDatabase,
1382        range: TextRange,
1383    ) -> Option<(FileRange, SyntaxContext)> {
1384        debug_assert!(self.expanded.value.text_range().contains_range(range));
1385        map_node_range_up(db, self.exp_map, range)
1386    }
1387
1388    /// Maps up the text range out of the expansion into its macro call.
1389    ///
1390    /// Note that this may return multiple ranges as we lose the precise association between input to output
1391    /// and as such we may consider inputs that are unrelated.
1392    pub fn map_range_up_once(
1393        &self,
1394        db: &dyn SourceDatabase,
1395        token: TextRange,
1396    ) -> InFile<smallvec::SmallVec<[TextRange; 1]>> {
1397        debug_assert!(self.expanded.value.text_range().contains_range(token));
1398        let span = self.exp_map.span_at(token.start());
1399        match &self.arg_map {
1400            SpanMap::RealSpanMap(_) => {
1401                let range = resolve_span(db, span);
1402                InFile { file_id: range.file_id.into(), value: smallvec::smallvec![range.range] }
1403            }
1404            SpanMap::ExpansionSpanMap(arg_map) => {
1405                let Some(arg_node) = &self.arg.value else {
1406                    return InFile::new(self.arg.file_id, smallvec::smallvec![]);
1407                };
1408                let arg_range = arg_node.text_range();
1409                InFile::new(
1410                    self.arg.file_id,
1411                    arg_map
1412                        .ranges_with_span_exact(span)
1413                        .map(|(range, _)| range)
1414                        .filter(|range| range.intersect(arg_range).is_some())
1415                        .collect(),
1416                )
1417            }
1418        }
1419    }
1420
1421    pub fn new(db: &'db dyn SourceDatabase, macro_file: MacroCallId) -> ExpansionInfo<'db> {
1422        let _p = tracing::info_span!("ExpansionInfo::new").entered();
1423        let loc = macro_file.loc(db);
1424
1425        let arg_tt = loc.kind.arg(db);
1426        let arg_map = arg_tt.file_id.span_map(db);
1427
1428        let (parse, exp_map) = &macro_file.parse_macro_expansion(db).value;
1429        let expanded = InMacroFile { file_id: macro_file, value: parse.syntax_node() };
1430
1431        ExpansionInfo { expanded, loc, arg: arg_tt, exp_map, arg_map }
1432    }
1433}
1434
1435/// Maps up the text range out of the expansion hierarchy back into the original file its from only
1436/// considering the root spans contained.
1437/// Unlike [`map_node_range_up`], this will not return `None` if any anchors or syntax contexts differ.
1438pub fn map_node_range_up_rooted(
1439    db: &dyn SourceDatabase,
1440    exp_map: &ExpansionSpanMap,
1441    range: TextRange,
1442) -> Option<FileRange> {
1443    let mut spans = exp_map.spans_for_range(range).filter(|span| span.ctx.is_root());
1444    let Span { range, anchor, ctx } = spans.next()?;
1445    let mut start = range.start();
1446    let mut end = range.end();
1447
1448    for span in spans {
1449        if span.anchor != anchor {
1450            return None;
1451        }
1452        start = start.min(span.range.start());
1453        end = end.max(span.range.end());
1454    }
1455    Some(resolve_span(db, Span { range: TextRange::new(start, end), anchor, ctx }))
1456}
1457
1458/// Maps up the text range out of the expansion hierarchy back into the original file its from.
1459///
1460/// this will return `None` if any anchors or syntax contexts differ.
1461pub fn map_node_range_up(
1462    db: &dyn SourceDatabase,
1463    exp_map: &ExpansionSpanMap,
1464    range: TextRange,
1465) -> Option<(FileRange, SyntaxContext)> {
1466    let mut spans = exp_map.spans_for_range(range);
1467    let Span { range, anchor, ctx } = spans.next()?;
1468    let mut start = range.start();
1469    let mut end = range.end();
1470
1471    for span in spans {
1472        if span.anchor != anchor || span.ctx != ctx {
1473            return None;
1474        }
1475        start = start.min(span.range.start());
1476        end = end.max(span.range.end());
1477    }
1478    Some((resolve_span(db, Span { range: TextRange::new(start, end), anchor, ctx }), ctx))
1479}
1480
1481/// Looks up the span at the given offset.
1482pub fn span_for_offset(
1483    db: &dyn SourceDatabase,
1484    exp_map: &ExpansionSpanMap,
1485    offset: TextSize,
1486) -> (FileRange, SyntaxContext) {
1487    let span = exp_map.span_at(offset);
1488    (resolve_span(db, span), span.ctx)
1489}
1490
1491// FIXME: This is only public because of its use in `load_cargo` (which we should consider removing
1492// by moving the implementations of the subrequests to `hir_expand`, and calling within `load-cargo`).
1493// Avoid adding any more outside uses.
1494pub fn resolve_span(db: &dyn SourceDatabase, Span { range, anchor, ctx: _ }: Span) -> FileRange {
1495    let file_id = EditionedFileId::from_span_file_id(db, anchor.file_id);
1496    let anchor_offset =
1497        HirFileId::from(file_id).ast_id_map(db).get_erased(anchor.ast_id).text_range().start();
1498    FileRange { file_id, range: range + anchor_offset }
1499}
1500
1501/// In Rust, macros expand token trees to token trees. When we want to turn a
1502/// token tree into an AST node, we need to figure out what kind of AST node we
1503/// want: something like `foo` can be a type, an expression, or a pattern.
1504///
1505/// Naively, one would think that "what this expands to" is a property of a
1506/// particular macro: macro `m1` returns an item, while macro `m2` returns an
1507/// expression, etc. That's not the case -- macros are polymorphic in the
1508/// result, and can expand to any type of the AST node.
1509///
1510/// What defines the actual AST node is the syntactic context of the macro
1511/// invocation. As a contrived example, in `let T![*] = T![*];` the first `T`
1512/// expands to a pattern, while the second one expands to an expression.
1513///
1514/// `ExpandTo` captures this bit of information about a particular macro call
1515/// site.
1516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1517pub enum ExpandTo {
1518    Statements,
1519    Items,
1520    Pattern,
1521    Type,
1522    Expr,
1523}
1524
1525impl ExpandTo {
1526    pub fn from_call_site(call: &ast::MacroCall) -> ExpandTo {
1527        use syntax::SyntaxKind::*;
1528
1529        let syn = call.syntax();
1530
1531        let parent = match syn.parent() {
1532            Some(it) => it,
1533            None => return ExpandTo::Statements,
1534        };
1535
1536        // FIXME: macros in statement position are treated as expression statements, they should
1537        // probably be their own statement kind. The *grand*parent indicates what's valid.
1538        if parent.kind() == MACRO_EXPR
1539            && parent
1540                .parent()
1541                .is_some_and(|p| matches!(p.kind(), EXPR_STMT | STMT_LIST | MACRO_STMTS))
1542        {
1543            return ExpandTo::Statements;
1544        }
1545
1546        match parent.kind() {
1547            MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => ExpandTo::Items,
1548            MACRO_STMTS | EXPR_STMT | STMT_LIST => ExpandTo::Statements,
1549            MACRO_PAT => ExpandTo::Pattern,
1550            MACRO_TYPE => ExpandTo::Type,
1551
1552            ARG_LIST | ARRAY_EXPR | AWAIT_EXPR | BIN_EXPR | BREAK_EXPR | CALL_EXPR | CAST_EXPR
1553            | CLOSURE_EXPR | FIELD_EXPR | FOR_EXPR | IF_EXPR | INDEX_EXPR | LET_EXPR
1554            | MATCH_ARM | MATCH_EXPR | MATCH_GUARD | METHOD_CALL_EXPR | PAREN_EXPR | PATH_EXPR
1555            | PREFIX_EXPR | RANGE_EXPR | RECORD_EXPR_FIELD | REF_EXPR | RETURN_EXPR | TRY_EXPR
1556            | TUPLE_EXPR | WHILE_EXPR | MACRO_EXPR => ExpandTo::Expr,
1557            _ => {
1558                // Unknown , Just guess it is `Items`
1559                ExpandTo::Items
1560            }
1561        }
1562    }
1563}
1564
1565/// Macro ids. That's probably the tricksiest bit in rust-analyzer, and the
1566/// reason why we use salsa at all.
1567///
1568/// We encode macro definitions into ids of macro calls, this what allows us
1569/// to be incremental.
1570#[salsa::interned(unsafe(no_lifetime), debug, revisions = usize::MAX)]
1571#[doc(alias = "MacroFileId")]
1572pub struct MacroCallId {
1573    #[returns(ref)]
1574    pub loc: MacroCallLoc,
1575}
1576
1577impl From<span::MacroCallId> for MacroCallId {
1578    #[inline]
1579    fn from(value: span::MacroCallId) -> Self {
1580        MacroCallId::from_id(value.0)
1581    }
1582}
1583
1584impl From<MacroCallId> for span::MacroCallId {
1585    #[inline]
1586    fn from(value: MacroCallId) -> span::MacroCallId {
1587        span::MacroCallId(value.as_id())
1588    }
1589}
1590
1591#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
1592pub enum HirFileId {
1593    FileId(EditionedFileId),
1594    MacroFile(MacroCallId),
1595}
1596
1597impl From<EditionedFileId> for HirFileId {
1598    #[inline]
1599    fn from(file_id: EditionedFileId) -> Self {
1600        HirFileId::FileId(file_id)
1601    }
1602}
1603
1604impl From<MacroCallId> for HirFileId {
1605    #[inline]
1606    fn from(file_id: MacroCallId) -> Self {
1607        HirFileId::MacroFile(file_id)
1608    }
1609}
1610
1611impl PartialEq<EditionedFileId> for HirFileId {
1612    fn eq(&self, &other: &EditionedFileId) -> bool {
1613        *self == HirFileId::from(other)
1614    }
1615}
1616impl PartialEq<HirFileId> for EditionedFileId {
1617    fn eq(&self, &other: &HirFileId) -> bool {
1618        other == HirFileId::from(*self)
1619    }
1620}
1621
1622impl HirFileId {
1623    #[inline]
1624    pub fn macro_file(self) -> Option<MacroCallId> {
1625        match self {
1626            HirFileId::FileId(_) => None,
1627            HirFileId::MacroFile(it) => Some(it),
1628        }
1629    }
1630
1631    #[inline]
1632    pub fn is_macro(self) -> bool {
1633        matches!(self, HirFileId::MacroFile(_))
1634    }
1635
1636    #[inline]
1637    pub fn file_id(self) -> Option<EditionedFileId> {
1638        match self {
1639            HirFileId::FileId(it) => Some(it),
1640            HirFileId::MacroFile(_) => None,
1641        }
1642    }
1643
1644    pub fn syntax_context(self, db: &dyn SourceDatabase, edition: Edition) -> SyntaxContext {
1645        match self {
1646            HirFileId::FileId(_) => SyntaxContext::root(edition),
1647            HirFileId::MacroFile(m) => {
1648                let kind = &m.loc(db).kind;
1649                m.macro_arg_considering_derives(db, kind).2.ctx
1650            }
1651        }
1652    }
1653
1654    pub fn edition(self, db: &dyn SourceDatabase) -> Edition {
1655        match self {
1656            HirFileId::FileId(file_id) => file_id.edition(db),
1657            HirFileId::MacroFile(m) => m.loc(db).def.edition,
1658        }
1659    }
1660
1661    pub fn original_file(self, db: &dyn SourceDatabase) -> EditionedFileId {
1662        let mut file_id = self;
1663        loop {
1664            match file_id {
1665                HirFileId::FileId(id) => break id,
1666                HirFileId::MacroFile(macro_call_id) => {
1667                    file_id = macro_call_id.loc(db).kind.file_id()
1668                }
1669            }
1670        }
1671    }
1672
1673    pub fn original_file_respecting_includes(mut self, db: &dyn SourceDatabase) -> EditionedFileId {
1674        loop {
1675            match self {
1676                HirFileId::FileId(id) => break id,
1677                HirFileId::MacroFile(file) => {
1678                    let loc = file.loc(db);
1679                    if loc.def.is_include()
1680                        && let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind
1681                        && let Ok(it) = include_input_to_file_id(db, file, &eager.arg)
1682                    {
1683                        break it;
1684                    }
1685                    self = loc.kind.file_id();
1686                }
1687            }
1688        }
1689    }
1690
1691    pub fn original_call_node(self, db: &dyn SourceDatabase) -> Option<InRealFile<SyntaxNode>> {
1692        let mut call = self.macro_file()?.loc(db).to_node(db);
1693        loop {
1694            match call.file_id {
1695                HirFileId::FileId(file_id) => {
1696                    break Some(InRealFile { file_id, value: call.value });
1697                }
1698                HirFileId::MacroFile(macro_call_id) => {
1699                    call = macro_call_id.loc(db).to_node(db);
1700                }
1701            }
1702        }
1703    }
1704
1705    pub fn call_node(self, db: &dyn SourceDatabase) -> Option<InFile<SyntaxNode>> {
1706        Some(self.macro_file()?.loc(db).to_node(db))
1707    }
1708
1709    pub fn as_builtin_derive_attr_node(
1710        &self,
1711        db: &dyn SourceDatabase,
1712    ) -> Option<InFile<ast::Attr>> {
1713        let macro_file = self.macro_file()?;
1714        let loc = macro_file.loc(db);
1715        let attr = match loc.def.kind {
1716            MacroDefKind::BuiltInDerive(..) => loc.to_node(db),
1717            _ => return None,
1718        };
1719        Some(attr.with_value(ast::Attr::cast(attr.value.clone())?))
1720    }
1721
1722    /// Main public API -- parses a hir file, not caring whether it's a real
1723    /// file or a macro expansion.
1724    pub fn parse_or_expand(self, db: &dyn SourceDatabase) -> SyntaxNode {
1725        match self {
1726            HirFileId::FileId(file_id) => file_id.parse(db).syntax_node(),
1727            HirFileId::MacroFile(macro_file) => {
1728                macro_file.parse_macro_expansion(db).value.0.syntax_node()
1729            }
1730        }
1731    }
1732
1733    pub(crate) fn parse_with_map(
1734        self,
1735        db: &dyn SourceDatabase,
1736    ) -> (Parse<SyntaxNode>, SpanMap<'_>) {
1737        match self {
1738            HirFileId::FileId(file_id) => (
1739                file_id.parse(db).to_syntax(),
1740                SpanMap::RealSpanMap(crate::span_map::real_span_map(db, file_id)),
1741            ),
1742            HirFileId::MacroFile(macro_file) => {
1743                let (parse, map) = &macro_file.parse_macro_expansion(db).value;
1744                (parse.clone(), SpanMap::ExpansionSpanMap(map))
1745            }
1746        }
1747    }
1748
1749    /// How many macro expansions separate this file from the real file it originates from.
1750    ///
1751    /// `Expander` and `DefCollector` seed their expansion depth counters from this. Both otherwise
1752    /// start at zero for every body and every block, so a macro expanding to an item that invokes
1753    /// the macro again advances neither counter past one and never reaches the recursion limit.
1754    ///
1755    /// Written recursively rather than as a loop so that salsa memoizes each file's depth. Callers
1756    /// ask for this once per body, and the bodies of one expansion chain sit at depths 1..n, so a
1757    /// loop would walk 1 + 2 + ... + n steps for that chain. Reusing the parent's memoized depth
1758    /// makes each file O(1) once computed, and the chain linear.
1759    #[inline]
1760    pub fn macro_expansion_depth(self, db: &dyn SourceDatabase) -> u32 {
1761        match self {
1762            HirFileId::MacroFile(macro_call) => macro_call.loc(db).macro_depth,
1763            HirFileId::FileId(_) => 0,
1764        }
1765    }
1766}
1767
1768#[salsa::tracked]
1769impl HirFileId {
1770    #[salsa::tracked(lru = 1024, returns(ref))]
1771    pub fn ast_id_map(self, db: &dyn SourceDatabase) -> AstIdMap {
1772        AstIdMap::from_source(&self.parse_or_expand(db))
1773    }
1774}