1 use super::_match::{MatchCheckCtxt, Matrix, expand_pattern, is_useful};
2 use super::_match::Usefulness::*;
3 use super::_match::WitnessPreference::*;
5 use super::{Pattern, PatternContext, PatternError, PatternKind};
7 use rustc::middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor};
8 use rustc::middle::expr_use_visitor::{LoanCause, MutateMode};
9 use rustc::middle::expr_use_visitor as euv;
10 use rustc::middle::mem_categorization::cmt_;
11 use rustc::middle::region;
12 use rustc::session::Session;
13 use rustc::ty::{self, Ty, TyCtxt};
14 use rustc::ty::subst::{InternalSubsts, SubstsRef};
16 use rustc_errors::{Applicability, DiagnosticBuilder};
18 use rustc::hir::def::*;
19 use rustc::hir::def_id::DefId;
20 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
21 use rustc::hir::{self, Pat, PatKind};
23 use smallvec::smallvec;
27 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
29 pub(crate) fn check_match<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
30 let body_id = if let Some(id) = tcx.hir().as_local_hir_id(def_id) {
31 tcx.hir().body_owned_by(id)
38 tables: tcx.body_tables(body_id),
39 region_scope_tree: &tcx.region_scope_tree(def_id),
40 param_env: tcx.param_env(def_id),
41 identity_substs: InternalSubsts::identity_for_item(tcx, def_id),
42 }.visit_body(tcx.hir().body(body_id));
45 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
46 struct_span_err!(sess, sp, E0004, "{}", &error_message)
49 struct MatchVisitor<'a, 'tcx: 'a> {
50 tcx: TyCtxt<'a, 'tcx, 'tcx>,
51 tables: &'a ty::TypeckTables<'tcx>,
52 param_env: ty::ParamEnv<'tcx>,
53 identity_substs: SubstsRef<'tcx>,
54 region_scope_tree: &'a region::ScopeTree,
57 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
58 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
59 NestedVisitorMap::None
62 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
63 intravisit::walk_expr(self, ex);
66 hir::ExprKind::Match(ref scrut, ref arms, source) => {
67 self.check_match(scrut, arms, source);
73 fn visit_local(&mut self, loc: &'tcx hir::Local) {
74 intravisit::walk_local(self, loc);
76 self.check_irrefutable(&loc.pat, match loc.source {
77 hir::LocalSource::Normal => "local binding",
78 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
79 hir::LocalSource::AsyncFn => "async fn binding",
80 hir::LocalSource::AwaitDesugar => "`await` future binding",
83 // Check legality of move bindings and `@` patterns.
84 self.check_patterns(false, slice::from_ref(&loc.pat));
87 fn visit_body(&mut self, body: &'tcx hir::Body) {
88 intravisit::walk_body(self, body);
90 for arg in &body.arguments {
91 self.check_irrefutable(&arg.pat, "function argument");
92 self.check_patterns(false, slice::from_ref(&arg.pat));
98 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
99 fn report_inlining_errors(&self, pat_span: Span) {
100 for error in &self.errors {
102 PatternError::StaticInPattern(span) => {
103 self.span_e0158(span, "statics cannot be referenced in patterns")
105 PatternError::AssociatedConstInPattern(span) => {
106 self.span_e0158(span, "associated consts cannot be referenced in patterns")
108 PatternError::FloatBug => {
109 // FIXME(#31407) this is only necessary because float parsing is buggy
110 ::rustc::mir::interpret::struct_error(
111 self.tcx.at(pat_span),
112 "could not evaluate float literal (see issue #31407)",
115 PatternError::NonConstPath(span) => {
116 ::rustc::mir::interpret::struct_error(
118 "runtime values cannot be referenced in patterns",
125 fn span_e0158(&self, span: Span, text: &str) {
126 span_err!(self.tcx.sess, span, E0158, "{}", text)
130 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
131 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
132 check_legality_of_move_bindings(self, has_guard, pats);
134 check_legality_of_bindings_in_at_patterns(self, pat);
141 arms: &'tcx [hir::Arm],
142 source: hir::MatchSource)
145 // First, check legality of move bindings.
146 self.check_patterns(arm.guard.is_some(), &arm.pats);
148 // Second, if there is a guard on each arm, make sure it isn't
149 // assigning or borrowing anything mutably.
150 if let Some(ref guard) = arm.guard {
151 if !self.tcx.features().bind_by_move_pattern_guards {
152 check_for_mutation_in_guard(self, &guard);
156 // Third, perform some lints.
157 for pat in &arm.pats {
158 check_for_bindings_named_same_as_variants(self, pat);
162 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
163 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
164 let mut have_errors = false;
166 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
167 arm.pats.iter().map(|pat| {
168 let mut patcx = PatternContext::new(self.tcx,
169 self.param_env.and(self.identity_substs),
171 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
172 if !patcx.errors.is_empty() {
173 patcx.report_inlining_errors(pat.span);
178 arm.guard.as_ref().map(|g| match g {
179 hir::Guard::If(ref e) => &**e,
183 // Bail out early if inlining failed.
188 // Fourth, check for unreachable arms.
189 check_arms(cx, &inlined_arms, source);
191 // Then, if the match has no arms, check whether the scrutinee
193 let pat_ty = self.tables.node_type(scrut.hir_id);
194 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
195 let mut def_span = None;
196 let mut missing_variants = vec![];
197 if inlined_arms.is_empty() {
198 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
199 self.tcx.is_ty_uninhabited_from(module, pat_ty)
204 def_span = self.tcx.hir().span_if_local(def.did);
205 if def.variants.len() < 4 && !def.variants.is_empty() {
206 // keep around to point at the definition of non-covered variants
207 missing_variants = def.variants.iter()
208 .map(|variant| variant.ident)
212 let is_non_exhaustive_and_non_local =
213 def.is_variant_list_non_exhaustive() && !def.did.is_local();
215 !(is_non_exhaustive_and_non_local) && def.variants.is_empty()
220 if !scrutinee_is_uninhabited {
221 // We know the type is inhabited, so this must be wrong
222 let mut err = create_e0004(
225 format!("non-exhaustive patterns: {}", match missing_variants.len() {
226 0 => format!("type `{}` is non-empty", pat_ty),
228 "pattern `{}` of type `{}` is not handled",
229 missing_variants[0].name,
232 _ => format!("multiple patterns of type `{}` are not handled", pat_ty),
235 err.help("ensure that all possible cases are being handled, \
236 possibly by adding wildcards or more match arms");
237 if let Some(sp) = def_span {
238 err.span_label(sp, format!("`{}` defined here", pat_ty));
240 // point at the definition of non-covered enum variants
241 for variant in &missing_variants {
242 err.span_label(variant.span, "variant not covered");
246 // If the type *is* uninhabited, it's vacuously exhaustive
250 let matrix: Matrix<'_, '_> = inlined_arms
252 .filter(|&&(_, guard)| guard.is_none())
253 .flat_map(|arm| &arm.0)
254 .map(|pat| smallvec![pat.0])
256 let scrut_ty = self.tables.node_type(scrut.hir_id);
257 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
261 fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
262 let module = self.tcx.hir().get_module_parent_by_hir_id(pat.hir_id);
263 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
264 let mut patcx = PatternContext::new(self.tcx,
265 self.param_env.and(self.identity_substs),
267 let pattern = patcx.lower_pattern(pat);
268 let pattern_ty = pattern.ty;
269 let pats: Matrix<'_, '_> = vec![smallvec![
270 expand_pattern(cx, pattern)
271 ]].into_iter().collect();
273 let wild_pattern = Pattern {
276 kind: box PatternKind::Wild,
278 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
279 UsefulWithWitness(witness) => witness,
284 let pattern_string = witness[0].single_pattern().to_string();
285 let mut err = struct_span_err!(
286 self.tcx.sess, pat.span, E0005,
287 "refutable pattern in {}: `{}` not covered",
288 origin, pattern_string
290 let label_msg = match pat.node {
291 PatKind::Path(hir::QPath::Resolved(None, ref path))
292 if path.segments.len() == 1 && path.segments[0].args.is_none() => {
293 format!("interpreted as {} {} pattern, not new variable",
294 path.res.article(), path.res.descr())
296 _ => format!("pattern `{}` not covered", pattern_string),
298 err.span_label(pat.span, label_msg);
299 if let ty::Adt(def, _) = pattern_ty.sty {
300 if let Some(sp) = self.tcx.hir().span_if_local(def.did){
301 err.span_label(sp, format!("`{}` defined here", pattern_ty));
309 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
311 if let PatKind::Binding(_, _, ident, None) = p.node {
312 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
313 if bm != ty::BindByValue(hir::MutImmutable) {
317 let pat_ty = cx.tables.pat_ty(p);
318 if let ty::Adt(edef, _) = pat_ty.sty {
319 if edef.is_enum() && edef.variants.iter().any(|variant| {
320 variant.ident == ident && variant.ctor_kind == CtorKind::Const
322 let ty_path = cx.tcx.def_path_str(edef.did);
323 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
324 "pattern binding `{}` is named the same as one \
325 of the variants of the type `{}`",
329 "to match on the variant, qualify the path",
330 format!("{}::{}", ty_path, ident),
331 Applicability::MachineApplicable
337 cx.tcx.sess.delay_span_bug(p.span, "missing binding mode");
344 /// Checks for common cases of "catchall" patterns that may not be intended as such.
345 fn pat_is_catchall(pat: &Pat) -> bool {
347 PatKind::Binding(.., None) => true,
348 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
349 PatKind::Ref(ref s, _) => pat_is_catchall(s),
350 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
357 // Check for unreachable patterns
358 fn check_arms<'a, 'tcx>(
359 cx: &mut MatchCheckCtxt<'a, 'tcx>,
360 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
361 source: hir::MatchSource,
363 let mut seen = Matrix::empty();
364 let mut catchall = None;
365 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
366 for &(pat, hir_pat) in pats {
367 let v = smallvec![pat];
369 match is_useful(cx, &seen, &v, LeaveOutWitness) {
372 hir::MatchSource::IfDesugar { .. } => bug!(),
373 hir::MatchSource::IfLetDesugar { .. } => {
375 lint::builtin::IRREFUTABLE_LET_PATTERNS,
378 "irrefutable if-let pattern",
382 hir::MatchSource::WhileLetDesugar => {
383 // check which arm we're on.
385 // The arm with the user-specified pattern.
388 lint::builtin::UNREACHABLE_PATTERNS,
389 hir_pat.hir_id, pat.span,
390 "unreachable pattern");
392 // The arm with the wildcard pattern.
395 lint::builtin::IRREFUTABLE_LET_PATTERNS,
398 "irrefutable while-let pattern",
405 hir::MatchSource::ForLoopDesugar |
406 hir::MatchSource::Normal => {
407 let mut err = cx.tcx.struct_span_lint_hir(
408 lint::builtin::UNREACHABLE_PATTERNS,
411 "unreachable pattern",
413 // if we had a catchall pattern, hint at that
414 if let Some(catchall) = catchall {
415 err.span_label(pat.span, "unreachable pattern");
416 err.span_label(catchall, "matches any value");
421 // Unreachable patterns in try and await expressions occur when one of
422 // the arms are an uninhabited type. Which is OK.
423 hir::MatchSource::AwaitDesugar |
424 hir::MatchSource::TryDesugar => {}
428 UsefulWithWitness(_) => bug!()
432 if catchall.is_none() && pat_is_catchall(hir_pat) {
433 catchall = Some(pat.span);
440 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(
441 cx: &mut MatchCheckCtxt<'a, 'tcx>,
444 matrix: &Matrix<'p, 'tcx>,
446 let wild_pattern = Pattern {
449 kind: box PatternKind::Wild,
451 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
452 UsefulWithWitness(pats) => {
453 let witnesses = if pats.is_empty() {
456 pats.iter().map(|w| w.single_pattern()).collect()
459 const LIMIT: usize = 3;
460 let joined_patterns = match witnesses.len() {
462 1 => format!("`{}`", witnesses[0]),
464 let (tail, head) = witnesses.split_last().unwrap();
465 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
466 format!("`{}` and `{}`", head.join("`, `"), tail)
469 let (head, tail) = witnesses.split_at(LIMIT);
470 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
471 format!("`{}` and {} more", head.join("`, `"), tail.len())
475 let label_text = match witnesses.len() {
476 1 => format!("pattern {} not covered", joined_patterns),
477 _ => format!("patterns {} not covered", joined_patterns),
479 let mut err = create_e0004(cx.tcx.sess, sp, format!(
480 "non-exhaustive patterns: {} not covered",
483 err.span_label(sp, label_text);
484 // point at the definition of non-covered enum variants
485 if let ty::Adt(def, _) = scrut_ty.sty {
486 if let Some(sp) = cx.tcx.hir().span_if_local(def.did){
487 err.span_label(sp, format!("`{}` defined here", scrut_ty));
490 let patterns = witnesses.iter().map(|p| (**p).clone()).collect::<Vec<Pattern<'_>>>();
491 if patterns.len() < 4 {
492 for sp in maybe_point_at_variant(cx, scrut_ty, patterns.as_slice()) {
493 err.span_label(sp, "not covered");
496 err.help("ensure that all possible cases are being handled, \
497 possibly by adding wildcards or more match arms");
501 // This is good, wildcard pattern isn't reachable
507 fn maybe_point_at_variant(
508 cx: &mut MatchCheckCtxt<'a, 'tcx>,
510 patterns: &[Pattern<'_>],
512 let mut covered = vec![];
513 if let ty::Adt(def, _) = ty.sty {
514 // Don't point at variants that have already been covered due to other patterns to avoid
516 for pattern in patterns {
517 let pk: &PatternKind<'_> = &pattern.kind;
518 if let PatternKind::Variant { adt_def, variant_index, subpatterns, .. } = pk {
519 if adt_def.did == def.did {
520 let sp = def.variants[*variant_index].ident.span;
521 if covered.contains(&sp) {
525 let subpatterns = subpatterns.iter()
526 .map(|field_pattern| field_pattern.pattern.clone())
527 .collect::<Vec<_>>();
529 maybe_point_at_variant(cx, ty, subpatterns.as_slice()),
533 if let PatternKind::Leaf { subpatterns } = pk {
534 let subpatterns = subpatterns.iter()
535 .map(|field_pattern| field_pattern.pattern.clone())
536 .collect::<Vec<_>>();
537 covered.extend(maybe_point_at_variant(cx, ty, subpatterns.as_slice()));
544 // Legality of move bindings checking
545 fn check_legality_of_move_bindings(
546 cx: &MatchVisitor<'_, '_>,
550 let mut by_ref_span = None;
552 pat.each_binding(|_, hir_id, span, _path| {
553 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
554 if let ty::BindByReference(..) = bm {
555 by_ref_span = Some(span);
558 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
562 let span_vec = &mut Vec::new();
563 let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
564 // check legality of moving out of the enum
566 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
567 if sub.map_or(false, |p| p.contains_bindings()) {
568 struct_span_err!(cx.tcx.sess, p.span, E0007,
569 "cannot bind by-move with sub-bindings")
570 .span_label(p.span, "binds an already bound by-move value by moving it")
572 } else if has_guard && !cx.tcx.features().bind_by_move_pattern_guards {
573 let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
574 "cannot bind by-move into a pattern guard");
575 err.span_label(p.span, "moves value into pattern guard");
576 if cx.tcx.sess.opts.unstable_features.is_nightly_build() {
577 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
578 crate attributes to enable");
581 } else if let Some(_by_ref_span) = by_ref_span {
582 span_vec.push(p.span);
588 if let PatKind::Binding(_, _, _, ref sub) = p.node {
589 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
591 ty::BindByValue(..) => {
592 let pat_ty = cx.tables.node_type(p.hir_id);
593 if !pat_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, pat.span) {
594 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
600 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
606 if !span_vec.is_empty(){
607 let span = MultiSpan::from_spans(span_vec.clone());
608 let mut err = struct_span_err!(
612 "cannot bind by-move and by-ref in the same pattern",
614 if let Some(by_ref_span) = by_ref_span {
615 err.span_label(by_ref_span, "both by-ref and by-move used");
617 for span in span_vec.iter(){
618 err.span_label(*span, "by-move pattern here");
624 /// Ensures that a pattern guard doesn't borrow by mutable reference or assign.
626 // FIXME: this should be done by borrowck.
627 fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) {
628 let mut checker = MutationChecker {
632 hir::Guard::If(expr) =>
633 ExprUseVisitor::new(&mut checker,
636 cx.region_scope_tree,
638 None).walk_expr(expr),
642 struct MutationChecker<'a, 'tcx: 'a> {
643 cx: &'a MatchVisitor<'a, 'tcx>,
646 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
647 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {}
648 fn consume(&mut self, _: hir::HirId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {}
649 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {}
655 kind:ty:: BorrowKind,
659 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
660 "cannot mutably borrow in a pattern guard");
661 err.span_label(span, "borrowed mutably in pattern guard");
662 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() {
663 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
664 crate attributes to enable");
668 ty::ImmBorrow | ty::UniqueImmBorrow => {}
671 fn decl_without_init(&mut self, _: hir::HirId, _: Span) {}
672 fn mutate(&mut self, _: hir::HirId, span: Span, _: &cmt_<'_>, mode: MutateMode) {
674 MutateMode::JustWrite | MutateMode::WriteAndRead => {
675 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
676 .span_label(span, "assignment in pattern guard")
679 MutateMode::Init => {}
684 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
685 /// because of the way rvalues are handled in the borrow check. (See issue
687 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
688 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
691 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
692 cx: &'a MatchVisitor<'b, 'tcx>,
693 bindings_allowed: bool
696 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
697 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
698 NestedVisitorMap::None
701 fn visit_pat(&mut self, pat: &Pat) {
703 PatKind::Binding(.., ref subpat) => {
704 if !self.bindings_allowed {
705 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
706 "pattern bindings are not allowed after an `@`")
707 .span_label(pat.span, "not allowed after `@`")
711 if subpat.is_some() {
712 let bindings_were_allowed = self.bindings_allowed;
713 self.bindings_allowed = false;
714 intravisit::walk_pat(self, pat);
715 self.bindings_allowed = bindings_were_allowed;
718 _ => intravisit::walk_pat(self, pat),