]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/completions/pattern.rs
Merge #9765
[rust.git] / crates / ide_completion / src / completions / pattern.rs
1 //! Completes constants and paths in patterns.
2
3 use crate::{context::PatternRefutability, CompletionContext, Completions};
4
5 /// Completes constants and paths in patterns.
6 pub(crate) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
7     let refutable = match ctx.is_pat_or_const {
8         Some(it) => it == PatternRefutability::Refutable,
9         None => return,
10     };
11
12     if refutable {
13         if let Some(hir::Adt::Enum(e)) =
14             ctx.expected_type.as_ref().and_then(|ty| ty.strip_references().as_adt())
15         {
16             super::enum_variants_with_paths(acc, ctx, e, |acc, ctx, variant, path| {
17                 acc.add_qualified_variant_pat(ctx, variant, path.clone());
18                 acc.add_qualified_enum_variant(ctx, variant, path);
19             });
20         }
21     }
22
23     // FIXME: ideally, we should look at the type we are matching against and
24     // suggest variants + auto-imports
25     ctx.process_all_names(&mut |name, res| {
26         let add_resolution = match &res {
27             hir::ScopeDef::ModuleDef(def) => match def {
28                 hir::ModuleDef::Adt(hir::Adt::Struct(strukt)) => {
29                     acc.add_struct_pat(ctx, *strukt, Some(name.clone()));
30                     true
31                 }
32                 hir::ModuleDef::Variant(variant) if refutable => {
33                     acc.add_variant_pat(ctx, *variant, Some(name.clone()));
34                     true
35                 }
36                 hir::ModuleDef::Adt(hir::Adt::Enum(..))
37                 | hir::ModuleDef::Variant(..)
38                 | hir::ModuleDef::Const(..)
39                 | hir::ModuleDef::Module(..) => refutable,
40                 _ => false,
41             },
42             hir::ScopeDef::MacroDef(mac) => mac.is_fn_like(),
43             hir::ScopeDef::ImplSelfType(impl_) => match impl_.self_ty(ctx.db).as_adt() {
44                 Some(hir::Adt::Struct(strukt)) => {
45                     acc.add_struct_pat(ctx, strukt, Some(name.clone()));
46                     true
47                 }
48                 Some(hir::Adt::Enum(_)) => refutable,
49                 _ => true,
50             },
51             _ => false,
52         };
53         if add_resolution {
54             acc.add_resolution(ctx, name, &res);
55         }
56     });
57 }