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 region_context = self.tcx.hir.local_def_id(id);
50 let region_maps = self.tcx.region_maps(region_context);
54 tables: self.tcx.body_tables(b),
55 region_maps: ®ion_maps,
56 param_env: &ty::ParameterEnvironment::for_item(self.tcx, 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: &'a ty::ParameterEnvironment<'tcx>,
74 region_maps: &'a RegionMaps<'tcx>,
77 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
78 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
79 NestedVisitorMap::None
82 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
83 intravisit::walk_expr(self, ex);
86 hir::ExprMatch(ref scrut, ref arms, source) => {
87 self.check_match(scrut, arms, source);
93 fn visit_local(&mut self, loc: &'tcx hir::Local) {
94 intravisit::walk_local(self, loc);
96 self.check_irrefutable(&loc.pat, false);
98 // Check legality of move bindings and `@` patterns.
99 self.check_patterns(false, slice::ref_slice(&loc.pat));
102 fn visit_body(&mut self, body: &'tcx hir::Body) {
103 intravisit::walk_body(self, body);
105 for arg in &body.arguments {
106 self.check_irrefutable(&arg.pat, true);
107 self.check_patterns(false, slice::ref_slice(&arg.pat));
112 impl<'a, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> {
113 fn report_inlining_errors(&self, pat_span: Span) {
114 for error in &self.errors {
116 PatternError::StaticInPattern(span) => {
117 span_err!(self.tcx.sess, span, E0158,
118 "statics cannot be referenced in patterns");
120 PatternError::ConstEval(ref err) => {
121 err.report(self.tcx, pat_span, "pattern");
128 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
129 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
130 check_legality_of_move_bindings(self, has_guard, pats);
132 check_legality_of_bindings_in_at_patterns(self, pat);
140 source: hir::MatchSource)
143 // First, check legality of move bindings.
144 self.check_patterns(arm.guard.is_some(), &arm.pats);
146 // Second, if there is a guard on each arm, make sure it isn't
147 // assigning or borrowing anything mutably.
148 if let Some(ref guard) = arm.guard {
149 check_for_mutation_in_guard(self, &guard);
152 // Third, perform some lints.
153 for pat in &arm.pats {
154 check_for_bindings_named_the_same_as_variants(self, pat);
158 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
159 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
160 let mut have_errors = false;
162 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
163 arm.pats.iter().map(|pat| {
164 let mut patcx = PatternContext::new(self.tcx, self.tables);
165 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
166 if !patcx.errors.is_empty() {
167 patcx.report_inlining_errors(pat.span);
172 arm.guard.as_ref().map(|e| &**e)
175 // Bail out early if inlining failed.
180 // Fourth, check for unreachable arms.
181 check_arms(cx, &inlined_arms, source);
183 // Then, if the match has no arms, check whether the scrutinee
185 let pat_ty = self.tables.node_id_to_type(scrut.id);
186 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
187 if inlined_arms.is_empty() {
188 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
189 pat_ty.is_uninhabited_from(module, self.tcx)
191 self.conservative_is_uninhabited(pat_ty)
193 if !scrutinee_is_uninhabited {
194 // We know the type is inhabited, so this must be wrong
195 let mut err = create_e0004(self.tcx.sess, scrut.span,
196 format!("non-exhaustive patterns: type {} \
199 span_help!(&mut err, scrut.span,
200 "Please ensure that all possible cases are being handled; \
201 possibly adding wildcards or more match arms.");
204 // If the type *is* uninhabited, it's vacuously exhaustive
208 let matrix: Matrix = inlined_arms
210 .filter(|&&(_, guard)| guard.is_none())
211 .flat_map(|arm| &arm.0)
212 .map(|pat| vec![pat.0])
214 let scrut_ty = self.tables.node_id_to_type(scrut.id);
215 check_exhaustive(cx, scrut_ty, scrut.span, &matrix, source);
219 fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
220 // "rustc-1.0-style" uncontentious uninhabitableness check
221 match scrutinee_ty.sty {
223 ty::TyAdt(def, _) => def.variants.is_empty(),
228 fn check_irrefutable(&self, pat: &Pat, is_fn_arg: bool) {
229 let origin = if is_fn_arg {
235 let module = self.tcx.hir.local_def_id(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, self.tables);
238 let pattern = patcx.lower_pattern(pat);
239 let pattern_ty = pattern.ty;
240 let pats : Matrix = vec![vec![
241 expand_pattern(cx, pattern)
242 ]].into_iter().collect();
244 let wild_pattern = Pattern {
247 kind: box PatternKind::Wild,
249 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
250 UsefulWithWitness(witness) => witness,
255 let pattern_string = witness[0].single_pattern().to_string();
256 let mut diag = struct_span_err!(
257 self.tcx.sess, pat.span, E0005,
258 "refutable pattern in {}: `{}` not covered",
259 origin, pattern_string
261 diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
267 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
269 if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), _, name, None) = p.node {
270 let pat_ty = cx.tables.pat_ty(p);
271 if let ty::TyAdt(edef, _) = pat_ty.sty {
272 if edef.is_enum() && edef.variants.iter().any(|variant| {
273 variant.name == name.node && variant.ctor_kind == CtorKind::Const
275 let ty_path = cx.tcx.item_path_str(edef.did);
276 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
277 "pattern binding `{}` is named the same as one \
278 of the variants of the type `{}`",
281 "if you meant to match on a variant, \
282 consider making the path in the pattern qualified: `{}::{}`",
292 /// Checks for common cases of "catchall" patterns that may not be intended as such.
293 fn pat_is_catchall(pat: &Pat) -> bool {
295 PatKind::Binding(.., None) => true,
296 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
297 PatKind::Ref(ref s, _) => pat_is_catchall(s),
298 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
305 // Check for unreachable patterns
306 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
307 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
308 source: hir::MatchSource)
310 let mut seen = Matrix::empty();
311 let mut catchall = None;
312 let mut printed_if_let_err = false;
313 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
314 for &(pat, hir_pat) in pats {
317 match is_useful(cx, &seen, &v, LeaveOutWitness) {
320 hir::MatchSource::IfLetDesugar { .. } => {
321 if printed_if_let_err {
322 // we already printed an irrefutable if-let pattern error.
323 // We don't want two, that's just confusing.
325 // find the first arm pattern so we can use its span
326 let &(ref first_arm_pats, _) = &arms[0];
327 let first_pat = &first_arm_pats[0];
328 let span = first_pat.0.span;
329 struct_span_err!(cx.tcx.sess, span, E0162,
330 "irrefutable if-let pattern")
331 .span_label(span, "irrefutable pattern")
333 printed_if_let_err = true;
337 hir::MatchSource::WhileLetDesugar => {
338 // find the first arm pattern so we can use its span
339 let &(ref first_arm_pats, _) = &arms[0];
340 let first_pat = &first_arm_pats[0];
341 let span = first_pat.0.span;
343 // check which arm we're on.
345 // The arm with the user-specified pattern.
347 let mut diagnostic = Diagnostic::new(Level::Warning,
348 "unreachable pattern");
349 diagnostic.set_span(pat.span);
350 cx.tcx.sess.add_lint_diagnostic(
351 lint::builtin::UNREACHABLE_PATTERNS,
352 hir_pat.id, diagnostic);
354 // The arm with the wildcard pattern.
356 struct_span_err!(cx.tcx.sess, span, E0165,
357 "irrefutable while-let pattern")
358 .span_label(span, "irrefutable pattern")
365 hir::MatchSource::ForLoopDesugar |
366 hir::MatchSource::Normal => {
367 let mut diagnostic = Diagnostic::new(Level::Warning,
368 "unreachable pattern");
369 diagnostic.set_span(pat.span);
370 // if we had a catchall pattern, hint at that
371 if let Some(catchall) = catchall {
372 diagnostic.span_label(pat.span, "this is an unreachable pattern");
373 diagnostic.span_note(catchall, "this pattern matches any value");
375 cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
376 hir_pat.id, diagnostic);
379 // Unreachable patterns in try expressions occur when one of the arms
380 // are an uninhabited type. Which is OK.
381 hir::MatchSource::TryDesugar => {}
385 UsefulWithWitness(_) => bug!()
389 if catchall.is_none() && pat_is_catchall(hir_pat) {
390 catchall = Some(pat.span);
397 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
400 matrix: &Matrix<'a, 'tcx>,
401 source: hir::MatchSource) {
402 let wild_pattern = Pattern {
405 kind: box PatternKind::Wild,
407 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
408 UsefulWithWitness(pats) => {
409 let witnesses = if pats.is_empty() {
412 pats.iter().map(|w| w.single_pattern()).collect()
415 hir::MatchSource::ForLoopDesugar => {
416 // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
417 let witness = match *witnesses[0].kind {
418 PatternKind::Variant { ref subpatterns, .. } => match &subpatterns[..] {
419 &[ref pat] => &pat.pattern,
424 let pattern_string = witness.to_string();
425 struct_span_err!(cx.tcx.sess, sp, E0297,
426 "refutable pattern in `for` loop binding: \
429 .span_label(sp, format!("pattern `{}` not covered", pattern_string))
433 const LIMIT: usize = 3;
434 let joined_patterns = match witnesses.len() {
436 1 => format!("`{}`", witnesses[0]),
438 let (tail, head) = witnesses.split_last().unwrap();
439 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
440 format!("`{}` and `{}`", head.join("`, `"), tail)
443 let (head, tail) = witnesses.split_at(LIMIT);
444 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
445 format!("`{}` and {} more", head.join("`, `"), tail.len())
449 let label_text = match witnesses.len() {
450 1 => format!("pattern {} not covered", joined_patterns),
451 _ => format!("patterns {} not covered", joined_patterns)
453 create_e0004(cx.tcx.sess, sp,
454 format!("non-exhaustive patterns: {} not covered",
456 .span_label(sp, label_text)
462 // This is good, wildcard pattern isn't reachable
468 // Legality of move bindings checking
469 fn check_legality_of_move_bindings(cx: &MatchVisitor,
472 let mut by_ref_span = None;
474 pat.each_binding(|bm, _, span, _path| {
475 if let hir::BindByRef(..) = bm {
476 by_ref_span = Some(span);
481 let check_move = |p: &Pat, sub: Option<&Pat>| {
482 // check legality of moving out of the enum
484 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
485 if sub.map_or(false, |p| p.contains_bindings()) {
486 struct_span_err!(cx.tcx.sess, p.span, E0007,
487 "cannot bind by-move with sub-bindings")
488 .span_label(p.span, "binds an already bound by-move value by moving it")
490 } else if has_guard {
491 struct_span_err!(cx.tcx.sess, p.span, E0008,
492 "cannot bind by-move into a pattern guard")
493 .span_label(p.span, "moves value into pattern guard")
495 } else if by_ref_span.is_some() {
496 struct_span_err!(cx.tcx.sess, p.span, E0009,
497 "cannot bind by-move and by-ref in the same pattern")
498 .span_label(p.span, "by-move pattern here")
499 .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
506 if let PatKind::Binding(hir::BindByValue(..), _, _, ref sub) = p.node {
507 let pat_ty = cx.tables.node_id_to_type(p.id);
508 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
509 check_move(p, sub.as_ref().map(|p| &**p));
517 /// Ensures that a pattern guard doesn't borrow by mutable reference or
520 /// FIXME: this should be done by borrowck.
521 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
522 cx.tcx.infer_ctxt((cx.tables, cx.param_env.clone()), Reveal::UserFacing).enter(|infcx| {
523 let mut checker = MutationChecker {
526 ExprUseVisitor::new(&mut checker, cx.region_maps, &infcx).walk_expr(guard);
530 struct MutationChecker<'a, 'gcx: 'a> {
531 cx: &'a MatchVisitor<'a, 'gcx>,
534 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
535 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
536 fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
537 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
543 kind:ty:: BorrowKind,
547 struct_span_err!(self.cx.tcx.sess, span, E0301,
548 "cannot mutably borrow in a pattern guard")
549 .span_label(span, "borrowed mutably in pattern guard")
552 ty::ImmBorrow | ty::UniqueImmBorrow => {}
555 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
556 fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
558 MutateMode::JustWrite | MutateMode::WriteAndRead => {
559 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
560 .span_label(span, "assignment in pattern guard")
563 MutateMode::Init => {}
568 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
569 /// because of the way rvalues are handled in the borrow check. (See issue
571 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
572 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
575 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
576 cx: &'a MatchVisitor<'b, 'tcx>,
577 bindings_allowed: bool
580 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
581 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
582 NestedVisitorMap::None
585 fn visit_pat(&mut self, pat: &Pat) {
587 PatKind::Binding(.., ref subpat) => {
588 if !self.bindings_allowed {
589 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
590 "pattern bindings are not allowed after an `@`")
591 .span_label(pat.span, "not allowed after `@`")
595 if subpat.is_some() {
596 let bindings_were_allowed = self.bindings_allowed;
597 self.bindings_allowed = false;
598 intravisit::walk_pat(self, pat);
599 self.bindings_allowed = bindings_were_allowed;
602 _ => intravisit::walk_pat(self, pat),