]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/lib.rs
Basic Support Macro 2.0
[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 diagnostics;
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 either::Either;
19 pub use mbe::{ExpandError, ExpandResult};
20
21 use std::hash::Hash;
22 use std::sync::Arc;
23
24 use base_db::{impl_intern_key, salsa, CrateId, FileId, FileRange};
25 use syntax::{
26     algo::skip_trivia_token,
27     ast::{self, AstNode},
28     Direction, SyntaxNode, SyntaxToken, TextRange, TextSize,
29 };
30
31 use crate::ast_id_map::FileAstId;
32 use crate::builtin_derive::BuiltinDeriveExpander;
33 use crate::builtin_macro::{BuiltinFnLikeExpander, EagerExpander};
34 use crate::proc_macro::ProcMacroExpander;
35
36 #[cfg(test)]
37 mod test_db;
38
39 /// Input to the analyzer is a set of files, where each file is identified by
40 /// `FileId` and contains source code. However, another source of source code in
41 /// Rust are macros: each macro can be thought of as producing a "temporary
42 /// file". To assign an id to such a file, we use the id of the macro call that
43 /// produced the file. So, a `HirFileId` is either a `FileId` (source code
44 /// written by user), or a `MacroCallId` (source code produced by macro).
45 ///
46 /// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
47 /// containing the call plus the offset of the macro call in the file. Note that
48 /// this is a recursive definition! However, the size_of of `HirFileId` is
49 /// finite (because everything bottoms out at the real `FileId`) and small
50 /// (`MacroCallId` uses the location interning. You can check details here:
51 /// https://en.wikipedia.org/wiki/String_interning).
52 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53 pub struct HirFileId(HirFileIdRepr);
54
55 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56 enum HirFileIdRepr {
57     FileId(FileId),
58     MacroFile(MacroFile),
59 }
60
61 impl From<FileId> for HirFileId {
62     fn from(id: FileId) -> Self {
63         HirFileId(HirFileIdRepr::FileId(id))
64     }
65 }
66
67 impl From<MacroFile> for HirFileId {
68     fn from(id: MacroFile) -> Self {
69         HirFileId(HirFileIdRepr::MacroFile(id))
70     }
71 }
72
73 impl HirFileId {
74     /// For macro-expansion files, returns the file original source file the
75     /// expansion originated from.
76     pub fn original_file(self, db: &dyn db::AstDatabase) -> FileId {
77         match self.0 {
78             HirFileIdRepr::FileId(file_id) => file_id,
79             HirFileIdRepr::MacroFile(macro_file) => {
80                 let file_id = match macro_file.macro_call_id {
81                     MacroCallId::LazyMacro(id) => {
82                         let loc = db.lookup_intern_macro(id);
83                         loc.kind.file_id()
84                     }
85                     MacroCallId::EagerMacro(id) => {
86                         let loc = db.lookup_intern_eager_expansion(id);
87                         if let Some(included_file) = loc.included_file {
88                             return included_file;
89                         } else {
90                             loc.call.file_id
91                         }
92                     }
93                 };
94                 file_id.original_file(db)
95             }
96         }
97     }
98
99     pub fn expansion_level(self, db: &dyn db::AstDatabase) -> u32 {
100         let mut level = 0;
101         let mut curr = self;
102         while let HirFileIdRepr::MacroFile(macro_file) = curr.0 {
103             level += 1;
104             curr = match macro_file.macro_call_id {
105                 MacroCallId::LazyMacro(id) => {
106                     let loc = db.lookup_intern_macro(id);
107                     loc.kind.file_id()
108                 }
109                 MacroCallId::EagerMacro(id) => {
110                     let loc = db.lookup_intern_eager_expansion(id);
111                     loc.call.file_id
112                 }
113             };
114         }
115         level
116     }
117
118     /// If this is a macro call, returns the syntax node of the call.
119     pub fn call_node(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxNode>> {
120         match self.0 {
121             HirFileIdRepr::FileId(_) => None,
122             HirFileIdRepr::MacroFile(macro_file) => match macro_file.macro_call_id {
123                 MacroCallId::LazyMacro(lazy_id) => {
124                     let loc: MacroCallLoc = db.lookup_intern_macro(lazy_id);
125                     Some(loc.kind.node(db))
126                 }
127                 MacroCallId::EagerMacro(id) => {
128                     let loc: EagerCallLoc = db.lookup_intern_eager_expansion(id);
129                     Some(loc.call.with_value(loc.call.to_node(db).syntax().clone()))
130                 }
131             },
132         }
133     }
134
135     /// Return expansion information if it is a macro-expansion file
136     pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
137         match self.0 {
138             HirFileIdRepr::FileId(_) => None,
139             HirFileIdRepr::MacroFile(macro_file) => {
140                 let lazy_id = match macro_file.macro_call_id {
141                     MacroCallId::LazyMacro(id) => id,
142                     MacroCallId::EagerMacro(_id) => {
143                         // FIXME: handle expansion_info for eager macro
144                         return None;
145                     }
146                 };
147                 let loc: MacroCallLoc = db.lookup_intern_macro(lazy_id);
148
149                 let arg_tt = loc.kind.arg(db)?;
150
151                 let def = loc.def.ast_id().left().and_then(|id| {
152                     let def_tt = match id.to_node(db) {
153                         ast::Macro::MacroRules(mac) => mac.token_tree()?,
154                         ast::Macro::MacroDef(mac) => mac.body()?,
155                     };
156                     Some(InFile::new(id.file_id, def_tt))
157                 });
158
159                 let macro_def = db.macro_def(loc.def)?;
160                 let (parse, exp_map) = db.parse_macro_expansion(macro_file).value?;
161                 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
162
163                 Some(ExpansionInfo {
164                     expanded: InFile::new(self, parse.syntax_node()),
165                     arg: InFile::new(loc.kind.file_id(), arg_tt),
166                     def,
167                     macro_arg,
168                     macro_def,
169                     exp_map,
170                 })
171             }
172         }
173     }
174
175     /// Indicate it is macro file generated for builtin derive
176     pub fn is_builtin_derive(&self, db: &dyn db::AstDatabase) -> Option<InFile<ast::Item>> {
177         match self.0 {
178             HirFileIdRepr::FileId(_) => None,
179             HirFileIdRepr::MacroFile(macro_file) => {
180                 let lazy_id = match macro_file.macro_call_id {
181                     MacroCallId::LazyMacro(id) => id,
182                     MacroCallId::EagerMacro(_id) => {
183                         return None;
184                     }
185                 };
186                 let loc: MacroCallLoc = db.lookup_intern_macro(lazy_id);
187                 let item = match loc.def.kind {
188                     MacroDefKind::BuiltInDerive(..) => loc.kind.node(db),
189                     _ => return None,
190                 };
191                 Some(item.with_value(ast::Item::cast(item.value.clone())?))
192             }
193         }
194     }
195
196     /// Return whether this file is an include macro
197     pub fn is_include_macro(&self, db: &dyn db::AstDatabase) -> bool {
198         match self.0 {
199             HirFileIdRepr::MacroFile(macro_file) => match macro_file.macro_call_id {
200                 MacroCallId::EagerMacro(id) => {
201                     let loc = db.lookup_intern_eager_expansion(id);
202                     return loc.included_file.is_some();
203                 }
204                 _ => {}
205             },
206             _ => {}
207         }
208         false
209     }
210 }
211
212 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213 pub struct MacroFile {
214     macro_call_id: MacroCallId,
215 }
216
217 /// `MacroCallId` identifies a particular macro invocation, like
218 /// `println!("Hello, {}", world)`.
219 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
220 pub enum MacroCallId {
221     LazyMacro(LazyMacroId),
222     EagerMacro(EagerMacroId),
223 }
224
225 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226 pub struct LazyMacroId(salsa::InternId);
227 impl_intern_key!(LazyMacroId);
228
229 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
230 pub struct EagerMacroId(salsa::InternId);
231 impl_intern_key!(EagerMacroId);
232
233 impl From<LazyMacroId> for MacroCallId {
234     fn from(it: LazyMacroId) -> Self {
235         MacroCallId::LazyMacro(it)
236     }
237 }
238 impl From<EagerMacroId> for MacroCallId {
239     fn from(it: EagerMacroId) -> Self {
240         MacroCallId::EagerMacro(it)
241     }
242 }
243
244 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
245 pub struct MacroDefId {
246     pub krate: CrateId,
247     pub kind: MacroDefKind,
248
249     pub local_inner: bool,
250 }
251
252 impl MacroDefId {
253     pub fn as_lazy_macro(
254         self,
255         db: &dyn db::AstDatabase,
256         krate: CrateId,
257         kind: MacroCallKind,
258     ) -> LazyMacroId {
259         db.intern_macro(MacroCallLoc { def: self, krate, kind })
260     }
261
262     pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
263         let id = match &self.kind {
264             MacroDefKind::Declarative(id) => id,
265             MacroDefKind::BuiltIn(_, id) => id,
266             MacroDefKind::BuiltInDerive(_, id) => id,
267             MacroDefKind::BuiltInEager(_, id) => id,
268             MacroDefKind::ProcMacro(_, id) => return Either::Right(*id),
269         };
270         Either::Left(*id)
271     }
272 }
273
274 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
275 pub enum MacroDefKind {
276     Declarative(AstId<ast::Macro>),
277     BuiltIn(BuiltinFnLikeExpander, AstId<ast::Macro>),
278     // FIXME: maybe just Builtin and rename BuiltinFnLikeExpander to BuiltinExpander
279     BuiltInDerive(BuiltinDeriveExpander, AstId<ast::Macro>),
280     BuiltInEager(EagerExpander, AstId<ast::Macro>),
281     ProcMacro(ProcMacroExpander, AstId<ast::Fn>),
282 }
283
284 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
285 pub struct MacroCallLoc {
286     pub(crate) def: MacroDefId,
287     pub(crate) krate: CrateId,
288     pub kind: MacroCallKind,
289 }
290
291 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
292 pub enum MacroCallKind {
293     FnLike(AstId<ast::MacroCall>),
294     Derive(AstId<ast::Item>, String),
295 }
296
297 impl MacroCallKind {
298     fn file_id(&self) -> HirFileId {
299         match self {
300             MacroCallKind::FnLike(ast_id) => ast_id.file_id,
301             MacroCallKind::Derive(ast_id, _) => ast_id.file_id,
302         }
303     }
304
305     fn node(&self, db: &dyn db::AstDatabase) -> InFile<SyntaxNode> {
306         match self {
307             MacroCallKind::FnLike(ast_id) => ast_id.with_value(ast_id.to_node(db).syntax().clone()),
308             MacroCallKind::Derive(ast_id, _) => {
309                 ast_id.with_value(ast_id.to_node(db).syntax().clone())
310             }
311         }
312     }
313
314     fn arg(&self, db: &dyn db::AstDatabase) -> Option<SyntaxNode> {
315         match self {
316             MacroCallKind::FnLike(ast_id) => {
317                 Some(ast_id.to_node(db).token_tree()?.syntax().clone())
318             }
319             MacroCallKind::Derive(ast_id, _) => Some(ast_id.to_node(db).syntax().clone()),
320         }
321     }
322 }
323
324 impl MacroCallId {
325     pub fn as_file(self) -> HirFileId {
326         MacroFile { macro_call_id: self }.into()
327     }
328 }
329
330 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
331 pub struct EagerCallLoc {
332     pub(crate) def: MacroDefId,
333     pub(crate) fragment: FragmentKind,
334     pub(crate) subtree: Arc<tt::Subtree>,
335     pub(crate) krate: CrateId,
336     pub(crate) call: AstId<ast::MacroCall>,
337     // The included file ID of the include macro.
338     pub(crate) included_file: Option<FileId>,
339 }
340
341 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
342 #[derive(Debug, Clone, PartialEq, Eq)]
343 pub struct ExpansionInfo {
344     expanded: InFile<SyntaxNode>,
345     arg: InFile<SyntaxNode>,
346     /// The `macro_rules!` arguments.
347     def: Option<InFile<ast::TokenTree>>,
348
349     macro_def: Arc<(db::TokenExpander, mbe::TokenMap)>,
350     macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
351     exp_map: Arc<mbe::TokenMap>,
352 }
353
354 pub use mbe::Origin;
355 use parser::FragmentKind;
356
357 impl ExpansionInfo {
358     pub fn call_node(&self) -> Option<InFile<SyntaxNode>> {
359         Some(self.arg.with_value(self.arg.value.parent()?))
360     }
361
362     pub fn map_token_down(&self, token: InFile<&SyntaxToken>) -> Option<InFile<SyntaxToken>> {
363         assert_eq!(token.file_id, self.arg.file_id);
364         let range = token.value.text_range().checked_sub(self.arg.value.text_range().start())?;
365         let token_id = self.macro_arg.1.token_by_range(range)?;
366         let token_id = self.macro_def.0.map_id_down(token_id);
367
368         let range = self.exp_map.range_by_token(token_id)?.by_kind(token.value.kind())?;
369
370         let token = self.expanded.value.covering_element(range).into_token()?;
371
372         Some(self.expanded.with_value(token))
373     }
374
375     pub fn map_token_up(
376         &self,
377         token: InFile<&SyntaxToken>,
378     ) -> Option<(InFile<SyntaxToken>, Origin)> {
379         let token_id = self.exp_map.token_by_range(token.value.text_range())?;
380
381         let (token_id, origin) = self.macro_def.0.map_id_up(token_id);
382         let (token_map, tt) = match origin {
383             mbe::Origin::Call => (&self.macro_arg.1, self.arg.clone()),
384             mbe::Origin::Def => (
385                 &self.macro_def.1,
386                 self.def
387                     .as_ref()
388                     .expect("`Origin::Def` used with non-`macro_rules!` macro")
389                     .as_ref()
390                     .map(|tt| tt.syntax().clone()),
391             ),
392         };
393
394         let range = token_map.range_by_token(token_id)?.by_kind(token.value.kind())?;
395         let token =
396             tt.value.covering_element(range + tt.value.text_range().start()).into_token()?;
397         Some((tt.with_value(token), origin))
398     }
399 }
400
401 /// `AstId` points to an AST node in any file.
402 ///
403 /// It is stable across reparses, and can be used as salsa key/value.
404 // FIXME: isn't this just a `Source<FileAstId<N>>` ?
405 pub type AstId<N> = InFile<FileAstId<N>>;
406
407 impl<N: AstNode> AstId<N> {
408     pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
409         let root = db.parse_or_expand(self.file_id).unwrap();
410         db.ast_id_map(self.file_id).get(self.value).to_node(&root)
411     }
412 }
413
414 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
415 ///
416 /// Typical usages are:
417 ///
418 /// * `InFile<SyntaxNode>` -- syntax node in a file
419 /// * `InFile<ast::FnDef>` -- ast node in a file
420 /// * `InFile<TextSize>` -- offset in a file
421 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
422 pub struct InFile<T> {
423     pub file_id: HirFileId,
424     pub value: T,
425 }
426
427 impl<T> InFile<T> {
428     pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
429         InFile { file_id, value }
430     }
431
432     // Similarly, naming here is stupid...
433     pub fn with_value<U>(&self, value: U) -> InFile<U> {
434         InFile::new(self.file_id, value)
435     }
436
437     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
438         InFile::new(self.file_id, f(self.value))
439     }
440     pub fn as_ref(&self) -> InFile<&T> {
441         self.with_value(&self.value)
442     }
443     pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
444         db.parse_or_expand(self.file_id).expect("source created from invalid file")
445     }
446 }
447
448 impl<T: Clone> InFile<&T> {
449     pub fn cloned(&self) -> InFile<T> {
450         self.with_value(self.value.clone())
451     }
452 }
453
454 impl<T> InFile<Option<T>> {
455     pub fn transpose(self) -> Option<InFile<T>> {
456         let value = self.value?;
457         Some(InFile::new(self.file_id, value))
458     }
459 }
460
461 impl InFile<SyntaxNode> {
462     pub fn ancestors_with_macros(
463         self,
464         db: &dyn db::AstDatabase,
465     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
466         std::iter::successors(Some(self), move |node| match node.value.parent() {
467             Some(parent) => Some(node.with_value(parent)),
468             None => {
469                 let parent_node = node.file_id.call_node(db)?;
470                 Some(parent_node)
471             }
472         })
473     }
474 }
475
476 impl<'a> InFile<&'a SyntaxNode> {
477     pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
478         if let Some(range) = original_range_opt(db, self) {
479             let original_file = range.file_id.original_file(db);
480             if range.file_id == original_file.into() {
481                 return FileRange { file_id: original_file, range: range.value };
482             }
483
484             log::error!("Fail to mapping up more for {:?}", range);
485             return FileRange { file_id: range.file_id.original_file(db), range: range.value };
486         }
487
488         // Fall back to whole macro call.
489         let mut node = self.cloned();
490         while let Some(call_node) = node.file_id.call_node(db) {
491             node = call_node;
492         }
493
494         let orig_file = node.file_id.original_file(db);
495         assert_eq!(node.file_id, orig_file.into());
496         FileRange { file_id: orig_file, range: node.value.text_range() }
497     }
498 }
499
500 fn original_range_opt(
501     db: &dyn db::AstDatabase,
502     node: InFile<&SyntaxNode>,
503 ) -> Option<InFile<TextRange>> {
504     let expansion = node.file_id.expansion_info(db)?;
505
506     // the input node has only one token ?
507     let single = skip_trivia_token(node.value.first_token()?, Direction::Next)?
508         == skip_trivia_token(node.value.last_token()?, Direction::Prev)?;
509
510     node.value.descendants().find_map(|it| {
511         let first = skip_trivia_token(it.first_token()?, Direction::Next)?;
512         let first = ascend_call_token(db, &expansion, node.with_value(first))?;
513
514         let last = skip_trivia_token(it.last_token()?, Direction::Prev)?;
515         let last = ascend_call_token(db, &expansion, node.with_value(last))?;
516
517         if (!single && first == last) || (first.file_id != last.file_id) {
518             return None;
519         }
520
521         Some(first.with_value(first.value.text_range().cover(last.value.text_range())))
522     })
523 }
524
525 fn ascend_call_token(
526     db: &dyn db::AstDatabase,
527     expansion: &ExpansionInfo,
528     token: InFile<SyntaxToken>,
529 ) -> Option<InFile<SyntaxToken>> {
530     let (mapped, origin) = expansion.map_token_up(token.as_ref())?;
531     if origin != Origin::Call {
532         return None;
533     }
534     if let Some(info) = mapped.file_id.expansion_info(db) {
535         return ascend_call_token(db, &info, mapped);
536     }
537     Some(mapped)
538 }
539
540 impl InFile<SyntaxToken> {
541     pub fn ancestors_with_macros(
542         self,
543         db: &dyn db::AstDatabase,
544     ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
545         self.value
546             .parent()
547             .into_iter()
548             .flat_map(move |parent| InFile::new(self.file_id, parent).ancestors_with_macros(db))
549     }
550 }
551
552 impl<N: AstNode> InFile<N> {
553     pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
554         self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
555     }
556
557     pub fn syntax(&self) -> InFile<&SyntaxNode> {
558         self.with_value(self.value.syntax())
559     }
560 }