]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/goto_definition.rs
Merge #646
[rust.git] / crates / ra_ide_api / src / goto_definition.rs
1 use ra_db::{FileId, SyntaxDatabase};
2 use ra_syntax::{
3     AstNode, ast,
4     algo::find_node_at_offset,
5 };
6 use test_utils::tested_by;
7
8 use crate::{FilePosition, NavigationTarget, db::RootDatabase, RangeInfo};
9
10 pub(crate) fn goto_definition(
11     db: &RootDatabase,
12     position: FilePosition,
13 ) -> Option<RangeInfo<Vec<NavigationTarget>>> {
14     let file = db.source_file(position.file_id);
15     let syntax = file.syntax();
16     if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, position.offset) {
17         let navs = reference_definition(db, position.file_id, name_ref).to_vec();
18         return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec()));
19     }
20     if let Some(name) = find_node_at_offset::<ast::Name>(syntax, position.offset) {
21         let navs = name_definition(db, position.file_id, name)?;
22         return Some(RangeInfo::new(name.syntax().range(), navs));
23     }
24     None
25 }
26
27 pub(crate) enum ReferenceResult {
28     Exact(NavigationTarget),
29     Approximate(Vec<NavigationTarget>),
30 }
31
32 impl ReferenceResult {
33     fn to_vec(self) -> Vec<NavigationTarget> {
34         use self::ReferenceResult::*;
35         match self {
36             Exact(target) => vec![target],
37             Approximate(vec) => vec,
38         }
39     }
40 }
41
42 pub(crate) fn reference_definition(
43     db: &RootDatabase,
44     file_id: FileId,
45     name_ref: &ast::NameRef,
46 ) -> ReferenceResult {
47     use self::ReferenceResult::*;
48     if let Some(function) =
49         hir::source_binder::function_from_child_node(db, file_id, name_ref.syntax())
50     {
51         let scope = function.scopes(db);
52         // First try to resolve the symbol locally
53         if let Some(entry) = scope.resolve_local_name(name_ref) {
54             let nav = NavigationTarget::from_scope_entry(file_id, &entry);
55             return Exact(nav);
56         };
57
58         // Next check if it is a method
59         if let Some(method_call) = name_ref
60             .syntax()
61             .parent()
62             .and_then(ast::MethodCallExpr::cast)
63         {
64             tested_by!(goto_definition_works_for_methods);
65             let infer_result = function.infer(db);
66             let syntax_mapping = function.body_syntax_mapping(db);
67             let expr = ast::Expr::cast(method_call.syntax()).unwrap();
68             if let Some(func) = syntax_mapping
69                 .node_expr(expr)
70                 .and_then(|it| infer_result.method_resolution(it))
71             {
72                 return Exact(NavigationTarget::from_function(db, func));
73             };
74         }
75         // It could also be a field access
76         if let Some(field_expr) = name_ref.syntax().parent().and_then(ast::FieldExpr::cast) {
77             tested_by!(goto_definition_works_for_fields);
78             let infer_result = function.infer(db);
79             let syntax_mapping = function.body_syntax_mapping(db);
80             let expr = ast::Expr::cast(field_expr.syntax()).unwrap();
81             if let Some(field) = syntax_mapping
82                 .node_expr(expr)
83                 .and_then(|it| infer_result.field_resolution(it))
84             {
85                 return Exact(NavigationTarget::from_field(db, field));
86             };
87         }
88     }
89     // Then try module name resolution
90     if let Some(module) = hir::source_binder::module_from_child_node(db, file_id, name_ref.syntax())
91     {
92         if let Some(path) = name_ref
93             .syntax()
94             .ancestors()
95             .find_map(ast::Path::cast)
96             .and_then(hir::Path::from_ast)
97         {
98             let resolved = module.resolve_path(db, &path);
99             if let Some(def_id) = resolved.take_types().or(resolved.take_values()) {
100                 if let Some(target) = NavigationTarget::from_def(db, def_id) {
101                     return Exact(target);
102                 }
103             }
104         }
105     }
106     // If that fails try the index based approach.
107     let navs = db
108         .index_resolve(name_ref)
109         .into_iter()
110         .map(NavigationTarget::from_symbol)
111         .collect();
112     Approximate(navs)
113 }
114
115 fn name_definition(
116     db: &RootDatabase,
117     file_id: FileId,
118     name: &ast::Name,
119 ) -> Option<Vec<NavigationTarget>> {
120     if let Some(module) = name.syntax().parent().and_then(ast::Module::cast) {
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     None
131 }
132
133 #[cfg(test)]
134 mod tests {
135     use test_utils::covers;
136
137     use crate::mock_analysis::analysis_and_position;
138
139     fn check_goto(fixuture: &str, expected: &str) {
140         let (analysis, pos) = analysis_and_position(fixuture);
141
142         let mut navs = analysis.goto_definition(pos).unwrap().unwrap().info;
143         assert_eq!(navs.len(), 1);
144         let nav = navs.pop().unwrap();
145         nav.assert_match(expected);
146     }
147
148     #[test]
149     fn goto_definition_works_in_items() {
150         check_goto(
151             "
152             //- /lib.rs
153             struct Foo;
154             enum E { X(Foo<|>) }
155             ",
156             "Foo STRUCT_DEF FileId(1) [0; 11) [7; 10)",
157         );
158     }
159
160     #[test]
161     fn goto_definition_resolves_correct_name() {
162         check_goto(
163             "
164             //- /lib.rs
165             use a::Foo;
166             mod a;
167             mod b;
168             enum E { X(Foo<|>) }
169             //- /a.rs
170             struct Foo;
171             //- /b.rs
172             struct Foo;
173             ",
174             "Foo STRUCT_DEF FileId(2) [0; 11) [7; 10)",
175         );
176     }
177
178     #[test]
179     fn goto_definition_works_for_module_declaration() {
180         check_goto(
181             "
182             //- /lib.rs
183             mod <|>foo;
184             //- /foo.rs
185             // empty
186             ",
187             "foo SOURCE_FILE FileId(2) [0; 10)",
188         );
189
190         check_goto(
191             "
192             //- /lib.rs
193             mod <|>foo;
194             //- /foo/mod.rs
195             // empty
196             ",
197             "foo SOURCE_FILE FileId(2) [0; 10)",
198         );
199     }
200
201     #[test]
202     fn goto_definition_works_for_methods() {
203         covers!(goto_definition_works_for_methods);
204         check_goto(
205             "
206             //- /lib.rs
207             struct Foo;
208             impl Foo {
209                 fn frobnicate(&self) {  }
210             }
211
212             fn bar(foo: &Foo) {
213                 foo.frobnicate<|>();
214             }
215             ",
216             "frobnicate FN_DEF FileId(1) [27; 52) [30; 40)",
217         );
218     }
219
220     #[test]
221     fn goto_definition_works_for_fields() {
222         covers!(goto_definition_works_for_fields);
223         check_goto(
224             "
225             //- /lib.rs
226             struct Foo {
227                 spam: u32,
228             }
229
230             fn bar(foo: &Foo) {
231                 foo.spam<|>;
232             }
233             ",
234             "spam NAMED_FIELD_DEF FileId(1) [17; 26) [17; 21)",
235         );
236     }
237 }