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::RegionMaps;
22 use rustc::session::Session;
23 use rustc::traits::Reveal;
24 use rustc::ty::{self, Ty, TyCtxt};
26 use rustc_errors::{Diagnostic, Level, 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_maps: &self.tcx.region_maps(def_id),
55 param_env: &self.tcx.parameter_environment(def_id)
56 }.visit_body(self.tcx.hir.body(b));
60 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
61 tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
62 tcx.sess.abort_if_errors();
65 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
66 struct_span_err!(sess, sp, E0004, "{}", &error_message)
69 struct MatchVisitor<'a, 'tcx: 'a> {
70 tcx: TyCtxt<'a, 'tcx, 'tcx>,
71 tables: &'a ty::TypeckTables<'tcx>,
72 param_env: &'a ty::ParameterEnvironment<'tcx>,
73 region_maps: &'a RegionMaps,
76 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
77 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
78 NestedVisitorMap::None
81 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
82 intravisit::walk_expr(self, ex);
85 hir::ExprMatch(ref scrut, ref arms, source) => {
86 self.check_match(scrut, arms, source);
92 fn visit_local(&mut self, loc: &'tcx hir::Local) {
93 intravisit::walk_local(self, loc);
95 self.check_irrefutable(&loc.pat, false);
97 // Check legality of move bindings and `@` patterns.
98 self.check_patterns(false, slice::ref_slice(&loc.pat));
101 fn visit_body(&mut self, body: &'tcx hir::Body) {
102 intravisit::walk_body(self, body);
104 for arg in &body.arguments {
105 self.check_irrefutable(&arg.pat, true);
106 self.check_patterns(false, slice::ref_slice(&arg.pat));
111 impl<'a, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> {
112 fn report_inlining_errors(&self, pat_span: Span) {
113 for error in &self.errors {
115 PatternError::StaticInPattern(span) => {
116 span_err!(self.tcx.sess, span, E0158,
117 "statics cannot be referenced in patterns");
119 PatternError::ConstEval(ref err) => {
120 err.report(self.tcx, pat_span, "pattern");
127 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
128 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
129 check_legality_of_move_bindings(self, has_guard, pats);
131 check_legality_of_bindings_in_at_patterns(self, pat);
139 source: hir::MatchSource)
142 // First, check legality of move bindings.
143 self.check_patterns(arm.guard.is_some(), &arm.pats);
145 // Second, if there is a guard on each arm, make sure it isn't
146 // assigning or borrowing anything mutably.
147 if let Some(ref guard) = arm.guard {
148 check_for_mutation_in_guard(self, &guard);
151 // Third, perform some lints.
152 for pat in &arm.pats {
153 check_for_bindings_named_the_same_as_variants(self, pat);
157 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
158 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
159 let mut have_errors = false;
161 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
162 arm.pats.iter().map(|pat| {
163 let mut patcx = PatternContext::new(self.tcx, self.tables);
164 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
165 if !patcx.errors.is_empty() {
166 patcx.report_inlining_errors(pat.span);
171 arm.guard.as_ref().map(|e| &**e)
174 // Bail out early if inlining failed.
179 // Fourth, check for unreachable arms.
180 check_arms(cx, &inlined_arms, source);
182 // Then, if the match has no arms, check whether the scrutinee
184 let pat_ty = self.tables.node_id_to_type(scrut.id);
185 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
186 if inlined_arms.is_empty() {
187 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
188 pat_ty.is_uninhabited_from(module, self.tcx)
190 self.conservative_is_uninhabited(pat_ty)
192 if !scrutinee_is_uninhabited {
193 // We know the type is inhabited, so this must be wrong
194 let mut err = create_e0004(self.tcx.sess, scrut.span,
195 format!("non-exhaustive patterns: type {} \
198 span_help!(&mut err, scrut.span,
199 "Please ensure that all possible cases are being handled; \
200 possibly adding wildcards or more match arms.");
203 // If the type *is* uninhabited, it's vacuously exhaustive
207 let matrix: Matrix = inlined_arms
209 .filter(|&&(_, guard)| guard.is_none())
210 .flat_map(|arm| &arm.0)
211 .map(|pat| vec![pat.0])
213 let scrut_ty = self.tables.node_id_to_type(scrut.id);
214 check_exhaustive(cx, scrut_ty, scrut.span, &matrix, source);
218 fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
219 // "rustc-1.0-style" uncontentious uninhabitableness check
220 match scrutinee_ty.sty {
222 ty::TyAdt(def, _) => def.variants.is_empty(),
227 fn check_irrefutable(&self, pat: &Pat, is_fn_arg: bool) {
228 let origin = if is_fn_arg {
234 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(pat.id));
235 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
236 let mut patcx = PatternContext::new(self.tcx, self.tables);
237 let pattern = patcx.lower_pattern(pat);
238 let pattern_ty = pattern.ty;
239 let pats : Matrix = vec![vec![
240 expand_pattern(cx, pattern)
241 ]].into_iter().collect();
243 let wild_pattern = Pattern {
246 kind: box PatternKind::Wild,
248 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
249 UsefulWithWitness(witness) => witness,
254 let pattern_string = witness[0].single_pattern().to_string();
255 let mut diag = struct_span_err!(
256 self.tcx.sess, pat.span, E0005,
257 "refutable pattern in {}: `{}` not covered",
258 origin, pattern_string
260 diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
266 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
268 if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), _, name, None) = p.node {
269 let pat_ty = cx.tables.pat_ty(p);
270 if let ty::TyAdt(edef, _) = pat_ty.sty {
271 if edef.is_enum() && edef.variants.iter().any(|variant| {
272 variant.name == name.node && variant.ctor_kind == CtorKind::Const
274 let ty_path = cx.tcx.item_path_str(edef.did);
275 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
276 "pattern binding `{}` is named the same as one \
277 of the variants of the type `{}`",
280 "if you meant to match on a variant, \
281 consider making the path in the pattern qualified: `{}::{}`",
291 /// Checks for common cases of "catchall" patterns that may not be intended as such.
292 fn pat_is_catchall(pat: &Pat) -> bool {
294 PatKind::Binding(.., None) => true,
295 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
296 PatKind::Ref(ref s, _) => pat_is_catchall(s),
297 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
304 // Check for unreachable patterns
305 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
306 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
307 source: hir::MatchSource)
309 let mut seen = Matrix::empty();
310 let mut catchall = None;
311 let mut printed_if_let_err = false;
312 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
313 for &(pat, hir_pat) in pats {
316 match is_useful(cx, &seen, &v, LeaveOutWitness) {
319 hir::MatchSource::IfLetDesugar { .. } => {
320 if printed_if_let_err {
321 // we already printed an irrefutable if-let pattern error.
322 // We don't want two, that's just confusing.
324 // find the first arm pattern so we can use its span
325 let &(ref first_arm_pats, _) = &arms[0];
326 let first_pat = &first_arm_pats[0];
327 let span = first_pat.0.span;
328 struct_span_err!(cx.tcx.sess, span, E0162,
329 "irrefutable if-let pattern")
330 .span_label(span, "irrefutable pattern")
332 printed_if_let_err = true;
336 hir::MatchSource::WhileLetDesugar => {
337 // find the first arm pattern so we can use its span
338 let &(ref first_arm_pats, _) = &arms[0];
339 let first_pat = &first_arm_pats[0];
340 let span = first_pat.0.span;
342 // check which arm we're on.
344 // The arm with the user-specified pattern.
346 let mut diagnostic = Diagnostic::new(Level::Warning,
347 "unreachable pattern");
348 diagnostic.set_span(pat.span);
349 cx.tcx.sess.add_lint_diagnostic(
350 lint::builtin::UNREACHABLE_PATTERNS,
351 hir_pat.id, diagnostic);
353 // The arm with the wildcard pattern.
355 struct_span_err!(cx.tcx.sess, span, E0165,
356 "irrefutable while-let pattern")
357 .span_label(span, "irrefutable pattern")
364 hir::MatchSource::ForLoopDesugar |
365 hir::MatchSource::Normal => {
366 let mut diagnostic = Diagnostic::new(Level::Warning,
367 "unreachable pattern");
368 diagnostic.set_span(pat.span);
369 // if we had a catchall pattern, hint at that
370 if let Some(catchall) = catchall {
371 diagnostic.span_label(pat.span, "this is an unreachable pattern");
372 diagnostic.span_note(catchall, "this pattern matches any value");
374 cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
375 hir_pat.id, diagnostic);
378 // Unreachable patterns in try expressions occur when one of the arms
379 // are an uninhabited type. Which is OK.
380 hir::MatchSource::TryDesugar => {}
384 UsefulWithWitness(_) => bug!()
388 if catchall.is_none() && pat_is_catchall(hir_pat) {
389 catchall = Some(pat.span);
396 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
399 matrix: &Matrix<'a, 'tcx>,
400 source: hir::MatchSource) {
401 let wild_pattern = Pattern {
404 kind: box PatternKind::Wild,
406 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
407 UsefulWithWitness(pats) => {
408 let witnesses = if pats.is_empty() {
411 pats.iter().map(|w| w.single_pattern()).collect()
414 hir::MatchSource::ForLoopDesugar => {
415 // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
416 let witness = match *witnesses[0].kind {
417 PatternKind::Variant { ref subpatterns, .. } => match &subpatterns[..] {
418 &[ref pat] => &pat.pattern,
423 let pattern_string = witness.to_string();
424 struct_span_err!(cx.tcx.sess, sp, E0297,
425 "refutable pattern in `for` loop binding: \
428 .span_label(sp, format!("pattern `{}` not covered", pattern_string))
432 const LIMIT: usize = 3;
433 let joined_patterns = match witnesses.len() {
435 1 => format!("`{}`", witnesses[0]),
437 let (tail, head) = witnesses.split_last().unwrap();
438 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
439 format!("`{}` and `{}`", head.join("`, `"), tail)
442 let (head, tail) = witnesses.split_at(LIMIT);
443 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
444 format!("`{}` and {} more", head.join("`, `"), tail.len())
448 let label_text = match witnesses.len() {
449 1 => format!("pattern {} not covered", joined_patterns),
450 _ => format!("patterns {} not covered", joined_patterns)
452 create_e0004(cx.tcx.sess, sp,
453 format!("non-exhaustive patterns: {} not covered",
455 .span_label(sp, label_text)
461 // This is good, wildcard pattern isn't reachable
467 // Legality of move bindings checking
468 fn check_legality_of_move_bindings(cx: &MatchVisitor,
471 let mut by_ref_span = None;
473 pat.each_binding(|bm, _, span, _path| {
474 if let hir::BindByRef(..) = bm {
475 by_ref_span = Some(span);
480 let check_move = |p: &Pat, sub: Option<&Pat>| {
481 // check legality of moving out of the enum
483 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
484 if sub.map_or(false, |p| p.contains_bindings()) {
485 struct_span_err!(cx.tcx.sess, p.span, E0007,
486 "cannot bind by-move with sub-bindings")
487 .span_label(p.span, "binds an already bound by-move value by moving it")
489 } else if has_guard {
490 struct_span_err!(cx.tcx.sess, p.span, E0008,
491 "cannot bind by-move into a pattern guard")
492 .span_label(p.span, "moves value into pattern guard")
494 } else if by_ref_span.is_some() {
495 struct_span_err!(cx.tcx.sess, p.span, E0009,
496 "cannot bind by-move and by-ref in the same pattern")
497 .span_label(p.span, "by-move pattern here")
498 .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
505 if let PatKind::Binding(hir::BindByValue(..), _, _, ref sub) = p.node {
506 let pat_ty = cx.tables.node_id_to_type(p.id);
507 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
508 check_move(p, sub.as_ref().map(|p| &**p));
516 /// Ensures that a pattern guard doesn't borrow by mutable reference or
519 /// FIXME: this should be done by borrowck.
520 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
521 cx.tcx.infer_ctxt((cx.tables, cx.param_env.clone()), Reveal::UserFacing).enter(|infcx| {
522 let mut checker = MutationChecker {
525 ExprUseVisitor::new(&mut checker, cx.region_maps, &infcx).walk_expr(guard);
529 struct MutationChecker<'a, 'gcx: 'a> {
530 cx: &'a MatchVisitor<'a, 'gcx>,
533 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
534 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
535 fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
536 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
542 kind:ty:: BorrowKind,
546 struct_span_err!(self.cx.tcx.sess, span, E0301,
547 "cannot mutably borrow in a pattern guard")
548 .span_label(span, "borrowed mutably in pattern guard")
551 ty::ImmBorrow | ty::UniqueImmBorrow => {}
554 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
555 fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
557 MutateMode::JustWrite | MutateMode::WriteAndRead => {
558 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
559 .span_label(span, "assignment in pattern guard")
562 MutateMode::Init => {}
567 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
568 /// because of the way rvalues are handled in the borrow check. (See issue
570 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
571 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
574 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
575 cx: &'a MatchVisitor<'b, 'tcx>,
576 bindings_allowed: bool
579 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
580 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
581 NestedVisitorMap::None
584 fn visit_pat(&mut self, pat: &Pat) {
586 PatKind::Binding(.., ref subpat) => {
587 if !self.bindings_allowed {
588 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
589 "pattern bindings are not allowed after an `@`")
590 .span_label(pat.span, "not allowed after `@`")
594 if subpat.is_some() {
595 let bindings_were_allowed = self.bindings_allowed;
596 self.bindings_allowed = false;
597 intravisit::walk_pat(self, pat);
598 self.bindings_allowed = bindings_were_allowed;
601 _ => intravisit::walk_pat(self, pat),