1 use std::convert::TryInto;
4 use hir::{AsAssocItem, InFile, ModuleDef, Semantics};
6 base_db::{AnchoredPath, FileId, FileLoader},
7 defs::{Definition, NameClass, NameRefClass},
11 ast, match_ast, AstNode, AstToken, SyntaxKind::*, SyntaxToken, TextRange, TokenAtOffset, T,
16 doc_links::{doc_attributes, extract_definitions_from_markdown, resolve_doc_path_for_def},
17 FilePosition, NavigationTarget, RangeInfo,
20 // Feature: Go to Definition
22 // Navigates to the definition of an identifier.
25 // | Editor | Shortcut
27 // | VS Code | kbd:[F12]
30 // image::https://user-images.githubusercontent.com/48062697/113065563-025fbe00-91b1-11eb-83e4-a5a703610b23.gif[]
31 pub(crate) fn goto_definition(
33 position: FilePosition,
34 ) -> Option<RangeInfo<Vec<NavigationTarget>>> {
35 let sema = Semantics::new(db);
36 let file = sema.parse(position.file_id).syntax().clone();
37 let original_token = pick_best(file.token_at_offset(position.offset))?;
38 let token = sema.descend_into_macros(original_token.clone());
39 let parent = token.parent()?;
40 if let Some(_) = ast::Comment::cast(token.clone()) {
41 let (attributes, def) = doc_attributes(&sema, &parent)?;
43 let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
45 extract_definitions_from_markdown(docs.as_str()).into_iter().find(|(range, ..)| {
46 doc_mapping.map(range.clone()).map_or(false, |InFile { file_id, value: range }| {
47 file_id == position.file_id.into() && range.contains(position.offset)
50 let nav = resolve_doc_path_for_def(db, def, &link, ns)?.try_to_nav(db)?;
51 return Some(RangeInfo::new(original_token.text_range(), vec![nav]));
53 let nav = match_ast! {
55 ast::NameRef(name_ref) => {
56 reference_definition(&sema, Either::Right(&name_ref))
59 let def = NameClass::classify(&sema, &name)?.referenced_or_defined(sema.db);
60 try_find_trait_fn_definition(&sema.db, &def)
61 .or_else(|| def.try_to_nav(sema.db))
63 ast::Lifetime(lt) => if let Some(name_class) = NameClass::classify_lifetime(&sema, <) {
64 let def = name_class.referenced_or_defined(sema.db);
65 def.try_to_nav(sema.db)
67 reference_definition(&sema, Either::Left(<))
69 ast::TokenTree(tt) => try_lookup_include_path(sema.db, tt, token, position.file_id),
74 Some(RangeInfo::new(original_token.text_range(), nav.into_iter().collect()))
77 fn try_lookup_include_path(
82 ) -> Option<NavigationTarget> {
83 let path = ast::String::cast(token)?.value()?.into_owned();
84 let macro_call = tt.syntax().parent().and_then(ast::MacroCall::cast)?;
85 let name = macro_call.path()?.segment()?.name_ref()?;
86 if !matches!(&*name.text(), "include" | "include_str" | "include_bytes") {
89 let file_id = db.resolve_path(AnchoredPath { anchor: file_id, path: &path })?;
90 let size = db.file_text(file_id).len().try_into().ok()?;
91 Some(NavigationTarget {
93 full_range: TextRange::new(0.into(), size),
103 /// finds the trait definition of an impl'd function
106 /// trait A { fn a(); }
108 /// impl A for S { fn a(); } // <-- on this function, will get the location of a() in the trait
110 fn try_find_trait_fn_definition(db: &RootDatabase, def: &Definition) -> Option<NavigationTarget> {
112 Definition::ModuleDef(ModuleDef::Function(f)) => {
113 let name = def.name(db)?;
114 let assoc = f.as_assoc_item(db)?;
115 let imp = match assoc.container(db) {
116 hir::AssocItemContainer::Impl(imp) => imp,
119 let trait_ = imp.trait_(db)?;
123 .find_map(|itm| (itm.name(db)? == name).then(|| itm.try_to_nav(db)).flatten())
129 fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> {
130 return tokens.max_by_key(priority);
131 fn priority(n: &SyntaxToken) -> usize {
133 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | COMMENT => 2,
134 kind if kind.is_trivia() => 0,
140 pub(crate) fn reference_definition(
141 sema: &Semantics<RootDatabase>,
142 name_ref: Either<&ast::Lifetime, &ast::NameRef>,
143 ) -> Option<NavigationTarget> {
144 let name_kind = name_ref.either(
145 |lifetime| NameRefClass::classify_lifetime(sema, lifetime),
146 |name_ref| NameRefClass::classify(sema, name_ref),
148 let def = name_kind.referenced(sema.db);
149 def.try_to_nav(sema.db)
154 use ide_db::base_db::FileRange;
158 fn check(ra_fixture: &str) {
159 let (analysis, position, expected) = fixture::nav_target_annotation(ra_fixture);
161 analysis.goto_definition(position).unwrap().expect("no definition found").info;
163 panic!("unresolved reference")
165 assert_eq!(navs.len(), 1);
167 let nav = navs.pop().unwrap();
168 assert_eq!(expected, FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() });
171 fn check_unresolved(ra_fixture: &str) {
172 let (analysis, position) = fixture::position(ra_fixture);
173 let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info;
175 assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {:?}", navs)
179 fn goto_def_for_extern_crate() {
182 //- /main.rs crate:main deps:std
184 //- /std/lib.rs crate:std
192 fn goto_def_for_renamed_extern_crate() {
195 //- /main.rs crate:main deps:std
196 extern crate std as abc$0;
197 //- /std/lib.rs crate:std
205 fn goto_def_in_items() {
216 fn goto_def_at_start_of_item() {
227 fn goto_definition_resolves_correct_name() {
246 fn goto_def_for_module_declaration() {
271 fn goto_def_for_macros() {
274 macro_rules! foo { () => { () } }
284 fn goto_def_for_macros_from_other_crates() {
287 //- /lib.rs crate:main deps:foo
293 //- /foo/lib.rs crate:foo
295 macro_rules! foo { () => { () } }
302 fn goto_def_for_macros_in_use_tree() {
305 //- /lib.rs crate:main deps:foo
308 //- /foo/lib.rs crate:foo
310 macro_rules! foo { () => { () } }
317 fn goto_def_for_macro_defined_fn_with_arg() {
321 macro_rules! define_fn {
322 ($name:ident) => (fn $name() {})
336 fn goto_def_for_macro_defined_fn_no_arg() {
340 macro_rules! define_fn {
355 fn goto_definition_works_for_macro_inside_pattern() {
359 macro_rules! foo {() => {0}}
372 fn goto_definition_works_for_macro_inside_match_arm_lhs() {
376 macro_rules! foo {() => {0}}
388 fn goto_def_for_use_alias() {
391 //- /lib.rs crate:main deps:foo
394 //- /foo/lib.rs crate:foo
402 fn goto_def_for_use_alias_foo_macro() {
405 //- /lib.rs crate:main deps:foo
406 use foo::foo as bar$0;
408 //- /foo/lib.rs crate:foo
410 macro_rules! foo { () => { () } }
417 fn goto_def_for_methods() {
422 fn frobnicate(&self) { }
434 fn goto_def_for_fields() {
449 fn goto_def_for_record_fields() {
467 fn goto_def_for_record_pat_fields() {
475 fn bar(foo: Foo) -> Foo {
476 let Foo { spam$0: _, } = foo
483 fn goto_def_for_record_fields_macros() {
486 macro_rules! m { () => { 92 };}
487 struct Foo { spam: u32 }
498 fn goto_for_tuple_fields() {
513 fn goto_def_for_ufcs_inherent_methods() {
529 fn goto_def_for_ufcs_trait_methods_through_traits() {
544 fn goto_def_for_ufcs_trait_methods_through_self() {
551 impl Trait for Foo {}
561 fn goto_definition_on_self() {
567 pub fn new() -> Self {
578 pub fn new() -> Self$0 {
590 pub fn new() -> Self$0 {
602 pub fn thing(a: &Self$0) {
610 fn goto_definition_on_self_in_trait_impl() {
643 fn goto_def_when_used_on_definition_name_itself() {
646 struct Foo$0 { value: u32 }
668 enum Foo$0 { Variant }
686 static INNER$0: &str = "";
693 const INNER$0: &str = "";
700 type Thing$0 = Option<()>;
721 fn goto_from_macro() {
725 ($($tt:tt)*) => { $($tt)* }
734 mod confuse_index { fn foo(); }
740 fn goto_through_format() {
744 macro_rules! format {
745 ($($arg:tt)*) => ($crate::fmt::format($crate::__export::format_args!($($arg)*)))
747 #[rustc_builtin_macro]
749 macro_rules! format_args {
750 ($fmt:expr) => ({ /* compiler built-in */ });
751 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
754 pub use crate::format_args;
755 fn foo() {} // for index confusion
760 format!("{}", fo$0o())
767 fn goto_through_included_file() {
771 #[rustc_builtin_macro]
772 macro_rules! include {}
775 //^^^^^^^^^^^^^^^^^^^
792 fn goto_for_type_param() {
795 struct Foo<T: Clone> { t: $0T }
802 fn goto_within_macro() {
806 ($($tt:tt)*) => ($($tt)*)
823 ($($tt:tt)*) => ($($tt)*)
839 fn goto_def_in_local_fn() {
854 fn goto_def_in_local_macro() {
858 macro_rules! foo { () => { () } }
867 fn goto_def_for_field_init_shorthand() {
870 struct Foo { x: i32 }
881 fn goto_def_for_enum_variant_field() {
889 Foo::Bar { x$0 } => x
897 fn goto_def_for_enum_variant_self_pattern_const() {
904 match self { Self::Bar$0 => {} }
912 fn goto_def_for_enum_variant_self_pattern_record() {
915 enum Foo { Bar { val: i32 } }
918 fn baz(self) -> i32 {
919 match self { Self::Bar$0 { val } => {} }
927 fn goto_def_for_enum_variant_self_expr_const() {
933 fn baz(self) { Self::Bar$0; }
940 fn goto_def_for_enum_variant_self_expr_record() {
943 enum Foo { Bar { val: i32 } }
946 fn baz(self) { Self::Bar$0 {val: 4}; }
953 fn goto_def_for_type_alias_generic_parameter() {
963 fn goto_def_for_macro_container() {
966 //- /lib.rs crate:main deps:foo
967 foo::module$0::mac!();
969 //- /foo/lib.rs crate:foo
973 macro_rules! _mac { () => { () } }
974 pub use crate::_mac as mac;
981 fn goto_def_for_assoc_ty_in_path() {
989 fn f() -> impl Iterator<Item$0 = u8> {}
995 fn unknown_assoc_ty() {
998 trait Iterator { type Item; }
999 fn f() -> impl Iterator<Invalid$0 = u8> {}
1005 fn goto_def_for_assoc_ty_in_path_multiple() {
1014 fn f() -> impl Iterator<A$0 = u8, B = ()> {}
1025 fn f() -> impl Iterator<A = u8, B$0 = ()> {}
1031 fn goto_def_for_assoc_ty_ufcs() {
1039 fn g() -> <() as Iterator<Item$0 = ()>>::Item {}
1045 fn goto_def_for_assoc_ty_ufcs_multiple() {
1054 fn g() -> <() as Iterator<A$0 = (), B = u8>>::B {}
1065 fn g() -> <() as Iterator<A = (), B$0 = u8>>::A {}
1071 fn goto_self_param_ty_specified() {
1077 fn bar(self: &Foo) {
1086 fn goto_self_param_on_decl() {
1100 fn goto_lifetime_param_on_decl() {
1103 fn foo<'foobar$0>(_: &'foobar ()) {
1110 fn goto_lifetime_param_decl() {
1113 fn foo<'foobar>(_: &'foobar$0 ()) {
1120 fn goto_lifetime_param_decl_nested() {
1123 fn foo<'foobar>(_: &'foobar ()) {
1124 fn foo<'foobar>(_: &'foobar$0 ()) {}
1131 #[ignore] // requires the HIR to somehow track these hrtb lifetimes
1132 fn goto_lifetime_hrtb() {
1135 fn foo<T>() where for<'a> T: Foo<&'a$0 (u8, u16)>, {}
1141 fn foo<T>() where for<'a$0> T: Foo<&'a (u8, u16)>, {}
1148 #[ignore] // requires ForTypes to be implemented
1149 fn goto_lifetime_hrtb_for_type() {
1152 fn foo<T>() where T: for<'a> Foo<&'a$0 (u8, u16)>, {}
1162 fn foo<'foo>(_: &'foo ()) {
1174 fn goto_def_for_intra_doc_link_same_file() {
1177 /// Blah, [`bar`](bar) .. [`foo`](foo$0) has [`bar`](bar)
1180 /// You might want to see [`std::fs::read()`] too.
1189 fn goto_def_for_intra_doc_link_inner() {
1204 fn goto_incomplete_field() {
1209 fn foo() { A { a$0: }; }
1215 fn goto_proc_macro() {
1218 //- /main.rs crate:main deps:mac
1223 //- /mac.rs crate:mac
1232 fn goto_intra_doc_links() {
1237 /// This is the item. Cool!
1242 /// Gives you a [`TheItem$0`].
1244 /// [`TheItem`]: theitem::TheItem
1245 pub fn gimme() -> theitem::TheItem {
1253 fn goto_ident_from_pat_macro() {
1257 ($name:ident) => { Enum::Variant1($name) }
1271 Enum::Variant2 => {}
1284 let str = include_str!("foo.txt$0");
1294 fn goto_def_of_trait_impl_fn() {
1304 impl Twait for Stwuct {