]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/goto_definition.rs
a4ee77d94789efc5378cf4b93b0e8043fd8d742e
[rust.git] / crates / ra_ide_api / src / goto_definition.rs
1 use ra_db::{FileId, SourceDatabase};
2 use ra_syntax::{
3     AstNode, ast::{self, NameOwner},
4     algo::{find_node_at_offset, visit::{visitor, Visitor}},
5     SyntaxNode,
6 };
7 use test_utils::tested_by;
8 use hir::Resolution;
9
10 use crate::{FilePosition, NavigationTarget, db::RootDatabase, RangeInfo};
11
12 pub(crate) fn goto_definition(
13     db: &RootDatabase,
14     position: FilePosition,
15 ) -> Option<RangeInfo<Vec<NavigationTarget>>> {
16     let file = db.parse(position.file_id);
17     let syntax = file.syntax();
18     if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, position.offset) {
19         let navs = reference_definition(db, position.file_id, name_ref).to_vec();
20         return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec()));
21     }
22     if let Some(name) = find_node_at_offset::<ast::Name>(syntax, position.offset) {
23         let navs = name_definition(db, position.file_id, name)?;
24         return Some(RangeInfo::new(name.syntax().range(), navs));
25     }
26     None
27 }
28
29 pub(crate) enum ReferenceResult {
30     Exact(NavigationTarget),
31     Approximate(Vec<NavigationTarget>),
32 }
33
34 impl ReferenceResult {
35     fn to_vec(self) -> Vec<NavigationTarget> {
36         use self::ReferenceResult::*;
37         match self {
38             Exact(target) => vec![target],
39             Approximate(vec) => vec,
40         }
41     }
42 }
43
44 pub(crate) fn reference_definition(
45     db: &RootDatabase,
46     file_id: FileId,
47     name_ref: &ast::NameRef,
48 ) -> ReferenceResult {
49     use self::ReferenceResult::*;
50     if let Some(function) =
51         hir::source_binder::function_from_child_node(db, file_id, name_ref.syntax())
52     {
53         // Check if it is a method
54         if let Some(method_call) = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast) {
55             tested_by!(goto_definition_works_for_methods);
56             let infer_result = function.infer(db);
57             let syntax_mapping = function.body_syntax_mapping(db);
58             let expr = ast::Expr::cast(method_call.syntax()).unwrap();
59             if let Some(func) =
60                 syntax_mapping.node_expr(expr).and_then(|it| infer_result.method_resolution(it))
61             {
62                 return Exact(NavigationTarget::from_function(db, func));
63             };
64         }
65         // It could also be a field access
66         if let Some(field_expr) = name_ref.syntax().parent().and_then(ast::FieldExpr::cast) {
67             tested_by!(goto_definition_works_for_fields);
68             let infer_result = function.infer(db);
69             let syntax_mapping = function.body_syntax_mapping(db);
70             let expr = ast::Expr::cast(field_expr.syntax()).unwrap();
71             if let Some(field) =
72                 syntax_mapping.node_expr(expr).and_then(|it| infer_result.field_resolution(it))
73             {
74                 return Exact(NavigationTarget::from_field(db, field));
75             };
76         }
77     }
78     // Try name resolution
79     let resolver = hir::source_binder::resolver_for_node(db, file_id, name_ref.syntax());
80     if let Some(path) =
81         name_ref.syntax().ancestors().find_map(ast::Path::cast).and_then(hir::Path::from_ast)
82     {
83         let resolved = resolver.resolve_path(db, &path);
84         match resolved.clone().take_types().or_else(|| resolved.take_values()) {
85             Some(Resolution::Def(def)) => return Exact(NavigationTarget::from_def(db, def)),
86             Some(Resolution::LocalBinding(pat)) => {
87                 let body = resolver.body().expect("no body for local binding");
88                 let syntax_mapping = body.syntax_mapping(db);
89                 let ptr =
90                     syntax_mapping.pat_syntax(pat).expect("pattern not found in syntax mapping");
91                 let name =
92                     path.as_ident().cloned().expect("local binding from a multi-segment path");
93                 let nav = NavigationTarget::from_scope_entry(file_id, name, ptr);
94                 return Exact(nav);
95             }
96             Some(Resolution::GenericParam(..)) => {
97                 // TODO: go to the generic param def
98             }
99             Some(Resolution::SelfType(_impl_block)) => {
100                 // TODO: go to the implemented type
101             }
102             None => {}
103         }
104     }
105     // If that fails try the index based approach.
106     let navs = crate::symbol_index::index_resolve(db, name_ref)
107         .into_iter()
108         .map(NavigationTarget::from_symbol)
109         .collect();
110     Approximate(navs)
111 }
112
113 fn name_definition(
114     db: &RootDatabase,
115     file_id: FileId,
116     name: &ast::Name,
117 ) -> Option<Vec<NavigationTarget>> {
118     let parent = name.syntax().parent()?;
119
120     if let Some(module) = ast::Module::cast(&parent) {
121         if module.has_semi() {
122             if let Some(child_module) =
123                 hir::source_binder::module_from_declaration(db, file_id, module)
124             {
125                 let nav = NavigationTarget::from_module(db, child_module);
126                 return Some(vec![nav]);
127             }
128         }
129     }
130
131     if let Some(nav) = named_target(file_id, &parent) {
132         return Some(vec![nav]);
133     }
134
135     None
136 }
137
138 fn named_target(file_id: FileId, node: &SyntaxNode) -> Option<NavigationTarget> {
139     fn to_nav_target<N: NameOwner>(node: &N, file_id: FileId) -> Option<NavigationTarget> {
140         Some(NavigationTarget::from_named(file_id, node))
141     }
142
143     visitor()
144         .visit(|n: &ast::StructDef| to_nav_target(n, file_id))
145         .visit(|n: &ast::EnumDef| to_nav_target(n, file_id))
146         .visit(|n: &ast::EnumVariant| to_nav_target(n, file_id))
147         .visit(|n: &ast::FnDef| to_nav_target(n, file_id))
148         .visit(|n: &ast::TypeDef| to_nav_target(n, file_id))
149         .visit(|n: &ast::ConstDef| to_nav_target(n, file_id))
150         .visit(|n: &ast::StaticDef| to_nav_target(n, file_id))
151         .visit(|n: &ast::TraitDef| to_nav_target(n, file_id))
152         .visit(|n: &ast::NamedFieldDef| to_nav_target(n, file_id))
153         .visit(|n: &ast::Module| to_nav_target(n, file_id))
154         .accept(node)?
155 }
156
157 #[cfg(test)]
158 mod tests {
159     use test_utils::covers;
160
161     use crate::mock_analysis::analysis_and_position;
162
163     fn check_goto(fixture: &str, expected: &str) {
164         let (analysis, pos) = analysis_and_position(fixture);
165
166         let mut navs = analysis.goto_definition(pos).unwrap().unwrap().info;
167         assert_eq!(navs.len(), 1);
168         let nav = navs.pop().unwrap();
169         nav.assert_match(expected);
170     }
171
172     #[test]
173     fn goto_definition_works_in_items() {
174         check_goto(
175             "
176             //- /lib.rs
177             struct Foo;
178             enum E { X(Foo<|>) }
179             ",
180             "Foo STRUCT_DEF FileId(1) [0; 11) [7; 10)",
181         );
182     }
183
184     #[test]
185     fn goto_definition_resolves_correct_name() {
186         check_goto(
187             "
188             //- /lib.rs
189             use a::Foo;
190             mod a;
191             mod b;
192             enum E { X(Foo<|>) }
193             //- /a.rs
194             struct Foo;
195             //- /b.rs
196             struct Foo;
197             ",
198             "Foo STRUCT_DEF FileId(2) [0; 11) [7; 10)",
199         );
200     }
201
202     #[test]
203     fn goto_definition_works_for_module_declaration() {
204         check_goto(
205             "
206             //- /lib.rs
207             mod <|>foo;
208             //- /foo.rs
209             // empty
210             ",
211             "foo SOURCE_FILE FileId(2) [0; 10)",
212         );
213
214         check_goto(
215             "
216             //- /lib.rs
217             mod <|>foo;
218             //- /foo/mod.rs
219             // empty
220             ",
221             "foo SOURCE_FILE FileId(2) [0; 10)",
222         );
223     }
224
225     #[test]
226     fn goto_definition_works_for_methods() {
227         covers!(goto_definition_works_for_methods);
228         check_goto(
229             "
230             //- /lib.rs
231             struct Foo;
232             impl Foo {
233                 fn frobnicate(&self) {  }
234             }
235
236             fn bar(foo: &Foo) {
237                 foo.frobnicate<|>();
238             }
239             ",
240             "frobnicate FN_DEF FileId(1) [27; 52) [30; 40)",
241         );
242     }
243
244     #[test]
245     fn goto_definition_works_for_fields() {
246         covers!(goto_definition_works_for_fields);
247         check_goto(
248             "
249             //- /lib.rs
250             struct Foo {
251                 spam: u32,
252             }
253
254             fn bar(foo: &Foo) {
255                 foo.spam<|>;
256             }
257             ",
258             "spam NAMED_FIELD_DEF FileId(1) [17; 26) [17; 21)",
259         );
260     }
261
262     #[test]
263     fn goto_definition_works_when_used_on_definition_name_itself() {
264         check_goto(
265             "
266             //- /lib.rs
267             struct Foo<|> { value: u32 }
268             ",
269             "Foo STRUCT_DEF FileId(1) [0; 25) [7; 10)",
270         );
271
272         check_goto(
273             r#"
274             //- /lib.rs
275             struct Foo {
276                 field<|>: string,
277             }
278             "#,
279             "field NAMED_FIELD_DEF FileId(1) [17; 30) [17; 22)",
280         );
281
282         check_goto(
283             "
284             //- /lib.rs
285             fn foo_test<|>() {
286             }
287             ",
288             "foo_test FN_DEF FileId(1) [0; 17) [3; 11)",
289         );
290
291         check_goto(
292             "
293             //- /lib.rs
294             enum Foo<|> {
295                 Variant,
296             }
297             ",
298             "Foo ENUM_DEF FileId(1) [0; 25) [5; 8)",
299         );
300
301         check_goto(
302             "
303             //- /lib.rs
304             enum Foo {
305                 Variant1,
306                 Variant2<|>,
307                 Variant3,
308             }
309             ",
310             "Variant2 ENUM_VARIANT FileId(1) [29; 37) [29; 37)",
311         );
312
313         check_goto(
314             r#"
315             //- /lib.rs
316             static inner<|>: &str = "";
317             "#,
318             "inner STATIC_DEF FileId(1) [0; 24) [7; 12)",
319         );
320
321         check_goto(
322             r#"
323             //- /lib.rs
324             const inner<|>: &str = "";
325             "#,
326             "inner CONST_DEF FileId(1) [0; 23) [6; 11)",
327         );
328
329         check_goto(
330             r#"
331             //- /lib.rs
332             type Thing<|> = Option<()>;
333             "#,
334             "Thing TYPE_DEF FileId(1) [0; 24) [5; 10)",
335         );
336
337         check_goto(
338             r#"
339             //- /lib.rs
340             trait Foo<|> {
341             }
342             "#,
343             "Foo TRAIT_DEF FileId(1) [0; 13) [6; 9)",
344         );
345
346         check_goto(
347             r#"
348             //- /lib.rs
349             mod bar<|> {
350             }
351             "#,
352             "bar MODULE FileId(1) [0; 11) [4; 7)",
353         );
354     }
355 }