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