aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorEkaterina Babshukova <[email protected]>2019-07-21 12:11:45 +0100
committerEkaterina Babshukova <[email protected]>2019-07-21 12:41:33 +0100
commit5fe19d2fbd2daa05b2cd3b1ebb6fa926e9d86c36 (patch)
tree8d0e74c6c5a734fc64edf2504aabfd11c09354c4 /crates
parent7bde8012cb28c44de7ffc779003781d385323808 (diff)
provide completion in struct patterns
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_hir/src/source_binder.rs9
-rw-r--r--crates/ra_hir/src/ty.rs2
-rw-r--r--crates/ra_hir/src/ty/infer.rs22
-rw-r--r--crates/ra_ide_api/src/completion.rs2
-rw-r--r--crates/ra_ide_api/src/completion/complete_struct_literal.rs15
-rw-r--r--crates/ra_ide_api/src/completion/complete_struct_pattern.rs94
-rw-r--r--crates/ra_ide_api/src/completion/completion_context.rs11
7 files changed, 134 insertions, 21 deletions
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 4c173a4f7..fc9bc33d2 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -266,9 +266,14 @@ impl SourceAnalyzer {
266 self.infer.as_ref()?.field_resolution(expr_id) 266 self.infer.as_ref()?.field_resolution(expr_id)
267 } 267 }
268 268
269 pub fn resolve_variant(&self, struct_lit: &ast::StructLit) -> Option<crate::VariantDef> { 269 pub fn resolve_struct_literal(&self, struct_lit: &ast::StructLit) -> Option<crate::VariantDef> {
270 let expr_id = self.body_source_map.as_ref()?.node_expr(&struct_lit.clone().into())?; 270 let expr_id = self.body_source_map.as_ref()?.node_expr(&struct_lit.clone().into())?;
271 self.infer.as_ref()?.variant_resolution(expr_id) 271 self.infer.as_ref()?.variant_resolution_for_expr(expr_id)
272 }
273
274 pub fn resolve_struct_pattern(&self, struct_pat: &ast::StructPat) -> Option<crate::VariantDef> {
275 let pat_id = self.body_source_map.as_ref()?.node_pat(&struct_pat.clone().into())?;
276 self.infer.as_ref()?.variant_resolution_for_pat(pat_id)
272 } 277 }
273 278
274 pub fn resolve_macro_call( 279 pub fn resolve_macro_call(
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index 4cf714f5d..82589e504 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -472,7 +472,7 @@ impl Ty {
472 472
473 /// Returns the type parameters of this type if it has some (i.e. is an ADT 473 /// Returns the type parameters of this type if it has some (i.e. is an ADT
474 /// or function); so if `self` is `Option<u32>`, this returns the `u32`. 474 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
475 fn substs(&self) -> Option<Substs> { 475 pub fn substs(&self) -> Option<Substs> {
476 match self { 476 match self {
477 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), 477 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
478 _ => None, 478 _ => None,
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs
index a82dff711..594c5bc79 100644
--- a/crates/ra_hir/src/ty/infer.rs
+++ b/crates/ra_hir/src/ty/infer.rs
@@ -113,7 +113,8 @@ pub struct InferenceResult {
113 method_resolutions: FxHashMap<ExprId, Function>, 113 method_resolutions: FxHashMap<ExprId, Function>,
114 /// For each field access expr, records the field it resolves to. 114 /// For each field access expr, records the field it resolves to.
115 field_resolutions: FxHashMap<ExprId, StructField>, 115 field_resolutions: FxHashMap<ExprId, StructField>,
116 variant_resolutions: FxHashMap<ExprId, VariantDef>, 116 /// For each struct literal, records the variant it resolves to.
117 variant_resolutions: FxHashMap<ExprOrPatId, VariantDef>,
117 /// For each associated item record what it resolves to 118 /// For each associated item record what it resolves to
118 assoc_resolutions: FxHashMap<ExprOrPatId, ImplItem>, 119 assoc_resolutions: FxHashMap<ExprOrPatId, ImplItem>,
119 diagnostics: Vec<InferenceDiagnostic>, 120 diagnostics: Vec<InferenceDiagnostic>,
@@ -128,8 +129,11 @@ impl InferenceResult {
128 pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> { 129 pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> {
129 self.field_resolutions.get(&expr).copied() 130 self.field_resolutions.get(&expr).copied()
130 } 131 }
131 pub fn variant_resolution(&self, expr: ExprId) -> Option<VariantDef> { 132 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantDef> {
132 self.variant_resolutions.get(&expr).copied() 133 self.variant_resolutions.get(&id.into()).copied()
134 }
135 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantDef> {
136 self.variant_resolutions.get(&id.into()).copied()
133 } 137 }
134 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<ImplItem> { 138 pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<ImplItem> {
135 self.assoc_resolutions.get(&id.into()).copied() 139 self.assoc_resolutions.get(&id.into()).copied()
@@ -218,8 +222,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
218 self.result.field_resolutions.insert(expr, field); 222 self.result.field_resolutions.insert(expr, field);
219 } 223 }
220 224
221 fn write_variant_resolution(&mut self, expr: ExprId, variant: VariantDef) { 225 fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantDef) {
222 self.result.variant_resolutions.insert(expr, variant); 226 self.result.variant_resolutions.insert(id, variant);
223 } 227 }
224 228
225 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: ImplItem) { 229 fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: ImplItem) {
@@ -678,8 +682,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
678 subpats: &[FieldPat], 682 subpats: &[FieldPat],
679 expected: &Ty, 683 expected: &Ty,
680 default_bm: BindingMode, 684 default_bm: BindingMode,
685 id: PatId,
681 ) -> Ty { 686 ) -> Ty {
682 let (ty, def) = self.resolve_variant(path); 687 let (ty, def) = self.resolve_variant(path);
688 if let Some(variant) = def {
689 self.write_variant_resolution(id.into(), variant);
690 }
683 691
684 self.unify(&ty, expected); 692 self.unify(&ty, expected);
685 693
@@ -762,7 +770,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
762 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) 770 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm)
763 } 771 }
764 Pat::Struct { path: ref p, args: ref fields } => { 772 Pat::Struct { path: ref p, args: ref fields } => {
765 self.infer_struct_pat(p.as_ref(), fields, expected, default_bm) 773 self.infer_struct_pat(p.as_ref(), fields, expected, default_bm, pat)
766 } 774 }
767 Pat::Path(path) => { 775 Pat::Path(path) => {
768 // FIXME use correct resolver for the surrounding expression 776 // FIXME use correct resolver for the surrounding expression
@@ -1064,7 +1072,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1064 Expr::StructLit { path, fields, spread } => { 1072 Expr::StructLit { path, fields, spread } => {
1065 let (ty, def_id) = self.resolve_variant(path.as_ref()); 1073 let (ty, def_id) = self.resolve_variant(path.as_ref());
1066 if let Some(variant) = def_id { 1074 if let Some(variant) = def_id {
1067 self.write_variant_resolution(tgt_expr, variant); 1075 self.write_variant_resolution(tgt_expr.into(), variant);
1068 } 1076 }
1069 1077
1070 let substs = ty.substs().unwrap_or_else(Substs::empty); 1078 let substs = ty.substs().unwrap_or_else(Substs::empty);
diff --git a/crates/ra_ide_api/src/completion.rs b/crates/ra_ide_api/src/completion.rs
index c23b5da59..85160358a 100644
--- a/crates/ra_ide_api/src/completion.rs
+++ b/crates/ra_ide_api/src/completion.rs
@@ -4,6 +4,7 @@ mod presentation;
4 4
5mod complete_dot; 5mod complete_dot;
6mod complete_struct_literal; 6mod complete_struct_literal;
7mod complete_struct_pattern;
7mod complete_pattern; 8mod complete_pattern;
8mod complete_fn_param; 9mod complete_fn_param;
9mod complete_keyword; 10mod complete_keyword;
@@ -65,6 +66,7 @@ pub(crate) fn completions(db: &db::RootDatabase, position: FilePosition) -> Opti
65 complete_scope::complete_scope(&mut acc, &ctx); 66 complete_scope::complete_scope(&mut acc, &ctx);
66 complete_dot::complete_dot(&mut acc, &ctx); 67 complete_dot::complete_dot(&mut acc, &ctx);
67 complete_struct_literal::complete_struct_literal(&mut acc, &ctx); 68 complete_struct_literal::complete_struct_literal(&mut acc, &ctx);
69 complete_struct_pattern::complete_struct_pattern(&mut acc, &ctx);
68 complete_pattern::complete_pattern(&mut acc, &ctx); 70 complete_pattern::complete_pattern(&mut acc, &ctx);
69 complete_postfix::complete_postfix(&mut acc, &ctx); 71 complete_postfix::complete_postfix(&mut acc, &ctx);
70 Some(acc) 72 Some(acc)
diff --git a/crates/ra_ide_api/src/completion/complete_struct_literal.rs b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
index 9410f740f..6aa41f498 100644
--- a/crates/ra_ide_api/src/completion/complete_struct_literal.rs
+++ b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
@@ -1,23 +1,22 @@
1use hir::{Substs, Ty}; 1use hir::Substs;
2 2
3use crate::completion::{CompletionContext, Completions}; 3use crate::completion::{CompletionContext, Completions};
4 4
5/// Complete fields in fields literals. 5/// Complete fields in fields literals.
6pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) { 6pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionContext) {
7 let (ty, variant) = match ctx.struct_lit_syntax.as_ref().and_then(|it| { 7 let (ty, variant) = match ctx.struct_lit_syntax.as_ref().and_then(|it| {
8 Some((ctx.analyzer.type_of(ctx.db, &it.clone().into())?, ctx.analyzer.resolve_variant(it)?)) 8 Some((
9 ctx.analyzer.type_of(ctx.db, &it.clone().into())?,
10 ctx.analyzer.resolve_struct_literal(it)?,
11 ))
9 }) { 12 }) {
10 Some(it) => it, 13 Some(it) => it,
11 _ => return, 14 _ => return,
12 }; 15 };
13 16 let substs = &ty.substs().unwrap_or_else(Substs::empty);
14 let ty_substs = match ty {
15 Ty::Apply(it) => it.parameters,
16 _ => Substs::empty(),
17 };
18 17
19 for field in variant.fields(ctx.db) { 18 for field in variant.fields(ctx.db) {
20 acc.add_field(ctx, field, &ty_substs); 19 acc.add_field(ctx, field, substs);
21 } 20 }
22} 21}
23 22
diff --git a/crates/ra_ide_api/src/completion/complete_struct_pattern.rs b/crates/ra_ide_api/src/completion/complete_struct_pattern.rs
new file mode 100644
index 000000000..d0dde5930
--- /dev/null
+++ b/crates/ra_ide_api/src/completion/complete_struct_pattern.rs
@@ -0,0 +1,94 @@
1use hir::Substs;
2
3use crate::completion::{CompletionContext, Completions};
4
5pub(super) fn complete_struct_pattern(acc: &mut Completions, ctx: &CompletionContext) {
6 let (ty, variant) = match ctx.struct_lit_pat.as_ref().and_then(|it| {
7 Some((
8 ctx.analyzer.type_of_pat(ctx.db, &it.clone().into())?,
9 ctx.analyzer.resolve_struct_pattern(it)?,
10 ))
11 }) {
12 Some(it) => it,
13 _ => return,
14 };
15 let substs = &ty.substs().unwrap_or_else(Substs::empty);
16
17 for field in variant.fields(ctx.db) {
18 acc.add_field(ctx, field, substs);
19 }
20}
21
22#[cfg(test)]
23mod tests {
24 use crate::completion::{do_completion, CompletionItem, CompletionKind};
25 use insta::assert_debug_snapshot_matches;
26
27 fn complete(code: &str) -> Vec<CompletionItem> {
28 do_completion(code, CompletionKind::Reference)
29 }
30
31 #[test]
32 fn test_struct_pattern_field() {
33 let completions = complete(
34 r"
35 struct S { foo: u32 }
36
37 fn process(f: S) {
38 match f {
39 S { f<|>: 92 } => (),
40 }
41 }
42 ",
43 );
44 assert_debug_snapshot_matches!(completions, @r###"
45 ⋮[
46 ⋮ CompletionItem {
47 ⋮ label: "foo",
48 ⋮ source_range: [117; 118),
49 ⋮ delete: [117; 118),
50 ⋮ insert: "foo",
51 ⋮ kind: Field,
52 ⋮ detail: "u32",
53 ⋮ },
54 ⋮]
55 "###);
56 }
57
58 #[test]
59 fn test_struct_pattern_enum_variant() {
60 let completions = complete(
61 r"
62 enum E {
63 S { foo: u32, bar: () }
64 }
65
66 fn process(e: E) {
67 match e {
68 E::S { <|> } => (),
69 }
70 }
71 ",
72 );
73 assert_debug_snapshot_matches!(completions, @r###"
74 ⋮[
75 ⋮ CompletionItem {
76 ⋮ label: "bar",
77 ⋮ source_range: [161; 161),
78 ⋮ delete: [161; 161),
79 ⋮ insert: "bar",
80 ⋮ kind: Field,
81 ⋮ detail: "()",
82 ⋮ },
83 ⋮ CompletionItem {
84 ⋮ label: "foo",
85 ⋮ source_range: [161; 161),
86 ⋮ delete: [161; 161),
87 ⋮ insert: "foo",
88 ⋮ kind: Field,
89 ⋮ detail: "u32",
90 ⋮ },
91 ⋮]
92 "###);
93 }
94}
diff --git a/crates/ra_ide_api/src/completion/completion_context.rs b/crates/ra_ide_api/src/completion/completion_context.rs
index 2f78d5409..6fee7b5be 100644
--- a/crates/ra_ide_api/src/completion/completion_context.rs
+++ b/crates/ra_ide_api/src/completion/completion_context.rs
@@ -21,6 +21,7 @@ pub(crate) struct CompletionContext<'a> {
21 pub(super) function_syntax: Option<ast::FnDef>, 21 pub(super) function_syntax: Option<ast::FnDef>,
22 pub(super) use_item_syntax: Option<ast::UseItem>, 22 pub(super) use_item_syntax: Option<ast::UseItem>,
23 pub(super) struct_lit_syntax: Option<ast::StructLit>, 23 pub(super) struct_lit_syntax: Option<ast::StructLit>,
24 pub(super) struct_lit_pat: Option<ast::StructPat>,
24 pub(super) is_param: bool, 25 pub(super) is_param: bool,
25 /// If a name-binding or reference to a const in a pattern. 26 /// If a name-binding or reference to a const in a pattern.
26 /// Irrefutable patterns (like let) are excluded. 27 /// Irrefutable patterns (like let) are excluded.
@@ -60,6 +61,7 @@ impl<'a> CompletionContext<'a> {
60 function_syntax: None, 61 function_syntax: None,
61 use_item_syntax: None, 62 use_item_syntax: None,
62 struct_lit_syntax: None, 63 struct_lit_syntax: None,
64 struct_lit_pat: None,
63 is_param: false, 65 is_param: false,
64 is_pat_binding: false, 66 is_pat_binding: false,
65 is_trivial_path: false, 67 is_trivial_path: false,
@@ -106,8 +108,7 @@ impl<'a> CompletionContext<'a> {
106 // Otherwise, see if this is a declaration. We can use heuristics to 108 // Otherwise, see if this is a declaration. We can use heuristics to
107 // suggest declaration names, see `CompletionKind::Magic`. 109 // suggest declaration names, see `CompletionKind::Magic`.
108 if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) { 110 if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) {
109 if is_node::<ast::BindPat>(name.syntax()) { 111 if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::BindPat::cast) {
110 let bind_pat = name.syntax().ancestors().find_map(ast::BindPat::cast).unwrap();
111 let parent = bind_pat.syntax().parent(); 112 let parent = bind_pat.syntax().parent();
112 if parent.clone().and_then(ast::MatchArm::cast).is_some() 113 if parent.clone().and_then(ast::MatchArm::cast).is_some()
113 || parent.and_then(ast::Condition::cast).is_some() 114 || parent.and_then(ast::Condition::cast).is_some()
@@ -119,6 +120,10 @@ impl<'a> CompletionContext<'a> {
119 self.is_param = true; 120 self.is_param = true;
120 return; 121 return;
121 } 122 }
123 if name.syntax().ancestors().find_map(ast::FieldPatList::cast).is_some() {
124 self.struct_lit_pat =
125 find_node_at_offset(original_parse.tree().syntax(), self.offset);
126 }
122 } 127 }
123 } 128 }
124 129
@@ -235,7 +240,7 @@ fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Op
235} 240}
236 241
237fn is_node<N: AstNode>(node: &SyntaxNode) -> bool { 242fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
238 match node.ancestors().filter_map(N::cast).next() { 243 match node.ancestors().find_map(N::cast) {
239 None => false, 244 None => false,
240 Some(n) => n.syntax().text_range() == node.text_range(), 245 Some(n) => n.syntax().text_range() == node.text_range(),
241 } 246 }