]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/dot.rs
Merge #9519
[rust.git] / crates / ide_completion / src / completions / dot.rs
1 //! Completes references after dot (fields and method calls).
2
3 use either::Either;
4 use hir::{HasVisibility, ScopeDef};
5 use rustc_hash::FxHashSet;
6
7 use crate::{context::CompletionContext, patterns::ImmediateLocation, Completions};
8
9 /// Complete dot accesses, i.e. fields or methods.
10 pub(crate) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
11     let dot_receiver = match ctx.dot_receiver() {
12         Some(expr) => expr,
13         _ => return complete_undotted_self(acc, ctx),
14     };
15
16     let receiver_ty = match ctx.sema.type_of_expr(dot_receiver) {
17         Some(ty) => ty,
18         _ => return,
19     };
20
21     if matches!(ctx.completion_location, Some(ImmediateLocation::MethodCall { .. })) {
22         cov_mark::hit!(test_no_struct_field_completion_for_method_call);
23     } else {
24         complete_fields(ctx, &receiver_ty, |field, ty| match field {
25             Either::Left(field) => acc.add_field(ctx, None, field, &ty),
26             Either::Right(tuple_idx) => acc.add_tuple_field(ctx, None, tuple_idx, &ty),
27         });
28     }
29     complete_methods(ctx, &receiver_ty, |func| acc.add_method(ctx, func, None, None));
30 }
31
32 fn complete_undotted_self(acc: &mut Completions, ctx: &CompletionContext) {
33     if !ctx.config.enable_self_on_the_fly {
34         return;
35     }
36     if !ctx.is_trivial_path() || ctx.is_path_disallowed() || !ctx.expects_expression() {
37         return;
38     }
39     ctx.scope.process_all_names(&mut |name, def| {
40         if let ScopeDef::Local(local) = &def {
41             if local.is_self(ctx.db) {
42                 let ty = local.ty(ctx.db);
43                 complete_fields(ctx, &ty, |field, ty| match field {
44                     either::Either::Left(field) => {
45                         acc.add_field(ctx, Some(name.clone()), field, &ty)
46                     }
47                     either::Either::Right(tuple_idx) => {
48                         acc.add_tuple_field(ctx, Some(name.clone()), tuple_idx, &ty)
49                     }
50                 });
51                 complete_methods(ctx, &ty, |func| {
52                     acc.add_method(ctx, func, Some(name.clone()), None)
53                 });
54             }
55         }
56     });
57 }
58
59 fn complete_fields(
60     ctx: &CompletionContext,
61     receiver: &hir::Type,
62     mut f: impl FnMut(Either<hir::Field, usize>, hir::Type),
63 ) {
64     for receiver in receiver.autoderef(ctx.db) {
65         for (field, ty) in receiver.fields(ctx.db) {
66             if ctx.scope.module().map_or(false, |m| !field.is_visible_from(ctx.db, m)) {
67                 // Skip private field. FIXME: If the definition location of the
68                 // field is editable, we should show the completion
69                 continue;
70             }
71             f(Either::Left(field), ty);
72         }
73         for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
74             // FIXME: Handle visibility
75             f(Either::Right(i), ty);
76         }
77     }
78 }
79
80 fn complete_methods(
81     ctx: &CompletionContext,
82     receiver: &hir::Type,
83     mut f: impl FnMut(hir::Function),
84 ) {
85     if let Some(krate) = ctx.krate {
86         let mut seen_methods = FxHashSet::default();
87         let traits_in_scope = ctx.scope.traits_in_scope();
88         receiver.iterate_method_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, func| {
89             if func.self_param(ctx.db).is_some()
90                 && ctx.scope.module().map_or(true, |m| func.is_visible_from(ctx.db, m))
91                 && seen_methods.insert(func.name(ctx.db))
92             {
93                 f(func);
94             }
95             None::<()>
96         });
97     }
98 }
99
100 #[cfg(test)]
101 mod tests {
102     use expect_test::{expect, Expect};
103
104     use crate::{
105         tests::{check_edit, filtered_completion_list},
106         CompletionKind,
107     };
108
109     fn check(ra_fixture: &str, expect: Expect) {
110         let actual = filtered_completion_list(ra_fixture, CompletionKind::Reference);
111         expect.assert_eq(&actual);
112     }
113
114     #[test]
115     fn test_struct_field_and_method_completion() {
116         check(
117             r#"
118 struct S { foo: u32 }
119 impl S {
120     fn bar(&self) {}
121 }
122 fn foo(s: S) { s.$0 }
123 "#,
124             expect![[r#"
125                 fd foo   u32
126                 me bar() fn(&self)
127             "#]],
128         );
129     }
130
131     #[test]
132     fn test_struct_field_completion_self() {
133         check(
134             r#"
135 struct S { the_field: (u32,) }
136 impl S {
137     fn foo(self) { self.$0 }
138 }
139 "#,
140             expect![[r#"
141                 fd the_field (u32,)
142                 me foo()     fn(self)
143             "#]],
144         )
145     }
146
147     #[test]
148     fn test_struct_field_completion_autoderef() {
149         check(
150             r#"
151 struct A { the_field: (u32, i32) }
152 impl A {
153     fn foo(&self) { self.$0 }
154 }
155 "#,
156             expect![[r#"
157                 fd the_field (u32, i32)
158                 me foo()     fn(&self)
159             "#]],
160         )
161     }
162
163     #[test]
164     fn test_no_struct_field_completion_for_method_call() {
165         cov_mark::check!(test_no_struct_field_completion_for_method_call);
166         check(
167             r#"
168 struct A { the_field: u32 }
169 fn foo(a: A) { a.$0() }
170 "#,
171             expect![[""]],
172         );
173     }
174
175     #[test]
176     fn test_visibility_filtering() {
177         check(
178             r#"
179 mod inner {
180     pub struct A {
181         private_field: u32,
182         pub pub_field: u32,
183         pub(crate) crate_field: u32,
184         pub(crate) super_field: u32,
185     }
186 }
187 fn foo(a: inner::A) { a.$0 }
188 "#,
189             expect![[r#"
190                 fd pub_field   u32
191                 fd crate_field u32
192                 fd super_field u32
193             "#]],
194         );
195
196         check(
197             r#"
198 struct A {}
199 mod m {
200     impl super::A {
201         fn private_method(&self) {}
202         pub(crate) fn the_method(&self) {}
203     }
204 }
205 fn foo(a: A) { a.$0 }
206 "#,
207             expect![[r#"
208                 me the_method() fn(&self)
209             "#]],
210         );
211     }
212
213     #[test]
214     fn test_union_field_completion() {
215         check(
216             r#"
217 union U { field: u8, other: u16 }
218 fn foo(u: U) { u.$0 }
219 "#,
220             expect![[r#"
221                 fd field u8
222                 fd other u16
223             "#]],
224         );
225     }
226
227     #[test]
228     fn test_method_completion_only_fitting_impls() {
229         check(
230             r#"
231 struct A<T> {}
232 impl A<u32> {
233     fn the_method(&self) {}
234 }
235 impl A<i32> {
236     fn the_other_method(&self) {}
237 }
238 fn foo(a: A<u32>) { a.$0 }
239 "#,
240             expect![[r#"
241                 me the_method() fn(&self)
242             "#]],
243         )
244     }
245
246     #[test]
247     fn test_trait_method_completion() {
248         check(
249             r#"
250 struct A {}
251 trait Trait { fn the_method(&self); }
252 impl Trait for A {}
253 fn foo(a: A) { a.$0 }
254 "#,
255             expect![[r#"
256                 me the_method() (as Trait) fn(&self)
257             "#]],
258         );
259         check_edit(
260             "the_method",
261             r#"
262 struct A {}
263 trait Trait { fn the_method(&self); }
264 impl Trait for A {}
265 fn foo(a: A) { a.$0 }
266 "#,
267             r#"
268 struct A {}
269 trait Trait { fn the_method(&self); }
270 impl Trait for A {}
271 fn foo(a: A) { a.the_method()$0 }
272 "#,
273         );
274     }
275
276     #[test]
277     fn test_trait_method_completion_deduplicated() {
278         check(
279             r"
280 struct A {}
281 trait Trait { fn the_method(&self); }
282 impl<T> Trait for T {}
283 fn foo(a: &A) { a.$0 }
284 ",
285             expect![[r#"
286                 me the_method() (as Trait) fn(&self)
287             "#]],
288         );
289     }
290
291     #[test]
292     fn completes_trait_method_from_other_module() {
293         check(
294             r"
295 struct A {}
296 mod m {
297     pub trait Trait { fn the_method(&self); }
298 }
299 use m::Trait;
300 impl Trait for A {}
301 fn foo(a: A) { a.$0 }
302 ",
303             expect![[r#"
304                 me the_method() (as Trait) fn(&self)
305             "#]],
306         );
307     }
308
309     #[test]
310     fn test_no_non_self_method() {
311         check(
312             r#"
313 struct A {}
314 impl A {
315     fn the_method() {}
316 }
317 fn foo(a: A) {
318    a.$0
319 }
320 "#,
321             expect![[""]],
322         );
323     }
324
325     #[test]
326     fn test_tuple_field_completion() {
327         check(
328             r#"
329 fn foo() {
330    let b = (0, 3.14);
331    b.$0
332 }
333 "#,
334             expect![[r#"
335                 fd 0 i32
336                 fd 1 f64
337             "#]],
338         )
339     }
340
341     #[test]
342     fn test_tuple_field_inference() {
343         check(
344             r#"
345 pub struct S;
346 impl S { pub fn blah(&self) {} }
347
348 struct T(S);
349
350 impl T {
351     fn foo(&self) {
352         // FIXME: This doesn't work without the trailing `a` as `0.` is a float
353         self.0.a$0
354     }
355 }
356 "#,
357             expect![[r#"
358                 me blah() fn(&self)
359             "#]],
360         );
361     }
362
363     #[test]
364     fn test_completion_works_in_consts() {
365         check(
366             r#"
367 struct A { the_field: u32 }
368 const X: u32 = {
369     A { the_field: 92 }.$0
370 };
371 "#,
372             expect![[r#"
373                 fd the_field u32
374             "#]],
375         );
376     }
377
378     #[test]
379     fn works_in_simple_macro_1() {
380         check(
381             r#"
382 macro_rules! m { ($e:expr) => { $e } }
383 struct A { the_field: u32 }
384 fn foo(a: A) {
385     m!(a.x$0)
386 }
387 "#,
388             expect![[r#"
389                 fd the_field u32
390             "#]],
391         );
392     }
393
394     #[test]
395     fn works_in_simple_macro_2() {
396         // this doesn't work yet because the macro doesn't expand without the token -- maybe it can be fixed with better recovery
397         check(
398             r#"
399 macro_rules! m { ($e:expr) => { $e } }
400 struct A { the_field: u32 }
401 fn foo(a: A) {
402     m!(a.$0)
403 }
404 "#,
405             expect![[r#"
406                 fd the_field u32
407             "#]],
408         );
409     }
410
411     #[test]
412     fn works_in_simple_macro_recursive_1() {
413         check(
414             r#"
415 macro_rules! m { ($e:expr) => { $e } }
416 struct A { the_field: u32 }
417 fn foo(a: A) {
418     m!(m!(m!(a.x$0)))
419 }
420 "#,
421             expect![[r#"
422                 fd the_field u32
423             "#]],
424         );
425     }
426
427     #[test]
428     fn macro_expansion_resilient() {
429         check(
430             r#"
431 macro_rules! d {
432     () => {};
433     ($val:expr) => {
434         match $val { tmp => { tmp } }
435     };
436     // Trailing comma with single argument is ignored
437     ($val:expr,) => { $crate::d!($val) };
438     ($($val:expr),+ $(,)?) => {
439         ($($crate::d!($val)),+,)
440     };
441 }
442 struct A { the_field: u32 }
443 fn foo(a: A) {
444     d!(a.$0)
445 }
446 "#,
447             expect![[r#"
448                 fd the_field u32
449             "#]],
450         );
451     }
452
453     #[test]
454     fn test_method_completion_issue_3547() {
455         check(
456             r#"
457 struct HashSet<T> {}
458 impl<T> HashSet<T> {
459     pub fn the_method(&self) {}
460 }
461 fn foo() {
462     let s: HashSet<_>;
463     s.$0
464 }
465 "#,
466             expect![[r#"
467                 me the_method() fn(&self)
468             "#]],
469         );
470     }
471
472     #[test]
473     fn completes_method_call_when_receiver_is_a_macro_call() {
474         check(
475             r#"
476 struct S;
477 impl S { fn foo(&self) {} }
478 macro_rules! make_s { () => { S }; }
479 fn main() { make_s!().f$0; }
480 "#,
481             expect![[r#"
482                 me foo() fn(&self)
483             "#]],
484         )
485     }
486
487     #[test]
488     fn completes_after_macro_call_in_submodule() {
489         check(
490             r#"
491 macro_rules! empty {
492     () => {};
493 }
494
495 mod foo {
496     #[derive(Debug, Default)]
497     struct Template2 {}
498
499     impl Template2 {
500         fn private(&self) {}
501     }
502     fn baz() {
503         let goo: Template2 = Template2 {};
504         empty!();
505         goo.$0
506     }
507 }
508         "#,
509             expect![[r#"
510                 me private() fn(&self)
511             "#]],
512         );
513     }
514
515     #[test]
516     fn issue_8931() {
517         check(
518             r#"
519 //- minicore: fn
520 struct S;
521
522 struct Foo;
523 impl Foo {
524     fn foo(&self) -> &[u8] { loop {} }
525 }
526
527 impl S {
528     fn indented(&mut self, f: impl FnOnce(&mut Self)) {
529     }
530
531     fn f(&mut self, v: Foo) {
532         self.indented(|this| v.$0)
533     }
534 }
535         "#,
536             expect![[r#"
537                 me foo() fn(&self) -> &[u8]
538             "#]],
539         );
540     }
541
542     #[test]
543     fn completes_bare_fields_and_methods_in_methods() {
544         check(
545             r#"
546 struct Foo { field: i32 }
547
548 impl Foo { fn foo(&self) { $0 } }"#,
549             expect![[r#"
550                 lc self       &Foo
551                 sp Self
552                 st Foo
553                 fd self.field i32
554                 me self.foo() fn(&self)
555             "#]],
556         );
557         check(
558             r#"
559 struct Foo(i32);
560
561 impl Foo { fn foo(&mut self) { $0 } }"#,
562             expect![[r#"
563                 lc self       &mut Foo
564                 sp Self
565                 st Foo
566                 fd self.0     i32
567                 me self.foo() fn(&mut self)
568             "#]],
569         );
570     }
571 }