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 _match::{MatchCheckCtxt, Matrix, expand_pattern, is_useful};
12 use _match::Usefulness::*;
13 use _match::WitnessPreference::*;
15 use pattern::{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::DiagnosticBuilder;
28 use rustc::hir::def::*;
29 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
30 use rustc::hir::{self, Pat, PatKind};
32 use rustc_back::slice;
36 use syntax_pos::{Span, DUMMY_SP};
38 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
40 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
41 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
42 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
45 fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
46 b: hir::BodyId, s: Span, id: ast::NodeId) {
47 intravisit::walk_fn(self, fk, fd, b, s, id);
49 let def_id = self.tcx.hir.local_def_id(id);
53 tables: self.tcx.body_tables(b),
54 region_scope_tree: &self.tcx.region_scope_tree(def_id),
55 param_env: self.tcx.param_env(def_id),
56 identity_substs: Substs::identity_for_item(self.tcx, def_id),
57 }.visit_body(self.tcx.hir.body(b));
61 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
62 tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
63 tcx.sess.abort_if_errors();
66 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
67 struct_span_err!(sess, sp, E0004, "{}", &error_message)
70 struct MatchVisitor<'a, 'tcx: 'a> {
71 tcx: TyCtxt<'a, 'tcx, 'tcx>,
72 tables: &'a ty::TypeckTables<'tcx>,
73 param_env: ty::ParamEnv<'tcx>,
74 identity_substs: &'tcx Substs<'tcx>,
75 region_scope_tree: &'a region::ScopeTree,
78 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
79 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
80 NestedVisitorMap::None
83 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
84 intravisit::walk_expr(self, ex);
87 hir::ExprMatch(ref scrut, ref arms, source) => {
88 self.check_match(scrut, arms, source);
94 fn visit_local(&mut self, loc: &'tcx hir::Local) {
95 intravisit::walk_local(self, loc);
97 self.check_irrefutable(&loc.pat, match loc.source {
98 hir::LocalSource::Normal => "local binding",
99 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
102 // Check legality of move bindings and `@` patterns.
103 self.check_patterns(false, slice::ref_slice(&loc.pat));
106 fn visit_body(&mut self, body: &'tcx hir::Body) {
107 intravisit::walk_body(self, body);
109 for arg in &body.arguments {
110 self.check_irrefutable(&arg.pat, "function argument");
111 self.check_patterns(false, slice::ref_slice(&arg.pat));
116 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
117 fn report_inlining_errors(&self, pat_span: Span) {
118 for error in &self.errors {
120 PatternError::StaticInPattern(span) => {
121 span_err!(self.tcx.sess, span, E0158,
122 "statics cannot be referenced in patterns");
124 PatternError::ConstEval(ref err) => {
125 err.report(self.tcx, pat_span, "pattern");
132 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
133 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
134 check_legality_of_move_bindings(self, has_guard, pats);
136 check_legality_of_bindings_in_at_patterns(self, pat);
143 arms: &'tcx [hir::Arm],
144 source: hir::MatchSource)
147 // First, check legality of move bindings.
148 self.check_patterns(arm.guard.is_some(), &arm.pats);
150 // Second, if there is a guard on each arm, make sure it isn't
151 // assigning or borrowing anything mutably.
152 if let Some(ref guard) = arm.guard {
153 check_for_mutation_in_guard(self, &guard);
156 // Third, perform some lints.
157 for pat in &arm.pats {
158 check_for_bindings_named_the_same_as_variants(self, pat);
162 let module = self.tcx.hir.get_module_parent(scrut.id);
163 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
164 let mut have_errors = false;
166 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
167 arm.pats.iter().map(|pat| {
168 let mut patcx = PatternContext::new(self.tcx,
169 self.param_env.and(self.identity_substs),
171 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
172 if !patcx.errors.is_empty() {
173 patcx.report_inlining_errors(pat.span);
178 arm.guard.as_ref().map(|e| &**e)
181 // Bail out early if inlining failed.
186 // Fourth, check for unreachable arms.
187 check_arms(cx, &inlined_arms, source);
189 // Then, if the match has no arms, check whether the scrutinee
191 let pat_ty = self.tables.node_id_to_type(scrut.hir_id);
192 let module = self.tcx.hir.get_module_parent(scrut.id);
193 if inlined_arms.is_empty() {
194 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
195 pat_ty.is_uninhabited_from(module, self.tcx)
197 self.conservative_is_uninhabited(pat_ty)
199 if !scrutinee_is_uninhabited {
200 // We know the type is inhabited, so this must be wrong
201 let mut err = create_e0004(self.tcx.sess, scrut.span,
202 format!("non-exhaustive patterns: type {} \
205 span_help!(&mut err, scrut.span,
206 "Please ensure that all possible cases are being handled; \
207 possibly adding wildcards or more match arms.");
210 // If the type *is* uninhabited, it's vacuously exhaustive
214 let matrix: Matrix = inlined_arms
216 .filter(|&&(_, guard)| guard.is_none())
217 .flat_map(|arm| &arm.0)
218 .map(|pat| vec![pat.0])
220 let scrut_ty = self.tables.node_id_to_type(scrut.hir_id);
221 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
225 fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
226 // "rustc-1.0-style" uncontentious uninhabitableness check
227 match scrutinee_ty.sty {
229 ty::TyAdt(def, _) => def.variants.is_empty(),
234 fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
235 let module = self.tcx.hir.get_module_parent(pat.id);
236 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
237 let mut patcx = PatternContext::new(self.tcx,
238 self.param_env.and(self.identity_substs),
240 let pattern = patcx.lower_pattern(pat);
241 let pattern_ty = pattern.ty;
242 let pats : Matrix = vec![vec![
243 expand_pattern(cx, pattern)
244 ]].into_iter().collect();
246 let wild_pattern = Pattern {
249 kind: box PatternKind::Wild,
251 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
252 UsefulWithWitness(witness) => witness,
257 let pattern_string = witness[0].single_pattern().to_string();
258 let mut diag = struct_span_err!(
259 self.tcx.sess, pat.span, E0005,
260 "refutable pattern in {}: `{}` not covered",
261 origin, pattern_string
263 diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
269 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
271 if let PatKind::Binding(_, _, name, None) = p.node {
275 .expect("missing binding mode");
277 if bm != ty::BindByValue(hir::MutImmutable) {
281 let pat_ty = cx.tables.pat_ty(p);
282 if let ty::TyAdt(edef, _) = pat_ty.sty {
283 if edef.is_enum() && edef.variants.iter().any(|variant| {
284 variant.name == name.node && variant.ctor_kind == CtorKind::Const
286 let ty_path = cx.tcx.item_path_str(edef.did);
287 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
288 "pattern binding `{}` is named the same as one \
289 of the variants of the type `{}`",
292 "if you meant to match on a variant, \
293 consider making the path in the pattern qualified: `{}::{}`",
303 /// Checks for common cases of "catchall" patterns that may not be intended as such.
304 fn pat_is_catchall(pat: &Pat) -> bool {
306 PatKind::Binding(.., None) => true,
307 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
308 PatKind::Ref(ref s, _) => pat_is_catchall(s),
309 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
316 // Check for unreachable patterns
317 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
318 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
319 source: hir::MatchSource)
321 let mut seen = Matrix::empty();
322 let mut catchall = None;
323 let mut printed_if_let_err = false;
324 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
325 for &(pat, hir_pat) in pats {
328 match is_useful(cx, &seen, &v, LeaveOutWitness) {
331 hir::MatchSource::IfLetDesugar { .. } => {
332 if printed_if_let_err {
333 // we already printed an irrefutable if-let pattern error.
334 // We don't want two, that's just confusing.
336 // find the first arm pattern so we can use its span
337 let &(ref first_arm_pats, _) = &arms[0];
338 let first_pat = &first_arm_pats[0];
339 let span = first_pat.0.span;
340 struct_span_err!(cx.tcx.sess, span, E0162,
341 "irrefutable if-let pattern")
342 .span_label(span, "irrefutable pattern")
344 printed_if_let_err = true;
348 hir::MatchSource::WhileLetDesugar => {
349 // find the first arm pattern so we can use its span
350 let &(ref first_arm_pats, _) = &arms[0];
351 let first_pat = &first_arm_pats[0];
352 let span = first_pat.0.span;
354 // check which arm we're on.
356 // The arm with the user-specified pattern.
359 lint::builtin::UNREACHABLE_PATTERNS,
360 hir_pat.id, pat.span,
361 "unreachable pattern");
363 // The arm with the wildcard pattern.
365 struct_span_err!(cx.tcx.sess, span, E0165,
366 "irrefutable while-let pattern")
367 .span_label(span, "irrefutable pattern")
374 hir::MatchSource::ForLoopDesugar |
375 hir::MatchSource::Normal => {
376 let mut err = cx.tcx.struct_span_lint_node(
377 lint::builtin::UNREACHABLE_PATTERNS,
380 "unreachable pattern",
382 // if we had a catchall pattern, hint at that
383 if let Some(catchall) = catchall {
384 err.span_label(pat.span, "this is an unreachable pattern");
385 err.span_note(catchall, "this pattern matches any value");
390 // Unreachable patterns in try expressions occur when one of the arms
391 // are an uninhabited type. Which is OK.
392 hir::MatchSource::TryDesugar => {}
396 UsefulWithWitness(_) => bug!()
400 if catchall.is_none() && pat_is_catchall(hir_pat) {
401 catchall = Some(pat.span);
408 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
411 matrix: &Matrix<'a, 'tcx>) {
412 let wild_pattern = Pattern {
415 kind: box PatternKind::Wild,
417 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
418 UsefulWithWitness(pats) => {
419 let witnesses = if pats.is_empty() {
422 pats.iter().map(|w| w.single_pattern()).collect()
425 const LIMIT: usize = 3;
426 let joined_patterns = match witnesses.len() {
428 1 => format!("`{}`", witnesses[0]),
430 let (tail, head) = witnesses.split_last().unwrap();
431 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
432 format!("`{}` and `{}`", head.join("`, `"), tail)
435 let (head, tail) = witnesses.split_at(LIMIT);
436 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
437 format!("`{}` and {} more", head.join("`, `"), tail.len())
441 let label_text = match witnesses.len() {
442 1 => format!("pattern {} not covered", joined_patterns),
443 _ => format!("patterns {} not covered", joined_patterns)
445 create_e0004(cx.tcx.sess, sp,
446 format!("non-exhaustive patterns: {} not covered",
448 .span_label(sp, label_text)
452 // This is good, wildcard pattern isn't reachable
458 // Legality of move bindings checking
459 fn check_legality_of_move_bindings(cx: &MatchVisitor,
462 let mut by_ref_span = None;
464 pat.each_binding(|_, id, span, _path| {
465 let hir_id = cx.tcx.hir.node_to_hir_id(id);
469 .expect("missing binding mode");
470 if let ty::BindByReference(..) = bm {
471 by_ref_span = Some(span);
476 let check_move = |p: &Pat, sub: Option<&Pat>| {
477 // check legality of moving out of the enum
479 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
480 if sub.map_or(false, |p| p.contains_bindings()) {
481 struct_span_err!(cx.tcx.sess, p.span, E0007,
482 "cannot bind by-move with sub-bindings")
483 .span_label(p.span, "binds an already bound by-move value by moving it")
485 } else if has_guard {
486 struct_span_err!(cx.tcx.sess, p.span, E0008,
487 "cannot bind by-move into a pattern guard")
488 .span_label(p.span, "moves value into pattern guard")
490 } else if by_ref_span.is_some() {
491 struct_span_err!(cx.tcx.sess, p.span, E0009,
492 "cannot bind by-move and by-ref in the same pattern")
493 .span_label(p.span, "by-move pattern here")
494 .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
501 if let PatKind::Binding(_, _, _, ref sub) = p.node {
505 .expect("missing binding mode");
507 ty::BindByValue(..) => {
508 let pat_ty = cx.tables.node_id_to_type(p.hir_id);
509 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
510 check_move(p, sub.as_ref().map(|p| &**p));
521 /// Ensures that a pattern guard doesn't borrow by mutable reference or
524 /// FIXME: this should be done by borrowck.
525 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
526 let mut checker = MutationChecker {
529 ExprUseVisitor::new(&mut checker, cx.tcx, cx.param_env, cx.region_scope_tree, cx.tables)
533 struct MutationChecker<'a, 'tcx: 'a> {
534 cx: &'a MatchVisitor<'a, 'tcx>,
537 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
538 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
539 fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
540 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
546 kind:ty:: BorrowKind,
550 struct_span_err!(self.cx.tcx.sess, span, E0301,
551 "cannot mutably borrow in a pattern guard")
552 .span_label(span, "borrowed mutably in pattern guard")
555 ty::ImmBorrow | ty::UniqueImmBorrow => {}
558 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
559 fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
561 MutateMode::JustWrite | MutateMode::WriteAndRead => {
562 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
563 .span_label(span, "assignment in pattern guard")
566 MutateMode::Init => {}
571 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
572 /// because of the way rvalues are handled in the borrow check. (See issue
574 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
575 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
578 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
579 cx: &'a MatchVisitor<'b, 'tcx>,
580 bindings_allowed: bool
583 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
584 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
585 NestedVisitorMap::None
588 fn visit_pat(&mut self, pat: &Pat) {
590 PatKind::Binding(.., ref subpat) => {
591 if !self.bindings_allowed {
592 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
593 "pattern bindings are not allowed after an `@`")
594 .span_label(pat.span, "not allowed after `@`")
598 if subpat.is_some() {
599 let bindings_were_allowed = self.bindings_allowed;
600 self.bindings_allowed = false;
601 intravisit::walk_pat(self, pat);
602 self.bindings_allowed = bindings_were_allowed;
605 _ => intravisit::walk_pat(self, pat),