]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/infer/pat.rs
Merge #8144
[rust.git] / crates / hir_ty / src / infer / pat.rs
1 //! Type inference for patterns.
2
3 use std::iter::repeat;
4 use std::sync::Arc;
5
6 use chalk_ir::Mutability;
7 use hir_def::{
8     expr::{BindingAnnotation, Expr, Literal, Pat, PatId, RecordFieldPat},
9     path::Path,
10     FieldId,
11 };
12 use hir_expand::name::Name;
13
14 use super::{BindingMode, Expectation, InferenceContext};
15 use crate::{
16     lower::lower_to_chalk_mutability,
17     utils::{generics, variant_data},
18     Interner, Substitution, Ty, TyKind,
19 };
20
21 impl<'a> InferenceContext<'a> {
22     fn infer_tuple_struct_pat(
23         &mut self,
24         path: Option<&Path>,
25         subpats: &[PatId],
26         expected: &Ty,
27         default_bm: BindingMode,
28         id: PatId,
29         ellipsis: Option<usize>,
30     ) -> Ty {
31         let (ty, def) = self.resolve_variant(path);
32         let var_data = def.map(|it| variant_data(self.db.upcast(), it));
33         if let Some(variant) = def {
34             self.write_variant_resolution(id.into(), variant);
35         }
36         self.unify(&ty, expected);
37
38         let substs = ty.substs().cloned().unwrap_or_else(Substitution::empty);
39
40         let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
41         let (pre, post) = match ellipsis {
42             Some(idx) => subpats.split_at(idx),
43             None => (subpats, &[][..]),
44         };
45         let post_idx_offset = field_tys.iter().count() - post.len();
46
47         let pre_iter = pre.iter().enumerate();
48         let post_iter = (post_idx_offset..).zip(post.iter());
49         for (i, &subpat) in pre_iter.chain(post_iter) {
50             let expected_ty = var_data
51                 .as_ref()
52                 .and_then(|d| d.field(&Name::new_tuple_field(i)))
53                 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
54             let expected_ty = self.normalize_associated_types_in(expected_ty);
55             self.infer_pat(subpat, &expected_ty, default_bm);
56         }
57
58         ty
59     }
60
61     fn infer_record_pat(
62         &mut self,
63         path: Option<&Path>,
64         subpats: &[RecordFieldPat],
65         expected: &Ty,
66         default_bm: BindingMode,
67         id: PatId,
68     ) -> Ty {
69         let (ty, def) = self.resolve_variant(path);
70         let var_data = def.map(|it| variant_data(self.db.upcast(), it));
71         if let Some(variant) = def {
72             self.write_variant_resolution(id.into(), variant);
73         }
74
75         self.unify(&ty, expected);
76
77         let substs = ty.substs().cloned().unwrap_or_else(Substitution::empty);
78
79         let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
80         for subpat in subpats {
81             let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name));
82             if let Some(local_id) = matching_field {
83                 let field_def = FieldId { parent: def.unwrap(), local_id };
84                 self.result.record_pat_field_resolutions.insert(subpat.pat, field_def);
85             }
86
87             let expected_ty = matching_field
88                 .map_or(self.err_ty(), |field| field_tys[field].clone().subst(&substs));
89             let expected_ty = self.normalize_associated_types_in(expected_ty);
90             self.infer_pat(subpat.pat, &expected_ty, default_bm);
91         }
92
93         ty
94     }
95
96     pub(super) fn infer_pat(
97         &mut self,
98         pat: PatId,
99         mut expected: &Ty,
100         mut default_bm: BindingMode,
101     ) -> Ty {
102         let body = Arc::clone(&self.body); // avoid borrow checker problem
103
104         if is_non_ref_pat(&body, pat) {
105             while let Some((inner, mutability)) = expected.as_reference() {
106                 expected = inner;
107                 default_bm = match default_bm {
108                     BindingMode::Move => BindingMode::Ref(mutability),
109                     BindingMode::Ref(Mutability::Not) => BindingMode::Ref(Mutability::Not),
110                     BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability),
111                 }
112             }
113         } else if let Pat::Ref { .. } = &body[pat] {
114             cov_mark::hit!(match_ergonomics_ref);
115             // When you encounter a `&pat` pattern, reset to Move.
116             // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
117             default_bm = BindingMode::Move;
118         }
119
120         // Lose mutability.
121         let default_bm = default_bm;
122         let expected = expected;
123
124         let ty = match &body[pat] {
125             &Pat::Tuple { ref args, ellipsis } => {
126                 let expectations = match expected.as_tuple() {
127                     Some(parameters) => &*parameters.0,
128                     _ => &[],
129                 };
130
131                 let (pre, post) = match ellipsis {
132                     Some(idx) => args.split_at(idx),
133                     None => (&args[..], &[][..]),
134                 };
135                 let n_uncovered_patterns = expectations.len().saturating_sub(args.len());
136                 let err_ty = self.err_ty();
137                 let mut expectations_iter = expectations.iter().chain(repeat(&err_ty));
138                 let mut infer_pat = |(&pat, ty)| self.infer_pat(pat, ty, default_bm);
139
140                 let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + args.len());
141                 inner_tys.extend(pre.iter().zip(expectations_iter.by_ref()).map(&mut infer_pat));
142                 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned());
143                 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat));
144
145                 TyKind::Tuple(inner_tys.len(), Substitution(inner_tys.into())).intern(&Interner)
146             }
147             Pat::Or(ref pats) => {
148                 if let Some((first_pat, rest)) = pats.split_first() {
149                     let ty = self.infer_pat(*first_pat, expected, default_bm);
150                     for pat in rest {
151                         self.infer_pat(*pat, expected, default_bm);
152                     }
153                     ty
154                 } else {
155                     self.err_ty()
156                 }
157             }
158             Pat::Ref { pat, mutability } => {
159                 let mutability = lower_to_chalk_mutability(*mutability);
160                 let expectation = match expected.as_reference() {
161                     Some((inner_ty, exp_mut)) => {
162                         if mutability != exp_mut {
163                             // FIXME: emit type error?
164                         }
165                         inner_ty.clone()
166                     }
167                     _ => self.result.standard_types.unknown.clone(),
168                 };
169                 let subty = self.infer_pat(*pat, &expectation, default_bm);
170                 TyKind::Ref(mutability, subty).intern(&Interner)
171             }
172             Pat::TupleStruct { path: p, args: subpats, ellipsis } => self.infer_tuple_struct_pat(
173                 p.as_ref(),
174                 subpats,
175                 expected,
176                 default_bm,
177                 pat,
178                 *ellipsis,
179             ),
180             Pat::Record { path: p, args: fields, ellipsis: _ } => {
181                 self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat)
182             }
183             Pat::Path(path) => {
184                 // FIXME use correct resolver for the surrounding expression
185                 let resolver = self.resolver.clone();
186                 self.infer_path(&resolver, &path, pat.into()).unwrap_or(self.err_ty())
187             }
188             Pat::Bind { mode, name: _, subpat } => {
189                 let mode = if mode == &BindingAnnotation::Unannotated {
190                     default_bm
191                 } else {
192                     BindingMode::convert(*mode)
193                 };
194                 let inner_ty = if let Some(subpat) = subpat {
195                     self.infer_pat(*subpat, expected, default_bm)
196                 } else {
197                     expected.clone()
198                 };
199                 let inner_ty = self.insert_type_vars_shallow(inner_ty);
200
201                 let bound_ty = match mode {
202                     BindingMode::Ref(mutability) => {
203                         TyKind::Ref(mutability, inner_ty.clone()).intern(&Interner)
204                     }
205                     BindingMode::Move => inner_ty.clone(),
206                 };
207                 let bound_ty = self.resolve_ty_as_possible(bound_ty);
208                 self.write_pat_ty(pat, bound_ty);
209                 return inner_ty;
210             }
211             Pat::Slice { prefix, slice, suffix } => {
212                 let (container_ty, elem_ty): (fn(_) -> _, _) = match expected.interned(&Interner) {
213                     TyKind::Array(st) => (TyKind::Array, st.clone()),
214                     TyKind::Slice(st) => (TyKind::Slice, st.clone()),
215                     _ => (TyKind::Slice, self.err_ty()),
216                 };
217
218                 for pat_id in prefix.iter().chain(suffix) {
219                     self.infer_pat(*pat_id, &elem_ty, default_bm);
220                 }
221
222                 let pat_ty = container_ty(elem_ty).intern(&Interner);
223                 if let Some(slice_pat_id) = slice {
224                     self.infer_pat(*slice_pat_id, &pat_ty, default_bm);
225                 }
226
227                 pat_ty
228             }
229             Pat::Wild => expected.clone(),
230             Pat::Range { start, end } => {
231                 let start_ty = self.infer_expr(*start, &Expectation::has_type(expected.clone()));
232                 let end_ty = self.infer_expr(*end, &Expectation::has_type(start_ty));
233                 end_ty
234             }
235             Pat::Lit(expr) => self.infer_expr(*expr, &Expectation::has_type(expected.clone())),
236             Pat::Box { inner } => match self.resolve_boxed_box() {
237                 Some(box_adt) => {
238                     let (inner_ty, alloc_ty) = match expected.as_adt() {
239                         Some((adt, subst)) if adt == box_adt => {
240                             (subst[0].clone(), subst.get(1).cloned())
241                         }
242                         _ => (self.result.standard_types.unknown.clone(), None),
243                     };
244
245                     let inner_ty = self.infer_pat(*inner, &inner_ty, default_bm);
246                     let mut sb = Substitution::build_for_generics(&generics(
247                         self.db.upcast(),
248                         box_adt.into(),
249                     ));
250                     sb = sb.push(inner_ty);
251                     if sb.remaining() == 1 {
252                         sb = sb.push(match alloc_ty {
253                             Some(alloc_ty) if !alloc_ty.is_unknown() => alloc_ty,
254                             _ => match self.db.generic_defaults(box_adt.into()).get(1) {
255                                 Some(alloc_ty) if !alloc_ty.value.is_unknown() => {
256                                     alloc_ty.value.clone()
257                                 }
258                                 _ => self.table.new_type_var(),
259                             },
260                         });
261                     }
262                     Ty::adt_ty(box_adt, sb.build())
263                 }
264                 None => self.err_ty(),
265             },
266             Pat::ConstBlock(expr) => {
267                 self.infer_expr(*expr, &Expectation::has_type(expected.clone()))
268             }
269             Pat::Missing => self.err_ty(),
270         };
271         // use a new type variable if we got error type here
272         let ty = self.insert_type_vars_shallow(ty);
273         if !self.unify(&ty, expected) {
274             // FIXME record mismatch, we need to change the type of self.type_mismatches for that
275         }
276         let ty = self.resolve_ty_as_possible(ty);
277         self.write_pat_ty(pat, ty.clone());
278         ty
279     }
280 }
281
282 fn is_non_ref_pat(body: &hir_def::body::Body, pat: PatId) -> bool {
283     match &body[pat] {
284         Pat::Tuple { .. }
285         | Pat::TupleStruct { .. }
286         | Pat::Record { .. }
287         | Pat::Range { .. }
288         | Pat::Slice { .. } => true,
289         Pat::Or(pats) => pats.iter().all(|p| is_non_ref_pat(body, *p)),
290         // FIXME: ConstBlock/Path/Lit might actually evaluate to ref, but inference is unimplemented.
291         Pat::Path(..) => true,
292         Pat::ConstBlock(..) => true,
293         Pat::Lit(expr) => match body[*expr] {
294             Expr::Literal(Literal::String(..)) => false,
295             _ => true,
296         },
297         Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Box { .. } | Pat::Missing => false,
298     }
299 }