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