]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/_match.rs
Rollup merge of #74213 - pickfire:patch-1, r=jonas-schievink
[rust.git] / src / librustc_typeck / check / _match.rs
1 use crate::check::coercion::CoerceMany;
2 use crate::check::{Diverges, Expectation, FnCtxt, Needs};
3 use rustc_hir as hir;
4 use rustc_hir::ExprKind;
5 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
6 use rustc_middle::ty::Ty;
7 use rustc_span::Span;
8 use rustc_trait_selection::traits::ObligationCauseCode;
9 use rustc_trait_selection::traits::{IfExpressionCause, MatchExpressionArmCause, ObligationCause};
10
11 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12     pub fn check_match(
13         &self,
14         expr: &'tcx hir::Expr<'tcx>,
15         scrut: &'tcx hir::Expr<'tcx>,
16         arms: &'tcx [hir::Arm<'tcx>],
17         expected: Expectation<'tcx>,
18         match_src: hir::MatchSource,
19     ) -> Ty<'tcx> {
20         let tcx = self.tcx;
21
22         use hir::MatchSource::*;
23         let (source_if, if_no_else, force_scrutinee_bool) = match match_src {
24             IfDesugar { contains_else_clause } => (true, !contains_else_clause, true),
25             IfLetDesugar { contains_else_clause } => (true, !contains_else_clause, false),
26             WhileDesugar => (false, false, true),
27             _ => (false, false, false),
28         };
29
30         // Type check the descriminant and get its type.
31         let scrut_ty = if force_scrutinee_bool {
32             // Here we want to ensure:
33             //
34             // 1. That default match bindings are *not* accepted in the condition of an
35             //    `if` expression. E.g. given `fn foo() -> &bool;` we reject `if foo() { .. }`.
36             //
37             // 2. By expecting `bool` for `expr` we get nice diagnostics for e.g. `if x = y { .. }`.
38             //
39             // FIXME(60707): Consider removing hack with principled solution.
40             self.check_expr_has_type_or_error(scrut, self.tcx.types.bool, |_| {})
41         } else {
42             self.demand_scrutinee_type(arms, scrut)
43         };
44
45         // If there are no arms, that is a diverging match; a special case.
46         if arms.is_empty() {
47             self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
48             return tcx.types.never;
49         }
50
51         self.warn_arms_when_scrutinee_diverges(arms, match_src);
52
53         // Otherwise, we have to union together the types that the arms produce and so forth.
54         let scrut_diverges = self.diverges.replace(Diverges::Maybe);
55
56         // #55810: Type check patterns first so we get types for all bindings.
57         for arm in arms {
58             self.check_pat_top(&arm.pat, scrut_ty, Some(scrut.span), true);
59         }
60
61         // Now typecheck the blocks.
62         //
63         // The result of the match is the common supertype of all the
64         // arms. Start out the value as bottom, since it's the, well,
65         // bottom the type lattice, and we'll be moving up the lattice as
66         // we process each arm. (Note that any match with 0 arms is matching
67         // on any empty type and is therefore unreachable; should the flow
68         // of execution reach it, we will panic, so bottom is an appropriate
69         // type in that case)
70         let mut all_arms_diverge = Diverges::WarnedAlways;
71
72         let expected = expected.adjust_for_branches(self);
73
74         let mut coercion = {
75             let coerce_first = match expected {
76                 // We don't coerce to `()` so that if the match expression is a
77                 // statement it's branches can have any consistent type. That allows
78                 // us to give better error messages (pointing to a usually better
79                 // arm for inconsistent arms or to the whole match when a `()` type
80                 // is required).
81                 Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety,
82                 _ => self.next_ty_var(TypeVariableOrigin {
83                     kind: TypeVariableOriginKind::MiscVariable,
84                     span: expr.span,
85                 }),
86             };
87             CoerceMany::with_coercion_sites(coerce_first, arms)
88         };
89
90         let mut other_arms = vec![]; // Used only for diagnostics.
91         let mut prior_arm_ty = None;
92         for (i, arm) in arms.iter().enumerate() {
93             if let Some(g) = &arm.guard {
94                 self.diverges.set(Diverges::Maybe);
95                 match g {
96                     hir::Guard::If(e) => {
97                         self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {})
98                     }
99                 };
100             }
101
102             self.diverges.set(Diverges::Maybe);
103             let arm_ty = if source_if
104                 && if_no_else
105                 && i != 0
106                 && self.if_fallback_coercion(expr.span, &arms[0].body, &mut coercion)
107             {
108                 tcx.ty_error()
109             } else {
110                 // Only call this if this is not an `if` expr with an expected type and no `else`
111                 // clause to avoid duplicated type errors. (#60254)
112                 self.check_expr_with_expectation(&arm.body, expected)
113             };
114             all_arms_diverge &= self.diverges.get();
115             if source_if {
116                 let then_expr = &arms[0].body;
117                 match (i, if_no_else) {
118                     (0, _) => coercion.coerce(self, &self.misc(expr.span), &arm.body, arm_ty),
119                     (_, true) => {} // Handled above to avoid duplicated type errors (#60254).
120                     (_, _) => {
121                         let then_ty = prior_arm_ty.unwrap();
122                         let cause = self.if_cause(expr.span, then_expr, &arm.body, then_ty, arm_ty);
123                         coercion.coerce(self, &cause, &arm.body, arm_ty);
124                     }
125                 }
126             } else {
127                 let arm_span = if let hir::ExprKind::Block(blk, _) = &arm.body.kind {
128                     // Point at the block expr instead of the entire block
129                     blk.expr.as_ref().map(|e| e.span).unwrap_or(arm.body.span)
130                 } else {
131                     arm.body.span
132                 };
133                 let (span, code) = match i {
134                     // The reason for the first arm to fail is not that the match arms diverge,
135                     // but rather that there's a prior obligation that doesn't hold.
136                     0 => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)),
137                     _ => (
138                         expr.span,
139                         ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
140                             arm_span,
141                             source: match_src,
142                             prior_arms: other_arms.clone(),
143                             last_ty: prior_arm_ty.unwrap(),
144                             scrut_hir_id: scrut.hir_id,
145                         }),
146                     ),
147                 };
148                 let cause = self.cause(span, code);
149                 coercion.coerce(self, &cause, &arm.body, arm_ty);
150                 other_arms.push(arm_span);
151                 if other_arms.len() > 5 {
152                     other_arms.remove(0);
153                 }
154             }
155             prior_arm_ty = Some(arm_ty);
156         }
157
158         // If all of the arms in the `match` diverge,
159         // and we're dealing with an actual `match` block
160         // (as opposed to a `match` desugared from something else'),
161         // we can emit a better note. Rather than pointing
162         // at a diverging expression in an arbitrary arm,
163         // we can point at the entire `match` expression
164         if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
165             all_arms_diverge = Diverges::Always {
166                 span: expr.span,
167                 custom_note: Some(
168                     "any code following this `match` expression is unreachable, as all arms diverge",
169                 ),
170             };
171         }
172
173         // We won't diverge unless the scrutinee or all arms diverge.
174         self.diverges.set(scrut_diverges | all_arms_diverge);
175
176         coercion.complete(self)
177     }
178
179     /// When the previously checked expression (the scrutinee) diverges,
180     /// warn the user about the match arms being unreachable.
181     fn warn_arms_when_scrutinee_diverges(
182         &self,
183         arms: &'tcx [hir::Arm<'tcx>],
184         source: hir::MatchSource,
185     ) {
186         use hir::MatchSource::*;
187         let msg = match source {
188             IfDesugar { .. } | IfLetDesugar { .. } => "block in `if` expression",
189             WhileDesugar { .. } | WhileLetDesugar { .. } => "block in `while` expression",
190             _ => "arm",
191         };
192         for arm in arms {
193             self.warn_if_unreachable(arm.body.hir_id, arm.body.span, msg);
194         }
195     }
196
197     /// Handle the fallback arm of a desugared if(-let) like a missing else.
198     ///
199     /// Returns `true` if there was an error forcing the coercion to the `()` type.
200     fn if_fallback_coercion(
201         &self,
202         span: Span,
203         then_expr: &'tcx hir::Expr<'tcx>,
204         coercion: &mut CoerceMany<'tcx, '_, rustc_hir::Arm<'tcx>>,
205     ) -> bool {
206         // If this `if` expr is the parent's function return expr,
207         // the cause of the type coercion is the return type, point at it. (#25228)
208         let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
209         let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
210         let mut error = false;
211         coercion.coerce_forced_unit(
212             self,
213             &cause,
214             &mut |err| {
215                 if let Some((span, msg)) = &ret_reason {
216                     err.span_label(*span, msg.as_str());
217                 } else if let ExprKind::Block(block, _) = &then_expr.kind {
218                     if let Some(expr) = &block.expr {
219                         err.span_label(expr.span, "found here".to_string());
220                     }
221                 }
222                 err.note("`if` expressions without `else` evaluate to `()`");
223                 err.help("consider adding an `else` block that evaluates to the expected type");
224                 error = true;
225             },
226             ret_reason.is_none(),
227         );
228         error
229     }
230
231     fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, span: Span) -> Option<(Span, String)> {
232         use hir::Node::{Block, Item, Local};
233
234         let hir = self.tcx.hir();
235         let arm_id = hir.get_parent_node(hir_id);
236         let match_id = hir.get_parent_node(arm_id);
237         let containing_id = hir.get_parent_node(match_id);
238
239         let node = hir.get(containing_id);
240         if let Block(block) = node {
241             // check that the body's parent is an fn
242             let parent = hir.get(hir.get_parent_node(hir.get_parent_node(block.hir_id)));
243             if let (Some(expr), Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
244                 (&block.expr, parent)
245             {
246                 // check that the `if` expr without `else` is the fn body's expr
247                 if expr.span == span {
248                     return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
249                         let span = fn_decl.output.span();
250                         let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
251                         Some((span, format!("expected `{}` because of this return type", snippet)))
252                     });
253                 }
254             }
255         }
256         if let Local(hir::Local { ty: Some(_), pat, .. }) = node {
257             return Some((pat.span, "expected because of this assignment".to_string()));
258         }
259         None
260     }
261
262     fn if_cause(
263         &self,
264         span: Span,
265         then_expr: &'tcx hir::Expr<'tcx>,
266         else_expr: &'tcx hir::Expr<'tcx>,
267         then_ty: Ty<'tcx>,
268         else_ty: Ty<'tcx>,
269     ) -> ObligationCause<'tcx> {
270         let mut outer_sp = if self.tcx.sess.source_map().is_multiline(span) {
271             // The `if`/`else` isn't in one line in the output, include some context to make it
272             // clear it is an if/else expression:
273             // ```
274             // LL |      let x = if true {
275             //    | _____________-
276             // LL ||         10i32
277             //    ||         ----- expected because of this
278             // LL ||     } else {
279             // LL ||         10u32
280             //    ||         ^^^^^ expected `i32`, found `u32`
281             // LL ||     };
282             //    ||_____- `if` and `else` have incompatible types
283             // ```
284             Some(span)
285         } else {
286             // The entire expression is in one line, only point at the arms
287             // ```
288             // LL |     let x = if true { 10i32 } else { 10u32 };
289             //    |                       -----          ^^^^^ expected `i32`, found `u32`
290             //    |                       |
291             //    |                       expected because of this
292             // ```
293             None
294         };
295
296         let mut remove_semicolon = None;
297         let error_sp = if let ExprKind::Block(block, _) = &else_expr.kind {
298             if let Some(expr) = &block.expr {
299                 expr.span
300             } else if let Some(stmt) = block.stmts.last() {
301                 // possibly incorrect trailing `;` in the else arm
302                 remove_semicolon = self.could_remove_semicolon(block, then_ty);
303                 stmt.span
304             } else {
305                 // empty block; point at its entirety
306                 // Avoid overlapping spans that aren't as readable:
307                 // ```
308                 // 2 |        let x = if true {
309                 //   |   _____________-
310                 // 3 |  |         3
311                 //   |  |         - expected because of this
312                 // 4 |  |     } else {
313                 //   |  |____________^
314                 // 5 | ||
315                 // 6 | ||     };
316                 //   | ||     ^
317                 //   | ||_____|
318                 //   | |______if and else have incompatible types
319                 //   |        expected integer, found `()`
320                 // ```
321                 // by not pointing at the entire expression:
322                 // ```
323                 // 2 |       let x = if true {
324                 //   |               ------- `if` and `else` have incompatible types
325                 // 3 |           3
326                 //   |           - expected because of this
327                 // 4 |       } else {
328                 //   |  ____________^
329                 // 5 | |
330                 // 6 | |     };
331                 //   | |_____^ expected integer, found `()`
332                 // ```
333                 if outer_sp.is_some() {
334                     outer_sp = Some(self.tcx.sess.source_map().guess_head_span(span));
335                 }
336                 else_expr.span
337             }
338         } else {
339             // shouldn't happen unless the parser has done something weird
340             else_expr.span
341         };
342
343         // Compute `Span` of `then` part of `if`-expression.
344         let then_sp = if let ExprKind::Block(block, _) = &then_expr.kind {
345             if let Some(expr) = &block.expr {
346                 expr.span
347             } else if let Some(stmt) = block.stmts.last() {
348                 // possibly incorrect trailing `;` in the else arm
349                 remove_semicolon = remove_semicolon.or(self.could_remove_semicolon(block, else_ty));
350                 stmt.span
351             } else {
352                 // empty block; point at its entirety
353                 outer_sp = None; // same as in `error_sp`; cleanup output
354                 then_expr.span
355             }
356         } else {
357             // shouldn't happen unless the parser has done something weird
358             then_expr.span
359         };
360
361         // Finally construct the cause:
362         self.cause(
363             error_sp,
364             ObligationCauseCode::IfExpression(box IfExpressionCause {
365                 then: then_sp,
366                 outer: outer_sp,
367                 semicolon: remove_semicolon,
368             }),
369         )
370     }
371
372     fn demand_scrutinee_type(
373         &self,
374         arms: &'tcx [hir::Arm<'tcx>],
375         scrut: &'tcx hir::Expr<'tcx>,
376     ) -> Ty<'tcx> {
377         // Not entirely obvious: if matches may create ref bindings, we want to
378         // use the *precise* type of the scrutinee, *not* some supertype, as
379         // the "scrutinee type" (issue #23116).
380         //
381         // arielb1 [writes here in this comment thread][c] that there
382         // is certainly *some* potential danger, e.g., for an example
383         // like:
384         //
385         // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
386         //
387         // ```
388         // let Foo(x) = f()[0];
389         // ```
390         //
391         // Then if the pattern matches by reference, we want to match
392         // `f()[0]` as a lexpr, so we can't allow it to be
393         // coerced. But if the pattern matches by value, `f()[0]` is
394         // still syntactically a lexpr, but we *do* want to allow
395         // coercions.
396         //
397         // However, *likely* we are ok with allowing coercions to
398         // happen if there are no explicit ref mut patterns - all
399         // implicit ref mut patterns must occur behind a reference, so
400         // they will have the "correct" variance and lifetime.
401         //
402         // This does mean that the following pattern would be legal:
403         //
404         // ```
405         // struct Foo(Bar);
406         // struct Bar(u32);
407         // impl Deref for Foo {
408         //     type Target = Bar;
409         //     fn deref(&self) -> &Bar { &self.0 }
410         // }
411         // impl DerefMut for Foo {
412         //     fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
413         // }
414         // fn foo(x: &mut Foo) {
415         //     {
416         //         let Bar(z): &mut Bar = x;
417         //         *z = 42;
418         //     }
419         //     assert_eq!(foo.0.0, 42);
420         // }
421         // ```
422         //
423         // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
424         // is problematic as the HIR is being scraped, but ref bindings may be
425         // implicit after #42640. We need to make sure that pat_adjustments
426         // (once introduced) is populated by the time we get here.
427         //
428         // See #44848.
429         let contains_ref_bindings = arms
430             .iter()
431             .filter_map(|a| a.pat.contains_explicit_ref_binding())
432             .max_by_key(|m| match *m {
433                 hir::Mutability::Mut => 1,
434                 hir::Mutability::Not => 0,
435             });
436
437         if let Some(m) = contains_ref_bindings {
438             self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
439         } else if arms.is_empty() {
440             self.check_expr(scrut)
441         } else {
442             // ...but otherwise we want to use any supertype of the
443             // scrutinee. This is sort of a workaround, see note (*) in
444             // `check_pat` for some details.
445             let scrut_ty = self.next_ty_var(TypeVariableOrigin {
446                 kind: TypeVariableOriginKind::TypeInference,
447                 span: scrut.span,
448             });
449             self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
450             scrut_ty
451         }
452     }
453 }