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