]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-completion/src/completions/dot.rs
Merge commit 'b52fb5234cd7c11ecfae51897a6f7fa52e8777fc' into clippyup
[rust.git] / src / tools / rust-analyzer / crates / ide-completion / src / completions / dot.rs
1 //! Completes references after dot (fields and method calls).
2
3 use ide_db::FxHashSet;
4
5 use crate::{
6     context::{CompletionContext, DotAccess, DotAccessKind, ExprCtx, PathCompletionCtx, Qualified},
7     CompletionItem, CompletionItemKind, Completions,
8 };
9
10 /// Complete dot accesses, i.e. fields or methods.
11 pub(crate) fn complete_dot(
12     acc: &mut Completions,
13     ctx: &CompletionContext<'_>,
14     dot_access: &DotAccess,
15 ) {
16     let receiver_ty = match dot_access {
17         DotAccess { receiver_ty: Some(receiver_ty), .. } => &receiver_ty.original,
18         _ => return,
19     };
20
21     // Suggest .await syntax for types that implement Future trait
22     if receiver_ty.impls_into_future(ctx.db) {
23         let mut item =
24             CompletionItem::new(CompletionItemKind::Keyword, ctx.source_range(), "await");
25         item.detail("expr.await");
26         item.add_to(acc);
27     }
28
29     if let DotAccessKind::Method { .. } = dot_access.kind {
30         cov_mark::hit!(test_no_struct_field_completion_for_method_call);
31     } else {
32         complete_fields(
33             acc,
34             ctx,
35             &receiver_ty,
36             |acc, field, ty| acc.add_field(ctx, dot_access, None, field, &ty),
37             |acc, field, ty| acc.add_tuple_field(ctx, None, field, &ty),
38         );
39     }
40     complete_methods(ctx, &receiver_ty, |func| acc.add_method(ctx, dot_access, func, None, None));
41 }
42
43 pub(crate) fn complete_undotted_self(
44     acc: &mut Completions,
45     ctx: &CompletionContext<'_>,
46     path_ctx: &PathCompletionCtx,
47     expr_ctx: &ExprCtx,
48 ) {
49     if !ctx.config.enable_self_on_the_fly {
50         return;
51     }
52     if !path_ctx.is_trivial_path() {
53         return;
54     }
55     if !ctx.qualifier_ctx.none() {
56         return;
57     }
58     if !matches!(path_ctx.qualified, Qualified::No) {
59         return;
60     }
61     let self_param = match expr_ctx {
62         ExprCtx { self_param: Some(self_param), .. } => self_param,
63         _ => return,
64     };
65
66     let ty = self_param.ty(ctx.db);
67     complete_fields(
68         acc,
69         ctx,
70         &ty,
71         |acc, field, ty| {
72             acc.add_field(
73                 ctx,
74                 &DotAccess {
75                     receiver: None,
76                     receiver_ty: None,
77                     kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal: false },
78                 },
79                 Some(hir::known::SELF_PARAM),
80                 field,
81                 &ty,
82             )
83         },
84         |acc, field, ty| acc.add_tuple_field(ctx, Some(hir::known::SELF_PARAM), field, &ty),
85     );
86     complete_methods(ctx, &ty, |func| {
87         acc.add_method(
88             ctx,
89             &DotAccess {
90                 receiver: None,
91                 receiver_ty: None,
92                 kind: DotAccessKind::Method { has_parens: false },
93             },
94             func,
95             Some(hir::known::SELF_PARAM),
96             None,
97         )
98     });
99 }
100
101 fn complete_fields(
102     acc: &mut Completions,
103     ctx: &CompletionContext<'_>,
104     receiver: &hir::Type,
105     mut named_field: impl FnMut(&mut Completions, hir::Field, hir::Type),
106     mut tuple_index: impl FnMut(&mut Completions, usize, hir::Type),
107 ) {
108     for receiver in receiver.autoderef(ctx.db) {
109         for (field, ty) in receiver.fields(ctx.db) {
110             named_field(acc, field, ty);
111         }
112         for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
113             // Tuple fields are always public (tuple struct fields are handled above).
114             tuple_index(acc, i, ty);
115         }
116     }
117 }
118
119 fn complete_methods(
120     ctx: &CompletionContext<'_>,
121     receiver: &hir::Type,
122     mut f: impl FnMut(hir::Function),
123 ) {
124     let mut seen_methods = FxHashSet::default();
125     receiver.iterate_method_candidates(
126         ctx.db,
127         &ctx.scope,
128         &ctx.traits_in_scope(),
129         Some(ctx.module),
130         None,
131         |func| {
132             if func.self_param(ctx.db).is_some() && seen_methods.insert(func.name(ctx.db)) {
133                 f(func);
134             }
135             None::<()>
136         },
137     );
138 }
139
140 #[cfg(test)]
141 mod tests {
142     use expect_test::{expect, Expect};
143
144     use crate::tests::{
145         check_edit, completion_list_no_kw, completion_list_no_kw_with_private_editable,
146     };
147
148     fn check(ra_fixture: &str, expect: Expect) {
149         let actual = completion_list_no_kw(ra_fixture);
150         expect.assert_eq(&actual);
151     }
152
153     fn check_with_private_editable(ra_fixture: &str, expect: Expect) {
154         let actual = completion_list_no_kw_with_private_editable(ra_fixture);
155         expect.assert_eq(&actual);
156     }
157
158     #[test]
159     fn test_struct_field_and_method_completion() {
160         check(
161             r#"
162 struct S { foo: u32 }
163 impl S {
164     fn bar(&self) {}
165 }
166 fn foo(s: S) { s.$0 }
167 "#,
168             expect![[r#"
169                 fd foo   u32
170                 me bar() fn(&self)
171             "#]],
172         );
173     }
174
175     #[test]
176     fn test_struct_field_completion_self() {
177         check(
178             r#"
179 struct S { the_field: (u32,) }
180 impl S {
181     fn foo(self) { self.$0 }
182 }
183 "#,
184             expect![[r#"
185                 fd the_field (u32,)
186                 me foo()     fn(self)
187             "#]],
188         )
189     }
190
191     #[test]
192     fn test_struct_field_completion_autoderef() {
193         check(
194             r#"
195 struct A { the_field: (u32, i32) }
196 impl A {
197     fn foo(&self) { self.$0 }
198 }
199 "#,
200             expect![[r#"
201                 fd the_field (u32, i32)
202                 me foo()     fn(&self)
203             "#]],
204         )
205     }
206
207     #[test]
208     fn test_no_struct_field_completion_for_method_call() {
209         cov_mark::check!(test_no_struct_field_completion_for_method_call);
210         check(
211             r#"
212 struct A { the_field: u32 }
213 fn foo(a: A) { a.$0() }
214 "#,
215             expect![[r#""#]],
216         );
217     }
218
219     #[test]
220     fn test_visibility_filtering() {
221         check(
222             r#"
223 //- /lib.rs crate:lib new_source_root:local
224 pub mod m {
225     pub struct A {
226         private_field: u32,
227         pub pub_field: u32,
228         pub(crate) crate_field: u32,
229         pub(super) super_field: u32,
230     }
231 }
232 //- /main.rs crate:main deps:lib new_source_root:local
233 fn foo(a: lib::m::A) { a.$0 }
234 "#,
235             expect![[r#"
236                 fd pub_field u32
237             "#]],
238         );
239
240         check(
241             r#"
242 //- /lib.rs crate:lib new_source_root:library
243 pub mod m {
244     pub struct A {
245         private_field: u32,
246         pub pub_field: u32,
247         pub(crate) crate_field: u32,
248         pub(super) super_field: u32,
249     }
250 }
251 //- /main.rs crate:main deps:lib new_source_root:local
252 fn foo(a: lib::m::A) { a.$0 }
253 "#,
254             expect![[r#"
255                 fd pub_field u32
256             "#]],
257         );
258
259         check(
260             r#"
261 //- /lib.rs crate:lib new_source_root:library
262 pub mod m {
263     pub struct A(
264         i32,
265         pub f64,
266     );
267 }
268 //- /main.rs crate:main deps:lib new_source_root:local
269 fn foo(a: lib::m::A) { a.$0 }
270 "#,
271             expect![[r#"
272                 fd 1 f64
273             "#]],
274         );
275
276         check(
277             r#"
278 //- /lib.rs crate:lib new_source_root:local
279 pub struct A {}
280 mod m {
281     impl super::A {
282         fn private_method(&self) {}
283         pub(crate) fn crate_method(&self) {}
284         pub fn pub_method(&self) {}
285     }
286 }
287 //- /main.rs crate:main deps:lib new_source_root:local
288 fn foo(a: lib::A) { a.$0 }
289 "#,
290             expect![[r#"
291                 me pub_method() fn(&self)
292             "#]],
293         );
294         check(
295             r#"
296 //- /lib.rs crate:lib new_source_root:library
297 pub struct A {}
298 mod m {
299     impl super::A {
300         fn private_method(&self) {}
301         pub(crate) fn crate_method(&self) {}
302         pub fn pub_method(&self) {}
303     }
304 }
305 //- /main.rs crate:main deps:lib new_source_root:local
306 fn foo(a: lib::A) { a.$0 }
307 "#,
308             expect![[r#"
309                 me pub_method() fn(&self)
310             "#]],
311         );
312     }
313
314     #[test]
315     fn test_visibility_filtering_with_private_editable_enabled() {
316         check_with_private_editable(
317             r#"
318 //- /lib.rs crate:lib new_source_root:local
319 pub mod m {
320     pub struct A {
321         private_field: u32,
322         pub pub_field: u32,
323         pub(crate) crate_field: u32,
324         pub(super) super_field: u32,
325     }
326 }
327 //- /main.rs crate:main deps:lib new_source_root:local
328 fn foo(a: lib::m::A) { a.$0 }
329 "#,
330             expect![[r#"
331                 fd crate_field   u32
332                 fd private_field u32
333                 fd pub_field     u32
334                 fd super_field   u32
335             "#]],
336         );
337
338         check_with_private_editable(
339             r#"
340 //- /lib.rs crate:lib new_source_root:library
341 pub mod m {
342     pub struct A {
343         private_field: u32,
344         pub pub_field: u32,
345         pub(crate) crate_field: u32,
346         pub(super) super_field: u32,
347     }
348 }
349 //- /main.rs crate:main deps:lib new_source_root:local
350 fn foo(a: lib::m::A) { a.$0 }
351 "#,
352             expect![[r#"
353                 fd pub_field u32
354             "#]],
355         );
356
357         check_with_private_editable(
358             r#"
359 //- /lib.rs crate:lib new_source_root:library
360 pub mod m {
361     pub struct A(
362         i32,
363         pub f64,
364     );
365 }
366 //- /main.rs crate:main deps:lib new_source_root:local
367 fn foo(a: lib::m::A) { a.$0 }
368 "#,
369             expect![[r#"
370                 fd 1 f64
371             "#]],
372         );
373
374         check_with_private_editable(
375             r#"
376 //- /lib.rs crate:lib new_source_root:local
377 pub struct A {}
378 mod m {
379     impl super::A {
380         fn private_method(&self) {}
381         pub(crate) fn crate_method(&self) {}
382         pub fn pub_method(&self) {}
383     }
384 }
385 //- /main.rs crate:main deps:lib new_source_root:local
386 fn foo(a: lib::A) { a.$0 }
387 "#,
388             expect![[r#"
389                 me crate_method()   fn(&self)
390                 me private_method() fn(&self)
391                 me pub_method()     fn(&self)
392             "#]],
393         );
394         check_with_private_editable(
395             r#"
396 //- /lib.rs crate:lib new_source_root:library
397 pub struct A {}
398 mod m {
399     impl super::A {
400         fn private_method(&self) {}
401         pub(crate) fn crate_method(&self) {}
402         pub fn pub_method(&self) {}
403     }
404 }
405 //- /main.rs crate:main deps:lib new_source_root:local
406 fn foo(a: lib::A) { a.$0 }
407 "#,
408             expect![[r#"
409                 me pub_method() fn(&self)
410             "#]],
411         );
412     }
413
414     #[test]
415     fn test_local_impls() {
416         check(
417             r#"
418 //- /lib.rs crate:lib
419 pub struct A {}
420 mod m {
421     impl super::A {
422         pub fn pub_module_method(&self) {}
423     }
424     fn f() {
425         impl super::A {
426             pub fn pub_foreign_local_method(&self) {}
427         }
428     }
429 }
430 //- /main.rs crate:main deps:lib
431 fn foo(a: lib::A) {
432     impl lib::A {
433         fn local_method(&self) {}
434     }
435     a.$0
436 }
437 "#,
438             expect![[r#"
439                 me local_method()      fn(&self)
440                 me pub_module_method() fn(&self)
441             "#]],
442         );
443     }
444
445     #[test]
446     fn test_doc_hidden_filtering() {
447         check(
448             r#"
449 //- /lib.rs crate:lib deps:dep
450 fn foo(a: dep::A) { a.$0 }
451 //- /dep.rs crate:dep
452 pub struct A {
453     #[doc(hidden)]
454     pub hidden_field: u32,
455     pub pub_field: u32,
456 }
457
458 impl A {
459     pub fn pub_method(&self) {}
460
461     #[doc(hidden)]
462     pub fn hidden_method(&self) {}
463 }
464             "#,
465             expect![[r#"
466                 fd pub_field    u32
467                 me pub_method() fn(&self)
468             "#]],
469         )
470     }
471
472     #[test]
473     fn test_union_field_completion() {
474         check(
475             r#"
476 union U { field: u8, other: u16 }
477 fn foo(u: U) { u.$0 }
478 "#,
479             expect![[r#"
480                 fd field u8
481                 fd other u16
482             "#]],
483         );
484     }
485
486     #[test]
487     fn test_method_completion_only_fitting_impls() {
488         check(
489             r#"
490 struct A<T> {}
491 impl A<u32> {
492     fn the_method(&self) {}
493 }
494 impl A<i32> {
495     fn the_other_method(&self) {}
496 }
497 fn foo(a: A<u32>) { a.$0 }
498 "#,
499             expect![[r#"
500                 me the_method() fn(&self)
501             "#]],
502         )
503     }
504
505     #[test]
506     fn test_trait_method_completion() {
507         check(
508             r#"
509 struct A {}
510 trait Trait { fn the_method(&self); }
511 impl Trait for A {}
512 fn foo(a: A) { a.$0 }
513 "#,
514             expect![[r#"
515                 me the_method() (as Trait) fn(&self)
516             "#]],
517         );
518         check_edit(
519             "the_method",
520             r#"
521 struct A {}
522 trait Trait { fn the_method(&self); }
523 impl Trait for A {}
524 fn foo(a: A) { a.$0 }
525 "#,
526             r#"
527 struct A {}
528 trait Trait { fn the_method(&self); }
529 impl Trait for A {}
530 fn foo(a: A) { a.the_method()$0 }
531 "#,
532         );
533     }
534
535     #[test]
536     fn test_trait_method_completion_deduplicated() {
537         check(
538             r"
539 struct A {}
540 trait Trait { fn the_method(&self); }
541 impl<T> Trait for T {}
542 fn foo(a: &A) { a.$0 }
543 ",
544             expect![[r#"
545                 me the_method() (as Trait) fn(&self)
546             "#]],
547         );
548     }
549
550     #[test]
551     fn completes_trait_method_from_other_module() {
552         check(
553             r"
554 struct A {}
555 mod m {
556     pub trait Trait { fn the_method(&self); }
557 }
558 use m::Trait;
559 impl Trait for A {}
560 fn foo(a: A) { a.$0 }
561 ",
562             expect![[r#"
563                 me the_method() (as Trait) fn(&self)
564             "#]],
565         );
566     }
567
568     #[test]
569     fn test_no_non_self_method() {
570         check(
571             r#"
572 struct A {}
573 impl A {
574     fn the_method() {}
575 }
576 fn foo(a: A) {
577    a.$0
578 }
579 "#,
580             expect![[r#""#]],
581         );
582     }
583
584     #[test]
585     fn test_tuple_field_completion() {
586         check(
587             r#"
588 fn foo() {
589    let b = (0, 3.14);
590    b.$0
591 }
592 "#,
593             expect![[r#"
594                 fd 0 i32
595                 fd 1 f64
596             "#]],
597         );
598     }
599
600     #[test]
601     fn test_tuple_struct_field_completion() {
602         check(
603             r#"
604 struct S(i32, f64);
605 fn foo() {
606    let b = S(0, 3.14);
607    b.$0
608 }
609 "#,
610             expect![[r#"
611                 fd 0 i32
612                 fd 1 f64
613             "#]],
614         );
615     }
616
617     #[test]
618     fn test_tuple_field_inference() {
619         check(
620             r#"
621 pub struct S;
622 impl S { pub fn blah(&self) {} }
623
624 struct T(S);
625
626 impl T {
627     fn foo(&self) {
628         // FIXME: This doesn't work without the trailing `a` as `0.` is a float
629         self.0.a$0
630     }
631 }
632 "#,
633             expect![[r#"
634                 me blah() fn(&self)
635             "#]],
636         );
637     }
638
639     #[test]
640     fn test_completion_works_in_consts() {
641         check(
642             r#"
643 struct A { the_field: u32 }
644 const X: u32 = {
645     A { the_field: 92 }.$0
646 };
647 "#,
648             expect![[r#"
649                 fd the_field u32
650             "#]],
651         );
652     }
653
654     #[test]
655     fn works_in_simple_macro_1() {
656         check(
657             r#"
658 macro_rules! m { ($e:expr) => { $e } }
659 struct A { the_field: u32 }
660 fn foo(a: A) {
661     m!(a.x$0)
662 }
663 "#,
664             expect![[r#"
665                 fd the_field u32
666             "#]],
667         );
668     }
669
670     #[test]
671     fn works_in_simple_macro_2() {
672         // this doesn't work yet because the macro doesn't expand without the token -- maybe it can be fixed with better recovery
673         check(
674             r#"
675 macro_rules! m { ($e:expr) => { $e } }
676 struct A { the_field: u32 }
677 fn foo(a: A) {
678     m!(a.$0)
679 }
680 "#,
681             expect![[r#"
682                 fd the_field u32
683             "#]],
684         );
685     }
686
687     #[test]
688     fn works_in_simple_macro_recursive_1() {
689         check(
690             r#"
691 macro_rules! m { ($e:expr) => { $e } }
692 struct A { the_field: u32 }
693 fn foo(a: A) {
694     m!(m!(m!(a.x$0)))
695 }
696 "#,
697             expect![[r#"
698                 fd the_field u32
699             "#]],
700         );
701     }
702
703     #[test]
704     fn macro_expansion_resilient() {
705         check(
706             r#"
707 macro_rules! d {
708     () => {};
709     ($val:expr) => {
710         match $val { tmp => { tmp } }
711     };
712     // Trailing comma with single argument is ignored
713     ($val:expr,) => { $crate::d!($val) };
714     ($($val:expr),+ $(,)?) => {
715         ($($crate::d!($val)),+,)
716     };
717 }
718 struct A { the_field: u32 }
719 fn foo(a: A) {
720     d!(a.$0)
721 }
722 "#,
723             expect![[r#"
724                 fd the_field u32
725             "#]],
726         );
727     }
728
729     #[test]
730     fn test_method_completion_issue_3547() {
731         check(
732             r#"
733 struct HashSet<T> {}
734 impl<T> HashSet<T> {
735     pub fn the_method(&self) {}
736 }
737 fn foo() {
738     let s: HashSet<_>;
739     s.$0
740 }
741 "#,
742             expect![[r#"
743                 me the_method() fn(&self)
744             "#]],
745         );
746     }
747
748     #[test]
749     fn completes_method_call_when_receiver_is_a_macro_call() {
750         check(
751             r#"
752 struct S;
753 impl S { fn foo(&self) {} }
754 macro_rules! make_s { () => { S }; }
755 fn main() { make_s!().f$0; }
756 "#,
757             expect![[r#"
758                 me foo() fn(&self)
759             "#]],
760         )
761     }
762
763     #[test]
764     fn completes_after_macro_call_in_submodule() {
765         check(
766             r#"
767 macro_rules! empty {
768     () => {};
769 }
770
771 mod foo {
772     #[derive(Debug, Default)]
773     struct Template2 {}
774
775     impl Template2 {
776         fn private(&self) {}
777     }
778     fn baz() {
779         let goo: Template2 = Template2 {};
780         empty!();
781         goo.$0
782     }
783 }
784         "#,
785             expect![[r#"
786                 me private() fn(&self)
787             "#]],
788         );
789     }
790
791     #[test]
792     fn issue_8931() {
793         check(
794             r#"
795 //- minicore: fn
796 struct S;
797
798 struct Foo;
799 impl Foo {
800     fn foo(&self) -> &[u8] { loop {} }
801 }
802
803 impl S {
804     fn indented(&mut self, f: impl FnOnce(&mut Self)) {
805     }
806
807     fn f(&mut self, v: Foo) {
808         self.indented(|this| v.$0)
809     }
810 }
811         "#,
812             expect![[r#"
813                 me foo() fn(&self) -> &[u8]
814             "#]],
815         );
816     }
817
818     #[test]
819     fn completes_bare_fields_and_methods_in_methods() {
820         check(
821             r#"
822 struct Foo { field: i32 }
823
824 impl Foo { fn foo(&self) { $0 } }"#,
825             expect![[r#"
826                 fd self.field i32
827                 lc self       &Foo
828                 sp Self
829                 st Foo
830                 bt u32
831                 me self.foo() fn(&self)
832             "#]],
833         );
834         check(
835             r#"
836 struct Foo(i32);
837
838 impl Foo { fn foo(&mut self) { $0 } }"#,
839             expect![[r#"
840                 fd self.0     i32
841                 lc self       &mut Foo
842                 sp Self
843                 st Foo
844                 bt u32
845                 me self.foo() fn(&mut self)
846             "#]],
847         );
848     }
849
850     #[test]
851     fn macro_completion_after_dot() {
852         check(
853             r#"
854 macro_rules! m {
855     ($e:expr) => { $e };
856 }
857
858 struct Completable;
859
860 impl Completable {
861     fn method(&self) {}
862 }
863
864 fn f() {
865     let c = Completable;
866     m!(c.$0);
867 }
868     "#,
869             expect![[r#"
870                 me method() fn(&self)
871             "#]],
872         );
873     }
874
875     #[test]
876     fn completes_method_call_when_receiver_type_has_errors_issue_10297() {
877         check(
878             r#"
879 //- minicore: iterator, sized
880 struct Vec<T>;
881 impl<T> IntoIterator for Vec<T> {
882     type Item = ();
883     type IntoIter = ();
884     fn into_iter(self);
885 }
886 fn main() {
887     let x: Vec<_>;
888     x.$0;
889 }
890 "#,
891             expect![[r#"
892                 me into_iter() (as IntoIterator) fn(self) -> <Self as IntoIterator>::IntoIter
893             "#]],
894         )
895     }
896
897     #[test]
898     fn postfix_drop_completion() {
899         cov_mark::check!(postfix_drop_completion);
900         check_edit(
901             "drop",
902             r#"
903 //- minicore: drop
904 struct Vec<T>(T);
905 impl<T> Drop for Vec<T> {
906     fn drop(&mut self) {}
907 }
908 fn main() {
909     let x = Vec(0u32)
910     x.$0;
911 }
912 "#,
913             r"
914 struct Vec<T>(T);
915 impl<T> Drop for Vec<T> {
916     fn drop(&mut self) {}
917 }
918 fn main() {
919     let x = Vec(0u32)
920     drop($0x);
921 }
922 ",
923         )
924     }
925
926     #[test]
927     fn issue_12484() {
928         check(
929             r#"
930 //- minicore: sized
931 trait SizeUser {
932     type Size;
933 }
934 trait Closure: SizeUser {}
935 trait Encrypt: SizeUser {
936     fn encrypt(self, _: impl Closure<Size = Self::Size>);
937 }
938 fn test(thing: impl Encrypt) {
939     thing.$0;
940 }
941         "#,
942             expect![[r#"
943                 me encrypt(…) (as Encrypt) fn(self, impl Closure<Size = <Self as SizeUser>::Size>)
944             "#]],
945         )
946     }
947 }