]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/check_match.rs
use a more conservative inhabitableness rule
[rust.git] / src / librustc_const_eval / check_match.rs
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.
4 //
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.
10
11 use _match::{MatchCheckCtxt, Matrix, expand_pattern, is_useful};
12 use _match::Usefulness::*;
13 use _match::WitnessPreference::*;
14
15 use pattern::{Pattern, PatternContext, PatternError, PatternKind};
16
17 use eval::report_const_eval_err;
18
19 use rustc::dep_graph::DepNode;
20
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};
28 use rustc::lint;
29 use rustc_errors::{Diagnostic, Level, DiagnosticBuilder};
30
31 use rustc::hir::def::*;
32 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
33 use rustc::hir::{self, Pat, PatKind};
34
35 use rustc_back::slice;
36
37 use syntax::ast;
38 use syntax::ptr::P;
39 use syntax_pos::{Span, DUMMY_SP};
40
41 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
42
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)
46     }
47
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);
51
52         MatchVisitor {
53             tcx: self.tcx,
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));
57     }
58 }
59
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();
64 }
65
66 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
67     struct_span_err!(sess, sp, E0004, "{}", &error_message)
68 }
69
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 }
75
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
79     }
80
81     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
82         intravisit::walk_expr(self, ex);
83
84         match ex.node {
85             hir::ExprMatch(ref scrut, ref arms, source) => {
86                 self.check_match(scrut, arms, source);
87             }
88             _ => {}
89         }
90     }
91
92     fn visit_local(&mut self, loc: &'tcx hir::Local) {
93         intravisit::walk_local(self, loc);
94
95         self.check_irrefutable(&loc.pat, false);
96
97         // Check legality of move bindings and `@` patterns.
98         self.check_patterns(false, slice::ref_slice(&loc.pat));
99     }
100
101     fn visit_body(&mut self, body: &'tcx hir::Body) {
102         intravisit::walk_body(self, body);
103
104         for arg in &body.arguments {
105             self.check_irrefutable(&arg.pat, true);
106             self.check_patterns(false, slice::ref_slice(&arg.pat));
107         }
108     }
109 }
110
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);
114         for pat in pats {
115             check_legality_of_bindings_in_at_patterns(self, pat);
116         }
117     }
118
119     fn report_inlining_errors(&self, patcx: PatternContext, pat_span: Span) {
120         for error in patcx.errors {
121             match error {
122                 PatternError::StaticInPattern(span) => {
123                     span_err!(self.tcx.sess, span, E0158,
124                               "statics cannot be referenced in patterns");
125                 }
126                 PatternError::ConstEval(err) => {
127                     report_const_eval_err(self.tcx, &err, pat_span, "pattern").emit();
128                 }
129             }
130         }
131     }
132
133     fn check_match(
134         &self,
135         scrut: &hir::Expr,
136         arms: &[hir::Arm],
137         source: hir::MatchSource)
138     {
139         for arm in arms {
140             // First, check legality of move bindings.
141             self.check_patterns(arm.guard.is_some(), &arm.pats);
142
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);
147             }
148
149             // Third, perform some lints.
150             for pat in &arm.pats {
151                 check_for_bindings_named_the_same_as_variants(self, pat);
152             }
153         }
154
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;
158
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);
165                         have_errors = true;
166                     }
167                     (pattern, &**pat)
168                 }).collect(),
169                 arm.guard.as_ref().map(|e| &**e)
170             )).collect();
171
172             // Bail out early if inlining failed.
173             if have_errors {
174                 return;
175             }
176
177             // Fourth, check for unreachable arms.
178             check_arms(cx, &inlined_arms, source);
179
180             // Then, if the match has no arms, check whether the scrutinee
181             // is uninhabited.
182             let pat_ty = self.tables.node_id_to_type(scrut.id);
183             let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(scrut.id));
184             if inlined_arms.is_empty() {
185                 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
186                     pat_ty.is_uninhabited_from(module, self.tcx)
187                 } else {
188                     self.conservative_is_uninhabited(pat_ty)
189                 };
190                 if !scrutinee_is_uninhabited {
191                     // We know the type is inhabited, so this must be wrong
192                     let mut err = create_e0004(self.tcx.sess, scrut.span,
193                                                format!("non-exhaustive patterns: type {} \
194                                                         is non-empty",
195                                                        pat_ty));
196                     span_help!(&mut err, scrut.span,
197                                "Please ensure that all possible cases are being handled; \
198                                 possibly adding wildcards or more match arms.");
199                     err.emit();
200                 }
201                 // If the type *is* uninhabited, it's vacuously exhaustive
202                 return;
203             }
204
205             let matrix: Matrix = inlined_arms
206                 .iter()
207                 .filter(|&&(_, guard)| guard.is_none())
208                 .flat_map(|arm| &arm.0)
209                 .map(|pat| vec![pat.0])
210                 .collect();
211             let scrut_ty = self.tables.node_id_to_type(scrut.id);
212             check_exhaustive(cx, scrut_ty, scrut.span, &matrix, source);
213         })
214     }
215
216     fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
217         // "rustc-1.0-style" uncontentious uninhabitableness check
218         match scrutinee_ty.sty {
219             ty::TyNever => true,
220             ty::TyAdt(def, _) => def.variants.is_empty(),
221             _ => false
222         }
223     }
224
225     fn check_irrefutable(&self, pat: &Pat, is_fn_arg: bool) {
226         let origin = if is_fn_arg {
227             "function argument"
228         } else {
229             "local binding"
230         };
231
232         let module = self.tcx.hir.local_def_id(self.tcx.hir.get_module_parent(pat.id));
233         MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
234             let mut patcx = PatternContext::new(self.tcx, self.tables);
235             let pattern = patcx.lower_pattern(pat);
236             let pattern_ty = pattern.ty;
237             let pats : Matrix = vec![vec![
238                 expand_pattern(cx, pattern)
239             ]].into_iter().collect();
240
241             let wild_pattern = Pattern {
242                 ty: pattern_ty,
243                 span: DUMMY_SP,
244                 kind: box PatternKind::Wild,
245             };
246             let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
247                 UsefulWithWitness(witness) => witness,
248                 NotUseful => return,
249                 Useful => bug!()
250             };
251
252             let pattern_string = witness[0].single_pattern().to_string();
253             let mut diag = struct_span_err!(
254                 self.tcx.sess, pat.span, E0005,
255                 "refutable pattern in {}: `{}` not covered",
256                 origin, pattern_string
257             );
258             diag.span_label(pat.span, &format!("pattern `{}` not covered", pattern_string));
259             diag.emit();
260         });
261     }
262 }
263
264 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
265     pat.walk(|p| {
266         if let PatKind::Binding(hir::BindByValue(hir::MutImmutable), _, name, None) = p.node {
267             let pat_ty = cx.tables.pat_ty(p);
268             if let ty::TyAdt(edef, _) = pat_ty.sty {
269                 if edef.is_enum() && edef.variants.iter().any(|variant| {
270                     variant.name == name.node && variant.ctor_kind == CtorKind::Const
271                 }) {
272                     let ty_path = cx.tcx.item_path_str(edef.did);
273                     let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
274                         "pattern binding `{}` is named the same as one \
275                          of the variants of the type `{}`",
276                         name.node, ty_path);
277                     help!(err,
278                         "if you meant to match on a variant, \
279                         consider making the path in the pattern qualified: `{}::{}`",
280                         ty_path, name.node);
281                     err.emit();
282                 }
283             }
284         }
285         true
286     });
287 }
288
289 /// Checks for common cases of "catchall" patterns that may not be intended as such.
290 fn pat_is_catchall(pat: &Pat) -> bool {
291     match pat.node {
292         PatKind::Binding(.., None) => true,
293         PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
294         PatKind::Ref(ref s, _) => pat_is_catchall(s),
295         PatKind::Tuple(ref v, _) => v.iter().all(|p| {
296             pat_is_catchall(&p)
297         }),
298         _ => false
299     }
300 }
301
302 // Check for unreachable patterns
303 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
304                         arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
305                         source: hir::MatchSource)
306 {
307     let mut seen = Matrix::empty();
308     let mut catchall = None;
309     let mut printed_if_let_err = false;
310     for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
311         for &(pat, hir_pat) in pats {
312             let v = vec![pat];
313
314             match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
315                 NotUseful => {
316                     match source {
317                         hir::MatchSource::IfLetDesugar { .. } => {
318                             if printed_if_let_err {
319                                 // we already printed an irrefutable if-let pattern error.
320                                 // We don't want two, that's just confusing.
321                             } else {
322                                 // find the first arm pattern so we can use its span
323                                 let &(ref first_arm_pats, _) = &arms[0];
324                                 let first_pat = &first_arm_pats[0];
325                                 let span = first_pat.0.span;
326                                 struct_span_err!(cx.tcx.sess, span, E0162,
327                                                 "irrefutable if-let pattern")
328                                     .span_label(span, &format!("irrefutable pattern"))
329                                     .emit();
330                                 printed_if_let_err = true;
331                             }
332                         },
333
334                         hir::MatchSource::WhileLetDesugar => {
335                             // find the first arm pattern so we can use its span
336                             let &(ref first_arm_pats, _) = &arms[0];
337                             let first_pat = &first_arm_pats[0];
338                             let span = first_pat.0.span;
339
340                             // check which arm we're on.
341                             match arm_index {
342                                 // The arm with the user-specified pattern.
343                                 0 => {
344                                     let mut diagnostic = Diagnostic::new(Level::Warning,
345                                                                          "unreachable pattern");
346                                     diagnostic.set_span(pat.span);
347                                     cx.tcx.sess.add_lint_diagnostic(
348                                             lint::builtin::UNREACHABLE_PATTERNS,
349                                             hir_pat.id, diagnostic);
350                                 },
351                                 // The arm with the wildcard pattern.
352                                 1 => {
353                                     struct_span_err!(cx.tcx.sess, span, E0165,
354                                                      "irrefutable while-let pattern")
355                                         .span_label(span, &format!("irrefutable pattern"))
356                                         .emit();
357                                 },
358                                 _ => bug!(),
359                             }
360                         },
361
362                         hir::MatchSource::ForLoopDesugar |
363                         hir::MatchSource::Normal => {
364                             let mut diagnostic = Diagnostic::new(Level::Warning,
365                                                                  "unreachable pattern");
366                             diagnostic.set_span(pat.span);
367                             // if we had a catchall pattern, hint at that
368                             if let Some(catchall) = catchall {
369                                 diagnostic.span_label(pat.span, &"this is an unreachable pattern");
370                                 diagnostic.span_note(catchall, "this pattern matches any value");
371                             }
372                             cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
373                                                             hir_pat.id, diagnostic);
374                         },
375
376                         // Unreachable patterns in try expressions occur when one of the arms
377                         // are an uninhabited type. Which is OK.
378                         hir::MatchSource::TryDesugar => {}
379                     }
380                 }
381                 Useful => (),
382                 UsefulWithWitness(_) => bug!()
383             }
384             if guard.is_none() {
385                 seen.push(v);
386                 if catchall.is_none() && pat_is_catchall(hir_pat) {
387                     catchall = Some(pat.span);
388                 }
389             }
390         }
391     }
392 }
393
394 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
395                               scrut_ty: Ty<'tcx>,
396                               sp: Span,
397                               matrix: &Matrix<'a, 'tcx>,
398                               source: hir::MatchSource) {
399     let wild_pattern = Pattern {
400         ty: scrut_ty,
401         span: DUMMY_SP,
402         kind: box PatternKind::Wild,
403     };
404     match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
405         UsefulWithWitness(pats) => {
406             let witnesses = if pats.is_empty() {
407                 vec![&wild_pattern]
408             } else {
409                 pats.iter().map(|w| w.single_pattern()).collect()
410             };
411             match source {
412                 hir::MatchSource::ForLoopDesugar => {
413                     // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
414                     let witness = match *witnesses[0].kind {
415                         PatternKind::Variant { ref subpatterns, .. } => match &subpatterns[..] {
416                             &[ref pat] => &pat.pattern,
417                             _ => bug!(),
418                         },
419                         _ => bug!(),
420                     };
421                     let pattern_string = witness.to_string();
422                     struct_span_err!(cx.tcx.sess, sp, E0297,
423                         "refutable pattern in `for` loop binding: \
424                                 `{}` not covered",
425                                 pattern_string)
426                         .span_label(sp, &format!("pattern `{}` not covered", pattern_string))
427                         .emit();
428                 },
429                 _ => {
430                     const LIMIT: usize = 3;
431                     let joined_patterns = match witnesses.len() {
432                         0 => bug!(),
433                         1 => format!("`{}`", witnesses[0]),
434                         2...LIMIT => {
435                             let (tail, head) = witnesses.split_last().unwrap();
436                             let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
437                             format!("`{}` and `{}`", head.join("`, `"), tail)
438                         },
439                         _ => {
440                             let (head, tail) = witnesses.split_at(LIMIT);
441                             let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
442                             format!("`{}` and {} more", head.join("`, `"), tail.len())
443                         }
444                     };
445
446                     let label_text = match witnesses.len() {
447                         1 => format!("pattern {} not covered", joined_patterns),
448                         _ => format!("patterns {} not covered", joined_patterns)
449                     };
450                     create_e0004(cx.tcx.sess, sp,
451                                  format!("non-exhaustive patterns: {} not covered",
452                                          joined_patterns))
453                         .span_label(sp, &label_text)
454                         .emit();
455                 },
456             }
457         }
458         NotUseful => {
459             // This is good, wildcard pattern isn't reachable
460         },
461         _ => bug!()
462     }
463 }
464
465 // Legality of move bindings checking
466 fn check_legality_of_move_bindings(cx: &MatchVisitor,
467                                    has_guard: bool,
468                                    pats: &[P<Pat>]) {
469     let mut by_ref_span = None;
470     for pat in pats {
471         pat.each_binding(|bm, _, span, _path| {
472             if let hir::BindByRef(..) = bm {
473                 by_ref_span = Some(span);
474             }
475         })
476     }
477
478     let check_move = |p: &Pat, sub: Option<&Pat>| {
479         // check legality of moving out of the enum
480
481         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
482         if sub.map_or(false, |p| p.contains_bindings()) {
483             struct_span_err!(cx.tcx.sess, p.span, E0007,
484                              "cannot bind by-move with sub-bindings")
485                 .span_label(p.span, &format!("binds an already bound by-move value by moving it"))
486                 .emit();
487         } else if has_guard {
488             struct_span_err!(cx.tcx.sess, p.span, E0008,
489                       "cannot bind by-move into a pattern guard")
490                 .span_label(p.span, &format!("moves value into pattern guard"))
491                 .emit();
492         } else if by_ref_span.is_some() {
493             struct_span_err!(cx.tcx.sess, p.span, E0009,
494                             "cannot bind by-move and by-ref in the same pattern")
495                     .span_label(p.span, &format!("by-move pattern here"))
496                     .span_label(by_ref_span.unwrap(), &format!("both by-ref and by-move used"))
497                     .emit();
498         }
499     };
500
501     for pat in pats {
502         pat.walk(|p| {
503             if let PatKind::Binding(hir::BindByValue(..), _, _, ref sub) = p.node {
504                 let pat_ty = cx.tables.node_id_to_type(p.id);
505                 if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
506                     check_move(p, sub.as_ref().map(|p| &**p));
507                 }
508             }
509             true
510         });
511     }
512 }
513
514 /// Ensures that a pattern guard doesn't borrow by mutable reference or
515 /// assign.
516 ///
517 /// FIXME: this should be done by borrowck.
518 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
519     cx.tcx.infer_ctxt((cx.tables, cx.param_env.clone()), Reveal::NotSpecializable).enter(|infcx| {
520         let mut checker = MutationChecker {
521             cx: cx,
522         };
523         ExprUseVisitor::new(&mut checker, &infcx).walk_expr(guard);
524     });
525 }
526
527 struct MutationChecker<'a, 'gcx: 'a> {
528     cx: &'a MatchVisitor<'a, 'gcx>,
529 }
530
531 impl<'a, 'gcx, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'gcx> {
532     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
533     fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
534     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
535     fn borrow(&mut self,
536               _: ast::NodeId,
537               span: Span,
538               _: cmt,
539               _: &'tcx ty::Region,
540               kind:ty:: BorrowKind,
541               _: LoanCause) {
542         match kind {
543             ty::MutBorrow => {
544                 struct_span_err!(self.cx.tcx.sess, span, E0301,
545                           "cannot mutably borrow in a pattern guard")
546                     .span_label(span, &format!("borrowed mutably in pattern guard"))
547                     .emit();
548             }
549             ty::ImmBorrow | ty::UniqueImmBorrow => {}
550         }
551     }
552     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
553     fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
554         match mode {
555             MutateMode::JustWrite | MutateMode::WriteAndRead => {
556                 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
557                     .span_label(span, &format!("assignment in pattern guard"))
558                     .emit();
559             }
560             MutateMode::Init => {}
561         }
562     }
563 }
564
565 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
566 /// because of the way rvalues are handled in the borrow check. (See issue
567 /// #14587.)
568 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
569     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
570 }
571
572 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
573     cx: &'a MatchVisitor<'b, 'tcx>,
574     bindings_allowed: bool
575 }
576
577 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
578     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
579         NestedVisitorMap::None
580     }
581
582     fn visit_pat(&mut self, pat: &Pat) {
583         match pat.node {
584             PatKind::Binding(.., ref subpat) => {
585                 if !self.bindings_allowed {
586                     struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
587                                      "pattern bindings are not allowed after an `@`")
588                         .span_label(pat.span,  &format!("not allowed after `@`"))
589                         .emit();
590                 }
591
592                 if subpat.is_some() {
593                     let bindings_were_allowed = self.bindings_allowed;
594                     self.bindings_allowed = false;
595                     intravisit::walk_pat(self, pat);
596                     self.bindings_allowed = bindings_were_allowed;
597                 }
598             }
599             _ => intravisit::walk_pat(self, pat),
600         }
601     }
602 }