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