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