]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/check_match.rs
b35b0865991659d29b461f44f441bc2991ab9d2d
[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 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};
25 use rustc::lint;
26 use rustc_errors::{Diagnostic, Level, DiagnosticBuilder};
27
28 use rustc::hir::def::*;
29 use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
30 use rustc::hir::{self, Pat, PatKind};
31
32 use rustc_back::slice;
33
34 use syntax::ast;
35 use syntax::ptr::P;
36 use syntax_pos::{Span, DUMMY_SP};
37
38 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
39
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)
43     }
44
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);
48
49         let def_id = self.tcx.hir.local_def_id(id);
50
51         MatchVisitor {
52             tcx: self.tcx,
53             tables: self.tcx.body_tables(b),
54             region_maps: &self.tcx.region_maps(def_id),
55             param_env: self.tcx.param_env(def_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.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
62     tcx.sess.abort_if_errors();
63 }
64
65 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
66     struct_span_err!(sess, sp, E0004, "{}", &error_message)
67 }
68
69 struct MatchVisitor<'a, 'tcx: 'a> {
70     tcx: TyCtxt<'a, 'tcx, 'tcx>,
71     tables: &'a ty::TypeckTables<'tcx>,
72     param_env: ty::ParamEnv<'tcx>,
73     region_maps: &'a RegionMaps,
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, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> {
112     fn report_inlining_errors(&self, pat_span: Span) {
113         for error in &self.errors {
114             match *error {
115                 PatternError::StaticInPattern(span) => {
116                     span_err!(self.tcx.sess, span, E0158,
117                               "statics cannot be referenced in patterns");
118                 }
119                 PatternError::ConstEval(ref err) => {
120                     err.report(self.tcx, pat_span, "pattern");
121                 }
122             }
123         }
124     }
125 }
126
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);
130         for pat in pats {
131             check_legality_of_bindings_in_at_patterns(self, pat);
132         }
133     }
134
135     fn check_match(
136         &self,
137         scrut: &hir::Expr,
138         arms: &[hir::Arm],
139         source: hir::MatchSource)
140     {
141         for arm in arms {
142             // First, check legality of move bindings.
143             self.check_patterns(arm.guard.is_some(), &arm.pats);
144
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);
149             }
150
151             // Third, perform some lints.
152             for pat in &arm.pats {
153                 check_for_bindings_named_the_same_as_variants(self, pat);
154             }
155         }
156
157         let module = 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;
160
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);
167                         have_errors = true;
168                     }
169                     (pattern, &**pat)
170                 }).collect(),
171                 arm.guard.as_ref().map(|e| &**e)
172             )).collect();
173
174             // Bail out early if inlining failed.
175             if have_errors {
176                 return;
177             }
178
179             // Fourth, check for unreachable arms.
180             check_arms(cx, &inlined_arms, source);
181
182             // Then, if the match has no arms, check whether the scrutinee
183             // is uninhabited.
184             let pat_ty = self.tables.node_id_to_type(scrut.id);
185             let module = 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)
189                 } else {
190                     self.conservative_is_uninhabited(pat_ty)
191                 };
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 {} \
196                                                         is non-empty",
197                                                        pat_ty));
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.");
201                     err.emit();
202                 }
203                 // If the type *is* uninhabited, it's vacuously exhaustive
204                 return;
205             }
206
207             let matrix: Matrix = inlined_arms
208                 .iter()
209                 .filter(|&&(_, guard)| guard.is_none())
210                 .flat_map(|arm| &arm.0)
211                 .map(|pat| vec![pat.0])
212                 .collect();
213             let scrut_ty = self.tables.node_id_to_type(scrut.id);
214             check_exhaustive(cx, scrut_ty, scrut.span, &matrix, source);
215         })
216     }
217
218     fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
219         // "rustc-1.0-style" uncontentious uninhabitableness check
220         match scrutinee_ty.sty {
221             ty::TyNever => true,
222             ty::TyAdt(def, _) => def.variants.is_empty(),
223             _ => false
224         }
225     }
226
227     fn check_irrefutable(&self, pat: &Pat, is_fn_arg: bool) {
228         let origin = if is_fn_arg {
229             "function argument"
230         } else {
231             "local binding"
232         };
233
234         let module = 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();
242
243             let wild_pattern = Pattern {
244                 ty: pattern_ty,
245                 span: DUMMY_SP,
246                 kind: box PatternKind::Wild,
247             };
248             let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
249                 UsefulWithWitness(witness) => witness,
250                 NotUseful => return,
251                 Useful => bug!()
252             };
253
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
259             );
260             diag.span_label(pat.span, format!("pattern `{}` not covered", pattern_string));
261             diag.emit();
262         });
263     }
264 }
265
266 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
267     pat.walk(|p| {
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
273                 }) {
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 `{}`",
278                         name.node, ty_path);
279                     help!(err,
280                         "if you meant to match on a variant, \
281                         consider making the path in the pattern qualified: `{}::{}`",
282                         ty_path, name.node);
283                     err.emit();
284                 }
285             }
286         }
287         true
288     });
289 }
290
291 /// Checks for common cases of "catchall" patterns that may not be intended as such.
292 fn pat_is_catchall(pat: &Pat) -> bool {
293     match pat.node {
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| {
298             pat_is_catchall(&p)
299         }),
300         _ => false
301     }
302 }
303
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)
308 {
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 {
314             let v = vec![pat];
315
316             match is_useful(cx, &seen, &v, LeaveOutWitness) {
317                 NotUseful => {
318                     match source {
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.
323                             } else {
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")
331                                     .emit();
332                                 printed_if_let_err = true;
333                             }
334                         },
335
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;
341
342                             // check which arm we're on.
343                             match arm_index {
344                                 // The arm with the user-specified pattern.
345                                 0 => {
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);
352                                 },
353                                 // The arm with the wildcard pattern.
354                                 1 => {
355                                     struct_span_err!(cx.tcx.sess, span, E0165,
356                                                      "irrefutable while-let pattern")
357                                         .span_label(span, "irrefutable pattern")
358                                         .emit();
359                                 },
360                                 _ => bug!(),
361                             }
362                         },
363
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");
373                             }
374                             cx.tcx.sess.add_lint_diagnostic(lint::builtin::UNREACHABLE_PATTERNS,
375                                                             hir_pat.id, diagnostic);
376                         },
377
378                         // Unreachable patterns in try expressions occur when one of the arms
379                         // are an uninhabited type. Which is OK.
380                         hir::MatchSource::TryDesugar => {}
381                     }
382                 }
383                 Useful => (),
384                 UsefulWithWitness(_) => bug!()
385             }
386             if guard.is_none() {
387                 seen.push(v);
388                 if catchall.is_none() && pat_is_catchall(hir_pat) {
389                     catchall = Some(pat.span);
390                 }
391             }
392         }
393     }
394 }
395
396 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
397                               scrut_ty: Ty<'tcx>,
398                               sp: Span,
399                               matrix: &Matrix<'a, 'tcx>,
400                               source: hir::MatchSource) {
401     let wild_pattern = Pattern {
402         ty: scrut_ty,
403         span: DUMMY_SP,
404         kind: box PatternKind::Wild,
405     };
406     match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
407         UsefulWithWitness(pats) => {
408             let witnesses = if pats.is_empty() {
409                 vec![&wild_pattern]
410             } else {
411                 pats.iter().map(|w| w.single_pattern()).collect()
412             };
413             match source {
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,
419                             _ => bug!(),
420                         },
421                         _ => bug!(),
422                     };
423                     let pattern_string = witness.to_string();
424                     struct_span_err!(cx.tcx.sess, sp, E0297,
425                         "refutable pattern in `for` loop binding: \
426                                 `{}` not covered",
427                                 pattern_string)
428                         .span_label(sp, format!("pattern `{}` not covered", pattern_string))
429                         .emit();
430                 },
431                 _ => {
432                     const LIMIT: usize = 3;
433                     let joined_patterns = match witnesses.len() {
434                         0 => bug!(),
435                         1 => format!("`{}`", witnesses[0]),
436                         2...LIMIT => {
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)
440                         },
441                         _ => {
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())
445                         }
446                     };
447
448                     let label_text = match witnesses.len() {
449                         1 => format!("pattern {} not covered", joined_patterns),
450                         _ => format!("patterns {} not covered", joined_patterns)
451                     };
452                     create_e0004(cx.tcx.sess, sp,
453                                  format!("non-exhaustive patterns: {} not covered",
454                                          joined_patterns))
455                         .span_label(sp, label_text)
456                         .emit();
457                 },
458             }
459         }
460         NotUseful => {
461             // This is good, wildcard pattern isn't reachable
462         },
463         _ => bug!()
464     }
465 }
466
467 // Legality of move bindings checking
468 fn check_legality_of_move_bindings(cx: &MatchVisitor,
469                                    has_guard: bool,
470                                    pats: &[P<Pat>]) {
471     let mut by_ref_span = None;
472     for pat in pats {
473         pat.each_binding(|bm, _, span, _path| {
474             if let hir::BindByRef(..) = bm {
475                 by_ref_span = Some(span);
476             }
477         })
478     }
479
480     let check_move = |p: &Pat, sub: Option<&Pat>| {
481         // check legality of moving out of the enum
482
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")
488                 .emit();
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")
493                 .emit();
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")
499                     .emit();
500         }
501     };
502
503     for pat in pats {
504         pat.walk(|p| {
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));
509                 }
510             }
511             true
512         });
513     }
514 }
515
516 /// Ensures that a pattern guard doesn't borrow by mutable reference or
517 /// assign.
518 ///
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), Reveal::UserFacing).enter(|infcx| {
522         let mut checker = MutationChecker {
523             cx: cx,
524         };
525         ExprUseVisitor::new(&mut checker, cx.region_maps, &infcx).walk_expr(guard);
526     });
527 }
528
529 struct MutationChecker<'a, 'gcx: 'a> {
530     cx: &'a MatchVisitor<'a, 'gcx>,
531 }
532
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) {}
537     fn borrow(&mut self,
538               _: ast::NodeId,
539               span: Span,
540               _: cmt,
541               _: ty::Region<'tcx>,
542               kind:ty:: BorrowKind,
543               _: LoanCause) {
544         match kind {
545             ty::MutBorrow => {
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")
549                     .emit();
550             }
551             ty::ImmBorrow | ty::UniqueImmBorrow => {}
552         }
553     }
554     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
555     fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
556         match mode {
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")
560                     .emit();
561             }
562             MutateMode::Init => {}
563         }
564     }
565 }
566
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
569 /// #14587.)
570 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
571     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
572 }
573
574 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
575     cx: &'a MatchVisitor<'b, 'tcx>,
576     bindings_allowed: bool
577 }
578
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
582     }
583
584     fn visit_pat(&mut self, pat: &Pat) {
585         match pat.node {
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 `@`")
591                         .emit();
592                 }
593
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;
599                 }
600             }
601             _ => intravisit::walk_pat(self, pat),
602         }
603     }
604 }