1 use crate::check::coercion::{AsCoercionSite, CoerceMany};
2 use crate::check::{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, ToPredicate, Ty, TypeFoldable};
9 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
10 use rustc_trait_selection::traits::{
11 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
12 StatementAsExpression,
15 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
16 #[instrument(skip(self), level = "debug")]
19 expr: &'tcx hir::Expr<'tcx>,
20 scrut: &'tcx hir::Expr<'tcx>,
21 arms: &'tcx [hir::Arm<'tcx>],
22 orig_expected: Expectation<'tcx>,
23 match_src: hir::MatchSource,
27 let acrb = arms_contain_ref_bindings(arms);
28 let scrutinee_ty = self.demand_scrutinee_type(scrut, acrb, arms.is_empty());
29 debug!(?scrutinee_ty);
31 // If there are no arms, that is a diverging match; a special case.
33 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
34 return tcx.types.never;
37 self.warn_arms_when_scrutinee_diverges(arms);
39 // Otherwise, we have to union together the types that the arms produce and so forth.
40 let scrut_diverges = self.diverges.replace(Diverges::Maybe);
42 // #55810: Type check patterns first so we get types for all bindings.
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);
61 let coerce_first = match expected {
62 // We don't coerce to `()` so that if the match expression is a
63 // statement it's branches can have any consistent type. That allows
64 // us to give better error messages (pointing to a usually better
65 // arm for inconsistent arms or to the whole match when a `()` type
67 Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety,
68 _ => self.next_ty_var(TypeVariableOrigin {
69 kind: TypeVariableOriginKind::MiscVariable,
73 CoerceMany::with_coercion_sites(coerce_first, arms)
76 let mut other_arms = vec![]; // Used only for diagnostics.
77 let mut prior_arm_ty = None;
78 for (i, arm) in arms.iter().enumerate() {
79 if let Some(g) = &arm.guard {
80 self.diverges.set(Diverges::Maybe);
82 hir::Guard::If(e) => {
83 self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {});
85 hir::Guard::IfLet(pat, e) => {
86 let scrutinee_ty = self.demand_scrutinee_type(
88 pat.contains_explicit_ref_binding(),
91 self.check_pat_top(&pat, scrutinee_ty, None, true);
96 self.diverges.set(Diverges::Maybe);
98 let arm_ty = self.check_expr_with_expectation(&arm.body, expected);
99 all_arms_diverge &= self.diverges.get();
101 let opt_suggest_box_span = self.opt_suggest_box_span(arm_ty, orig_expected);
103 let (arm_span, semi_span) =
104 self.get_appropriate_arm_semicolon_removal_span(&arms, i, prior_arm_ty, arm_ty);
105 let (span, code) = match i {
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 0 => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)),
111 ObligationCauseCode::MatchExpressionArm(Box::new(MatchExpressionArmCause {
113 scrut_span: scrut.span,
116 prior_arms: other_arms.clone(),
117 last_ty: prior_arm_ty.unwrap(),
118 scrut_hir_id: scrut.hir_id,
119 opt_suggest_box_span,
123 let cause = self.cause(span, code);
125 // This is the moral equivalent of `coercion.coerce(self, cause, arm.body, arm_ty)`.
126 // We use it this way to be able to expand on the potential error and detect when a
127 // `match` tail statement could be a tail expression instead. If so, we suggest
128 // removing the stray semicolon.
129 coercion.coerce_inner(
134 Some(&mut |err: &mut Diagnostic| {
135 let can_coerce_to_return_ty = match self.ret_coercion.as_ref() {
136 Some(ret_coercion) if self.in_tail_expr => {
137 let ret_ty = ret_coercion.borrow().expected_ty();
138 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
139 self.can_coerce(arm_ty, ret_ty)
140 && prior_arm_ty.map_or(true, |t| self.can_coerce(t, ret_ty))
141 // The match arms need to unify for the case of `impl Trait`.
142 && !matches!(ret_ty.kind(), ty::Opaque(..))
146 if let (Expectation::IsLast(stmt), Some(ret), true) =
147 (orig_expected, self.ret_type_span, can_coerce_to_return_ty)
149 let semi_span = expr.span.shrink_to_hi().with_hi(stmt.hi());
150 let mut ret_span: MultiSpan = semi_span.into();
151 ret_span.push_span_label(
153 "this could be implicitly returned but it is a statement, not a \
157 ret_span.push_span_label(
159 "the `match` arms can conform to this return type".to_owned(),
161 ret_span.push_span_label(
163 "the `match` is a statement because of this semicolon, consider \
169 "you might have meant to return the `match` expression",
171 err.tool_only_span_suggestion(
173 "remove this semicolon",
175 Applicability::MaybeIncorrect,
182 other_arms.push(arm_span);
183 if other_arms.len() > 5 {
184 other_arms.remove(0);
186 prior_arm_ty = Some(arm_ty);
189 // If all of the arms in the `match` diverge,
190 // and we're dealing with an actual `match` block
191 // (as opposed to a `match` desugared from something else'),
192 // we can emit a better note. Rather than pointing
193 // at a diverging expression in an arbitrary arm,
194 // we can point at the entire `match` expression
195 if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
196 all_arms_diverge = Diverges::Always {
199 "any code following this `match` expression is unreachable, as all arms diverge",
204 // We won't diverge unless the scrutinee or all arms diverge.
205 self.diverges.set(scrut_diverges | all_arms_diverge);
207 coercion.complete(self)
210 fn get_appropriate_arm_semicolon_removal_span(
212 arms: &'tcx [hir::Arm<'tcx>],
214 prior_arm_ty: Option<Ty<'tcx>>,
216 ) -> (Span, Option<(Span, StatementAsExpression)>) {
218 let (arm_span, mut semi_span) = if let hir::ExprKind::Block(blk, _) = &arm.body.kind {
219 self.find_block_span(blk, prior_arm_ty)
221 (arm.body.span, None)
223 if semi_span.is_none() && i > 0 {
224 if let hir::ExprKind::Block(blk, _) = &arms[i - 1].body.kind {
225 let (_, semi_span_prev) = self.find_block_span(blk, Some(arm_ty));
226 semi_span = semi_span_prev;
229 (arm_span, semi_span)
232 /// When the previously checked expression (the scrutinee) diverges,
233 /// warn the user about the match arms being unreachable.
234 fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [hir::Arm<'tcx>]) {
236 self.warn_if_unreachable(arm.body.hir_id, arm.body.span, "arm");
240 /// Handle the fallback arm of a desugared if(-let) like a missing else.
242 /// Returns `true` if there was an error forcing the coercion to the `()` type.
243 pub(super) fn if_fallback_coercion<T>(
246 then_expr: &'tcx hir::Expr<'tcx>,
247 coercion: &mut CoerceMany<'tcx, '_, T>,
252 // If this `if` expr is the parent's function return expr,
253 // the cause of the type coercion is the return type, point at it. (#25228)
254 let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
255 let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
256 let mut error = false;
257 coercion.coerce_forced_unit(
261 if let Some((span, msg)) = &ret_reason {
262 err.span_label(*span, msg.as_str());
263 } else if let ExprKind::Block(block, _) = &then_expr.kind
264 && let Some(expr) = &block.expr
266 err.span_label(expr.span, "found here".to_string());
268 err.note("`if` expressions without `else` evaluate to `()`");
269 err.help("consider adding an `else` block that evaluates to the expected type");
272 ret_reason.is_none(),
277 fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, sp: Span) -> Option<(Span, String)> {
279 let rslt = self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(hir_id));
280 self.tcx.hir().get(rslt)
282 if let hir::Node::Block(block) = node {
283 // check that the body's parent is an fn
287 .get(self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(block.hir_id)));
288 if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
289 (&block.expr, parent)
291 // check that the `if` expr without `else` is the fn body's expr
293 return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
294 let span = fn_decl.output.span();
295 let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
296 Some((span, format!("expected `{snippet}` because of this return type")))
301 if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node {
302 return Some((pat.span, "expected because of this assignment".to_string()));
307 pub(crate) fn if_cause(
310 then_expr: &'tcx hir::Expr<'tcx>,
311 else_expr: &'tcx hir::Expr<'tcx>,
314 opt_suggest_box_span: Option<Span>,
315 ) -> ObligationCause<'tcx> {
316 let mut outer_sp = if self.tcx.sess.source_map().is_multiline(span) {
317 // The `if`/`else` isn't in one line in the output, include some context to make it
318 // clear it is an if/else expression:
320 // LL | let x = if true {
323 // || ----- expected because of this
326 // || ^^^^^ expected `i32`, found `u32`
328 // ||_____- `if` and `else` have incompatible types
332 // The entire expression is in one line, only point at the arms
334 // LL | let x = if true { 10i32 } else { 10u32 };
335 // | ----- ^^^^^ expected `i32`, found `u32`
337 // | expected because of this
342 let mut remove_semicolon = None;
343 let error_sp = if let ExprKind::Block(block, _) = &else_expr.kind {
344 let (error_sp, semi_sp) = self.find_block_span(block, Some(then_ty));
345 remove_semicolon = semi_sp;
346 if block.expr.is_none() && block.stmts.is_empty() {
347 // Avoid overlapping spans that aren't as readable:
349 // 2 | let x = if true {
352 // | | - expected because of this
359 // | |______if and else have incompatible types
360 // | expected integer, found `()`
362 // by not pointing at the entire expression:
364 // 2 | let x = if true {
365 // | ------- `if` and `else` have incompatible types
367 // | - expected because of this
372 // | |_____^ expected integer, found `()`
374 if outer_sp.is_some() {
375 outer_sp = Some(self.tcx.sess.source_map().guess_head_span(span));
380 // shouldn't happen unless the parser has done something weird
384 // Compute `Span` of `then` part of `if`-expression.
385 let then_sp = if let ExprKind::Block(block, _) = &then_expr.kind {
386 let (then_sp, semi_sp) = self.find_block_span(block, Some(else_ty));
387 remove_semicolon = remove_semicolon.or(semi_sp);
388 if block.expr.is_none() && block.stmts.is_empty() {
389 outer_sp = None; // same as in `error_sp`; cleanup output
393 // shouldn't happen unless the parser has done something weird
397 // Finally construct the cause:
400 ObligationCauseCode::IfExpression(Box::new(IfExpressionCause {
404 semicolon: remove_semicolon,
405 opt_suggest_box_span,
410 pub(super) fn demand_scrutinee_type(
412 scrut: &'tcx hir::Expr<'tcx>,
413 contains_ref_bindings: Option<hir::Mutability>,
416 // Not entirely obvious: if matches may create ref bindings, we want to
417 // use the *precise* type of the scrutinee, *not* some supertype, as
418 // the "scrutinee type" (issue #23116).
420 // arielb1 [writes here in this comment thread][c] that there
421 // is certainly *some* potential danger, e.g., for an example
424 // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
427 // let Foo(x) = f()[0];
430 // Then if the pattern matches by reference, we want to match
431 // `f()[0]` as a lexpr, so we can't allow it to be
432 // coerced. But if the pattern matches by value, `f()[0]` is
433 // still syntactically a lexpr, but we *do* want to allow
436 // However, *likely* we are ok with allowing coercions to
437 // happen if there are no explicit ref mut patterns - all
438 // implicit ref mut patterns must occur behind a reference, so
439 // they will have the "correct" variance and lifetime.
441 // This does mean that the following pattern would be legal:
446 // impl Deref for Foo {
447 // type Target = Bar;
448 // fn deref(&self) -> &Bar { &self.0 }
450 // impl DerefMut for Foo {
451 // fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
453 // fn foo(x: &mut Foo) {
455 // let Bar(z): &mut Bar = x;
458 // assert_eq!(foo.0.0, 42);
462 // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
463 // is problematic as the HIR is being scraped, but ref bindings may be
464 // implicit after #42640. We need to make sure that pat_adjustments
465 // (once introduced) is populated by the time we get here.
468 if let Some(m) = contains_ref_bindings {
469 self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
471 self.check_expr(scrut)
473 // ...but otherwise we want to use any supertype of the
474 // scrutinee. This is sort of a workaround, see note (*) in
475 // `check_pat` for some details.
476 let scrut_ty = self.next_ty_var(TypeVariableOrigin {
477 kind: TypeVariableOriginKind::TypeInference,
480 self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
487 block: &'tcx hir::Block<'tcx>,
488 expected_ty: Option<Ty<'tcx>>,
489 ) -> (Span, Option<(Span, StatementAsExpression)>) {
490 if let Some(expr) = &block.expr {
492 } else if let Some(stmt) = block.stmts.last() {
493 // possibly incorrect trailing `;` in the else arm
494 (stmt.span, expected_ty.and_then(|ty| self.could_remove_semicolon(block, ty)))
496 // empty block; point at its entirety
501 // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait`
502 // we check if the different arms would work with boxed trait objects instead and
503 // provide a structured suggestion in that case.
504 pub(crate) fn opt_suggest_box_span(
507 orig_expected: Expectation<'tcx>,
509 match orig_expected {
510 Expectation::ExpectHasType(expected)
512 && self.ret_coercion.as_ref()?.borrow().merged_ty().has_opaque_types()
513 && self.can_coerce(outer_ty, expected) =>
515 let obligations = self.fulfillment_cx.borrow().pending_obligations();
516 let mut suggest_box = !obligations.is_empty();
517 for o in obligations {
518 match o.predicate.kind().skip_binder() {
519 ty::PredicateKind::Trait(t) => {
521 ty::Binder::dummy(ty::PredicateKind::Trait(ty::TraitPredicate {
522 trait_ref: ty::TraitRef {
524 substs: self.infcx.tcx.mk_substs_trait(outer_ty, &[]),
526 constness: t.constness,
527 polarity: t.polarity,
529 let obl = Obligation::new(
532 pred.to_predicate(self.infcx.tcx),
534 suggest_box &= self.infcx.predicate_must_hold_modulo_regions(&obl);
536 // We've encountered some obligation that didn't hold, so the
537 // return expression can't just be boxed. We don't need to
538 // evaluate the rest of the obligations.
545 // If all the obligations hold (or there are no obligations) the tail expression
546 // we can suggest to return a boxed trait object instead of an opaque type.
547 if suggest_box { self.ret_type_span } else { None }
554 fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
555 arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max_by_key(|m| match *m {
556 hir::Mutability::Mut => 1,
557 hir::Mutability::Not => 0,