1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use super::_match::{MatchCheckCtxt, Matrix, expand_pattern, is_useful};
12 use super::_match::Usefulness::*;
13 use super::_match::WitnessPreference::*;
15 use super::{Pattern, PatternContext, PatternError, PatternKind};
17 use rustc::middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor};
18 use rustc::middle::expr_use_visitor::{LoanCause, MutateMode};
19 use rustc::middle::expr_use_visitor as euv;
20 use rustc::middle::mem_categorization::cmt_;
21 use rustc::middle::region;
22 use rustc::session::Session;
23 use rustc::ty::{self, Ty, TyCtxt};
24 use rustc::ty::subst::Substs;
26 use rustc_errors::{Applicability, DiagnosticBuilder};
27 use rustc::util::common::ErrorReported;
29 use rustc::hir::def::*;
30 use rustc::hir::def_id::DefId;
31 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
32 use rustc::hir::{self, Pat, PatKind};
34 use smallvec::smallvec;
39 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
41 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
43 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
44 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
45 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
48 fn visit_body(&mut self, body: &'tcx hir::Body) {
49 intravisit::walk_body(self, body);
50 let def_id = self.tcx.hir().body_owner_def_id(body.id());
51 let _ = self.tcx.check_match(def_id);
55 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
56 tcx.hir().krate().visit_all_item_likes(&mut OuterVisitor { tcx }.as_deep_visitor());
57 tcx.sess.abort_if_errors();
60 pub(crate) fn check_match<'a, 'tcx>(
61 tcx: TyCtxt<'a, 'tcx, 'tcx>,
63 ) -> Result<(), ErrorReported> {
64 let body_id = if let Some(id) = tcx.hir().as_local_node_id(def_id) {
65 tcx.hir().body_owned_by(id)
70 tcx.sess.track_errors(|| {
73 tables: tcx.body_tables(body_id),
74 region_scope_tree: &tcx.region_scope_tree(def_id),
75 param_env: tcx.param_env(def_id),
76 identity_substs: Substs::identity_for_item(tcx, def_id),
77 }.visit_body(tcx.hir().body(body_id));
81 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
82 struct_span_err!(sess, sp, E0004, "{}", &error_message)
85 struct MatchVisitor<'a, 'tcx: 'a> {
86 tcx: TyCtxt<'a, 'tcx, 'tcx>,
87 tables: &'a ty::TypeckTables<'tcx>,
88 param_env: ty::ParamEnv<'tcx>,
89 identity_substs: &'tcx Substs<'tcx>,
90 region_scope_tree: &'a region::ScopeTree,
93 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
94 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
95 NestedVisitorMap::None
98 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
99 intravisit::walk_expr(self, ex);
102 hir::ExprKind::Match(ref scrut, ref arms, source) => {
103 self.check_match(scrut, arms, source);
109 fn visit_local(&mut self, loc: &'tcx hir::Local) {
110 intravisit::walk_local(self, loc);
112 self.check_irrefutable(&loc.pat, match loc.source {
113 hir::LocalSource::Normal => "local binding",
114 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
117 // Check legality of move bindings and `@` patterns.
118 self.check_patterns(false, slice::from_ref(&loc.pat));
121 fn visit_body(&mut self, body: &'tcx hir::Body) {
122 intravisit::walk_body(self, body);
124 for arg in &body.arguments {
125 self.check_irrefutable(&arg.pat, "function argument");
126 self.check_patterns(false, slice::from_ref(&arg.pat));
132 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
133 fn report_inlining_errors(&self, pat_span: Span) {
134 for error in &self.errors {
136 PatternError::StaticInPattern(span) => {
137 self.span_e0158(span, "statics cannot be referenced in patterns")
139 PatternError::AssociatedConstInPattern(span) => {
140 self.span_e0158(span, "associated consts cannot be referenced in patterns")
142 PatternError::FloatBug => {
143 // FIXME(#31407) this is only necessary because float parsing is buggy
144 ::rustc::mir::interpret::struct_error(
145 self.tcx.at(pat_span),
146 "could not evaluate float literal (see issue #31407)",
149 PatternError::NonConstPath(span) => {
150 ::rustc::mir::interpret::struct_error(
152 "runtime values cannot be referenced in patterns",
159 fn span_e0158(&self, span: Span, text: &str) {
160 span_err!(self.tcx.sess, span, E0158, "{}", text)
164 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
165 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
166 check_legality_of_move_bindings(self, has_guard, pats);
168 check_legality_of_bindings_in_at_patterns(self, pat);
175 arms: &'tcx [hir::Arm],
176 source: hir::MatchSource)
179 // First, check legality of move bindings.
180 self.check_patterns(arm.guard.is_some(), &arm.pats);
182 // Second, if there is a guard on each arm, make sure it isn't
183 // assigning or borrowing anything mutably.
184 if let Some(ref guard) = arm.guard {
185 if self.tcx.check_for_mutation_in_guard_via_ast_walk() {
186 check_for_mutation_in_guard(self, &guard);
190 // Third, perform some lints.
191 for pat in &arm.pats {
192 check_for_bindings_named_same_as_variants(self, pat);
196 let module = self.tcx.hir().get_module_parent(scrut.id);
197 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
198 let mut have_errors = false;
200 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
201 arm.pats.iter().map(|pat| {
202 let mut patcx = PatternContext::new(self.tcx,
203 self.param_env.and(self.identity_substs),
205 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
206 if !patcx.errors.is_empty() {
207 patcx.report_inlining_errors(pat.span);
212 arm.guard.as_ref().map(|g| match g {
213 hir::Guard::If(ref e) => &**e,
217 // Bail out early if inlining failed.
222 // Fourth, check for unreachable arms.
223 check_arms(cx, &inlined_arms, source);
225 // Then, if the match has no arms, check whether the scrutinee
227 let pat_ty = self.tables.node_id_to_type(scrut.hir_id);
228 let module = self.tcx.hir().get_module_parent(scrut.id);
229 if inlined_arms.is_empty() {
230 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
231 self.tcx.is_ty_uninhabited_from(module, pat_ty)
233 pat_ty.conservative_is_uninhabited(self.tcx)
235 if !scrutinee_is_uninhabited {
236 // We know the type is inhabited, so this must be wrong
237 let mut err = create_e0004(self.tcx.sess, scrut.span,
238 format!("non-exhaustive patterns: type `{}` \
241 span_help!(&mut err, scrut.span,
242 "ensure that all possible cases are being handled, \
243 possibly by adding wildcards or more match arms");
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_id_to_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(pat.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 diag = 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 diag.span_label(pat.span, label_msg);
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.name == ident.name && variant.ctor_kind == CtorKind::Const
317 let ty_path = cx.tcx.item_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 `{}`",
322 err.span_suggestion_with_applicability(
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>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
354 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
355 source: hir::MatchSource)
357 let mut seen = Matrix::empty();
358 let mut catchall = None;
359 let mut printed_if_let_err = false;
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 { .. } => {
368 if cx.tcx.features().irrefutable_let_patterns {
370 lint::builtin::IRREFUTABLE_LET_PATTERNS,
371 hir_pat.id, pat.span,
372 "irrefutable if-let pattern");
374 if printed_if_let_err {
375 // we already printed an irrefutable if-let pattern error.
376 // We don't want two, that's just confusing.
378 // find the first arm pattern so we can use its span
379 let &(ref first_arm_pats, _) = &arms[0];
380 let first_pat = &first_arm_pats[0];
381 let span = first_pat.0.span;
382 struct_span_err!(cx.tcx.sess, span, E0162,
383 "irrefutable if-let pattern")
384 .span_label(span, "irrefutable pattern")
386 printed_if_let_err = true;
391 hir::MatchSource::WhileLetDesugar => {
392 // check which arm we're on.
394 // The arm with the user-specified pattern.
397 lint::builtin::UNREACHABLE_PATTERNS,
398 hir_pat.id, pat.span,
399 "unreachable pattern");
401 // The arm with the wildcard pattern.
403 if cx.tcx.features().irrefutable_let_patterns {
405 lint::builtin::IRREFUTABLE_LET_PATTERNS,
406 hir_pat.id, pat.span,
407 "irrefutable while-let pattern");
409 // find the first arm pattern so we can use its span
410 let &(ref first_arm_pats, _) = &arms[0];
411 let first_pat = &first_arm_pats[0];
412 let span = first_pat.0.span;
413 struct_span_err!(cx.tcx.sess, span, E0165,
414 "irrefutable while-let pattern")
415 .span_label(span, "irrefutable pattern")
423 hir::MatchSource::ForLoopDesugar |
424 hir::MatchSource::Normal => {
425 let mut err = cx.tcx.struct_span_lint_node(
426 lint::builtin::UNREACHABLE_PATTERNS,
429 "unreachable pattern",
431 // if we had a catchall pattern, hint at that
432 if let Some(catchall) = catchall {
433 err.span_label(pat.span, "unreachable pattern");
434 err.span_label(catchall, "matches any value");
439 // Unreachable patterns in try expressions occur when one of the arms
440 // are an uninhabited type. Which is OK.
441 hir::MatchSource::TryDesugar => {}
445 UsefulWithWitness(_) => bug!()
449 if catchall.is_none() && pat_is_catchall(hir_pat) {
450 catchall = Some(pat.span);
457 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
460 matrix: &Matrix<'p, 'tcx>) {
461 let wild_pattern = Pattern {
464 kind: box PatternKind::Wild,
466 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
467 UsefulWithWitness(pats) => {
468 let witnesses = if pats.is_empty() {
471 pats.iter().map(|w| w.single_pattern()).collect()
474 const LIMIT: usize = 3;
475 let joined_patterns = match witnesses.len() {
477 1 => format!("`{}`", witnesses[0]),
479 let (tail, head) = witnesses.split_last().unwrap();
480 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
481 format!("`{}` and `{}`", head.join("`, `"), tail)
484 let (head, tail) = witnesses.split_at(LIMIT);
485 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
486 format!("`{}` and {} more", head.join("`, `"), tail.len())
490 let label_text = match witnesses.len() {
491 1 => format!("pattern {} not covered", joined_patterns),
492 _ => format!("patterns {} not covered", joined_patterns)
494 create_e0004(cx.tcx.sess, sp,
495 format!("non-exhaustive patterns: {} not covered",
497 .span_label(sp, label_text)
501 // This is good, wildcard pattern isn't reachable
507 // Legality of move bindings checking
508 fn check_legality_of_move_bindings(cx: &MatchVisitor,
511 let mut by_ref_span = None;
513 pat.each_binding(|_, hir_id, span, _path| {
514 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
515 if let ty::BindByReference(..) = bm {
516 by_ref_span = Some(span);
519 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
523 let span_vec = &mut Vec::new();
524 let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
525 // check legality of moving out of the enum
527 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
528 if sub.map_or(false, |p| p.contains_bindings()) {
529 struct_span_err!(cx.tcx.sess, p.span, E0007,
530 "cannot bind by-move with sub-bindings")
531 .span_label(p.span, "binds an already bound by-move value by moving it")
533 } else if has_guard && !cx.tcx.allow_bind_by_move_patterns_with_guards() {
534 let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
535 "cannot bind by-move into a pattern guard");
536 err.span_label(p.span, "moves value into pattern guard");
537 if cx.tcx.sess.opts.unstable_features.is_nightly_build() && cx.tcx.use_mir_borrowck() {
538 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
539 crate attributes to enable");
542 } else if let Some(_by_ref_span) = by_ref_span {
543 span_vec.push(p.span);
549 if let PatKind::Binding(_, _, _, ref sub) = p.node {
550 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
552 ty::BindByValue(..) => {
553 let pat_ty = cx.tables.node_id_to_type(p.hir_id);
554 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
555 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
561 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
567 if !span_vec.is_empty(){
568 let span = MultiSpan::from_spans(span_vec.clone());
569 let mut err = struct_span_err!(
573 "cannot bind by-move and by-ref in the same pattern",
575 err.span_label(by_ref_span.unwrap(), "both by-ref and by-move used");
576 for span in span_vec.iter(){
577 err.span_label(*span, "by-move pattern here");
583 /// Ensures that a pattern guard doesn't borrow by mutable reference or
586 /// FIXME: this should be done by borrowck.
587 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Guard) {
588 let mut checker = MutationChecker {
592 hir::Guard::If(expr) =>
593 ExprUseVisitor::new(&mut checker,
596 cx.region_scope_tree,
598 None).walk_expr(expr),
602 struct MutationChecker<'a, 'tcx: 'a> {
603 cx: &'a MatchVisitor<'a, 'tcx>,
606 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
607 fn matched_pat(&mut self, _: &Pat, _: &cmt_, _: euv::MatchMode) {}
608 fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_, _: ConsumeMode) {}
609 fn consume_pat(&mut self, _: &Pat, _: &cmt_, _: ConsumeMode) {}
615 kind:ty:: BorrowKind,
619 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
620 "cannot mutably borrow in a pattern guard");
621 err.span_label(span, "borrowed mutably in pattern guard");
622 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() &&
623 self.cx.tcx.use_mir_borrowck()
625 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
626 crate attributes to enable");
630 ty::ImmBorrow | ty::UniqueImmBorrow => {}
633 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
634 fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) {
636 MutateMode::JustWrite | MutateMode::WriteAndRead => {
637 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
638 .span_label(span, "assignment in pattern guard")
641 MutateMode::Init => {}
646 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
647 /// because of the way rvalues are handled in the borrow check. (See issue
649 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
650 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
653 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
654 cx: &'a MatchVisitor<'b, 'tcx>,
655 bindings_allowed: bool
658 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
659 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
660 NestedVisitorMap::None
663 fn visit_pat(&mut self, pat: &Pat) {
665 PatKind::Binding(.., ref subpat) => {
666 if !self.bindings_allowed {
667 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
668 "pattern bindings are not allowed after an `@`")
669 .span_label(pat.span, "not allowed after `@`")
673 if subpat.is_some() {
674 let bindings_were_allowed = self.bindings_allowed;
675 self.bindings_allowed = false;
676 intravisit::walk_pat(self, pat);
677 self.bindings_allowed = bindings_were_allowed;
680 _ => intravisit::walk_pat(self, pat),