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::ty::{self, Ty, TyCtxt};
25 use rustc_errors::{Diagnostic, Level, DiagnosticBuilder};
27 use rustc::hir::def::*;
28 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
29 use rustc::hir::{self, Pat, PatKind};
31 use rustc_back::slice;
35 use syntax_pos::{Span, DUMMY_SP};
37 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
39 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
40 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
41 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
44 fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
45 b: hir::BodyId, s: Span, id: ast::NodeId) {
46 intravisit::walk_fn(self, fk, fd, b, s, id);
48 let def_id = self.tcx.hir.local_def_id(id);
52 tables: self.tcx.body_tables(b),
53 region_maps: &self.tcx.region_maps(def_id),
54 param_env: self.tcx.param_env(def_id)
55 }.visit_body(self.tcx.hir.body(b));
59 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
60 tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
61 tcx.sess.abort_if_errors();
64 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
65 struct_span_err!(sess, sp, E0004, "{}", &error_message)
68 struct MatchVisitor<'a, 'tcx: 'a> {
69 tcx: TyCtxt<'a, 'tcx, 'tcx>,
70 tables: &'a ty::TypeckTables<'tcx>,
71 param_env: ty::ParamEnv<'tcx>,
72 region_maps: &'a RegionMaps,
75 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
76 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
77 NestedVisitorMap::None
80 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
81 intravisit::walk_expr(self, ex);
84 hir::ExprMatch(ref scrut, ref arms, source) => {
85 self.check_match(scrut, arms, source);
91 fn visit_local(&mut self, loc: &'tcx hir::Local) {
92 intravisit::walk_local(self, loc);
94 self.check_irrefutable(&loc.pat, match loc.source {
95 hir::LocalSource::Normal => "local binding",
96 hir::LocalSource::ForLoopDesugar => "`for` loop binding",
99 // Check legality of move bindings and `@` patterns.
100 self.check_patterns(false, slice::ref_slice(&loc.pat));
103 fn visit_body(&mut self, body: &'tcx hir::Body) {
104 intravisit::walk_body(self, body);
106 for arg in &body.arguments {
107 self.check_irrefutable(&arg.pat, "function argument");
108 self.check_patterns(false, slice::ref_slice(&arg.pat));
113 impl<'a, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> {
114 fn report_inlining_errors(&self, pat_span: Span) {
115 for error in &self.errors {
117 PatternError::StaticInPattern(span) => {
118 span_err!(self.tcx.sess, span, E0158,
119 "statics cannot be referenced in patterns");
121 PatternError::ConstEval(ref err) => {
122 err.report(self.tcx, pat_span, "pattern");
129 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
130 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
131 check_legality_of_move_bindings(self, has_guard, pats);
133 check_legality_of_bindings_in_at_patterns(self, pat);
141 source: hir::MatchSource)
144 // First, check legality of move bindings.
145 self.check_patterns(arm.guard.is_some(), &arm.pats);
147 // Second, if there is a guard on each arm, make sure it isn't
148 // assigning or borrowing anything mutably.
149 if let Some(ref guard) = arm.guard {
150 check_for_mutation_in_guard(self, &guard);
153 // Third, perform some lints.
154 for pat in &arm.pats {
155 check_for_bindings_named_the_same_as_variants(self, pat);
159 let module = self.tcx.hir.get_module_parent(scrut.id);
160 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
161 let mut have_errors = false;
163 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
164 arm.pats.iter().map(|pat| {
165 let mut patcx = PatternContext::new(self.tcx, self.tables);
166 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
167 if !patcx.errors.is_empty() {
168 patcx.report_inlining_errors(pat.span);
173 arm.guard.as_ref().map(|e| &**e)
176 // Bail out early if inlining failed.
181 // Fourth, check for unreachable arms.
182 check_arms(cx, &inlined_arms, source);
184 // Then, if the match has no arms, check whether the scrutinee
186 let pat_ty = self.tables.node_id_to_type(scrut.id);
187 let module = self.tcx.hir.get_module_parent(scrut.id);
188 if inlined_arms.is_empty() {
189 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
190 pat_ty.is_uninhabited_from(module, self.tcx)
192 self.conservative_is_uninhabited(pat_ty)
194 if !scrutinee_is_uninhabited {
195 // We know the type is inhabited, so this must be wrong
196 let mut err = create_e0004(self.tcx.sess, scrut.span,
197 format!("non-exhaustive patterns: type {} \
200 span_help!(&mut err, scrut.span,
201 "Please ensure that all possible cases are being handled; \
202 possibly adding wildcards or more match arms.");
205 // If the type *is* uninhabited, it's vacuously exhaustive
209 let matrix: Matrix = inlined_arms
211 .filter(|&&(_, guard)| guard.is_none())
212 .flat_map(|arm| &arm.0)
213 .map(|pat| vec![pat.0])
215 let scrut_ty = self.tables.node_id_to_type(scrut.id);
216 check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
220 fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
221 // "rustc-1.0-style" uncontentious uninhabitableness check
222 match scrutinee_ty.sty {
224 ty::TyAdt(def, _) => def.variants.is_empty(),
229 fn check_irrefutable(&self, pat: &Pat, origin: &str) {
230 let module = self.tcx.hir.get_module_parent(pat.id);
231 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
232 let mut patcx = PatternContext::new(self.tcx, self.tables);
233 let pattern = patcx.lower_pattern(pat);
234 let pattern_ty = pattern.ty;
235 let pats : Matrix = vec![vec![
236 expand_pattern(cx, pattern)
237 ]].into_iter().collect();
239 let wild_pattern = Pattern {
242 kind: box PatternKind::Wild,
244 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
245 UsefulWithWitness(witness) => witness,
250 let pattern_string = witness[0].single_pattern().to_string();
251 let mut diag = struct_span_err!(
252 self.tcx.sess, pat.span, E0005,
253 "refutable pattern in {}: `{}` not covered",
254 origin, pattern_string
256 diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
262 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
264 if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), _, name, None) = p.node {
265 let pat_ty = cx.tables.pat_ty(p);
266 if let ty::TyAdt(edef, _) = pat_ty.sty {
267 if edef.is_enum() && edef.variants.iter().any(|variant| {
268 variant.name == name.node && variant.ctor_kind == CtorKind::Const
270 let ty_path = cx.tcx.item_path_str(edef.did);
271 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
272 "pattern binding `{}` is named the same as one \
273 of the variants of the type `{}`",
276 "if you meant to match on a variant, \
277 consider making the path in the pattern qualified: `{}::{}`",
287 /// Checks for common cases of "catchall" patterns that may not be intended as such.
288 fn pat_is_catchall(pat: &Pat) -> bool {
290 PatKind::Binding(.., None) => true,
291 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
292 PatKind::Ref(ref s, _) => pat_is_catchall(s),
293 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
300 // Check for unreachable patterns
301 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
302 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
303 source: hir::MatchSource)
305 let mut seen = Matrix::empty();
306 let mut catchall = None;
307 let mut printed_if_let_err = false;
308 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
309 for &(pat, hir_pat) in pats {
312 match is_useful(cx, &seen, &v, LeaveOutWitness) {
315 hir::MatchSource::IfLetDesugar { .. } => {
316 if printed_if_let_err {
317 // we already printed an irrefutable if-let pattern error.
318 // We don't want two, that's just confusing.
320 // find the first arm pattern so we can use its span
321 let &(ref first_arm_pats, _) = &arms[0];
322 let first_pat = &first_arm_pats[0];
323 let span = first_pat.0.span;
324 struct_span_err!(cx.tcx.sess, span, E0162,
325 "irrefutable if-let pattern")
326 .span_label(span, "irrefutable pattern")
328 printed_if_let_err = true;
332 hir::MatchSource::WhileLetDesugar => {
333 // find the first arm pattern so we can use its span
334 let &(ref first_arm_pats, _) = &arms[0];
335 let first_pat = &first_arm_pats[0];
336 let span = first_pat.0.span;
338 // check which arm we're on.
340 // The arm with the user-specified pattern.
342 let mut diagnostic = Diagnostic::new(Level::Warning,
343 "unreachable pattern");
344 diagnostic.set_span(pat.span);
345 cx.tcx.sess.add_lint_diagnostic(
346 lint::builtin::UNREACHABLE_PATTERNS,
347 hir_pat.id, diagnostic);
349 // The arm with the wildcard pattern.
351 struct_span_err!(cx.tcx.sess, span, E0165,
352 "irrefutable while-let pattern")
353 .span_label(span, "irrefutable pattern")
360 hir::MatchSource::ForLoopDesugar |
361 hir::MatchSource::Normal => {
362 let mut diagnostic = Diagnostic::new(Level::Warning,
363 "unreachable pattern");
364 diagnostic.set_span(pat.span);
365 // if we had a catchall pattern, hint at that
366 if let Some(catchall) = catchall {
367 diagnostic.span_label(pat.span, "this is an unreachable pattern");
368 diagnostic.span_note(catchall, "this pattern matches any value");
370 cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
371 hir_pat.id, diagnostic);
374 // Unreachable patterns in try expressions occur when one of the arms
375 // are an uninhabited type. Which is OK.
376 hir::MatchSource::TryDesugar => {}
380 UsefulWithWitness(_) => bug!()
384 if catchall.is_none() && pat_is_catchall(hir_pat) {
385 catchall = Some(pat.span);
392 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
395 matrix: &Matrix<'a, 'tcx>) {
396 let wild_pattern = Pattern {
399 kind: box PatternKind::Wild,
401 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
402 UsefulWithWitness(pats) => {
403 let witnesses = if pats.is_empty() {
406 pats.iter().map(|w| w.single_pattern()).collect()
409 const LIMIT: usize = 3;
410 let joined_patterns = match witnesses.len() {
412 1 => format!("`{}`", witnesses[0]),
414 let (tail, head) = witnesses.split_last().unwrap();
415 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
416 format!("`{}` and `{}`", head.join("`, `"), tail)
419 let (head, tail) = witnesses.split_at(LIMIT);
420 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
421 format!("`{}` and {} more", head.join("`, `"), tail.len())
425 let label_text = match witnesses.len() {
426 1 => format!("pattern {} not covered", joined_patterns),
427 _ => format!("patterns {} not covered", joined_patterns)
429 create_e0004(cx.tcx.sess, sp,
430 format!("non-exhaustive patterns: {} not covered",
432 .span_label(sp, label_text)
436 // This is good, wildcard pattern isn't reachable
442 // Legality of move bindings checking
443 fn check_legality_of_move_bindings(cx: &MatchVisitor,
446 let mut by_ref_span = None;
448 pat.each_binding(|bm, _, span, _path| {
449 if let hir::BindByRef(..) = bm {
450 by_ref_span = Some(span);
455 let check_move = |p: &Pat, sub: Option<&Pat>| {
456 // check legality of moving out of the enum
458 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
459 if sub.map_or(false, |p| p.contains_bindings()) {
460 struct_span_err!(cx.tcx.sess, p.span, E0007,
461 "cannot bind by-move with sub-bindings")
462 .span_label(p.span, "binds an already bound by-move value by moving it")
464 } else if has_guard {
465 struct_span_err!(cx.tcx.sess, p.span, E0008,
466 "cannot bind by-move into a pattern guard")
467 .span_label(p.span, "moves value into pattern guard")
469 } else if by_ref_span.is_some() {
470 struct_span_err!(cx.tcx.sess, p.span, E0009,
471 "cannot bind by-move and by-ref in the same pattern")
472 .span_label(p.span, "by-move pattern here")
473 .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
480 if let PatKind::Binding(hir::BindByValue(..), _, _, ref sub) = p.node {
481 let pat_ty = cx.tables.node_id_to_type(p.id);
482 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
483 check_move(p, sub.as_ref().map(|p| &**p));
491 /// Ensures that a pattern guard doesn't borrow by mutable reference or
494 /// FIXME: this should be done by borrowck.
495 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
496 cx.tcx.infer_ctxt(cx.tables).enter(|infcx| {
497 let mut checker = MutationChecker {
500 ExprUseVisitor::new(&mut checker, cx.region_maps, &infcx, cx.param_env).walk_expr(guard);
504 struct MutationChecker<'a, 'gcx: 'a> {
505 cx: &'a MatchVisitor<'a, 'gcx>,
508 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
509 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
510 fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
511 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
517 kind:ty:: BorrowKind,
521 struct_span_err!(self.cx.tcx.sess, span, E0301,
522 "cannot mutably borrow in a pattern guard")
523 .span_label(span, "borrowed mutably in pattern guard")
526 ty::ImmBorrow | ty::UniqueImmBorrow => {}
529 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
530 fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
532 MutateMode::JustWrite | MutateMode::WriteAndRead => {
533 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
534 .span_label(span, "assignment in pattern guard")
537 MutateMode::Init => {}
542 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
543 /// because of the way rvalues are handled in the borrow check. (See issue
545 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
546 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
549 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
550 cx: &'a MatchVisitor<'b, 'tcx>,
551 bindings_allowed: bool
554 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
555 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
556 NestedVisitorMap::None
559 fn visit_pat(&mut self, pat: &Pat) {
561 PatKind::Binding(.., ref subpat) => {
562 if !self.bindings_allowed {
563 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
564 "pattern bindings are not allowed after an `@`")
565 .span_label(pat.span, "not allowed after `@`")
569 if subpat.is_some() {
570 let bindings_were_allowed = self.bindings_allowed;
571 self.bindings_allowed = false;
572 intravisit::walk_pat(self, pat);
573 self.bindings_allowed = bindings_were_allowed;
576 _ => intravisit::walk_pat(self, pat),