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