]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/lib.rs
cc38faa13693c64d2227339fe52afa974e7ccd3b
[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         match self.0 {
179             HirFileIdRepr::FileId(file_id) => file_id,
180             HirFileIdRepr::MacroFile(macro_file) => {
181                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
182                 let file_id = match loc.eager {
183                     Some(EagerCallInfo { included_file: Some(file), .. }) => file.into(),
184                     _ => loc.kind.file_id(),
185                 };
186                 file_id.original_file(db)
187             }
188         }
189     }
190
191     pub fn expansion_level(self, db: &dyn db::AstDatabase) -> u32 {
192         let mut level = 0;
193         let mut curr = self;
194         while let HirFileIdRepr::MacroFile(macro_file) = curr.0 {
195             let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
196
197             level += 1;
198             curr = loc.kind.file_id();
199         }
200         level
201     }
202
203     /// If this is a macro call, returns the syntax node of the call.
204     pub fn call_node(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxNode>> {
205         match self.0 {
206             HirFileIdRepr::FileId(_) => None,
207             HirFileIdRepr::MacroFile(macro_file) => {
208                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
209                 Some(loc.kind.to_node(db))
210             }
211         }
212     }
213
214     /// Return expansion information if it is a macro-expansion file
215     pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
216         match self.0 {
217             HirFileIdRepr::FileId(_) => None,
218             HirFileIdRepr::MacroFile(macro_file) => {
219                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
220
221                 let arg_tt = loc.kind.arg(db)?;
222
223                 let macro_def = db.macro_def(loc.def).ok()?;
224                 let (parse, exp_map) = db.parse_macro_expansion(macro_file).value?;
225                 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
226
227                 let def = loc.def.ast_id().left().and_then(|id| {
228                     let def_tt = match id.to_node(db) {
229                         ast::Macro::MacroRules(mac) => mac.token_tree()?,
230                         ast::Macro::MacroDef(_)
231                             if matches!(*macro_def, TokenExpander::BuiltinAttr(_)) =>
232                         {
233                             return None
234                         }
235                         ast::Macro::MacroDef(mac) => mac.body()?,
236                     };
237                     Some(InFile::new(id.file_id, def_tt))
238                 });
239                 let attr_input_or_mac_def = def.or_else(|| match loc.kind {
240                     MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
241                         let tt = ast_id
242                             .to_node(db)
243                             .doc_comments_and_attrs()
244                             .nth(invoc_attr_index as usize)
245                             .and_then(Either::left)?
246                             .token_tree()?;
247                         Some(InFile::new(ast_id.file_id, tt))
248                     }
249                     _ => None,
250                 });
251
252                 Some(ExpansionInfo {
253                     expanded: InFile::new(self, parse.syntax_node()),
254                     arg: InFile::new(loc.kind.file_id(), arg_tt),
255                     attr_input_or_mac_def,
256                     macro_arg_shift: mbe::Shift::new(&macro_arg.0),
257                     macro_arg,
258                     macro_def,
259                     exp_map,
260                 })
261             }
262         }
263     }
264
265     /// Indicate it is macro file generated for builtin derive
266     pub fn is_builtin_derive(&self, db: &dyn db::AstDatabase) -> Option<InFile<ast::Attr>> {
267         match self.0 {
268             HirFileIdRepr::FileId(_) => None,
269             HirFileIdRepr::MacroFile(macro_file) => {
270                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
271                 let attr = match loc.def.kind {
272                     MacroDefKind::BuiltInDerive(..) => loc.kind.to_node(db),
273                     _ => return None,
274                 };
275                 Some(attr.with_value(ast::Attr::cast(attr.value.clone())?))
276             }
277         }
278     }
279
280     pub fn is_custom_derive(&self, db: &dyn db::AstDatabase) -> bool {
281         match self.0 {
282             HirFileIdRepr::FileId(_) => false,
283             HirFileIdRepr::MacroFile(macro_file) => {
284                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
285                 matches!(loc.def.kind, MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _))
286             }
287         }
288     }
289
290     /// Return whether this file is an include macro
291     pub fn is_include_macro(&self, db: &dyn db::AstDatabase) -> bool {
292         match self.0 {
293             HirFileIdRepr::MacroFile(macro_file) => {
294                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
295                 matches!(loc.eager, Some(EagerCallInfo { included_file: Some(_), .. }))
296             }
297             _ => false,
298         }
299     }
300
301     /// Return whether this file is an attr macro
302     pub fn is_attr_macro(&self, db: &dyn db::AstDatabase) -> bool {
303         match self.0 {
304             HirFileIdRepr::MacroFile(macro_file) => {
305                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
306                 matches!(loc.kind, MacroCallKind::Attr { .. })
307             }
308             _ => false,
309         }
310     }
311
312     /// Return whether this file is the pseudo expansion of the derive attribute.
313     pub fn is_derive_attr_macro(&self, db: &dyn db::AstDatabase) -> bool {
314         match self.0 {
315             HirFileIdRepr::MacroFile(macro_file) => {
316                 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
317                 matches!(loc.kind, MacroCallKind::Attr { is_derive: true, .. })
318             }
319             _ => false,
320         }
321     }
322
323     pub fn is_macro(self) -> bool {
324         matches!(self.0, HirFileIdRepr::MacroFile(_))
325     }
326
327     pub fn macro_file(self) -> Option<MacroFile> {
328         match self.0 {
329             HirFileIdRepr::FileId(_) => None,
330             HirFileIdRepr::MacroFile(m) => Some(m),
331         }
332     }
333 }
334
335 impl MacroDefId {
336     pub fn as_lazy_macro(
337         self,
338         db: &dyn db::AstDatabase,
339         krate: CrateId,
340         kind: MacroCallKind,
341     ) -> MacroCallId {
342         db.intern_macro_call(MacroCallLoc { def: self, krate, eager: None, kind })
343     }
344
345     pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
346         let id = match self.kind {
347             MacroDefKind::ProcMacro(.., id) => return Either::Right(id),
348             MacroDefKind::Declarative(id)
349             | MacroDefKind::BuiltIn(_, id)
350             | MacroDefKind::BuiltInAttr(_, id)
351             | MacroDefKind::BuiltInDerive(_, id)
352             | MacroDefKind::BuiltInEager(_, id) => id,
353         };
354         Either::Left(id)
355     }
356
357     pub fn is_proc_macro(&self) -> bool {
358         matches!(self.kind, MacroDefKind::ProcMacro(..))
359     }
360
361     pub fn is_attribute(&self) -> bool {
362         matches!(
363             self.kind,
364             MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, ProcMacroKind::Attr, _)
365         )
366     }
367 }
368
369 // FIXME: attribute indices do not account for `cfg_attr`, which means that we'll strip the whole
370 // `cfg_attr` instead of just one of the attributes it expands to
371
372 impl MacroCallKind {
373     /// Returns the file containing the macro invocation.
374     fn file_id(&self) -> HirFileId {
375         match *self {
376             MacroCallKind::FnLike { ast_id: InFile { file_id, .. }, .. }
377             | MacroCallKind::Derive { ast_id: InFile { file_id, .. }, .. }
378             | MacroCallKind::Attr { ast_id: InFile { file_id, .. }, .. } => file_id,
379         }
380     }
381
382     pub fn to_node(&self, db: &dyn db::AstDatabase) -> InFile<SyntaxNode> {
383         match self {
384             MacroCallKind::FnLike { ast_id, .. } => {
385                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
386             }
387             MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
388                 // FIXME: handle `cfg_attr`
389                 ast_id.with_value(ast_id.to_node(db)).map(|it| {
390                     it.doc_comments_and_attrs()
391                         .nth(*derive_attr_index as usize)
392                         .and_then(|it| match it {
393                             Either::Left(attr) => Some(attr.syntax().clone()),
394                             Either::Right(_) => None,
395                         })
396                         .unwrap_or_else(|| it.syntax().clone())
397                 })
398             }
399             MacroCallKind::Attr { ast_id, is_derive: true, invoc_attr_index, .. } => {
400                 // FIXME: handle `cfg_attr`
401                 ast_id.with_value(ast_id.to_node(db)).map(|it| {
402                     it.doc_comments_and_attrs()
403                         .nth(*invoc_attr_index as usize)
404                         .and_then(|it| match it {
405                             Either::Left(attr) => Some(attr.syntax().clone()),
406                             Either::Right(_) => None,
407                         })
408                         .unwrap_or_else(|| it.syntax().clone())
409                 })
410             }
411             MacroCallKind::Attr { ast_id, .. } => {
412                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
413             }
414         }
415     }
416
417     /// Returns the original file range that best describes the location of this macro call.
418     ///
419     /// Here we try to roughly match what rustc does to improve diagnostics: fn-like macros
420     /// get the whole `ast::MacroCall`, attribute macros get the attribute's range, and derives
421     /// get only the specific derive that is being referred to.
422     pub fn original_call_range(self, db: &dyn db::AstDatabase) -> FileRange {
423         let mut kind = self;
424         let file_id = loop {
425             match kind.file_id().0 {
426                 HirFileIdRepr::MacroFile(file) => {
427                     kind = db.lookup_intern_macro_call(file.macro_call_id).kind;
428                 }
429                 HirFileIdRepr::FileId(file_id) => break file_id,
430             }
431         };
432
433         let range = match kind {
434             MacroCallKind::FnLike { ast_id, .. } => ast_id.to_node(db).syntax().text_range(),
435             MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
436                 // FIXME: should be the range of the macro name, not the whole derive
437                 ast_id
438                     .to_node(db)
439                     .doc_comments_and_attrs()
440                     .nth(derive_attr_index as usize)
441                     .expect("missing derive")
442                     .expect_left("derive is a doc comment?")
443                     .syntax()
444                     .text_range()
445             }
446             MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => ast_id
447                 .to_node(db)
448                 .doc_comments_and_attrs()
449                 .nth(invoc_attr_index as usize)
450                 .expect("missing attribute")
451                 .expect_left("attribute macro is a doc comment?")
452                 .syntax()
453                 .text_range(),
454         };
455
456         FileRange { range, file_id }
457     }
458
459     fn arg(&self, db: &dyn db::AstDatabase) -> Option<SyntaxNode> {
460         match self {
461             MacroCallKind::FnLike { ast_id, .. } => {
462                 Some(ast_id.to_node(db).token_tree()?.syntax().clone())
463             }
464             MacroCallKind::Derive { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
465             MacroCallKind::Attr { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
466         }
467     }
468
469     fn expand_to(&self) -> ExpandTo {
470         match self {
471             MacroCallKind::FnLike { expand_to, .. } => *expand_to,
472             MacroCallKind::Derive { .. } => ExpandTo::Items,
473             MacroCallKind::Attr { is_derive: true, .. } => ExpandTo::Statements,
474             MacroCallKind::Attr { .. } => ExpandTo::Items, // is this always correct?
475         }
476     }
477 }
478
479 impl MacroCallId {
480     pub fn as_file(self) -> HirFileId {
481         MacroFile { macro_call_id: self }.into()
482     }
483 }
484
485 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
486 #[derive(Debug, Clone, PartialEq, Eq)]
487 pub struct ExpansionInfo {
488     expanded: InFile<SyntaxNode>,
489     /// The argument TokenTree or item for attributes
490     arg: InFile<SyntaxNode>,
491     /// The `macro_rules!` or attribute input.
492     attr_input_or_mac_def: Option<InFile<ast::TokenTree>>,
493
494     macro_def: Arc<TokenExpander>,
495     macro_arg: Arc<(tt::Subtree, mbe::TokenMap, fixup::SyntaxFixupUndoInfo)>,
496     /// A shift built from `macro_arg`'s subtree, relevant for attributes as the item is the macro arg
497     /// and as such we need to shift tokens if they are part of an attributes input instead of their item.
498     macro_arg_shift: mbe::Shift,
499     exp_map: Arc<mbe::TokenMap>,
500 }
501
502 impl ExpansionInfo {
503     pub fn expanded(&self) -> InFile<SyntaxNode> {
504         self.expanded.clone()
505     }
506
507     pub fn call_node(&self) -> Option<InFile<SyntaxNode>> {
508         Some(self.arg.with_value(self.arg.value.parent()?))
509     }
510
511     /// Map a token down from macro input into the macro expansion.
512     ///
513     /// The inner workings of this function differ slightly depending on the type of macro we are dealing with:
514     /// - declarative:
515     ///     For declarative macros, we need to accommodate for the macro definition site(which acts as a second unchanging input)
516     ///     , as tokens can mapped in and out of it.
517     ///     To do this we shift all ids in the expansion by the maximum id of the definition site giving us an easy
518     ///     way to map all the tokens.
519     /// - attribute:
520     ///     Attributes have two different inputs, the input tokentree in the attribute node and the item
521     ///     the attribute is annotating. Similarly as for declarative macros we need to do a shift here
522     ///     as well. Currently this is done by shifting the attribute input by the maximum id of the item.
523     /// - function-like and derives:
524     ///     Both of these only have one simple call site input so no special handling is required here.
525     pub fn map_token_down(
526         &self,
527         db: &dyn db::AstDatabase,
528         item: Option<ast::Item>,
529         token: InFile<&SyntaxToken>,
530     ) -> Option<impl Iterator<Item = InFile<SyntaxToken>> + '_> {
531         assert_eq!(token.file_id, self.arg.file_id);
532         let token_id_in_attr_input = if let Some(item) = item {
533             // check if we are mapping down in an attribute input
534             // this is a special case as attributes can have two inputs
535             let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
536             let loc = db.lookup_intern_macro_call(call_id);
537
538             let token_range = token.value.text_range();
539             match &loc.kind {
540                 MacroCallKind::Attr { attr_args, invoc_attr_index, is_derive, .. } => {
541                     let attr = item
542                         .doc_comments_and_attrs()
543                         .nth(*invoc_attr_index as usize)
544                         .and_then(Either::left)?;
545                     match attr.token_tree() {
546                         Some(token_tree)
547                             if token_tree.syntax().text_range().contains_range(token_range) =>
548                         {
549                             let attr_input_start =
550                                 token_tree.left_delimiter_token()?.text_range().start();
551                             let relative_range =
552                                 token.value.text_range().checked_sub(attr_input_start)?;
553                             // shift by the item's tree's max id
554                             let token_id = attr_args.1.token_by_range(relative_range)?;
555                             let token_id = if *is_derive {
556                                 // we do not shift for `#[derive]`, as we only need to downmap the derive attribute tokens
557                                 token_id
558                             } else {
559                                 self.macro_arg_shift.shift(token_id)
560                             };
561                             Some(token_id)
562                         }
563                         _ => None,
564                     }
565                 }
566                 _ => None,
567             }
568         } else {
569             None
570         };
571
572         let token_id = match token_id_in_attr_input {
573             Some(token_id) => token_id,
574             // the token is not inside an attribute's input so do the lookup in the macro_arg as ususal
575             None => {
576                 let relative_range =
577                     token.value.text_range().checked_sub(self.arg.value.text_range().start())?;
578                 let token_id = self.macro_arg.1.token_by_range(relative_range)?;
579                 // conditionally shift the id by a declaratives macro definition
580                 self.macro_def.map_id_down(token_id)
581             }
582         };
583
584         let tokens = self
585             .exp_map
586             .ranges_by_token(token_id, token.value.kind())
587             .flat_map(move |range| self.expanded.value.covering_element(range).into_token());
588
589         Some(tokens.map(move |token| self.expanded.with_value(token)))
590     }
591
592     /// Map a token up out of the expansion it resides in into the arguments of the macro call of the expansion.
593     pub fn map_token_up(
594         &self,
595         db: &dyn db::AstDatabase,
596         token: InFile<&SyntaxToken>,
597     ) -> Option<(InFile<SyntaxToken>, Origin)> {
598         // Fetch the id through its text range,
599         let token_id = self.exp_map.token_by_range(token.value.text_range())?;
600         // conditionally unshifting the id to accommodate for macro-rules def site
601         let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
602
603         let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
604         let loc = db.lookup_intern_macro_call(call_id);
605
606         // Attributes are a bit special for us, they have two inputs, the input tokentree and the annotated item.
607         let (token_map, tt) = match &loc.kind {
608             MacroCallKind::Attr { attr_args, is_derive: true, .. } => {
609                 (&attr_args.1, self.attr_input_or_mac_def.clone()?.syntax().cloned())
610             }
611             MacroCallKind::Attr { attr_args, .. } => {
612                 // try unshifting the the token id, if unshifting fails, the token resides in the non-item attribute input
613                 // note that the `TokenExpander::map_id_up` earlier only unshifts for declarative macros, so we don't double unshift with this
614                 match self.macro_arg_shift.unshift(token_id) {
615                     Some(unshifted) => {
616                         token_id = unshifted;
617                         (&attr_args.1, self.attr_input_or_mac_def.clone()?.syntax().cloned())
618                     }
619                     None => (&self.macro_arg.1, self.arg.clone()),
620                 }
621             }
622             _ => match origin {
623                 mbe::Origin::Call => (&self.macro_arg.1, self.arg.clone()),
624                 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def) {
625                     (TokenExpander::DeclarativeMacro { def_site_token_map, .. }, Some(tt)) => {
626                         (def_site_token_map, tt.syntax().cloned())
627                     }
628                     _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
629                 },
630             },
631         };
632
633         let range = token_map.first_range_by_token(token_id, token.value.kind())?;
634         let token =
635             tt.value.covering_element(range + tt.value.text_range().start()).into_token()?;
636         Some((tt.with_value(token), origin))
637     }
638 }
639
640 /// `AstId` points to an AST node in any file.
641 ///
642 /// It is stable across reparses, and can be used as salsa key/value.
643 pub type AstId<N> = InFile<FileAstId<N>>;
644
645 impl<N: AstNode> AstId<N> {
646     pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
647         let root = db.parse_or_expand(self.file_id).unwrap();
648         db.ast_id_map(self.file_id).get(self.value).to_node(&root)
649     }
650 }
651
652 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
653 ///
654 /// Typical usages are:
655 ///
656 /// * `InFile<SyntaxNode>` -- syntax node in a file
657 /// * `InFile<ast::FnDef>` -- ast node in a file
658 /// * `InFile<TextSize>` -- offset in a file
659 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
660 pub struct InFile<T> {
661     pub file_id: HirFileId,
662     pub value: T,
663 }
664
665 impl<T> InFile<T> {
666     pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
667         InFile { file_id, value }
668     }
669
670     pub fn with_value<U>(&self, value: U) -> InFile<U> {
671         InFile::new(self.file_id, value)
672     }
673
674     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
675         InFile::new(self.file_id, f(self.value))
676     }
677     pub fn as_ref(&self) -> InFile<&T> {
678         self.with_value(&self.value)
679     }
680     pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
681         db.parse_or_expand(self.file_id).expect("source created from invalid file")
682     }
683 }
684
685 impl<T: Clone> InFile<&T> {
686     pub fn cloned(&self) -> InFile<T> {
687         self.with_value(self.value.clone())
688     }
689 }
690
691 impl<T> InFile<Option<T>> {
692     pub fn transpose(self) -> Option<InFile<T>> {
693         let value = self.value?;
694         Some(InFile::new(self.file_id, value))
695     }
696 }
697
698 impl<'a> InFile<&'a SyntaxNode> {
699     pub fn ancestors_with_macros(
700         self,
701         db: &dyn db::AstDatabase,
702     ) -> impl Iterator<Item = InFile<SyntaxNode>> + Clone + '_ {
703         iter::successors(Some(self.cloned()), move |node| match node.value.parent() {
704             Some(parent) => Some(node.with_value(parent)),
705             None => node.file_id.call_node(db),
706         })
707     }
708
709     /// Skips the attributed item that caused the macro invocation we are climbing up
710     pub fn ancestors_with_macros_skip_attr_item(
711         self,
712         db: &dyn db::AstDatabase,
713     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
714         iter::successors(Some(self.cloned()), move |node| match node.value.parent() {
715             Some(parent) => Some(node.with_value(parent)),
716             None => {
717                 let parent_node = node.file_id.call_node(db)?;
718                 if node.file_id.is_attr_macro(db) {
719                     // macro call was an attributed item, skip it
720                     // FIXME: does this fail if this is a direct expansion of another macro?
721                     parent_node.map(|node| node.parent()).transpose()
722                 } else {
723                     Some(parent_node)
724                 }
725             }
726         })
727     }
728
729     /// Falls back to the macro call range if the node cannot be mapped up fully.
730     pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
731         if let Some(res) = self.original_file_range_opt(db) {
732             return res;
733         }
734
735         // Fall back to whole macro call.
736         match self.file_id.0 {
737             HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
738             HirFileIdRepr::MacroFile(mac_file) => {
739                 let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
740                 loc.kind.original_call_range(db)
741             }
742         }
743     }
744
745     /// Attempts to map the syntax node back up its macro calls.
746     pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
747         match ascend_node_border_tokens(db, self) {
748             Some(InFile { file_id, value: (first, last) }) => {
749                 let original_file = file_id.original_file(db);
750                 let range = first.text_range().cover(last.text_range());
751                 if file_id != original_file.into() {
752                     tracing::error!("Failed mapping up more for {:?}", range);
753                     return None;
754                 }
755                 Some(FileRange { file_id: original_file, range })
756             }
757             _ if !self.file_id.is_macro() => Some(FileRange {
758                 file_id: self.file_id.original_file(db),
759                 range: self.value.text_range(),
760             }),
761             _ => None,
762         }
763     }
764 }
765
766 impl InFile<SyntaxToken> {
767     pub fn upmap(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxToken>> {
768         let expansion = self.file_id.expansion_info(db)?;
769         expansion.map_token_up(db, self.as_ref()).map(|(it, _)| it)
770     }
771 }
772
773 fn ascend_node_border_tokens(
774     db: &dyn db::AstDatabase,
775     InFile { file_id, value: node }: InFile<&SyntaxNode>,
776 ) -> Option<InFile<(SyntaxToken, SyntaxToken)>> {
777     let expansion = file_id.expansion_info(db)?;
778
779     let first_token = |node: &SyntaxNode| skip_trivia_token(node.first_token()?, Direction::Next);
780     let last_token = |node: &SyntaxNode| skip_trivia_token(node.last_token()?, Direction::Prev);
781
782     let first = first_token(node)?;
783     let last = last_token(node)?;
784     let first = ascend_call_token(db, &expansion, InFile::new(file_id, first))?;
785     let last = ascend_call_token(db, &expansion, InFile::new(file_id, last))?;
786     (first.file_id == last.file_id).then(|| InFile::new(first.file_id, (first.value, last.value)))
787 }
788
789 fn ascend_call_token(
790     db: &dyn db::AstDatabase,
791     expansion: &ExpansionInfo,
792     token: InFile<SyntaxToken>,
793 ) -> Option<InFile<SyntaxToken>> {
794     let mut mapping = expansion.map_token_up(db, token.as_ref())?;
795     while let (mapped, Origin::Call) = mapping {
796         match mapped.file_id.expansion_info(db) {
797             Some(info) => mapping = info.map_token_up(db, mapped.as_ref())?,
798             None => return Some(mapped),
799         }
800     }
801     None
802 }
803
804 impl InFile<SyntaxToken> {
805     pub fn ancestors_with_macros(
806         self,
807         db: &dyn db::AstDatabase,
808     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
809         self.value.parent().into_iter().flat_map({
810             let file_id = self.file_id;
811             move |parent| InFile::new(file_id, &parent).ancestors_with_macros(db)
812         })
813     }
814 }
815
816 impl<N: AstNode> InFile<N> {
817     pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
818         self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
819     }
820
821     pub fn original_ast_node(self, db: &dyn db::AstDatabase) -> Option<InFile<N>> {
822         // This kind of upmapping can only be achieved in attribute expanded files,
823         // as we don't have node inputs otherwise and  therefor can't find an `N` node in the input
824         if !self.file_id.is_macro() {
825             return Some(self);
826         } else if !self.file_id.is_attr_macro(db) {
827             return None;
828         }
829
830         if let Some(InFile { file_id, value: (first, last) }) =
831             ascend_node_border_tokens(db, self.syntax())
832         {
833             if file_id.is_macro() {
834                 let range = first.text_range().cover(last.text_range());
835                 tracing::error!("Failed mapping out of macro file for {:?}", range);
836                 return None;
837             }
838             // FIXME: This heuristic is brittle and with the right macro may select completely unrelated nodes
839             let anc = algo::least_common_ancestor(&first.parent()?, &last.parent()?)?;
840             let value = anc.ancestors().find_map(N::cast)?;
841             return Some(InFile::new(file_id, value));
842         }
843         None
844     }
845
846     pub fn syntax(&self) -> InFile<&SyntaxNode> {
847         self.with_value(self.value.syntax())
848     }
849 }
850
851 /// In Rust, macros expand token trees to token trees. When we want to turn a
852 /// token tree into an AST node, we need to figure out what kind of AST node we
853 /// want: something like `foo` can be a type, an expression, or a pattern.
854 ///
855 /// Naively, one would think that "what this expands to" is a property of a
856 /// particular macro: macro `m1` returns an item, while macro `m2` returns an
857 /// expression, etc. That's not the case -- macros are polymorphic in the
858 /// result, and can expand to any type of the AST node.
859 ///
860 /// What defines the actual AST node is the syntactic context of the macro
861 /// invocation. As a contrived example, in `let T![*] = T![*];` the first `T`
862 /// expands to a pattern, while the second one expands to an expression.
863 ///
864 /// `ExpandTo` captures this bit of information about a particular macro call
865 /// site.
866 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
867 pub enum ExpandTo {
868     Statements,
869     Items,
870     Pattern,
871     Type,
872     Expr,
873 }
874
875 impl ExpandTo {
876     pub fn from_call_site(call: &ast::MacroCall) -> ExpandTo {
877         use syntax::SyntaxKind::*;
878
879         let syn = call.syntax();
880
881         let parent = match syn.parent() {
882             Some(it) => it,
883             None => return ExpandTo::Statements,
884         };
885
886         match parent.kind() {
887             MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => ExpandTo::Items,
888             MACRO_STMTS | EXPR_STMT | STMT_LIST => ExpandTo::Statements,
889             MACRO_PAT => ExpandTo::Pattern,
890             MACRO_TYPE => ExpandTo::Type,
891
892             ARG_LIST | TRY_EXPR | TUPLE_EXPR | PAREN_EXPR | ARRAY_EXPR | FOR_EXPR | PATH_EXPR
893             | CLOSURE_EXPR | BREAK_EXPR | RETURN_EXPR | MATCH_EXPR | MATCH_ARM | MATCH_GUARD
894             | RECORD_EXPR_FIELD | CALL_EXPR | INDEX_EXPR | METHOD_CALL_EXPR | FIELD_EXPR
895             | AWAIT_EXPR | CAST_EXPR | REF_EXPR | PREFIX_EXPR | RANGE_EXPR | BIN_EXPR
896             | LET_EXPR => ExpandTo::Expr,
897             LET_STMT => {
898                 // FIXME: Handle LHS Pattern
899                 ExpandTo::Expr
900             }
901
902             _ => {
903                 // Unknown , Just guess it is `Items`
904                 ExpandTo::Items
905             }
906         }
907     }
908 }
909
910 #[derive(Debug)]
911 pub struct UnresolvedMacro {
912     pub path: ModPath,
913 }