]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/_match.rs
Rollup merge of #106453 - coastalwhite:master, r=GuillaumeGomez
[rust.git] / compiler / rustc_hir_typeck / src / _match.rs
1 use crate::coercion::{AsCoercionSite, CoerceMany};
2 use crate::{Diverges, Expectation, FnCtxt, Needs};
3 use rustc_errors::{Applicability, Diagnostic, 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, 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", ret)]
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                     self.suggest_removing_semicolon_for_coerce(
141                         err,
142                         expr,
143                         orig_expected,
144                         arm_ty,
145                         prior_arm,
146                     )
147                 }),
148                 false,
149             );
150
151             other_arms.push(arm_span);
152             if other_arms.len() > 5 {
153                 other_arms.remove(0);
154             }
155
156             prior_arm = Some((arm_block_id, arm_ty, arm_span));
157         }
158
159         // If all of the arms in the `match` diverge,
160         // and we're dealing with an actual `match` block
161         // (as opposed to a `match` desugared from something else'),
162         // we can emit a better note. Rather than pointing
163         // at a diverging expression in an arbitrary arm,
164         // we can point at the entire `match` expression
165         if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
166             all_arms_diverge = Diverges::Always {
167                 span: expr.span,
168                 custom_note: Some(
169                     "any code following this `match` expression is unreachable, as all arms diverge",
170                 ),
171             };
172         }
173
174         // We won't diverge unless the scrutinee or all arms diverge.
175         self.diverges.set(scrut_diverges | all_arms_diverge);
176
177         coercion.complete(self)
178     }
179
180     fn suggest_removing_semicolon_for_coerce(
181         &self,
182         diag: &mut Diagnostic,
183         expr: &hir::Expr<'tcx>,
184         expectation: Expectation<'tcx>,
185         arm_ty: Ty<'tcx>,
186         prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
187     ) {
188         let hir = self.tcx.hir();
189
190         // First, check that we're actually in the tail of a function.
191         let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Block(block, _), .. }) =
192             hir.get(self.body_id) else { return; };
193         let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. })
194             = block.innermost_block().stmts.last() else {  return; };
195         if last_expr.hir_id != expr.hir_id {
196             return;
197         }
198
199         // Next, make sure that we have no type expectation.
200         let Some(ret) = hir
201             .find_by_def_id(self.body_id.owner.def_id)
202             .and_then(|owner| owner.fn_decl())
203             .map(|decl| decl.output.span()) else { return; };
204         let Expectation::IsLast(stmt) = expectation else {
205             return;
206         };
207
208         let can_coerce_to_return_ty = match self.ret_coercion.as_ref() {
209             Some(ret_coercion) => {
210                 let ret_ty = ret_coercion.borrow().expected_ty();
211                 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
212                 self.can_coerce(arm_ty, ret_ty)
213                     && prior_arm.map_or(true, |(_, ty, _)| self.can_coerce(ty, ret_ty))
214                     // The match arms need to unify for the case of `impl Trait`.
215                     && !matches!(ret_ty.kind(), ty::Alias(ty::Opaque, ..))
216             }
217             _ => false,
218         };
219         if !can_coerce_to_return_ty {
220             return;
221         }
222
223         let semi_span = expr.span.shrink_to_hi().with_hi(stmt.hi());
224         let mut ret_span: MultiSpan = semi_span.into();
225         ret_span.push_span_label(
226             expr.span,
227             "this could be implicitly returned but it is a statement, not a \
228                             tail expression",
229         );
230         ret_span.push_span_label(ret, "the `match` arms can conform to this return type");
231         ret_span.push_span_label(
232             semi_span,
233             "the `match` is a statement because of this semicolon, consider \
234                             removing it",
235         );
236         diag.span_note(ret_span, "you might have meant to return the `match` expression");
237         diag.tool_only_span_suggestion(
238             semi_span,
239             "remove this semicolon",
240             "",
241             Applicability::MaybeIncorrect,
242         );
243     }
244
245     /// When the previously checked expression (the scrutinee) diverges,
246     /// warn the user about the match arms being unreachable.
247     fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [hir::Arm<'tcx>]) {
248         for arm in arms {
249             self.warn_if_unreachable(arm.body.hir_id, arm.body.span, "arm");
250         }
251     }
252
253     /// Handle the fallback arm of a desugared if(-let) like a missing else.
254     ///
255     /// Returns `true` if there was an error forcing the coercion to the `()` type.
256     pub(super) fn if_fallback_coercion<T>(
257         &self,
258         span: Span,
259         then_expr: &'tcx hir::Expr<'tcx>,
260         coercion: &mut CoerceMany<'tcx, '_, T>,
261     ) -> bool
262     where
263         T: AsCoercionSite,
264     {
265         // If this `if` expr is the parent's function return expr,
266         // the cause of the type coercion is the return type, point at it. (#25228)
267         let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
268         let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
269         let mut error = false;
270         coercion.coerce_forced_unit(
271             self,
272             &cause,
273             &mut |err| {
274                 if let Some((span, msg)) = &ret_reason {
275                     err.span_label(*span, msg);
276                 } else if let ExprKind::Block(block, _) = &then_expr.kind
277                     && let Some(expr) = &block.expr
278                 {
279                     err.span_label(expr.span, "found here");
280                 }
281                 err.note("`if` expressions without `else` evaluate to `()`");
282                 err.help("consider adding an `else` block that evaluates to the expected type");
283                 error = true;
284             },
285             false,
286         );
287         error
288     }
289
290     fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, sp: Span) -> Option<(Span, String)> {
291         let node = {
292             let rslt = self.tcx.hir().parent_id(self.tcx.hir().parent_id(hir_id));
293             self.tcx.hir().get(rslt)
294         };
295         if let hir::Node::Block(block) = node {
296             // check that the body's parent is an fn
297             let parent = self.tcx.hir().get_parent(self.tcx.hir().parent_id(block.hir_id));
298             if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
299                 (&block.expr, parent)
300             {
301                 // check that the `if` expr without `else` is the fn body's expr
302                 if expr.span == sp {
303                     return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
304                         let span = fn_decl.output.span();
305                         let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
306                         Some((span, format!("expected `{snippet}` because of this return type")))
307                     });
308                 }
309             }
310         }
311         if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node {
312             return Some((pat.span, "expected because of this assignment".to_string()));
313         }
314         None
315     }
316
317     pub(crate) fn if_cause(
318         &self,
319         span: Span,
320         cond_span: Span,
321         then_expr: &'tcx hir::Expr<'tcx>,
322         else_expr: &'tcx hir::Expr<'tcx>,
323         then_ty: Ty<'tcx>,
324         else_ty: Ty<'tcx>,
325         opt_suggest_box_span: Option<Span>,
326     ) -> ObligationCause<'tcx> {
327         let mut outer_span = if self.tcx.sess.source_map().is_multiline(span) {
328             // The `if`/`else` isn't in one line in the output, include some context to make it
329             // clear it is an if/else expression:
330             // ```
331             // LL |      let x = if true {
332             //    | _____________-
333             // LL ||         10i32
334             //    ||         ----- expected because of this
335             // LL ||     } else {
336             // LL ||         10u32
337             //    ||         ^^^^^ expected `i32`, found `u32`
338             // LL ||     };
339             //    ||_____- `if` and `else` have incompatible types
340             // ```
341             Some(span)
342         } else {
343             // The entire expression is in one line, only point at the arms
344             // ```
345             // LL |     let x = if true { 10i32 } else { 10u32 };
346             //    |                       -----          ^^^^^ expected `i32`, found `u32`
347             //    |                       |
348             //    |                       expected because of this
349             // ```
350             None
351         };
352
353         let (error_sp, else_id) = if let ExprKind::Block(block, _) = &else_expr.kind {
354             let block = block.innermost_block();
355
356             // Avoid overlapping spans that aren't as readable:
357             // ```
358             // 2 |        let x = if true {
359             //   |   _____________-
360             // 3 |  |         3
361             //   |  |         - expected because of this
362             // 4 |  |     } else {
363             //   |  |____________^
364             // 5 | ||
365             // 6 | ||     };
366             //   | ||     ^
367             //   | ||_____|
368             //   | |______if and else have incompatible types
369             //   |        expected integer, found `()`
370             // ```
371             // by not pointing at the entire expression:
372             // ```
373             // 2 |       let x = if true {
374             //   |               ------- `if` and `else` have incompatible types
375             // 3 |           3
376             //   |           - expected because of this
377             // 4 |       } else {
378             //   |  ____________^
379             // 5 | |
380             // 6 | |     };
381             //   | |_____^ expected integer, found `()`
382             // ```
383             if block.expr.is_none() && block.stmts.is_empty()
384                 && let Some(outer_span) = &mut outer_span
385                 && let Some(cond_span) = cond_span.find_ancestor_inside(*outer_span)
386             {
387                 *outer_span = outer_span.with_hi(cond_span.hi())
388             }
389
390             (self.find_block_span(block), block.hir_id)
391         } else {
392             (else_expr.span, else_expr.hir_id)
393         };
394
395         let then_id = if let ExprKind::Block(block, _) = &then_expr.kind {
396             let block = block.innermost_block();
397             // Exclude overlapping spans
398             if block.expr.is_none() && block.stmts.is_empty() {
399                 outer_span = None;
400             }
401             block.hir_id
402         } else {
403             then_expr.hir_id
404         };
405
406         // Finally construct the cause:
407         self.cause(
408             error_sp,
409             ObligationCauseCode::IfExpression(Box::new(IfExpressionCause {
410                 else_id,
411                 then_id,
412                 then_ty,
413                 else_ty,
414                 outer_span,
415                 opt_suggest_box_span,
416             })),
417         )
418     }
419
420     pub(super) fn demand_scrutinee_type(
421         &self,
422         scrut: &'tcx hir::Expr<'tcx>,
423         contains_ref_bindings: Option<hir::Mutability>,
424         no_arms: bool,
425     ) -> Ty<'tcx> {
426         // Not entirely obvious: if matches may create ref bindings, we want to
427         // use the *precise* type of the scrutinee, *not* some supertype, as
428         // the "scrutinee type" (issue #23116).
429         //
430         // arielb1 [writes here in this comment thread][c] that there
431         // is certainly *some* potential danger, e.g., for an example
432         // like:
433         //
434         // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
435         //
436         // ```
437         // let Foo(x) = f()[0];
438         // ```
439         //
440         // Then if the pattern matches by reference, we want to match
441         // `f()[0]` as a lexpr, so we can't allow it to be
442         // coerced. But if the pattern matches by value, `f()[0]` is
443         // still syntactically a lexpr, but we *do* want to allow
444         // coercions.
445         //
446         // However, *likely* we are ok with allowing coercions to
447         // happen if there are no explicit ref mut patterns - all
448         // implicit ref mut patterns must occur behind a reference, so
449         // they will have the "correct" variance and lifetime.
450         //
451         // This does mean that the following pattern would be legal:
452         //
453         // ```
454         // struct Foo(Bar);
455         // struct Bar(u32);
456         // impl Deref for Foo {
457         //     type Target = Bar;
458         //     fn deref(&self) -> &Bar { &self.0 }
459         // }
460         // impl DerefMut for Foo {
461         //     fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
462         // }
463         // fn foo(x: &mut Foo) {
464         //     {
465         //         let Bar(z): &mut Bar = x;
466         //         *z = 42;
467         //     }
468         //     assert_eq!(foo.0.0, 42);
469         // }
470         // ```
471         //
472         // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
473         // is problematic as the HIR is being scraped, but ref bindings may be
474         // implicit after #42640. We need to make sure that pat_adjustments
475         // (once introduced) is populated by the time we get here.
476         //
477         // See #44848.
478         if let Some(m) = contains_ref_bindings {
479             self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
480         } else if no_arms {
481             self.check_expr(scrut)
482         } else {
483             // ...but otherwise we want to use any supertype of the
484             // scrutinee. This is sort of a workaround, see note (*) in
485             // `check_pat` for some details.
486             let scrut_ty = self.next_ty_var(TypeVariableOrigin {
487                 kind: TypeVariableOriginKind::TypeInference,
488                 span: scrut.span,
489             });
490             self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
491             scrut_ty
492         }
493     }
494
495     /// When we have a `match` as a tail expression in a `fn` with a returned `impl Trait`
496     /// we check if the different arms would work with boxed trait objects instead and
497     /// provide a structured suggestion in that case.
498     pub(crate) fn opt_suggest_box_span(
499         &self,
500         first_ty: Ty<'tcx>,
501         second_ty: Ty<'tcx>,
502         orig_expected: Expectation<'tcx>,
503     ) -> Option<Span> {
504         // FIXME(compiler-errors): This really shouldn't need to be done during the
505         // "good" path of typeck, but here we are.
506         match orig_expected {
507             Expectation::ExpectHasType(expected) => {
508                 let TypeVariableOrigin {
509                     span,
510                     kind: TypeVariableOriginKind::OpaqueTypeInference(rpit_def_id),
511                     ..
512                 } = self.type_var_origin(expected)? else { return None; };
513
514                 let sig = self.body_fn_sig()?;
515
516                 let substs = sig.output().walk().find_map(|arg| {
517                     if let ty::GenericArgKind::Type(ty) = arg.unpack()
518                         && let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *ty.kind()
519                         && def_id == rpit_def_id
520                     {
521                         Some(substs)
522                     } else {
523                         None
524                     }
525                 })?;
526
527                 if !self.can_coerce(first_ty, expected) || !self.can_coerce(second_ty, expected) {
528                     return None;
529                 }
530
531                 for ty in [first_ty, second_ty] {
532                     for (pred, _) in self
533                         .tcx
534                         .bound_explicit_item_bounds(rpit_def_id)
535                         .subst_iter_copied(self.tcx, substs)
536                     {
537                         let pred = pred.kind().rebind(match pred.kind().skip_binder() {
538                             ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) => {
539                                 // FIXME(rpitit): This will need to be fixed when we move to associated types
540                                 assert!(matches!(
541                                     *trait_pred.trait_ref.self_ty().kind(),
542                                     ty::Alias(_, ty::AliasTy { def_id, substs, .. })
543                                     if def_id == rpit_def_id && substs == substs
544                                 ));
545                                 ty::PredicateKind::Clause(ty::Clause::Trait(
546                                     trait_pred.with_self_ty(self.tcx, ty),
547                                 ))
548                             }
549                             ty::PredicateKind::Clause(ty::Clause::Projection(mut proj_pred)) => {
550                                 assert!(matches!(
551                                     *proj_pred.projection_ty.self_ty().kind(),
552                                     ty::Alias(_, ty::AliasTy { def_id, substs, .. })
553                                     if def_id == rpit_def_id && substs == substs
554                                 ));
555                                 proj_pred = proj_pred.with_self_ty(self.tcx, ty);
556                                 ty::PredicateKind::Clause(ty::Clause::Projection(proj_pred))
557                             }
558                             _ => continue,
559                         });
560                         if !self.predicate_must_hold_modulo_regions(&Obligation::new(
561                             self.tcx,
562                             ObligationCause::misc(span, self.body_id),
563                             self.param_env,
564                             pred,
565                         )) {
566                             return None;
567                         }
568                     }
569                 }
570
571                 Some(span)
572             }
573             _ => None,
574         }
575     }
576 }
577
578 fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
579     arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max()
580 }