1 //! `hir_expand` deals with macro expansion.
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
11 pub mod builtin_attr_macro;
12 pub mod builtin_derive_macro;
13 pub mod builtin_fn_macro;
19 pub use mbe::{ExpandError, ExpandResult, Origin};
21 use std::{hash::Hash, iter, sync::Arc};
23 use base_db::{impl_intern_key, salsa, CrateId, FileId, FileRange, ProcMacroKind};
26 algo::{self, skip_trivia_token},
27 ast::{self, AstNode, HasDocComments},
28 Direction, SyntaxNode, SyntaxToken,
32 ast_id_map::FileAstId,
33 builtin_attr_macro::BuiltinAttrExpander,
34 builtin_derive_macro::BuiltinDeriveExpander,
35 builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
38 proc_macro::ProcMacroExpander,
41 /// Input to the analyzer is a set of files, where each file is identified by
42 /// `FileId` and contains source code. However, another source of source code in
43 /// Rust are macros: each macro can be thought of as producing a "temporary
44 /// file". To assign an id to such a file, we use the id of the macro call that
45 /// produced the file. So, a `HirFileId` is either a `FileId` (source code
46 /// written by user), or a `MacroCallId` (source code produced by macro).
48 /// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
49 /// containing the call plus the offset of the macro call in the file. Note that
50 /// this is a recursive definition! However, the size_of of `HirFileId` is
51 /// finite (because everything bottoms out at the real `FileId`) and small
52 /// (`MacroCallId` uses the location interning. You can check details here:
53 /// <https://en.wikipedia.org/wiki/String_interning>).
54 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55 pub struct HirFileId(HirFileIdRepr);
57 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63 impl From<FileId> for HirFileId {
64 fn from(id: FileId) -> Self {
65 HirFileId(HirFileIdRepr::FileId(id))
69 impl From<MacroFile> for HirFileId {
70 fn from(id: MacroFile) -> Self {
71 HirFileId(HirFileIdRepr::MacroFile(id))
75 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76 pub struct MacroFile {
77 pub macro_call_id: MacroCallId,
80 /// `MacroCallId` identifies a particular macro invocation, like
81 /// `println!("Hello, {}", world)`.
82 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83 pub struct MacroCallId(salsa::InternId);
84 impl_intern_key!(MacroCallId);
86 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
87 pub struct MacroCallLoc {
89 pub(crate) krate: CrateId,
90 eager: Option<EagerCallInfo>,
91 pub kind: MacroCallKind,
94 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95 pub struct MacroDefId {
97 pub kind: MacroDefKind,
98 pub local_inner: bool,
101 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102 pub enum MacroDefKind {
103 Declarative(AstId<ast::Macro>),
104 BuiltIn(BuiltinFnLikeExpander, AstId<ast::Macro>),
105 // FIXME: maybe just Builtin and rename BuiltinFnLikeExpander to BuiltinExpander
106 BuiltInAttr(BuiltinAttrExpander, AstId<ast::Macro>),
107 BuiltInDerive(BuiltinDeriveExpander, AstId<ast::Macro>),
108 BuiltInEager(EagerExpander, AstId<ast::Macro>),
109 ProcMacro(ProcMacroExpander, ProcMacroKind, AstId<ast::Fn>),
112 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
113 struct EagerCallInfo {
114 /// NOTE: This can be *either* the expansion result, *or* the argument to the eager macro!
115 arg_or_expansion: Arc<tt::Subtree>,
116 included_file: Option<FileId>,
119 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
120 pub enum MacroCallKind {
122 ast_id: AstId<ast::MacroCall>,
126 ast_id: AstId<ast::Adt>,
127 derive_name: Box<str>,
128 /// Syntactical index of the invoking `#[derive]` attribute.
130 /// Outer attributes are counted first, then inner attributes. This does not support
131 /// out-of-line modules, which may have attributes spread across 2 files!
132 derive_attr_index: u32,
135 ast_id: AstId<ast::Item>,
137 attr_args: (tt::Subtree, mbe::TokenMap),
138 /// Syntactical index of the invoking `#[attribute]`.
140 /// Outer attributes are counted first, then inner attributes. This does not support
141 /// out-of-line modules, which may have attributes spread across 2 files!
142 invoc_attr_index: u32,
147 /// For macro-expansion files, returns the file original source file the
148 /// expansion originated from.
149 pub fn original_file(self, db: &dyn db::AstDatabase) -> FileId {
151 HirFileIdRepr::FileId(file_id) => file_id,
152 HirFileIdRepr::MacroFile(macro_file) => {
153 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
154 let file_id = match loc.eager {
155 Some(EagerCallInfo { included_file: Some(file), .. }) => file.into(),
156 _ => loc.kind.file_id(),
158 file_id.original_file(db)
163 pub fn expansion_level(self, db: &dyn db::AstDatabase) -> u32 {
166 while let HirFileIdRepr::MacroFile(macro_file) = curr.0 {
167 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
170 curr = loc.kind.file_id();
175 /// If this is a macro call, returns the syntax node of the call.
176 pub fn call_node(self, db: &dyn db::AstDatabase) -> Option<InFile<SyntaxNode>> {
178 HirFileIdRepr::FileId(_) => None,
179 HirFileIdRepr::MacroFile(macro_file) => {
180 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
181 Some(loc.kind.to_node(db))
186 /// Return expansion information if it is a macro-expansion file
187 pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
189 HirFileIdRepr::FileId(_) => None,
190 HirFileIdRepr::MacroFile(macro_file) => {
191 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
193 let arg_tt = loc.kind.arg(db)?;
195 let def = loc.def.ast_id().left().and_then(|id| {
196 let def_tt = match id.to_node(db) {
197 ast::Macro::MacroRules(mac) => mac.token_tree()?,
198 ast::Macro::MacroDef(mac) => mac.body()?,
200 Some(InFile::new(id.file_id, def_tt))
202 let attr_input_or_mac_def = def.or_else(|| match loc.kind {
203 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
206 .doc_comments_and_attrs()
207 .nth(invoc_attr_index as usize)
208 .and_then(Either::left)?
210 Some(InFile::new(ast_id.file_id, tt))
215 let macro_def = db.macro_def(loc.def).ok()?;
216 let (parse, exp_map) = db.parse_macro_expansion(macro_file).value?;
217 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
220 expanded: InFile::new(self, parse.syntax_node()),
221 arg: InFile::new(loc.kind.file_id(), arg_tt),
222 attr_input_or_mac_def,
223 macro_arg_shift: mbe::Shift::new(¯o_arg.0),
232 /// Indicate it is macro file generated for builtin derive
233 pub fn is_builtin_derive(&self, db: &dyn db::AstDatabase) -> Option<InFile<ast::Item>> {
235 HirFileIdRepr::FileId(_) => None,
236 HirFileIdRepr::MacroFile(macro_file) => {
237 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
238 let item = match loc.def.kind {
239 MacroDefKind::BuiltInDerive(..) => loc.kind.to_node(db),
242 Some(item.with_value(ast::Item::cast(item.value.clone())?))
247 pub fn is_custom_derive(&self, db: &dyn db::AstDatabase) -> bool {
249 HirFileIdRepr::FileId(_) => false,
250 HirFileIdRepr::MacroFile(macro_file) => {
251 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
252 matches!(loc.def.kind, MacroDefKind::ProcMacro(_, ProcMacroKind::CustomDerive, _))
257 /// Return whether this file is an include macro
258 pub fn is_include_macro(&self, db: &dyn db::AstDatabase) -> bool {
260 HirFileIdRepr::MacroFile(macro_file) => {
261 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
262 matches!(loc.eager, Some(EagerCallInfo { included_file: Some(_), .. }))
268 /// Return whether this file is an include macro
269 pub fn is_attr_macro(&self, db: &dyn db::AstDatabase) -> bool {
271 HirFileIdRepr::MacroFile(macro_file) => {
272 let loc: MacroCallLoc = db.lookup_intern_macro_call(macro_file.macro_call_id);
273 matches!(loc.kind, MacroCallKind::Attr { .. })
279 pub fn is_macro(self) -> bool {
280 matches!(self.0, HirFileIdRepr::MacroFile(_))
283 pub fn macro_file(self) -> Option<MacroFile> {
285 HirFileIdRepr::FileId(_) => None,
286 HirFileIdRepr::MacroFile(m) => Some(m),
292 pub fn as_lazy_macro(
294 db: &dyn db::AstDatabase,
298 db.intern_macro_call(MacroCallLoc { def: self, krate, eager: None, kind })
301 pub fn ast_id(&self) -> Either<AstId<ast::Macro>, AstId<ast::Fn>> {
302 let id = match self.kind {
303 MacroDefKind::ProcMacro(.., id) => return Either::Right(id),
304 MacroDefKind::Declarative(id)
305 | MacroDefKind::BuiltIn(_, id)
306 | MacroDefKind::BuiltInAttr(_, id)
307 | MacroDefKind::BuiltInDerive(_, id)
308 | MacroDefKind::BuiltInEager(_, id) => id,
313 pub fn is_proc_macro(&self) -> bool {
314 matches!(self.kind, MacroDefKind::ProcMacro(..))
317 pub fn is_attribute(&self) -> bool {
320 MacroDefKind::BuiltInAttr(..) | MacroDefKind::ProcMacro(_, ProcMacroKind::Attr, _)
325 // FIXME: attribute indices do not account for `cfg_attr`, which means that we'll strip the whole
326 // `cfg_attr` instead of just one of the attributes it expands to
329 /// Returns the file containing the macro invocation.
330 fn file_id(&self) -> HirFileId {
332 MacroCallKind::FnLike { ast_id: InFile { file_id, .. }, .. }
333 | MacroCallKind::Derive { ast_id: InFile { file_id, .. }, .. }
334 | MacroCallKind::Attr { ast_id: InFile { file_id, .. }, .. } => file_id,
338 pub fn to_node(&self, db: &dyn db::AstDatabase) -> InFile<SyntaxNode> {
340 MacroCallKind::FnLike { ast_id, .. } => {
341 ast_id.with_value(ast_id.to_node(db).syntax().clone())
343 MacroCallKind::Derive { ast_id, .. } => {
344 ast_id.with_value(ast_id.to_node(db).syntax().clone())
346 MacroCallKind::Attr { ast_id, .. } => {
347 ast_id.with_value(ast_id.to_node(db).syntax().clone())
352 /// Returns the original file range that best describes the location of this macro call.
354 /// Here we try to roughly match what rustc does to improve diagnostics: fn-like macros
355 /// get the whole `ast::MacroCall`, attribute macros get the attribute's range, and derives
356 /// get only the specific derive that is being referred to.
357 pub fn original_call_range(self, db: &dyn db::AstDatabase) -> FileRange {
360 match kind.file_id().0 {
361 HirFileIdRepr::MacroFile(file) => {
362 kind = db.lookup_intern_macro_call(file.macro_call_id).kind;
364 HirFileIdRepr::FileId(file_id) => break file_id,
368 let range = match kind {
369 MacroCallKind::FnLike { ast_id, .. } => ast_id.to_node(db).syntax().text_range(),
370 MacroCallKind::Derive { ast_id, derive_attr_index, .. } => {
371 // FIXME: should be the range of the macro name, not the whole derive
374 .doc_comments_and_attrs()
375 .nth(derive_attr_index as usize)
376 .expect("missing derive")
377 .expect_left("derive is a doc comment?")
381 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => ast_id
383 .doc_comments_and_attrs()
384 .nth(invoc_attr_index as usize)
385 .expect("missing attribute")
386 .expect_left("attribute macro is a doc comment?")
391 FileRange { range, file_id }
394 fn arg(&self, db: &dyn db::AstDatabase) -> Option<SyntaxNode> {
396 MacroCallKind::FnLike { ast_id, .. } => {
397 Some(ast_id.to_node(db).token_tree()?.syntax().clone())
399 MacroCallKind::Derive { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
400 MacroCallKind::Attr { ast_id, .. } => Some(ast_id.to_node(db).syntax().clone()),
404 fn expand_to(&self) -> ExpandTo {
406 MacroCallKind::FnLike { expand_to, .. } => *expand_to,
407 MacroCallKind::Derive { .. } => ExpandTo::Items,
408 MacroCallKind::Attr { .. } => ExpandTo::Items, // is this always correct?
414 pub fn as_file(self) -> HirFileId {
415 MacroFile { macro_call_id: self }.into()
419 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
420 #[derive(Debug, Clone, PartialEq, Eq)]
421 pub struct ExpansionInfo {
422 expanded: InFile<SyntaxNode>,
423 /// The argument TokenTree or item for attributes
424 arg: InFile<SyntaxNode>,
425 /// The `macro_rules!` or attribute input.
426 attr_input_or_mac_def: Option<InFile<ast::TokenTree>>,
428 macro_def: Arc<TokenExpander>,
429 macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
430 /// A shift built from `macro_arg`'s subtree, relevant for attributes as the item is the macro arg
431 /// and as such we need to shift tokens if they are part of an attributes input instead of their item.
432 macro_arg_shift: mbe::Shift,
433 exp_map: Arc<mbe::TokenMap>,
437 pub fn expanded(&self) -> InFile<SyntaxNode> {
438 self.expanded.clone()
441 pub fn call_node(&self) -> Option<InFile<SyntaxNode>> {
442 Some(self.arg.with_value(self.arg.value.parent()?))
445 /// Map a token down from macro input into the macro expansion.
447 /// The inner workings of this function differ slightly depending on the type of macro we are dealing with:
449 /// For declarative macros, we need to accommodate for the macro definition site(which acts as a second unchanging input)
450 /// , as tokens can mapped in and out of it.
451 /// To do this we shift all ids in the expansion by the maximum id of the definition site giving us an easy
452 /// way to map all the tokens.
454 /// Attributes have two different inputs, the input tokentree in the attribute node and the item
455 /// the attribute is annotating. Similarly as for declarative macros we need to do a shift here
456 /// as well. Currently this is done by shifting the attribute input by the maximum id of the item.
457 /// - function-like and derives:
458 /// Both of these only have one simple call site input so no special handling is required here.
459 pub fn map_token_down(
461 db: &dyn db::AstDatabase,
462 item: Option<ast::Item>,
463 token: InFile<&SyntaxToken>,
464 ) -> Option<impl Iterator<Item = InFile<SyntaxToken>> + '_> {
465 assert_eq!(token.file_id, self.arg.file_id);
466 let token_id_in_attr_input = if let Some(item) = item {
467 // check if we are mapping down in an attribute input
468 // this is a special case as attributes can have two inputs
469 let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
470 let loc = db.lookup_intern_macro_call(call_id);
472 let token_range = token.value.text_range();
474 MacroCallKind::Attr { attr_args: (_, map), invoc_attr_index, .. } => {
476 .doc_comments_and_attrs()
477 .nth(*invoc_attr_index as usize)
478 .and_then(Either::left)?;
479 match attr.token_tree() {
481 if token_tree.syntax().text_range().contains_range(token_range) =>
483 let attr_input_start =
484 token_tree.left_delimiter_token()?.text_range().start();
486 token.value.text_range().checked_sub(attr_input_start)?;
487 // shift by the item's tree's max id
489 self.macro_arg_shift.shift(map.token_by_range(relative_range)?);
501 let token_id = match token_id_in_attr_input {
502 Some(token_id) => token_id,
503 // the token is not inside an attribute's input so do the lookup in the macro_arg as ususal
506 token.value.text_range().checked_sub(self.arg.value.text_range().start())?;
507 let token_id = self.macro_arg.1.token_by_range(relative_range)?;
508 // conditionally shift the id by a declaratives macro definition
509 self.macro_def.map_id_down(token_id)
515 .ranges_by_token(token_id, token.value.kind())
516 .flat_map(move |range| self.expanded.value.covering_element(range).into_token());
518 Some(tokens.map(move |token| self.expanded.with_value(token)))
521 /// Map a token up out of the expansion it resides in into the arguments of the macro call of the expansion.
524 db: &dyn db::AstDatabase,
525 token: InFile<&SyntaxToken>,
526 ) -> Option<(InFile<SyntaxToken>, Origin)> {
527 // Fetch the id through its text range,
528 let token_id = self.exp_map.token_by_range(token.value.text_range())?;
529 // conditionally unshifting the id to accommodate for macro-rules def site
530 let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
532 let call_id = self.expanded.file_id.macro_file()?.macro_call_id;
533 let loc = db.lookup_intern_macro_call(call_id);
535 // Attributes are a bit special for us, they have two inputs, the input tokentree and the annotated item.
536 let (token_map, tt) = match &loc.kind {
537 MacroCallKind::Attr { attr_args: (_, arg_token_map), .. } => {
538 // try unshifting the the token id, if unshifting fails, the token resides in the non-item attribute input
539 // note that the `TokenExpander::map_id_up` earlier only unshifts for declarative macros, so we don't double unshift with this
540 match self.macro_arg_shift.unshift(token_id) {
542 token_id = unshifted;
543 (arg_token_map, self.attr_input_or_mac_def.clone()?.syntax().cloned())
545 None => (&self.macro_arg.1, self.arg.clone()),
549 mbe::Origin::Call => (&self.macro_arg.1, self.arg.clone()),
550 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def) {
551 (TokenExpander::DeclarativeMacro { def_site_token_map, .. }, Some(tt)) => {
552 (def_site_token_map, tt.syntax().cloned())
554 _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
559 let range = token_map.first_range_by_token(token_id, token.value.kind())?;
561 tt.value.covering_element(range + tt.value.text_range().start()).into_token()?;
562 Some((tt.with_value(token), origin))
566 /// `AstId` points to an AST node in any file.
568 /// It is stable across reparses, and can be used as salsa key/value.
569 pub type AstId<N> = InFile<FileAstId<N>>;
571 impl<N: AstNode> AstId<N> {
572 pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
573 let root = db.parse_or_expand(self.file_id).unwrap();
574 db.ast_id_map(self.file_id).get(self.value).to_node(&root)
578 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
580 /// Typical usages are:
582 /// * `InFile<SyntaxNode>` -- syntax node in a file
583 /// * `InFile<ast::FnDef>` -- ast node in a file
584 /// * `InFile<TextSize>` -- offset in a file
585 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
586 pub struct InFile<T> {
587 pub file_id: HirFileId,
592 pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
593 InFile { file_id, value }
596 pub fn with_value<U>(&self, value: U) -> InFile<U> {
597 InFile::new(self.file_id, value)
600 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
601 InFile::new(self.file_id, f(self.value))
603 pub fn as_ref(&self) -> InFile<&T> {
604 self.with_value(&self.value)
606 pub fn file_syntax(&self, db: &dyn db::AstDatabase) -> SyntaxNode {
607 db.parse_or_expand(self.file_id).expect("source created from invalid file")
611 impl<T: Clone> InFile<&T> {
612 pub fn cloned(&self) -> InFile<T> {
613 self.with_value(self.value.clone())
617 impl<T> InFile<Option<T>> {
618 pub fn transpose(self) -> Option<InFile<T>> {
619 let value = self.value?;
620 Some(InFile::new(self.file_id, value))
624 impl<'a> InFile<&'a SyntaxNode> {
625 pub fn ancestors_with_macros(
627 db: &dyn db::AstDatabase,
628 ) -> impl Iterator<Item = InFile<SyntaxNode>> + Clone + '_ {
629 iter::successors(Some(self.cloned()), move |node| match node.value.parent() {
630 Some(parent) => Some(node.with_value(parent)),
631 None => node.file_id.call_node(db),
635 /// Skips the attributed item that caused the macro invocation we are climbing up
636 pub fn ancestors_with_macros_skip_attr_item(
638 db: &dyn db::AstDatabase,
639 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
640 iter::successors(Some(self.cloned()), move |node| match node.value.parent() {
641 Some(parent) => Some(node.with_value(parent)),
643 let parent_node = node.file_id.call_node(db)?;
644 if node.file_id.is_attr_macro(db) {
645 // macro call was an attributed item, skip it
646 // FIXME: does this fail if this is a direct expansion of another macro?
647 parent_node.map(|node| node.parent()).transpose()
655 /// Falls back to the macro call range if the node cannot be mapped up fully.
656 pub fn original_file_range(self, db: &dyn db::AstDatabase) -> FileRange {
657 if let Some(res) = self.original_file_range_opt(db) {
661 // Fall back to whole macro call.
662 match self.file_id.0 {
663 HirFileIdRepr::FileId(file_id) => FileRange { file_id, range: self.value.text_range() },
664 HirFileIdRepr::MacroFile(mac_file) => {
665 let loc = db.lookup_intern_macro_call(mac_file.macro_call_id);
666 loc.kind.original_call_range(db)
671 /// Attempts to map the syntax node back up its macro calls.
672 pub fn original_file_range_opt(self, db: &dyn db::AstDatabase) -> Option<FileRange> {
673 match ascend_node_border_tokens(db, self) {
674 Some(InFile { file_id, value: (first, last) }) => {
675 let original_file = file_id.original_file(db);
676 let range = first.text_range().cover(last.text_range());
677 if file_id != original_file.into() {
678 tracing::error!("Failed mapping up more for {:?}", range);
681 Some(FileRange { file_id: original_file, range })
683 _ if !self.file_id.is_macro() => Some(FileRange {
684 file_id: self.file_id.original_file(db),
685 range: self.value.text_range(),
692 fn ascend_node_border_tokens(
693 db: &dyn db::AstDatabase,
694 InFile { file_id, value: node }: InFile<&SyntaxNode>,
695 ) -> Option<InFile<(SyntaxToken, SyntaxToken)>> {
696 let expansion = file_id.expansion_info(db)?;
698 let first_token = |node: &SyntaxNode| skip_trivia_token(node.first_token()?, Direction::Next);
699 let last_token = |node: &SyntaxNode| skip_trivia_token(node.last_token()?, Direction::Prev);
701 let first = first_token(node)?;
702 let last = last_token(node)?;
703 let first = ascend_call_token(db, &expansion, InFile::new(file_id, first))?;
704 let last = ascend_call_token(db, &expansion, InFile::new(file_id, last))?;
705 (first.file_id == last.file_id).then(|| InFile::new(first.file_id, (first.value, last.value)))
708 fn ascend_call_token(
709 db: &dyn db::AstDatabase,
710 expansion: &ExpansionInfo,
711 token: InFile<SyntaxToken>,
712 ) -> Option<InFile<SyntaxToken>> {
713 let mut mapping = expansion.map_token_up(db, token.as_ref())?;
714 while let (mapped, Origin::Call) = mapping {
715 match mapped.file_id.expansion_info(db) {
716 Some(info) => mapping = info.map_token_up(db, mapped.as_ref())?,
717 None => return Some(mapped),
723 impl InFile<SyntaxToken> {
724 pub fn ancestors_with_macros(
726 db: &dyn db::AstDatabase,
727 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
728 self.value.parent().into_iter().flat_map({
729 let file_id = self.file_id;
730 move |parent| InFile::new(file_id, &parent).ancestors_with_macros(db)
735 impl<N: AstNode> InFile<N> {
736 pub fn descendants<T: AstNode>(self) -> impl Iterator<Item = InFile<T>> {
737 self.value.syntax().descendants().filter_map(T::cast).map(move |n| self.with_value(n))
740 pub fn original_ast_node(self, db: &dyn db::AstDatabase) -> Option<InFile<N>> {
741 // This kind of upmapping can only be achieved in attribute expanded files,
742 // as we don't have node inputs otherwise and therefor can't find an `N` node in the input
743 if !self.file_id.is_macro() {
745 } else if !self.file_id.is_attr_macro(db) {
749 if let Some(InFile { file_id, value: (first, last) }) =
750 ascend_node_border_tokens(db, self.syntax())
752 if file_id.is_macro() {
753 let range = first.text_range().cover(last.text_range());
754 tracing::error!("Failed mapping out of macro file for {:?}", range);
757 // FIXME: This heuristic is brittle and with the right macro may select completely unrelated nodes
758 let anc = algo::least_common_ancestor(&first.parent()?, &last.parent()?)?;
759 let value = anc.ancestors().find_map(N::cast)?;
760 return Some(InFile::new(file_id, value));
765 pub fn syntax(&self) -> InFile<&SyntaxNode> {
766 self.with_value(self.value.syntax())
770 /// In Rust, macros expand token trees to token trees. When we want to turn a
771 /// token tree into an AST node, we need to figure out what kind of AST node we
772 /// want: something like `foo` can be a type, an expression, or a pattern.
774 /// Naively, one would think that "what this expands to" is a property of a
775 /// particular macro: macro `m1` returns an item, while macro `m2` returns an
776 /// expression, etc. That's not the case -- macros are polymorphic in the
777 /// result, and can expand to any type of the AST node.
779 /// What defines the actual AST node is the syntactic context of the macro
780 /// invocation. As a contrived example, in `let T![*] = T![*];` the first `T`
781 /// expands to a pattern, while the second one expands to an expression.
783 /// `ExpandTo` captures this bit of information about a particular macro call
785 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
795 pub fn from_call_site(call: &ast::MacroCall) -> ExpandTo {
796 use syntax::SyntaxKind::*;
798 let syn = call.syntax();
800 let parent = match syn.parent() {
802 None => return ExpandTo::Statements,
805 match parent.kind() {
806 MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => ExpandTo::Items,
807 MACRO_STMTS | EXPR_STMT | STMT_LIST => ExpandTo::Statements,
808 MACRO_PAT => ExpandTo::Pattern,
809 MACRO_TYPE => ExpandTo::Type,
811 ARG_LIST | TRY_EXPR | TUPLE_EXPR | PAREN_EXPR | ARRAY_EXPR | FOR_EXPR | PATH_EXPR
812 | CLOSURE_EXPR | CONDITION | BREAK_EXPR | RETURN_EXPR | MATCH_EXPR | MATCH_ARM
813 | MATCH_GUARD | RECORD_EXPR_FIELD | CALL_EXPR | INDEX_EXPR | METHOD_CALL_EXPR
814 | FIELD_EXPR | AWAIT_EXPR | CAST_EXPR | REF_EXPR | PREFIX_EXPR | RANGE_EXPR
815 | BIN_EXPR => ExpandTo::Expr,
817 // FIXME: Handle LHS Pattern
822 // Unknown , Just guess it is `Items`
830 pub struct UnresolvedMacro {