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