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