]> git.lizzy.rs Git - rust.git/commitdiff
complete fields in enum variants
authorEkaterina Babshukova <ekaterina.babshukova@yandex.ru>
Fri, 12 Jul 2019 16:56:18 +0000 (19:56 +0300)
committerEkaterina Babshukova <ekaterina.babshukova@yandex.ru>
Fri, 12 Jul 2019 17:31:49 +0000 (20:31 +0300)
crates/ra_hir/src/adt.rs
crates/ra_hir/src/lib.rs
crates/ra_hir/src/source_binder.rs
crates/ra_hir/src/ty/infer.rs
crates/ra_ide_api/src/completion/complete_struct_literal.rs

index 5a3ea5f5589e37f1779ec6bae0d28b3af96b7207..8afdac801d5b4435709716c4ab41f8e1fb99f5e6 100644 (file)
@@ -185,6 +185,13 @@ pub enum VariantDef {
 impl_froms!(VariantDef: Struct, EnumVariant);
 
 impl VariantDef {
+    pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
+        match self {
+            VariantDef::Struct(it) => it.fields(db),
+            VariantDef::EnumVariant(it) => it.fields(db),
+        }
+    }
+
     pub(crate) fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
         match self {
             VariantDef::Struct(it) => it.field(db, name),
index 56831ba05b0b619141715218bbf87f88d62d4555..55d1298cfda025d29bf91b6e1dfcfb89b7688630 100644 (file)
@@ -55,7 +55,7 @@ fn from(it: $v) -> $e {
 };
 
 pub use self::{
-    adt::AdtDef,
+    adt::{AdtDef, VariantDef},
     either::Either,
     expr::ExprScopes,
     generics::{GenericParam, GenericParams, HasGenericParams},
index 573add7da5a49a57bf4d3ccf31e2f118e74d8f58..071c1bb1887686c56e6220544c5b92cff1f12537 100644 (file)
@@ -266,6 +266,11 @@ pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField
         self.infer.as_ref()?.field_resolution(expr_id)
     }
 
+    pub fn resolve_variant(&self, struct_lit: &ast::StructLit) -> Option<crate::VariantDef> {
+        let expr_id = self.body_source_map.as_ref()?.node_expr(struct_lit.into())?;
+        self.infer.as_ref()?.variant_resolution(expr_id)
+    }
+
     pub fn resolve_macro_call(
         &self,
         db: &impl HirDatabase,
index 26ddf031709542eac65891d92c64ec1542a5b8a5..5ad4f73ec1e7bbdf89ab72a1f160efe59807b758 100644 (file)
@@ -113,6 +113,7 @@ pub struct InferenceResult {
     method_resolutions: FxHashMap<ExprId, Function>,
     /// For each field access expr, records the field it resolves to.
     field_resolutions: FxHashMap<ExprId, StructField>,
+    variant_resolutions: FxHashMap<ExprId, VariantDef>,
     /// For each associated item record what it resolves to
     assoc_resolutions: FxHashMap<ExprOrPatId, ImplItem>,
     diagnostics: Vec<InferenceDiagnostic>,
@@ -127,6 +128,9 @@ pub fn method_resolution(&self, expr: ExprId) -> Option<Function> {
     pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> {
         self.field_resolutions.get(&expr).copied()
     }
+    pub fn variant_resolution(&self, expr: ExprId) -> Option<VariantDef> {
+        self.variant_resolutions.get(&expr).copied()
+    }
     pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<ImplItem> {
         self.assoc_resolutions.get(&id.into()).copied()
     }
@@ -170,6 +174,7 @@ struct InferenceContext<'a, D: HirDatabase> {
     obligations: Vec<Obligation>,
     method_resolutions: FxHashMap<ExprId, Function>,
     field_resolutions: FxHashMap<ExprId, StructField>,
+    variant_resolutions: FxHashMap<ExprId, VariantDef>,
     assoc_resolutions: FxHashMap<ExprOrPatId, ImplItem>,
     type_of_expr: ArenaMap<ExprId, Ty>,
     type_of_pat: ArenaMap<PatId, Ty>,
@@ -183,6 +188,7 @@ fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self {
         InferenceContext {
             method_resolutions: FxHashMap::default(),
             field_resolutions: FxHashMap::default(),
+            variant_resolutions: FxHashMap::default(),
             assoc_resolutions: FxHashMap::default(),
             type_of_expr: ArenaMap::default(),
             type_of_pat: ArenaMap::default(),
@@ -213,6 +219,7 @@ fn resolve_all(mut self) -> InferenceResult {
         InferenceResult {
             method_resolutions: self.method_resolutions,
             field_resolutions: self.field_resolutions,
+            variant_resolutions: self.variant_resolutions,
             assoc_resolutions: self.assoc_resolutions,
             type_of_expr: expr_types,
             type_of_pat: pat_types,
@@ -232,6 +239,10 @@ fn write_field_resolution(&mut self, expr: ExprId, field: StructField) {
         self.field_resolutions.insert(expr, field);
     }
 
+    fn write_variant_resolution(&mut self, expr: ExprId, variant: VariantDef) {
+        self.variant_resolutions.insert(expr, variant);
+    }
+
     fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: ImplItem) {
         self.assoc_resolutions.insert(id, item);
     }
@@ -1069,6 +1080,10 @@ fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
             }
             Expr::StructLit { path, fields, spread } => {
                 let (ty, def_id) = self.resolve_variant(path.as_ref());
+                if let Some(variant) = def_id {
+                    self.write_variant_resolution(tgt_expr, variant);
+                }
+
                 let substs = ty.substs().unwrap_or_else(Substs::empty);
                 for (field_idx, field) in fields.iter().enumerate() {
                     let field_ty = def_id
index 35fb2111336a8ccfe044fb857a1cc3fabad3ff45..b6216f857d6453dc605d025417a61942ce871545 100644 (file)
@@ -1,28 +1,24 @@
-use hir::AdtDef;
+use hir::{Substs, Ty};
 
 use crate::completion::{CompletionContext, Completions};
 
 /// Complete fields in fields literals.
 pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) {
-    let ty = match ctx.struct_lit_syntax.and_then(|it| ctx.analyzer.type_of(ctx.db, it.into())) {
+    let (ty, variant) = match ctx.struct_lit_syntax.and_then(|it| {
+        Some((ctx.analyzer.type_of(ctx.db, it.into())?, ctx.analyzer.resolve_variant(it)?))
+    }) {
         Some(it) => it,
-        None => return,
-    };
-    let (adt, substs) = match ty.as_adt() {
-        Some(res) => res,
         _ => return,
     };
-    match adt {
-        AdtDef::Struct(s) => {
-            for field in s.fields(ctx.db) {
-                acc.add_field(ctx, field, substs);
-            }
-        }
 
-        // FIXME unions
-        AdtDef::Union(_) => (),
-        AdtDef::Enum(_) => (),
+    let ty_substs = match ty {
+        Ty::Apply(it) => it.parameters,
+        _ => Substs::empty(),
     };
+
+    for field in variant.fields(ctx.db) {
+        acc.add_field(ctx, field, &ty_substs);
+    }
 }
 
 #[cfg(test)]
@@ -57,4 +53,81 @@ fn foo() {
        ⋮]
         "###);
     }
+
+    #[test]
+    fn test_struct_literal_enum_variant() {
+        let completions = complete(
+            r"
+            enum E {
+                A { a: u32 }
+            }
+            fn foo() {
+                let _ = E::A { <|> }
+            }
+            ",
+        );
+        assert_debug_snapshot_matches!(completions, @r###"
+       ⋮[
+       ⋮    CompletionItem {
+       ⋮        label: "a",
+       ⋮        source_range: [119; 119),
+       ⋮        delete: [119; 119),
+       ⋮        insert: "a",
+       ⋮        kind: Field,
+       ⋮        detail: "u32",
+       ⋮    },
+       ⋮]
+        "###);
+    }
+
+    #[test]
+    fn test_struct_literal_two_structs() {
+        let completions = complete(
+            r"
+            struct A { a: u32 }
+            struct B { b: u32 }
+
+            fn foo() {
+               let _: A = B { <|> }
+            }
+            ",
+        );
+        assert_debug_snapshot_matches!(completions, @r###"
+       ⋮[
+       ⋮    CompletionItem {
+       ⋮        label: "b",
+       ⋮        source_range: [119; 119),
+       ⋮        delete: [119; 119),
+       ⋮        insert: "b",
+       ⋮        kind: Field,
+       ⋮        detail: "u32",
+       ⋮    },
+       ⋮]
+        "###);
+    }
+
+    #[test]
+    fn test_struct_literal_generic_struct() {
+        let completions = complete(
+            r"
+            struct A<T> { a: T }
+
+            fn foo() {
+               let _: A<u32> = A { <|> }
+            }
+            ",
+        );
+        assert_debug_snapshot_matches!(completions, @r###"
+       ⋮[
+       ⋮    CompletionItem {
+       ⋮        label: "a",
+       ⋮        source_range: [93; 93),
+       ⋮        delete: [93; 93),
+       ⋮        insert: "a",
+       ⋮        kind: Field,
+       ⋮        detail: "u32",
+       ⋮    },
+       ⋮]
+        "###);
+    }
 }