]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/lib.rs
fix: Fix SearchScope using incorrect text ranges for macro-emitted inline modules
[rust.git] / crates / hir_expand / src / 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
7 pub mod db;
8 pub mod ast_id_map;
9 pub mod name;
10 pub mod hygiene;
11 pub mod builtin_attr_macro;
12 pub mod builtin_derive_macro;
13 pub mod builtin_fn_macro;
14 pub mod proc_macro;
15 pub mod quote;
16 pub mod eager;
17 pub mod mod_path;
18 mod fixup;
19
20 pub use mbe::{Origin, ValueResult};
21
22 use std::{fmt, hash::Hash, iter, sync::Arc};
23
24 use base_db::{impl_intern_key, salsa, CrateId, FileId, FileRange, ProcMacroKind};
25 use either::Either;
26 use syntax::{
27     algo::{self, skip_trivia_token},
28     ast::{self, AstNode, HasDocComments},
29     Direction, SyntaxNode, SyntaxToken,
30 };
31
32 use crate::{
33     ast_id_map::FileAstId,
34     builtin_attr_macro::BuiltinAttrExpander,
35     builtin_derive_macro::BuiltinDeriveExpander,
36     builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
37     db::TokenExpander,
38     mod_path::ModPath,
39     proc_macro::ProcMacroExpander,
40 };
41
42 pub type ExpandResult<T> = ValueResult<T, ExpandError>;
43
44 #[derive(Debug, PartialEq, Eq, Clone)]
45 pub enum ExpandError {
46     UnresolvedProcMacro,
47     Mbe(mbe::ExpandError),
48     Other(Box<str>),
49 }
50
51 impl From<mbe::ExpandError> for ExpandError {
52     fn from(mbe: mbe::ExpandError) -> Self {
53         Self::Mbe(mbe)
54     }
55 }
56
57 impl fmt::Display for ExpandError {
58     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59         match self {
60             ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc-macro"),
61             ExpandError::Mbe(it) => it.fmt(f),
62             ExpandError::Other(it) => f.write_str(it),
63         }
64     }
65 }
66
67 /// Input to the analyzer is a set of files, where each file is identified by
68 /// `FileId` and contains source code. However, another source of source code in
69 /// Rust are macros: each macro can be thought of as producing a "temporary
70 /// file". To assign an id to such a file, we use the id of the macro call that
71 /// produced the file. So, a `HirFileId` is either a `FileId` (source code
72 /// written by user), or a `MacroCallId` (source code produced by macro).
73 ///
74 /// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
75 /// containing the call plus the offset of the macro call in the file. Note that
76 /// this is a recursive definition! However, the size_of of `HirFileId` is
77 /// finite (because everything bottoms out at the real `FileId`) and small
78 /// (`MacroCallId` uses the location interning. You can check details here:
79 /// <https://en.wikipedia.org/wiki/String_interning>).
80 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81 pub struct HirFileId(HirFileIdRepr);
82
83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84 enum HirFileIdRepr {
85     FileId(FileId),
86     MacroFile(MacroFile),
87 }
88
89 impl From<FileId> for HirFileId {
90     fn from(id: FileId) -> Self {
91         HirFileId(HirFileIdRepr::FileId(id))
92     }
93 }
94
95 impl From<MacroFile> for HirFileId {
96     fn from(id: MacroFile) -> Self {
97         HirFileId(HirFileIdRepr::MacroFile(id))
98     }
99 }
100
101 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102 pub struct MacroFile {
103     pub macro_call_id: MacroCallId,
104 }
105
106 /// `MacroCallId` identifies a particular macro invocation, like
107 /// `println!("Hello, {}", world)`.
108 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109 pub struct MacroCallId(salsa::InternId);
110 impl_intern_key!(MacroCallId);
111
112 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
113 pub struct MacroCallLoc {
114     pub def: MacroDefId,
115     pub(crate) krate: CrateId,
116     eager: Option<EagerCallInfo>,
117     pub kind: MacroCallKind,
118 }
119
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121 pub struct MacroDefId {
122     pub krate: CrateId,
123     pub kind: MacroDefKind,
124     pub local_inner: bool,
125 }
126
127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128 pub enum MacroDefKind {
129     Declarative(AstId<ast::Macro>),
130     BuiltIn(BuiltinFnLikeExpander, AstId<ast::Macro>),
131     // FIXME: maybe just Builtin and rename BuiltinFnLikeExpander to BuiltinExpander
132     BuiltInAttr(BuiltinAttrExpander, AstId<ast::Macro>),
133     BuiltInDerive(BuiltinDeriveExpander, AstId<ast::Macro>),
134     BuiltInEager(EagerExpander, AstId<ast::Macro>),
135     ProcMacro(ProcMacroExpander, ProcMacroKind, AstId<ast::Fn>),
136 }
137
138 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
139 struct EagerCallInfo {
140     /// NOTE: This can be *either* the expansion result, *or* the argument to the eager macro!
141     arg_or_expansion: Arc<tt::Subtree>,
142     included_file: Option<FileId>,
143 }
144
145 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
146 pub enum MacroCallKind {
147     FnLike {
148         ast_id: AstId<ast::MacroCall>,
149         expand_to: ExpandTo,
150     },
151     Derive {
152         ast_id: AstId<ast::Adt>,
153         /// Syntactical index of the invoking `#[derive]` attribute.
154         ///
155         /// Outer attributes are counted first, then inner attributes. This does not support
156         /// out-of-line modules, which may have attributes spread across 2 files!
157         derive_attr_index: u32,
158         /// Index of the derive macro in the derive attribute
159         derive_index: u32,
160     },
161     Attr {
162         ast_id: AstId<ast::Item>,
163         attr_args: Arc<(tt::Subtree, mbe::TokenMap)>,
164         /// Syntactical index of the invoking `#[attribute]`.
165         ///
166         /// Outer attributes are counted first, then inner attributes. This does not support
167         /// out-of-line modules, which may have attributes spread across 2 files!
168         invoc_attr_index: u32,
169         /// Whether this attribute is the `#[derive]` attribute.
170         is_derive: bool,
171     },
172 }
173
174 impl HirFileId {
175     /// For macro-expansion files, returns the file original source file the
176     /// expansion originated from.
177     pub fn original_file(self, db: &dyn db::AstDatabase) -> FileId {
178         let mut file_id = self;
179         loop {
180             match file_id.0 {
181                 HirFileIdRepr::FileId(id) => break id,
182                 HirFileIdRepr::MacroFile(MacroFile { macro_call_id }) => {
183                     let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_call_id);
184                     file_id = match loc.eager {
185                         Some(EagerCallInfo { included_file: Some(file), .. }) => file.into(),
186                         _ => loc.kind.file_id(),
187                     };
188                 }
189             }
190         }
191     }
192
193     pub fn expansion_level(self, db: &dyn db::AstDatabase) -> u32 {
194         let mut level = 0;
195         let mut curr = self;
196         while let HirFileIdRepr::MacroFile(macro_file) = curr.0 {
197             let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
198
199             level += 1;
200             curr = loc.kind.file_id();
201         }
202         level
203     }
204
205     /// If this is a macro call, returns the syntax node of the call.
206     pub fn call_node(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxNode>> {
207         match self.0 {
208             HirFileIdRepr::FileId(_) => None,
209             HirFileIdRepr::MacroFile(macro_file) => {
210                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
211                 Some(loc.kind.to_node(db))
212             }
213         }
214     }
215
216     /// If this is a macro call, returns the syntax node of the very first macro call this file resides in.
217     pub fn original_call_node(self, db: &dyn db::AstDatabase) -> Option<(FileId, SyntaxNode)> {
218         let mut call = match self.0 {
219             HirFileIdRepr::FileId(_) => return None,
220             HirFileIdRepr::MacroFile(MacroFile { macro_call_id }) => {
221                 db.lookup_intern_macro_call(macro_call_id).kind.to_node(db)
222             }
223         };
224         loop {
225             match call.file_id.0 {
226                 HirFileIdRepr::FileId(file_id) => break Some((file_id, call.value)),
227                 HirFileIdRepr::MacroFile(MacroFile { macro_call_id }) => {
228                     call = db.lookup_intern_macro_call(macro_call_id).kind.to_node(db);
229                 }
230             }
231         }
232     }
233
234     /// Return expansion information if it is a macro-expansion file
235     pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
236         match self.0 {
237             HirFileIdRepr::FileId(_) => None,
238             HirFileIdRepr::MacroFile(macro_file) => {
239                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
240
241                 let arg_tt = loc.kind.arg(db)?;
242
243                 let macro_def = db.macro_def(loc.def).ok()?;
244                 let (parse, exp_map) = db.parse_macro_expansion(macro_file).value?;
245                 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
246
247                 let def = loc.def.ast_id().left().and_then(|id| {
248                     let def_tt = match id.to_node(db) {
249                         ast::Macro::MacroRules(mac) => mac.token_tree()?,
250                         ast::Macro::MacroDef(_)
251                             if matches!(*macro_def, TokenExpander::BuiltinAttr(_)) =>
252                         {
253                             return None
254                         }
255                         ast::Macro::MacroDef(mac) => mac.body()?,
256                     };
257                     Some(InFile::new(id.file_id, def_tt))
258                 });
259                 let attr_input_or_mac_def = def.or_else(|| match loc.kind {
260                     MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
261                         let tt = ast_id
262                             .to_node(db)
263                             .doc_comments_and_attrs()
264                             .nth(invoc_attr_index as usize)
265                             .and_then(Either::left)?
266                             .token_tree()?;
267                         Some(InFile::new(ast_id.file_id, tt))
268                     }
269                     _ => None,
270                 });
271
272                 Some(ExpansionInfo {
273                     expanded: InFile::new(self, parse.syntax_node()),
274                     arg: InFile::new(loc.kind.file_id(), arg_tt),
275                     attr_input_or_mac_def,
276                     macro_arg_shift: mbe::Shift::new(&macro_arg.0),
277                     macro_arg,
278                     macro_def,
279                     exp_map,
280                 })
281             }
282         }
283     }
284
285     /// Indicate it is macro file generated for builtin derive
286     pub fn is_builtin_derive(&self, db: &dyn db::AstDatabase) -> Option<InFile<ast::Attr>> {
287         match self.0 {
288             HirFileIdRepr::FileId(_) => None,
289             HirFileIdRepr::MacroFile(macro_file) => {
290                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
291                 let attr = match loc.def.kind {
292                     MacroDefKind::BuiltInDerive(..) => loc.kind.to_node(db),
293                     _ => return None,
294                 };
295                 Some(attr.with_value(ast::Attr::cast(attr.value.clone())?))
296             }
297         }
298     }
299
300     pub fn is_custom_derive(&self, db: &dyn db::AstDatabase) -> bool {
301         match self.0 {
302             HirFileIdRepr::FileId(_) => false,
303             HirFileIdRepr::MacroFile(macro_file) => {
304                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
305                 matches!(loc.def.kind, MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _))
306             }
307         }
308     }
309
310     /// Return whether this file is an include macro
311     pub fn is_include_macro(&self, db: &dyn db::AstDatabase) -> bool {
312         match self.0 {
313             HirFileIdRepr::MacroFile(macro_file) => {
314                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
315                 matches!(loc.eager, Some(EagerCallInfo { included_file: Some(_), .. }))
316             }
317             _ => false,
318         }
319     }
320
321     /// Return whether this file is an attr macro
322     pub fn is_attr_macro(&self, db: &dyn db::AstDatabase) -> bool {
323         match self.0 {
324             HirFileIdRepr::MacroFile(macro_file) => {
325                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
326                 matches!(loc.kind, MacroCallKind::Attr { .. })
327             }
328             _ => false,
329         }
330     }
331
332     /// Return whether this file is the pseudo expansion of the derive attribute.
333     /// See [`crate::builtin_attr_macro::derive_attr_expand`].
334     pub fn is_derive_attr_pseudo_expansion(&self, db: &dyn db::AstDatabase) -> bool {
335         match self.0 {
336             HirFileIdRepr::MacroFile(macro_file) => {
337                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
338                 matches!(loc.kind, MacroCallKind::Attr { is_derive: true, .. })
339             }
340             _ => false,
341         }
342     }
343
344     pub fn is_macro(self) -> bool {
345         matches!(self.0, HirFileIdRepr::MacroFile(_))
346     }
347
348     pub fn macro_file(self) -> Option<MacroFile> {
349         match self.0 {
350             HirFileIdRepr::FileId(_) => None,
351             HirFileIdRepr::MacroFile(m) => Some(m),
352         }
353     }
354 }
355
356 impl MacroDefId {
357     pub fn as_lazy_macro(
358         self,
359         db: &dyn db::AstDatabase,
360         krate: CrateId,
361         kind: MacroCallKind,
362     ) -> MacroCallId {
363         db.intern_macro_call(MacroCallLoc { def: self, krate, eager: None, kind })
364     }
365
366     pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
367         let id = match self.kind {
368             MacroDefKind::ProcMacro(.., id) => return Either::Right(id),
369             MacroDefKind::Declarative(id)
370             | MacroDefKind::BuiltIn(_, id)
371             | MacroDefKind::BuiltInAttr(_, id)
372             | MacroDefKind::BuiltInDerive(_, id)
373             | MacroDefKind::BuiltInEager(_, id) => id,
374         };
375         Either::Left(id)
376     }
377
378     pub fn is_proc_macro(&self) -> bool {
379         matches!(self.kind, MacroDefKind::ProcMacro(..))
380     }
381
382     pub fn is_attribute(&self) -> bool {
383         matches!(
384             self.kind,
385             MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, ProcMacroKind::Attr, _)
386         )
387     }
388 }
389
390 // FIXME: attribute indices do not account for `cfg_attr`, which means that we'll strip the whole
391 // `cfg_attr` instead of just one of the attributes it expands to
392
393 impl MacroCallKind {
394     /// Returns the file containing the macro invocation.
395     fn file_id(&self) -> HirFileId {
396         match *self {
397             MacroCallKind::FnLike { ast_id: InFile { file_id, .. }, .. }
398             | MacroCallKind::Derive { ast_id: InFile { file_id, .. }, .. }
399             | MacroCallKind::Attr { ast_id: InFile { file_id, .. }, .. } => file_id,
400         }
401     }
402
403     pub fn to_node(&self, db: &dyn db::AstDatabase) -> InFile<SyntaxNode> {
404         match self {
405             MacroCallKind::FnLike { ast_id, .. } => {
406                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
407             }
408             MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
409                 // FIXME: handle `cfg_attr`
410                 ast_id.with_value(ast_id.to_node(db)).map(|it| {
411                     it.doc_comments_and_attrs()
412                         .nth(*derive_attr_index as usize)
413                         .and_then(|it| match it {
414                             Either::Left(attr) => Some(attr.syntax().clone()),
415                             Either::Right(_) => None,
416                         })
417                         .unwrap_or_else(|| it.syntax().clone())
418                 })
419             }
420             MacroCallKind::Attr { ast_id, is_derive: true, invoc_attr_index, .. } => {
421                 // FIXME: handle `cfg_attr`
422                 ast_id.with_value(ast_id.to_node(db)).map(|it| {
423                     it.doc_comments_and_attrs()
424                         .nth(*invoc_attr_index as usize)
425                         .and_then(|it| match it {
426                             Either::Left(attr) => Some(attr.syntax().clone()),
427                             Either::Right(_) => None,
428                         })
429                         .unwrap_or_else(|| it.syntax().clone())
430                 })
431             }
432             MacroCallKind::Attr { ast_id, .. } => {
433                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
434             }
435         }
436     }
437
438     /// Returns the original file range that best describes the location of this macro call.
439     ///
440     /// Here we try to roughly match what rustc does to improve diagnostics: fn-like macros
441     /// get the whole `ast::MacroCall`, attribute macros get the attribute's range, and derives
442     /// get only the specific derive that is being referred to.
443     pub fn original_call_range(self, db: &dyn db::AstDatabase) -> FileRange {
444         let mut kind = self;
445         let file_id = loop {
446             match kind.file_id().0 {
447                 HirFileIdRepr::MacroFile(file) => {
448                     kind = db.lookup_intern_macro_call(file.macro_call_id).kind;
449                 }
450                 HirFileIdRepr::FileId(file_id) => break file_id,
451             }
452         };
453
454         let range = match kind {
455             MacroCallKind::FnLike { ast_id, .. } => ast_id.to_node(db).syntax().text_range(),
456             MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
457                 // FIXME: should be the range of the macro name, not the whole derive
458                 ast_id
459                     .to_node(db)
460                     .doc_comments_and_attrs()
461                     .nth(derive_attr_index as usize)
462                     .expect("missing derive")
463                     .expect_left("derive is a doc comment?")
464                     .syntax()
465                     .text_range()
466             }
467             MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => ast_id
468                 .to_node(db)
469                 .doc_comments_and_attrs()
470                 .nth(invoc_attr_index as usize)
471                 .expect("missing attribute")
472                 .expect_left("attribute macro is a doc comment?")
473                 .syntax()
474                 .text_range(),
475         };
476
477         FileRange { range, file_id }
478     }
479
480     fn arg(&self, db: &dyn db::AstDatabase) -> Option<SyntaxNode> {
481         match self {
482             MacroCallKind::FnLike { ast_id, .. } => {
483                 Some(ast_id.to_node(db).token_tree()?.syntax().clone())
484             }
485             MacroCallKind::Derive { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
486             MacroCallKind::Attr { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
487         }
488     }
489
490     fn expand_to(&self) -> ExpandTo {
491         match self {
492             MacroCallKind::FnLike { expand_to, .. } => *expand_to,
493             MacroCallKind::Derive { .. } => ExpandTo::Items,
494             MacroCallKind::Attr { is_derive: true, .. } => ExpandTo::Statements,
495             MacroCallKind::Attr { .. } => ExpandTo::Items, // is this always correct?
496         }
497     }
498 }
499
500 impl MacroCallId {
501     pub fn as_file(self) -> HirFileId {
502         MacroFile { macro_call_id: self }.into()
503     }
504 }
505
506 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
507 #[derive(Debug, Clone, PartialEq, Eq)]
508 pub struct ExpansionInfo {
509     expanded: InFile<SyntaxNode>,
510     /// The argument TokenTree or item for attributes
511     arg: InFile<SyntaxNode>,
512     /// The `macro_rules!` or attribute input.
513     attr_input_or_mac_def: Option<InFile<ast::TokenTree>>,
514
515     macro_def: Arc<TokenExpander>,
516     macro_arg: Arc<(tt::Subtree, mbe::TokenMap, fixup::SyntaxFixupUndoInfo)>,
517     /// A shift built from `macro_arg`'s subtree, relevant for attributes as the item is the macro arg
518     /// and as such we need to shift tokens if they are part of an attributes input instead of their item.
519     macro_arg_shift: mbe::Shift,
520     exp_map: Arc<mbe::TokenMap>,
521 }
522
523 impl ExpansionInfo {
524     pub fn expanded(&self) -> InFile<SyntaxNode> {
525         self.expanded.clone()
526     }
527
528     pub fn call_node(&self) -> Option<InFile<SyntaxNode>> {
529         Some(self.arg.with_value(self.arg.value.parent()?))
530     }
531
532     /// Map a token down from macro input into the macro expansion.
533     ///
534     /// The inner workings of this function differ slightly depending on the type of macro we are dealing with:
535     /// - declarative:
536     ///     For declarative macros, we need to accommodate for the macro definition site(which acts as a second unchanging input)
537     ///     , as tokens can mapped in and out of it.
538     ///     To do this we shift all ids in the expansion by the maximum id of the definition site giving us an easy
539     ///     way to map all the tokens.
540     /// - attribute:
541     ///     Attributes have two different inputs, the input tokentree in the attribute node and the item
542     ///     the attribute is annotating. Similarly as for declarative macros we need to do a shift here
543     ///     as well. Currently this is done by shifting the attribute input by the maximum id of the item.
544     /// - function-like and derives:
545     ///     Both of these only have one simple call site input so no special handling is required here.
546     pub fn map_token_down(
547         &self,
548         db: &dyn db::AstDatabase,
549         item: Option<ast::Item>,
550         token: InFile<&SyntaxToken>,
551     ) -> Option<impl Iterator<Item = InFile<SyntaxToken>> + '_> {
552         assert_eq!(token.file_id, self.arg.file_id);
553         let token_id_in_attr_input = if let Some(item) = item {
554             // check if we are mapping down in an attribute input
555             // this is a special case as attributes can have two inputs
556             let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
557             let loc = db.lookup_intern_macro_call(call_id);
558
559             let token_range = token.value.text_range();
560             match &loc.kind {
561                 MacroCallKind::Attr { attr_args, invoc_attr_index, is_derive, .. } => {
562                     let attr = item
563                         .doc_comments_and_attrs()
564                         .nth(*invoc_attr_index as usize)
565                         .and_then(Either::left)?;
566                     match attr.token_tree() {
567                         Some(token_tree)
568                             if token_tree.syntax().text_range().contains_range(token_range) =>
569                         {
570                             let attr_input_start =
571                                 token_tree.left_delimiter_token()?.text_range().start();
572                             let relative_range =
573                                 token.value.text_range().checked_sub(attr_input_start)?;
574                             // shift by the item's tree's max id
575                             let token_id = attr_args.1.token_by_range(relative_range)?;
576                             let token_id = if *is_derive {
577                                 // we do not shift for `#[derive]`, as we only need to downmap the derive attribute tokens
578                                 token_id
579                             } else {
580                                 self.macro_arg_shift.shift(token_id)
581                             };
582                             Some(token_id)
583                         }
584                         _ => None,
585                     }
586                 }
587                 _ => None,
588             }
589         } else {
590             None
591         };
592
593         let token_id = match token_id_in_attr_input {
594             Some(token_id) => token_id,
595             // the token is not inside an attribute's input so do the lookup in the macro_arg as ususal
596             None => {
597                 let relative_range =
598                     token.value.text_range().checked_sub(self.arg.value.text_range().start())?;
599                 let token_id = self.macro_arg.1.token_by_range(relative_range)?;
600                 // conditionally shift the id by a declaratives macro definition
601                 self.macro_def.map_id_down(token_id)
602             }
603         };
604
605         let tokens = self
606             .exp_map
607             .ranges_by_token(token_id, token.value.kind())
608             .flat_map(move |range| self.expanded.value.covering_element(range).into_token());
609
610         Some(tokens.map(move |token| self.expanded.with_value(token)))
611     }
612
613     /// Map a token up out of the expansion it resides in into the arguments of the macro call of the expansion.
614     pub fn map_token_up(
615         &self,
616         db: &dyn db::AstDatabase,
617         token: InFile<&SyntaxToken>,
618     ) -> Option<(InFile<SyntaxToken>, Origin)> {
619         // Fetch the id through its text range,
620         let token_id = self.exp_map.token_by_range(token.value.text_range())?;
621         // conditionally unshifting the id to accommodate for macro-rules def site
622         let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
623
624         let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
625         let loc = db.lookup_intern_macro_call(call_id);
626
627         // Attributes are a bit special for us, they have two inputs, the input tokentree and the annotated item.
628         let (token_map, tt) = match &loc.kind {
629             MacroCallKind::Attr { attr_args, is_derive: true, .. } => {
630                 (&attr_args.1, self.attr_input_or_mac_def.clone()?.syntax().cloned())
631             }
632             MacroCallKind::Attr { attr_args, .. } => {
633                 // try unshifting the the token id, if unshifting fails, the token resides in the non-item attribute input
634                 // note that the `TokenExpander::map_id_up` earlier only unshifts for declarative macros, so we don't double unshift with this
635                 match self.macro_arg_shift.unshift(token_id) {
636                     Some(unshifted) => {
637                         token_id = unshifted;
638                         (&attr_args.1, self.attr_input_or_mac_def.clone()?.syntax().cloned())
639                     }
640                     None => (&self.macro_arg.1, self.arg.clone()),
641                 }
642             }
643             _ => match origin {
644                 mbe::Origin::Call => (&self.macro_arg.1, self.arg.clone()),
645                 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def) {
646                     (TokenExpander::DeclarativeMacro { def_site_token_map, .. }, Some(tt)) => {
647                         (def_site_token_map, tt.syntax().cloned())
648                     }
649                     _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
650                 },
651             },
652         };
653
654         let range = token_map.first_range_by_token(token_id, token.value.kind())?;
655         let token =
656             tt.value.covering_element(range + tt.value.text_range().start()).into_token()?;
657         Some((tt.with_value(token), origin))
658     }
659 }
660
661 /// `AstId` points to an AST node in any file.
662 ///
663 /// It is stable across reparses, and can be used as salsa key/value.
664 pub type AstId<N> = InFile<FileAstId<N>>;
665
666 impl<N: AstNode> AstId<N> {
667     pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
668         let root = db.parse_or_expand(self.file_id).unwrap();
669         db.ast_id_map(self.file_id).get(self.value).to_node(&root)
670     }
671 }
672
673 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
674 ///
675 /// Typical usages are:
676 ///
677 /// * `InFile<SyntaxNode>` -- syntax node in a file
678 /// * `InFile<ast::FnDef>` -- ast node in a file
679 /// * `InFile<TextSize>` -- offset in a file
680 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
681 pub struct InFile<T> {
682     pub file_id: HirFileId,
683     pub value: T,
684 }
685
686 impl<T> InFile<T> {
687     pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
688         InFile { file_id, value }
689     }
690
691     pub fn with_value<U>(&self, value: U) -> InFile<U> {
692         InFile::new(self.file_id, value)
693     }
694
695     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
696         InFile::new(self.file_id, f(self.value))
697     }
698
699     pub fn as_ref(&self) -> InFile<&T> {
700         self.with_value(&self.value)
701     }
702
703     pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
704         db.parse_or_expand(self.file_id).expect("source created from invalid file")
705     }
706 }
707
708 impl<T: Clone> InFile<&T> {
709     pub fn cloned(&self) -> InFile<T> {
710         self.with_value(self.value.clone())
711     }
712 }
713
714 impl<T> InFile<Option<T>> {
715     pub fn transpose(self) -> Option<InFile<T>> {
716         let value = self.value?;
717         Some(InFile::new(self.file_id, value))
718     }
719 }
720
721 impl<'a> InFile<&'a SyntaxNode> {
722     pub fn ancestors_with_macros(
723         self,
724         db: &dyn db::AstDatabase,
725     ) -> impl Iterator<Item = InFile<SyntaxNode>> + Clone + '_ {
726         iter::successors(Some(self.cloned()), move |node| match node.value.parent() {
727             Some(parent) => Some(node.with_value(parent)),
728             None => node.file_id.call_node(db),
729         })
730     }
731
732     /// Skips the attributed item that caused the macro invocation we are climbing up
733     pub fn ancestors_with_macros_skip_attr_item(
734         self,
735         db: &dyn db::AstDatabase,
736     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
737         let succ = move |node: &InFile<SyntaxNode>| match node.value.parent() {
738             Some(parent) => Some(node.with_value(parent)),
739             None => {
740                 let parent_node = node.file_id.call_node(db)?;
741                 if node.file_id.is_attr_macro(db) {
742                     // macro call was an attributed item, skip it
743                     // FIXME: does this fail if this is a direct expansion of another macro?
744                     parent_node.map(|node| node.parent()).transpose()
745                 } else {
746                     Some(parent_node)
747                 }
748             }
749         };
750         iter::successors(succ(&self.cloned()), succ)
751     }
752
753     /// Falls back to the macro call range if the node cannot be mapped up fully.
754     pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
755         if let Some(res) = self.original_file_range_opt(db) {
756             return res;
757         }
758
759         // Fall back to whole macro call.
760         match self.file_id.0 {
761             HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
762             HirFileIdRepr::MacroFile(mac_file) => {
763                 let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
764                 loc.kind.original_call_range(db)
765             }
766         }
767     }
768
769     /// Attempts to map the syntax node back up its macro calls.
770     pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
771         match ascend_node_border_tokens(db, self) {
772             Some(InFile { file_id, value: (first, last) }) => {
773                 let original_file = file_id.original_file(db);
774                 let range = first.text_range().cover(last.text_range());
775                 if file_id != original_file.into() {
776                     tracing::error!("Failed mapping up more for {:?}", range);
777                     return None;
778                 }
779                 Some(FileRange { file_id: original_file, range })
780             }
781             _ if !self.file_id.is_macro() => Some(FileRange {
782                 file_id: self.file_id.original_file(db),
783                 range: self.value.text_range(),
784             }),
785             _ => None,
786         }
787     }
788 }
789
790 impl InFile<SyntaxToken> {
791     pub fn upmap(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxToken>> {
792         let expansion = self.file_id.expansion_info(db)?;
793         expansion.map_token_up(db, self.as_ref()).map(|(it, _)| it)
794     }
795 }
796
797 fn ascend_node_border_tokens(
798     db: &dyn db::AstDatabase,
799     InFile { file_id, value: node }: InFile<&SyntaxNode>,
800 ) -> Option<InFile<(SyntaxToken, SyntaxToken)>> {
801     let expansion = file_id.expansion_info(db)?;
802
803     let first_token = |node: &SyntaxNode| skip_trivia_token(node.first_token()?, Direction::Next);
804     let last_token = |node: &SyntaxNode| skip_trivia_token(node.last_token()?, Direction::Prev);
805
806     let first = first_token(node)?;
807     let last = last_token(node)?;
808     let first = ascend_call_token(db, &expansion, InFile::new(file_id, first))?;
809     let last = ascend_call_token(db, &expansion, InFile::new(file_id, last))?;
810     (first.file_id == last.file_id).then(|| InFile::new(first.file_id, (first.value, last.value)))
811 }
812
813 fn ascend_call_token(
814     db: &dyn db::AstDatabase,
815     expansion: &ExpansionInfo,
816     token: InFile<SyntaxToken>,
817 ) -> Option<InFile<SyntaxToken>> {
818     let mut mapping = expansion.map_token_up(db, token.as_ref())?;
819     while let (mapped, Origin::Call) = mapping {
820         match mapped.file_id.expansion_info(db) {
821             Some(info) => mapping = info.map_token_up(db, mapped.as_ref())?,
822             None => return Some(mapped),
823         }
824     }
825     None
826 }
827
828 impl InFile<SyntaxToken> {
829     pub fn ancestors_with_macros(
830         self,
831         db: &dyn db::AstDatabase,
832     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
833         self.value.parent().into_iter().flat_map({
834             let file_id = self.file_id;
835             move |parent| InFile::new(file_id, &parent).ancestors_with_macros(db)
836         })
837     }
838 }
839
840 impl<N: AstNode> InFile<N> {
841     pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
842         self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
843     }
844
845     pub fn original_ast_node(self, db: &dyn db::AstDatabase) -> Option<InFile<N>> {
846         // This kind of upmapping can only be achieved in attribute expanded files,
847         // as we don't have node inputs otherwise and  therefor can't find an `N` node in the input
848         if !self.file_id.is_macro() {
849             return Some(self);
850         } else if !self.file_id.is_attr_macro(db) {
851             return None;
852         }
853
854         if let Some(InFile { file_id, value: (first, last) }) =
855             ascend_node_border_tokens(db, self.syntax())
856         {
857             if file_id.is_macro() {
858                 let range = first.text_range().cover(last.text_range());
859                 tracing::error!("Failed mapping out of macro file for {:?}", range);
860                 return None;
861             }
862             // FIXME: This heuristic is brittle and with the right macro may select completely unrelated nodes
863             let anc = algo::least_common_ancestor(&first.parent()?, &last.parent()?)?;
864             let value = anc.ancestors().find_map(N::cast)?;
865             return Some(InFile::new(file_id, value));
866         }
867         None
868     }
869
870     pub fn syntax(&self) -> InFile<&SyntaxNode> {
871         self.with_value(self.value.syntax())
872     }
873 }
874
875 /// In Rust, macros expand token trees to token trees. When we want to turn a
876 /// token tree into an AST node, we need to figure out what kind of AST node we
877 /// want: something like `foo` can be a type, an expression, or a pattern.
878 ///
879 /// Naively, one would think that "what this expands to" is a property of a
880 /// particular macro: macro `m1` returns an item, while macro `m2` returns an
881 /// expression, etc. That's not the case -- macros are polymorphic in the
882 /// result, and can expand to any type of the AST node.
883 ///
884 /// What defines the actual AST node is the syntactic context of the macro
885 /// invocation. As a contrived example, in `let T![*] = T![*];` the first `T`
886 /// expands to a pattern, while the second one expands to an expression.
887 ///
888 /// `ExpandTo` captures this bit of information about a particular macro call
889 /// site.
890 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
891 pub enum ExpandTo {
892     Statements,
893     Items,
894     Pattern,
895     Type,
896     Expr,
897 }
898
899 impl ExpandTo {
900     pub fn from_call_site(call: &ast::MacroCall) -> ExpandTo {
901         use syntax::SyntaxKind::*;
902
903         let syn = call.syntax();
904
905         let parent = match syn.parent() {
906             Some(it) => it,
907             None => return ExpandTo::Statements,
908         };
909
910         // FIXME: macros in statement position are treated as expression statements, they should
911         // probably be their own statement kind. The *grand*parent indicates what's valid.
912         if parent.kind() == MACRO_EXPR
913             && parent
914                 .parent()
915                 .map_or(true, |p| matches!(p.kind(), EXPR_STMT | STMT_LIST | MACRO_STMTS))
916         {
917             return ExpandTo::Statements;
918         }
919
920         match parent.kind() {
921             MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => ExpandTo::Items,
922             MACRO_STMTS | EXPR_STMT | STMT_LIST => ExpandTo::Statements,
923             MACRO_PAT => ExpandTo::Pattern,
924             MACRO_TYPE => ExpandTo::Type,
925
926             ARG_LIST | ARRAY_EXPR | AWAIT_EXPR | BIN_EXPR | BREAK_EXPR | CALL_EXPR | CAST_EXPR
927             | CLOSURE_EXPR | FIELD_EXPR | FOR_EXPR | IF_EXPR | INDEX_EXPR | LET_EXPR
928             | MATCH_ARM | MATCH_EXPR | MATCH_GUARD | METHOD_CALL_EXPR | PAREN_EXPR | PATH_EXPR
929             | PREFIX_EXPR | RANGE_EXPR | RECORD_EXPR_FIELD | REF_EXPR | RETURN_EXPR | TRY_EXPR
930             | TUPLE_EXPR | WHILE_EXPR | MACRO_EXPR => ExpandTo::Expr,
931             _ => {
932                 // Unknown , Just guess it is `Items`
933                 ExpandTo::Items
934             }
935         }
936     }
937 }
938
939 #[derive(Debug)]
940 pub struct UnresolvedMacro {
941     pub path: ModPath,
942 }