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