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, TyKind};
14 use rustc::ty::subst::{InternalSubsts, SubstsRef};
16 use rustc_errors::{Applicability, DiagnosticBuilder};
17 use rustc::util::common::ErrorReported;
19 use rustc::hir::def::*;
20 use rustc::hir::def_id::DefId;
21 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
22 use rustc::hir::{self, Pat, PatKind};
24 use smallvec::smallvec;
28 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
30 pub(crate) fn check_match<'a, 'tcx>(
31 tcx: TyCtxt<'a, 'tcx, 'tcx>,
33 ) -> Result<(), ErrorReported> {
34 let body_id = if let Some(id) = tcx.hir().as_local_hir_id(def_id) {
35 tcx.hir().body_owned_by(id)
40 tcx.sess.track_errors(|| {
43 tables: tcx.body_tables(body_id),
44 region_scope_tree: &tcx.region_scope_tree(def_id),
45 param_env: tcx.param_env(def_id),
46 identity_substs: InternalSubsts::identity_for_item(tcx, def_id),
47 }.visit_body(tcx.hir().body(body_id));
51 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
52 struct_span_err!(sess, sp, E0004, "{}", &error_message)
55 struct MatchVisitor<'a, 'tcx: 'a> {
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 tables: &'a ty::TypeckTables<'tcx>,
58 param_env: ty::ParamEnv<'tcx>,
59 identity_substs: SubstsRef<'tcx>,
60 region_scope_tree: &'a region::ScopeTree,
63 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
64 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
65 NestedVisitorMap::None
68 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
69 intravisit::walk_expr(self, ex);
72 hir::ExprKind::Match(ref scrut, ref arms, source) => {
73 self.check_match(scrut, arms, source);
79 fn visit_local(&mut self, loc: &'tcx hir::Local) {
80 intravisit::walk_local(self, loc);
82 self.check_irrefutable(&loc.pat, match loc.source {
83 hir::LocalSource::Normal => "local binding",
84 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
87 // Check legality of move bindings and `@` patterns.
88 self.check_patterns(false, slice::from_ref(&loc.pat));
91 fn visit_body(&mut self, body: &'tcx hir::Body) {
92 intravisit::walk_body(self, body);
94 for arg in &body.arguments {
95 self.check_irrefutable(&arg.pat, "function argument");
96 self.check_patterns(false, slice::from_ref(&arg.pat));
102 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
103 fn report_inlining_errors(&self, pat_span: Span) {
104 for error in &self.errors {
106 PatternError::StaticInPattern(span) => {
107 self.span_e0158(span, "statics cannot be referenced in patterns")
109 PatternError::AssociatedConstInPattern(span) => {
110 self.span_e0158(span, "associated consts cannot be referenced in patterns")
112 PatternError::FloatBug => {
113 // FIXME(#31407) this is only necessary because float parsing is buggy
114 ::rustc::mir::interpret::struct_error(
115 self.tcx.at(pat_span),
116 "could not evaluate float literal (see issue #31407)",
119 PatternError::NonConstPath(span) => {
120 ::rustc::mir::interpret::struct_error(
122 "runtime values cannot be referenced in patterns",
129 fn span_e0158(&self, span: Span, text: &str) {
130 span_err!(self.tcx.sess, span, E0158, "{}", text)
134 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
135 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
136 check_legality_of_move_bindings(self, has_guard, pats);
138 check_legality_of_bindings_in_at_patterns(self, pat);
145 arms: &'tcx [hir::Arm],
146 source: hir::MatchSource)
149 // First, check legality of move bindings.
150 self.check_patterns(arm.guard.is_some(), &arm.pats);
152 // Second, if there is a guard on each arm, make sure it isn't
153 // assigning or borrowing anything mutably.
154 if let Some(ref guard) = arm.guard {
155 if self.tcx.check_for_mutation_in_guard_via_ast_walk() {
156 check_for_mutation_in_guard(self, &guard);
160 // Third, perform some lints.
161 for pat in &arm.pats {
162 check_for_bindings_named_same_as_variants(self, pat);
166 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
167 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
168 let mut have_errors = false;
170 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
171 arm.pats.iter().map(|pat| {
172 let mut patcx = PatternContext::new(self.tcx,
173 self.param_env.and(self.identity_substs),
175 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
176 if !patcx.errors.is_empty() {
177 patcx.report_inlining_errors(pat.span);
182 arm.guard.as_ref().map(|g| match g {
183 hir::Guard::If(ref e) => &**e,
187 // Bail out early if inlining failed.
192 // Fourth, check for unreachable arms.
193 check_arms(cx, &inlined_arms, source);
195 // Then, if the match has no arms, check whether the scrutinee
197 let pat_ty = self.tables.node_type(scrut.hir_id);
198 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
199 let mut def_span = None;
200 let mut missing_variants = vec![];
201 if inlined_arms.is_empty() {
202 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
203 self.tcx.is_ty_uninhabited_from(module, pat_ty)
208 def_span = self.tcx.hir().span_if_local(def.did);
209 if def.variants.len() < 4 && !def.variants.is_empty() {
210 // keep around to point at the definition of non-covered variants
211 missing_variants = def.variants.iter()
212 .map(|variant| variant.ident)
215 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.def.article(), path.def.kind_name())
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.item_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::IfLetDesugar { .. } => {
374 lint::builtin::IRREFUTABLE_LET_PATTERNS,
377 "irrefutable if-let pattern",
381 hir::MatchSource::WhileLetDesugar => {
382 // check which arm we're on.
384 // The arm with the user-specified pattern.
387 lint::builtin::UNREACHABLE_PATTERNS,
388 hir_pat.hir_id, pat.span,
389 "unreachable pattern");
391 // The arm with the wildcard pattern.
394 lint::builtin::IRREFUTABLE_LET_PATTERNS,
397 "irrefutable while-let pattern",
404 hir::MatchSource::ForLoopDesugar |
405 hir::MatchSource::Normal => {
406 let mut err = cx.tcx.struct_span_lint_hir(
407 lint::builtin::UNREACHABLE_PATTERNS,
410 "unreachable pattern",
412 // if we had a catchall pattern, hint at that
413 if let Some(catchall) = catchall {
414 err.span_label(pat.span, "unreachable pattern");
415 err.span_label(catchall, "matches any value");
420 // Unreachable patterns in try expressions occur when one of the arms
421 // are an uninhabited type. Which is OK.
422 hir::MatchSource::TryDesugar => {}
426 UsefulWithWitness(_) => bug!()
430 if catchall.is_none() && pat_is_catchall(hir_pat) {
431 catchall = Some(pat.span);
438 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(
439 cx: &mut MatchCheckCtxt<'a, 'tcx>,
442 matrix: &Matrix<'p, 'tcx>,
444 let wild_pattern = Pattern {
447 kind: box PatternKind::Wild,
449 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
450 UsefulWithWitness(pats) => {
451 let witnesses = if pats.is_empty() {
454 pats.iter().map(|w| w.single_pattern()).collect()
457 const LIMIT: usize = 3;
458 let joined_patterns = match witnesses.len() {
460 1 => format!("`{}`", witnesses[0]),
462 let (tail, head) = witnesses.split_last().unwrap();
463 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
464 format!("`{}` and `{}`", head.join("`, `"), tail)
467 let (head, tail) = witnesses.split_at(LIMIT);
468 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
469 format!("`{}` and {} more", head.join("`, `"), tail.len())
473 let label_text = match witnesses.len() {
474 1 => format!("pattern {} not covered", joined_patterns),
475 _ => format!("patterns {} not covered", joined_patterns),
477 let mut err = create_e0004(cx.tcx.sess, sp, format!(
478 "non-exhaustive patterns: {} not covered",
481 err.span_label(sp, label_text);
482 // point at the definition of non-covered enum variants
483 if let ty::Adt(def, _) = scrut_ty.sty {
484 if let Some(sp) = cx.tcx.hir().span_if_local(def.did){
485 err.span_label(sp, format!("`{}` defined here", scrut_ty));
488 let patterns = witnesses.iter().map(|p| (**p).clone()).collect::<Vec<Pattern<'_>>>();
489 if patterns.len() < 4 {
490 for sp in maybe_point_at_variant(cx, &scrut_ty.sty, patterns.as_slice()) {
491 err.span_label(sp, "not covered");
494 err.help("ensure that all possible cases are being handled, \
495 possibly by adding wildcards or more match arms");
499 // This is good, wildcard pattern isn't reachable
505 fn maybe_point_at_variant(
506 cx: &mut MatchCheckCtxt<'a, 'tcx>,
508 patterns: &[Pattern<'_>],
510 let mut covered = vec![];
511 if let ty::Adt(def, _) = sty {
512 // Don't point at variants that have already been covered due to other patterns to avoid
514 for pattern in patterns {
515 let pk: &PatternKind<'_> = &pattern.kind;
516 if let PatternKind::Variant { adt_def, variant_index, subpatterns, .. } = pk {
517 if adt_def.did == def.did {
518 let sp = def.variants[*variant_index].ident.span;
519 if covered.contains(&sp) {
523 let subpatterns = subpatterns.iter()
524 .map(|field_pattern| field_pattern.pattern.clone())
525 .collect::<Vec<_>>();
527 maybe_point_at_variant(cx, sty, subpatterns.as_slice()),
531 if let PatternKind::Leaf { subpatterns } = pk {
532 let subpatterns = subpatterns.iter()
533 .map(|field_pattern| field_pattern.pattern.clone())
534 .collect::<Vec<_>>();
535 covered.extend(maybe_point_at_variant(cx, sty, subpatterns.as_slice()));
542 // Legality of move bindings checking
543 fn check_legality_of_move_bindings(
544 cx: &MatchVisitor<'_, '_>,
548 let mut by_ref_span = None;
550 pat.each_binding(|_, hir_id, span, _path| {
551 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
552 if let ty::BindByReference(..) = bm {
553 by_ref_span = Some(span);
556 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
560 let span_vec = &mut Vec::new();
561 let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
562 // check legality of moving out of the enum
564 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
565 if sub.map_or(false, |p| p.contains_bindings()) {
566 struct_span_err!(cx.tcx.sess, p.span, E0007,
567 "cannot bind by-move with sub-bindings")
568 .span_label(p.span, "binds an already bound by-move value by moving it")
570 } else if has_guard && !cx.tcx.allow_bind_by_move_patterns_with_guards() {
571 let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
572 "cannot bind by-move into a pattern guard");
573 err.span_label(p.span, "moves value into pattern guard");
574 if cx.tcx.sess.opts.unstable_features.is_nightly_build() && cx.tcx.use_mir_borrowck() {
575 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
576 crate attributes to enable");
579 } else if let Some(_by_ref_span) = by_ref_span {
580 span_vec.push(p.span);
586 if let PatKind::Binding(_, _, _, ref sub) = p.node {
587 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
589 ty::BindByValue(..) => {
590 let pat_ty = cx.tables.node_type(p.hir_id);
591 if !pat_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, pat.span) {
592 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
598 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
604 if !span_vec.is_empty(){
605 let span = MultiSpan::from_spans(span_vec.clone());
606 let mut err = struct_span_err!(
610 "cannot bind by-move and by-ref in the same pattern",
612 err.span_label(by_ref_span.unwrap(), "both by-ref and by-move used");
613 for span in span_vec.iter(){
614 err.span_label(*span, "by-move pattern here");
620 /// Ensures that a pattern guard doesn't borrow by mutable reference or assign.
622 // FIXME: this should be done by borrowck.
623 fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) {
624 let mut checker = MutationChecker {
628 hir::Guard::If(expr) =>
629 ExprUseVisitor::new(&mut checker,
632 cx.region_scope_tree,
634 None).walk_expr(expr),
638 struct MutationChecker<'a, 'tcx: 'a> {
639 cx: &'a MatchVisitor<'a, 'tcx>,
642 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
643 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {}
644 fn consume(&mut self, _: hir::HirId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {}
645 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {}
651 kind:ty:: BorrowKind,
655 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
656 "cannot mutably borrow in a pattern guard");
657 err.span_label(span, "borrowed mutably in pattern guard");
658 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() &&
659 self.cx.tcx.use_mir_borrowck()
661 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
662 crate attributes to enable");
666 ty::ImmBorrow | ty::UniqueImmBorrow => {}
669 fn decl_without_init(&mut self, _: hir::HirId, _: Span) {}
670 fn mutate(&mut self, _: hir::HirId, span: Span, _: &cmt_<'_>, mode: MutateMode) {
672 MutateMode::JustWrite | MutateMode::WriteAndRead => {
673 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
674 .span_label(span, "assignment in pattern guard")
677 MutateMode::Init => {}
682 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
683 /// because of the way rvalues are handled in the borrow check. (See issue
685 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
686 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
689 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
690 cx: &'a MatchVisitor<'b, 'tcx>,
691 bindings_allowed: bool
694 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
695 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
696 NestedVisitorMap::None
699 fn visit_pat(&mut self, pat: &Pat) {
701 PatKind::Binding(.., ref subpat) => {
702 if !self.bindings_allowed {
703 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
704 "pattern bindings are not allowed after an `@`")
705 .span_label(pat.span, "not allowed after `@`")
709 if subpat.is_some() {
710 let bindings_were_allowed = self.bindings_allowed;
711 self.bindings_allowed = false;
712 intravisit::walk_pat(self, pat);
713 self.bindings_allowed = bindings_were_allowed;
716 _ => intravisit::walk_pat(self, pat),