Skip to content

Commit 3b8801c

Browse files
committedDec 16, 2023
Go to definition for macros in #[macro_use(...)]
1 parent 0e49024 commit 3b8801c

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed
 

‎crates/ide/src/goto_definition.rs

+70-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{
44
doc_links::token_as_doc_comment, navigation_target::ToNav, FilePosition, NavigationTarget,
55
RangeInfo, TryToNav,
66
};
7-
use hir::{AsAssocItem, AssocItem, DescendPreference, Semantics};
7+
use hir::{AsAssocItem, AssocItem, DescendPreference, ModuleDef, Semantics};
88
use ide_db::{
99
base_db::{AnchoredPath, FileId, FileLoader},
1010
defs::{Definition, IdentClass},
@@ -73,10 +73,15 @@ pub(crate) fn goto_definition(
7373
.into_iter()
7474
.filter_map(|token| {
7575
let parent = token.parent()?;
76+
7677
if let Some(tt) = ast::TokenTree::cast(parent.clone()) {
7778
if let Some(x) = try_lookup_include_path(sema, tt, token.clone(), file_id) {
7879
return Some(vec![x]);
7980
}
81+
82+
if let Some(x) = try_lookup_macro_def_in_macro_use(sema, token.clone()) {
83+
return Some(vec![x]);
84+
}
8085
}
8186
Some(
8287
IdentClass::classify_node(sema, &parent)?
@@ -140,6 +145,27 @@ fn try_lookup_include_path(
140145
})
141146
}
142147

148+
fn try_lookup_macro_def_in_macro_use(
149+
sema: &Semantics<'_, RootDatabase>,
150+
token: SyntaxToken,
151+
) -> Option<NavigationTarget> {
152+
let extern_crate = token.parent()?.ancestors().find_map(ast::ExternCrate::cast)?;
153+
let extern_crate = sema.to_def(&extern_crate)?;
154+
let krate = extern_crate.resolved_crate(sema.db)?;
155+
156+
for mod_def in krate.root_module().declarations(sema.db) {
157+
if let ModuleDef::Macro(mac) = mod_def {
158+
if mac.name(sema.db).as_str() == Some(token.text()) {
159+
if let Some(nav) = mac.try_to_nav(sema.db) {
160+
return Some(nav.call_site);
161+
}
162+
}
163+
}
164+
}
165+
166+
None
167+
}
168+
143169
/// finds the trait definition of an impl'd item, except function
144170
/// e.g.
145171
/// ```rust
@@ -2081,4 +2107,47 @@ fn test() {
20812107
"#,
20822108
);
20832109
}
2110+
2111+
#[test]
2112+
fn goto_macro_def_from_macro_use() {
2113+
check(
2114+
r#"
2115+
//- /main.rs crate:main deps:mac
2116+
#[macro_use(foo$0)]
2117+
extern crate mac;
2118+
2119+
//- /mac.rs crate:mac
2120+
#[macro_export]
2121+
macro_rules! foo {
2122+
//^^^
2123+
() => {};
2124+
}
2125+
"#,
2126+
);
2127+
2128+
check(
2129+
r#"
2130+
//- /main.rs crate:main deps:mac
2131+
#[macro_use(foo, bar$0, baz)]
2132+
extern crate mac;
2133+
2134+
//- /mac.rs crate:mac
2135+
#[macro_export]
2136+
macro_rules! foo {
2137+
() => {};
2138+
}
2139+
2140+
#[macro_export]
2141+
macro_rules! bar {
2142+
//^^^
2143+
() => {};
2144+
}
2145+
2146+
#[macro_export]
2147+
macro_rules! baz {
2148+
() => {};
2149+
}
2150+
"#,
2151+
);
2152+
}
20842153
}

0 commit comments

Comments
 (0)
Please sign in to comment.