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, TypeVisitable};
9 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
10 use rustc_trait_selection::traits::{
11 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
14 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15 #[instrument(skip(self), level = "debug")]
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,
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);
30 // If there are no arms, that is a diverging match; a special case.
32 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
33 return tcx.types.never;
36 self.warn_arms_when_scrutinee_diverges(arms);
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);
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);
44 self.check_pat_top(&arm.pat, scrutinee_ty, Some(scrut_span), true);
47 // Now typecheck the blocks.
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
56 let mut all_arms_diverge = Diverges::WarnedAlways;
58 let expected = orig_expected.adjust_for_branches(self);
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
68 Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety,
69 _ => self.next_ty_var(TypeVariableOrigin {
70 kind: TypeVariableOriginKind::MiscVariable,
74 CoerceMany::with_coercion_sites(coerce_first, arms)
77 let mut other_arms = vec![]; // Used only for diagnostics.
78 let mut prior_arm = None;
80 if let Some(g) = &arm.guard {
81 self.diverges.set(Diverges::Maybe);
83 hir::Guard::If(e) => {
84 self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {});
86 hir::Guard::IfLet(l) => {
87 self.check_expr_let(l);
92 self.diverges.set(Diverges::Maybe);
94 let arm_ty = self.check_expr_with_expectation(&arm.body, expected);
95 all_arms_diverge &= self.diverges.get();
97 let opt_suggest_box_span = self.opt_suggest_box_span(arm_ty, orig_expected);
99 let (arm_block_id, arm_span) = if let hir::ExprKind::Block(blk, _) = arm.body.kind {
100 (Some(blk.hir_id), self.find_block_span(blk))
102 (None, arm.body.span)
105 let (span, code) = match prior_arm {
106 // The reason for the first arm to fail is not that the match arms diverge,
107 // but rather that there's a prior obligation that doesn't hold.
108 None => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)),
109 Some((prior_arm_block_id, prior_arm_ty, prior_arm_span)) => (
111 ObligationCauseCode::MatchExpressionArm(Box::new(MatchExpressionArmCause {
118 scrut_span: scrut.span,
120 prior_arms: other_arms.clone(),
121 scrut_hir_id: scrut.hir_id,
122 opt_suggest_box_span,
126 let cause = self.cause(span, code);
128 // This is the moral equivalent of `coercion.coerce(self, cause, arm.body, arm_ty)`.
129 // We use it this way to be able to expand on the potential error and detect when a
130 // `match` tail statement could be a tail expression instead. If so, we suggest
131 // removing the stray semicolon.
132 coercion.coerce_inner(
138 let Some(ret) = self.ret_type_span else {
141 let Expectation::IsLast(stmt) = orig_expected else {
144 let can_coerce_to_return_ty = match self.ret_coercion.as_ref() {
145 Some(ret_coercion) if self.in_tail_expr => {
146 let ret_ty = ret_coercion.borrow().expected_ty();
147 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
148 self.can_coerce(arm_ty, ret_ty)
149 && prior_arm.map_or(true, |(_, t, _)| self.can_coerce(t, ret_ty))
150 // The match arms need to unify for the case of `impl Trait`.
151 && !matches!(ret_ty.kind(), ty::Opaque(..))
155 if !can_coerce_to_return_ty {
159 let semi_span = expr.span.shrink_to_hi().with_hi(stmt.hi());
160 let mut ret_span: MultiSpan = semi_span.into();
161 ret_span.push_span_label(
163 "this could be implicitly returned but it is a statement, not a \
167 .push_span_label(ret, "the `match` arms can conform to this return type");
168 ret_span.push_span_label(
170 "the `match` is a statement because of this semicolon, consider \
175 "you might have meant to return the `match` expression",
177 err.tool_only_span_suggestion(
179 "remove this semicolon",
181 Applicability::MaybeIncorrect,
187 other_arms.push(arm_span);
188 if other_arms.len() > 5 {
189 other_arms.remove(0);
192 prior_arm = Some((arm_block_id, arm_ty, arm_span));
195 // If all of the arms in the `match` diverge,
196 // and we're dealing with an actual `match` block
197 // (as opposed to a `match` desugared from something else'),
198 // we can emit a better note. Rather than pointing
199 // at a diverging expression in an arbitrary arm,
200 // we can point at the entire `match` expression
201 if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
202 all_arms_diverge = Diverges::Always {
205 "any code following this `match` expression is unreachable, as all arms diverge",
210 // We won't diverge unless the scrutinee or all arms diverge.
211 self.diverges.set(scrut_diverges | all_arms_diverge);
213 let match_ty = coercion.complete(self);
218 /// When the previously checked expression (the scrutinee) diverges,
219 /// warn the user about the match arms being unreachable.
220 fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [hir::Arm<'tcx>]) {
222 self.warn_if_unreachable(arm.body.hir_id, arm.body.span, "arm");
226 /// Handle the fallback arm of a desugared if(-let) like a missing else.
228 /// Returns `true` if there was an error forcing the coercion to the `()` type.
229 pub(super) fn if_fallback_coercion<T>(
232 then_expr: &'tcx hir::Expr<'tcx>,
233 coercion: &mut CoerceMany<'tcx, '_, T>,
238 // If this `if` expr is the parent's function return expr,
239 // the cause of the type coercion is the return type, point at it. (#25228)
240 let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
241 let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
242 let mut error = false;
243 coercion.coerce_forced_unit(
247 if let Some((span, msg)) = &ret_reason {
248 err.span_label(*span, msg);
249 } else if let ExprKind::Block(block, _) = &then_expr.kind
250 && let Some(expr) = &block.expr
252 err.span_label(expr.span, "found here");
254 err.note("`if` expressions without `else` evaluate to `()`");
255 err.help("consider adding an `else` block that evaluates to the expected type");
258 ret_reason.is_none(),
263 fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, sp: Span) -> Option<(Span, String)> {
265 let rslt = self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(hir_id));
266 self.tcx.hir().get(rslt)
268 if let hir::Node::Block(block) = node {
269 // check that the body's parent is an fn
273 .get(self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(block.hir_id)));
274 if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
275 (&block.expr, parent)
277 // check that the `if` expr without `else` is the fn body's expr
279 return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
280 let span = fn_decl.output.span();
281 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
282 Some((span, format!("expected `{snippet}` because of this return type")))
287 if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node {
288 return Some((pat.span, "expected because of this assignment".to_string()));
293 pub(crate) fn if_cause(
297 then_expr: &'tcx hir::Expr<'tcx>,
298 else_expr: &'tcx hir::Expr<'tcx>,
301 opt_suggest_box_span: Option<Span>,
302 ) -> ObligationCause<'tcx> {
303 let mut outer_span = if self.tcx.sess.source_map().is_multiline(span) {
304 // The `if`/`else` isn't in one line in the output, include some context to make it
305 // clear it is an if/else expression:
307 // LL | let x = if true {
310 // || ----- expected because of this
313 // || ^^^^^ expected `i32`, found `u32`
315 // ||_____- `if` and `else` have incompatible types
319 // The entire expression is in one line, only point at the arms
321 // LL | let x = if true { 10i32 } else { 10u32 };
322 // | ----- ^^^^^ expected `i32`, found `u32`
324 // | expected because of this
329 let (error_sp, else_id) = if let ExprKind::Block(block, _) = &else_expr.kind {
330 let block = block.innermost_block();
332 // Avoid overlapping spans that aren't as readable:
334 // 2 | let x = if true {
337 // | | - expected because of this
344 // | |______if and else have incompatible types
345 // | expected integer, found `()`
347 // by not pointing at the entire expression:
349 // 2 | let x = if true {
350 // | ------- `if` and `else` have incompatible types
352 // | - expected because of this
357 // | |_____^ expected integer, found `()`
359 if block.expr.is_none() && block.stmts.is_empty()
360 && let Some(outer_span) = &mut outer_span
361 && let Some(cond_span) = cond_span.find_ancestor_inside(*outer_span)
363 *outer_span = outer_span.with_hi(cond_span.hi())
366 (self.find_block_span(block), block.hir_id)
368 (else_expr.span, else_expr.hir_id)
371 let then_id = if let ExprKind::Block(block, _) = &then_expr.kind {
372 let block = block.innermost_block();
373 // Exclude overlapping spans
374 if block.expr.is_none() && block.stmts.is_empty() {
382 // Finally construct the cause:
385 ObligationCauseCode::IfExpression(Box::new(IfExpressionCause {
391 opt_suggest_box_span,
396 pub(super) fn demand_scrutinee_type(
398 scrut: &'tcx hir::Expr<'tcx>,
399 contains_ref_bindings: Option<hir::Mutability>,
402 // Not entirely obvious: if matches may create ref bindings, we want to
403 // use the *precise* type of the scrutinee, *not* some supertype, as
404 // the "scrutinee type" (issue #23116).
406 // arielb1 [writes here in this comment thread][c] that there
407 // is certainly *some* potential danger, e.g., for an example
410 // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
413 // let Foo(x) = f()[0];
416 // Then if the pattern matches by reference, we want to match
417 // `f()[0]` as a lexpr, so we can't allow it to be
418 // coerced. But if the pattern matches by value, `f()[0]` is
419 // still syntactically a lexpr, but we *do* want to allow
422 // However, *likely* we are ok with allowing coercions to
423 // happen if there are no explicit ref mut patterns - all
424 // implicit ref mut patterns must occur behind a reference, so
425 // they will have the "correct" variance and lifetime.
427 // This does mean that the following pattern would be legal:
432 // impl Deref for Foo {
433 // type Target = Bar;
434 // fn deref(&self) -> &Bar { &self.0 }
436 // impl DerefMut for Foo {
437 // fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
439 // fn foo(x: &mut Foo) {
441 // let Bar(z): &mut Bar = x;
444 // assert_eq!(foo.0.0, 42);
448 // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
449 // is problematic as the HIR is being scraped, but ref bindings may be
450 // implicit after #42640. We need to make sure that pat_adjustments
451 // (once introduced) is populated by the time we get here.
454 if let Some(m) = contains_ref_bindings {
455 self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
457 self.check_expr(scrut)
459 // ...but otherwise we want to use any supertype of the
460 // scrutinee. This is sort of a workaround, see note (*) in
461 // `check_pat` for some details.
462 let scrut_ty = self.next_ty_var(TypeVariableOrigin {
463 kind: TypeVariableOriginKind::TypeInference,
466 self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
471 // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait`
472 // we check if the different arms would work with boxed trait objects instead and
473 // provide a structured suggestion in that case.
474 pub(crate) fn opt_suggest_box_span(
477 orig_expected: Expectation<'tcx>,
479 match orig_expected {
480 Expectation::ExpectHasType(expected)
482 && self.ret_coercion.as_ref()?.borrow().merged_ty().has_opaque_types()
483 && self.can_coerce(outer_ty, expected) =>
485 let obligations = self.fulfillment_cx.borrow().pending_obligations();
486 let mut suggest_box = !obligations.is_empty();
487 for o in obligations {
488 match o.predicate.kind().skip_binder() {
489 ty::PredicateKind::Trait(t) => {
491 ty::Binder::dummy(ty::PredicateKind::Trait(ty::TraitPredicate {
492 trait_ref: ty::TraitRef {
494 substs: self.tcx.mk_substs_trait(outer_ty, &[]),
496 constness: t.constness,
497 polarity: t.polarity,
499 let obl = Obligation::new(
502 pred.to_predicate(self.tcx),
504 suggest_box &= self.predicate_must_hold_modulo_regions(&obl);
506 // We've encountered some obligation that didn't hold, so the
507 // return expression can't just be boxed. We don't need to
508 // evaluate the rest of the obligations.
515 // If all the obligations hold (or there are no obligations) the tail expression
516 // we can suggest to return a boxed trait object instead of an opaque type.
517 if suggest_box { self.ret_type_span } else { None }
524 fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
525 arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max_by_key(|m| match *m {
526 hir::Mutability::Mut => 1,
527 hir::Mutability::Not => 0,