1use rustc_errors::{Applicability, Diag};
2use rustc_hir::def::{CtorOf, DefKind, Res};
3use rustc_hir::def_id::LocalDefId;
4use rustc_hir::{selfas hir, ExprKind, HirId, PatKind};
5use rustc_hir_pretty::ty_to_string;
6use rustc_middle::ty::{self, Ty};
7use rustc_span::Span;
8use rustc_trait_selection::traits::{
9MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
10};
11use tracing::{debug, instrument};
1213use crate::coercion::CoerceMany;
14use crate::{Diverges, Expectation, FnCtxt, GatherLocalsVisitor, Needs};
1516impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17x;#[instrument(skip(self), level = "debug", ret)]18pub(crate) fn check_expr_match(
19&self,
20 expr: &'tcx hir::Expr<'tcx>,
21 scrut: &'tcx hir::Expr<'tcx>,
22 arms: &'tcx [hir::Arm<'tcx>],
23 orig_expected: Expectation<'tcx>,
24 match_src: hir::MatchSource,
25 ) -> Ty<'tcx> {
26let tcx = self.tcx;
2728let acrb = arms_contain_ref_bindings(arms);
29let scrutinee_ty = self.demand_scrutinee_type(scrut, acrb, arms.is_empty());
30debug!(?scrutinee_ty);
3132// If there are no arms, that is a diverging match; a special case.
33if arms.is_empty() {
34self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
35return tcx.types.never;
36 }
3738self.warn_arms_when_scrutinee_diverges(arms);
3940// Otherwise, we have to union together the types that the arms produce and so forth.
41let scrut_diverges = self.diverges.replace(Diverges::Maybe);
4243// #55810: Type check patterns first so we get types for all bindings.
44let scrut_span = scrut.span.find_ancestor_inside(expr.span).unwrap_or(scrut.span);
45for arm in arms {
46 GatherLocalsVisitor::gather_from_arm(self, arm);
4748self.check_pat_top(arm.pat, scrutinee_ty, Some(scrut_span), Some(scrut), None);
49 }
5051// Now typecheck the blocks.
52 //
53 // The result of the match is the common supertype of all the
54 // arms. Start out the value as bottom, since it's the, well,
55 // bottom the type lattice, and we'll be moving up the lattice as
56 // we process each arm. (Note that any match with 0 arms is matching
57 // on any empty type and is therefore unreachable; should the flow
58 // of execution reach it, we will panic, so bottom is an appropriate
59 // type in that case)
60let mut all_arms_diverge = Diverges::WarnedAlways;
6162let expected =
63 orig_expected.try_structurally_resolve_and_adjust_for_branches(self, expr.span);
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::Opaque, ..) => true,
_ => false,
}matches!(ret_ty.kind(), ty::Alias(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/// Explain why `if` expressions without `else` evaluate to `()` and detect likely irrefutable
295 /// `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`.
296fn explain_if_expr(
297&self,
298 err: &mut Diag<'_>,
299 ret_reason: Option<(Span, String)>,
300 if_span: Span,
301 cond_expr: &'tcx hir::Expr<'tcx>,
302 then_expr: &'tcx hir::Expr<'tcx>,
303 error: &mut bool,
304 ) {
305if let Some((if_span, msg)) = ret_reason {
306err.span_label(if_span, msg);
307 } else if let ExprKind::Block(block, _) = then_expr.kind
308 && let Some(expr) = block.expr
309 {
310err.span_label(expr.span, "found here");
311 }
312err.note("`if` expressions without `else` evaluate to `()`");
313err.help("consider adding an `else` block that evaluates to the expected type");
314*error = true;
315if let ExprKind::Let(hir::LetExpr { span, pat, init, .. }) = cond_expr.kind
316 && let ExprKind::Block(block, _) = then_expr.kind
317// Refutability checks occur on the MIR, so we approximate it here by checking
318 // if we have an enum with a single variant or a struct in the pattern.
319&& let PatKind::TupleStruct(qpath, ..) | PatKind::Struct(qpath, ..) = pat.kind
320 && let hir::QPath::Resolved(_, path) = qpath321 {
322match path.res {
323 Res::Def(DefKind::Ctor(CtorOf::Struct, _), _) => {
324// Structs are always irrefutable. Their fields might not be, but we
325 // don't check for that here, it's only an approximation.
326}
327 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id)
328if self329 .tcx
330 .adt_def(self.tcx.parent(self.tcx.parent(def_id)))
331 .variants()
332 .len()
333 == 1 =>
334 {
335// There's only a single variant in the `enum`, so we can suggest the
336 // irrefutable `let` instead of `if let`.
337}
338_ => return,
339 }
340341let mut sugg = <[_]>::into_vec(::alloc::boxed::box_new([(if_span.until(*span),
String::new())]))vec![
342// Remove the `if`
343(if_span.until(*span), String::new()),
344 ];
345match (block.stmts, block.expr) {
346 ([first, ..], Some(expr)) => {
347let padding = self348 .tcx
349 .sess
350 .source_map()
351 .indentation_before(first.span)
352 .unwrap_or_else(|| String::new());
353sugg.extend([
354 (init.span.between(first.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(";\n{0}", padding))
})format!(";\n{padding}")),
355 (expr.span.shrink_to_hi().with_hi(block.span.hi()), String::new()),
356 ]);
357 }
358 ([], Some(expr)) => {
359let padding = self360 .tcx
361 .sess
362 .source_map()
363 .indentation_before(expr.span)
364 .unwrap_or_else(|| String::new());
365sugg.extend([
366 (init.span.between(expr.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(";\n{0}", padding))
})format!(";\n{padding}")),
367 (expr.span.shrink_to_hi().with_hi(block.span.hi()), String::new()),
368 ]);
369 }
370// If there's no value in the body, then the `if` expression would already
371 // be of type `()`, so checking for those cases is unnecessary.
372(_, None) => return,
373 }
374err.multipart_suggestion(
375"consider using an irrefutable `let` binding instead",
376sugg,
377 Applicability::MaybeIncorrect,
378 );
379 }
380 }
381382pub(crate) fn maybe_get_coercion_reason(
383&self,
384 hir_id: hir::HirId,
385 sp: Span,
386 ) -> Option<(Span, String)> {
387let node = self.tcx.hir_node(hir_id);
388if let hir::Node::Block(block) = node {
389// check that the body's parent is an fn
390let parent = self.tcx.parent_hir_node(self.tcx.parent_hir_id(block.hir_id));
391if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })) =
392 (&block.expr, parent)
393 {
394// check that the `if` expr without `else` is the fn body's expr
395if expr.span == sp {
396return self.get_fn_decl(hir_id).map(|(_, fn_decl)| {
397let (ty, span) = match fn_decl.output {
398 hir::FnRetTy::DefaultReturn(span) => ("()".to_string(), span),
399 hir::FnRetTy::Return(ty) => (ty_to_string(&self.tcx, ty), ty.span),
400 };
401 (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"))
402 });
403 }
404 }
405 }
406if let hir::Node::LetStmt(hir::LetStmt { ty: Some(_), pat, .. }) = node {
407return Some((pat.span, "expected because of this assignment".to_string()));
408 }
409None410 }
411412pub(crate) fn if_cause(
413&self,
414 expr_id: HirId,
415 else_expr: &'tcx hir::Expr<'tcx>,
416 tail_defines_return_position_impl_trait: Option<LocalDefId>,
417 ) -> ObligationCause<'tcx> {
418let error_sp = self.find_block_span_from_hir_id(else_expr.hir_id);
419420// Finally construct the cause:
421self.cause(
422error_sp,
423 ObligationCauseCode::IfExpression { expr_id, tail_defines_return_position_impl_trait },
424 )
425 }
426427pub(super) fn demand_scrutinee_type(
428&self,
429 scrut: &'tcx hir::Expr<'tcx>,
430 contains_ref_bindings: Option<hir::Mutability>,
431 no_arms: bool,
432 ) -> Ty<'tcx> {
433// Not entirely obvious: if matches may create ref bindings, we want to
434 // use the *precise* type of the scrutinee, *not* some supertype, as
435 // the "scrutinee type" (issue #23116).
436 //
437 // arielb1 [writes here in this comment thread][c] that there
438 // is certainly *some* potential danger, e.g., for an example
439 // like:
440 //
441 // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
442 //
443 // ```
444 // let Foo(x) = f()[0];
445 // ```
446 //
447 // Then if the pattern matches by reference, we want to match
448 // `f()[0]` as a lexpr, so we can't allow it to be
449 // coerced. But if the pattern matches by value, `f()[0]` is
450 // still syntactically a lexpr, but we *do* want to allow
451 // coercions.
452 //
453 // However, *likely* we are ok with allowing coercions to
454 // happen if there are no explicit ref mut patterns - all
455 // implicit ref mut patterns must occur behind a reference, so
456 // they will have the "correct" variance and lifetime.
457 //
458 // This does mean that the following pattern would be legal:
459 //
460 // ```
461 // struct Foo(Bar);
462 // struct Bar(u32);
463 // impl Deref for Foo {
464 // type Target = Bar;
465 // fn deref(&self) -> &Bar { &self.0 }
466 // }
467 // impl DerefMut for Foo {
468 // fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
469 // }
470 // fn foo(x: &mut Foo) {
471 // {
472 // let Bar(z): &mut Bar = x;
473 // *z = 42;
474 // }
475 // assert_eq!(foo.0.0, 42);
476 // }
477 // ```
478 //
479 // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
480 // is problematic as the HIR is being scraped, but ref bindings may be
481 // implicit after #42640. We need to make sure that pat_adjustments
482 // (once introduced) is populated by the time we get here.
483 //
484 // See #44848.
485if let Some(m) = contains_ref_bindings {
486self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
487 } else if no_arms {
488self.check_expr(scrut)
489 } else {
490// ...but otherwise we want to use any supertype of the
491 // scrutinee. This is sort of a workaround, see note (*) in
492 // `check_pat` for some details.
493let scrut_ty = self.next_ty_var(scrut.span);
494self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
495scrut_ty496 }
497 }
498499// Does the expectation of the match define an RPIT?
500 // (e.g. we're in the tail of a function body)
501 //
502 // Returns the `LocalDefId` of the RPIT, which is always identity-substituted.
503pub(crate) fn return_position_impl_trait_from_match_expectation(
504&self,
505 expectation: Expectation<'tcx>,
506 ) -> Option<LocalDefId> {
507let expected_ty = expectation.to_option(self)?;
508let (def_id, args) = match *expected_ty.kind() {
509// FIXME: Could also check that the RPIT is not defined
510ty::Alias(ty::Opaque, alias_ty) => (alias_ty.def_id.as_local()?, alias_ty.args),
511// FIXME(-Znext-solver=no): Remove this branch once `replace_opaque_types_with_infer` is gone.
512ty::Infer(ty::TyVar(_)) => self513 .inner
514 .borrow_mut()
515 .opaque_types()
516 .iter_opaque_types()
517 .find(|(_, v)| v.ty == expected_ty)
518 .map(|(k, _)| (k.def_id, k.args))?,
519_ => return None,
520 };
521let hir::OpaqueTyOrigin::FnReturn { parent: parent_def_id, .. } =
522self.tcx.local_opaque_ty_origin(def_id)
523else {
524return None;
525 };
526if &args[0..self.tcx.generics_of(parent_def_id).count()]
527 != ty::GenericArgs::identity_for_item(self.tcx, parent_def_id).as_slice()
528 {
529return None;
530 }
531Some(def_id)
532 }
533}
534535fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
536arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max()
537}