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