]> git.lizzy.rs Git - rust.git/blob - crates/hir-ty/src/infer/pat.rs
Auto merge of #13056 - DropDemBits:make-refactors, r=Veykril
[rust.git] / crates / hir-ty / src / infer / pat.rs
1 //! Type inference for patterns.
2
3 use std::iter::repeat_with;
4
5 use chalk_ir::Mutability;
6 use hir_def::{
7     expr::{BindingAnnotation, Expr, Literal, Pat, PatId},
8     path::Path,
9     type_ref::ConstScalar,
10 };
11 use hir_expand::name::Name;
12
13 use crate::{
14     consteval::intern_const_scalar,
15     infer::{BindingMode, Expectation, InferenceContext, TypeMismatch},
16     lower::lower_to_chalk_mutability,
17     primitive::UintTy,
18     static_lifetime, ConcreteConst, ConstValue, Interner, Scalar, Substitution, Ty, TyBuilder,
19     TyExt, TyKind,
20 };
21
22 use super::PatLike;
23
24 impl<'a> InferenceContext<'a> {
25     /// Infers type for tuple struct pattern or its corresponding assignee expression.
26     ///
27     /// Ellipses found in the original pattern or expression must be filtered out.
28     pub(super) fn infer_tuple_struct_pat_like<T: PatLike>(
29         &mut self,
30         path: Option<&Path>,
31         expected: &Ty,
32         default_bm: T::BindingMode,
33         id: T,
34         ellipsis: Option<usize>,
35         subs: &[T],
36     ) -> Ty {
37         let (ty, def) = self.resolve_variant(path, true);
38         let var_data = def.map(|it| it.variant_data(self.db.upcast()));
39         if let Some(variant) = def {
40             self.write_variant_resolution(id.into(), variant);
41         }
42         self.unify(&ty, expected);
43
44         let substs =
45             ty.as_adt().map(|(_, s)| s.clone()).unwrap_or_else(|| Substitution::empty(Interner));
46
47         let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
48         let (pre, post) = match ellipsis {
49             Some(idx) => subs.split_at(idx),
50             None => (subs, &[][..]),
51         };
52         let post_idx_offset = field_tys.iter().count().saturating_sub(post.len());
53
54         let pre_iter = pre.iter().enumerate();
55         let post_iter = (post_idx_offset..).zip(post.iter());
56         for (i, &subpat) in pre_iter.chain(post_iter) {
57             let expected_ty = var_data
58                 .as_ref()
59                 .and_then(|d| d.field(&Name::new_tuple_field(i)))
60                 .map_or(self.err_ty(), |field| {
61                     field_tys[field].clone().substitute(Interner, &substs)
62                 });
63             let expected_ty = self.normalize_associated_types_in(expected_ty);
64             T::infer(self, subpat, &expected_ty, default_bm);
65         }
66
67         ty
68     }
69
70     /// Infers type for record pattern or its corresponding assignee expression.
71     pub(super) fn infer_record_pat_like<T: PatLike>(
72         &mut self,
73         path: Option<&Path>,
74         expected: &Ty,
75         default_bm: T::BindingMode,
76         id: T,
77         subs: impl Iterator<Item = (Name, T)>,
78     ) -> Ty {
79         let (ty, def) = self.resolve_variant(path, false);
80         if let Some(variant) = def {
81             self.write_variant_resolution(id.into(), variant);
82         }
83
84         self.unify(&ty, expected);
85
86         let substs =
87             ty.as_adt().map(|(_, s)| s.clone()).unwrap_or_else(|| Substitution::empty(Interner));
88
89         let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
90         let var_data = def.map(|it| it.variant_data(self.db.upcast()));
91
92         for (name, inner) in subs {
93             let expected_ty = var_data
94                 .as_ref()
95                 .and_then(|it| it.field(&name))
96                 .map_or(self.err_ty(), |f| field_tys[f].clone().substitute(Interner, &substs));
97             let expected_ty = self.normalize_associated_types_in(expected_ty);
98
99             T::infer(self, inner, &expected_ty, default_bm);
100         }
101
102         ty
103     }
104
105     /// Infers type for tuple pattern or its corresponding assignee expression.
106     ///
107     /// Ellipses found in the original pattern or expression must be filtered out.
108     pub(super) fn infer_tuple_pat_like<T: PatLike>(
109         &mut self,
110         expected: &Ty,
111         default_bm: T::BindingMode,
112         ellipsis: Option<usize>,
113         subs: &[T],
114     ) -> Ty {
115         let expectations = match expected.as_tuple() {
116             Some(parameters) => &*parameters.as_slice(Interner),
117             _ => &[],
118         };
119
120         let ((pre, post), n_uncovered_patterns) = match ellipsis {
121             Some(idx) => (subs.split_at(idx), expectations.len().saturating_sub(subs.len())),
122             None => ((&subs[..], &[][..]), 0),
123         };
124         let mut expectations_iter = expectations
125             .iter()
126             .cloned()
127             .map(|a| a.assert_ty_ref(Interner).clone())
128             .chain(repeat_with(|| self.table.new_type_var()));
129
130         let mut inner_tys = Vec::with_capacity(n_uncovered_patterns + subs.len());
131
132         inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns + subs.len()));
133
134         // Process pre
135         for (ty, pat) in inner_tys.iter_mut().zip(pre) {
136             *ty = T::infer(self, *pat, ty, default_bm);
137         }
138
139         // Process post
140         for (ty, pat) in inner_tys.iter_mut().skip(pre.len() + n_uncovered_patterns).zip(post) {
141             *ty = T::infer(self, *pat, ty, default_bm);
142         }
143
144         TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys))
145             .intern(Interner)
146     }
147
148     pub(super) fn infer_pat(
149         &mut self,
150         pat: PatId,
151         expected: &Ty,
152         mut default_bm: BindingMode,
153     ) -> Ty {
154         let mut expected = self.resolve_ty_shallow(expected);
155
156         if is_non_ref_pat(&self.body, pat) {
157             let mut pat_adjustments = Vec::new();
158             while let Some((inner, _lifetime, mutability)) = expected.as_reference() {
159                 pat_adjustments.push(expected.clone());
160                 expected = self.resolve_ty_shallow(inner);
161                 default_bm = match default_bm {
162                     BindingMode::Move => BindingMode::Ref(mutability),
163                     BindingMode::Ref(Mutability::Not) => BindingMode::Ref(Mutability::Not),
164                     BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability),
165                 }
166             }
167
168             if !pat_adjustments.is_empty() {
169                 pat_adjustments.shrink_to_fit();
170                 self.result.pat_adjustments.insert(pat, pat_adjustments);
171             }
172         } else if let Pat::Ref { .. } = &self.body[pat] {
173             cov_mark::hit!(match_ergonomics_ref);
174             // When you encounter a `&pat` pattern, reset to Move.
175             // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
176             default_bm = BindingMode::Move;
177         }
178
179         // Lose mutability.
180         let default_bm = default_bm;
181         let expected = expected;
182
183         let ty = match &self.body[pat] {
184             Pat::Tuple { args, ellipsis } => {
185                 self.infer_tuple_pat_like(&expected, default_bm, *ellipsis, args)
186             }
187             Pat::Or(pats) => {
188                 if let Some((first_pat, rest)) = pats.split_first() {
189                     let ty = self.infer_pat(*first_pat, &expected, default_bm);
190                     for pat in rest {
191                         self.infer_pat(*pat, &expected, default_bm);
192                     }
193                     ty
194                 } else {
195                     self.err_ty()
196                 }
197             }
198             Pat::Ref { pat, mutability } => {
199                 let mutability = lower_to_chalk_mutability(*mutability);
200                 let expectation = match expected.as_reference() {
201                     Some((inner_ty, _lifetime, exp_mut)) => {
202                         if mutability != exp_mut {
203                             // FIXME: emit type error?
204                         }
205                         inner_ty.clone()
206                     }
207                     _ => self.result.standard_types.unknown.clone(),
208                 };
209                 let subty = self.infer_pat(*pat, &expectation, default_bm);
210                 TyKind::Ref(mutability, static_lifetime(), subty).intern(Interner)
211             }
212             Pat::TupleStruct { path: p, args: subpats, ellipsis } => self
213                 .infer_tuple_struct_pat_like(
214                     p.as_deref(),
215                     &expected,
216                     default_bm,
217                     pat,
218                     *ellipsis,
219                     subpats,
220                 ),
221             Pat::Record { path: p, args: fields, ellipsis: _ } => {
222                 let subs = fields.iter().map(|f| (f.name.clone(), f.pat));
223                 self.infer_record_pat_like(p.as_deref(), &expected, default_bm, pat.into(), subs)
224             }
225             Pat::Path(path) => {
226                 // FIXME use correct resolver for the surrounding expression
227                 let resolver = self.resolver.clone();
228                 self.infer_path(&resolver, path, pat.into()).unwrap_or_else(|| self.err_ty())
229             }
230             Pat::Bind { mode, name: _, subpat } => {
231                 let mode = if mode == &BindingAnnotation::Unannotated {
232                     default_bm
233                 } else {
234                     BindingMode::convert(*mode)
235                 };
236                 self.result.pat_binding_modes.insert(pat, mode);
237
238                 let inner_ty = match subpat {
239                     Some(subpat) => self.infer_pat(*subpat, &expected, default_bm),
240                     None => expected,
241                 };
242                 let inner_ty = self.insert_type_vars_shallow(inner_ty);
243
244                 let bound_ty = match mode {
245                     BindingMode::Ref(mutability) => {
246                         TyKind::Ref(mutability, static_lifetime(), inner_ty.clone())
247                             .intern(Interner)
248                     }
249                     BindingMode::Move => inner_ty.clone(),
250                 };
251                 self.write_pat_ty(pat, bound_ty);
252                 return inner_ty;
253             }
254             Pat::Slice { prefix, slice, suffix } => {
255                 let elem_ty = match expected.kind(Interner) {
256                     TyKind::Array(st, _) | TyKind::Slice(st) => st.clone(),
257                     _ => self.err_ty(),
258                 };
259
260                 for &pat_id in prefix.iter().chain(suffix.iter()) {
261                     self.infer_pat(pat_id, &elem_ty, default_bm);
262                 }
263
264                 if let &Some(slice_pat_id) = slice {
265                     let rest_pat_ty = match expected.kind(Interner) {
266                         TyKind::Array(_, length) => {
267                             let len = match length.data(Interner).value {
268                                 ConstValue::Concrete(ConcreteConst {
269                                     interned: ConstScalar::UInt(len),
270                                 }) => len.checked_sub((prefix.len() + suffix.len()) as u128),
271                                 _ => None,
272                             };
273                             TyKind::Array(
274                                 elem_ty.clone(),
275                                 intern_const_scalar(
276                                     len.map_or(ConstScalar::Unknown, |len| ConstScalar::UInt(len)),
277                                     TyBuilder::usize(),
278                                 ),
279                             )
280                         }
281                         _ => TyKind::Slice(elem_ty.clone()),
282                     }
283                     .intern(Interner);
284                     self.infer_pat(slice_pat_id, &rest_pat_ty, default_bm);
285                 }
286
287                 match expected.kind(Interner) {
288                     TyKind::Array(_, const_) => TyKind::Array(elem_ty, const_.clone()),
289                     _ => TyKind::Slice(elem_ty),
290                 }
291                 .intern(Interner)
292             }
293             Pat::Wild => expected.clone(),
294             Pat::Range { start, end } => {
295                 let start_ty = self.infer_expr(*start, &Expectation::has_type(expected.clone()));
296                 self.infer_expr(*end, &Expectation::has_type(start_ty))
297             }
298             &Pat::Lit(expr) => {
299                 // FIXME: using `Option` here is a workaround until we can use if-let chains in stable.
300                 let mut pat_ty = None;
301
302                 // Like slice patterns, byte string patterns can denote both `&[u8; N]` and `&[u8]`.
303                 if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] {
304                     if let Some((inner, ..)) = expected.as_reference() {
305                         let inner = self.resolve_ty_shallow(inner);
306                         if matches!(inner.kind(Interner), TyKind::Slice(_)) {
307                             let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
308                             let slice_ty = TyKind::Slice(elem_ty).intern(Interner);
309                             let ty = TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty)
310                                 .intern(Interner);
311                             self.write_expr_ty(expr, ty.clone());
312                             pat_ty = Some(ty);
313                         }
314                     }
315                 }
316
317                 pat_ty.unwrap_or_else(|| {
318                     self.infer_expr(expr, &Expectation::has_type(expected.clone()))
319                 })
320             }
321             Pat::Box { inner } => match self.resolve_boxed_box() {
322                 Some(box_adt) => {
323                     let (inner_ty, alloc_ty) = match expected.as_adt() {
324                         Some((adt, subst)) if adt == box_adt => (
325                             subst.at(Interner, 0).assert_ty_ref(Interner).clone(),
326                             subst.as_slice(Interner).get(1).and_then(|a| a.ty(Interner).cloned()),
327                         ),
328                         _ => (self.result.standard_types.unknown.clone(), None),
329                     };
330
331                     let inner_ty = self.infer_pat(*inner, &inner_ty, default_bm);
332                     let mut b = TyBuilder::adt(self.db, box_adt).push(inner_ty);
333
334                     if let Some(alloc_ty) = alloc_ty {
335                         b = b.push(alloc_ty);
336                     }
337                     b.fill_with_defaults(self.db, || self.table.new_type_var()).build()
338                 }
339                 None => self.err_ty(),
340             },
341             Pat::ConstBlock(expr) => {
342                 self.infer_expr(*expr, &Expectation::has_type(expected.clone()))
343             }
344             Pat::Missing => self.err_ty(),
345         };
346         // use a new type variable if we got error type here
347         let ty = self.insert_type_vars_shallow(ty);
348         if !self.unify(&ty, &expected) {
349             self.result
350                 .type_mismatches
351                 .insert(pat.into(), TypeMismatch { expected, actual: ty.clone() });
352         }
353         self.write_pat_ty(pat, ty.clone());
354         ty
355     }
356 }
357
358 fn is_non_ref_pat(body: &hir_def::body::Body, pat: PatId) -> bool {
359     match &body[pat] {
360         Pat::Tuple { .. }
361         | Pat::TupleStruct { .. }
362         | Pat::Record { .. }
363         | Pat::Range { .. }
364         | Pat::Slice { .. } => true,
365         Pat::Or(pats) => pats.iter().all(|p| is_non_ref_pat(body, *p)),
366         // FIXME: ConstBlock/Path/Lit might actually evaluate to ref, but inference is unimplemented.
367         Pat::Path(..) => true,
368         Pat::ConstBlock(..) => true,
369         Pat::Lit(expr) => {
370             !matches!(body[*expr], Expr::Literal(Literal::String(..) | Literal::ByteString(..)))
371         }
372         Pat::Bind {
373             mode: BindingAnnotation::Mutable | BindingAnnotation::Unannotated,
374             subpat: Some(subpat),
375             ..
376         } => is_non_ref_pat(body, *subpat),
377         Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Box { .. } | Pat::Missing => false,
378     }
379 }