aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_ty/src/diagnostics/match_check.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_ty/src/diagnostics/match_check.rs')
-rw-r--r--crates/ra_hir_ty/src/diagnostics/match_check.rs2158
1 files changed, 2158 insertions, 0 deletions
diff --git a/crates/ra_hir_ty/src/diagnostics/match_check.rs b/crates/ra_hir_ty/src/diagnostics/match_check.rs
new file mode 100644
index 000000000..722c0e9ee
--- /dev/null
+++ b/crates/ra_hir_ty/src/diagnostics/match_check.rs
@@ -0,0 +1,2158 @@
1//! This module implements match statement exhaustiveness checking and usefulness checking
2//! for match arms.
3//!
4//! It is modeled on the rustc module `librustc_mir_build::hair::pattern::_match`, which
5//! contains very detailed documentation about the algorithms used here. I've duplicated
6//! most of that documentation below.
7//!
8//! This file includes the logic for exhaustiveness and usefulness checking for
9//! pattern-matching. Specifically, given a list of patterns for a type, we can
10//! tell whether:
11//! - (a) the patterns cover every possible constructor for the type (exhaustiveness).
12//! - (b) each pattern is necessary (usefulness).
13//!
14//! The algorithm implemented here is a modified version of the one described in
15//! <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
16//! However, to save future implementors from reading the original paper, we
17//! summarise the algorithm here to hopefully save time and be a little clearer
18//! (without being so rigorous).
19//!
20//! The core of the algorithm revolves about a "usefulness" check. In particular, we
21//! are trying to compute a predicate `U(P, p)` where `P` is a list of patterns (we refer to this as
22//! a matrix). `U(P, p)` represents whether, given an existing list of patterns
23//! `P_1 ..= P_m`, adding a new pattern `p` will be "useful" (that is, cover previously-
24//! uncovered values of the type).
25//!
26//! If we have this predicate, then we can easily compute both exhaustiveness of an
27//! entire set of patterns and the individual usefulness of each one.
28//! (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard
29//! match doesn't increase the number of values we're matching)
30//! (b) a pattern `P_i` is not useful if `U(P[0..=(i-1), P_i)` is false (i.e., adding a
31//! pattern to those that have come before it doesn't increase the number of values
32//! we're matching).
33//!
34//! During the course of the algorithm, the rows of the matrix won't just be individual patterns,
35//! but rather partially-deconstructed patterns in the form of a list of patterns. The paper
36//! calls those pattern-vectors, and we will call them pattern-stacks. The same holds for the
37//! new pattern `p`.
38//!
39//! For example, say we have the following:
40//!
41//! ```ignore
42//! // x: (Option<bool>, Result<()>)
43//! match x {
44//! (Some(true), _) => {}
45//! (None, Err(())) => {}
46//! (None, Err(_)) => {}
47//! }
48//! ```
49//!
50//! Here, the matrix `P` starts as:
51//!
52//! ```text
53//! [
54//! [(Some(true), _)],
55//! [(None, Err(()))],
56//! [(None, Err(_))],
57//! ]
58//! ```
59//!
60//! We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
61//! `[(Some(false), _)]`, for instance). In addition, row 3 is not useful, because
62//! all the values it covers are already covered by row 2.
63//!
64//! A list of patterns can be thought of as a stack, because we are mainly interested in the top of
65//! the stack at any given point, and we can pop or apply constructors to get new pattern-stacks.
66//! To match the paper, the top of the stack is at the beginning / on the left.
67//!
68//! There are two important operations on pattern-stacks necessary to understand the algorithm:
69//!
70//! 1. We can pop a given constructor off the top of a stack. This operation is called
71//! `specialize`, and is denoted `S(c, p)` where `c` is a constructor (like `Some` or
72//! `None`) and `p` a pattern-stack.
73//! If the pattern on top of the stack can cover `c`, this removes the constructor and
74//! pushes its arguments onto the stack. It also expands OR-patterns into distinct patterns.
75//! Otherwise the pattern-stack is discarded.
76//! This essentially filters those pattern-stacks whose top covers the constructor `c` and
77//! discards the others.
78//!
79//! For example, the first pattern above initially gives a stack `[(Some(true), _)]`. If we
80//! pop the tuple constructor, we are left with `[Some(true), _]`, and if we then pop the
81//! `Some` constructor we get `[true, _]`. If we had popped `None` instead, we would get
82//! nothing back.
83//!
84//! This returns zero or more new pattern-stacks, as follows. We look at the pattern `p_1`
85//! on top of the stack, and we have four cases:
86//!
87//! * 1.1. `p_1 = c(r_1, .., r_a)`, i.e. the top of the stack has constructor `c`. We push onto
88//! the stack the arguments of this constructor, and return the result:
89//!
90//! r_1, .., r_a, p_2, .., p_n
91//!
92//! * 1.2. `p_1 = c'(r_1, .., r_a')` where `c ≠ c'`. We discard the current stack and return
93//! nothing.
94//! * 1.3. `p_1 = _`. We push onto the stack as many wildcards as the constructor `c` has
95//! arguments (its arity), and return the resulting stack:
96//!
97//! _, .., _, p_2, .., p_n
98//!
99//! * 1.4. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting stack:
100//!
101//! S(c, (r_1, p_2, .., p_n))
102//! S(c, (r_2, p_2, .., p_n))
103//!
104//! 2. We can pop a wildcard off the top of the stack. This is called `D(p)`, where `p` is
105//! a pattern-stack.
106//! This is used when we know there are missing constructor cases, but there might be
107//! existing wildcard patterns, so to check the usefulness of the matrix, we have to check
108//! all its *other* components.
109//!
110//! It is computed as follows. We look at the pattern `p_1` on top of the stack,
111//! and we have three cases:
112//! * 1.1. `p_1 = c(r_1, .., r_a)`. We discard the current stack and return nothing.
113//! * 1.2. `p_1 = _`. We return the rest of the stack:
114//!
115//! p_2, .., p_n
116//!
117//! * 1.3. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting stack:
118//!
119//! D((r_1, p_2, .., p_n))
120//! D((r_2, p_2, .., p_n))
121//!
122//! Note that the OR-patterns are not always used directly in Rust, but are used to derive the
123//! exhaustive integer matching rules, so they're written here for posterity.
124//!
125//! Both those operations extend straightforwardly to a list or pattern-stacks, i.e. a matrix, by
126//! working row-by-row. Popping a constructor ends up keeping only the matrix rows that start with
127//! the given constructor, and popping a wildcard keeps those rows that start with a wildcard.
128//!
129//!
130//! The algorithm for computing `U`
131//! -------------------------------
132//! The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
133//! That means we're going to check the components from left-to-right, so the algorithm
134//! operates principally on the first component of the matrix and new pattern-stack `p`.
135//! This algorithm is realised in the `is_useful` function.
136//!
137//! Base case (`n = 0`, i.e., an empty tuple pattern):
138//! - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`), then
139//! `U(P, p)` is false.
140//! - Otherwise, `P` must be empty, so `U(P, p)` is true.
141//!
142//! Inductive step (`n > 0`, i.e., whether there's at least one column [which may then be expanded
143//! into further columns later]). We're going to match on the top of the new pattern-stack, `p_1`:
144//!
145//! - If `p_1 == c(r_1, .., r_a)`, i.e. we have a constructor pattern.
146//! Then, the usefulness of `p_1` can be reduced to whether it is useful when
147//! we ignore all the patterns in the first column of `P` that involve other constructors.
148//! This is where `S(c, P)` comes in:
149//!
150//! ```text
151//! U(P, p) := U(S(c, P), S(c, p))
152//! ```
153//!
154//! This special case is handled in `is_useful_specialized`.
155//!
156//! For example, if `P` is:
157//!
158//! ```text
159//! [
160//! [Some(true), _],
161//! [None, 0],
162//! ]
163//! ```
164//!
165//! and `p` is `[Some(false), 0]`, then we don't care about row 2 since we know `p` only
166//! matches values that row 2 doesn't. For row 1 however, we need to dig into the
167//! arguments of `Some` to know whether some new value is covered. So we compute
168//! `U([[true, _]], [false, 0])`.
169//!
170//! - If `p_1 == _`, then we look at the list of constructors that appear in the first component of
171//! the rows of `P`:
172//! - If there are some constructors that aren't present, then we might think that the
173//! wildcard `_` is useful, since it covers those constructors that weren't covered
174//! before.
175//! That's almost correct, but only works if there were no wildcards in those first
176//! components. So we need to check that `p` is useful with respect to the rows that
177//! start with a wildcard, if there are any. This is where `D` comes in:
178//! `U(P, p) := U(D(P), D(p))`
179//!
180//! For example, if `P` is:
181//! ```text
182//! [
183//! [_, true, _],
184//! [None, false, 1],
185//! ]
186//! ```
187//! and `p` is `[_, false, _]`, the `Some` constructor doesn't appear in `P`. So if we
188//! only had row 2, we'd know that `p` is useful. However row 1 starts with a
189//! wildcard, so we need to check whether `U([[true, _]], [false, 1])`.
190//!
191//! - Otherwise, all possible constructors (for the relevant type) are present. In this
192//! case we must check whether the wildcard pattern covers any unmatched value. For
193//! that, we can think of the `_` pattern as a big OR-pattern that covers all
194//! possible constructors. For `Option`, that would mean `_ = None | Some(_)` for
195//! example. The wildcard pattern is useful in this case if it is useful when
196//! specialized to one of the possible constructors. So we compute:
197//! `U(P, p) := ∃(k ϵ constructors) U(S(k, P), S(k, p))`
198//!
199//! For example, if `P` is:
200//! ```text
201//! [
202//! [Some(true), _],
203//! [None, false],
204//! ]
205//! ```
206//! and `p` is `[_, false]`, both `None` and `Some` constructors appear in the first
207//! components of `P`. We will therefore try popping both constructors in turn: we
208//! compute `U([[true, _]], [_, false])` for the `Some` constructor, and `U([[false]],
209//! [false])` for the `None` constructor. The first case returns true, so we know that
210//! `p` is useful for `P`. Indeed, it matches `[Some(false), _]` that wasn't matched
211//! before.
212//!
213//! - If `p_1 == r_1 | r_2`, then the usefulness depends on each `r_i` separately:
214//!
215//! ```text
216//! U(P, p) := U(P, (r_1, p_2, .., p_n))
217//! || U(P, (r_2, p_2, .., p_n))
218//! ```
219use std::sync::Arc;
220
221use hir_def::{
222 adt::VariantData,
223 body::Body,
224 expr::{Expr, Literal, Pat, PatId},
225 AdtId, EnumVariantId, VariantId,
226};
227use ra_arena::Idx;
228use smallvec::{smallvec, SmallVec};
229
230use crate::{db::HirDatabase, ApplicationTy, InferenceResult, Ty, TypeCtor};
231
232#[derive(Debug, Clone, Copy)]
233/// Either a pattern from the source code being analyzed, represented as
234/// as `PatId`, or a `Wild` pattern which is created as an intermediate
235/// step in the match checking algorithm and thus is not backed by a
236/// real `PatId`.
237///
238/// Note that it is totally valid for the `PatId` variant to contain
239/// a `PatId` which resolves to a `Wild` pattern, if that wild pattern
240/// exists in the source code being analyzed.
241enum PatIdOrWild {
242 PatId(PatId),
243 Wild,
244}
245
246impl PatIdOrWild {
247 fn as_pat(self, cx: &MatchCheckCtx) -> Pat {
248 match self {
249 PatIdOrWild::PatId(id) => cx.body.pats[id].clone(),
250 PatIdOrWild::Wild => Pat::Wild,
251 }
252 }
253
254 fn as_id(self) -> Option<PatId> {
255 match self {
256 PatIdOrWild::PatId(id) => Some(id),
257 PatIdOrWild::Wild => None,
258 }
259 }
260}
261
262impl From<PatId> for PatIdOrWild {
263 fn from(pat_id: PatId) -> Self {
264 Self::PatId(pat_id)
265 }
266}
267
268impl From<&PatId> for PatIdOrWild {
269 fn from(pat_id: &PatId) -> Self {
270 Self::PatId(*pat_id)
271 }
272}
273
274#[derive(Debug, Clone, Copy, PartialEq)]
275pub enum MatchCheckErr {
276 NotImplemented,
277 MalformedMatchArm,
278 /// Used when type inference cannot resolve the type of
279 /// a pattern or expression.
280 Unknown,
281}
282
283/// The return type of `is_useful` is either an indication of usefulness
284/// of the match arm, or an error in the case the match statement
285/// is made up of types for which exhaustiveness checking is currently
286/// not completely implemented.
287///
288/// The `std::result::Result` type is used here rather than a custom enum
289/// to allow the use of `?`.
290pub type MatchCheckResult<T> = Result<T, MatchCheckErr>;
291
292#[derive(Debug)]
293/// A row in a Matrix.
294///
295/// This type is modeled from the struct of the same name in `rustc`.
296pub(crate) struct PatStack(PatStackInner);
297type PatStackInner = SmallVec<[PatIdOrWild; 2]>;
298
299impl PatStack {
300 pub(crate) fn from_pattern(pat_id: PatId) -> PatStack {
301 Self(smallvec!(pat_id.into()))
302 }
303
304 pub(crate) fn from_wild() -> PatStack {
305 Self(smallvec!(PatIdOrWild::Wild))
306 }
307
308 fn from_slice(slice: &[PatIdOrWild]) -> PatStack {
309 Self(SmallVec::from_slice(slice))
310 }
311
312 fn from_vec(v: PatStackInner) -> PatStack {
313 Self(v)
314 }
315
316 fn get_head(&self) -> Option<PatIdOrWild> {
317 self.0.first().copied()
318 }
319
320 fn tail(&self) -> &[PatIdOrWild] {
321 self.0.get(1..).unwrap_or(&[])
322 }
323
324 fn to_tail(&self) -> PatStack {
325 Self::from_slice(self.tail())
326 }
327
328 fn replace_head_with<I, T>(&self, pats: I) -> PatStack
329 where
330 I: Iterator<Item = T>,
331 T: Into<PatIdOrWild>,
332 {
333 let mut patterns: PatStackInner = smallvec![];
334 for pat in pats {
335 patterns.push(pat.into());
336 }
337 for pat in &self.0[1..] {
338 patterns.push(*pat);
339 }
340 PatStack::from_vec(patterns)
341 }
342
343 /// Computes `D(self)`.
344 ///
345 /// See the module docs and the associated documentation in rustc for details.
346 fn specialize_wildcard(&self, cx: &MatchCheckCtx) -> Option<PatStack> {
347 if matches!(self.get_head()?.as_pat(cx), Pat::Wild) {
348 Some(self.to_tail())
349 } else {
350 None
351 }
352 }
353
354 /// Computes `S(constructor, self)`.
355 ///
356 /// See the module docs and the associated documentation in rustc for details.
357 fn specialize_constructor(
358 &self,
359 cx: &MatchCheckCtx,
360 constructor: &Constructor,
361 ) -> MatchCheckResult<Option<PatStack>> {
362 let head = match self.get_head() {
363 Some(head) => head,
364 None => return Ok(None),
365 };
366
367 let head_pat = head.as_pat(cx);
368 let result = match (head_pat, constructor) {
369 (Pat::Tuple { args: ref pat_ids, ellipsis }, Constructor::Tuple { arity: _ }) => {
370 if ellipsis.is_some() {
371 // If there are ellipsis here, we should add the correct number of
372 // Pat::Wild patterns to `pat_ids`. We should be able to use the
373 // constructors arity for this, but at the time of writing we aren't
374 // correctly calculating this arity when ellipsis are present.
375 return Err(MatchCheckErr::NotImplemented);
376 }
377
378 Some(self.replace_head_with(pat_ids.iter()))
379 }
380 (Pat::Lit(lit_expr), Constructor::Bool(constructor_val)) => {
381 match cx.body.exprs[lit_expr] {
382 Expr::Literal(Literal::Bool(pat_val)) if *constructor_val == pat_val => {
383 Some(self.to_tail())
384 }
385 // it was a bool but the value doesn't match
386 Expr::Literal(Literal::Bool(_)) => None,
387 // perhaps this is actually unreachable given we have
388 // already checked that these match arms have the appropriate type?
389 _ => return Err(MatchCheckErr::NotImplemented),
390 }
391 }
392 (Pat::Wild, constructor) => Some(self.expand_wildcard(cx, constructor)?),
393 (Pat::Path(_), Constructor::Enum(constructor)) => {
394 // unit enum variants become `Pat::Path`
395 let pat_id = head.as_id().expect("we know this isn't a wild");
396 if !enum_variant_matches(cx, pat_id, *constructor) {
397 None
398 } else {
399 Some(self.to_tail())
400 }
401 }
402 (
403 Pat::TupleStruct { args: ref pat_ids, ellipsis, .. },
404 Constructor::Enum(enum_constructor),
405 ) => {
406 let pat_id = head.as_id().expect("we know this isn't a wild");
407 if !enum_variant_matches(cx, pat_id, *enum_constructor) {
408 None
409 } else {
410 let constructor_arity = constructor.arity(cx)?;
411 if let Some(ellipsis_position) = ellipsis {
412 // If there are ellipsis in the pattern, the ellipsis must take the place
413 // of at least one sub-pattern, so `pat_ids` should be smaller than the
414 // constructor arity.
415 if pat_ids.len() < constructor_arity {
416 let mut new_patterns: Vec<PatIdOrWild> = vec![];
417
418 for pat_id in &pat_ids[0..ellipsis_position] {
419 new_patterns.push((*pat_id).into());
420 }
421
422 for _ in 0..(constructor_arity - pat_ids.len()) {
423 new_patterns.push(PatIdOrWild::Wild);
424 }
425
426 for pat_id in &pat_ids[ellipsis_position..pat_ids.len()] {
427 new_patterns.push((*pat_id).into());
428 }
429
430 Some(self.replace_head_with(new_patterns.into_iter()))
431 } else {
432 return Err(MatchCheckErr::MalformedMatchArm);
433 }
434 } else {
435 // If there is no ellipsis in the tuple pattern, the number
436 // of patterns must equal the constructor arity.
437 if pat_ids.len() == constructor_arity {
438 Some(self.replace_head_with(pat_ids.into_iter()))
439 } else {
440 return Err(MatchCheckErr::MalformedMatchArm);
441 }
442 }
443 }
444 }
445 (Pat::Record { args: ref arg_patterns, .. }, Constructor::Enum(e)) => {
446 let pat_id = head.as_id().expect("we know this isn't a wild");
447 if !enum_variant_matches(cx, pat_id, *e) {
448 None
449 } else {
450 match cx.db.enum_data(e.parent).variants[e.local_id].variant_data.as_ref() {
451 VariantData::Record(struct_field_arena) => {
452 // Here we treat any missing fields in the record as the wild pattern, as
453 // if the record has ellipsis. We want to do this here even if the
454 // record does not contain ellipsis, because it allows us to continue
455 // enforcing exhaustiveness for the rest of the match statement.
456 //
457 // Creating the diagnostic for the missing field in the pattern
458 // should be done in a different diagnostic.
459 let patterns = struct_field_arena.iter().map(|(_, struct_field)| {
460 arg_patterns
461 .iter()
462 .find(|pat| pat.name == struct_field.name)
463 .map(|pat| PatIdOrWild::from(pat.pat))
464 .unwrap_or(PatIdOrWild::Wild)
465 });
466
467 Some(self.replace_head_with(patterns))
468 }
469 _ => return Err(MatchCheckErr::Unknown),
470 }
471 }
472 }
473 (Pat::Or(_), _) => return Err(MatchCheckErr::NotImplemented),
474 (_, _) => return Err(MatchCheckErr::NotImplemented),
475 };
476
477 Ok(result)
478 }
479
480 /// A special case of `specialize_constructor` where the head of the pattern stack
481 /// is a Wild pattern.
482 ///
483 /// Replaces the Wild pattern at the head of the pattern stack with N Wild patterns
484 /// (N >= 0), where N is the arity of the given constructor.
485 fn expand_wildcard(
486 &self,
487 cx: &MatchCheckCtx,
488 constructor: &Constructor,
489 ) -> MatchCheckResult<PatStack> {
490 assert_eq!(
491 Pat::Wild,
492 self.get_head().expect("expand_wildcard called on empty PatStack").as_pat(cx),
493 "expand_wildcard must only be called on PatStack with wild at head",
494 );
495
496 let mut patterns: PatStackInner = smallvec![];
497
498 for _ in 0..constructor.arity(cx)? {
499 patterns.push(PatIdOrWild::Wild);
500 }
501
502 for pat in &self.0[1..] {
503 patterns.push(*pat);
504 }
505
506 Ok(PatStack::from_vec(patterns))
507 }
508}
509
510/// A collection of PatStack.
511///
512/// This type is modeled from the struct of the same name in `rustc`.
513pub(crate) struct Matrix(Vec<PatStack>);
514
515impl Matrix {
516 pub(crate) fn empty() -> Self {
517 Self(vec![])
518 }
519
520 pub(crate) fn push(&mut self, cx: &MatchCheckCtx, row: PatStack) {
521 if let Some(Pat::Or(pat_ids)) = row.get_head().map(|pat_id| pat_id.as_pat(cx)) {
522 // Or patterns are expanded here
523 for pat_id in pat_ids {
524 self.0.push(PatStack::from_pattern(pat_id));
525 }
526 } else {
527 self.0.push(row);
528 }
529 }
530
531 fn is_empty(&self) -> bool {
532 self.0.is_empty()
533 }
534
535 fn heads(&self) -> Vec<PatIdOrWild> {
536 self.0.iter().flat_map(|p| p.get_head()).collect()
537 }
538
539 /// Computes `D(self)` for each contained PatStack.
540 ///
541 /// See the module docs and the associated documentation in rustc for details.
542 fn specialize_wildcard(&self, cx: &MatchCheckCtx) -> Self {
543 Self::collect(cx, self.0.iter().filter_map(|r| r.specialize_wildcard(cx)))
544 }
545
546 /// Computes `S(constructor, self)` for each contained PatStack.
547 ///
548 /// See the module docs and the associated documentation in rustc for details.
549 fn specialize_constructor(
550 &self,
551 cx: &MatchCheckCtx,
552 constructor: &Constructor,
553 ) -> MatchCheckResult<Self> {
554 let mut new_matrix = Matrix::empty();
555 for pat in &self.0 {
556 if let Some(pat) = pat.specialize_constructor(cx, constructor)? {
557 new_matrix.push(cx, pat);
558 }
559 }
560
561 Ok(new_matrix)
562 }
563
564 fn collect<T: IntoIterator<Item = PatStack>>(cx: &MatchCheckCtx, iter: T) -> Self {
565 let mut matrix = Matrix::empty();
566
567 for pat in iter {
568 // using push ensures we expand or-patterns
569 matrix.push(cx, pat);
570 }
571
572 matrix
573 }
574}
575
576#[derive(Clone, Debug, PartialEq)]
577/// An indication of the usefulness of a given match arm, where
578/// usefulness is defined as matching some patterns which were
579/// not matched by an prior match arms.
580///
581/// We may eventually need an `Unknown` variant here.
582pub enum Usefulness {
583 Useful,
584 NotUseful,
585}
586
587pub struct MatchCheckCtx<'a> {
588 pub match_expr: Idx<Expr>,
589 pub body: Arc<Body>,
590 pub infer: Arc<InferenceResult>,
591 pub db: &'a dyn HirDatabase,
592}
593
594/// Given a set of patterns `matrix`, and pattern to consider `v`, determines
595/// whether `v` is useful. A pattern is useful if it covers cases which were
596/// not previously covered.
597///
598/// When calling this function externally (that is, not the recursive calls) it
599/// expected that you have already type checked the match arms. All patterns in
600/// matrix should be the same type as v, as well as they should all be the same
601/// type as the match expression.
602pub(crate) fn is_useful(
603 cx: &MatchCheckCtx,
604 matrix: &Matrix,
605 v: &PatStack,
606) -> MatchCheckResult<Usefulness> {
607 // Handle two special cases:
608 // - enum with no variants
609 // - `!` type
610 // In those cases, no match arm is useful.
611 match cx.infer[cx.match_expr].strip_references() {
612 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(AdtId::EnumId(enum_id)), .. }) => {
613 if cx.db.enum_data(*enum_id).variants.is_empty() {
614 return Ok(Usefulness::NotUseful);
615 }
616 }
617 Ty::Apply(ApplicationTy { ctor: TypeCtor::Never, .. }) => {
618 return Ok(Usefulness::NotUseful);
619 }
620 _ => (),
621 }
622
623 let head = match v.get_head() {
624 Some(head) => head,
625 None => {
626 let result = if matrix.is_empty() { Usefulness::Useful } else { Usefulness::NotUseful };
627
628 return Ok(result);
629 }
630 };
631
632 if let Pat::Or(pat_ids) = head.as_pat(cx) {
633 let mut found_unimplemented = false;
634 let any_useful = pat_ids.iter().any(|&pat_id| {
635 let v = PatStack::from_pattern(pat_id);
636
637 match is_useful(cx, matrix, &v) {
638 Ok(Usefulness::Useful) => true,
639 Ok(Usefulness::NotUseful) => false,
640 _ => {
641 found_unimplemented = true;
642 false
643 }
644 }
645 });
646
647 return if any_useful {
648 Ok(Usefulness::Useful)
649 } else if found_unimplemented {
650 Err(MatchCheckErr::NotImplemented)
651 } else {
652 Ok(Usefulness::NotUseful)
653 };
654 }
655
656 if let Some(constructor) = pat_constructor(cx, head)? {
657 let matrix = matrix.specialize_constructor(&cx, &constructor)?;
658 let v = v
659 .specialize_constructor(&cx, &constructor)?
660 .expect("we know this can't fail because we get the constructor from `v.head()` above");
661
662 is_useful(&cx, &matrix, &v)
663 } else {
664 // expanding wildcard
665 let mut used_constructors: Vec<Constructor> = vec![];
666 for pat in matrix.heads() {
667 if let Some(constructor) = pat_constructor(cx, pat)? {
668 used_constructors.push(constructor);
669 }
670 }
671
672 // We assume here that the first constructor is the "correct" type. Since we
673 // only care about the "type" of the constructor (i.e. if it is a bool we
674 // don't care about the value), this assumption should be valid as long as
675 // the match statement is well formed. We currently uphold this invariant by
676 // filtering match arms before calling `is_useful`, only passing in match arms
677 // whose type matches the type of the match expression.
678 match &used_constructors.first() {
679 Some(constructor) if all_constructors_covered(&cx, constructor, &used_constructors) => {
680 // If all constructors are covered, then we need to consider whether
681 // any values are covered by this wildcard.
682 //
683 // For example, with matrix '[[Some(true)], [None]]', all
684 // constructors are covered (`Some`/`None`), so we need
685 // to perform specialization to see that our wildcard will cover
686 // the `Some(false)` case.
687 //
688 // Here we create a constructor for each variant and then check
689 // usefulness after specializing for that constructor.
690 let mut found_unimplemented = false;
691 for constructor in constructor.all_constructors(cx) {
692 let matrix = matrix.specialize_constructor(&cx, &constructor)?;
693 let v = v.expand_wildcard(&cx, &constructor)?;
694
695 match is_useful(&cx, &matrix, &v) {
696 Ok(Usefulness::Useful) => return Ok(Usefulness::Useful),
697 Ok(Usefulness::NotUseful) => continue,
698 _ => found_unimplemented = true,
699 };
700 }
701
702 if found_unimplemented {
703 Err(MatchCheckErr::NotImplemented)
704 } else {
705 Ok(Usefulness::NotUseful)
706 }
707 }
708 _ => {
709 // Either not all constructors are covered, or the only other arms
710 // are wildcards. Either way, this pattern is useful if it is useful
711 // when compared to those arms with wildcards.
712 let matrix = matrix.specialize_wildcard(&cx);
713 let v = v.to_tail();
714
715 is_useful(&cx, &matrix, &v)
716 }
717 }
718 }
719}
720
721#[derive(Debug, Clone, Copy)]
722/// Similar to TypeCtor, but includes additional information about the specific
723/// value being instantiated. For example, TypeCtor::Bool doesn't contain the
724/// boolean value.
725enum Constructor {
726 Bool(bool),
727 Tuple { arity: usize },
728 Enum(EnumVariantId),
729}
730
731impl Constructor {
732 fn arity(&self, cx: &MatchCheckCtx) -> MatchCheckResult<usize> {
733 let arity = match self {
734 Constructor::Bool(_) => 0,
735 Constructor::Tuple { arity } => *arity,
736 Constructor::Enum(e) => {
737 match cx.db.enum_data(e.parent).variants[e.local_id].variant_data.as_ref() {
738 VariantData::Tuple(struct_field_data) => struct_field_data.len(),
739 VariantData::Record(struct_field_data) => struct_field_data.len(),
740 VariantData::Unit => 0,
741 }
742 }
743 };
744
745 Ok(arity)
746 }
747
748 fn all_constructors(&self, cx: &MatchCheckCtx) -> Vec<Constructor> {
749 match self {
750 Constructor::Bool(_) => vec![Constructor::Bool(true), Constructor::Bool(false)],
751 Constructor::Tuple { .. } => vec![*self],
752 Constructor::Enum(e) => cx
753 .db
754 .enum_data(e.parent)
755 .variants
756 .iter()
757 .map(|(local_id, _)| {
758 Constructor::Enum(EnumVariantId { parent: e.parent, local_id })
759 })
760 .collect(),
761 }
762 }
763}
764
765/// Returns the constructor for the given pattern. Should only return None
766/// in the case of a Wild pattern.
767fn pat_constructor(cx: &MatchCheckCtx, pat: PatIdOrWild) -> MatchCheckResult<Option<Constructor>> {
768 let res = match pat.as_pat(cx) {
769 Pat::Wild => None,
770 // FIXME somehow create the Tuple constructor with the proper arity. If there are
771 // ellipsis, the arity is not equal to the number of patterns.
772 Pat::Tuple { args: pats, ellipsis } if ellipsis.is_none() => {
773 Some(Constructor::Tuple { arity: pats.len() })
774 }
775 Pat::Lit(lit_expr) => match cx.body.exprs[lit_expr] {
776 Expr::Literal(Literal::Bool(val)) => Some(Constructor::Bool(val)),
777 _ => return Err(MatchCheckErr::NotImplemented),
778 },
779 Pat::TupleStruct { .. } | Pat::Path(_) | Pat::Record { .. } => {
780 let pat_id = pat.as_id().expect("we already know this pattern is not a wild");
781 let variant_id =
782 cx.infer.variant_resolution_for_pat(pat_id).ok_or(MatchCheckErr::Unknown)?;
783 match variant_id {
784 VariantId::EnumVariantId(enum_variant_id) => {
785 Some(Constructor::Enum(enum_variant_id))
786 }
787 _ => return Err(MatchCheckErr::NotImplemented),
788 }
789 }
790 _ => return Err(MatchCheckErr::NotImplemented),
791 };
792
793 Ok(res)
794}
795
796fn all_constructors_covered(
797 cx: &MatchCheckCtx,
798 constructor: &Constructor,
799 used_constructors: &[Constructor],
800) -> bool {
801 match constructor {
802 Constructor::Tuple { arity } => {
803 used_constructors.iter().any(|constructor| match constructor {
804 Constructor::Tuple { arity: used_arity } => arity == used_arity,
805 _ => false,
806 })
807 }
808 Constructor::Bool(_) => {
809 if used_constructors.is_empty() {
810 return false;
811 }
812
813 let covers_true =
814 used_constructors.iter().any(|c| matches!(c, Constructor::Bool(true)));
815 let covers_false =
816 used_constructors.iter().any(|c| matches!(c, Constructor::Bool(false)));
817
818 covers_true && covers_false
819 }
820 Constructor::Enum(e) => cx.db.enum_data(e.parent).variants.iter().all(|(id, _)| {
821 for constructor in used_constructors {
822 if let Constructor::Enum(e) = constructor {
823 if id == e.local_id {
824 return true;
825 }
826 }
827 }
828
829 false
830 }),
831 }
832}
833
834fn enum_variant_matches(cx: &MatchCheckCtx, pat_id: PatId, enum_variant_id: EnumVariantId) -> bool {
835 Some(enum_variant_id.into()) == cx.infer.variant_resolution_for_pat(pat_id)
836}
837
838#[cfg(test)]
839mod tests {
840 pub(super) use insta::assert_snapshot;
841 pub(super) use ra_db::fixture::WithFixture;
842
843 pub(super) use crate::{diagnostics::MissingMatchArms, test_db::TestDB};
844
845 pub(super) fn check_diagnostic_message(ra_fixture: &str) -> String {
846 TestDB::with_single_file(ra_fixture).0.diagnostic::<MissingMatchArms>().0
847 }
848
849 pub(super) fn check_diagnostic(ra_fixture: &str) {
850 let diagnostic_count =
851 TestDB::with_single_file(ra_fixture).0.diagnostic::<MissingMatchArms>().1;
852
853 assert_eq!(1, diagnostic_count, "no diagnostic reported");
854 }
855
856 pub(super) fn check_no_diagnostic(ra_fixture: &str) {
857 let (s, diagnostic_count) =
858 TestDB::with_single_file(ra_fixture).0.diagnostic::<MissingMatchArms>();
859
860 assert_eq!(0, diagnostic_count, "expected no diagnostic, found one: {}", s);
861 }
862
863 #[test]
864 fn empty_tuple_no_arms_diagnostic_message() {
865 assert_snapshot!(
866 check_diagnostic_message(r"
867 fn test_fn() {
868 match () {
869 }
870 }
871 "),
872 @"\"()\": Missing match arm\n"
873 );
874 }
875
876 #[test]
877 fn empty_tuple_no_arms() {
878 check_diagnostic(
879 r"
880 fn test_fn() {
881 match () {
882 }
883 }
884 ",
885 );
886 }
887
888 #[test]
889 fn empty_tuple_wild() {
890 check_no_diagnostic(
891 r"
892 fn test_fn() {
893 match () {
894 _ => {}
895 }
896 }
897 ",
898 );
899 }
900
901 #[test]
902 fn empty_tuple_no_diagnostic() {
903 check_no_diagnostic(
904 r"
905 fn test_fn() {
906 match () {
907 () => {}
908 }
909 }
910 ",
911 );
912 }
913
914 #[test]
915 fn tuple_of_empty_tuple_no_arms() {
916 check_diagnostic(
917 r"
918 fn test_fn() {
919 match (()) {
920 }
921 }
922 ",
923 );
924 }
925
926 #[test]
927 fn tuple_of_empty_tuple_no_diagnostic() {
928 check_no_diagnostic(
929 r"
930 fn test_fn() {
931 match (()) {
932 (()) => {}
933 }
934 }
935 ",
936 );
937 }
938
939 #[test]
940 fn tuple_of_two_empty_tuple_no_arms() {
941 check_diagnostic(
942 r"
943 fn test_fn() {
944 match ((), ()) {
945 }
946 }
947 ",
948 );
949 }
950
951 #[test]
952 fn tuple_of_two_empty_tuple_no_diagnostic() {
953 check_no_diagnostic(
954 r"
955 fn test_fn() {
956 match ((), ()) {
957 ((), ()) => {}
958 }
959 }
960 ",
961 );
962 }
963
964 #[test]
965 fn bool_no_arms() {
966 check_diagnostic(
967 r"
968 fn test_fn() {
969 match false {
970 }
971 }
972 ",
973 );
974 }
975
976 #[test]
977 fn bool_missing_arm() {
978 check_diagnostic(
979 r"
980 fn test_fn() {
981 match false {
982 true => {}
983 }
984 }
985 ",
986 );
987 }
988
989 #[test]
990 fn bool_no_diagnostic() {
991 check_no_diagnostic(
992 r"
993 fn test_fn() {
994 match false {
995 true => {}
996 false => {}
997 }
998 }
999 ",
1000 );
1001 }
1002
1003 #[test]
1004 fn tuple_of_bools_no_arms() {
1005 check_diagnostic(
1006 r"
1007 fn test_fn() {
1008 match (false, true) {
1009 }
1010 }
1011 ",
1012 );
1013 }
1014
1015 #[test]
1016 fn tuple_of_bools_missing_arms() {
1017 check_diagnostic(
1018 r"
1019 fn test_fn() {
1020 match (false, true) {
1021 (true, true) => {},
1022 }
1023 }
1024 ",
1025 );
1026 }
1027
1028 #[test]
1029 fn tuple_of_bools_missing_arm() {
1030 check_diagnostic(
1031 r"
1032 fn test_fn() {
1033 match (false, true) {
1034 (false, true) => {},
1035 (false, false) => {},
1036 (true, false) => {},
1037 }
1038 }
1039 ",
1040 );
1041 }
1042
1043 #[test]
1044 fn tuple_of_bools_with_wilds() {
1045 check_no_diagnostic(
1046 r"
1047 fn test_fn() {
1048 match (false, true) {
1049 (false, _) => {},
1050 (true, false) => {},
1051 (_, true) => {},
1052 }
1053 }
1054 ",
1055 );
1056 }
1057
1058 #[test]
1059 fn tuple_of_bools_no_diagnostic() {
1060 check_no_diagnostic(
1061 r"
1062 fn test_fn() {
1063 match (false, true) {
1064 (true, true) => {},
1065 (true, false) => {},
1066 (false, true) => {},
1067 (false, false) => {},
1068 }
1069 }
1070 ",
1071 );
1072 }
1073
1074 #[test]
1075 fn tuple_of_bools_binding_missing_arms() {
1076 check_diagnostic(
1077 r"
1078 fn test_fn() {
1079 match (false, true) {
1080 (true, _x) => {},
1081 }
1082 }
1083 ",
1084 );
1085 }
1086
1087 #[test]
1088 fn tuple_of_bools_binding_no_diagnostic() {
1089 check_no_diagnostic(
1090 r"
1091 fn test_fn() {
1092 match (false, true) {
1093 (true, _x) => {},
1094 (false, true) => {},
1095 (false, false) => {},
1096 }
1097 }
1098 ",
1099 );
1100 }
1101
1102 #[test]
1103 fn tuple_of_bools_with_ellipsis_at_end_no_diagnostic() {
1104 check_no_diagnostic(
1105 r"
1106 fn test_fn() {
1107 match (false, true, false) {
1108 (false, ..) => {},
1109 (true, ..) => {},
1110 }
1111 }
1112 ",
1113 );
1114 }
1115
1116 #[test]
1117 fn tuple_of_bools_with_ellipsis_at_beginning_no_diagnostic() {
1118 check_no_diagnostic(
1119 r"
1120 fn test_fn() {
1121 match (false, true, false) {
1122 (.., false) => {},
1123 (.., true) => {},
1124 }
1125 }
1126 ",
1127 );
1128 }
1129
1130 #[test]
1131 fn tuple_of_bools_with_ellipsis_no_diagnostic() {
1132 check_no_diagnostic(
1133 r"
1134 fn test_fn() {
1135 match (false, true, false) {
1136 (..) => {},
1137 }
1138 }
1139 ",
1140 );
1141 }
1142
1143 #[test]
1144 fn tuple_of_tuple_and_bools_no_arms() {
1145 check_diagnostic(
1146 r"
1147 fn test_fn() {
1148 match (false, ((), false)) {
1149 }
1150 }
1151 ",
1152 );
1153 }
1154
1155 #[test]
1156 fn tuple_of_tuple_and_bools_missing_arms() {
1157 check_diagnostic(
1158 r"
1159 fn test_fn() {
1160 match (false, ((), false)) {
1161 (true, ((), true)) => {},
1162 }
1163 }
1164 ",
1165 );
1166 }
1167
1168 #[test]
1169 fn tuple_of_tuple_and_bools_no_diagnostic() {
1170 check_no_diagnostic(
1171 r"
1172 fn test_fn() {
1173 match (false, ((), false)) {
1174 (true, ((), true)) => {},
1175 (true, ((), false)) => {},
1176 (false, ((), true)) => {},
1177 (false, ((), false)) => {},
1178 }
1179 }
1180 ",
1181 );
1182 }
1183
1184 #[test]
1185 fn tuple_of_tuple_and_bools_wildcard_missing_arms() {
1186 check_diagnostic(
1187 r"
1188 fn test_fn() {
1189 match (false, ((), false)) {
1190 (true, _) => {},
1191 }
1192 }
1193 ",
1194 );
1195 }
1196
1197 #[test]
1198 fn tuple_of_tuple_and_bools_wildcard_no_diagnostic() {
1199 check_no_diagnostic(
1200 r"
1201 fn test_fn() {
1202 match (false, ((), false)) {
1203 (true, ((), true)) => {},
1204 (true, ((), false)) => {},
1205 (false, _) => {},
1206 }
1207 }
1208 ",
1209 );
1210 }
1211
1212 #[test]
1213 fn enum_no_arms() {
1214 check_diagnostic(
1215 r"
1216 enum Either {
1217 A,
1218 B,
1219 }
1220 fn test_fn() {
1221 match Either::A {
1222 }
1223 }
1224 ",
1225 );
1226 }
1227
1228 #[test]
1229 fn enum_missing_arms() {
1230 check_diagnostic(
1231 r"
1232 enum Either {
1233 A,
1234 B,
1235 }
1236 fn test_fn() {
1237 match Either::B {
1238 Either::A => {},
1239 }
1240 }
1241 ",
1242 );
1243 }
1244
1245 #[test]
1246 fn enum_no_diagnostic() {
1247 check_no_diagnostic(
1248 r"
1249 enum Either {
1250 A,
1251 B,
1252 }
1253 fn test_fn() {
1254 match Either::B {
1255 Either::A => {},
1256 Either::B => {},
1257 }
1258 }
1259 ",
1260 );
1261 }
1262
1263 #[test]
1264 fn enum_ref_missing_arms() {
1265 check_diagnostic(
1266 r"
1267 enum Either {
1268 A,
1269 B,
1270 }
1271 fn test_fn() {
1272 match &Either::B {
1273 Either::A => {},
1274 }
1275 }
1276 ",
1277 );
1278 }
1279
1280 #[test]
1281 fn enum_ref_no_diagnostic() {
1282 check_no_diagnostic(
1283 r"
1284 enum Either {
1285 A,
1286 B,
1287 }
1288 fn test_fn() {
1289 match &Either::B {
1290 Either::A => {},
1291 Either::B => {},
1292 }
1293 }
1294 ",
1295 );
1296 }
1297
1298 #[test]
1299 fn enum_containing_bool_no_arms() {
1300 check_diagnostic(
1301 r"
1302 enum Either {
1303 A(bool),
1304 B,
1305 }
1306 fn test_fn() {
1307 match Either::B {
1308 }
1309 }
1310 ",
1311 );
1312 }
1313
1314 #[test]
1315 fn enum_containing_bool_missing_arms() {
1316 check_diagnostic(
1317 r"
1318 enum Either {
1319 A(bool),
1320 B,
1321 }
1322 fn test_fn() {
1323 match Either::B {
1324 Either::A(true) => (),
1325 Either::B => (),
1326 }
1327 }
1328 ",
1329 );
1330 }
1331
1332 #[test]
1333 fn enum_containing_bool_no_diagnostic() {
1334 check_no_diagnostic(
1335 r"
1336 enum Either {
1337 A(bool),
1338 B,
1339 }
1340 fn test_fn() {
1341 match Either::B {
1342 Either::A(true) => (),
1343 Either::A(false) => (),
1344 Either::B => (),
1345 }
1346 }
1347 ",
1348 );
1349 }
1350
1351 #[test]
1352 fn enum_containing_bool_with_wild_no_diagnostic() {
1353 check_no_diagnostic(
1354 r"
1355 enum Either {
1356 A(bool),
1357 B,
1358 }
1359 fn test_fn() {
1360 match Either::B {
1361 Either::B => (),
1362 _ => (),
1363 }
1364 }
1365 ",
1366 );
1367 }
1368
1369 #[test]
1370 fn enum_containing_bool_with_wild_2_no_diagnostic() {
1371 check_no_diagnostic(
1372 r"
1373 enum Either {
1374 A(bool),
1375 B,
1376 }
1377 fn test_fn() {
1378 match Either::B {
1379 Either::A(_) => (),
1380 Either::B => (),
1381 }
1382 }
1383 ",
1384 );
1385 }
1386
1387 #[test]
1388 fn enum_different_sizes_missing_arms() {
1389 check_diagnostic(
1390 r"
1391 enum Either {
1392 A(bool),
1393 B(bool, bool),
1394 }
1395 fn test_fn() {
1396 match Either::A(false) {
1397 Either::A(_) => (),
1398 Either::B(false, _) => (),
1399 }
1400 }
1401 ",
1402 );
1403 }
1404
1405 #[test]
1406 fn enum_different_sizes_no_diagnostic() {
1407 check_no_diagnostic(
1408 r"
1409 enum Either {
1410 A(bool),
1411 B(bool, bool),
1412 }
1413 fn test_fn() {
1414 match Either::A(false) {
1415 Either::A(_) => (),
1416 Either::B(true, _) => (),
1417 Either::B(false, _) => (),
1418 }
1419 }
1420 ",
1421 );
1422 }
1423
1424 #[test]
1425 fn or_no_diagnostic() {
1426 check_no_diagnostic(
1427 r"
1428 enum Either {
1429 A(bool),
1430 B(bool, bool),
1431 }
1432 fn test_fn() {
1433 match Either::A(false) {
1434 Either::A(true) | Either::A(false) => (),
1435 Either::B(true, _) => (),
1436 Either::B(false, _) => (),
1437 }
1438 }
1439 ",
1440 );
1441 }
1442
1443 #[test]
1444 fn tuple_of_enum_no_diagnostic() {
1445 check_no_diagnostic(
1446 r"
1447 enum Either {
1448 A(bool),
1449 B(bool, bool),
1450 }
1451 enum Either2 {
1452 C,
1453 D,
1454 }
1455 fn test_fn() {
1456 match (Either::A(false), Either2::C) {
1457 (Either::A(true), _) | (Either::A(false), _) => (),
1458 (Either::B(true, _), Either2::C) => (),
1459 (Either::B(false, _), Either2::C) => (),
1460 (Either::B(_, _), Either2::D) => (),
1461 }
1462 }
1463 ",
1464 );
1465 }
1466
1467 #[test]
1468 fn mismatched_types() {
1469 // Match statements with arms that don't match the
1470 // expression pattern do not fire this diagnostic.
1471 check_no_diagnostic(
1472 r"
1473 enum Either {
1474 A,
1475 B,
1476 }
1477 enum Either2 {
1478 C,
1479 D,
1480 }
1481 fn test_fn() {
1482 match Either::A {
1483 Either2::C => (),
1484 Either2::D => (),
1485 }
1486 }
1487 ",
1488 );
1489 }
1490
1491 #[test]
1492 fn mismatched_types_with_different_arity() {
1493 // Match statements with arms that don't match the
1494 // expression pattern do not fire this diagnostic.
1495 check_no_diagnostic(
1496 r"
1497 fn test_fn() {
1498 match (true, false) {
1499 (true, false, true) => (),
1500 (true) => (),
1501 }
1502 }
1503 ",
1504 );
1505 }
1506
1507 #[test]
1508 fn malformed_match_arm_tuple_missing_pattern() {
1509 // Match statements with arms that don't match the
1510 // expression pattern do not fire this diagnostic.
1511 check_no_diagnostic(
1512 r"
1513 fn test_fn() {
1514 match (0) {
1515 () => (),
1516 }
1517 }
1518 ",
1519 );
1520 }
1521
1522 #[test]
1523 fn malformed_match_arm_tuple_enum_missing_pattern() {
1524 // We are testing to be sure we don't panic here when the match
1525 // arm `Either::B` is missing its pattern.
1526 check_no_diagnostic(
1527 r"
1528 enum Either {
1529 A,
1530 B(u32),
1531 }
1532 fn test_fn() {
1533 match Either::A {
1534 Either::A => (),
1535 Either::B() => (),
1536 }
1537 }
1538 ",
1539 );
1540 }
1541
1542 #[test]
1543 fn enum_not_in_scope() {
1544 // The enum is not in scope so we don't perform exhaustiveness
1545 // checking, but we want to be sure we don't panic here (and
1546 // we don't create a diagnostic).
1547 check_no_diagnostic(
1548 r"
1549 fn test_fn() {
1550 match Foo::Bar {
1551 Foo::Baz => (),
1552 }
1553 }
1554 ",
1555 );
1556 }
1557
1558 #[test]
1559 fn expr_diverges() {
1560 check_no_diagnostic(
1561 r"
1562 enum Either {
1563 A,
1564 B,
1565 }
1566 fn test_fn() {
1567 match loop {} {
1568 Either::A => (),
1569 Either::B => (),
1570 }
1571 }
1572 ",
1573 );
1574 }
1575
1576 #[test]
1577 fn expr_loop_with_break() {
1578 check_no_diagnostic(
1579 r"
1580 enum Either {
1581 A,
1582 B,
1583 }
1584 fn test_fn() {
1585 match loop { break Foo::A } {
1586 Either::A => (),
1587 Either::B => (),
1588 }
1589 }
1590 ",
1591 );
1592 }
1593
1594 #[test]
1595 fn expr_partially_diverges() {
1596 check_no_diagnostic(
1597 r"
1598 enum Either<T> {
1599 A(T),
1600 B,
1601 }
1602 fn foo() -> Either<!> {
1603 Either::B
1604 }
1605 fn test_fn() -> u32 {
1606 match foo() {
1607 Either::A(val) => val,
1608 Either::B => 0,
1609 }
1610 }
1611 ",
1612 );
1613 }
1614
1615 #[test]
1616 fn enum_record_no_arms() {
1617 check_diagnostic(
1618 r"
1619 enum Either {
1620 A { foo: bool },
1621 B,
1622 }
1623 fn test_fn() {
1624 let a = Either::A { foo: true };
1625 match a {
1626 }
1627 }
1628 ",
1629 );
1630 }
1631
1632 #[test]
1633 fn enum_record_missing_arms() {
1634 check_diagnostic(
1635 r"
1636 enum Either {
1637 A { foo: bool },
1638 B,
1639 }
1640 fn test_fn() {
1641 let a = Either::A { foo: true };
1642 match a {
1643 Either::A { foo: true } => (),
1644 }
1645 }
1646 ",
1647 );
1648 }
1649
1650 #[test]
1651 fn enum_record_no_diagnostic() {
1652 check_no_diagnostic(
1653 r"
1654 enum Either {
1655 A { foo: bool },
1656 B,
1657 }
1658 fn test_fn() {
1659 let a = Either::A { foo: true };
1660 match a {
1661 Either::A { foo: true } => (),
1662 Either::A { foo: false } => (),
1663 Either::B => (),
1664 }
1665 }
1666 ",
1667 );
1668 }
1669
1670 #[test]
1671 fn enum_record_missing_field_no_diagnostic() {
1672 // When `Either::A` is missing a struct member, we don't want
1673 // to fire the missing match arm diagnostic. This should fire
1674 // some other diagnostic.
1675 check_no_diagnostic(
1676 r"
1677 enum Either {
1678 A { foo: bool },
1679 B,
1680 }
1681 fn test_fn() {
1682 let a = Either::B;
1683 match a {
1684 Either::A { } => (),
1685 Either::B => (),
1686 }
1687 }
1688 ",
1689 );
1690 }
1691
1692 #[test]
1693 fn enum_record_missing_field_missing_match_arm() {
1694 // Even though `Either::A` is missing fields, we still want to fire
1695 // the missing arm diagnostic here, since we know `Either::B` is missing.
1696 check_diagnostic(
1697 r"
1698 enum Either {
1699 A { foo: bool },
1700 B,
1701 }
1702 fn test_fn() {
1703 let a = Either::B;
1704 match a {
1705 Either::A { } => (),
1706 }
1707 }
1708 ",
1709 );
1710 }
1711
1712 #[test]
1713 fn enum_record_no_diagnostic_wild() {
1714 check_no_diagnostic(
1715 r"
1716 enum Either {
1717 A { foo: bool },
1718 B,
1719 }
1720 fn test_fn() {
1721 let a = Either::A { foo: true };
1722 match a {
1723 Either::A { foo: _ } => (),
1724 Either::B => (),
1725 }
1726 }
1727 ",
1728 );
1729 }
1730
1731 #[test]
1732 fn enum_record_fields_out_of_order_missing_arm() {
1733 check_diagnostic(
1734 r"
1735 enum Either {
1736 A { foo: bool, bar: () },
1737 B,
1738 }
1739 fn test_fn() {
1740 let a = Either::A { foo: true };
1741 match a {
1742 Either::A { bar: (), foo: false } => (),
1743 Either::A { foo: true, bar: () } => (),
1744 }
1745 }
1746 ",
1747 );
1748 }
1749
1750 #[test]
1751 fn enum_record_fields_out_of_order_no_diagnostic() {
1752 check_no_diagnostic(
1753 r"
1754 enum Either {
1755 A { foo: bool, bar: () },
1756 B,
1757 }
1758 fn test_fn() {
1759 let a = Either::A { foo: true };
1760 match a {
1761 Either::A { bar: (), foo: false } => (),
1762 Either::A { foo: true, bar: () } => (),
1763 Either::B => (),
1764 }
1765 }
1766 ",
1767 );
1768 }
1769
1770 #[test]
1771 fn enum_record_ellipsis_missing_arm() {
1772 check_diagnostic(
1773 r"
1774 enum Either {
1775 A { foo: bool, bar: bool },
1776 B,
1777 }
1778 fn test_fn() {
1779 match Either::B {
1780 Either::A { foo: true, .. } => (),
1781 Either::B => (),
1782 }
1783 }
1784 ",
1785 );
1786 }
1787
1788 #[test]
1789 fn enum_record_ellipsis_no_diagnostic() {
1790 check_no_diagnostic(
1791 r"
1792 enum Either {
1793 A { foo: bool, bar: bool },
1794 B,
1795 }
1796 fn test_fn() {
1797 let a = Either::A { foo: true };
1798 match a {
1799 Either::A { foo: true, .. } => (),
1800 Either::A { foo: false, .. } => (),
1801 Either::B => (),
1802 }
1803 }
1804 ",
1805 );
1806 }
1807
1808 #[test]
1809 fn enum_record_ellipsis_all_fields_missing_arm() {
1810 check_diagnostic(
1811 r"
1812 enum Either {
1813 A { foo: bool, bar: bool },
1814 B,
1815 }
1816 fn test_fn() {
1817 let a = Either::B;
1818 match a {
1819 Either::A { .. } => (),
1820 }
1821 }
1822 ",
1823 );
1824 }
1825
1826 #[test]
1827 fn enum_record_ellipsis_all_fields_no_diagnostic() {
1828 check_no_diagnostic(
1829 r"
1830 enum Either {
1831 A { foo: bool, bar: bool },
1832 B,
1833 }
1834 fn test_fn() {
1835 let a = Either::B;
1836 match a {
1837 Either::A { .. } => (),
1838 Either::B => (),
1839 }
1840 }
1841 ",
1842 );
1843 }
1844
1845 #[test]
1846 fn enum_tuple_partial_ellipsis_no_diagnostic() {
1847 check_no_diagnostic(
1848 r"
1849 enum Either {
1850 A(bool, bool, bool, bool),
1851 B,
1852 }
1853 fn test_fn() {
1854 match Either::B {
1855 Either::A(true, .., true) => {},
1856 Either::A(true, .., false) => {},
1857 Either::A(false, .., true) => {},
1858 Either::A(false, .., false) => {},
1859 Either::B => {},
1860 }
1861 }
1862 ",
1863 );
1864 }
1865
1866 #[test]
1867 fn enum_tuple_partial_ellipsis_2_no_diagnostic() {
1868 check_no_diagnostic(
1869 r"
1870 enum Either {
1871 A(bool, bool, bool, bool),
1872 B,
1873 }
1874 fn test_fn() {
1875 match Either::B {
1876 Either::A(true, .., true) => {},
1877 Either::A(true, .., false) => {},
1878 Either::A(.., true) => {},
1879 Either::A(.., false) => {},
1880 Either::B => {},
1881 }
1882 }
1883 ",
1884 );
1885 }
1886
1887 #[test]
1888 fn enum_tuple_partial_ellipsis_missing_arm() {
1889 check_diagnostic(
1890 r"
1891 enum Either {
1892 A(bool, bool, bool, bool),
1893 B,
1894 }
1895 fn test_fn() {
1896 match Either::B {
1897 Either::A(true, .., true) => {},
1898 Either::A(true, .., false) => {},
1899 Either::A(false, .., false) => {},
1900 Either::B => {},
1901 }
1902 }
1903 ",
1904 );
1905 }
1906
1907 #[test]
1908 fn enum_tuple_partial_ellipsis_2_missing_arm() {
1909 check_diagnostic(
1910 r"
1911 enum Either {
1912 A(bool, bool, bool, bool),
1913 B,
1914 }
1915 fn test_fn() {
1916 match Either::B {
1917 Either::A(true, .., true) => {},
1918 Either::A(true, .., false) => {},
1919 Either::A(.., true) => {},
1920 Either::B => {},
1921 }
1922 }
1923 ",
1924 );
1925 }
1926
1927 #[test]
1928 fn enum_tuple_ellipsis_no_diagnostic() {
1929 check_no_diagnostic(
1930 r"
1931 enum Either {
1932 A(bool, bool, bool, bool),
1933 B,
1934 }
1935 fn test_fn() {
1936 match Either::B {
1937 Either::A(..) => {},
1938 Either::B => {},
1939 }
1940 }
1941 ",
1942 );
1943 }
1944
1945 #[test]
1946 fn enum_never() {
1947 check_no_diagnostic(
1948 r"
1949 enum Never {}
1950
1951 fn test_fn(never: Never) {
1952 match never {}
1953 }
1954 ",
1955 );
1956 }
1957
1958 #[test]
1959 fn type_never() {
1960 check_no_diagnostic(
1961 r"
1962 fn test_fn(never: !) {
1963 match never {}
1964 }
1965 ",
1966 );
1967 }
1968
1969 #[test]
1970 fn enum_never_ref() {
1971 check_no_diagnostic(
1972 r"
1973 enum Never {}
1974
1975 fn test_fn(never: &Never) {
1976 match never {}
1977 }
1978 ",
1979 );
1980 }
1981
1982 #[test]
1983 fn expr_diverges_missing_arm() {
1984 check_no_diagnostic(
1985 r"
1986 enum Either {
1987 A,
1988 B,
1989 }
1990 fn test_fn() {
1991 match loop {} {
1992 Either::A => (),
1993 }
1994 }
1995 ",
1996 );
1997 }
1998
1999 #[test]
2000 fn or_pattern_panic() {
2001 check_no_diagnostic(
2002 r"
2003 pub enum Category {
2004 Infinity,
2005 Zero,
2006 }
2007
2008 fn panic(a: Category, b: Category) {
2009 match (a, b) {
2010 (Category::Zero | Category::Infinity, _) => {}
2011 (_, Category::Zero | Category::Infinity) => {}
2012 }
2013 }
2014 ",
2015 );
2016 }
2017
2018 #[test]
2019 fn or_pattern_panic_2() {
2020 // FIXME: This is a false positive, but the code used to cause a panic in the match checker,
2021 // so this acts as a regression test for that.
2022 check_diagnostic(
2023 r"
2024 pub enum Category {
2025 Infinity,
2026 Zero,
2027 }
2028
2029 fn panic(a: Category, b: Category) {
2030 match (a, b) {
2031 (Category::Infinity, Category::Infinity) | (Category::Zero, Category::Zero) => {}
2032
2033 (Category::Infinity | Category::Zero, _) => {}
2034 }
2035 }
2036 ",
2037 );
2038 }
2039}
2040
2041#[cfg(test)]
2042mod false_negatives {
2043 //! The implementation of match checking here is a work in progress. As we roll this out, we
2044 //! prefer false negatives to false positives (ideally there would be no false positives). This
2045 //! test module should document known false negatives. Eventually we will have a complete
2046 //! implementation of match checking and this module will be empty.
2047 //!
2048 //! The reasons for documenting known false negatives:
2049 //!
2050 //! 1. It acts as a backlog of work that can be done to improve the behavior of the system.
2051 //! 2. It ensures the code doesn't panic when handling these cases.
2052
2053 use super::tests::*;
2054
2055 #[test]
2056 fn integers() {
2057 // This is a false negative.
2058 // We don't currently check integer exhaustiveness.
2059 check_no_diagnostic(
2060 r"
2061 fn test_fn() {
2062 match 5 {
2063 10 => (),
2064 11..20 => (),
2065 }
2066 }
2067 ",
2068 );
2069 }
2070
2071 #[test]
2072 fn internal_or() {
2073 // This is a false negative.
2074 // We do not currently handle patterns with internal `or`s.
2075 check_no_diagnostic(
2076 r"
2077 fn test_fn() {
2078 enum Either {
2079 A(bool),
2080 B,
2081 }
2082 match Either::B {
2083 Either::A(true | false) => (),
2084 }
2085 }
2086 ",
2087 );
2088 }
2089
2090 #[test]
2091 fn expr_loop_missing_arm() {
2092 // This is a false negative.
2093 // We currently infer the type of `loop { break Foo::A }` to `!`, which
2094 // causes us to skip the diagnostic since `Either::A` doesn't type check
2095 // with `!`.
2096 check_diagnostic(
2097 r"
2098 enum Either {
2099 A,
2100 B,
2101 }
2102 fn test_fn() {
2103 match loop { break Foo::A } {
2104 Either::A => (),
2105 }
2106 }
2107 ",
2108 );
2109 }
2110
2111 #[test]
2112 fn tuple_of_bools_with_ellipsis_at_end_missing_arm() {
2113 // This is a false negative.
2114 // We don't currently handle tuple patterns with ellipsis.
2115 check_no_diagnostic(
2116 r"
2117 fn test_fn() {
2118 match (false, true, false) {
2119 (false, ..) => {},
2120 }
2121 }
2122 ",
2123 );
2124 }
2125
2126 #[test]
2127 fn tuple_of_bools_with_ellipsis_at_beginning_missing_arm() {
2128 // This is a false negative.
2129 // We don't currently handle tuple patterns with ellipsis.
2130 check_no_diagnostic(
2131 r"
2132 fn test_fn() {
2133 match (false, true, false) {
2134 (.., false) => {},
2135 }
2136 }
2137 ",
2138 );
2139 }
2140
2141 #[test]
2142 fn struct_missing_arm() {
2143 // This is a false negative.
2144 // We don't currently handle structs.
2145 check_no_diagnostic(
2146 r"
2147 struct Foo {
2148 a: bool,
2149 }
2150 fn test_fn(f: Foo) {
2151 match f {
2152 Foo { a: true } => {},
2153 }
2154 }
2155 ",
2156 );
2157 }
2158}