]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/completions/unqualified_path.rs
YAGNI active_resolve_capabilities
[rust.git] / crates / completion / src / completions / unqualified_path.rs
1 //! Completion of names from the current scope, e.g. locals and imported items.
2
3 use std::iter;
4
5 use either::Either;
6 use hir::{Adt, ModPath, ModuleDef, ScopeDef, Type};
7 use ide_db::helpers::insert_use::ImportScope;
8 use ide_db::imports_locator;
9 use syntax::AstNode;
10 use test_utils::mark;
11
12 use crate::{
13     render::{render_resolution_with_import, RenderContext},
14     CompletionContext, Completions, ImportEdit,
15 };
16
17 pub(crate) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) {
18     if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) {
19         return;
20     }
21     if ctx.record_lit_syntax.is_some()
22         || ctx.record_pat_syntax.is_some()
23         || ctx.attribute_under_caret.is_some()
24         || ctx.mod_declaration_under_caret.is_some()
25     {
26         return;
27     }
28
29     if let Some(ty) = &ctx.expected_type {
30         complete_enum_variants(acc, ctx, ty);
31     }
32
33     if ctx.is_pat_binding_or_const {
34         return;
35     }
36
37     ctx.scope.process_all_names(&mut |name, res| {
38         if ctx.use_item_syntax.is_some() {
39             if let (ScopeDef::Unknown, Some(name_ref)) = (&res, &ctx.name_ref_syntax) {
40                 if name_ref.syntax().text() == name.to_string().as_str() {
41                     mark::hit!(self_fulfilling_completion);
42                     return;
43                 }
44             }
45         }
46         acc.add_resolution(ctx, name.to_string(), &res)
47     });
48
49     if ctx.config.enable_autoimport_completions {
50         fuzzy_completion(acc, ctx);
51     }
52 }
53
54 fn complete_enum_variants(acc: &mut Completions, ctx: &CompletionContext, ty: &Type) {
55     if let Some(Adt::Enum(enum_data)) =
56         iter::successors(Some(ty.clone()), |ty| ty.remove_ref()).last().and_then(|ty| ty.as_adt())
57     {
58         let variants = enum_data.variants(ctx.db);
59
60         let module = if let Some(module) = ctx.scope.module() {
61             // Compute path from the completion site if available.
62             module
63         } else {
64             // Otherwise fall back to the enum's definition site.
65             enum_data.module(ctx.db)
66         };
67
68         for variant in variants {
69             if let Some(path) = module.find_use_path(ctx.db, ModuleDef::from(variant)) {
70                 // Variants with trivial paths are already added by the existing completion logic,
71                 // so we should avoid adding these twice
72                 if path.segments.len() > 1 {
73                     acc.add_qualified_enum_variant(ctx, variant, path);
74                 }
75             }
76         }
77     }
78 }
79
80 // Feature: Fuzzy Completion and Autoimports
81 //
82 // When completing names in the current scope, proposes additional imports from other modules or crates,
83 // if they can be qualified in the scope and their name contains all symbols from the completion input
84 // (case-insensitive, in any order or places).
85 //
86 // ```
87 // fn main() {
88 //     pda<|>
89 // }
90 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
91 // ```
92 // ->
93 // ```
94 // use std::marker::PhantomData;
95 //
96 // fn main() {
97 //     PhantomData
98 // }
99 // # pub mod std { pub mod marker { pub struct PhantomData { } } }
100 // ```
101 //
102 // .Fuzzy search details
103 //
104 // To avoid an excessive amount of the results returned, completion input is checked for inclusion in the names only
105 // (i.e. in `HashMap` in the `std::collections::HashMap` path).
106 // For the same reasons, avoids searching for any imports for inputs with their length less that 2 symbols.
107 //
108 // .Merge Behavior
109 //
110 // It is possible to configure how use-trees are merged with the `importMergeBehavior` setting.
111 // Mimics the corresponding behavior of the `Auto Import` feature.
112 //
113 // .LSP and performance implications
114 //
115 // The feature is enabled only if the LSP client supports LSP protocol version 3.16+ and reports the `additionalTextEdits`
116 // (case sensitive) resolve client capability in its client capabilities.
117 // This way the server is able to defer the costly computations, doing them for a selected completion item only.
118 // For clients with no such support, all edits have to be calculated on the completion request, including the fuzzy search completion ones,
119 // which might be slow ergo the feature is automatically disabled.
120 //
121 // .Feature toggle
122 //
123 // The feature can be forcefully turned off in the settings with the `rust-analyzer.completion.enableAutoimportCompletions` flag.
124 // Note that having this flag set to `true` does not guarantee that the feature is enabled: your client needs to have the corredponding
125 // capability enabled.
126 fn fuzzy_completion(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
127     let potential_import_name = ctx.token.to_string();
128     let _p = profile::span("fuzzy_completion").detail(|| potential_import_name.clone());
129
130     if potential_import_name.len() < 2 {
131         return None;
132     }
133
134     let current_module = ctx.scope.module()?;
135     let anchor = ctx.name_ref_syntax.as_ref()?;
136     let import_scope = ImportScope::find_insert_use_container(anchor.syntax(), &ctx.sema)?;
137
138     let user_input_lowercased = potential_import_name.to_lowercase();
139     let mut all_mod_paths = imports_locator::find_similar_imports(
140         &ctx.sema,
141         ctx.krate?,
142         Some(40),
143         potential_import_name,
144         true,
145         true,
146     )
147     .filter_map(|import_candidate| {
148         Some(match import_candidate {
149             Either::Left(module_def) => {
150                 (current_module.find_use_path(ctx.db, module_def)?, ScopeDef::ModuleDef(module_def))
151             }
152             Either::Right(macro_def) => {
153                 (current_module.find_use_path(ctx.db, macro_def)?, ScopeDef::MacroDef(macro_def))
154             }
155         })
156     })
157     .filter(|(mod_path, _)| mod_path.len() > 1)
158     .collect::<Vec<_>>();
159
160     all_mod_paths.sort_by_cached_key(|(mod_path, _)| {
161         compute_fuzzy_completion_order_key(mod_path, &user_input_lowercased)
162     });
163
164     acc.add_all(all_mod_paths.into_iter().filter_map(|(import_path, definition)| {
165         render_resolution_with_import(
166             RenderContext::new(ctx),
167             ImportEdit { import_path, import_scope: import_scope.clone() },
168             &definition,
169         )
170     }));
171     Some(())
172 }
173
174 fn compute_fuzzy_completion_order_key(
175     proposed_mod_path: &ModPath,
176     user_input_lowercased: &str,
177 ) -> usize {
178     mark::hit!(certain_fuzzy_order_test);
179     let proposed_import_name = match proposed_mod_path.segments.last() {
180         Some(name) => name.to_string().to_lowercase(),
181         None => return usize::MAX,
182     };
183     match proposed_import_name.match_indices(user_input_lowercased).next() {
184         Some((first_matching_index, _)) => first_matching_index,
185         None => usize::MAX,
186     }
187 }
188
189 #[cfg(test)]
190 mod tests {
191     use expect_test::{expect, Expect};
192     use test_utils::mark;
193
194     use crate::{
195         test_utils::{check_edit, check_edit_with_config, completion_list_with_config},
196         CompletionConfig, CompletionKind,
197     };
198
199     fn check(ra_fixture: &str, expect: Expect) {
200         check_with_config(CompletionConfig::default(), ra_fixture, expect);
201     }
202
203     fn check_with_config(config: CompletionConfig, ra_fixture: &str, expect: Expect) {
204         let actual = completion_list_with_config(config, ra_fixture, CompletionKind::Reference);
205         expect.assert_eq(&actual)
206     }
207
208     fn fuzzy_completion_config() -> CompletionConfig {
209         CompletionConfig::default()
210     }
211
212     #[test]
213     fn self_fulfilling_completion() {
214         mark::check!(self_fulfilling_completion);
215         check(
216             r#"
217 use foo<|>
218 use std::collections;
219 "#,
220             expect![[r#"
221                 ?? collections
222             "#]],
223         );
224     }
225
226     #[test]
227     fn bind_pat_and_path_ignore_at() {
228         check(
229             r#"
230 enum Enum { A, B }
231 fn quux(x: Option<Enum>) {
232     match x {
233         None => (),
234         Some(en<|> @ Enum::A) => (),
235     }
236 }
237 "#,
238             expect![[""]],
239         );
240     }
241
242     #[test]
243     fn bind_pat_and_path_ignore_ref() {
244         check(
245             r#"
246 enum Enum { A, B }
247 fn quux(x: Option<Enum>) {
248     match x {
249         None => (),
250         Some(ref en<|>) => (),
251     }
252 }
253 "#,
254             expect![[""]],
255         );
256     }
257
258     #[test]
259     fn bind_pat_and_path() {
260         check(
261             r#"
262 enum Enum { A, B }
263 fn quux(x: Option<Enum>) {
264     match x {
265         None => (),
266         Some(En<|>) => (),
267     }
268 }
269 "#,
270             expect![[r#"
271                 en Enum
272             "#]],
273         );
274     }
275
276     #[test]
277     fn completes_bindings_from_let() {
278         check(
279             r#"
280 fn quux(x: i32) {
281     let y = 92;
282     1 + <|>;
283     let z = ();
284 }
285 "#,
286             expect![[r#"
287                 bn y       i32
288                 bn x       i32
289                 fn quux(…) fn quux(x: i32)
290             "#]],
291         );
292     }
293
294     #[test]
295     fn completes_bindings_from_if_let() {
296         check(
297             r#"
298 fn quux() {
299     if let Some(x) = foo() {
300         let y = 92;
301     };
302     if let Some(a) = bar() {
303         let b = 62;
304         1 + <|>
305     }
306 }
307 "#,
308             expect![[r#"
309                 bn b      i32
310                 bn a
311                 fn quux() fn quux()
312             "#]],
313         );
314     }
315
316     #[test]
317     fn completes_bindings_from_for() {
318         check(
319             r#"
320 fn quux() {
321     for x in &[1, 2, 3] { <|> }
322 }
323 "#,
324             expect![[r#"
325                 bn x
326                 fn quux() fn quux()
327             "#]],
328         );
329     }
330
331     #[test]
332     fn completes_if_prefix_is_keyword() {
333         mark::check!(completes_if_prefix_is_keyword);
334         check_edit(
335             "wherewolf",
336             r#"
337 fn main() {
338     let wherewolf = 92;
339     drop(where<|>)
340 }
341 "#,
342             r#"
343 fn main() {
344     let wherewolf = 92;
345     drop(wherewolf)
346 }
347 "#,
348         )
349     }
350
351     #[test]
352     fn completes_generic_params() {
353         check(
354             r#"fn quux<T>() { <|> }"#,
355             expect![[r#"
356                 tp T
357                 fn quux() fn quux<T>()
358             "#]],
359         );
360     }
361
362     #[test]
363     fn completes_generic_params_in_struct() {
364         check(
365             r#"struct S<T> { x: <|>}"#,
366             expect![[r#"
367                 tp Self
368                 tp T
369                 st S<…>
370             "#]],
371         );
372     }
373
374     #[test]
375     fn completes_self_in_enum() {
376         check(
377             r#"enum X { Y(<|>) }"#,
378             expect![[r#"
379                 tp Self
380                 en X
381             "#]],
382         );
383     }
384
385     #[test]
386     fn completes_module_items() {
387         check(
388             r#"
389 struct S;
390 enum E {}
391 fn quux() { <|> }
392 "#,
393             expect![[r#"
394                 st S
395                 fn quux() fn quux()
396                 en E
397             "#]],
398         );
399     }
400
401     /// Regression test for issue #6091.
402     #[test]
403     fn correctly_completes_module_items_prefixed_with_underscore() {
404         check_edit(
405             "_alpha",
406             r#"
407 fn main() {
408     _<|>
409 }
410 fn _alpha() {}
411 "#,
412             r#"
413 fn main() {
414     _alpha()$0
415 }
416 fn _alpha() {}
417 "#,
418         )
419     }
420
421     #[test]
422     fn completes_extern_prelude() {
423         check(
424             r#"
425 //- /lib.rs crate:main deps:other_crate
426 use <|>;
427
428 //- /other_crate/lib.rs crate:other_crate
429 // nothing here
430 "#,
431             expect![[r#"
432                 md other_crate
433             "#]],
434         );
435     }
436
437     #[test]
438     fn completes_module_items_in_nested_modules() {
439         check(
440             r#"
441 struct Foo;
442 mod m {
443     struct Bar;
444     fn quux() { <|> }
445 }
446 "#,
447             expect![[r#"
448                 fn quux() fn quux()
449                 st Bar
450             "#]],
451         );
452     }
453
454     #[test]
455     fn completes_return_type() {
456         check(
457             r#"
458 struct Foo;
459 fn x() -> <|>
460 "#,
461             expect![[r#"
462                 st Foo
463                 fn x() fn x()
464             "#]],
465         );
466     }
467
468     #[test]
469     fn dont_show_both_completions_for_shadowing() {
470         check(
471             r#"
472 fn foo() {
473     let bar = 92;
474     {
475         let bar = 62;
476         drop(<|>)
477     }
478 }
479 "#,
480             // FIXME: should be only one bar here
481             expect![[r#"
482                 bn bar   i32
483                 bn bar   i32
484                 fn foo() fn foo()
485             "#]],
486         );
487     }
488
489     #[test]
490     fn completes_self_in_methods() {
491         check(
492             r#"impl S { fn foo(&self) { <|> } }"#,
493             expect![[r#"
494                 bn self &{unknown}
495                 tp Self
496             "#]],
497         );
498     }
499
500     #[test]
501     fn completes_prelude() {
502         check(
503             r#"
504 //- /main.rs crate:main deps:std
505 fn foo() { let x: <|> }
506
507 //- /std/lib.rs crate:std
508 #[prelude_import]
509 use prelude::*;
510
511 mod prelude { struct Option; }
512 "#,
513             expect![[r#"
514                 fn foo()  fn foo()
515                 md std
516                 st Option
517             "#]],
518         );
519     }
520
521     #[test]
522     fn completes_std_prelude_if_core_is_defined() {
523         check(
524             r#"
525 //- /main.rs crate:main deps:core,std
526 fn foo() { let x: <|> }
527
528 //- /core/lib.rs crate:core
529 #[prelude_import]
530 use prelude::*;
531
532 mod prelude { struct Option; }
533
534 //- /std/lib.rs crate:std deps:core
535 #[prelude_import]
536 use prelude::*;
537
538 mod prelude { struct String; }
539 "#,
540             expect![[r#"
541                 fn foo()  fn foo()
542                 md std
543                 md core
544                 st String
545             "#]],
546         );
547     }
548
549     #[test]
550     fn completes_macros_as_value() {
551         check(
552             r#"
553 macro_rules! foo { () => {} }
554
555 #[macro_use]
556 mod m1 {
557     macro_rules! bar { () => {} }
558 }
559
560 mod m2 {
561     macro_rules! nope { () => {} }
562
563     #[macro_export]
564     macro_rules! baz { () => {} }
565 }
566
567 fn main() { let v = <|> }
568 "#,
569             expect![[r##"
570                 md m1
571                 ma baz!(…) #[macro_export]
572                 macro_rules! baz
573                 fn main()  fn main()
574                 md m2
575                 ma bar!(…) macro_rules! bar
576                 ma foo!(…) macro_rules! foo
577             "##]],
578         );
579     }
580
581     #[test]
582     fn completes_both_macro_and_value() {
583         check(
584             r#"
585 macro_rules! foo { () => {} }
586 fn foo() { <|> }
587 "#,
588             expect![[r#"
589                 fn foo()   fn foo()
590                 ma foo!(…) macro_rules! foo
591             "#]],
592         );
593     }
594
595     #[test]
596     fn completes_macros_as_type() {
597         check(
598             r#"
599 macro_rules! foo { () => {} }
600 fn main() { let x: <|> }
601 "#,
602             expect![[r#"
603                 fn main()  fn main()
604                 ma foo!(…) macro_rules! foo
605             "#]],
606         );
607     }
608
609     #[test]
610     fn completes_macros_as_stmt() {
611         check(
612             r#"
613 macro_rules! foo { () => {} }
614 fn main() { <|> }
615 "#,
616             expect![[r#"
617                 fn main()  fn main()
618                 ma foo!(…) macro_rules! foo
619             "#]],
620         );
621     }
622
623     #[test]
624     fn completes_local_item() {
625         check(
626             r#"
627 fn main() {
628     return f<|>;
629     fn frobnicate() {}
630 }
631 "#,
632             expect![[r#"
633                 fn frobnicate() fn frobnicate()
634                 fn main()       fn main()
635             "#]],
636         );
637     }
638
639     #[test]
640     fn completes_in_simple_macro_1() {
641         check(
642             r#"
643 macro_rules! m { ($e:expr) => { $e } }
644 fn quux(x: i32) {
645     let y = 92;
646     m!(<|>);
647 }
648 "#,
649             expect![[r#"
650                 bn y       i32
651                 bn x       i32
652                 fn quux(…) fn quux(x: i32)
653                 ma m!(…)   macro_rules! m
654             "#]],
655         );
656     }
657
658     #[test]
659     fn completes_in_simple_macro_2() {
660         check(
661             r"
662 macro_rules! m { ($e:expr) => { $e } }
663 fn quux(x: i32) {
664     let y = 92;
665     m!(x<|>);
666 }
667 ",
668             expect![[r#"
669                 bn y       i32
670                 bn x       i32
671                 fn quux(…) fn quux(x: i32)
672                 ma m!(…)   macro_rules! m
673             "#]],
674         );
675     }
676
677     #[test]
678     fn completes_in_simple_macro_without_closing_parens() {
679         check(
680             r#"
681 macro_rules! m { ($e:expr) => { $e } }
682 fn quux(x: i32) {
683     let y = 92;
684     m!(x<|>
685 }
686 "#,
687             expect![[r#"
688                 bn y       i32
689                 bn x       i32
690                 fn quux(…) fn quux(x: i32)
691                 ma m!(…)   macro_rules! m
692             "#]],
693         );
694     }
695
696     #[test]
697     fn completes_unresolved_uses() {
698         check(
699             r#"
700 use spam::Quux;
701
702 fn main() { <|> }
703 "#,
704             expect![[r#"
705                 fn main() fn main()
706                 ?? Quux
707             "#]],
708         );
709     }
710
711     #[test]
712     fn completes_enum_variant_matcharm() {
713         check(
714             r#"
715 enum Foo { Bar, Baz, Quux }
716
717 fn main() {
718     let foo = Foo::Quux;
719     match foo { Qu<|> }
720 }
721 "#,
722             expect![[r#"
723                 ev Foo::Bar  ()
724                 ev Foo::Baz  ()
725                 ev Foo::Quux ()
726                 en Foo
727             "#]],
728         )
729     }
730
731     #[test]
732     fn completes_enum_variant_matcharm_ref() {
733         check(
734             r#"
735 enum Foo { Bar, Baz, Quux }
736
737 fn main() {
738     let foo = Foo::Quux;
739     match &foo { Qu<|> }
740 }
741 "#,
742             expect![[r#"
743                 ev Foo::Bar  ()
744                 ev Foo::Baz  ()
745                 ev Foo::Quux ()
746                 en Foo
747             "#]],
748         )
749     }
750
751     #[test]
752     fn completes_enum_variant_iflet() {
753         check(
754             r#"
755 enum Foo { Bar, Baz, Quux }
756
757 fn main() {
758     let foo = Foo::Quux;
759     if let Qu<|> = foo { }
760 }
761 "#,
762             expect![[r#"
763                 ev Foo::Bar  ()
764                 ev Foo::Baz  ()
765                 ev Foo::Quux ()
766                 en Foo
767             "#]],
768         )
769     }
770
771     #[test]
772     fn completes_enum_variant_basic_expr() {
773         check(
774             r#"
775 enum Foo { Bar, Baz, Quux }
776 fn main() { let foo: Foo = Q<|> }
777 "#,
778             expect![[r#"
779                 ev Foo::Bar  ()
780                 ev Foo::Baz  ()
781                 ev Foo::Quux ()
782                 en Foo
783                 fn main()    fn main()
784             "#]],
785         )
786     }
787
788     #[test]
789     fn completes_enum_variant_from_module() {
790         check(
791             r#"
792 mod m { pub enum E { V } }
793 fn f() -> m::E { V<|> }
794 "#,
795             expect![[r#"
796                 ev m::E::V ()
797                 md m
798                 fn f()     fn f() -> m::E
799             "#]],
800         )
801     }
802
803     #[test]
804     fn dont_complete_attr() {
805         check(
806             r#"
807 struct Foo;
808 #[<|>]
809 fn f() {}
810 "#,
811             expect![[""]],
812         )
813     }
814
815     #[test]
816     fn completes_type_or_trait_in_impl_block() {
817         check(
818             r#"
819 trait MyTrait {}
820 struct MyStruct {}
821
822 impl My<|>
823 "#,
824             expect![[r#"
825                 tp Self
826                 tt MyTrait
827                 st MyStruct
828             "#]],
829         )
830     }
831
832     #[test]
833     fn function_fuzzy_completion() {
834         check_edit_with_config(
835             fuzzy_completion_config(),
836             "stdin",
837             r#"
838 //- /lib.rs crate:dep
839 pub mod io {
840     pub fn stdin() {}
841 };
842
843 //- /main.rs crate:main deps:dep
844 fn main() {
845     stdi<|>
846 }
847 "#,
848             r#"
849 use dep::io::stdin;
850
851 fn main() {
852     stdin()$0
853 }
854 "#,
855         );
856     }
857
858     #[test]
859     fn macro_fuzzy_completion() {
860         check_edit_with_config(
861             fuzzy_completion_config(),
862             "macro_with_curlies!",
863             r#"
864 //- /lib.rs crate:dep
865 /// Please call me as macro_with_curlies! {}
866 #[macro_export]
867 macro_rules! macro_with_curlies {
868     () => {}
869 }
870
871 //- /main.rs crate:main deps:dep
872 fn main() {
873     curli<|>
874 }
875 "#,
876             r#"
877 use dep::macro_with_curlies;
878
879 fn main() {
880     macro_with_curlies! {$0}
881 }
882 "#,
883         );
884     }
885
886     #[test]
887     fn struct_fuzzy_completion() {
888         check_edit_with_config(
889             fuzzy_completion_config(),
890             "ThirdStruct",
891             r#"
892 //- /lib.rs crate:dep
893 pub struct FirstStruct;
894 pub mod some_module {
895     pub struct SecondStruct;
896     pub struct ThirdStruct;
897 }
898
899 //- /main.rs crate:main deps:dep
900 use dep::{FirstStruct, some_module::SecondStruct};
901
902 fn main() {
903     this<|>
904 }
905 "#,
906             r#"
907 use dep::{FirstStruct, some_module::{SecondStruct, ThirdStruct}};
908
909 fn main() {
910     ThirdStruct
911 }
912 "#,
913         );
914     }
915
916     #[test]
917     fn fuzzy_completions_come_in_specific_order() {
918         mark::check!(certain_fuzzy_order_test);
919         check_with_config(
920             fuzzy_completion_config(),
921             r#"
922 //- /lib.rs crate:dep
923 pub struct FirstStruct;
924 pub mod some_module {
925     // already imported, omitted
926     pub struct SecondStruct;
927     // does not contain all letters from the query, omitted
928     pub struct UnrelatedOne;
929     // contains all letters from the query, but not in sequence, displayed last
930     pub struct ThiiiiiirdStruct;
931     // contains all letters from the query, but not in the beginning, displayed second
932     pub struct AfterThirdStruct;
933     // contains all letters from the query in the begginning, displayed first
934     pub struct ThirdStruct;
935 }
936
937 //- /main.rs crate:main deps:dep
938 use dep::{FirstStruct, some_module::SecondStruct};
939
940 fn main() {
941     hir<|>
942 }
943 "#,
944             expect![[r#"
945                 fn main()           fn main()
946                 st SecondStruct
947                 st FirstStruct
948                 md dep
949                 st dep::some_module::ThirdStruct
950                 st dep::some_module::AfterThirdStruct
951                 st dep::some_module::ThiiiiiirdStruct
952             "#]],
953         );
954     }
955 }