]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/unqualified_path.rs
819fa3a430cdcf6eeb13cedab846897f38c58677
[rust.git] / crates / ide_completion / src / completions / unqualified_path.rs
1 //! Completion of names from the current scope, e.g. locals and imported items.
2
3 use hir::ScopeDef;
4 use syntax::{ast, AstNode};
5
6 use crate::{patterns::ImmediateLocation, CompletionContext, Completions};
7
8 pub(crate) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) {
9     if ctx.is_path_disallowed() || !ctx.is_trivial_path() || ctx.has_impl_or_trait_prev_sibling() {
10         return;
11     }
12
13     if ctx.expects_item() || ctx.expects_assoc_item() {
14         // only show macros in {Assoc}ItemList
15         ctx.scope.process_all_names(&mut |name, res| {
16             if let hir::ScopeDef::MacroDef(mac) = res {
17                 if mac.is_fn_like() {
18                     acc.add_macro(ctx, Some(name.clone()), mac);
19                 }
20             }
21             if let hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(_)) = res {
22                 acc.add_resolution(ctx, name, &res);
23             }
24         });
25         return;
26     }
27
28     if ctx.in_use_tree() {
29         // only show modules in a fresh UseTree
30         cov_mark::hit!(only_completes_modules_in_import);
31         ctx.scope.process_all_names(&mut |name, res| {
32             if let ScopeDef::ModuleDef(hir::ModuleDef::Module(_)) = res {
33                 acc.add_resolution(ctx, name, &res);
34             }
35         });
36         return;
37     }
38
39     if !ctx.expects_type() {
40         if let Some(hir::Adt::Enum(e)) =
41             ctx.expected_type.as_ref().and_then(|ty| ty.strip_references().as_adt())
42         {
43             super::enum_variants_with_paths(acc, ctx, e, |acc, ctx, variant, path| {
44                 acc.add_qualified_enum_variant(ctx, variant, path)
45             });
46         }
47     }
48
49     if let Some(ImmediateLocation::GenericArgList(arg_list)) = &ctx.completion_location {
50         if let Some(path_seg) = arg_list.syntax().parent().and_then(ast::PathSegment::cast) {
51             if let Some(hir::PathResolution::Def(hir::ModuleDef::Trait(trait_))) =
52                 ctx.sema.resolve_path(&path_seg.parent_path())
53             {
54                 trait_.items(ctx.sema.db).into_iter().for_each(|it| {
55                     if let hir::AssocItem::TypeAlias(alias) = it {
56                         acc.add_type_alias_with_eq(ctx, alias)
57                     }
58                 });
59             }
60         }
61     }
62
63     ctx.scope.process_all_names(&mut |name, res| {
64         if let ScopeDef::GenericParam(hir::GenericParam::LifetimeParam(_)) | ScopeDef::Label(_) =
65             res
66         {
67             cov_mark::hit!(skip_lifetime_completion);
68             return;
69         }
70         let add_resolution = match res {
71             ScopeDef::ImplSelfType(_) => {
72                 !ctx.previous_token_is(syntax::T![impl]) && !ctx.previous_token_is(syntax::T![for])
73             }
74             // Don't suggest attribute macros and derives.
75             ScopeDef::MacroDef(mac) => mac.is_fn_like(),
76             // no values in type places
77             ScopeDef::ModuleDef(
78                 hir::ModuleDef::Function(_)
79                 | hir::ModuleDef::Variant(_)
80                 | hir::ModuleDef::Static(_),
81             )
82             | ScopeDef::Local(_) => !ctx.expects_type(),
83             // unless its a constant in a generic arg list position
84             ScopeDef::ModuleDef(hir::ModuleDef::Const(_))
85             | ScopeDef::GenericParam(hir::GenericParam::ConstParam(_)) => {
86                 !ctx.expects_type() || ctx.expects_generic_arg()
87             }
88             _ => true,
89         };
90         if add_resolution {
91             acc.add_resolution(ctx, name, &res);
92         }
93     });
94 }
95
96 #[cfg(test)]
97 mod tests {
98     use expect_test::{expect, Expect};
99
100     use crate::{
101         tests::{check_edit, filtered_completion_list_with_config, TEST_CONFIG},
102         CompletionConfig, CompletionKind,
103     };
104
105     fn check(ra_fixture: &str, expect: Expect) {
106         check_with_config(TEST_CONFIG, ra_fixture, expect);
107     }
108
109     fn check_with_config(config: CompletionConfig, ra_fixture: &str, expect: Expect) {
110         let actual =
111             filtered_completion_list_with_config(config, ra_fixture, CompletionKind::Reference);
112         expect.assert_eq(&actual)
113     }
114
115     #[test]
116     fn dont_complete_values_in_type_pos() {
117         check(
118             r#"
119 const FOO: () = ();
120 static BAR: () = ();
121 enum Foo {
122     Bar
123 }
124 struct Baz;
125 fn foo() {
126     let local = ();
127     let _: $0;
128 }
129 "#,
130             expect![[r#"
131                 en Foo
132                 st Baz
133             "#]],
134         );
135     }
136
137     #[test]
138     fn completes_bindings_from_let() {
139         check(
140             r#"
141 fn quux(x: i32) {
142     let y = 92;
143     1 + $0;
144     let z = ();
145 }
146 "#,
147             expect![[r#"
148                 lc y       i32
149                 lc x       i32
150                 fn quux(…) fn(i32)
151             "#]],
152         );
153     }
154
155     #[test]
156     fn completes_bindings_from_if_let() {
157         check(
158             r#"
159 fn quux() {
160     if let Some(x) = foo() {
161         let y = 92;
162     };
163     if let Some(a) = bar() {
164         let b = 62;
165         1 + $0
166     }
167 }
168 "#,
169             expect![[r#"
170                 lc b      i32
171                 lc a
172                 fn quux() fn()
173             "#]],
174         );
175     }
176
177     #[test]
178     fn completes_bindings_from_for() {
179         check(
180             r#"
181 fn quux() {
182     for x in &[1, 2, 3] { $0 }
183 }
184 "#,
185             expect![[r#"
186                 lc x
187                 fn quux() fn()
188             "#]],
189         );
190     }
191
192     #[test]
193     fn completes_if_prefix_is_keyword() {
194         cov_mark::check!(completes_if_prefix_is_keyword);
195         check_edit(
196             "wherewolf",
197             r#"
198 fn main() {
199     let wherewolf = 92;
200     drop(where$0)
201 }
202 "#,
203             r#"
204 fn main() {
205     let wherewolf = 92;
206     drop(wherewolf)
207 }
208 "#,
209         )
210     }
211
212     #[test]
213     fn completes_generic_params() {
214         check(
215             r#"fn quux<T>() { $0 }"#,
216             expect![[r#"
217                 tp T
218                 fn quux() fn()
219             "#]],
220         );
221         check(
222             r#"fn quux<const C: usize>() { $0 }"#,
223             expect![[r#"
224                 cp C
225                 fn quux() fn()
226             "#]],
227         );
228     }
229
230     #[test]
231     fn does_not_complete_lifetimes() {
232         cov_mark::check!(skip_lifetime_completion);
233         check(
234             r#"fn quux<'a>() { $0 }"#,
235             expect![[r#"
236                 fn quux() fn()
237             "#]],
238         );
239     }
240
241     #[test]
242     fn completes_generic_params_in_struct() {
243         check(
244             r#"struct S<T> { x: $0}"#,
245             expect![[r#"
246                 sp Self
247                 tp T
248                 st S<…>
249             "#]],
250         );
251     }
252
253     #[test]
254     fn completes_self_in_enum() {
255         check(
256             r#"enum X { Y($0) }"#,
257             expect![[r#"
258                 sp Self
259                 en X
260             "#]],
261         );
262     }
263
264     #[test]
265     fn completes_module_items() {
266         check(
267             r#"
268 struct S;
269 enum E {}
270 fn quux() { $0 }
271 "#,
272             expect![[r#"
273                 st S
274                 fn quux() fn()
275                 en E
276             "#]],
277         );
278     }
279
280     /// Regression test for issue #6091.
281     #[test]
282     fn correctly_completes_module_items_prefixed_with_underscore() {
283         check_edit(
284             "_alpha",
285             r#"
286 fn main() {
287     _$0
288 }
289 fn _alpha() {}
290 "#,
291             r#"
292 fn main() {
293     _alpha()$0
294 }
295 fn _alpha() {}
296 "#,
297         )
298     }
299
300     #[test]
301     fn completes_module_items_in_nested_modules() {
302         check(
303             r#"
304 struct Foo;
305 mod m {
306     struct Bar;
307     fn quux() { $0 }
308 }
309 "#,
310             expect![[r#"
311                 fn quux() fn()
312                 st Bar
313             "#]],
314         );
315     }
316
317     #[test]
318     fn completes_return_type() {
319         check(
320             r#"
321 struct Foo;
322 fn x() -> $0
323 "#,
324             expect![[r#"
325                 st Foo
326             "#]],
327         );
328     }
329
330     #[test]
331     fn dont_show_both_completions_for_shadowing() {
332         check(
333             r#"
334 fn foo() {
335     let bar = 92;
336     {
337         let bar = 62;
338         drop($0)
339     }
340 }
341 "#,
342             // FIXME: should be only one bar here
343             expect![[r#"
344                 lc bar   i32
345                 lc bar   i32
346                 fn foo() fn()
347             "#]],
348         );
349     }
350
351     #[test]
352     fn completes_self_in_methods() {
353         check(
354             r#"impl S { fn foo(&self) { $0 } }"#,
355             expect![[r#"
356                 lc self &{unknown}
357                 sp Self
358             "#]],
359         );
360     }
361
362     #[test]
363     fn completes_prelude() {
364         check(
365             r#"
366 //- /main.rs crate:main deps:std
367 fn foo() { let x: $0 }
368
369 //- /std/lib.rs crate:std
370 pub mod prelude {
371     pub mod rust_2018 {
372         pub struct Option;
373     }
374 }
375 "#,
376             expect![[r#"
377                 md std
378                 st Option
379             "#]],
380         );
381     }
382
383     #[test]
384     fn completes_prelude_macros() {
385         check(
386             r#"
387 //- /main.rs crate:main deps:std
388 fn f() {$0}
389
390 //- /std/lib.rs crate:std
391 pub mod prelude {
392     pub mod rust_2018 {
393         pub use crate::concat;
394     }
395 }
396
397 mod macros {
398     #[rustc_builtin_macro]
399     #[macro_export]
400     macro_rules! concat { }
401 }
402 "#,
403             expect![[r##"
404                 fn f()        fn()
405                 ma concat!(…) #[macro_export] macro_rules! concat
406                 md std
407             "##]],
408         );
409     }
410
411     #[test]
412     fn does_not_complete_non_fn_macros() {
413         check(
414             r#"
415 #[rustc_builtin_macro]
416 pub macro Clone {}
417
418 fn f() {$0}
419 "#,
420             expect![[r#"
421                 fn f() fn()
422             "#]],
423         );
424         check(
425             r#"
426 #[rustc_builtin_macro]
427 pub macro bench {}
428
429 fn f() {$0}
430 "#,
431             expect![[r#"
432                 fn f() fn()
433             "#]],
434         );
435     }
436
437     #[test]
438     fn completes_std_prelude_if_core_is_defined() {
439         check(
440             r#"
441 //- /main.rs crate:main deps:core,std
442 fn foo() { let x: $0 }
443
444 //- /core/lib.rs crate:core
445 pub mod prelude {
446     pub mod rust_2018 {
447         pub struct Option;
448     }
449 }
450
451 //- /std/lib.rs crate:std deps:core
452 pub mod prelude {
453     pub mod rust_2018 {
454         pub struct String;
455     }
456 }
457 "#,
458             expect![[r#"
459                 md std
460                 md core
461                 st String
462             "#]],
463         );
464     }
465
466     #[test]
467     fn completes_macros_as_value() {
468         check(
469             r#"
470 macro_rules! foo { () => {} }
471
472 #[macro_use]
473 mod m1 {
474     macro_rules! bar { () => {} }
475 }
476
477 mod m2 {
478     macro_rules! nope { () => {} }
479
480     #[macro_export]
481     macro_rules! baz { () => {} }
482 }
483
484 fn main() { let v = $0 }
485 "#,
486             expect![[r##"
487                 md m1
488                 ma baz!(…) #[macro_export] macro_rules! baz
489                 fn main()  fn()
490                 md m2
491                 ma bar!(…) macro_rules! bar
492                 ma foo!(…) macro_rules! foo
493             "##]],
494         );
495     }
496
497     #[test]
498     fn completes_both_macro_and_value() {
499         check(
500             r#"
501 macro_rules! foo { () => {} }
502 fn foo() { $0 }
503 "#,
504             expect![[r#"
505                 fn foo()   fn()
506                 ma foo!(…) macro_rules! foo
507             "#]],
508         );
509     }
510
511     #[test]
512     fn completes_macros_as_type() {
513         check(
514             r#"
515 macro_rules! foo { () => {} }
516 fn main() { let x: $0 }
517 "#,
518             expect![[r#"
519                 ma foo!(…) macro_rules! foo
520             "#]],
521         );
522     }
523
524     #[test]
525     fn completes_macros_as_stmt() {
526         check(
527             r#"
528 macro_rules! foo { () => {} }
529 fn main() { $0 }
530 "#,
531             expect![[r#"
532                 fn main()  fn()
533                 ma foo!(…) macro_rules! foo
534             "#]],
535         );
536     }
537
538     #[test]
539     fn completes_local_item() {
540         check(
541             r#"
542 fn main() {
543     return f$0;
544     fn frobnicate() {}
545 }
546 "#,
547             expect![[r#"
548                 fn frobnicate() fn()
549                 fn main()       fn()
550             "#]],
551         );
552     }
553
554     #[test]
555     fn completes_in_simple_macro_1() {
556         check(
557             r#"
558 macro_rules! m { ($e:expr) => { $e } }
559 fn quux(x: i32) {
560     let y = 92;
561     m!($0);
562 }
563 "#,
564             expect![[r#"
565                 lc y       i32
566                 lc x       i32
567                 fn quux(…) fn(i32)
568                 ma m!(…)   macro_rules! m
569             "#]],
570         );
571     }
572
573     #[test]
574     fn completes_in_simple_macro_2() {
575         check(
576             r"
577 macro_rules! m { ($e:expr) => { $e } }
578 fn quux(x: i32) {
579     let y = 92;
580     m!(x$0);
581 }
582 ",
583             expect![[r#"
584                 lc y       i32
585                 lc x       i32
586                 fn quux(…) fn(i32)
587                 ma m!(…)   macro_rules! m
588             "#]],
589         );
590     }
591
592     #[test]
593     fn completes_in_simple_macro_without_closing_parens() {
594         check(
595             r#"
596 macro_rules! m { ($e:expr) => { $e } }
597 fn quux(x: i32) {
598     let y = 92;
599     m!(x$0
600 }
601 "#,
602             expect![[r#"
603                 lc y       i32
604                 lc x       i32
605                 fn quux(…) fn(i32)
606                 ma m!(…)   macro_rules! m
607             "#]],
608         );
609     }
610
611     #[test]
612     fn completes_unresolved_uses() {
613         check(
614             r#"
615 use spam::Quux;
616
617 fn main() { $0 }
618 "#,
619             expect![[r#"
620                 fn main() fn()
621                 ?? Quux
622             "#]],
623         );
624     }
625
626     #[test]
627     fn completes_enum_variant_basic_expr() {
628         check(
629             r#"
630 enum Foo { Bar, Baz, Quux }
631 fn main() { let foo: Foo = Q$0 }
632 "#,
633             expect![[r#"
634                 ev Foo::Bar  ()
635                 ev Foo::Baz  ()
636                 ev Foo::Quux ()
637                 en Foo
638                 fn main()    fn()
639             "#]],
640         )
641     }
642
643     #[test]
644     fn completes_enum_variant_from_module() {
645         check(
646             r#"
647 mod m { pub enum E { V } }
648 fn f() -> m::E { V$0 }
649 "#,
650             expect![[r#"
651                 ev m::E::V ()
652                 md m
653                 fn f()     fn() -> E
654             "#]],
655         )
656     }
657
658     #[test]
659     fn dont_complete_attr() {
660         check(
661             r#"
662 struct Foo;
663 #[$0]
664 fn f() {}
665 "#,
666             expect![[""]],
667         )
668     }
669
670     #[test]
671     fn completes_types_and_const_in_arg_list() {
672         check(
673             r#"
674 enum Bar {
675     Baz
676 }
677 trait Foo {
678     type Bar;
679 }
680
681 const CONST: () = ();
682
683 fn foo<T: Foo<$0>, const CONST_PARAM: usize>(_: T) {}
684 "#,
685             expect![[r#"
686                 ta Bar =       type Bar;
687                 tp T
688                 cp CONST_PARAM
689                 tt Foo
690                 en Bar
691                 ct CONST
692             "#]],
693         );
694     }
695 }