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};
38 use syntax_pos::{Span, DUMMY_SP};
40 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
42 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
43 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
44 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
47 fn visit_body(&mut self, body: &'tcx hir::Body) {
48 intravisit::walk_body(self, body);
49 let def_id = self.tcx.hir.body_owner_def_id(body.id());
50 let _ = self.tcx.check_match(def_id);
54 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
55 tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
56 tcx.sess.abort_if_errors();
59 pub(crate) fn check_match<'a, 'tcx>(
60 tcx: TyCtxt<'a, 'tcx, 'tcx>,
62 ) -> Result<(), ErrorReported> {
63 let body_id = if let Some(id) = tcx.hir.as_local_node_id(def_id) {
64 tcx.hir.body_owned_by(id)
69 tcx.sess.track_errors(|| {
72 tables: tcx.body_tables(body_id),
73 region_scope_tree: &tcx.region_scope_tree(def_id),
74 param_env: tcx.param_env(def_id),
75 identity_substs: Substs::identity_for_item(tcx, def_id),
76 }.visit_body(tcx.hir.body(body_id));
80 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
81 struct_span_err!(sess, sp, E0004, "{}", &error_message)
84 struct MatchVisitor<'a, 'tcx: 'a> {
85 tcx: TyCtxt<'a, 'tcx, 'tcx>,
86 tables: &'a ty::TypeckTables<'tcx>,
87 param_env: ty::ParamEnv<'tcx>,
88 identity_substs: &'tcx Substs<'tcx>,
89 region_scope_tree: &'a region::ScopeTree,
92 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
93 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
94 NestedVisitorMap::None
97 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
98 intravisit::walk_expr(self, ex);
101 hir::ExprKind::Match(ref scrut, ref arms, source) => {
102 self.check_match(scrut, arms, source);
108 fn visit_local(&mut self, loc: &'tcx hir::Local) {
109 intravisit::walk_local(self, loc);
111 self.check_irrefutable(&loc.pat, match loc.source {
112 hir::LocalSource::Normal => "local binding",
113 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
116 // Check legality of move bindings and `@` patterns.
117 self.check_patterns(false, slice::from_ref(&loc.pat));
120 fn visit_body(&mut self, body: &'tcx hir::Body) {
121 intravisit::walk_body(self, body);
123 for arg in &body.arguments {
124 self.check_irrefutable(&arg.pat, "function argument");
125 self.check_patterns(false, slice::from_ref(&arg.pat));
131 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
132 fn report_inlining_errors(&self, pat_span: Span) {
133 for error in &self.errors {
135 PatternError::StaticInPattern(span) => {
136 self.span_e0158(span, "statics cannot be referenced in patterns")
138 PatternError::AssociatedConstInPattern(span) => {
139 self.span_e0158(span, "associated consts cannot be referenced in patterns")
141 PatternError::FloatBug => {
142 // FIXME(#31407) this is only necessary because float parsing is buggy
143 ::rustc::mir::interpret::struct_error(
144 self.tcx.at(pat_span),
145 "could not evaluate float literal (see issue #31407)",
148 PatternError::NonConstPath(span) => {
149 ::rustc::mir::interpret::struct_error(
151 "runtime values cannot be referenced in patterns",
158 fn span_e0158(&self, span: Span, text: &str) {
159 span_err!(self.tcx.sess, span, E0158, "{}", text)
163 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
164 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
165 check_legality_of_move_bindings(self, has_guard, pats);
167 check_legality_of_bindings_in_at_patterns(self, pat);
174 arms: &'tcx [hir::Arm],
175 source: hir::MatchSource)
178 // First, check legality of move bindings.
179 self.check_patterns(arm.guard.is_some(), &arm.pats);
181 // Second, if there is a guard on each arm, make sure it isn't
182 // assigning or borrowing anything mutably.
183 if let Some(ref guard) = arm.guard {
184 if self.tcx.check_for_mutation_in_guard_via_ast_walk() {
185 check_for_mutation_in_guard(self, &guard);
189 // Third, perform some lints.
190 for pat in &arm.pats {
191 check_for_bindings_named_the_same_as_variants(self, pat);
195 let module = self.tcx.hir.get_module_parent(scrut.id);
196 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
197 let mut have_errors = false;
199 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
200 arm.pats.iter().map(|pat| {
201 let mut patcx = PatternContext::new(self.tcx,
202 self.param_env.and(self.identity_substs),
204 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
205 if !patcx.errors.is_empty() {
206 patcx.report_inlining_errors(pat.span);
211 arm.guard.as_ref().map(|e| &**e)
214 // Bail out early if inlining failed.
219 // Fourth, check for unreachable arms.
220 check_arms(cx, &inlined_arms, source);
222 // Then, if the match has no arms, check whether the scrutinee
224 let pat_ty = self.tables.node_id_to_type(scrut.hir_id);
225 let module = self.tcx.hir.get_module_parent(scrut.id);
226 if inlined_arms.is_empty() {
227 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
228 self.tcx.is_ty_uninhabited_from(module, pat_ty)
230 self.conservative_is_uninhabited(pat_ty)
232 if !scrutinee_is_uninhabited {
233 // We know the type is inhabited, so this must be wrong
234 let mut err = create_e0004(self.tcx.sess, scrut.span,
235 format!("non-exhaustive patterns: type {} \
238 span_help!(&mut err, scrut.span,
239 "Please ensure that all possible cases are being handled; \
240 possibly adding wildcards or more match arms.");
243 // If the type *is* uninhabited, it's vacuously exhaustive
247 let matrix: Matrix = inlined_arms
249 .filter(|&&(_, guard)| guard.is_none())
250 .flat_map(|arm| &arm.0)
251 .map(|pat| vec![pat.0])
253 let scrut_ty = self.tables.node_id_to_type(scrut.hir_id);
254 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
258 fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
259 // "rustc-1.0-style" uncontentious uninhabitableness check
260 match scrutinee_ty.sty {
262 ty::TyAdt(def, _) => def.variants.is_empty(),
267 fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
268 let module = self.tcx.hir.get_module_parent(pat.id);
269 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
270 let mut patcx = PatternContext::new(self.tcx,
271 self.param_env.and(self.identity_substs),
273 let pattern = patcx.lower_pattern(pat);
274 let pattern_ty = pattern.ty;
275 let pats : Matrix = vec![vec![
276 expand_pattern(cx, pattern)
277 ]].into_iter().collect();
279 let wild_pattern = Pattern {
282 kind: box PatternKind::Wild,
284 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
285 UsefulWithWitness(witness) => witness,
290 let pattern_string = witness[0].single_pattern().to_string();
291 let mut diag = struct_span_err!(
292 self.tcx.sess, pat.span, E0005,
293 "refutable pattern in {}: `{}` not covered",
294 origin, pattern_string
296 let label_msg = match pat.node {
297 PatKind::Path(hir::QPath::Resolved(None, ref path))
298 if path.segments.len() == 1 && path.segments[0].args.is_none() => {
299 format!("interpreted as a {} pattern, not new variable", path.def.kind_name())
301 _ => format!("pattern `{}` not covered", pattern_string),
303 diag.span_label(pat.span, label_msg);
309 fn check_for_bindings_named_the_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::TyAdt(edef, _) = pat_ty.sty {
319 if edef.is_enum() && edef.variants.iter().any(|variant| {
320 variant.name == ident.name && 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 `{}`",
327 err.span_suggestion_with_applicability(
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>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
359 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
360 source: hir::MatchSource)
362 let mut seen = Matrix::empty();
363 let mut catchall = None;
364 let mut printed_if_let_err = false;
365 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
366 for &(pat, hir_pat) in pats {
369 match is_useful(cx, &seen, &v, LeaveOutWitness) {
372 hir::MatchSource::IfLetDesugar { .. } => {
373 if cx.tcx.features().irrefutable_let_patterns {
375 lint::builtin::IRREFUTABLE_LET_PATTERNS,
376 hir_pat.id, pat.span,
377 "irrefutable if-let pattern");
379 if printed_if_let_err {
380 // we already printed an irrefutable if-let pattern error.
381 // We don't want two, that's just confusing.
383 // find the first arm pattern so we can use its span
384 let &(ref first_arm_pats, _) = &arms[0];
385 let first_pat = &first_arm_pats[0];
386 let span = first_pat.0.span;
387 struct_span_err!(cx.tcx.sess, span, E0162,
388 "irrefutable if-let pattern")
389 .span_label(span, "irrefutable pattern")
391 printed_if_let_err = true;
396 hir::MatchSource::WhileLetDesugar => {
397 // check which arm we're on.
399 // The arm with the user-specified pattern.
402 lint::builtin::UNREACHABLE_PATTERNS,
403 hir_pat.id, pat.span,
404 "unreachable pattern");
406 // The arm with the wildcard pattern.
408 if cx.tcx.features().irrefutable_let_patterns {
410 lint::builtin::IRREFUTABLE_LET_PATTERNS,
411 hir_pat.id, pat.span,
412 "irrefutable while-let pattern");
414 // find the first arm pattern so we can use its span
415 let &(ref first_arm_pats, _) = &arms[0];
416 let first_pat = &first_arm_pats[0];
417 let span = first_pat.0.span;
418 struct_span_err!(cx.tcx.sess, span, E0165,
419 "irrefutable while-let pattern")
420 .span_label(span, "irrefutable pattern")
428 hir::MatchSource::ForLoopDesugar |
429 hir::MatchSource::Normal => {
430 let mut err = cx.tcx.struct_span_lint_node(
431 lint::builtin::UNREACHABLE_PATTERNS,
434 "unreachable pattern",
436 // if we had a catchall pattern, hint at that
437 if let Some(catchall) = catchall {
438 err.span_label(pat.span, "unreachable pattern");
439 err.span_label(catchall, "matches any value");
444 // Unreachable patterns in try expressions occur when one of the arms
445 // are an uninhabited type. Which is OK.
446 hir::MatchSource::TryDesugar => {}
450 UsefulWithWitness(_) => bug!()
454 if catchall.is_none() && pat_is_catchall(hir_pat) {
455 catchall = Some(pat.span);
462 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
465 matrix: &Matrix<'a, 'tcx>) {
466 let wild_pattern = Pattern {
469 kind: box PatternKind::Wild,
471 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
472 UsefulWithWitness(pats) => {
473 let witnesses = if pats.is_empty() {
476 pats.iter().map(|w| w.single_pattern()).collect()
479 const LIMIT: usize = 3;
480 let joined_patterns = match witnesses.len() {
482 1 => format!("`{}`", witnesses[0]),
484 let (tail, head) = witnesses.split_last().unwrap();
485 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
486 format!("`{}` and `{}`", head.join("`, `"), tail)
489 let (head, tail) = witnesses.split_at(LIMIT);
490 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
491 format!("`{}` and {} more", head.join("`, `"), tail.len())
495 let label_text = match witnesses.len() {
496 1 => format!("pattern {} not covered", joined_patterns),
497 _ => format!("patterns {} not covered", joined_patterns)
499 create_e0004(cx.tcx.sess, sp,
500 format!("non-exhaustive patterns: {} not covered",
502 .span_label(sp, label_text)
506 // This is good, wildcard pattern isn't reachable
512 // Legality of move bindings checking
513 fn check_legality_of_move_bindings(cx: &MatchVisitor,
516 let mut by_ref_span = None;
518 pat.each_binding(|_, hir_id, span, _path| {
519 if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
520 if let ty::BindByReference(..) = bm {
521 by_ref_span = Some(span);
524 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
529 let check_move = |p: &Pat, sub: Option<&Pat>| {
530 // check legality of moving out of the enum
532 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
533 if sub.map_or(false, |p| p.contains_bindings()) {
534 struct_span_err!(cx.tcx.sess, p.span, E0007,
535 "cannot bind by-move with sub-bindings")
536 .span_label(p.span, "binds an already bound by-move value by moving it")
538 } else if has_guard {
539 struct_span_err!(cx.tcx.sess, p.span, E0008,
540 "cannot bind by-move into a pattern guard")
541 .span_label(p.span, "moves value into pattern guard")
543 } else if by_ref_span.is_some() {
544 struct_span_err!(cx.tcx.sess, p.span, E0009,
545 "cannot bind by-move and by-ref in the same pattern")
546 .span_label(p.span, "by-move pattern here")
547 .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
554 if let PatKind::Binding(_, _, _, ref sub) = p.node {
555 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
557 ty::BindByValue(..) => {
558 let pat_ty = cx.tables.node_id_to_type(p.hir_id);
559 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
560 check_move(p, sub.as_ref().map(|p| &**p));
566 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
574 /// Ensures that a pattern guard doesn't borrow by mutable reference or
577 /// FIXME: this should be done by borrowck.
578 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
579 let mut checker = MutationChecker {
582 ExprUseVisitor::new(&mut checker, cx.tcx, cx.param_env, cx.region_scope_tree, cx.tables, None)
586 struct MutationChecker<'a, 'tcx: 'a> {
587 cx: &'a MatchVisitor<'a, 'tcx>,
590 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
591 fn matched_pat(&mut self, _: &Pat, _: &cmt_, _: euv::MatchMode) {}
592 fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_, _: ConsumeMode) {}
593 fn consume_pat(&mut self, _: &Pat, _: &cmt_, _: ConsumeMode) {}
599 kind:ty:: BorrowKind,
603 struct_span_err!(self.cx.tcx.sess, span, E0301,
604 "cannot mutably borrow in a pattern guard")
605 .span_label(span, "borrowed mutably in pattern guard")
608 ty::ImmBorrow | ty::UniqueImmBorrow => {}
611 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
612 fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) {
614 MutateMode::JustWrite | MutateMode::WriteAndRead => {
615 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
616 .span_label(span, "assignment in pattern guard")
619 MutateMode::Init => {}
624 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
625 /// because of the way rvalues are handled in the borrow check. (See issue
627 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
628 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
631 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
632 cx: &'a MatchVisitor<'b, 'tcx>,
633 bindings_allowed: bool
636 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
637 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
638 NestedVisitorMap::None
641 fn visit_pat(&mut self, pat: &Pat) {
643 PatKind::Binding(.., ref subpat) => {
644 if !self.bindings_allowed {
645 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
646 "pattern bindings are not allowed after an `@`")
647 .span_label(pat.span, "not allowed after `@`")
651 if subpat.is_some() {
652 let bindings_were_allowed = self.bindings_allowed;
653 self.bindings_allowed = false;
654 intravisit::walk_pat(self, pat);
655 self.bindings_allowed = bindings_were_allowed;
658 _ => intravisit::walk_pat(self, pat),