1use rustc_errors::codes::*;
2use rustc_errors::{Applicability, Diag};
3use rustc_hir::def::{CtorOf, DefKind, Res};
4use rustc_hir::def_id::LocalDefId;
5use rustc_hir::{selfas hir, ExprKind, HirId, PatKind};
6use rustc_hir_pretty::ty_to_string;
7use rustc_middle::ty::{self, Ty};
8use rustc_span::{Span, sym};
9use rustc_trait_selection::traits::{
10MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
11};
12use tracing::{debug, instrument};
1314use crate::coercion::CoerceMany;
15use crate::{Diverges, Expectation, FnCtxt, GatherLocalsVisitor, Needs};
1617impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
18x;#[instrument(skip(self), level = "debug", ret)]19pub(crate) fn check_expr_match(
20&self,
21 expr: &'tcx hir::Expr<'tcx>,
22 scrut: &'tcx hir::Expr<'tcx>,
23 arms: &'tcx [hir::Arm<'tcx>],
24 orig_expected: Expectation<'tcx>,
25 match_src: hir::MatchSource,
26 ) -> Ty<'tcx> {
27let tcx = self.tcx;
2829let acrb = arms_contain_ref_bindings(arms);
30let scrutinee_ty = self.demand_scrutinee_type(scrut, acrb, arms.is_empty());
31debug!(?scrutinee_ty);
3233// If there are no arms, that is a diverging match; a special case.
34if arms.is_empty() {
35self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
36return tcx.types.never;
37 }
3839self.warn_arms_when_scrutinee_diverges(arms);
4041// Otherwise, we have to union together the types that the arms produce and so forth.
42let scrut_diverges = self.diverges.replace(Diverges::Maybe);
4344// #55810: Type check patterns first so we get types for all bindings.
45let scrut_span = scrut.span.find_ancestor_inside(expr.span).unwrap_or(scrut.span);
46for arm in arms {
47 GatherLocalsVisitor::gather_from_arm(self, arm);
4849self.check_pat_top(arm.pat, scrutinee_ty, Some(scrut_span), Some(scrut), None);
50 }
5152// Now typecheck the blocks.
53 //
54 // The result of the match is the common supertype of all the
55 // arms. Start out the value as bottom, since it's the, well,
56 // bottom the type lattice, and we'll be moving up the lattice as
57 // we process each arm. (Note that any match with 0 arms is matching
58 // on any empty type and is therefore unreachable; should the flow
59 // of execution reach it, we will panic, so bottom is an appropriate
60 // type in that case)
61let mut all_arms_diverge = Diverges::WarnedAlways;
6263let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self);
64debug!(?expected);
6566let mut coercion = {
67let coerce_first = match expected {
68// We don't coerce to `()` so that if the match expression is a
69 // statement it's branches can have any consistent type. That allows
70 // us to give better error messages (pointing to a usually better
71 // arm for inconsistent arms or to the whole match when a `()` type
72 // is required).
73Expectation::ExpectHasType(ety) if ety != tcx.types.unit => ety,
74_ => self.next_ty_var(expr.span),
75 };
76 CoerceMany::with_capacity(coerce_first, arms.len())
77 };
7879let mut prior_non_diverging_arms = vec![]; // Used only for diagnostics.
80let mut prior_arm = None;
81for arm in arms {
82self.diverges.set(Diverges::Maybe);
8384if let Some(e) = &arm.guard {
85self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {});
8687// FIXME: If this is the first arm and the pattern is irrefutable,
88 // e.g. `_` or `x`, and the guard diverges, then the whole match
89 // may also be considered to diverge. We should warn on all subsequent
90 // arms, too, just like we do for diverging scrutinees above.
91}
9293// N.B. We don't reset diverges here b/c we want to warn in the arm
94 // if the guard diverges, like: `x if { loop {} } => f()`, and we
95 // also want to consider the arm to diverge itself.
9697let arm_ty = self.check_expr_with_expectation(arm.body, expected);
98 all_arms_diverge &= self.diverges.get();
99let tail_defines_return_position_impl_trait =
100self.return_position_impl_trait_from_match_expectation(orig_expected);
101102let (arm_block_id, arm_span) = if let hir::ExprKind::Block(blk, _) = arm.body.kind {
103 (Some(blk.hir_id), self.find_block_span(blk))
104 } else {
105 (None, arm.body.span)
106 };
107108let code = match prior_arm {
109// The reason for the first arm to fail is not that the match arms diverge,
110 // but rather that there's a prior obligation that doesn't hold.
111None => ObligationCauseCode::BlockTailExpression(arm.body.hir_id, match_src),
112Some((prior_arm_block_id, prior_arm_ty, prior_arm_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 expr_span: expr.span,
122 source: match_src,
123 prior_non_diverging_arms: prior_non_diverging_arms.clone(),
124 tail_defines_return_position_impl_trait,
125 }))
126 }
127 };
128let cause = self.cause(arm_span, code);
129130// 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.
134coercion.coerce_inner(
135self,
136&cause,
137Some(arm.body),
138 arm_ty,
139 |err| {
140self.explain_never_type_coerced_to_unit(err, arm, arm_ty, prior_arm, expr);
141 },
142false,
143 );
144145if !arm_ty.is_never() {
146// When a match arm has type `!`, then it doesn't influence the expected type for
147 // the following arm. If all of the prior arms are `!`, then the influence comes
148 // from elsewhere and we shouldn't point to any previous arm.
149prior_arm = Some((arm_block_id, arm_ty, arm_span));
150151 prior_non_diverging_arms.push(arm_span);
152if prior_non_diverging_arms.len() > 5 {
153 prior_non_diverging_arms.remove(0);
154 }
155 }
156 }
157158// If all of the arms in the `match` diverge,
159 // and we're dealing with an actual `match` block
160 // (as opposed to a `match` desugared from something else'),
161 // we can emit a better note. Rather than pointing
162 // at a diverging expression in an arbitrary arm,
163 // we can point at the entire `match` expression
164if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
165 all_arms_diverge = Diverges::Always {
166 span: expr.span,
167 custom_note: Some(
168"any code following this `match` expression is unreachable, as all arms diverge",
169 ),
170 };
171 }
172173// We won't diverge unless the scrutinee or all arms diverge.
174self.diverges.set(scrut_diverges | all_arms_diverge);
175176 coercion.complete(self)
177 }
178179fn explain_never_type_coerced_to_unit(
180&self,
181 err: &mut Diag<'_>,
182 arm: &hir::Arm<'tcx>,
183 arm_ty: Ty<'tcx>,
184 prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
185 expr: &hir::Expr<'tcx>,
186 ) {
187if let hir::ExprKind::Block(block, _) = arm.body.kind
188 && let Some(expr) = block.expr
189 && let arm_tail_ty = self.node_ty(expr.hir_id)
190 && arm_tail_ty.is_never()
191 && !arm_ty.is_never()
192 {
193err.span_label(
194expr.span,
195::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression is of type `!`, but it is coerced to `{0}` due to its surrounding expression",
arm_ty))
})format!(
196"this expression is of type `!`, but it is coerced to `{arm_ty}` due to its \
197 surrounding expression",
198 ),
199 );
200self.suggest_mismatched_types_on_tail(
201err,
202expr,
203arm_ty,
204prior_arm.map_or(arm_tail_ty, |(_, ty, _)| ty),
205expr.hir_id,
206 );
207 }
208self.suggest_removing_semicolon_for_coerce(err, expr, arm_ty, prior_arm)
209 }
210211fn suggest_removing_semicolon_for_coerce(
212&self,
213 diag: &mut Diag<'_>,
214 expr: &hir::Expr<'tcx>,
215 arm_ty: Ty<'tcx>,
216 prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
217 ) {
218// First, check that we're actually in the tail of a function.
219let Some(body) = self.tcx.hir_maybe_body_owned_by(self.body_id) else {
220return;
221 };
222let hir::ExprKind::Block(block, _) = body.value.kind else {
223return;
224 };
225let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), span: semi_span, .. }) =
226block.innermost_block().stmts.last()
227else {
228return;
229 };
230if last_expr.hir_id != expr.hir_id {
231return;
232 }
233234// Next, make sure that we have no type expectation.
235let Some(ret) =
236self.tcx.hir_node_by_def_id(self.body_id).fn_decl().map(|decl| decl.output.span())
237else {
238return;
239 };
240241let can_coerce_to_return_ty = match self.ret_coercion.as_ref() {
242Some(ret_coercion) => {
243let ret_ty = ret_coercion.borrow().expected_ty();
244let ret_ty = self.infcx.shallow_resolve(ret_ty);
245self.may_coerce(arm_ty, ret_ty)
246 && prior_arm.is_none_or(|(_, ty, _)| self.may_coerce(ty, ret_ty))
247// The match arms need to unify for the case of `impl Trait`.
248 && !#[allow(non_exhaustive_omitted_patterns)] match ret_ty.kind() {
ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => true,
_ => false,
}matches!(ret_ty.kind(), ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }))249 }
250_ => false,
251 };
252if !can_coerce_to_return_ty {
253return;
254 }
255256let semi = expr.span.shrink_to_hi().with_hi(semi_span.hi());
257let sugg = crate::errors::RemoveSemiForCoerce { expr: expr.span, ret, semi };
258diag.subdiagnostic(sugg);
259 }
260261/// When the previously checked expression (the scrutinee) diverges,
262 /// warn the user about the match arms being unreachable.
263fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [hir::Arm<'tcx>]) {
264for arm in arms {
265self.warn_if_unreachable(arm.body.hir_id, arm.body.span, "arm");
266 }
267 }
268269/// Handle the fallback arm of a desugared if(-let) like a missing else.
270 ///
271 /// Returns `true` if there was an error forcing the coercion to the `()` type.
272pub(super) fn if_fallback_coercion(
273&self,
274 if_span: Span,
275 cond_expr: &'tcx hir::Expr<'tcx>,
276 then_expr: &'tcx hir::Expr<'tcx>,
277 coercion: &mut CoerceMany<'tcx>,
278 ) -> bool {
279// If this `if` expr is the parent's function return expr,
280 // the cause of the type coercion is the return type, point at it. (#25228)
281let hir_id = self.tcx.parent_hir_id(self.tcx.parent_hir_id(then_expr.hir_id));
282let ret_reason = self.maybe_get_coercion_reason(hir_id, if_span);
283let cause = self.cause(if_span, ObligationCauseCode::IfExpressionWithNoElse);
284let mut error = false;
285coercion.coerce_forced_unit(
286self,
287&cause,
288 |err| self.explain_if_expr(err, ret_reason, if_span, cond_expr, then_expr, &mut error),
289false,
290 );
291error292 }
293294/// Check if the span comes from an assert-like macro expansion.
295fn is_from_assert_macro(&self, span: Span) -> bool {
296span.ctxt().outer_expn_data().macro_def_id.is_some_and(|def_id| {
297#[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(def_id)
{
Some(sym::assert_macro | sym::debug_assert_macro | sym::assert_eq_macro |
sym::assert_ne_macro | sym::debug_assert_eq_macro |
sym::debug_assert_ne_macro) => true,
_ => false,
}matches!(
298self.tcx.get_diagnostic_name(def_id),
299Some(
300 sym::assert_macro
301 | sym::debug_assert_macro
302 | sym::assert_eq_macro
303 | sym::assert_ne_macro
304 | sym::debug_assert_eq_macro
305 | sym::debug_assert_ne_macro
306 )
307 )308 })
309 }
310311/// Explain why `if` expressions without `else` evaluate to `()` and detect likely irrefutable
312 /// `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`.
313fn explain_if_expr(
314&self,
315 err: &mut Diag<'_>,
316 ret_reason: Option<(Span, String)>,
317 if_span: Span,
318 cond_expr: &'tcx hir::Expr<'tcx>,
319 then_expr: &'tcx hir::Expr<'tcx>,
320 error: &mut bool,
321 ) {
322let is_assert_macro = self.is_from_assert_macro(if_span);
323324if let Some((if_span, msg)) = ret_reason {
325err.span_label(if_span, msg);
326 } else if let ExprKind::Block(block, _) = then_expr.kind
327 && let Some(expr) = block.expr
328 {
329err.span_label(expr.span, "found here");
330 }
331332if is_assert_macro {
333err.code(E0308);
334err.primary_message("mismatched types");
335 } else {
336err.note("`if` expressions without `else` evaluate to `()`");
337err.help("consider adding an `else` block that evaluates to the expected type");
338 }
339*error = true;
340if let ExprKind::Let(hir::LetExpr { span, pat, init, .. }) = cond_expr.kind
341 && let ExprKind::Block(block, _) = then_expr.kind
342// Refutability checks occur on the MIR, so we approximate it here by checking
343 // if we have an enum with a single variant or a struct in the pattern.
344&& let PatKind::TupleStruct(qpath, ..) | PatKind::Struct(qpath, ..) = pat.kind
345 && let hir::QPath::Resolved(_, path) = qpath346 {
347match path.res {
348 Res::Def(DefKind::Ctor(CtorOf::Struct, _), _) => {
349// Structs are always irrefutable. Their fields might not be, but we
350 // don't check for that here, it's only an approximation.
351}
352 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id)
353if self354 .tcx
355 .adt_def(self.tcx.parent(self.tcx.parent(def_id)))
356 .variants()
357 .len()
358 == 1 =>
359 {
360// There's only a single variant in the `enum`, so we can suggest the
361 // irrefutable `let` instead of `if let`.
362}
363_ => return,
364 }
365366let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(if_span.until(*span), String::new())]))vec![
367// Remove the `if`
368(if_span.until(*span), String::new()),
369 ];
370match (block.stmts, block.expr) {
371 ([first, ..], Some(expr)) => {
372let padding = self373 .tcx
374 .sess
375 .source_map()
376 .indentation_before(first.span)
377 .unwrap_or_else(|| String::new());
378sugg.extend([
379 (init.span.between(first.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(";\n{0}", padding))
})format!(";\n{padding}")),
380 (expr.span.shrink_to_hi().with_hi(block.span.hi()), String::new()),
381 ]);
382 }
383 ([], Some(expr)) => {
384let padding = self385 .tcx
386 .sess
387 .source_map()
388 .indentation_before(expr.span)
389 .unwrap_or_else(|| String::new());
390sugg.extend([
391 (init.span.between(expr.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(";\n{0}", padding))
})format!(";\n{padding}")),
392 (expr.span.shrink_to_hi().with_hi(block.span.hi()), String::new()),
393 ]);
394 }
395// If there's no value in the body, then the `if` expression would already
396 // be of type `()`, so checking for those cases is unnecessary.
397(_, None) => return,
398 }
399err.multipart_suggestion(
400"consider using an irrefutable `let` binding instead",
401sugg,
402 Applicability::MaybeIncorrect,
403 );
404 }
405 }
406407pub(crate) fn maybe_get_coercion_reason(
408&self,
409 hir_id: hir::HirId,
410 sp: Span,
411 ) -> Option<(Span, String)> {
412let node = self.tcx.hir_node(hir_id);
413if let hir::Node::Block(block) = node {
414// check that the body's parent is an fn
415let parent = self.tcx.parent_hir_node(self.tcx.parent_hir_id(block.hir_id));
416if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })) =
417 (&block.expr, parent)
418 {
419// check that the `if` expr without `else` is the fn body's expr
420if expr.span == sp {
421return self.get_fn_decl(hir_id).map(|(_, fn_decl)| {
422let (ty, span) = match fn_decl.output {
423 hir::FnRetTy::DefaultReturn(span) => ("()".to_string(), span),
424 hir::FnRetTy::Return(ty) => (ty_to_string(&self.tcx, ty), ty.span),
425 };
426 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` because of this return type",
ty))
})format!("expected `{ty}` because of this return type"))
427 });
428 }
429 }
430 }
431if let hir::Node::LetStmt(hir::LetStmt { ty: Some(_), pat, .. }) = node {
432return Some((pat.span, "expected because of this assignment".to_string()));
433 }
434None435 }
436437pub(crate) fn if_cause(
438&self,
439 expr_id: HirId,
440 else_expr: &'tcx hir::Expr<'tcx>,
441 tail_defines_return_position_impl_trait: Option<LocalDefId>,
442 ) -> ObligationCause<'tcx> {
443let error_sp = self.find_block_span_from_hir_id(else_expr.hir_id);
444445// Finally construct the cause:
446self.cause(
447error_sp,
448 ObligationCauseCode::IfExpression { expr_id, tail_defines_return_position_impl_trait },
449 )
450 }
451452pub(super) fn demand_scrutinee_type(
453&self,
454 scrut: &'tcx hir::Expr<'tcx>,
455 contains_ref_bindings: Option<hir::Mutability>,
456 no_arms: bool,
457 ) -> Ty<'tcx> {
458// Not entirely obvious: if matches may create ref bindings, we want to
459 // use the *precise* type of the scrutinee, *not* some supertype, as
460 // the "scrutinee type" (issue #23116).
461 //
462 // arielb1 [writes here in this comment thread][c] that there
463 // is certainly *some* potential danger, e.g., for an example
464 // like:
465 //
466 // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
467 //
468 // ```
469 // let Foo(x) = f()[0];
470 // ```
471 //
472 // Then if the pattern matches by reference, we want to match
473 // `f()[0]` as a lexpr, so we can't allow it to be
474 // coerced. But if the pattern matches by value, `f()[0]` is
475 // still syntactically a lexpr, but we *do* want to allow
476 // coercions.
477 //
478 // However, *likely* we are ok with allowing coercions to
479 // happen if there are no explicit ref mut patterns - all
480 // implicit ref mut patterns must occur behind a reference, so
481 // they will have the "correct" variance and lifetime.
482 //
483 // This does mean that the following pattern would be legal:
484 //
485 // ```
486 // struct Foo(Bar);
487 // struct Bar(u32);
488 // impl Deref for Foo {
489 // type Target = Bar;
490 // fn deref(&self) -> &Bar { &self.0 }
491 // }
492 // impl DerefMut for Foo {
493 // fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
494 // }
495 // fn foo(x: &mut Foo) {
496 // {
497 // let Bar(z): &mut Bar = x;
498 // *z = 42;
499 // }
500 // assert_eq!(foo.0.0, 42);
501 // }
502 // ```
503 //
504 // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
505 // is problematic as the HIR is being scraped, but ref bindings may be
506 // implicit after #42640. We need to make sure that pat_adjustments
507 // (once introduced) is populated by the time we get here.
508 //
509 // See #44848.
510if let Some(m) = contains_ref_bindings {
511self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
512 } else if no_arms {
513self.check_expr(scrut)
514 } else {
515// ...but otherwise we want to use any supertype of the
516 // scrutinee. This is sort of a workaround, see note (*) in
517 // `check_pat` for some details.
518let scrut_ty = self.next_ty_var(scrut.span);
519self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
520scrut_ty521 }
522 }
523524// Does the expectation of the match define an RPIT?
525 // (e.g. we're in the tail of a function body)
526 //
527 // Returns the `LocalDefId` of the RPIT, which is always identity-substituted.
528pub(crate) fn return_position_impl_trait_from_match_expectation(
529&self,
530 expectation: Expectation<'tcx>,
531 ) -> Option<LocalDefId> {
532let expected_ty = expectation.to_option(self)?;
533let (def_id, args) = match *expected_ty.kind() {
534// FIXME: Could also check that the RPIT is not defined
535ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
536 (def_id.as_local()?, args)
537 }
538// FIXME(-Znext-solver=no): Remove this branch once `replace_opaque_types_with_infer` is gone.
539ty::Infer(ty::TyVar(_)) => self540 .inner
541 .borrow_mut()
542 .opaque_types()
543 .iter_opaque_types()
544 .find(|(_, v)| v.ty == expected_ty)
545 .map(|(k, _)| (k.def_id, k.args))?,
546_ => return None,
547 };
548let hir::OpaqueTyOrigin::FnReturn { parent: parent_def_id, .. } =
549self.tcx.local_opaque_ty_origin(def_id)
550else {
551return None;
552 };
553if &args[0..self.tcx.generics_of(parent_def_id).count()]
554 != ty::GenericArgs::identity_for_item(self.tcx, parent_def_id).as_slice()
555 {
556return None;
557 }
558Some(def_id)
559 }
560}
561562fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
563arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max()
564}