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