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