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