use crate::check::coercion::CoerceMany;
use crate::check::{Diverges, Expectation, FnCtxt, Needs};
use rustc_hir as hir;
use rustc_hir::ExprKind;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_middle::ty::Ty;
use rustc_span::Span;
use rustc_trait_selection::traits::ObligationCauseCode;
use rustc_trait_selection::traits::{IfExpressionCause, MatchExpressionArmCause, ObligationCause};
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn check_match(
&self,
expr: &'tcx hir::Expr<'tcx>,
scrut: &'tcx hir::Expr<'tcx>,
arms: &'tcx [hir::Arm<'tcx>],
expected: Expectation<'tcx>,
match_src: hir::MatchSource,
) -> Ty<'tcx> {
let tcx = self.tcx;
use hir::MatchSource::*;
let (source_if, if_no_else, force_scrutinee_bool) = match match_src {
IfDesugar { contains_else_clause } => (true, !contains_else_clause, true),
IfLetDesugar { contains_else_clause } => (true, !contains_else_clause, false),
WhileDesugar => (false, false, true),
_ => (false, false, false),
};
let scrut_ty = if force_scrutinee_bool {
self.check_expr_has_type_or_error(scrut, self.tcx.types.bool, |_| {})
} else {
self.demand_scrutinee_type(arms, scrut)
};
if arms.is_empty() {
self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
return tcx.types.never;
}
self.warn_arms_when_scrutinee_diverges(arms, match_src);
let scrut_diverges = self.diverges.replace(Diverges::Maybe);
for arm in arms {
self.check_pat_top(&arm.pat, scrut_ty, Some(scrut.span), true);
}
let mut all_arms_diverge = Diverges::WarnedAlways;
let expected = expected.adjust_for_branches(self);
let mut coercion = {
let coerce_first = match expected {
Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety,
_ => self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::MiscVariable,
span: expr.span,
}),
};
CoerceMany::with_coercion_sites(coerce_first, arms)
};
let mut other_arms = vec![];
let mut prior_arm_ty = None;
for (i, arm) in arms.iter().enumerate() {
if let Some(g) = &arm.guard {
self.diverges.set(Diverges::Maybe);
match g {
hir::Guard::If(e) => {
self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {})
}
};
}
self.diverges.set(Diverges::Maybe);
let arm_ty = if source_if
&& if_no_else
&& i != 0
&& self.if_fallback_coercion(expr.span, &arms[0].body, &mut coercion)
{
tcx.ty_error()
} else {
self.check_expr_with_expectation(&arm.body, expected)
};
all_arms_diverge &= self.diverges.get();
if source_if {
let then_expr = &arms[0].body;
match (i, if_no_else) {
(0, _) => coercion.coerce(self, &self.misc(expr.span), &arm.body, arm_ty),
(_, true) => {}
(_, _) => {
let then_ty = prior_arm_ty.unwrap();
let cause = self.if_cause(expr.span, then_expr, &arm.body, then_ty, arm_ty);
coercion.coerce(self, &cause, &arm.body, arm_ty);
}
}
} else {
let (arm_span, semi_span) = if let hir::ExprKind::Block(blk, _) = &arm.body.kind {
self.find_block_span(blk, prior_arm_ty)
} else {
(arm.body.span, None)
};
let (span, code) = match i {
0 => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)),
_ => (
expr.span,
ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
arm_span,
semi_span,
source: match_src,
prior_arms: other_arms.clone(),
last_ty: prior_arm_ty.unwrap(),
scrut_hir_id: scrut.hir_id,
}),
),
};
let cause = self.cause(span, code);
coercion.coerce(self, &cause, &arm.body, arm_ty);
other_arms.push(arm_span);
if other_arms.len() > 5 {
other_arms.remove(0);
}
}
prior_arm_ty = Some(arm_ty);
}
if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
all_arms_diverge = Diverges::Always {
span: expr.span,
custom_note: Some(
"any code following this `match` expression is unreachable, as all arms diverge",
),
};
}
self.diverges.set(scrut_diverges | all_arms_diverge);
coercion.complete(self)
}
fn warn_arms_when_scrutinee_diverges(
&self,
arms: &'tcx [hir::Arm<'tcx>],
source: hir::MatchSource,
) {
use hir::MatchSource::*;
let msg = match source {
IfDesugar { .. } | IfLetDesugar { .. } => "block in `if` expression",
WhileDesugar { .. } | WhileLetDesugar { .. } => "block in `while` expression",
_ => "arm",
};
for arm in arms {
self.warn_if_unreachable(arm.body.hir_id, arm.body.span, msg);
}
}
fn if_fallback_coercion(
&self,
span: Span,
then_expr: &'tcx hir::Expr<'tcx>,
coercion: &mut CoerceMany<'tcx, '_, rustc_hir::Arm<'tcx>>,
) -> bool {
let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
let mut error = false;
coercion.coerce_forced_unit(
self,
&cause,
&mut |err| {
if let Some((span, msg)) = &ret_reason {
err.span_label(*span, msg.as_str());
} else if let ExprKind::Block(block, _) = &then_expr.kind {
if let Some(expr) = &block.expr {
err.span_label(expr.span, "found here".to_string());
}
}
err.note("`if` expressions without `else` evaluate to `()`");
err.help("consider adding an `else` block that evaluates to the expected type");
error = true;
},
ret_reason.is_none(),
);
error
}
fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, span: Span) -> Option<(Span, String)> {
use hir::Node::{Block, Item, Local};
let hir = self.tcx.hir();
let arm_id = hir.get_parent_node(hir_id);
let match_id = hir.get_parent_node(arm_id);
let containing_id = hir.get_parent_node(match_id);
let node = hir.get(containing_id);
if let Block(block) = node {
let parent = hir.get(hir.get_parent_node(hir.get_parent_node(block.hir_id)));
if let (Some(expr), Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
(&block.expr, parent)
{
if expr.span == span {
return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
let span = fn_decl.output.span();
let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
Some((span, format!("expected `{}` because of this return type", snippet)))
});
}
}
}
if let Local(hir::Local { ty: Some(_), pat, .. }) = node {
return Some((pat.span, "expected because of this assignment".to_string()));
}
None
}
fn if_cause(
&self,
span: Span,
then_expr: &'tcx hir::Expr<'tcx>,
else_expr: &'tcx hir::Expr<'tcx>,
then_ty: Ty<'tcx>,
else_ty: Ty<'tcx>,
) -> ObligationCause<'tcx> {
let mut outer_sp = if self.tcx.sess.source_map().is_multiline(span) {
Some(span)
} else {
None
};
let mut remove_semicolon = None;
let error_sp = if let ExprKind::Block(block, _) = &else_expr.kind {
let (error_sp, semi_sp) = self.find_block_span(block, Some(then_ty));
remove_semicolon = semi_sp;
if block.expr.is_none() && block.stmts.is_empty() {
if outer_sp.is_some() {
outer_sp = Some(self.tcx.sess.source_map().guess_head_span(span));
}
}
error_sp
} else {
else_expr.span
};
let then_sp = if let ExprKind::Block(block, _) = &then_expr.kind {
let (then_sp, semi_sp) = self.find_block_span(block, Some(else_ty));
remove_semicolon = remove_semicolon.or(semi_sp);
if block.expr.is_none() && block.stmts.is_empty() {
outer_sp = None;
}
then_sp
} else {
then_expr.span
};
self.cause(
error_sp,
ObligationCauseCode::IfExpression(box IfExpressionCause {
then: then_sp,
outer: outer_sp,
semicolon: remove_semicolon,
}),
)
}
fn demand_scrutinee_type(
&self,
arms: &'tcx [hir::Arm<'tcx>],
scrut: &'tcx hir::Expr<'tcx>,
) -> Ty<'tcx> {
let contains_ref_bindings = arms
.iter()
.filter_map(|a| a.pat.contains_explicit_ref_binding())
.max_by_key(|m| match *m {
hir::Mutability::Mut => 1,
hir::Mutability::Not => 0,
});
if let Some(m) = contains_ref_bindings {
self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
} else if arms.is_empty() {
self.check_expr(scrut)
} else {
let scrut_ty = self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::TypeInference,
span: scrut.span,
});
self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
scrut_ty
}
}
fn find_block_span(
&self,
block: &'tcx hir::Block<'tcx>,
expected_ty: Option<Ty<'tcx>>,
) -> (Span, Option<Span>) {
if let Some(expr) = &block.expr {
(expr.span, None)
} else if let Some(stmt) = block.stmts.last() {
(stmt.span, expected_ty.and_then(|ty| self.could_remove_semicolon(block, ty)))
} else {
(block.span, None)
}
}
}