]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/goto_definition.rs
Remove unnecessary to_nav_target
[rust.git] / crates / ra_ide_api / src / goto_definition.rs
1 use ra_db::{FileId, SourceDatabase};
2 use ra_syntax::{
3     AstNode, ast,
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     visitor()
140         .visit(|node: &ast::StructDef| NavigationTarget::from_named(file_id, node))
141         .visit(|node: &ast::EnumDef| NavigationTarget::from_named(file_id, node))
142         .visit(|node: &ast::EnumVariant| NavigationTarget::from_named(file_id, node))
143         .visit(|node: &ast::FnDef| NavigationTarget::from_named(file_id, node))
144         .visit(|node: &ast::TypeDef| NavigationTarget::from_named(file_id, node))
145         .visit(|node: &ast::ConstDef| NavigationTarget::from_named(file_id, node))
146         .visit(|node: &ast::StaticDef| NavigationTarget::from_named(file_id, node))
147         .visit(|node: &ast::TraitDef| NavigationTarget::from_named(file_id, node))
148         .visit(|node: &ast::NamedFieldDef| NavigationTarget::from_named(file_id, node))
149         .visit(|node: &ast::Module| NavigationTarget::from_named(file_id, node))
150         .accept(node)
151 }
152
153 #[cfg(test)]
154 mod tests {
155     use test_utils::covers;
156
157     use crate::mock_analysis::analysis_and_position;
158
159     fn check_goto(fixture: &str, expected: &str) {
160         let (analysis, pos) = analysis_and_position(fixture);
161
162         let mut navs = analysis.goto_definition(pos).unwrap().unwrap().info;
163         assert_eq!(navs.len(), 1);
164         let nav = navs.pop().unwrap();
165         nav.assert_match(expected);
166     }
167
168     #[test]
169     fn goto_definition_works_in_items() {
170         check_goto(
171             "
172             //- /lib.rs
173             struct Foo;
174             enum E { X(Foo<|>) }
175             ",
176             "Foo STRUCT_DEF FileId(1) [0; 11) [7; 10)",
177         );
178     }
179
180     #[test]
181     fn goto_definition_resolves_correct_name() {
182         check_goto(
183             "
184             //- /lib.rs
185             use a::Foo;
186             mod a;
187             mod b;
188             enum E { X(Foo<|>) }
189             //- /a.rs
190             struct Foo;
191             //- /b.rs
192             struct Foo;
193             ",
194             "Foo STRUCT_DEF FileId(2) [0; 11) [7; 10)",
195         );
196     }
197
198     #[test]
199     fn goto_definition_works_for_module_declaration() {
200         check_goto(
201             "
202             //- /lib.rs
203             mod <|>foo;
204             //- /foo.rs
205             // empty
206             ",
207             "foo SOURCE_FILE FileId(2) [0; 10)",
208         );
209
210         check_goto(
211             "
212             //- /lib.rs
213             mod <|>foo;
214             //- /foo/mod.rs
215             // empty
216             ",
217             "foo SOURCE_FILE FileId(2) [0; 10)",
218         );
219     }
220
221     #[test]
222     fn goto_definition_works_for_methods() {
223         covers!(goto_definition_works_for_methods);
224         check_goto(
225             "
226             //- /lib.rs
227             struct Foo;
228             impl Foo {
229                 fn frobnicate(&self) {  }
230             }
231
232             fn bar(foo: &Foo) {
233                 foo.frobnicate<|>();
234             }
235             ",
236             "frobnicate FN_DEF FileId(1) [27; 52) [30; 40)",
237         );
238     }
239
240     #[test]
241     fn goto_definition_works_for_fields() {
242         covers!(goto_definition_works_for_fields);
243         check_goto(
244             "
245             //- /lib.rs
246             struct Foo {
247                 spam: u32,
248             }
249
250             fn bar(foo: &Foo) {
251                 foo.spam<|>;
252             }
253             ",
254             "spam NAMED_FIELD_DEF FileId(1) [17; 26) [17; 21)",
255         );
256     }
257
258     #[test]
259     fn goto_definition_works_when_used_on_definition_name_itself() {
260         check_goto(
261             "
262             //- /lib.rs
263             struct Foo<|> { value: u32 }
264             ",
265             "Foo STRUCT_DEF FileId(1) [0; 25) [7; 10)",
266         );
267
268         check_goto(
269             r#"
270             //- /lib.rs
271             struct Foo {
272                 field<|>: string,
273             }
274             "#,
275             "field NAMED_FIELD_DEF FileId(1) [17; 30) [17; 22)",
276         );
277
278         check_goto(
279             "
280             //- /lib.rs
281             fn foo_test<|>() {
282             }
283             ",
284             "foo_test FN_DEF FileId(1) [0; 17) [3; 11)",
285         );
286
287         check_goto(
288             "
289             //- /lib.rs
290             enum Foo<|> {
291                 Variant,
292             }
293             ",
294             "Foo ENUM_DEF FileId(1) [0; 25) [5; 8)",
295         );
296
297         check_goto(
298             "
299             //- /lib.rs
300             enum Foo {
301                 Variant1,
302                 Variant2<|>,
303                 Variant3,
304             }
305             ",
306             "Variant2 ENUM_VARIANT FileId(1) [29; 37) [29; 37)",
307         );
308
309         check_goto(
310             r#"
311             //- /lib.rs
312             static inner<|>: &str = "";
313             "#,
314             "inner STATIC_DEF FileId(1) [0; 24) [7; 12)",
315         );
316
317         check_goto(
318             r#"
319             //- /lib.rs
320             const inner<|>: &str = "";
321             "#,
322             "inner CONST_DEF FileId(1) [0; 23) [6; 11)",
323         );
324
325         check_goto(
326             r#"
327             //- /lib.rs
328             type Thing<|> = Option<()>;
329             "#,
330             "Thing TYPE_DEF FileId(1) [0; 24) [5; 10)",
331         );
332
333         check_goto(
334             r#"
335             //- /lib.rs
336             trait Foo<|> {
337             }
338             "#,
339             "Foo TRAIT_DEF FileId(1) [0; 13) [6; 9)",
340         );
341
342         check_goto(
343             r#"
344             //- /lib.rs
345             mod bar<|> {
346             }
347             "#,
348             "bar MODULE FileId(1) [0; 11) [4; 7)",
349         );
350     }
351 }