]>
Commit | Line | Data |
---|---|---|
c30ab7b3 SL |
1 | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
11 | use self::Constructor::*; | |
12 | use self::Usefulness::*; | |
13 | use self::WitnessPreference::*; | |
14 | ||
15 | use rustc::middle::const_val::ConstVal; | |
16 | use eval::{compare_const_vals}; | |
17 | ||
18 | use rustc_const_math::ConstInt; | |
19 | ||
8bb4bdeb | 20 | use rustc_data_structures::fx::FxHashMap; |
c30ab7b3 SL |
21 | use rustc_data_structures::indexed_vec::Idx; |
22 | ||
23 | use pattern::{FieldPattern, Pattern, PatternKind}; | |
24 | use pattern::{PatternFoldable, PatternFolder}; | |
25 | ||
476ff2be | 26 | use rustc::hir::def_id::DefId; |
32a655c1 | 27 | use rustc::hir::RangeEnd; |
abe05a73 | 28 | use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; |
c30ab7b3 | 29 | |
32a655c1 | 30 | use rustc::mir::Field; |
c30ab7b3 SL |
31 | use rustc::util::common::ErrorReported; |
32 | ||
c30ab7b3 SL |
33 | use syntax_pos::{Span, DUMMY_SP}; |
34 | ||
35 | use arena::TypedArena; | |
36 | ||
476ff2be | 37 | use std::cmp::{self, Ordering}; |
c30ab7b3 SL |
38 | use std::fmt; |
39 | use std::iter::{FromIterator, IntoIterator, repeat}; | |
40 | ||
41 | pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>) | |
42 | -> &'a Pattern<'tcx> | |
43 | { | |
44 | cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat)) | |
45 | } | |
46 | ||
47 | struct LiteralExpander; | |
48 | impl<'tcx> PatternFolder<'tcx> for LiteralExpander { | |
49 | fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> { | |
50 | match (&pat.ty.sty, &*pat.kind) { | |
51 | (&ty::TyRef(_, mt), &PatternKind::Constant { ref value }) => { | |
52 | Pattern { | |
53 | ty: pat.ty, | |
54 | span: pat.span, | |
55 | kind: box PatternKind::Deref { | |
56 | subpattern: Pattern { | |
57 | ty: mt.ty, | |
58 | span: pat.span, | |
59 | kind: box PatternKind::Constant { value: value.clone() }, | |
60 | } | |
61 | } | |
62 | } | |
63 | } | |
64 | (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => { | |
65 | s.fold_with(self) | |
66 | } | |
67 | _ => pat.super_fold_with(self) | |
68 | } | |
69 | } | |
70 | } | |
71 | ||
c30ab7b3 SL |
72 | impl<'tcx> Pattern<'tcx> { |
73 | fn is_wildcard(&self) -> bool { | |
74 | match *self.kind { | |
75 | PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild => | |
76 | true, | |
77 | _ => false | |
78 | } | |
79 | } | |
80 | } | |
81 | ||
82 | pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>); | |
83 | ||
84 | impl<'a, 'tcx> Matrix<'a, 'tcx> { | |
85 | pub fn empty() -> Self { | |
86 | Matrix(vec![]) | |
87 | } | |
88 | ||
89 | pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) { | |
90 | self.0.push(row) | |
91 | } | |
92 | } | |
93 | ||
94 | /// Pretty-printer for matrices of patterns, example: | |
95 | /// ++++++++++++++++++++++++++ | |
96 | /// + _ + [] + | |
97 | /// ++++++++++++++++++++++++++ | |
98 | /// + true + [First] + | |
99 | /// ++++++++++++++++++++++++++ | |
100 | /// + true + [Second(true)] + | |
101 | /// ++++++++++++++++++++++++++ | |
102 | /// + false + [_] + | |
103 | /// ++++++++++++++++++++++++++ | |
104 | /// + _ + [_, _, ..tail] + | |
105 | /// ++++++++++++++++++++++++++ | |
106 | impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> { | |
107 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
108 | write!(f, "\n")?; | |
109 | ||
110 | let &Matrix(ref m) = self; | |
111 | let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| { | |
112 | row.iter().map(|pat| format!("{:?}", pat)).collect() | |
113 | }).collect(); | |
114 | ||
115 | let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0); | |
116 | assert!(m.iter().all(|row| row.len() == column_count)); | |
117 | let column_widths: Vec<usize> = (0..column_count).map(|col| { | |
118 | pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0) | |
119 | }).collect(); | |
120 | ||
121 | let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1; | |
122 | let br = repeat('+').take(total_width).collect::<String>(); | |
123 | write!(f, "{}\n", br)?; | |
124 | for row in pretty_printed_matrix { | |
125 | write!(f, "+")?; | |
126 | for (column, pat_str) in row.into_iter().enumerate() { | |
127 | write!(f, " ")?; | |
128 | write!(f, "{:1$}", pat_str, column_widths[column])?; | |
129 | write!(f, " +")?; | |
130 | } | |
131 | write!(f, "\n")?; | |
132 | write!(f, "{}\n", br)?; | |
133 | } | |
134 | Ok(()) | |
135 | } | |
136 | } | |
137 | ||
138 | impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> { | |
139 | fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self | |
140 | { | |
141 | Matrix(iter.into_iter().collect()) | |
142 | } | |
143 | } | |
144 | ||
145 | //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv | |
146 | pub struct MatchCheckCtxt<'a, 'tcx: 'a> { | |
147 | pub tcx: TyCtxt<'a, 'tcx, 'tcx>, | |
32a655c1 SL |
148 | /// The module in which the match occurs. This is necessary for |
149 | /// checking inhabited-ness of types because whether a type is (visibly) | |
150 | /// inhabited can depend on whether it was defined in the current module or | |
151 | /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty | |
152 | /// outside it's module and should not be matchable with an empty match | |
153 | /// statement. | |
154 | pub module: DefId, | |
c30ab7b3 | 155 | pub pattern_arena: &'a TypedArena<Pattern<'tcx>>, |
476ff2be | 156 | pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>, |
c30ab7b3 SL |
157 | } |
158 | ||
159 | impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { | |
160 | pub fn create_and_enter<F, R>( | |
161 | tcx: TyCtxt<'a, 'tcx, 'tcx>, | |
32a655c1 | 162 | module: DefId, |
c30ab7b3 SL |
163 | f: F) -> R |
164 | where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R | |
165 | { | |
c30ab7b3 SL |
166 | let pattern_arena = TypedArena::new(); |
167 | ||
168 | f(MatchCheckCtxt { | |
3b2f2976 XL |
169 | tcx, |
170 | module, | |
c30ab7b3 | 171 | pattern_arena: &pattern_arena, |
476ff2be | 172 | byte_array_map: FxHashMap(), |
c30ab7b3 SL |
173 | }) |
174 | } | |
175 | ||
176 | // convert a byte-string pattern to a list of u8 patterns. | |
32a655c1 SL |
177 | fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>> |
178 | where 'a: 'p | |
179 | { | |
c30ab7b3 SL |
180 | let pattern_arena = &*self.pattern_arena; |
181 | let tcx = self.tcx; | |
182 | self.byte_array_map.entry(pat).or_insert_with(|| { | |
183 | match pat.kind { | |
184 | box PatternKind::Constant { | |
ea8adc8c | 185 | value: &ty::Const { val: ConstVal::ByteStr(b), .. } |
c30ab7b3 | 186 | } => { |
ea8adc8c | 187 | b.data.iter().map(|&b| &*pattern_arena.alloc(Pattern { |
c30ab7b3 SL |
188 | ty: tcx.types.u8, |
189 | span: pat.span, | |
190 | kind: box PatternKind::Constant { | |
ea8adc8c XL |
191 | value: tcx.mk_const(ty::Const { |
192 | val: ConstVal::Integral(ConstInt::U8(b)), | |
193 | ty: tcx.types.u8 | |
194 | }) | |
c30ab7b3 SL |
195 | } |
196 | })).collect() | |
197 | } | |
198 | _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat) | |
199 | } | |
200 | }).clone() | |
201 | } | |
32a655c1 SL |
202 | |
203 | fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool { | |
204 | if self.tcx.sess.features.borrow().never_type { | |
abe05a73 | 205 | self.tcx.is_ty_uninhabited_from(self.module, ty) |
32a655c1 SL |
206 | } else { |
207 | false | |
208 | } | |
209 | } | |
210 | ||
abe05a73 XL |
211 | fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool { |
212 | match ty.sty { | |
213 | ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(), | |
214 | _ => false, | |
215 | } | |
216 | } | |
217 | ||
218 | fn is_local(&self, ty: Ty<'tcx>) -> bool { | |
219 | match ty.sty { | |
220 | ty::TyAdt(adt_def, ..) => adt_def.did.is_local(), | |
221 | _ => false, | |
222 | } | |
223 | } | |
224 | ||
32a655c1 SL |
225 | fn is_variant_uninhabited(&self, |
226 | variant: &'tcx ty::VariantDef, | |
abe05a73 XL |
227 | substs: &'tcx ty::subst::Substs<'tcx>) |
228 | -> bool | |
32a655c1 SL |
229 | { |
230 | if self.tcx.sess.features.borrow().never_type { | |
abe05a73 | 231 | self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs) |
32a655c1 SL |
232 | } else { |
233 | false | |
234 | } | |
235 | } | |
c30ab7b3 SL |
236 | } |
237 | ||
238 | #[derive(Clone, Debug, PartialEq)] | |
8bb4bdeb | 239 | pub enum Constructor<'tcx> { |
c30ab7b3 SL |
240 | /// The constructor of all patterns that don't vary by constructor, |
241 | /// e.g. struct patterns and fixed-length arrays. | |
242 | Single, | |
243 | /// Enum variants. | |
244 | Variant(DefId), | |
245 | /// Literal values. | |
ea8adc8c | 246 | ConstantValue(&'tcx ty::Const<'tcx>), |
32a655c1 | 247 | /// Ranges of literal values (`2...5` and `2..5`). |
ea8adc8c | 248 | ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd), |
c30ab7b3 | 249 | /// Array patterns of length n. |
ea8adc8c | 250 | Slice(u64), |
c30ab7b3 SL |
251 | } |
252 | ||
8bb4bdeb | 253 | impl<'tcx> Constructor<'tcx> { |
32a655c1 | 254 | fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize { |
c30ab7b3 | 255 | match self { |
32a655c1 | 256 | &Variant(vid) => adt.variant_index_with_id(vid), |
c30ab7b3 SL |
257 | &Single => { |
258 | assert_eq!(adt.variants.len(), 1); | |
32a655c1 | 259 | 0 |
c30ab7b3 SL |
260 | } |
261 | _ => bug!("bad constructor {:?} for adt {:?}", self, adt) | |
262 | } | |
263 | } | |
264 | } | |
265 | ||
32a655c1 SL |
266 | #[derive(Clone)] |
267 | pub enum Usefulness<'tcx> { | |
c30ab7b3 | 268 | Useful, |
32a655c1 | 269 | UsefulWithWitness(Vec<Witness<'tcx>>), |
c30ab7b3 SL |
270 | NotUseful |
271 | } | |
272 | ||
32a655c1 SL |
273 | impl<'tcx> Usefulness<'tcx> { |
274 | fn is_useful(&self) -> bool { | |
275 | match *self { | |
276 | NotUseful => false, | |
277 | _ => true | |
278 | } | |
279 | } | |
280 | } | |
281 | ||
c30ab7b3 SL |
282 | #[derive(Copy, Clone)] |
283 | pub enum WitnessPreference { | |
284 | ConstructWitness, | |
285 | LeaveOutWitness | |
286 | } | |
287 | ||
288 | #[derive(Copy, Clone, Debug)] | |
289 | struct PatternContext<'tcx> { | |
290 | ty: Ty<'tcx>, | |
ea8adc8c | 291 | max_slice_length: u64, |
c30ab7b3 SL |
292 | } |
293 | ||
c30ab7b3 | 294 | /// A stack of patterns in reverse order of construction |
32a655c1 SL |
295 | #[derive(Clone)] |
296 | pub struct Witness<'tcx>(Vec<Pattern<'tcx>>); | |
c30ab7b3 | 297 | |
32a655c1 SL |
298 | impl<'tcx> Witness<'tcx> { |
299 | pub fn single_pattern(&self) -> &Pattern<'tcx> { | |
c30ab7b3 SL |
300 | assert_eq!(self.0.len(), 1); |
301 | &self.0[0] | |
302 | } | |
303 | ||
32a655c1 | 304 | fn push_wild_constructor<'a>( |
c30ab7b3 SL |
305 | mut self, |
306 | cx: &MatchCheckCtxt<'a, 'tcx>, | |
8bb4bdeb | 307 | ctor: &Constructor<'tcx>, |
c30ab7b3 SL |
308 | ty: Ty<'tcx>) |
309 | -> Self | |
310 | { | |
32a655c1 SL |
311 | let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty); |
312 | self.0.extend(sub_pattern_tys.into_iter().map(|ty| { | |
313 | Pattern { | |
3b2f2976 | 314 | ty, |
32a655c1 SL |
315 | span: DUMMY_SP, |
316 | kind: box PatternKind::Wild, | |
317 | } | |
318 | })); | |
c30ab7b3 SL |
319 | self.apply_constructor(cx, ctor, ty) |
320 | } | |
321 | ||
322 | ||
323 | /// Constructs a partial witness for a pattern given a list of | |
324 | /// patterns expanded by the specialization step. | |
325 | /// | |
326 | /// When a pattern P is discovered to be useful, this function is used bottom-up | |
327 | /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset | |
328 | /// of values, V, where each value in that set is not covered by any previously | |
329 | /// used patterns and is covered by the pattern P'. Examples: | |
330 | /// | |
331 | /// left_ty: tuple of 3 elements | |
332 | /// pats: [10, 20, _] => (10, 20, _) | |
333 | /// | |
334 | /// left_ty: struct X { a: (bool, &'static str), b: usize} | |
335 | /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 } | |
32a655c1 | 336 | fn apply_constructor<'a>( |
c30ab7b3 SL |
337 | mut self, |
338 | cx: &MatchCheckCtxt<'a,'tcx>, | |
8bb4bdeb | 339 | ctor: &Constructor<'tcx>, |
c30ab7b3 SL |
340 | ty: Ty<'tcx>) |
341 | -> Self | |
342 | { | |
343 | let arity = constructor_arity(cx, ctor, ty); | |
344 | let pat = { | |
ea8adc8c XL |
345 | let len = self.0.len() as u64; |
346 | let mut pats = self.0.drain((len-arity) as usize..).rev(); | |
c30ab7b3 SL |
347 | |
348 | match ty.sty { | |
32a655c1 SL |
349 | ty::TyAdt(..) | |
350 | ty::TyTuple(..) => { | |
351 | let pats = pats.enumerate().map(|(i, p)| { | |
352 | FieldPattern { | |
353 | field: Field::new(i), | |
354 | pattern: p | |
c30ab7b3 | 355 | } |
32a655c1 SL |
356 | }).collect(); |
357 | ||
358 | if let ty::TyAdt(adt, substs) = ty.sty { | |
359 | if adt.variants.len() > 1 { | |
360 | PatternKind::Variant { | |
361 | adt_def: adt, | |
3b2f2976 | 362 | substs, |
32a655c1 SL |
363 | variant_index: ctor.variant_index_for_adt(adt), |
364 | subpatterns: pats | |
365 | } | |
366 | } else { | |
367 | PatternKind::Leaf { subpatterns: pats } | |
c30ab7b3 | 368 | } |
32a655c1 SL |
369 | } else { |
370 | PatternKind::Leaf { subpatterns: pats } | |
c30ab7b3 SL |
371 | } |
372 | } | |
373 | ||
32a655c1 SL |
374 | ty::TyRef(..) => { |
375 | PatternKind::Deref { subpattern: pats.nth(0).unwrap() } | |
c30ab7b3 SL |
376 | } |
377 | ||
378 | ty::TySlice(_) | ty::TyArray(..) => { | |
32a655c1 SL |
379 | PatternKind::Slice { |
380 | prefix: pats.collect(), | |
381 | slice: None, | |
382 | suffix: vec![] | |
383 | } | |
c30ab7b3 SL |
384 | } |
385 | ||
386 | _ => { | |
387 | match *ctor { | |
ea8adc8c | 388 | ConstantValue(value) => PatternKind::Constant { value }, |
32a655c1 | 389 | _ => PatternKind::Wild, |
c30ab7b3 SL |
390 | } |
391 | } | |
392 | } | |
393 | }; | |
394 | ||
32a655c1 | 395 | self.0.push(Pattern { |
3b2f2976 | 396 | ty, |
32a655c1 SL |
397 | span: DUMMY_SP, |
398 | kind: Box::new(pat), | |
399 | }); | |
c30ab7b3 SL |
400 | |
401 | self | |
402 | } | |
403 | } | |
404 | ||
c30ab7b3 SL |
405 | /// This determines the set of all possible constructors of a pattern matching |
406 | /// values of type `left_ty`. For vectors, this would normally be an infinite set | |
32a655c1 SL |
407 | /// but is instead bounded by the maximum fixed length of slice patterns in |
408 | /// the column of patterns being analyzed. | |
c30ab7b3 SL |
409 | /// |
410 | /// This intentionally does not list ConstantValue specializations for | |
411 | /// non-booleans, because we currently assume that there is always a | |
412 | /// "non-standard constant" that matches. See issue #12483. | |
413 | /// | |
32a655c1 SL |
414 | /// We make sure to omit constructors that are statically impossible. eg for |
415 | /// Option<!> we do not include Some(_) in the returned list of constructors. | |
416 | fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, | |
8bb4bdeb XL |
417 | pcx: PatternContext<'tcx>) |
418 | -> Vec<Constructor<'tcx>> | |
32a655c1 SL |
419 | { |
420 | debug!("all_constructors({:?})", pcx.ty); | |
c30ab7b3 | 421 | match pcx.ty.sty { |
ea8adc8c XL |
422 | ty::TyBool => { |
423 | [true, false].iter().map(|&b| { | |
424 | ConstantValue(cx.tcx.mk_const(ty::Const { | |
425 | val: ConstVal::Bool(b), | |
426 | ty: cx.tcx.types.bool | |
427 | })) | |
428 | }).collect() | |
429 | } | |
430 | ty::TyArray(ref sub_ty, len) if len.val.to_const_int().is_some() => { | |
431 | let len = len.val.to_const_int().unwrap().to_u64().unwrap(); | |
432 | if len != 0 && cx.is_uninhabited(sub_ty) { | |
433 | vec![] | |
434 | } else { | |
435 | vec![Slice(len)] | |
436 | } | |
437 | } | |
438 | // Treat arrays of a constant but unknown length like slices. | |
439 | ty::TyArray(ref sub_ty, _) | | |
32a655c1 SL |
440 | ty::TySlice(ref sub_ty) => { |
441 | if cx.is_uninhabited(sub_ty) { | |
442 | vec![Slice(0)] | |
443 | } else { | |
444 | (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect() | |
445 | } | |
446 | } | |
32a655c1 SL |
447 | ty::TyAdt(def, substs) if def.is_enum() && def.variants.len() != 1 => { |
448 | def.variants.iter() | |
449 | .filter(|v| !cx.is_variant_uninhabited(v, substs)) | |
450 | .map(|v| Variant(v.did)) | |
451 | .collect() | |
452 | } | |
453 | _ => { | |
454 | if cx.is_uninhabited(pcx.ty) { | |
455 | vec![] | |
456 | } else { | |
457 | vec![Single] | |
458 | } | |
459 | } | |
c30ab7b3 SL |
460 | } |
461 | } | |
462 | ||
32a655c1 | 463 | fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>( |
476ff2be | 464 | _cx: &mut MatchCheckCtxt<'a, 'tcx>, |
ea8adc8c | 465 | patterns: I) -> u64 |
32a655c1 | 466 | where I: Iterator<Item=&'p Pattern<'tcx>> |
476ff2be SL |
467 | { |
468 | // The exhaustiveness-checking paper does not include any details on | |
469 | // checking variable-length slice patterns. However, they are matched | |
470 | // by an infinite collection of fixed-length array patterns. | |
471 | // | |
472 | // Checking the infinite set directly would take an infinite amount | |
473 | // of time. However, it turns out that for each finite set of | |
474 | // patterns `P`, all sufficiently large array lengths are equivalent: | |
475 | // | |
476 | // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies | |
477 | // to exactly the subset `Pₜ` of `P` can be transformed to a slice | |
478 | // `sₘ` for each sufficiently-large length `m` that applies to exactly | |
479 | // the same subset of `P`. | |
480 | // | |
481 | // Because of that, each witness for reachability-checking from one | |
482 | // of the sufficiently-large lengths can be transformed to an | |
483 | // equally-valid witness from any other length, so we only have | |
484 | // to check slice lengths from the "minimal sufficiently-large length" | |
485 | // and below. | |
486 | // | |
487 | // Note that the fact that there is a *single* `sₘ` for each `m` | |
488 | // not depending on the specific pattern in `P` is important: if | |
489 | // you look at the pair of patterns | |
490 | // `[true, ..]` | |
491 | // `[.., false]` | |
492 | // Then any slice of length ≥1 that matches one of these two | |
493 | // patterns can be be trivially turned to a slice of any | |
494 | // other length ≥1 that matches them and vice-versa - for | |
495 | // but the slice from length 2 `[false, true]` that matches neither | |
496 | // of these patterns can't be turned to a slice from length 1 that | |
497 | // matches neither of these patterns, so we have to consider | |
498 | // slices from length 2 there. | |
499 | // | |
500 | // Now, to see that that length exists and find it, observe that slice | |
501 | // patterns are either "fixed-length" patterns (`[_, _, _]`) or | |
502 | // "variable-length" patterns (`[_, .., _]`). | |
503 | // | |
504 | // For fixed-length patterns, all slices with lengths *longer* than | |
505 | // the pattern's length have the same outcome (of not matching), so | |
506 | // as long as `L` is greater than the pattern's length we can pick | |
507 | // any `sₘ` from that length and get the same result. | |
508 | // | |
509 | // For variable-length patterns, the situation is more complicated, | |
510 | // because as seen above the precise value of `sₘ` matters. | |
511 | // | |
512 | // However, for each variable-length pattern `p` with a prefix of length | |
513 | // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last | |
514 | // `slâ‚š` elements are examined. | |
515 | // | |
516 | // Therefore, as long as `L` is positive (to avoid concerns about empty | |
517 | // types), all elements after the maximum prefix length and before | |
518 | // the maximum suffix length are not examined by any variable-length | |
519 | // pattern, and therefore can be added/removed without affecting | |
520 | // them - creating equivalent patterns from any sufficiently-large | |
521 | // length. | |
522 | // | |
523 | // Of course, if fixed-length patterns exist, we must be sure | |
524 | // that our length is large enough to miss them all, so | |
525 | // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})` | |
526 | // | |
527 | // for example, with the above pair of patterns, all elements | |
528 | // but the first and last can be added/removed, so any | |
529 | // witness of length ≥2 (say, `[false, false, true]`) can be | |
530 | // turned to a witness from any other length ≥2. | |
531 | ||
532 | let mut max_prefix_len = 0; | |
533 | let mut max_suffix_len = 0; | |
534 | let mut max_fixed_len = 0; | |
535 | ||
536 | for row in patterns { | |
537 | match *row.kind { | |
ea8adc8c XL |
538 | PatternKind::Constant { value: &ty::Const { val: ConstVal::ByteStr(b), .. } } => { |
539 | max_fixed_len = cmp::max(max_fixed_len, b.data.len() as u64); | |
476ff2be SL |
540 | } |
541 | PatternKind::Slice { ref prefix, slice: None, ref suffix } => { | |
ea8adc8c | 542 | let fixed_len = prefix.len() as u64 + suffix.len() as u64; |
476ff2be SL |
543 | max_fixed_len = cmp::max(max_fixed_len, fixed_len); |
544 | } | |
545 | PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => { | |
ea8adc8c XL |
546 | max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64); |
547 | max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64); | |
476ff2be SL |
548 | } |
549 | _ => {} | |
550 | } | |
551 | } | |
552 | ||
553 | cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len) | |
554 | } | |
555 | ||
c30ab7b3 | 556 | /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html |
32a655c1 SL |
557 | /// The algorithm from the paper has been modified to correctly handle empty |
558 | /// types. The changes are: | |
559 | /// (0) We don't exit early if the pattern matrix has zero rows. We just | |
560 | /// continue to recurse over columns. | |
561 | /// (1) all_constructors will only return constructors that are statically | |
562 | /// possible. eg. it will only return Ok for Result<T, !> | |
c30ab7b3 SL |
563 | /// |
564 | /// Whether a vector `v` of patterns is 'useful' in relation to a set of such | |
565 | /// vectors `m` is defined as there being a set of inputs that will match `v` | |
566 | /// but not any of the sets in `m`. | |
567 | /// | |
568 | /// This is used both for reachability checking (if a pattern isn't useful in | |
569 | /// relation to preceding patterns, it is not reachable) and exhaustiveness | |
570 | /// checking (if a wildcard pattern is useful in relation to a matrix, the | |
571 | /// matrix isn't exhaustive). | |
32a655c1 SL |
572 | pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, |
573 | matrix: &Matrix<'p, 'tcx>, | |
574 | v: &[&'p Pattern<'tcx>], | |
c30ab7b3 | 575 | witness: WitnessPreference) |
32a655c1 | 576 | -> Usefulness<'tcx> { |
c30ab7b3 SL |
577 | let &Matrix(ref rows) = matrix; |
578 | debug!("is_useful({:?}, {:?})", matrix, v); | |
c30ab7b3 | 579 | |
32a655c1 SL |
580 | // The base case. We are pattern-matching on () and the return value is |
581 | // based on whether our matrix has a row or not. | |
582 | // NOTE: This could potentially be optimized by checking rows.is_empty() | |
583 | // first and then, if v is non-empty, the return value is based on whether | |
584 | // the type of the tuple we're checking is inhabited or not. | |
585 | if v.is_empty() { | |
586 | return if rows.is_empty() { | |
587 | match witness { | |
588 | ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]), | |
589 | LeaveOutWitness => Useful, | |
590 | } | |
591 | } else { | |
592 | NotUseful | |
593 | } | |
594 | }; | |
476ff2be | 595 | |
32a655c1 | 596 | assert!(rows.iter().all(|r| r.len() == v.len())); |
476ff2be | 597 | |
c30ab7b3 SL |
598 | let pcx = PatternContext { |
599 | ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()) | |
600 | .unwrap_or(v[0].ty), | |
476ff2be | 601 | max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0]))) |
c30ab7b3 SL |
602 | }; |
603 | ||
604 | debug!("is_useful_expand_first_col: pcx={:?}, expanding {:?}", pcx, v[0]); | |
605 | ||
606 | if let Some(constructors) = pat_constructors(cx, v[0], pcx) { | |
607 | debug!("is_useful - expanding constructors: {:?}", constructors); | |
608 | constructors.into_iter().map(|c| | |
609 | is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness) | |
32a655c1 | 610 | ).find(|result| result.is_useful()).unwrap_or(NotUseful) |
c30ab7b3 SL |
611 | } else { |
612 | debug!("is_useful - expanding wildcard"); | |
32a655c1 SL |
613 | |
614 | let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| { | |
615 | pat_constructors(cx, row[0], pcx).unwrap_or(vec![]) | |
616 | }).collect(); | |
617 | debug!("used_ctors = {:?}", used_ctors); | |
618 | let all_ctors = all_constructors(cx, pcx); | |
619 | debug!("all_ctors = {:?}", all_ctors); | |
620 | let missing_ctors: Vec<Constructor> = all_ctors.iter().filter(|c| { | |
621 | !used_ctors.contains(*c) | |
622 | }).cloned().collect(); | |
623 | ||
624 | // `missing_ctors` is the set of constructors from the same type as the | |
625 | // first column of `matrix` that are matched only by wildcard patterns | |
626 | // from the first column. | |
627 | // | |
628 | // Therefore, if there is some pattern that is unmatched by `matrix`, | |
629 | // it will still be unmatched if the first constructor is replaced by | |
630 | // any of the constructors in `missing_ctors` | |
631 | // | |
632 | // However, if our scrutinee is *privately* an empty enum, we | |
633 | // must treat it as though it had an "unknown" constructor (in | |
634 | // that case, all other patterns obviously can't be variants) | |
635 | // to avoid exposing its emptyness. See the `match_privately_empty` | |
636 | // test for details. | |
637 | // | |
638 | // FIXME: currently the only way I know of something can | |
639 | // be a privately-empty enum is when the never_type | |
640 | // feature flag is not present, so this is only | |
641 | // needed for that case. | |
642 | ||
643 | let is_privately_empty = | |
644 | all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty); | |
abe05a73 XL |
645 | let is_declared_nonexhaustive = |
646 | cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty); | |
647 | debug!("missing_ctors={:?} is_privately_empty={:?} is_declared_nonexhaustive={:?}", | |
648 | missing_ctors, is_privately_empty, is_declared_nonexhaustive); | |
649 | ||
650 | // For privately empty and non-exhaustive enums, we work as if there were an "extra" | |
651 | // `_` constructor for the type, so we can never match over all constructors. | |
652 | let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive; | |
653 | ||
654 | if missing_ctors.is_empty() && !is_non_exhaustive { | |
32a655c1 | 655 | all_ctors.into_iter().map(|c| { |
c30ab7b3 | 656 | is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness) |
32a655c1 | 657 | }).find(|result| result.is_useful()).unwrap_or(NotUseful) |
c30ab7b3 SL |
658 | } else { |
659 | let matrix = rows.iter().filter_map(|r| { | |
660 | if r[0].is_wildcard() { | |
661 | Some(r[1..].to_vec()) | |
662 | } else { | |
663 | None | |
664 | } | |
665 | }).collect(); | |
666 | match is_useful(cx, &matrix, &v[1..], witness) { | |
667 | UsefulWithWitness(pats) => { | |
668 | let cx = &*cx; | |
abe05a73 XL |
669 | // In this case, there's at least one "free" |
670 | // constructor that is only matched against by | |
671 | // wildcard patterns. | |
672 | // | |
673 | // There are 2 ways we can report a witness here. | |
674 | // Commonly, we can report all the "free" | |
675 | // constructors as witnesses, e.g. if we have: | |
676 | // | |
677 | // ``` | |
678 | // enum Direction { N, S, E, W } | |
679 | // let Direction::N = ...; | |
680 | // ``` | |
681 | // | |
682 | // we can report 3 witnesses: `S`, `E`, and `W`. | |
683 | // | |
684 | // However, there are 2 cases where we don't want | |
685 | // to do this and instead report a single `_` witness: | |
686 | // | |
687 | // 1) If the user is matching against a non-exhaustive | |
688 | // enum, there is no point in enumerating all possible | |
689 | // variants, because the user can't actually match | |
690 | // against them himself, e.g. in an example like: | |
691 | // ``` | |
692 | // let err: io::ErrorKind = ...; | |
693 | // match err { | |
694 | // io::ErrorKind::NotFound => {}, | |
695 | // } | |
696 | // ``` | |
697 | // we don't want to show every possible IO error, | |
698 | // but instead have `_` as the witness (this is | |
699 | // actually *required* if the user specified *all* | |
700 | // IO errors, but is probably what we want in every | |
701 | // case). | |
702 | // | |
703 | // 2) If the user didn't actually specify a constructor | |
704 | // in this arm, e.g. in | |
705 | // ``` | |
706 | // let x: (Direction, Direction, bool) = ...; | |
707 | // let (_, _, false) = x; | |
708 | // ``` | |
709 | // we don't want to show all 16 possible witnesses | |
710 | // `(<direction-1>, <direction-2>, true)` - we are | |
711 | // satisfied with `(_, _, true)`. In this case, | |
712 | // `used_ctors` is empty. | |
713 | let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() { | |
32a655c1 SL |
714 | // All constructors are unused. Add wild patterns |
715 | // rather than each individual constructor | |
716 | pats.into_iter().map(|mut witness| { | |
717 | witness.0.push(Pattern { | |
718 | ty: pcx.ty, | |
719 | span: DUMMY_SP, | |
720 | kind: box PatternKind::Wild, | |
721 | }); | |
722 | witness | |
723 | }).collect() | |
724 | } else { | |
725 | pats.into_iter().flat_map(|witness| { | |
726 | missing_ctors.iter().map(move |ctor| { | |
727 | witness.clone().push_wild_constructor(cx, ctor, pcx.ty) | |
728 | }) | |
729 | }).collect() | |
730 | }; | |
731 | UsefulWithWitness(new_witnesses) | |
c30ab7b3 SL |
732 | } |
733 | result => result | |
734 | } | |
735 | } | |
736 | } | |
737 | } | |
738 | ||
32a655c1 | 739 | fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>( |
c30ab7b3 | 740 | cx: &mut MatchCheckCtxt<'a, 'tcx>, |
32a655c1 SL |
741 | &Matrix(ref m): &Matrix<'p, 'tcx>, |
742 | v: &[&'p Pattern<'tcx>], | |
8bb4bdeb | 743 | ctor: Constructor<'tcx>, |
c30ab7b3 | 744 | lty: Ty<'tcx>, |
32a655c1 | 745 | witness: WitnessPreference) -> Usefulness<'tcx> |
c30ab7b3 | 746 | { |
32a655c1 SL |
747 | debug!("is_useful_specialized({:?}, {:?}, {:?})", v, ctor, lty); |
748 | let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty); | |
749 | let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| { | |
750 | Pattern { | |
3b2f2976 | 751 | ty, |
32a655c1 SL |
752 | span: DUMMY_SP, |
753 | kind: box PatternKind::Wild, | |
754 | } | |
755 | }).collect(); | |
756 | let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect(); | |
c30ab7b3 | 757 | let matrix = Matrix(m.iter().flat_map(|r| { |
cc61c64b | 758 | specialize(cx, &r, &ctor, &wild_patterns) |
c30ab7b3 | 759 | }).collect()); |
32a655c1 | 760 | match specialize(cx, v, &ctor, &wild_patterns) { |
cc61c64b | 761 | Some(v) => match is_useful(cx, &matrix, &v, witness) { |
c30ab7b3 SL |
762 | UsefulWithWitness(witnesses) => UsefulWithWitness( |
763 | witnesses.into_iter() | |
764 | .map(|witness| witness.apply_constructor(cx, &ctor, lty)) | |
765 | .collect() | |
766 | ), | |
767 | result => result | |
768 | }, | |
769 | None => NotUseful | |
770 | } | |
771 | } | |
772 | ||
773 | /// Determines the constructors that the given pattern can be specialized to. | |
774 | /// | |
775 | /// In most cases, there's only one constructor that a specific pattern | |
776 | /// represents, such as a specific enum variant or a specific literal value. | |
777 | /// Slice patterns, however, can match slices of different lengths. For instance, | |
778 | /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on. | |
779 | /// | |
780 | /// Returns None in case of a catch-all, which can't be specialized. | |
8bb4bdeb XL |
781 | fn pat_constructors<'tcx>(_cx: &mut MatchCheckCtxt, |
782 | pat: &Pattern<'tcx>, | |
783 | pcx: PatternContext) | |
784 | -> Option<Vec<Constructor<'tcx>>> | |
c30ab7b3 SL |
785 | { |
786 | match *pat.kind { | |
787 | PatternKind::Binding { .. } | PatternKind::Wild => | |
788 | None, | |
789 | PatternKind::Leaf { .. } | PatternKind::Deref { .. } => | |
790 | Some(vec![Single]), | |
791 | PatternKind::Variant { adt_def, variant_index, .. } => | |
792 | Some(vec![Variant(adt_def.variants[variant_index].did)]), | |
ea8adc8c XL |
793 | PatternKind::Constant { value } => |
794 | Some(vec![ConstantValue(value)]), | |
795 | PatternKind::Range { lo, hi, end } => | |
796 | Some(vec![ConstantRange(lo, hi, end)]), | |
c30ab7b3 | 797 | PatternKind::Array { .. } => match pcx.ty.sty { |
ea8adc8c XL |
798 | ty::TyArray(_, length) => Some(vec![ |
799 | Slice(length.val.to_const_int().unwrap().to_u64().unwrap()) | |
800 | ]), | |
c30ab7b3 SL |
801 | _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty) |
802 | }, | |
803 | PatternKind::Slice { ref prefix, ref slice, ref suffix } => { | |
ea8adc8c | 804 | let pat_len = prefix.len() as u64 + suffix.len() as u64; |
c30ab7b3 SL |
805 | if slice.is_some() { |
806 | Some((pat_len..pcx.max_slice_length+1).map(Slice).collect()) | |
807 | } else { | |
808 | Some(vec![Slice(pat_len)]) | |
809 | } | |
810 | } | |
811 | } | |
812 | } | |
813 | ||
814 | /// This computes the arity of a constructor. The arity of a constructor | |
815 | /// is how many subpattern patterns of that constructor should be expanded to. | |
816 | /// | |
817 | /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3. | |
818 | /// A struct pattern's arity is the number of fields it contains, etc. | |
ea8adc8c | 819 | fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 { |
c30ab7b3 SL |
820 | debug!("constructor_arity({:?}, {:?})", ctor, ty); |
821 | match ty.sty { | |
ea8adc8c | 822 | ty::TyTuple(ref fs, _) => fs.len() as u64, |
c30ab7b3 SL |
823 | ty::TySlice(..) | ty::TyArray(..) => match *ctor { |
824 | Slice(length) => length, | |
825 | ConstantValue(_) => 0, | |
826 | _ => bug!("bad slice pattern {:?} {:?}", ctor, ty) | |
827 | }, | |
828 | ty::TyRef(..) => 1, | |
829 | ty::TyAdt(adt, _) => { | |
ea8adc8c | 830 | adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64 |
c30ab7b3 SL |
831 | } |
832 | _ => 0 | |
833 | } | |
834 | } | |
835 | ||
32a655c1 SL |
836 | /// This computes the types of the sub patterns that a constructor should be |
837 | /// expanded to. | |
838 | /// | |
839 | /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char]. | |
840 | fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>, | |
841 | ctor: &Constructor, | |
842 | ty: Ty<'tcx>) -> Vec<Ty<'tcx>> | |
843 | { | |
844 | debug!("constructor_sub_pattern_tys({:?}, {:?})", ctor, ty); | |
845 | match ty.sty { | |
8bb4bdeb | 846 | ty::TyTuple(ref fs, _) => fs.into_iter().map(|t| *t).collect(), |
32a655c1 | 847 | ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor { |
ea8adc8c | 848 | Slice(length) => (0..length).map(|_| ty).collect(), |
32a655c1 SL |
849 | ConstantValue(_) => vec![], |
850 | _ => bug!("bad slice pattern {:?} {:?}", ctor, ty) | |
851 | }, | |
852 | ty::TyRef(_, ref ty_and_mut) => vec![ty_and_mut.ty], | |
853 | ty::TyAdt(adt, substs) => { | |
041b39d2 XL |
854 | if adt.is_box() { |
855 | // Use T as the sub pattern type of Box<T>. | |
856 | vec![substs[0].as_type().unwrap()] | |
857 | } else { | |
858 | adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| { | |
859 | let is_visible = adt.is_enum() | |
860 | || field.vis.is_accessible_from(cx.module, cx.tcx); | |
861 | if is_visible { | |
862 | field.ty(cx.tcx, substs) | |
863 | } else { | |
864 | // Treat all non-visible fields as nil. They | |
865 | // can't appear in any other pattern from | |
866 | // this match (because they are private), | |
867 | // so their type does not matter - but | |
868 | // we don't want to know they are | |
869 | // uninhabited. | |
870 | cx.tcx.mk_nil() | |
871 | } | |
872 | }).collect() | |
873 | } | |
32a655c1 SL |
874 | } |
875 | _ => vec![], | |
876 | } | |
877 | } | |
878 | ||
c30ab7b3 SL |
879 | fn slice_pat_covered_by_constructor(_tcx: TyCtxt, _span: Span, |
880 | ctor: &Constructor, | |
881 | prefix: &[Pattern], | |
882 | slice: &Option<Pattern>, | |
883 | suffix: &[Pattern]) | |
884 | -> Result<bool, ErrorReported> { | |
885 | let data = match *ctor { | |
ea8adc8c | 886 | ConstantValue(&ty::Const { val: ConstVal::ByteStr(b), .. }) => b.data, |
c30ab7b3 SL |
887 | _ => bug!() |
888 | }; | |
889 | ||
890 | let pat_len = prefix.len() + suffix.len(); | |
891 | if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) { | |
892 | return Ok(false); | |
893 | } | |
894 | ||
895 | for (ch, pat) in | |
896 | data[..prefix.len()].iter().zip(prefix).chain( | |
897 | data[data.len()-suffix.len()..].iter().zip(suffix)) | |
898 | { | |
899 | match pat.kind { | |
ea8adc8c | 900 | box PatternKind::Constant { value } => match value.val { |
c30ab7b3 SL |
901 | ConstVal::Integral(ConstInt::U8(u)) => { |
902 | if u != *ch { | |
903 | return Ok(false); | |
904 | } | |
905 | }, | |
906 | _ => span_bug!(pat.span, "bad const u8 {:?}", value) | |
907 | }, | |
908 | _ => {} | |
909 | } | |
910 | } | |
911 | ||
912 | Ok(true) | |
913 | } | |
914 | ||
041b39d2 | 915 | fn constructor_covered_by_range(tcx: TyCtxt, span: Span, |
c30ab7b3 | 916 | ctor: &Constructor, |
32a655c1 SL |
917 | from: &ConstVal, to: &ConstVal, |
918 | end: RangeEnd) | |
c30ab7b3 | 919 | -> Result<bool, ErrorReported> { |
32a655c1 SL |
920 | let cmp_from = |c_from| Ok(compare_const_vals(tcx, span, c_from, from)? != Ordering::Less); |
921 | let cmp_to = |c_to| compare_const_vals(tcx, span, c_to, to); | |
922 | match *ctor { | |
ea8adc8c XL |
923 | ConstantValue(value) => { |
924 | let to = cmp_to(&value.val)?; | |
041b39d2 XL |
925 | let end = (to == Ordering::Less) || |
926 | (end == RangeEnd::Included && to == Ordering::Equal); | |
ea8adc8c | 927 | Ok(cmp_from(&value.val)? && end) |
32a655c1 | 928 | }, |
ea8adc8c XL |
929 | ConstantRange(from, to, RangeEnd::Included) => { |
930 | let to = cmp_to(&to.val)?; | |
041b39d2 XL |
931 | let end = (to == Ordering::Less) || |
932 | (end == RangeEnd::Included && to == Ordering::Equal); | |
ea8adc8c | 933 | Ok(cmp_from(&from.val)? && end) |
32a655c1 | 934 | }, |
ea8adc8c XL |
935 | ConstantRange(from, to, RangeEnd::Excluded) => { |
936 | let to = cmp_to(&to.val)?; | |
32a655c1 SL |
937 | let end = (to == Ordering::Less) || |
938 | (end == RangeEnd::Excluded && to == Ordering::Equal); | |
ea8adc8c | 939 | Ok(cmp_from(&from.val)? && end) |
32a655c1 SL |
940 | } |
941 | Single => Ok(true), | |
942 | _ => bug!(), | |
943 | } | |
c30ab7b3 SL |
944 | } |
945 | ||
32a655c1 SL |
946 | fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>( |
947 | subpatterns: &'p [FieldPattern<'tcx>], | |
948 | wild_patterns: &[&'p Pattern<'tcx>]) | |
949 | -> Vec<&'p Pattern<'tcx>> | |
c30ab7b3 | 950 | { |
32a655c1 | 951 | let mut result = wild_patterns.to_owned(); |
c30ab7b3 SL |
952 | |
953 | for subpat in subpatterns { | |
954 | result[subpat.field.index()] = &subpat.pattern; | |
955 | } | |
956 | ||
32a655c1 | 957 | debug!("patterns_for_variant({:?}, {:?}) = {:?}", subpatterns, wild_patterns, result); |
c30ab7b3 SL |
958 | result |
959 | } | |
960 | ||
961 | /// This is the main specialization step. It expands the first pattern in the given row | |
962 | /// into `arity` patterns based on the constructor. For most patterns, the step is trivial, | |
963 | /// for instance tuple patterns are flattened and box patterns expand into their inner pattern. | |
964 | /// | |
965 | /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple | |
966 | /// different patterns. | |
967 | /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing | |
968 | /// fields filled with wild patterns. | |
32a655c1 | 969 | fn specialize<'p, 'a: 'p, 'tcx: 'a>( |
c30ab7b3 | 970 | cx: &mut MatchCheckCtxt<'a, 'tcx>, |
32a655c1 SL |
971 | r: &[&'p Pattern<'tcx>], |
972 | constructor: &Constructor, | |
973 | wild_patterns: &[&'p Pattern<'tcx>]) | |
974 | -> Option<Vec<&'p Pattern<'tcx>>> | |
c30ab7b3 | 975 | { |
32a655c1 | 976 | let pat = &r[0]; |
c30ab7b3 SL |
977 | |
978 | let head: Option<Vec<&Pattern>> = match *pat.kind { | |
32a655c1 SL |
979 | PatternKind::Binding { .. } | PatternKind::Wild => { |
980 | Some(wild_patterns.to_owned()) | |
981 | }, | |
c30ab7b3 | 982 | |
32a655c1 | 983 | PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => { |
c30ab7b3 SL |
984 | let ref variant = adt_def.variants[variant_index]; |
985 | if *constructor == Variant(variant.did) { | |
32a655c1 | 986 | Some(patterns_for_variant(subpatterns, wild_patterns)) |
c30ab7b3 SL |
987 | } else { |
988 | None | |
989 | } | |
990 | } | |
991 | ||
32a655c1 SL |
992 | PatternKind::Leaf { ref subpatterns } => { |
993 | Some(patterns_for_variant(subpatterns, wild_patterns)) | |
994 | } | |
995 | PatternKind::Deref { ref subpattern } => { | |
996 | Some(vec![subpattern]) | |
997 | } | |
c30ab7b3 | 998 | |
ea8adc8c | 999 | PatternKind::Constant { value } => { |
c30ab7b3 | 1000 | match *constructor { |
ea8adc8c XL |
1001 | Slice(..) => match value.val { |
1002 | ConstVal::ByteStr(b) => { | |
1003 | if wild_patterns.len() == b.data.len() { | |
c30ab7b3 SL |
1004 | Some(cx.lower_byte_str_pattern(pat)) |
1005 | } else { | |
1006 | None | |
1007 | } | |
1008 | } | |
1009 | _ => span_bug!(pat.span, | |
1010 | "unexpected const-val {:?} with ctor {:?}", value, constructor) | |
1011 | }, | |
1012 | _ => { | |
041b39d2 | 1013 | match constructor_covered_by_range( |
ea8adc8c | 1014 | cx.tcx, pat.span, constructor, &value.val, &value.val, RangeEnd::Included |
c30ab7b3 SL |
1015 | ) { |
1016 | Ok(true) => Some(vec![]), | |
1017 | Ok(false) => None, | |
1018 | Err(ErrorReported) => None, | |
1019 | } | |
1020 | } | |
1021 | } | |
1022 | } | |
1023 | ||
ea8adc8c | 1024 | PatternKind::Range { lo, hi, ref end } => { |
041b39d2 | 1025 | match constructor_covered_by_range( |
ea8adc8c | 1026 | cx.tcx, pat.span, constructor, &lo.val, &hi.val, end.clone() |
c30ab7b3 SL |
1027 | ) { |
1028 | Ok(true) => Some(vec![]), | |
1029 | Ok(false) => None, | |
1030 | Err(ErrorReported) => None, | |
1031 | } | |
1032 | } | |
1033 | ||
1034 | PatternKind::Array { ref prefix, ref slice, ref suffix } | | |
1035 | PatternKind::Slice { ref prefix, ref slice, ref suffix } => { | |
1036 | match *constructor { | |
1037 | Slice(..) => { | |
1038 | let pat_len = prefix.len() + suffix.len(); | |
32a655c1 | 1039 | if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) { |
c30ab7b3 SL |
1040 | if slice_count == 0 || slice.is_some() { |
1041 | Some( | |
1042 | prefix.iter().chain( | |
32a655c1 SL |
1043 | wild_patterns.iter().map(|p| *p) |
1044 | .skip(prefix.len()) | |
1045 | .take(slice_count) | |
1046 | .chain( | |
c30ab7b3 SL |
1047 | suffix.iter() |
1048 | )).collect()) | |
1049 | } else { | |
1050 | None | |
1051 | } | |
1052 | } else { | |
1053 | None | |
1054 | } | |
1055 | } | |
1056 | ConstantValue(..) => { | |
1057 | match slice_pat_covered_by_constructor( | |
1058 | cx.tcx, pat.span, constructor, prefix, slice, suffix | |
1059 | ) { | |
1060 | Ok(true) => Some(vec![]), | |
1061 | Ok(false) => None, | |
1062 | Err(ErrorReported) => None | |
1063 | } | |
1064 | } | |
1065 | _ => span_bug!(pat.span, | |
1066 | "unexpected ctor {:?} for slice pat", constructor) | |
1067 | } | |
1068 | } | |
1069 | }; | |
32a655c1 | 1070 | debug!("specialize({:?}, {:?}) = {:?}", r[0], wild_patterns, head); |
c30ab7b3 SL |
1071 | |
1072 | head.map(|mut head| { | |
32a655c1 | 1073 | head.extend_from_slice(&r[1 ..]); |
c30ab7b3 SL |
1074 | head |
1075 | }) | |
1076 | } |