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