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 eval::report_const_eval_err;
19 use rustc::dep_graph::DepNode;
21 use rustc::middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor};
22 use rustc::middle::expr_use_visitor::{LoanCause, MutateMode};
23 use rustc::middle::expr_use_visitor as euv;
24 use rustc::middle::mem_categorization::{cmt};
25 use rustc::session::Session;
26 use rustc::traits::Reveal;
27 use rustc::ty::{self, Ty, TyCtxt};
29 use rustc_errors::{Diagnostic, Level, DiagnosticBuilder};
31 use rustc::hir::def::*;
32 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
33 use rustc::hir::{self, Pat, PatKind};
35 use rustc_back::slice;
39 use syntax_pos::{Span, DUMMY_SP};
41 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
43 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
44 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
45 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
48 fn visit_fn(&mut self, fk: FnKind<'tcx>, fd: &'tcx hir::FnDecl,
49 b: hir::BodyId, s: Span, id: ast::NodeId) {
50 intravisit::walk_fn(self, fk, fd, b, s, id);
54 tables: self.tcx.body_tables(b),
55 param_env: &ty::ParameterEnvironment::for_item(self.tcx, id)
56 }.visit_body(self.tcx.hir.body(b));
60 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
61 tcx.visit_all_item_likes_in_krate(DepNode::MatchCheck,
62 &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>
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, 'tcx> MatchVisitor<'a, 'tcx> {
112 fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
113 check_legality_of_move_bindings(self, has_guard, pats);
115 check_legality_of_bindings_in_at_patterns(self, pat);
119 fn report_inlining_errors(&self, patcx: PatternContext, pat_span: Span) {
120 for error in patcx.errors {
122 PatternError::StaticInPattern(span) => {
123 span_err!(self.tcx.sess, span, E0158,
124 "statics cannot be referenced in patterns");
126 PatternError::ConstEval(err) => {
127 report_const_eval_err(self.tcx, &err, pat_span, "pattern").emit();
137 source: hir::MatchSource)
140 // First, check legality of move bindings.
141 self.check_patterns(arm.guard.is_some(), &arm.pats);
143 // Second, if there is a guard on each arm, make sure it isn't
144 // assigning or borrowing anything mutably.
145 if let Some(ref guard) = arm.guard {
146 check_for_mutation_in_guard(self, &guard);
149 // Third, perform some lints.
150 for pat in &arm.pats {
151 check_for_bindings_named_the_same_as_variants(self, pat);
155 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
156 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
157 let mut have_errors = false;
159 let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
160 arm.pats.iter().map(|pat| {
161 let mut patcx = PatternContext::new(self.tcx, self.tables);
162 let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
163 if !patcx.errors.is_empty() {
164 self.report_inlining_errors(patcx, pat.span);
169 arm.guard.as_ref().map(|e| &**e)
172 // Bail out early if inlining failed.
177 // Fourth, check for unreachable arms.
178 check_arms(cx, &inlined_arms, source);
180 let matrix: Matrix = inlined_arms
182 .filter(|&&(_, guard)| guard.is_none())
183 .flat_map(|arm| &arm.0)
184 .map(|pat| vec![pat.0])
186 let scrut_ty = self.tables.node_id_to_type(scrut.id);
187 check_exhaustive(cx, scrut_ty, scrut.span, &matrix, source);
191 fn check_irrefutable(&self, pat: &Pat, is_fn_arg: bool) {
192 let origin = if is_fn_arg {
198 let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(pat.id));
199 MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
200 let mut patcx = PatternContext::new(self.tcx, self.tables);
201 let pattern = patcx.lower_pattern(pat);
202 let pattern_ty = pattern.ty;
203 let pats : Matrix = vec![vec![
204 expand_pattern(cx, pattern)
205 ]].into_iter().collect();
207 let wild_pattern = Pattern {
210 kind: box PatternKind::Wild,
212 let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
213 UsefulWithWitness(witness) => witness,
218 let pattern_string = witness[0].single_pattern().to_string();
219 let mut diag = struct_span_err!(
220 self.tcx.sess, pat.span, E0005,
221 "refutable pattern in {}: `{}` not covered",
222 origin, pattern_string
224 diag.span_label(pat.span, &format!("pattern `{}` not covered", pattern_string));
230 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
232 if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), _, name, None) = p.node {
233 let pat_ty = cx.tables.pat_ty(p);
234 if let ty::TyAdt(edef, _) = pat_ty.sty {
235 if edef.is_enum() && edef.variants.iter().any(|variant| {
236 variant.name == name.node && variant.ctor_kind == CtorKind::Const
238 let ty_path = cx.tcx.item_path_str(edef.did);
239 let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
240 "pattern binding `{}` is named the same as one \
241 of the variants of the type `{}`",
244 "if you meant to match on a variant, \
245 consider making the path in the pattern qualified: `{}::{}`",
255 /// Checks for common cases of "catchall" patterns that may not be intended as such.
256 fn pat_is_catchall(pat: &Pat) -> bool {
258 PatKind::Binding(.., None) => true,
259 PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
260 PatKind::Ref(ref s, _) => pat_is_catchall(s),
261 PatKind::Tuple(ref v, _) => v.iter().all(|p| {
268 // Check for unreachable patterns
269 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
270 arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
271 source: hir::MatchSource)
273 let mut seen = Matrix::empty();
274 let mut catchall = None;
275 let mut printed_if_let_err = false;
276 for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
277 for &(pat, hir_pat) in pats {
280 match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
283 hir::MatchSource::IfLetDesugar { .. } => {
284 if printed_if_let_err {
285 // we already printed an irrefutable if-let pattern error.
286 // We don't want two, that's just confusing.
288 // find the first arm pattern so we can use its span
289 let &(ref first_arm_pats, _) = &arms[0];
290 let first_pat = &first_arm_pats[0];
291 let span = first_pat.0.span;
292 struct_span_err!(cx.tcx.sess, span, E0162,
293 "irrefutable if-let pattern")
294 .span_label(span, &format!("irrefutable pattern"))
296 printed_if_let_err = true;
300 hir::MatchSource::WhileLetDesugar => {
301 // find the first arm pattern so we can use its span
302 let &(ref first_arm_pats, _) = &arms[0];
303 let first_pat = &first_arm_pats[0];
304 let span = first_pat.0.span;
306 // check which arm we're on.
308 // The arm with the user-specified pattern.
310 let mut diagnostic = Diagnostic::new(Level::Warning,
311 "unreachable pattern");
312 diagnostic.set_span(pat.span);
313 cx.tcx.sess.add_lint_diagnostic(
314 lint::builtin::UNREACHABLE_PATTERNS,
315 hir_pat.id, diagnostic);
317 // The arm with the wildcard pattern.
319 struct_span_err!(cx.tcx.sess, span, E0165,
320 "irrefutable while-let pattern")
321 .span_label(span, &format!("irrefutable pattern"))
328 hir::MatchSource::ForLoopDesugar |
329 hir::MatchSource::Normal => {
330 let mut diagnostic = Diagnostic::new(Level::Warning,
331 "unreachable pattern");
332 diagnostic.set_span(pat.span);
333 // if we had a catchall pattern, hint at that
334 if let Some(catchall) = catchall {
335 diagnostic.span_label(pat.span, &"this is an unreachable pattern");
336 diagnostic.span_note(catchall, "this pattern matches any value");
338 cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
339 hir_pat.id, diagnostic);
342 // Unreachable patterns in try expressions occur when one of the arms
343 // are an uninhabited type. Which is OK.
344 hir::MatchSource::TryDesugar => {}
348 UsefulWithWitness(_) => bug!()
352 if catchall.is_none() && pat_is_catchall(hir_pat) {
353 catchall = Some(pat.span);
360 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
363 matrix: &Matrix<'a, 'tcx>,
364 source: hir::MatchSource) {
365 let wild_pattern = Pattern {
368 kind: box PatternKind::Wild,
370 match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
371 UsefulWithWitness(pats) => {
372 let witnesses = if pats.is_empty() {
375 pats.iter().map(|w| w.single_pattern()).collect()
378 hir::MatchSource::ForLoopDesugar => {
379 // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
380 let witness = match *witnesses[0].kind {
381 PatternKind::Variant { ref subpatterns, .. } => match &subpatterns[..] {
382 &[ref pat] => &pat.pattern,
387 let pattern_string = witness.to_string();
388 struct_span_err!(cx.tcx.sess, sp, E0297,
389 "refutable pattern in `for` loop binding: \
392 .span_label(sp, &format!("pattern `{}` not covered", pattern_string))
396 const LIMIT: usize = 3;
397 let joined_patterns = match witnesses.len() {
399 1 => format!("`{}`", witnesses[0]),
401 let (tail, head) = witnesses.split_last().unwrap();
402 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
403 format!("`{}` and `{}`", head.join("`, `"), tail)
406 let (head, tail) = witnesses.split_at(LIMIT);
407 let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
408 format!("`{}` and {} more", head.join("`, `"), tail.len())
412 let label_text = match witnesses.len() {
413 1 => format!("pattern {} not covered", joined_patterns),
414 _ => format!("patterns {} not covered", joined_patterns)
416 create_e0004(cx.tcx.sess, sp,
417 format!("non-exhaustive patterns: {} not covered",
419 .span_label(sp, &label_text)
425 // This is good, wildcard pattern isn't reachable
431 // Legality of move bindings checking
432 fn check_legality_of_move_bindings(cx: &MatchVisitor,
435 let mut by_ref_span = None;
437 pat.each_binding(|bm, _, span, _path| {
438 if let hir::BindByRef(..) = bm {
439 by_ref_span = Some(span);
444 let check_move = |p: &Pat, sub: Option<&Pat>| {
445 // check legality of moving out of the enum
447 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
448 if sub.map_or(false, |p| p.contains_bindings()) {
449 struct_span_err!(cx.tcx.sess, p.span, E0007,
450 "cannot bind by-move with sub-bindings")
451 .span_label(p.span, &format!("binds an already bound by-move value by moving it"))
453 } else if has_guard {
454 struct_span_err!(cx.tcx.sess, p.span, E0008,
455 "cannot bind by-move into a pattern guard")
456 .span_label(p.span, &format!("moves value into pattern guard"))
458 } else if by_ref_span.is_some() {
459 struct_span_err!(cx.tcx.sess, p.span, E0009,
460 "cannot bind by-move and by-ref in the same pattern")
461 .span_label(p.span, &format!("by-move pattern here"))
462 .span_label(by_ref_span.unwrap(), &format!("both by-ref and by-move used"))
469 if let PatKind::Binding(hir::BindByValue(..), _, _, ref sub) = p.node {
470 let pat_ty = cx.tables.node_id_to_type(p.id);
471 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
472 check_move(p, sub.as_ref().map(|p| &**p));
480 /// Ensures that a pattern guard doesn't borrow by mutable reference or
483 /// FIXME: this should be done by borrowck.
484 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
485 cx.tcx.infer_ctxt((cx.tables, cx.param_env.clone()), Reveal::NotSpecializable).enter(|infcx| {
486 let mut checker = MutationChecker {
489 ExprUseVisitor::new(&mut checker, &infcx).walk_expr(guard);
493 struct MutationChecker<'a, 'gcx: 'a> {
494 cx: &'a MatchVisitor<'a, 'gcx>,
497 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
498 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
499 fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
500 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
506 kind:ty:: BorrowKind,
510 struct_span_err!(self.cx.tcx.sess, span, E0301,
511 "cannot mutably borrow in a pattern guard")
512 .span_label(span, &format!("borrowed mutably in pattern guard"))
515 ty::ImmBorrow | ty::UniqueImmBorrow => {}
518 fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
519 fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
521 MutateMode::JustWrite | MutateMode::WriteAndRead => {
522 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
523 .span_label(span, &format!("assignment in pattern guard"))
526 MutateMode::Init => {}
531 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
532 /// because of the way rvalues are handled in the borrow check. (See issue
534 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
535 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
538 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
539 cx: &'a MatchVisitor<'b, 'tcx>,
540 bindings_allowed: bool
543 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
544 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
545 NestedVisitorMap::None
548 fn visit_pat(&mut self, pat: &Pat) {
550 PatKind::Binding(.., ref subpat) => {
551 if !self.bindings_allowed {
552 struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
553 "pattern bindings are not allowed after an `@`")
554 .span_label(pat.span, &format!("not allowed after `@`"))
558 if subpat.is_some() {
559 let bindings_were_allowed = self.bindings_allowed;
560 self.bindings_allowed = false;
561 intravisit::walk_pat(self, pat);
562 self.bindings_allowed = bindings_were_allowed;
565 _ => intravisit::walk_pat(self, pat),