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",
82 // Check legality of move bindings and `@` patterns.
83 self.check_patterns(false, slice::from_ref(&loc.pat));
86 fn visit_body(&mut self, body: &'tcx hir::Body) {
87 intravisit::walk_body(self, body);
89 for arg in &body.arguments {
90 self.check_irrefutable(&arg.pat, "function argument");
91 self.check_patterns(false, slice::from_ref(&arg.pat));
97 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
98 fn report_inlining_errors(&self, pat_span: Span) {
99 for error in &self.errors {
101 PatternError::StaticInPattern(span) => {
102 self.span_e0158(span, "statics cannot be referenced in patterns")
104 PatternError::AssociatedConstInPattern(span) => {
105 self.span_e0158(span, "associated consts cannot be referenced in patterns")
107 PatternError::FloatBug => {
108 // FIXME(#31407) this is only necessary because float parsing is buggy
109 ::rustc::mir::interpret::struct_error(
110 self.tcx.at(pat_span),
111 "could not evaluate float literal (see issue #31407)",
114 PatternError::NonConstPath(span) => {
115 ::rustc::mir::interpret::struct_error(
117 "runtime values cannot be referenced in patterns",
124 fn span_e0158(&self, span: Span, text: &str) {
125 span_err!(self.tcx.sess, span, E0158, "{}", text)
129 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
130 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
131 check_legality_of_move_bindings(self, has_guard, pats);
133 check_legality_of_bindings_in_at_patterns(self, pat);
140 arms: &'tcx [hir::Arm],
141 source: hir::MatchSource)
144 // First, check legality of move bindings.
145 self.check_patterns(arm.guard.is_some(), &arm.pats);
147 // Second, if there is a guard on each arm, make sure it isn't
148 // assigning or borrowing anything mutably.
149 if let Some(ref guard) = arm.guard {
150 if !self.tcx.features().bind_by_move_pattern_guards {
151 check_for_mutation_in_guard(self, &guard);
155 // Third, perform some lints.
156 for pat in &arm.pats {
157 check_for_bindings_named_same_as_variants(self, pat);
161 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
162 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
163 let mut have_errors = false;
165 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
166 arm.pats.iter().map(|pat| {
167 let mut patcx = PatternContext::new(self.tcx,
168 self.param_env.and(self.identity_substs),
170 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
171 if !patcx.errors.is_empty() {
172 patcx.report_inlining_errors(pat.span);
177 arm.guard.as_ref().map(|g| match g {
178 hir::Guard::If(ref e) => &**e,
182 // Bail out early if inlining failed.
187 // Fourth, check for unreachable arms.
188 check_arms(cx, &inlined_arms, source);
190 // Then, if the match has no arms, check whether the scrutinee
192 let pat_ty = self.tables.node_type(scrut.hir_id);
193 let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
194 let mut def_span = None;
195 let mut missing_variants = vec![];
196 if inlined_arms.is_empty() {
197 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
198 self.tcx.is_ty_uninhabited_from(module, pat_ty)
203 def_span = self.tcx.hir().span_if_local(def.did);
204 if def.variants.len() < 4 && !def.variants.is_empty() {
205 // keep around to point at the definition of non-covered variants
206 missing_variants = def.variants.iter()
207 .map(|variant| variant.ident)
210 def.variants.is_empty()
215 if !scrutinee_is_uninhabited {
216 // We know the type is inhabited, so this must be wrong
217 let mut err = create_e0004(
220 format!("non-exhaustive patterns: {}", match missing_variants.len() {
221 0 => format!("type `{}` is non-empty", pat_ty),
223 "pattern `{}` of type `{}` is not handled",
224 missing_variants[0].name,
227 _ => format!("multiple patterns of type `{}` are not handled", pat_ty),
230 err.help("ensure that all possible cases are being handled, \
231 possibly by adding wildcards or more match arms");
232 if let Some(sp) = def_span {
233 err.span_label(sp, format!("`{}` defined here", pat_ty));
235 // point at the definition of non-covered enum variants
236 for variant in &missing_variants {
237 err.span_label(variant.span, "variant not covered");
241 // If the type *is* uninhabited, it's vacuously exhaustive
245 let matrix: Matrix<'_, '_> = inlined_arms
247 .filter(|&&(_, guard)| guard.is_none())
248 .flat_map(|arm| &arm.0)
249 .map(|pat| smallvec![pat.0])
251 let scrut_ty = self.tables.node_type(scrut.hir_id);
252 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
256 fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
257 let module = self.tcx.hir().get_module_parent_by_hir_id(pat.hir_id);
258 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
259 let mut patcx = PatternContext::new(self.tcx,
260 self.param_env.and(self.identity_substs),
262 let pattern = patcx.lower_pattern(pat);
263 let pattern_ty = pattern.ty;
264 let pats: Matrix<'_, '_> = vec![smallvec![
265 expand_pattern(cx, pattern)
266 ]].into_iter().collect();
268 let wild_pattern = Pattern {
271 kind: box PatternKind::Wild,
273 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
274 UsefulWithWitness(witness) => witness,
279 let pattern_string = witness[0].single_pattern().to_string();
280 let mut err = struct_span_err!(
281 self.tcx.sess, pat.span, E0005,
282 "refutable pattern in {}: `{}` not covered",
283 origin, pattern_string
285 let label_msg = match pat.node {
286 PatKind::Path(hir::QPath::Resolved(None, ref path))
287 if path.segments.len() == 1 && path.segments[0].args.is_none() => {
288 format!("interpreted as {} {} pattern, not new variable",
289 path.res.article(), path.res.descr())
291 _ => format!("pattern `{}` not covered", pattern_string),
293 err.span_label(pat.span, label_msg);
294 if let ty::Adt(def, _) = pattern_ty.sty {
295 if let Some(sp) = self.tcx.hir().span_if_local(def.did){
296 err.span_label(sp, format!("`{}` defined here", pattern_ty));
304 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
306 if let PatKind::Binding(_, _, ident, None) = p.node {
307 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
308 if bm != ty::BindByValue(hir::MutImmutable) {
312 let pat_ty = cx.tables.pat_ty(p);
313 if let ty::Adt(edef, _) = pat_ty.sty {
314 if edef.is_enum() && edef.variants.iter().any(|variant| {
315 variant.ident == ident && variant.ctor_kind == CtorKind::Const
317 let ty_path = cx.tcx.def_path_str(edef.did);
318 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
319 "pattern binding `{}` is named the same as one \
320 of the variants of the type `{}`",
324 "to match on the variant, qualify the path",
325 format!("{}::{}", ty_path, ident),
326 Applicability::MachineApplicable
332 cx.tcx.sess.delay_span_bug(p.span, "missing binding mode");
339 /// Checks for common cases of "catchall" patterns that may not be intended as such.
340 fn pat_is_catchall(pat: &Pat) -> bool {
342 PatKind::Binding(.., None) => true,
343 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
344 PatKind::Ref(ref s, _) => pat_is_catchall(s),
345 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
352 // Check for unreachable patterns
353 fn check_arms<'a, 'tcx>(
354 cx: &mut MatchCheckCtxt<'a, 'tcx>,
355 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
356 source: hir::MatchSource,
358 let mut seen = Matrix::empty();
359 let mut catchall = None;
360 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
361 for &(pat, hir_pat) in pats {
362 let v = smallvec![pat];
364 match is_useful(cx, &seen, &v, LeaveOutWitness) {
367 hir::MatchSource::IfLetDesugar { .. } => {
369 lint::builtin::IRREFUTABLE_LET_PATTERNS,
372 "irrefutable if-let pattern",
376 hir::MatchSource::WhileLetDesugar => {
377 // check which arm we're on.
379 // The arm with the user-specified pattern.
382 lint::builtin::UNREACHABLE_PATTERNS,
383 hir_pat.hir_id, pat.span,
384 "unreachable pattern");
386 // The arm with the wildcard pattern.
389 lint::builtin::IRREFUTABLE_LET_PATTERNS,
392 "irrefutable while-let pattern",
399 hir::MatchSource::ForLoopDesugar |
400 hir::MatchSource::Normal => {
401 let mut err = cx.tcx.struct_span_lint_hir(
402 lint::builtin::UNREACHABLE_PATTERNS,
405 "unreachable pattern",
407 // if we had a catchall pattern, hint at that
408 if let Some(catchall) = catchall {
409 err.span_label(pat.span, "unreachable pattern");
410 err.span_label(catchall, "matches any value");
415 // Unreachable patterns in try expressions occur when one of the arms
416 // are an uninhabited type. Which is OK.
417 hir::MatchSource::TryDesugar => {}
421 UsefulWithWitness(_) => bug!()
425 if catchall.is_none() && pat_is_catchall(hir_pat) {
426 catchall = Some(pat.span);
433 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(
434 cx: &mut MatchCheckCtxt<'a, 'tcx>,
437 matrix: &Matrix<'p, 'tcx>,
439 let wild_pattern = Pattern {
442 kind: box PatternKind::Wild,
444 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
445 UsefulWithWitness(pats) => {
446 let witnesses = if pats.is_empty() {
449 pats.iter().map(|w| w.single_pattern()).collect()
452 const LIMIT: usize = 3;
453 let joined_patterns = match witnesses.len() {
455 1 => format!("`{}`", witnesses[0]),
457 let (tail, head) = witnesses.split_last().unwrap();
458 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
459 format!("`{}` and `{}`", head.join("`, `"), tail)
462 let (head, tail) = witnesses.split_at(LIMIT);
463 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
464 format!("`{}` and {} more", head.join("`, `"), tail.len())
468 let label_text = match witnesses.len() {
469 1 => format!("pattern {} not covered", joined_patterns),
470 _ => format!("patterns {} not covered", joined_patterns),
472 let mut err = create_e0004(cx.tcx.sess, sp, format!(
473 "non-exhaustive patterns: {} not covered",
476 err.span_label(sp, label_text);
477 // point at the definition of non-covered enum variants
478 if let ty::Adt(def, _) = scrut_ty.sty {
479 if let Some(sp) = cx.tcx.hir().span_if_local(def.did){
480 err.span_label(sp, format!("`{}` defined here", scrut_ty));
483 let patterns = witnesses.iter().map(|p| (**p).clone()).collect::<Vec<Pattern<'_>>>();
484 if patterns.len() < 4 {
485 for sp in maybe_point_at_variant(cx, scrut_ty, patterns.as_slice()) {
486 err.span_label(sp, "not covered");
489 err.help("ensure that all possible cases are being handled, \
490 possibly by adding wildcards or more match arms");
494 // This is good, wildcard pattern isn't reachable
500 fn maybe_point_at_variant(
501 cx: &mut MatchCheckCtxt<'a, 'tcx>,
503 patterns: &[Pattern<'_>],
505 let mut covered = vec![];
506 if let ty::Adt(def, _) = ty.sty {
507 // Don't point at variants that have already been covered due to other patterns to avoid
509 for pattern in patterns {
510 let pk: &PatternKind<'_> = &pattern.kind;
511 if let PatternKind::Variant { adt_def, variant_index, subpatterns, .. } = pk {
512 if adt_def.did == def.did {
513 let sp = def.variants[*variant_index].ident.span;
514 if covered.contains(&sp) {
518 let subpatterns = subpatterns.iter()
519 .map(|field_pattern| field_pattern.pattern.clone())
520 .collect::<Vec<_>>();
522 maybe_point_at_variant(cx, ty, subpatterns.as_slice()),
526 if let PatternKind::Leaf { subpatterns } = pk {
527 let subpatterns = subpatterns.iter()
528 .map(|field_pattern| field_pattern.pattern.clone())
529 .collect::<Vec<_>>();
530 covered.extend(maybe_point_at_variant(cx, ty, subpatterns.as_slice()));
537 // Legality of move bindings checking
538 fn check_legality_of_move_bindings(
539 cx: &MatchVisitor<'_, '_>,
543 let mut by_ref_span = None;
545 pat.each_binding(|_, hir_id, span, _path| {
546 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
547 if let ty::BindByReference(..) = bm {
548 by_ref_span = Some(span);
551 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
555 let span_vec = &mut Vec::new();
556 let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
557 // check legality of moving out of the enum
559 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
560 if sub.map_or(false, |p| p.contains_bindings()) {
561 struct_span_err!(cx.tcx.sess, p.span, E0007,
562 "cannot bind by-move with sub-bindings")
563 .span_label(p.span, "binds an already bound by-move value by moving it")
565 } else if has_guard && !cx.tcx.features().bind_by_move_pattern_guards {
566 let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
567 "cannot bind by-move into a pattern guard");
568 err.span_label(p.span, "moves value into pattern guard");
569 if cx.tcx.sess.opts.unstable_features.is_nightly_build() {
570 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
571 crate attributes to enable");
574 } else if let Some(_by_ref_span) = by_ref_span {
575 span_vec.push(p.span);
581 if let PatKind::Binding(_, _, _, ref sub) = p.node {
582 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
584 ty::BindByValue(..) => {
585 let pat_ty = cx.tables.node_type(p.hir_id);
586 if !pat_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, pat.span) {
587 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
593 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
599 if !span_vec.is_empty(){
600 let span = MultiSpan::from_spans(span_vec.clone());
601 let mut err = struct_span_err!(
605 "cannot bind by-move and by-ref in the same pattern",
607 if let Some(by_ref_span) = by_ref_span {
608 err.span_label(by_ref_span, "both by-ref and by-move used");
610 for span in span_vec.iter(){
611 err.span_label(*span, "by-move pattern here");
617 /// Ensures that a pattern guard doesn't borrow by mutable reference or assign.
619 // FIXME: this should be done by borrowck.
620 fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) {
621 let mut checker = MutationChecker {
625 hir::Guard::If(expr) =>
626 ExprUseVisitor::new(&mut checker,
629 cx.region_scope_tree,
631 None).walk_expr(expr),
635 struct MutationChecker<'a, 'tcx: 'a> {
636 cx: &'a MatchVisitor<'a, 'tcx>,
639 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
640 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {}
641 fn consume(&mut self, _: hir::HirId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {}
642 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {}
648 kind:ty:: BorrowKind,
652 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
653 "cannot mutably borrow in a pattern guard");
654 err.span_label(span, "borrowed mutably in pattern guard");
655 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() {
656 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
657 crate attributes to enable");
661 ty::ImmBorrow | ty::UniqueImmBorrow => {}
664 fn decl_without_init(&mut self, _: hir::HirId, _: Span) {}
665 fn mutate(&mut self, _: hir::HirId, span: Span, _: &cmt_<'_>, mode: MutateMode) {
667 MutateMode::JustWrite | MutateMode::WriteAndRead => {
668 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
669 .span_label(span, "assignment in pattern guard")
672 MutateMode::Init => {}
677 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
678 /// because of the way rvalues are handled in the borrow check. (See issue
680 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
681 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
684 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
685 cx: &'a MatchVisitor<'b, 'tcx>,
686 bindings_allowed: bool
689 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
690 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
691 NestedVisitorMap::None
694 fn visit_pat(&mut self, pat: &Pat) {
696 PatKind::Binding(.., ref subpat) => {
697 if !self.bindings_allowed {
698 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
699 "pattern bindings are not allowed after an `@`")
700 .span_label(pat.span, "not allowed after `@`")
704 if subpat.is_some() {
705 let bindings_were_allowed = self.bindings_allowed;
706 self.bindings_allowed = false;
707 intravisit::walk_pat(self, pat);
708 self.bindings_allowed = bindings_were_allowed;
711 _ => intravisit::walk_pat(self, pat),