]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/lib.rs
minor: align code to code style
[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};
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::skip_trivia_token,
28     ast::{self, AstNode, HasAttrs},
29     Direction, SyntaxNode, SyntaxToken, TextRange,
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 #[cfg(test)]
42 mod test_db;
43
44 /// Input to the analyzer is a set of files, where each file is identified by
45 /// `FileId` and contains source code. However, another source of source code in
46 /// Rust are macros: each macro can be thought of as producing a "temporary
47 /// file". To assign an id to such a file, we use the id of the macro call that
48 /// produced the file. So, a `HirFileId` is either a `FileId` (source code
49 /// written by user), or a `MacroCallId` (source code produced by macro).
50 ///
51 /// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
52 /// containing the call plus the offset of the macro call in the file. Note that
53 /// this is a recursive definition! However, the size_of of `HirFileId` is
54 /// finite (because everything bottoms out at the real `FileId`) and small
55 /// (`MacroCallId` uses the location interning. You can check details here:
56 /// <https://en.wikipedia.org/wiki/String_interning>).
57 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58 pub struct HirFileId(HirFileIdRepr);
59
60 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61 enum HirFileIdRepr {
62     FileId(FileId),
63     MacroFile(MacroFile),
64 }
65 impl From<FileId> for HirFileId {
66     fn from(id: FileId) -> Self {
67         HirFileId(HirFileIdRepr::FileId(id))
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::Item>,
128         derive_name: String,
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: String,
138         attr_args: (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(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(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(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(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                             .attrs()
208                             .nth(invoc_attr_index as usize)?
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(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(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(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(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
287 impl MacroDefId {
288     pub fn as_lazy_macro(
289         self,
290         db: &dyn db::AstDatabase,
291         krate: CrateId,
292         kind: MacroCallKind,
293     ) -> MacroCallId {
294         db.intern_macro(MacroCallLoc { def: self, krate, eager: None, kind })
295     }
296
297     pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
298         let id = match &self.kind {
299             MacroDefKind::ProcMacro(.., id) => return Either::Right(*id),
300             MacroDefKind::Declarative(id)
301             | MacroDefKind::BuiltIn(_, id)
302             | MacroDefKind::BuiltInAttr(_, id)
303             | MacroDefKind::BuiltInDerive(_, id)
304             | MacroDefKind::BuiltInEager(_, id) => id,
305         };
306         Either::Left(*id)
307     }
308
309     pub fn is_proc_macro(&self) -> bool {
310         matches!(self.kind, MacroDefKind::ProcMacro(..))
311     }
312 }
313
314 // FIXME: attribute indices do not account for `cfg_attr`, which means that we'll strip the whole
315 // `cfg_attr` instead of just one of the attributes it expands to
316
317 impl MacroCallKind {
318     /// Returns the file containing the macro invocation.
319     fn file_id(&self) -> HirFileId {
320         match self {
321             MacroCallKind::FnLike { ast_id, .. } => ast_id.file_id,
322             MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
323                 ast_id.file_id
324             }
325         }
326     }
327
328     pub fn to_node(&self, db: &dyn db::AstDatabase) -> InFile<SyntaxNode> {
329         match self {
330             MacroCallKind::FnLike { ast_id, .. } => {
331                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
332             }
333             MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
334                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
335             }
336         }
337     }
338
339     fn arg(&self, db: &dyn db::AstDatabase) -> Option<SyntaxNode> {
340         match self {
341             MacroCallKind::FnLike { ast_id, .. } => {
342                 Some(ast_id.to_node(db).token_tree()?.syntax().clone())
343             }
344             MacroCallKind::Derive { ast_id, .. } | MacroCallKind::Attr { ast_id, .. } => {
345                 Some(ast_id.to_node(db).syntax().clone())
346             }
347         }
348     }
349
350     fn expand_to(&self) -> ExpandTo {
351         match self {
352             MacroCallKind::FnLike { expand_to, .. } => *expand_to,
353             MacroCallKind::Derive { .. } => ExpandTo::Items,
354             MacroCallKind::Attr { .. } => ExpandTo::Items, // is this always correct?
355         }
356     }
357 }
358
359 impl MacroCallId {
360     pub fn as_file(self) -> HirFileId {
361         MacroFile { macro_call_id: self }.into()
362     }
363 }
364
365 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
366 #[derive(Debug, Clone, PartialEq, Eq)]
367 pub struct ExpansionInfo {
368     expanded: InFile<SyntaxNode>,
369     arg: InFile<SyntaxNode>,
370     /// The `macro_rules!` arguments or attribute input.
371     attr_input_or_mac_def: Option<InFile<ast::TokenTree>>,
372
373     macro_def: Arc<TokenExpander>,
374     macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
375     macro_arg_shift: mbe::Shift,
376     exp_map: Arc<mbe::TokenMap>,
377 }
378
379 pub use mbe::Origin;
380
381 impl ExpansionInfo {
382     pub fn call_node(&self) -> Option<InFile<SyntaxNode>> {
383         Some(self.arg.with_value(self.arg.value.parent()?))
384     }
385
386     pub fn map_token_down(
387         &self,
388         db: &dyn db::AstDatabase,
389         item: Option<ast::Item>,
390         token: InFile<&SyntaxToken>,
391     ) -> Option<impl Iterator<Item = InFile<SyntaxToken>> + '_> {
392         assert_eq!(token.file_id, self.arg.file_id);
393         let token_id = if let Some(item) = item {
394             // check if we are mapping down in an attribute input
395             let call_id = match self.expanded.file_id.0 {
396                 HirFileIdRepr::FileId(_) => return None,
397                 HirFileIdRepr::MacroFile(macro_file) => macro_file.macro_call_id,
398             };
399             let loc = db.lookup_intern_macro(call_id);
400
401             let token_range = token.value.text_range();
402             match &loc.kind {
403                 MacroCallKind::Attr { attr_args, invoc_attr_index, .. } => {
404                     let attr = item.attrs().nth(*invoc_attr_index as usize)?;
405                     match attr.token_tree() {
406                         Some(token_tree)
407                             if token_tree.syntax().text_range().contains_range(token_range) =>
408                         {
409                             let attr_input_start =
410                                 token_tree.left_delimiter_token()?.text_range().start();
411                             let range = token.value.text_range().checked_sub(attr_input_start)?;
412                             let token_id =
413                                 self.macro_arg_shift.shift(attr_args.1.token_by_range(range)?);
414                             Some(token_id)
415                         }
416                         _ => None,
417                     }
418                 }
419                 _ => None,
420             }
421         } else {
422             None
423         };
424
425         let token_id = match token_id {
426             Some(token_id) => token_id,
427             None => {
428                 let range =
429                     token.value.text_range().checked_sub(self.arg.value.text_range().start())?;
430                 let token_id = self.macro_arg.1.token_by_range(range)?;
431                 self.macro_def.map_id_down(token_id)
432             }
433         };
434
435         let tokens = self
436             .exp_map
437             .ranges_by_token(token_id, token.value.kind())
438             .flat_map(move |range| self.expanded.value.covering_element(range).into_token());
439
440         Some(tokens.map(move |token| self.expanded.with_value(token)))
441     }
442
443     pub fn map_token_up(
444         &self,
445         db: &dyn db::AstDatabase,
446         token: InFile<&SyntaxToken>,
447     ) -> Option<(InFile<SyntaxToken>, Origin)> {
448         let token_id = self.exp_map.token_by_range(token.value.text_range())?;
449         let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
450
451         let call_id = match self.expanded.file_id.0 {
452             HirFileIdRepr::FileId(_) => return None,
453             HirFileIdRepr::MacroFile(macro_file) => macro_file.macro_call_id,
454         };
455         let loc = db.lookup_intern_macro(call_id);
456
457         let (token_map, tt) = match &loc.kind {
458             MacroCallKind::Attr { attr_args, .. } => match self.macro_arg_shift.unshift(token_id) {
459                 Some(unshifted) => {
460                     token_id = unshifted;
461                     (&attr_args.1, self.attr_input_or_mac_def.clone()?.syntax().cloned())
462                 }
463                 None => (&self.macro_arg.1, self.arg.clone()),
464             },
465             _ => match origin {
466                 mbe::Origin::Call => (&self.macro_arg.1, self.arg.clone()),
467                 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def) {
468                     (
469                         TokenExpander::MacroRules { def_site_token_map, .. }
470                         | TokenExpander::MacroDef { def_site_token_map, .. },
471                         Some(tt),
472                     ) => (def_site_token_map, tt.syntax().cloned()),
473                     _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
474                 },
475             },
476         };
477
478         let range = token_map.first_range_by_token(token_id, token.value.kind())?;
479         let token =
480             tt.value.covering_element(range + tt.value.text_range().start()).into_token()?;
481         Some((tt.with_value(token), origin))
482     }
483 }
484
485 /// `AstId` points to an AST node in any file.
486 ///
487 /// It is stable across reparses, and can be used as salsa key/value.
488 // FIXME: isn't this just a `Source<FileAstId<N>>` ?
489 pub type AstId<N> = InFile<FileAstId<N>>;
490
491 impl<N: AstNode> AstId<N> {
492     pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
493         let root = db.parse_or_expand(self.file_id).unwrap();
494         db.ast_id_map(self.file_id).get(self.value).to_node(&root)
495     }
496 }
497
498 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
499 ///
500 /// Typical usages are:
501 ///
502 /// * `InFile<SyntaxNode>` -- syntax node in a file
503 /// * `InFile<ast::FnDef>` -- ast node in a file
504 /// * `InFile<TextSize>` -- offset in a file
505 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
506 pub struct InFile<T> {
507     pub file_id: HirFileId,
508     pub value: T,
509 }
510
511 impl<T> InFile<T> {
512     pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
513         InFile { file_id, value }
514     }
515
516     // Similarly, naming here is stupid...
517     pub fn with_value<U>(&self, value: U) -> InFile<U> {
518         InFile::new(self.file_id, value)
519     }
520
521     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
522         InFile::new(self.file_id, f(self.value))
523     }
524     pub fn as_ref(&self) -> InFile<&T> {
525         self.with_value(&self.value)
526     }
527     pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
528         db.parse_or_expand(self.file_id).expect("source created from invalid file")
529     }
530 }
531
532 impl<T: Clone> InFile<&T> {
533     pub fn cloned(&self) -> InFile<T> {
534         self.with_value(self.value.clone())
535     }
536 }
537
538 impl<T> InFile<Option<T>> {
539     pub fn transpose(self) -> Option<InFile<T>> {
540         let value = self.value?;
541         Some(InFile::new(self.file_id, value))
542     }
543 }
544
545 impl InFile<SyntaxNode> {
546     pub fn ancestors_with_macros(
547         self,
548         db: &dyn db::AstDatabase,
549     ) -> impl Iterator<Item = InFile<SyntaxNode>> + Clone + '_ {
550         iter::successors(Some(self), move |node| match node.value.parent() {
551             Some(parent) => Some(node.with_value(parent)),
552             None => {
553                 let parent_node = node.file_id.call_node(db)?;
554                 Some(parent_node)
555             }
556         })
557     }
558
559     /// Skips the attributed item that caused the macro invocation we are climbing up
560     pub fn ancestors_with_macros_skip_attr_item(
561         self,
562         db: &dyn db::AstDatabase,
563     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
564         iter::successors(Some(self), move |node| match node.value.parent() {
565             Some(parent) => Some(node.with_value(parent)),
566             None => {
567                 let parent_node = node.file_id.call_node(db)?;
568                 if node.file_id.is_attr_macro(db) {
569                     // macro call was an attributed item, skip it
570                     // FIXME: does this fail if this is a direct expansion of another macro?
571                     parent_node.map(|node| node.parent()).transpose()
572                 } else {
573                     Some(parent_node)
574                 }
575             }
576         })
577     }
578 }
579
580 impl<'a> InFile<&'a SyntaxNode> {
581     /// Falls back to the macro call range if the node cannot be mapped up fully.
582     pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
583         if let Some(res) = self.original_file_range_opt(db) {
584             return res;
585         }
586
587         // Fall back to whole macro call.
588         let mut node = self.cloned();
589         while let Some(call_node) = node.file_id.call_node(db) {
590             node = call_node;
591         }
592
593         let orig_file = node.file_id.original_file(db);
594         assert_eq!(node.file_id, orig_file.into());
595
596         FileRange { file_id: orig_file, range: node.value.text_range() }
597     }
598
599     /// Attempts to map the syntax node back up its macro calls.
600     pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
601         match original_range_opt(db, self) {
602             Some(range) => {
603                 let original_file = range.file_id.original_file(db);
604                 if range.file_id != original_file.into() {
605                     tracing::error!("Failed mapping up more for {:?}", range);
606                 }
607                 Some(FileRange { file_id: original_file, range: range.value })
608             }
609             _ if !self.file_id.is_macro() => Some(FileRange {
610                 file_id: self.file_id.original_file(db),
611                 range: self.value.text_range(),
612             }),
613             _ => None,
614         }
615     }
616 }
617
618 fn original_range_opt(
619     db: &dyn db::AstDatabase,
620     node: InFile<&SyntaxNode>,
621 ) -> Option<InFile<TextRange>> {
622     let expansion = node.file_id.expansion_info(db)?;
623
624     // the input node has only one token ?
625     let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
626         == skip_trivia_token(node.value.last_token()?, Direction::Prev)?;
627
628     node.value.descendants().find_map(|it| {
629         let first = skip_trivia_token(it.first_token()?, Direction::Next)?;
630         let first = ascend_call_token(db, &expansion, node.with_value(first))?;
631
632         let last = skip_trivia_token(it.last_token()?, Direction::Prev)?;
633         let last = ascend_call_token(db, &expansion, node.with_value(last))?;
634
635         if (!single && first == last) || (first.file_id != last.file_id) {
636             return None;
637         }
638
639         Some(first.with_value(first.value.text_range().cover(last.value.text_range())))
640     })
641 }
642
643 fn ascend_call_token(
644     db: &dyn db::AstDatabase,
645     expansion: &ExpansionInfo,
646     token: InFile<SyntaxToken>,
647 ) -> Option<InFile<SyntaxToken>> {
648     let (mapped, origin) = expansion.map_token_up(db, token.as_ref())?;
649     if origin != Origin::Call {
650         return None;
651     }
652     if let Some(info) = mapped.file_id.expansion_info(db) {
653         return ascend_call_token(db, &info, mapped);
654     }
655     Some(mapped)
656 }
657
658 impl InFile<SyntaxToken> {
659     pub fn ancestors_with_macros(
660         self,
661         db: &dyn db::AstDatabase,
662     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
663         self.value.parent().into_iter().flat_map({
664             let file_id = self.file_id;
665             move |parent| InFile::new(file_id, parent).ancestors_with_macros(db)
666         })
667     }
668 }
669
670 impl<N: AstNode> InFile<N> {
671     pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
672         self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
673     }
674
675     pub fn syntax(&self) -> InFile<&SyntaxNode> {
676         self.with_value(self.value.syntax())
677     }
678
679     pub fn nodes_with_attributes<'db>(
680         self,
681         db: &'db dyn db::AstDatabase,
682     ) -> impl Iterator<Item = InFile<N>> + 'db
683     where
684         N: 'db,
685     {
686         iter::successors(Some(self), move |node| {
687             let InFile { file_id, value } = node.file_id.call_node(db)?;
688             N::cast(value).map(|n| InFile::new(file_id, n))
689         })
690     }
691
692     pub fn node_with_attributes(self, db: &dyn db::AstDatabase) -> InFile<N> {
693         self.nodes_with_attributes(db).last().unwrap()
694     }
695 }
696
697 /// In Rust, macros expand token trees to token trees. When we want to turn a
698 /// token tree into an AST node, we need to figure out what kind of AST node we
699 /// want: something like `foo` can be a type, an expression, or a pattern.
700 ///
701 /// Naively, one would think that "what this expands to" is a property of a
702 /// particular macro: macro `m1` returns an item, while macro `m2` returns an
703 /// expression, etc. That's not the case -- macros are polymorphic in the
704 /// result, and can expand to any type of the AST node.
705 ///
706 /// What defines the actual AST node is the syntactic context of the macro
707 /// invocation. As a contrived example, in `let T![*] = T![*];` the first `T`
708 /// expands to a pattern, while the second one expands to an expression.
709 ///
710 /// `ExpandTo` captures this bit of information about a particular macro call
711 /// site.
712 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
713 pub enum ExpandTo {
714     Statements,
715     Items,
716     Pattern,
717     Type,
718     Expr,
719 }
720
721 impl ExpandTo {
722     pub fn from_call_site(call: &ast::MacroCall) -> ExpandTo {
723         use syntax::SyntaxKind::*;
724
725         let syn = call.syntax();
726
727         let parent = match syn.parent() {
728             Some(it) => it,
729             None => return ExpandTo::Statements,
730         };
731
732         match parent.kind() {
733             MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => ExpandTo::Items,
734             MACRO_STMTS | EXPR_STMT | STMT_LIST => ExpandTo::Statements,
735             MACRO_PAT => ExpandTo::Pattern,
736             MACRO_TYPE => ExpandTo::Type,
737
738             ARG_LIST | TRY_EXPR | TUPLE_EXPR | PAREN_EXPR | ARRAY_EXPR | FOR_EXPR | PATH_EXPR
739             | CLOSURE_EXPR | CONDITION | BREAK_EXPR | RETURN_EXPR | MATCH_EXPR | MATCH_ARM
740             | MATCH_GUARD | RECORD_EXPR_FIELD | CALL_EXPR | INDEX_EXPR | METHOD_CALL_EXPR
741             | FIELD_EXPR | AWAIT_EXPR | CAST_EXPR | REF_EXPR | PREFIX_EXPR | RANGE_EXPR
742             | BIN_EXPR => ExpandTo::Expr,
743             LET_STMT => {
744                 // FIXME: Handle LHS Pattern
745                 ExpandTo::Expr
746             }
747
748             _ => {
749                 // Unknown , Just guess it is `Items`
750                 ExpandTo::Items
751             }
752         }
753     }
754 }