ide_completion/completions/
dot.rs

1//! Completes references after dot (fields and method calls).
2
3use std::ops::ControlFlow;
4
5use hir::{Complete, Function, HasContainer, ItemContainer, MethodCandidateCallback};
6use ide_db::FxHashSet;
7use itertools::Either;
8use syntax::SmolStr;
9
10use crate::{
11    CompletionItem, CompletionItemKind, Completions,
12    context::{
13        CompletionContext, DotAccess, DotAccessExprCtx, DotAccessKind, PathCompletionCtx,
14        PathExprCtx, Qualified,
15    },
16};
17
18/// Complete dot accesses, i.e. fields or methods.
19pub(crate) fn complete_dot(
20    acc: &mut Completions,
21    ctx: &CompletionContext<'_>,
22    dot_access: &DotAccess<'_>,
23) {
24    let receiver_ty = match dot_access {
25        DotAccess { receiver_ty: Some(receiver_ty), .. } => &receiver_ty.original,
26        _ => return,
27    };
28
29    let has_parens = matches!(dot_access.kind, DotAccessKind::Method);
30    let traits_in_scope = ctx.traits_in_scope();
31
32    // Suggest .await syntax for types that implement Future trait
33    if let Some(future_output) = receiver_ty.into_future_output(ctx.db) {
34        let await_str = SmolStr::new_static("await");
35        let mut item = CompletionItem::new(
36            CompletionItemKind::Keyword,
37            ctx.source_range(),
38            await_str.clone(),
39            ctx.edition,
40        );
41        item.detail("expr.await");
42        item.add_to(acc, ctx.db);
43
44        if ctx.config.enable_auto_await {
45            // Completions that skip `.await`, e.g. `.await.foo()`.
46            let dot_access_kind = match &dot_access.kind {
47                DotAccessKind::Field { receiver_is_ambiguous_float_literal: _ } => {
48                    DotAccessKind::Field { receiver_is_ambiguous_float_literal: false }
49                }
50                it @ DotAccessKind::Method => *it,
51            };
52            let dot_access = DotAccess {
53                receiver: dot_access.receiver.clone(),
54                receiver_ty: Some(hir::TypeInfo {
55                    original: future_output.clone(),
56                    adjusted: None,
57                }),
58                kind: dot_access_kind,
59                ctx: dot_access.ctx,
60            };
61            complete_fields(
62                acc,
63                ctx,
64                &future_output,
65                |acc, field, ty| {
66                    acc.add_field(ctx, &dot_access, Some(await_str.clone()), field, &ty)
67                },
68                |acc, field, ty| acc.add_tuple_field(ctx, Some(await_str.clone()), field, &ty),
69                has_parens,
70            );
71            complete_methods(ctx, &future_output, &traits_in_scope, |func| {
72                acc.add_method(ctx, &dot_access, func, Some(await_str.clone()), None)
73            });
74        }
75    }
76
77    complete_fields(
78        acc,
79        ctx,
80        receiver_ty,
81        |acc, field, ty| acc.add_field(ctx, dot_access, None, field, &ty),
82        |acc, field, ty| acc.add_tuple_field(ctx, None, field, &ty),
83        has_parens,
84    );
85    complete_methods(ctx, receiver_ty, &traits_in_scope, |func| {
86        acc.add_method(ctx, dot_access, func, None, None)
87    });
88
89    if ctx.config.enable_auto_iter && !receiver_ty.strip_references().impls_iterator(ctx.db) {
90        // FIXME:
91        // Checking for the existence of `iter()` is complicated in our setup, because we need to substitute
92        // its return type, so we instead check for `<&Self as IntoIterator>::IntoIter`.
93        // Does <&receiver_ty as IntoIterator>::IntoIter` exist? Assume `iter` is valid
94        let iter = receiver_ty
95            .autoderef(ctx.db)
96            .map(|ty| ty.strip_references().add_reference(hir::Mutability::Shared))
97            .find_map(|ty| ty.into_iterator_iter(ctx.db))
98            .map(|ty| (ty, SmolStr::new_static("iter()")));
99        // Does <receiver_ty as IntoIterator>::IntoIter` exist?
100        let into_iter = || {
101            receiver_ty
102                .clone()
103                .into_iterator_iter(ctx.db)
104                .map(|ty| (ty, SmolStr::new_static("into_iter()")))
105        };
106        if let Some((iter, iter_sym)) = iter.or_else(into_iter) {
107            // Skip iterators, e.g. complete `.iter().filter_map()`.
108            let dot_access_kind = match &dot_access.kind {
109                DotAccessKind::Field { receiver_is_ambiguous_float_literal: _ } => {
110                    DotAccessKind::Field { receiver_is_ambiguous_float_literal: false }
111                }
112                it @ DotAccessKind::Method => *it,
113            };
114            let dot_access = DotAccess {
115                receiver: dot_access.receiver.clone(),
116                receiver_ty: Some(hir::TypeInfo { original: iter.clone(), adjusted: None }),
117                kind: dot_access_kind,
118                ctx: dot_access.ctx,
119            };
120            complete_methods(ctx, &iter, &traits_in_scope, |func| {
121                acc.add_method(ctx, &dot_access, func, Some(iter_sym.clone()), None)
122            });
123        }
124    }
125}
126
127pub(crate) fn complete_undotted_self(
128    acc: &mut Completions,
129    ctx: &CompletionContext<'_>,
130    path_ctx: &PathCompletionCtx<'_>,
131    expr_ctx: &PathExprCtx<'_>,
132) {
133    if !ctx.config.enable_self_on_the_fly {
134        return;
135    }
136    if !path_ctx.is_trivial_path() {
137        return;
138    }
139    if !ctx.qualifier_ctx.none() {
140        return;
141    }
142    if !matches!(path_ctx.qualified, Qualified::No) {
143        return;
144    }
145    let self_param = match expr_ctx {
146        PathExprCtx { self_param: Some(self_param), .. } => self_param,
147        _ => return,
148    };
149
150    let (param_name, ty) = match self_param {
151        Either::Left(self_param) => ("self", &self_param.ty(ctx.db)),
152        Either::Right(this_param) => ("this", this_param.ty()),
153    };
154    complete_fields(
155        acc,
156        ctx,
157        ty,
158        |acc, field, ty| {
159            acc.add_field(
160                ctx,
161                &DotAccess {
162                    receiver: None,
163                    receiver_ty: None,
164                    kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal: false },
165                    ctx: DotAccessExprCtx {
166                        in_block_expr: expr_ctx.in_block_expr,
167                        in_breakable: expr_ctx.in_breakable,
168                    },
169                },
170                Some(SmolStr::new_static(param_name)),
171                field,
172                &ty,
173            )
174        },
175        |acc, field, ty| {
176            acc.add_tuple_field(ctx, Some(SmolStr::new_static(param_name)), field, &ty)
177        },
178        false,
179    );
180    complete_methods(ctx, ty, &ctx.traits_in_scope(), |func| {
181        acc.add_method(
182            ctx,
183            &DotAccess {
184                receiver: None,
185                receiver_ty: None,
186                kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal: false },
187                ctx: DotAccessExprCtx {
188                    in_block_expr: expr_ctx.in_block_expr,
189                    in_breakable: expr_ctx.in_breakable,
190                },
191            },
192            func,
193            Some(SmolStr::new_static(param_name)),
194            None,
195        )
196    });
197}
198
199fn complete_fields(
200    acc: &mut Completions,
201    ctx: &CompletionContext<'_>,
202    receiver: &hir::Type<'_>,
203    mut named_field: impl FnMut(&mut Completions, hir::Field, hir::Type<'_>),
204    mut tuple_index: impl FnMut(&mut Completions, usize, hir::Type<'_>),
205    has_parens: bool,
206) {
207    let mut seen_names = FxHashSet::default();
208    for receiver in receiver.autoderef(ctx.db) {
209        for (field, ty) in receiver.fields(ctx.db) {
210            if seen_names.insert(field.name(ctx.db))
211                && (!has_parens || ty.is_fn() || ty.is_closure())
212            {
213                named_field(acc, field, ty);
214            }
215        }
216        for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
217            // Tuples are always the last type in a deref chain, so just check if the name is
218            // already seen without inserting into the hashset.
219            if !seen_names.contains(&hir::Name::new_tuple_field(i))
220                && (!has_parens || ty.is_fn() || ty.is_closure())
221            {
222                // Tuple fields are always public (tuple struct fields are handled above).
223                tuple_index(acc, i, ty);
224            }
225        }
226    }
227}
228
229fn complete_methods(
230    ctx: &CompletionContext<'_>,
231    receiver: &hir::Type<'_>,
232    traits_in_scope: &FxHashSet<hir::TraitId>,
233    f: impl FnMut(hir::Function),
234) {
235    struct Callback<'a, F> {
236        ctx: &'a CompletionContext<'a>,
237        f: F,
238        // We deliberately deduplicate by function ID and not name, because while inherent methods cannot be
239        // duplicated, trait methods can. And it is still useful to show all of them (even when there
240        // is also an inherent method, especially considering that it may be private, and filtered later).
241        seen_methods: FxHashSet<Function>,
242    }
243
244    impl<F> MethodCandidateCallback for Callback<'_, F>
245    where
246        F: FnMut(hir::Function),
247    {
248        // We don't want to exclude inherent trait methods - that is, methods of traits available from
249        // `where` clauses or `dyn Trait`.
250        fn on_inherent_method(&mut self, func: hir::Function) -> ControlFlow<()> {
251            if func.self_param(self.ctx.db).is_some() && self.seen_methods.insert(func) {
252                (self.f)(func);
253            }
254            ControlFlow::Continue(())
255        }
256
257        fn on_trait_method(&mut self, func: hir::Function) -> ControlFlow<()> {
258            // This needs to come before the `seen_methods` test, so that if we see the same method twice,
259            // once as inherent and once not, we will include it.
260            if let ItemContainer::Trait(trait_) = func.container(self.ctx.db)
261                && (self.ctx.exclude_traits.contains(&trait_)
262                    || trait_.complete(self.ctx.db) == Complete::IgnoreMethods)
263            {
264                return ControlFlow::Continue(());
265            }
266
267            if func.self_param(self.ctx.db).is_some() && self.seen_methods.insert(func) {
268                (self.f)(func);
269            }
270
271            ControlFlow::Continue(())
272        }
273    }
274
275    receiver.iterate_method_candidates_split_inherent(
276        ctx.db,
277        &ctx.scope,
278        traits_in_scope,
279        None,
280        Callback { ctx, f, seen_methods: FxHashSet::default() },
281    );
282}
283
284#[cfg(test)]
285mod tests {
286    use expect_test::expect;
287
288    use crate::tests::{check_edit, check_no_kw, check_with_private_editable};
289
290    #[test]
291    fn test_struct_field_and_method_completion() {
292        check_no_kw(
293            r#"
294struct S { foo: u32 }
295impl S {
296    fn bar(&self) {}
297}
298fn foo(s: S) { s.$0 }
299"#,
300            expect![[r#"
301                fd foo         u32
302                me bar() fn(&self)
303            "#]],
304        );
305    }
306
307    #[test]
308    fn no_unstable_method_on_stable() {
309        check_no_kw(
310            r#"
311//- /main.rs crate:main deps:std
312fn foo(s: std::S) { s.$0 }
313//- /std.rs crate:std
314pub struct S;
315impl S {
316    #[unstable]
317    pub fn bar(&self) {}
318}
319"#,
320            expect![""],
321        );
322    }
323
324    #[test]
325    fn unstable_method_on_nightly() {
326        check_no_kw(
327            r#"
328//- toolchain:nightly
329//- /main.rs crate:main deps:std
330fn foo(s: std::S) { s.$0 }
331//- /std.rs crate:std
332pub struct S;
333impl S {
334    #[unstable]
335    pub fn bar(&self) {}
336}
337"#,
338            expect![[r#"
339                me bar() fn(&self)
340            "#]],
341        );
342    }
343
344    #[test]
345    fn test_struct_field_completion_self() {
346        check_no_kw(
347            r#"
348struct S { the_field: (u32,) }
349impl S {
350    fn foo(self) { self.$0 }
351}
352"#,
353            expect![[r#"
354                fd the_field (u32,)
355                me foo()   fn(self)
356            "#]],
357        )
358    }
359
360    #[test]
361    fn test_struct_field_completion_autoderef() {
362        check_no_kw(
363            r#"
364struct A { the_field: (u32, i32) }
365impl A {
366    fn foo(&self) { self.$0 }
367}
368"#,
369            expect![[r#"
370                fd the_field (u32, i32)
371                me foo()      fn(&self)
372            "#]],
373        )
374    }
375
376    #[test]
377    fn test_no_struct_field_completion_for_method_call() {
378        check_no_kw(
379            r#"
380struct A { the_field: u32 }
381fn foo(a: A) { a.$0() }
382"#,
383            expect![[r#""#]],
384        );
385    }
386
387    #[test]
388    fn test_visibility_filtering() {
389        check_no_kw(
390            r#"
391//- /lib.rs crate:lib new_source_root:local
392pub mod m {
393    pub struct A {
394        private_field: u32,
395        pub pub_field: u32,
396        pub(crate) crate_field: u32,
397        pub(super) super_field: u32,
398    }
399}
400//- /main.rs crate:main deps:lib new_source_root:local
401fn foo(a: lib::m::A) { a.$0 }
402"#,
403            expect![[r#"
404                fd pub_field u32
405            "#]],
406        );
407
408        check_no_kw(
409            r#"
410//- /lib.rs crate:lib new_source_root:library
411pub mod m {
412    pub struct A {
413        private_field: u32,
414        pub pub_field: u32,
415        pub(crate) crate_field: u32,
416        pub(super) super_field: u32,
417    }
418}
419//- /main.rs crate:main deps:lib new_source_root:local
420fn foo(a: lib::m::A) { a.$0 }
421"#,
422            expect![[r#"
423                fd pub_field u32
424            "#]],
425        );
426
427        check_no_kw(
428            r#"
429//- /lib.rs crate:lib new_source_root:library
430pub mod m {
431    pub struct A(
432        i32,
433        pub f64,
434    );
435}
436//- /main.rs crate:main deps:lib new_source_root:local
437fn foo(a: lib::m::A) { a.$0 }
438"#,
439            expect![[r#"
440                fd 1 f64
441            "#]],
442        );
443
444        check_no_kw(
445            r#"
446//- /lib.rs crate:lib new_source_root:local
447pub struct A {}
448mod m {
449    impl super::A {
450        fn private_method(&self) {}
451        pub(crate) fn crate_method(&self) {}
452        pub fn pub_method(&self) {}
453    }
454}
455//- /main.rs crate:main deps:lib new_source_root:local
456fn foo(a: lib::A) { a.$0 }
457"#,
458            expect![[r#"
459                me pub_method() fn(&self)
460            "#]],
461        );
462        check_no_kw(
463            r#"
464//- /lib.rs crate:lib new_source_root:library
465pub struct A {}
466mod m {
467    impl super::A {
468        fn private_method(&self) {}
469        pub(crate) fn crate_method(&self) {}
470        pub fn pub_method(&self) {}
471    }
472}
473//- /main.rs crate:main deps:lib new_source_root:local
474fn foo(a: lib::A) { a.$0 }
475"#,
476            expect![[r#"
477                me pub_method() fn(&self)
478            "#]],
479        );
480    }
481
482    #[test]
483    fn test_visibility_filtering_with_private_editable_enabled() {
484        check_with_private_editable(
485            r#"
486//- /lib.rs crate:lib new_source_root:local
487pub mod m {
488    pub struct A {
489        private_field: u32,
490        pub pub_field: u32,
491        pub(crate) crate_field: u32,
492        pub(super) super_field: u32,
493    }
494}
495//- /main.rs crate:main deps:lib new_source_root:local
496fn foo(a: lib::m::A) { a.$0 }
497"#,
498            expect![[r#"
499                fd crate_field   u32
500                fd private_field u32
501                fd pub_field     u32
502                fd super_field   u32
503            "#]],
504        );
505
506        check_with_private_editable(
507            r#"
508//- /lib.rs crate:lib new_source_root:library
509pub mod m {
510    pub struct A {
511        private_field: u32,
512        pub pub_field: u32,
513        pub(crate) crate_field: u32,
514        pub(super) super_field: u32,
515    }
516}
517//- /main.rs crate:main deps:lib new_source_root:local
518fn foo(a: lib::m::A) { a.$0 }
519"#,
520            expect![[r#"
521                fd pub_field u32
522            "#]],
523        );
524
525        check_with_private_editable(
526            r#"
527//- /lib.rs crate:lib new_source_root:library
528pub mod m {
529    pub struct A(
530        i32,
531        pub f64,
532    );
533}
534//- /main.rs crate:main deps:lib new_source_root:local
535fn foo(a: lib::m::A) { a.$0 }
536"#,
537            expect![[r#"
538                fd 1 f64
539            "#]],
540        );
541
542        check_with_private_editable(
543            r#"
544//- /lib.rs crate:lib new_source_root:local
545pub struct A {}
546mod m {
547    impl super::A {
548        fn private_method(&self) {}
549        pub(crate) fn crate_method(&self) {}
550        pub fn pub_method(&self) {}
551    }
552}
553//- /main.rs crate:main deps:lib new_source_root:local
554fn foo(a: lib::A) { a.$0 }
555"#,
556            expect![[r#"
557                me crate_method()   fn(&self)
558                me private_method() fn(&self)
559                me pub_method()     fn(&self)
560            "#]],
561        );
562        check_with_private_editable(
563            r#"
564//- /lib.rs crate:lib new_source_root:library
565pub struct A {}
566mod m {
567    impl super::A {
568        fn private_method(&self) {}
569        pub(crate) fn crate_method(&self) {}
570        pub fn pub_method(&self) {}
571    }
572}
573//- /main.rs crate:main deps:lib new_source_root:local
574fn foo(a: lib::A) { a.$0 }
575"#,
576            expect![[r#"
577                me pub_method() fn(&self)
578            "#]],
579        );
580    }
581
582    #[test]
583    fn test_local_impls() {
584        check_no_kw(
585            r#"
586pub struct A {}
587mod m {
588    impl super::A {
589        pub fn pub_module_method(&self) {}
590    }
591    fn f() {
592        impl super::A {
593            pub fn pub_foreign_local_method(&self) {}
594        }
595    }
596}
597fn foo(a: A) {
598    impl A {
599        fn local_method(&self) {}
600    }
601    a.$0
602}
603"#,
604            expect![[r#"
605                me pub_module_method() fn(&self)
606            "#]],
607        );
608    }
609
610    #[test]
611    fn test_doc_hidden_filtering() {
612        check_no_kw(
613            r#"
614//- /lib.rs crate:lib deps:dep
615fn foo(a: dep::A) { a.$0 }
616//- /dep.rs crate:dep
617pub struct A {
618    #[doc(hidden)]
619    pub hidden_field: u32,
620    pub pub_field: u32,
621}
622
623impl A {
624    pub fn pub_method(&self) {}
625
626    #[doc(hidden)]
627    pub fn hidden_method(&self) {}
628}
629            "#,
630            expect![[r#"
631                fd pub_field          u32
632                me pub_method() fn(&self)
633            "#]],
634        )
635    }
636
637    #[test]
638    fn test_union_field_completion() {
639        check_no_kw(
640            r#"
641union U { field: u8, other: u16 }
642fn foo(u: U) { u.$0 }
643"#,
644            expect![[r#"
645                fd field  u8
646                fd other u16
647            "#]],
648        );
649    }
650
651    #[test]
652    fn test_method_completion_only_fitting_impls() {
653        check_no_kw(
654            r#"
655struct A<T>(T);
656impl A<u32> {
657    fn the_method(&self) {}
658}
659impl A<i32> {
660    fn the_other_method(&self) {}
661}
662fn foo(a: A<u32>) { a.$0 }
663"#,
664            expect![[r#"
665                fd 0                  u32
666                me the_method() fn(&self)
667            "#]],
668        )
669    }
670
671    #[test]
672    fn test_trait_method_completion() {
673        check_no_kw(
674            r#"
675struct A {}
676trait Trait { fn the_method(&self); }
677impl Trait for A {}
678fn foo(a: A) { a.$0 }
679"#,
680            expect![[r#"
681                me the_method() (as Trait) fn(&self)
682            "#]],
683        );
684        check_edit(
685            "the_method",
686            r#"
687struct A {}
688trait Trait { fn the_method(&self); }
689impl Trait for A {}
690fn foo(a: A) { a.$0 }
691"#,
692            r#"
693struct A {}
694trait Trait { fn the_method(&self); }
695impl Trait for A {}
696fn foo(a: A) { a.the_method();$0 }
697"#,
698        );
699    }
700
701    #[test]
702    fn test_trait_method_completion_deduplicated() {
703        check_no_kw(
704            r"
705struct A {}
706trait Trait { fn the_method(&self); }
707impl<T> Trait for T {}
708fn foo(a: &A) { a.$0 }
709",
710            expect![[r#"
711                me the_method() (as Trait) fn(&self)
712            "#]],
713        );
714    }
715
716    #[test]
717    fn completes_trait_method_from_other_module() {
718        check_no_kw(
719            r"
720struct A {}
721mod m {
722    pub trait Trait { fn the_method(&self); }
723}
724use m::Trait;
725impl Trait for A {}
726fn foo(a: A) { a.$0 }
727",
728            expect![[r#"
729                me the_method() (as Trait) fn(&self)
730            "#]],
731        );
732    }
733
734    #[test]
735    fn test_no_non_self_method() {
736        check_no_kw(
737            r#"
738struct A {}
739impl A {
740    fn the_method() {}
741}
742fn foo(a: A) {
743   a.$0
744}
745"#,
746            expect![[r#""#]],
747        );
748    }
749
750    #[test]
751    fn test_tuple_field_completion() {
752        check_no_kw(
753            r#"
754fn foo() {
755   let b = (0, 3.14);
756   b.$0
757}
758"#,
759            expect![[r#"
760                fd 0 i32
761                fd 1 f64
762            "#]],
763        );
764    }
765
766    #[test]
767    fn test_tuple_struct_field_completion() {
768        check_no_kw(
769            r#"
770struct S(i32, f64);
771fn foo() {
772   let b = S(0, 3.14);
773   b.$0
774}
775"#,
776            expect![[r#"
777                fd 0 i32
778                fd 1 f64
779            "#]],
780        );
781    }
782
783    #[test]
784    fn test_tuple_field_inference() {
785        check_no_kw(
786            r#"
787pub struct S;
788impl S { pub fn blah(&self) {} }
789
790struct T(S);
791
792impl T {
793    fn foo(&self) {
794        self.0.$0
795    }
796}
797"#,
798            expect![[r#"
799                me blah() fn(&self)
800            "#]],
801        );
802    }
803
804    #[test]
805    fn test_field_no_same_name() {
806        check_no_kw(
807            r#"
808//- minicore: deref
809struct A { field: u8 }
810struct B { field: u16, another: u32 }
811impl core::ops::Deref for A {
812    type Target = B;
813    fn deref(&self) -> &Self::Target { loop {} }
814}
815fn test(a: A) {
816    a.$0
817}
818"#,
819            expect![[r#"
820                fd another                                                          u32
821                fd field                                                             u8
822                me deref() (use core::ops::Deref) fn(&self) -> &<Self as Deref>::Target
823            "#]],
824        );
825    }
826
827    #[test]
828    fn test_tuple_field_no_same_index() {
829        check_no_kw(
830            r#"
831//- minicore: deref
832struct A(u8);
833struct B(u16, u32);
834impl core::ops::Deref for A {
835    type Target = B;
836    fn deref(&self) -> &Self::Target { loop {} }
837}
838fn test(a: A) {
839    a.$0
840}
841"#,
842            expect![[r#"
843                fd 0                                                                 u8
844                fd 1                                                                u32
845                me deref() (use core::ops::Deref) fn(&self) -> &<Self as Deref>::Target
846            "#]],
847        );
848    }
849
850    #[test]
851    fn test_tuple_struct_deref_to_tuple_no_same_index() {
852        check_no_kw(
853            r#"
854//- minicore: deref
855struct A(u8);
856impl core::ops::Deref for A {
857    type Target = (u16, u32);
858    fn deref(&self) -> &Self::Target { loop {} }
859}
860fn test(a: A) {
861    a.$0
862}
863"#,
864            expect![[r#"
865                fd 0                                                                 u8
866                fd 1                                                                u32
867                me deref() (use core::ops::Deref) fn(&self) -> &<Self as Deref>::Target
868            "#]],
869        );
870    }
871
872    #[test]
873    fn test_completion_works_in_consts() {
874        check_no_kw(
875            r#"
876struct A { the_field: u32 }
877const X: u32 = {
878    A { the_field: 92 }.$0
879};
880"#,
881            expect![[r#"
882                fd the_field u32
883            "#]],
884        );
885    }
886
887    #[test]
888    fn works_in_simple_macro_1() {
889        check_no_kw(
890            r#"
891macro_rules! m { ($e:expr) => { $e } }
892struct A { the_field: u32 }
893fn foo(a: A) {
894    m!(a.x$0)
895}
896"#,
897            expect![[r#"
898                fd the_field u32
899            "#]],
900        );
901    }
902
903    #[test]
904    fn works_in_simple_macro_2() {
905        // this doesn't work yet because the macro doesn't expand without the token -- maybe it can be fixed with better recovery
906        check_no_kw(
907            r#"
908macro_rules! m { ($e:expr) => { $e } }
909struct A { the_field: u32 }
910fn foo(a: A) {
911    m!(a.$0)
912}
913"#,
914            expect![[r#"
915                fd the_field u32
916            "#]],
917        );
918    }
919
920    #[test]
921    fn works_in_simple_macro_recursive_1() {
922        check_no_kw(
923            r#"
924macro_rules! m { ($e:expr) => { $e } }
925struct A { the_field: u32 }
926fn foo(a: A) {
927    m!(m!(m!(a.x$0)))
928}
929"#,
930            expect![[r#"
931                fd the_field u32
932            "#]],
933        );
934    }
935
936    #[test]
937    fn macro_expansion_resilient() {
938        check_no_kw(
939            r#"
940macro_rules! d {
941    () => {};
942    ($val:expr) => {
943        match $val { tmp => { tmp } }
944    };
945    // Trailing comma with single argument is ignored
946    ($val:expr,) => { $crate::d!($val) };
947    ($($val:expr),+ $(,)?) => {
948        ($($crate::d!($val)),+,)
949    };
950}
951struct A { the_field: u32 }
952fn foo(a: A) {
953    d!(a.$0)
954}
955"#,
956            expect![[r#"
957                fd the_field u32
958            "#]],
959        );
960    }
961
962    #[test]
963    fn test_method_completion_issue_3547() {
964        check_no_kw(
965            r#"
966struct HashSet<T> {}
967impl<T> HashSet<T> {
968    pub fn the_method(&self) {}
969}
970fn foo() {
971    let s: HashSet<_>;
972    s.$0
973}
974"#,
975            expect![[r#"
976                me the_method() fn(&self)
977            "#]],
978        );
979    }
980
981    #[test]
982    fn completes_method_call_when_receiver_is_a_macro_call() {
983        check_no_kw(
984            r#"
985struct S;
986impl S { fn foo(&self) {} }
987macro_rules! make_s { () => { S }; }
988fn main() { make_s!().f$0; }
989"#,
990            expect![[r#"
991                me foo() fn(&self)
992            "#]],
993        )
994    }
995
996    #[test]
997    fn completes_after_macro_call_in_submodule() {
998        check_no_kw(
999            r#"
1000macro_rules! empty {
1001    () => {};
1002}
1003
1004mod foo {
1005    #[derive(Debug, Default)]
1006    struct Template2 {}
1007
1008    impl Template2 {
1009        fn private(&self) {}
1010    }
1011    fn baz() {
1012        let goo: Template2 = Template2 {};
1013        empty!();
1014        goo.$0
1015    }
1016}
1017        "#,
1018            expect![[r#"
1019                me private() fn(&self)
1020            "#]],
1021        );
1022    }
1023
1024    #[test]
1025    fn issue_8931() {
1026        check_no_kw(
1027            r#"
1028//- minicore: fn
1029struct S;
1030
1031struct Foo;
1032impl Foo {
1033    fn foo(&self) -> &[u8] { loop {} }
1034}
1035
1036impl S {
1037    fn indented(&mut self, f: impl FnOnce(&mut Self)) {
1038    }
1039
1040    fn f(&mut self, v: Foo) {
1041        self.indented(|this| v.$0)
1042    }
1043}
1044        "#,
1045            expect![[r#"
1046                me foo() fn(&self) -> &[u8]
1047            "#]],
1048        );
1049    }
1050
1051    #[test]
1052    fn completes_bare_fields_and_methods_in_methods() {
1053        check_no_kw(
1054            r#"
1055struct Foo { field: i32 }
1056
1057impl Foo { fn foo(&self) { $0 } }"#,
1058            expect![[r#"
1059                fd self.field       i32
1060                me self.foo() fn(&self)
1061                lc self            &Foo
1062                sp Self             Foo
1063                st Foo              Foo
1064                bt u32              u32
1065            "#]],
1066        );
1067        check_no_kw(
1068            r#"
1069struct Foo(i32);
1070
1071impl Foo { fn foo(&mut self) { $0 } }"#,
1072            expect![[r#"
1073                fd self.0               i32
1074                me self.foo() fn(&mut self)
1075                lc self            &mut Foo
1076                sp Self                 Foo
1077                st Foo                  Foo
1078                bt u32                  u32
1079            "#]],
1080        );
1081    }
1082
1083    #[test]
1084    fn completes_bare_fields_and_methods_in_this_closure() {
1085        check_no_kw(
1086            r#"
1087//- minicore: fn
1088struct Foo { field: i32 }
1089
1090impl Foo { fn foo(&mut self) { let _: fn(&mut Self) = |this| { $0 } } }"#,
1091            expect![[r#"
1092                fd this.field           i32
1093                me this.foo() fn(&mut self)
1094                lc self            &mut Foo
1095                lc this            &mut Foo
1096                md core
1097                sp Self                 Foo
1098                st Foo                  Foo
1099                tt Fn
1100                tt FnMut
1101                tt FnOnce
1102                bt u32                  u32
1103            "#]],
1104        );
1105    }
1106
1107    #[test]
1108    fn completes_bare_fields_and_methods_in_other_closure() {
1109        check_no_kw(
1110            r#"
1111//- minicore: fn
1112struct Foo { field: i32 }
1113
1114impl Foo { fn foo(&self) { let _: fn(&Self) = |foo| { $0 } } }"#,
1115            expect![[r#"
1116                fd self.field       i32
1117                me self.foo() fn(&self)
1118                lc foo             &Foo
1119                lc self            &Foo
1120                md core
1121                sp Self             Foo
1122                st Foo              Foo
1123                tt Fn
1124                tt FnMut
1125                tt FnOnce
1126                bt u32              u32
1127            "#]],
1128        );
1129
1130        check_no_kw(
1131            r#"
1132//- minicore: fn
1133struct Foo { field: i32 }
1134
1135impl Foo { fn foo(&self) { let _: fn(&Self) = || { $0 } } }"#,
1136            expect![[r#"
1137                fd self.field       i32
1138                me self.foo() fn(&self)
1139                lc self            &Foo
1140                md core
1141                sp Self             Foo
1142                st Foo              Foo
1143                tt Fn
1144                tt FnMut
1145                tt FnOnce
1146                bt u32              u32
1147            "#]],
1148        );
1149
1150        check_no_kw(
1151            r#"
1152//- minicore: fn
1153struct Foo { field: i32 }
1154
1155impl Foo { fn foo(&self) { let _: fn(&Self, &Self) = |foo, other| { $0 } } }"#,
1156            expect![[r#"
1157                fd self.field       i32
1158                me self.foo() fn(&self)
1159                lc foo             &Foo
1160                lc other           &Foo
1161                lc self            &Foo
1162                md core
1163                sp Self             Foo
1164                st Foo              Foo
1165                tt Fn
1166                tt FnMut
1167                tt FnOnce
1168                bt u32              u32
1169            "#]],
1170        );
1171    }
1172
1173    #[test]
1174    fn macro_completion_after_dot() {
1175        check_no_kw(
1176            r#"
1177macro_rules! m {
1178    ($e:expr) => { $e };
1179}
1180
1181struct Completable;
1182
1183impl Completable {
1184    fn method(&self) {}
1185}
1186
1187fn f() {
1188    let c = Completable;
1189    m!(c.$0);
1190}
1191    "#,
1192            expect![[r#"
1193                me method() fn(&self)
1194            "#]],
1195        );
1196    }
1197
1198    #[test]
1199    fn completes_method_call_when_receiver_type_has_errors_issue_10297() {
1200        check_no_kw(
1201            r#"
1202//- minicore: iterator, sized
1203struct Vec<T>;
1204impl<T> IntoIterator for Vec<T> {
1205    type Item = ();
1206    type IntoIter = ();
1207    fn into_iter(self);
1208}
1209fn main() {
1210    let x: Vec<_>;
1211    x.$0;
1212}
1213"#,
1214            expect![[r#"
1215                me into_iter() (as IntoIterator) fn(self) -> <Self as IntoIterator>::IntoIter
1216            "#]],
1217        )
1218    }
1219
1220    #[test]
1221    fn postfix_drop_completion() {
1222        cov_mark::check!(postfix_drop_completion);
1223        check_edit(
1224            "drop",
1225            r#"
1226//- minicore: drop
1227struct Vec<T>(T);
1228impl<T> Drop for Vec<T> {
1229    fn drop(&mut self) {}
1230}
1231fn main() {
1232    let x = Vec(0u32)
1233    x.$0;
1234}
1235"#,
1236            r"
1237struct Vec<T>(T);
1238impl<T> Drop for Vec<T> {
1239    fn drop(&mut self) {}
1240}
1241fn main() {
1242    let x = Vec(0u32)
1243    drop($0x);
1244}
1245",
1246        )
1247    }
1248
1249    #[test]
1250    fn issue_12484() {
1251        check_no_kw(
1252            r#"
1253//- minicore: sized
1254trait SizeUser {
1255    type Size;
1256}
1257trait Closure: SizeUser {}
1258trait Encrypt: SizeUser {
1259    fn encrypt(self, _: impl Closure<Size = Self::Size>);
1260}
1261fn test(thing: impl Encrypt) {
1262    thing.$0;
1263}
1264        "#,
1265            expect![[r#"
1266                me encrypt(…) (as Encrypt) fn(self, impl Closure<Size = <Self as SizeUser>::Size>)
1267            "#]],
1268        )
1269    }
1270
1271    #[test]
1272    fn only_consider_same_type_once() {
1273        check_no_kw(
1274            r#"
1275//- minicore: deref
1276struct A(u8);
1277struct B(u16);
1278impl core::ops::Deref for A {
1279    type Target = B;
1280    fn deref(&self) -> &Self::Target { loop {} }
1281}
1282impl core::ops::Deref for B {
1283    type Target = A;
1284    fn deref(&self) -> &Self::Target { loop {} }
1285}
1286fn test(a: A) {
1287    a.$0
1288}
1289"#,
1290            expect![[r#"
1291                fd 0                                                                 u8
1292                me deref() (use core::ops::Deref) fn(&self) -> &<Self as Deref>::Target
1293            "#]],
1294        );
1295    }
1296
1297    #[test]
1298    fn no_inference_var_in_completion() {
1299        check_no_kw(
1300            r#"
1301struct S<T>(T);
1302fn test(s: S<Unknown>) {
1303    s.$0
1304}
1305"#,
1306            expect![[r#"
1307                fd 0 {unknown}
1308            "#]],
1309        );
1310    }
1311
1312    #[test]
1313    fn assoc_impl_1() {
1314        check_no_kw(
1315            r#"
1316//- minicore: deref
1317fn main() {
1318    let foo: Foo<&u8> = Foo::new(&42_u8);
1319    foo.$0
1320}
1321
1322trait Bar {
1323    fn bar(&self);
1324}
1325
1326impl Bar for u8 {
1327    fn bar(&self) {}
1328}
1329
1330struct Foo<F> {
1331    foo: F,
1332}
1333
1334impl<F> Foo<F> {
1335    fn new(foo: F) -> Foo<F> {
1336        Foo { foo }
1337    }
1338}
1339
1340impl<F: core::ops::Deref<Target = impl Bar>> Foo<F> {
1341    fn foobar(&self) {
1342        self.foo.deref().bar()
1343    }
1344}
1345"#,
1346            expect![[r#"
1347                fd foo            &u8
1348                me foobar() fn(&self)
1349            "#]],
1350        );
1351    }
1352
1353    #[test]
1354    fn assoc_impl_2() {
1355        check_no_kw(
1356            r#"
1357//- minicore: deref
1358fn main() {
1359    let foo: Foo<&u8> = Foo::new(&42_u8);
1360    foo.$0
1361}
1362
1363trait Bar {
1364    fn bar(&self);
1365}
1366
1367struct Foo<F> {
1368    foo: F,
1369}
1370
1371impl<F> Foo<F> {
1372    fn new(foo: F) -> Foo<F> {
1373        Foo { foo }
1374    }
1375}
1376
1377impl<B: Bar, F: core::ops::Deref<Target = B>> Foo<F> {
1378    fn foobar(&self) {
1379        self.foo.deref().bar()
1380    }
1381}
1382"#,
1383            expect![[r#"
1384                fd foo &u8
1385            "#]],
1386        );
1387    }
1388
1389    #[test]
1390    fn test_struct_function_field_completion() {
1391        check_no_kw(
1392            r#"
1393struct S { va_field: u32, fn_field: fn() }
1394fn foo() { S { va_field: 0, fn_field: || {} }.fi$0() }
1395"#,
1396            expect![[r#"
1397                fd fn_field fn()
1398            "#]],
1399        );
1400
1401        check_edit(
1402            "fn_field",
1403            r#"
1404struct S { va_field: u32, fn_field: fn() }
1405fn foo() { S { va_field: 0, fn_field: || {} }.fi$0() }
1406"#,
1407            r#"
1408struct S { va_field: u32, fn_field: fn() }
1409fn foo() { (S { va_field: 0, fn_field: || {} }.fn_field)() }
1410"#,
1411        );
1412    }
1413
1414    #[test]
1415    fn test_tuple_function_field_completion() {
1416        check_no_kw(
1417            r#"
1418struct B(u32, fn())
1419fn foo() {
1420   let b = B(0, || {});
1421   b.$0()
1422}
1423"#,
1424            expect![[r#"
1425                fd 1 fn()
1426            "#]],
1427        );
1428
1429        check_edit(
1430            "1",
1431            r#"
1432struct B(u32, fn())
1433fn foo() {
1434   let b = B(0, || {});
1435   b.$0()
1436}
1437"#,
1438            r#"
1439struct B(u32, fn())
1440fn foo() {
1441   let b = B(0, || {});
1442   (b.1)()
1443}
1444"#,
1445        )
1446    }
1447
1448    #[test]
1449    fn test_fn_field_dot_access_method_has_parens_false() {
1450        check_no_kw(
1451            r#"
1452struct Foo { baz: fn() }
1453impl Foo {
1454    fn bar<T>(self, t: T) -> T { t }
1455}
1456
1457fn baz() {
1458    let foo = Foo{ baz: || {} };
1459    foo.ba$0;
1460}
1461"#,
1462            expect![[r#"
1463                fd baz                fn()
1464                me bar(…) fn(self, T) -> T
1465            "#]],
1466        );
1467
1468        check_edit(
1469            "baz",
1470            r#"
1471struct Foo { baz: fn() }
1472impl Foo {
1473    fn bar<T>(self, t: T) -> T { t }
1474}
1475
1476fn baz() {
1477    let foo = Foo{ baz: || {} };
1478    foo.ba$0;
1479}
1480"#,
1481            r#"
1482struct Foo { baz: fn() }
1483impl Foo {
1484    fn bar<T>(self, t: T) -> T { t }
1485}
1486
1487fn baz() {
1488    let foo = Foo{ baz: || {} };
1489    (foo.baz)();
1490}
1491"#,
1492        );
1493
1494        check_edit(
1495            "bar",
1496            r#"
1497struct Foo { baz: fn() }
1498impl Foo {
1499    fn bar<T>(self, t: T) -> T { t }
1500}
1501
1502fn baz() {
1503    let foo = Foo{ baz: || {} };
1504    foo.ba$0;
1505}
1506"#,
1507            r#"
1508struct Foo { baz: fn() }
1509impl Foo {
1510    fn bar<T>(self, t: T) -> T { t }
1511}
1512
1513fn baz() {
1514    let foo = Foo{ baz: || {} };
1515    foo.bar(${1:t})$0;
1516}
1517"#,
1518        );
1519    }
1520
1521    #[test]
1522    fn skip_iter() {
1523        check_no_kw(
1524            r#"
1525        //- minicore: iterator, clone, builtin_impls
1526        fn foo() {
1527            [].$0
1528        }
1529        "#,
1530            expect![[r#"
1531                me clone() (as Clone)                                             fn(&self) -> Self
1532                me fmt(…) (use core::fmt::Debug) fn(&self, &mut Formatter<'_>) -> Result<(), Error>
1533                me into_iter() (as IntoIterator)       fn(self) -> <Self as IntoIterator>::IntoIter
1534            "#]],
1535        );
1536        check_no_kw(
1537            r#"
1538//- minicore: iterator
1539struct MyIntoIter;
1540impl IntoIterator for MyIntoIter {
1541    type Item = ();
1542    type IntoIter = MyIterator;
1543    fn into_iter(self) -> Self::IntoIter {
1544        MyIterator
1545    }
1546}
1547
1548struct MyIterator;
1549impl Iterator for MyIterator {
1550    type Item = ();
1551    fn next(&mut self) -> Self::Item {}
1552}
1553
1554fn foo() {
1555    MyIntoIter.$0
1556}
1557"#,
1558            expect![[r#"
1559                me into_iter() (as IntoIterator)                fn(self) -> <Self as IntoIterator>::IntoIter
1560                me into_iter().by_ref() (as Iterator)                             fn(&mut self) -> &mut Self
1561                me into_iter().into_iter() (as IntoIterator)    fn(self) -> <Self as IntoIterator>::IntoIter
1562                me into_iter().next() (as Iterator)        fn(&mut self) -> Option<<Self as Iterator>::Item>
1563                me into_iter().nth(…) (as Iterator) fn(&mut self, usize) -> Option<<Self as Iterator>::Item>
1564            "#]],
1565        );
1566        check_no_kw(
1567            r#"
1568//- minicore: iterator, deref
1569struct Foo;
1570impl Foo { fn iter(&self) -> Iter { Iter } }
1571impl IntoIterator for &Foo {
1572    type Item = ();
1573    type IntoIter = Iter;
1574    fn into_iter(self) -> Self::IntoIter { Iter }
1575}
1576struct Ref;
1577impl core::ops::Deref for Ref {
1578    type Target = Foo;
1579    fn deref(&self) -> &Self::Target { &Foo }
1580}
1581struct Iter;
1582impl Iterator for Iter {
1583    type Item = ();
1584    fn next(&mut self) -> Option<Self::Item> { None }
1585}
1586fn foo() {
1587    Ref.$0
1588}
1589"#,
1590            expect![[r#"
1591                me deref() (use core::ops::Deref)                 fn(&self) -> &<Self as Deref>::Target
1592                me into_iter() (as IntoIterator)           fn(self) -> <Self as IntoIterator>::IntoIter
1593                me iter()                                                             fn(&self) -> Iter
1594                me iter().by_ref() (as Iterator)                             fn(&mut self) -> &mut Self
1595                me iter().into_iter() (as IntoIterator)    fn(self) -> <Self as IntoIterator>::IntoIter
1596                me iter().next() (as Iterator)        fn(&mut self) -> Option<<Self as Iterator>::Item>
1597                me iter().nth(…) (as Iterator) fn(&mut self, usize) -> Option<<Self as Iterator>::Item>
1598            "#]],
1599        );
1600    }
1601
1602    #[test]
1603    fn skip_await() {
1604        check_no_kw(
1605            r#"
1606//- minicore: future
1607struct Foo;
1608impl Foo {
1609    fn foo(self) {}
1610}
1611
1612async fn foo() -> Foo { Foo }
1613
1614async fn bar() {
1615    foo().$0
1616}
1617"#,
1618            expect![[r#"
1619    me await.foo()                                                                      fn(self)
1620    me into_future() (use core::future::IntoFuture) fn(self) -> <Self as IntoFuture>::IntoFuture
1621"#]],
1622        );
1623        check_edit(
1624            "foo",
1625            r#"
1626//- minicore: future
1627struct Foo;
1628impl Foo {
1629    fn foo(self) {}
1630}
1631
1632async fn foo() -> Foo { Foo }
1633
1634async fn bar() {
1635    foo().$0
1636}
1637"#,
1638            r#"
1639struct Foo;
1640impl Foo {
1641    fn foo(self) {}
1642}
1643
1644async fn foo() -> Foo { Foo }
1645
1646async fn bar() {
1647    foo().await.foo();$0
1648}
1649"#,
1650        );
1651    }
1652
1653    #[test]
1654    fn receiver_without_deref_impl_completion() {
1655        check_no_kw(
1656            r#"
1657//- minicore: receiver
1658#![feature(arbitrary_self_types)]
1659
1660use core::ops::Receiver;
1661
1662struct Foo;
1663
1664impl Foo {
1665    fn foo(self: Bar) {}
1666}
1667
1668struct Bar;
1669
1670impl Receiver for Bar {
1671    type Target = Foo;
1672}
1673
1674fn main() {
1675    let bar = Bar;
1676    bar.$0
1677}
1678"#,
1679            expect![[r#"
1680                me foo() fn(self: Bar)
1681            "#]],
1682        );
1683    }
1684
1685    #[test]
1686    fn no_iter_suggestion_on_iterator() {
1687        check_no_kw(
1688            r#"
1689//- minicore: iterator
1690struct MyIter;
1691impl Iterator for MyIter {
1692    type Item = ();
1693    fn next(&mut self) -> Option<Self::Item> { None }
1694}
1695
1696fn main() {
1697    MyIter.$0
1698}
1699"#,
1700            expect![[r#"
1701                me by_ref() (as Iterator)                             fn(&mut self) -> &mut Self
1702                me into_iter() (as IntoIterator)    fn(self) -> <Self as IntoIterator>::IntoIter
1703                me next() (as Iterator)        fn(&mut self) -> Option<<Self as Iterator>::Item>
1704                me nth(…) (as Iterator) fn(&mut self, usize) -> Option<<Self as Iterator>::Item>
1705            "#]],
1706        );
1707    }
1708}