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)
235 ty::Adt(def, _) => def.variants.is_empty(),
239 if !scrutinee_is_uninhabited {
240 // We know the type is inhabited, so this must be wrong
241 let mut err = create_e0004(self.tcx.sess, scrut.span,
242 format!("non-exhaustive patterns: type `{}` \
245 span_help!(&mut err, scrut.span,
246 "ensure that all possible cases are being handled, \
247 possibly by adding wildcards or more match arms");
250 // If the type *is* uninhabited, it's vacuously exhaustive
254 let matrix: Matrix = inlined_arms
256 .filter(|&&(_, guard)| guard.is_none())
257 .flat_map(|arm| &arm.0)
258 .map(|pat| smallvec![pat.0])
260 let scrut_ty = self.tables.node_id_to_type(scrut.hir_id);
261 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
265 fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
266 let module = self.tcx.hir().get_module_parent(pat.id);
267 MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
268 let mut patcx = PatternContext::new(self.tcx,
269 self.param_env.and(self.identity_substs),
271 let pattern = patcx.lower_pattern(pat);
272 let pattern_ty = pattern.ty;
273 let pats: Matrix = vec![smallvec![
274 expand_pattern(cx, pattern)
275 ]].into_iter().collect();
277 let wild_pattern = Pattern {
280 kind: box PatternKind::Wild,
282 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
283 UsefulWithWitness(witness) => witness,
288 let pattern_string = witness[0].single_pattern().to_string();
289 let mut diag = struct_span_err!(
290 self.tcx.sess, pat.span, E0005,
291 "refutable pattern in {}: `{}` not covered",
292 origin, pattern_string
294 let label_msg = match pat.node {
295 PatKind::Path(hir::QPath::Resolved(None, ref path))
296 if path.segments.len() == 1 && path.segments[0].args.is_none() => {
297 format!("interpreted as {} {} pattern, not new variable",
298 path.def.article(), path.def.kind_name())
300 _ => format!("pattern `{}` not covered", pattern_string),
302 diag.span_label(pat.span, label_msg);
308 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
310 if let PatKind::Binding(_, _, ident, None) = p.node {
311 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
312 if bm != ty::BindByValue(hir::MutImmutable) {
316 let pat_ty = cx.tables.pat_ty(p);
317 if let ty::Adt(edef, _) = pat_ty.sty {
318 if edef.is_enum() && edef.variants.iter().any(|variant| {
319 variant.name == ident.name && variant.ctor_kind == CtorKind::Const
321 let ty_path = cx.tcx.item_path_str(edef.did);
322 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
323 "pattern binding `{}` is named the same as one \
324 of the variants of the type `{}`",
326 err.span_suggestion_with_applicability(
328 "to match on the variant, qualify the path",
329 format!("{}::{}", ty_path, ident),
330 Applicability::MachineApplicable
336 cx.tcx.sess.delay_span_bug(p.span, "missing binding mode");
343 /// Checks for common cases of "catchall" patterns that may not be intended as such.
344 fn pat_is_catchall(pat: &Pat) -> bool {
346 PatKind::Binding(.., None) => true,
347 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
348 PatKind::Ref(ref s, _) => pat_is_catchall(s),
349 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
356 // Check for unreachable patterns
357 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
358 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
359 source: hir::MatchSource)
361 let mut seen = Matrix::empty();
362 let mut catchall = None;
363 let mut printed_if_let_err = false;
364 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
365 for &(pat, hir_pat) in pats {
366 let v = smallvec![pat];
368 match is_useful(cx, &seen, &v, LeaveOutWitness) {
371 hir::MatchSource::IfLetDesugar { .. } => {
372 if cx.tcx.features().irrefutable_let_patterns {
374 lint::builtin::IRREFUTABLE_LET_PATTERNS,
375 hir_pat.id, pat.span,
376 "irrefutable if-let pattern");
378 if printed_if_let_err {
379 // we already printed an irrefutable if-let pattern error.
380 // We don't want two, that's just confusing.
382 // find the first arm pattern so we can use its span
383 let &(ref first_arm_pats, _) = &arms[0];
384 let first_pat = &first_arm_pats[0];
385 let span = first_pat.0.span;
386 struct_span_err!(cx.tcx.sess, span, E0162,
387 "irrefutable if-let pattern")
388 .span_label(span, "irrefutable pattern")
390 printed_if_let_err = true;
395 hir::MatchSource::WhileLetDesugar => {
396 // check which arm we're on.
398 // The arm with the user-specified pattern.
401 lint::builtin::UNREACHABLE_PATTERNS,
402 hir_pat.id, pat.span,
403 "unreachable pattern");
405 // The arm with the wildcard pattern.
407 if cx.tcx.features().irrefutable_let_patterns {
409 lint::builtin::IRREFUTABLE_LET_PATTERNS,
410 hir_pat.id, pat.span,
411 "irrefutable while-let pattern");
413 // find the first arm pattern so we can use its span
414 let &(ref first_arm_pats, _) = &arms[0];
415 let first_pat = &first_arm_pats[0];
416 let span = first_pat.0.span;
417 struct_span_err!(cx.tcx.sess, span, E0165,
418 "irrefutable while-let pattern")
419 .span_label(span, "irrefutable pattern")
427 hir::MatchSource::ForLoopDesugar |
428 hir::MatchSource::Normal => {
429 let mut err = cx.tcx.struct_span_lint_node(
430 lint::builtin::UNREACHABLE_PATTERNS,
433 "unreachable pattern",
435 // if we had a catchall pattern, hint at that
436 if let Some(catchall) = catchall {
437 err.span_label(pat.span, "unreachable pattern");
438 err.span_label(catchall, "matches any value");
443 // Unreachable patterns in try expressions occur when one of the arms
444 // are an uninhabited type. Which is OK.
445 hir::MatchSource::TryDesugar => {}
449 UsefulWithWitness(_) => bug!()
453 if catchall.is_none() && pat_is_catchall(hir_pat) {
454 catchall = Some(pat.span);
461 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
464 matrix: &Matrix<'p, 'tcx>) {
465 let wild_pattern = Pattern {
468 kind: box PatternKind::Wild,
470 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
471 UsefulWithWitness(pats) => {
472 let witnesses = if pats.is_empty() {
475 pats.iter().map(|w| w.single_pattern()).collect()
478 const LIMIT: usize = 3;
479 let joined_patterns = match witnesses.len() {
481 1 => format!("`{}`", witnesses[0]),
483 let (tail, head) = witnesses.split_last().unwrap();
484 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
485 format!("`{}` and `{}`", head.join("`, `"), tail)
488 let (head, tail) = witnesses.split_at(LIMIT);
489 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
490 format!("`{}` and {} more", head.join("`, `"), tail.len())
494 let label_text = match witnesses.len() {
495 1 => format!("pattern {} not covered", joined_patterns),
496 _ => format!("patterns {} not covered", joined_patterns)
498 create_e0004(cx.tcx.sess, sp,
499 format!("non-exhaustive patterns: {} not covered",
501 .span_label(sp, label_text)
505 // This is good, wildcard pattern isn't reachable
511 // Legality of move bindings checking
512 fn check_legality_of_move_bindings(cx: &MatchVisitor,
515 let mut by_ref_span = None;
517 pat.each_binding(|_, hir_id, span, _path| {
518 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
519 if let ty::BindByReference(..) = bm {
520 by_ref_span = Some(span);
523 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
527 let span_vec = &mut Vec::new();
528 let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
529 // check legality of moving out of the enum
531 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
532 if sub.map_or(false, |p| p.contains_bindings()) {
533 struct_span_err!(cx.tcx.sess, p.span, E0007,
534 "cannot bind by-move with sub-bindings")
535 .span_label(p.span, "binds an already bound by-move value by moving it")
537 } else if has_guard && !cx.tcx.allow_bind_by_move_patterns_with_guards() {
538 let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
539 "cannot bind by-move into a pattern guard");
540 err.span_label(p.span, "moves value into pattern guard");
541 if cx.tcx.sess.opts.unstable_features.is_nightly_build() && cx.tcx.use_mir_borrowck() {
542 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
543 crate attributes to enable");
546 } else if let Some(_by_ref_span) = by_ref_span {
547 span_vec.push(p.span);
553 if let PatKind::Binding(_, _, _, ref sub) = p.node {
554 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
556 ty::BindByValue(..) => {
557 let pat_ty = cx.tables.node_id_to_type(p.hir_id);
558 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
559 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
565 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
571 if !span_vec.is_empty(){
572 let span = MultiSpan::from_spans(span_vec.clone());
573 let mut err = struct_span_err!(
577 "cannot bind by-move and by-ref in the same pattern",
579 err.span_label(by_ref_span.unwrap(), "both by-ref and by-move used");
580 for span in span_vec.iter(){
581 err.span_label(*span, "by-move pattern here");
587 /// Ensures that a pattern guard doesn't borrow by mutable reference or
590 /// FIXME: this should be done by borrowck.
591 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Guard) {
592 let mut checker = MutationChecker {
596 hir::Guard::If(expr) =>
597 ExprUseVisitor::new(&mut checker,
600 cx.region_scope_tree,
602 None).walk_expr(expr),
606 struct MutationChecker<'a, 'tcx: 'a> {
607 cx: &'a MatchVisitor<'a, 'tcx>,
610 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
611 fn matched_pat(&mut self, _: &Pat, _: &cmt_, _: euv::MatchMode) {}
612 fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_, _: ConsumeMode) {}
613 fn consume_pat(&mut self, _: &Pat, _: &cmt_, _: ConsumeMode) {}
619 kind:ty:: BorrowKind,
623 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
624 "cannot mutably borrow in a pattern guard");
625 err.span_label(span, "borrowed mutably in pattern guard");
626 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() &&
627 self.cx.tcx.use_mir_borrowck()
629 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
630 crate attributes to enable");
634 ty::ImmBorrow | ty::UniqueImmBorrow => {}
637 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
638 fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) {
640 MutateMode::JustWrite | MutateMode::WriteAndRead => {
641 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
642 .span_label(span, "assignment in pattern guard")
645 MutateMode::Init => {}
650 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
651 /// because of the way rvalues are handled in the borrow check. (See issue
653 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
654 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
657 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
658 cx: &'a MatchVisitor<'b, 'tcx>,
659 bindings_allowed: bool
662 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
663 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
664 NestedVisitorMap::None
667 fn visit_pat(&mut self, pat: &Pat) {
669 PatKind::Binding(.., ref subpat) => {
670 if !self.bindings_allowed {
671 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
672 "pattern bindings are not allowed after an `@`")
673 .span_label(pat.span, "not allowed after `@`")
677 if subpat.is_some() {
678 let bindings_were_allowed = self.bindings_allowed;
679 self.bindings_allowed = false;
680 intravisit::walk_pat(self, pat);
681 self.bindings_allowed = bindings_were_allowed;
684 _ => intravisit::walk_pat(self, pat),