1 use crate::check
::coercion
::{AsCoercionSite, CoerceMany}
;
2 use crate::check
::{Diverges, Expectation, FnCtxt, Needs}
;
3 use rustc_errors
::{Applicability, DiagnosticBuilder}
;
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, TyS}
;
8 use rustc_span
::{MultiSpan, Span}
;
9 use rustc_trait_selection
::opaque_types
::InferCtxtExt
as _
;
10 use rustc_trait_selection
::traits
::query
::evaluate_obligation
::InferCtxtExt
;
11 use rustc_trait_selection
::traits
::{
12 IfExpressionCause
, MatchExpressionArmCause
, ObligationCause
, ObligationCauseCode
,
13 StatementAsExpression
,
16 macro_rules
! create_maybe_get_coercion_reason
{
17 ($fn_name
:ident
, $node
:expr
) => {
18 pub(crate) fn $
fn_name(&self, hir_id
: hir
::HirId
, sp
: Span
) -> Option
<(Span
, String
)> {
19 let node
= $
node(self.tcx
.hir(), hir_id
);
20 if let hir
::Node
::Block(block
) = node
{
21 // check that the body's parent is an fn
22 let parent
= self.tcx
.hir().get(
23 self.tcx
.hir().get_parent_node(self.tcx
.hir().get_parent_node(block
.hir_id
)),
27 hir
::Node
::Item(hir
::Item { kind: hir::ItemKind::Fn(..), .. }
),
28 ) = (&block
.expr
, parent
)
30 // check that the `if` expr without `else` is the fn body's expr
32 return self.get_fn_decl(hir_id
).and_then(|(fn_decl
, _
)| {
33 let span
= fn_decl
.output
.span();
34 let snippet
= self.tcx
.sess
.source_map().span_to_snippet(span
).ok()?
;
37 format
!("expected `{}` because of this return type", snippet
),
43 if let hir
::Node
::Local(hir
::Local { ty: Some(_), pat, .. }
) = node
{
44 return Some((pat
.span
, "expected because of this assignment".to_string()));
51 impl<'a
, 'tcx
> FnCtxt
<'a
, 'tcx
> {
54 expr
: &'tcx hir
::Expr
<'tcx
>,
55 scrut
: &'tcx hir
::Expr
<'tcx
>,
56 arms
: &'tcx
[hir
::Arm
<'tcx
>],
57 orig_expected
: Expectation
<'tcx
>,
58 match_src
: hir
::MatchSource
,
62 use hir
::MatchSource
::*;
63 let (source_if
, if_no_else
, force_scrutinee_bool
) = match match_src
{
64 IfLetDesugar { contains_else_clause, .. }
=> (true, !contains_else_clause
, false),
65 WhileDesugar
=> (false, false, true),
66 _
=> (false, false, false),
69 // Type check the discriminant and get its type.
70 let scrutinee_ty
= if force_scrutinee_bool
{
71 // Here we want to ensure:
73 // 1. That default match bindings are *not* accepted in the condition of an
74 // `if` expression. E.g. given `fn foo() -> &bool;` we reject `if foo() { .. }`.
76 // 2. By expecting `bool` for `expr` we get nice diagnostics for e.g. `if x = y { .. }`.
78 // FIXME(60707): Consider removing hack with principled solution.
79 self.check_expr_has_type_or_error(scrut
, self.tcx
.types
.bool
, |_
| {}
)
81 self.demand_scrutinee_type(scrut
, arms_contain_ref_bindings(arms
), arms
.is_empty())
84 // If there are no arms, that is a diverging match; a special case.
86 self.diverges
.set(self.diverges
.get() | Diverges
::always(expr
.span
));
87 return tcx
.types
.never
;
90 self.warn_arms_when_scrutinee_diverges(arms
, match_src
);
92 // Otherwise, we have to union together the types that the arms produce and so forth.
93 let scrut_diverges
= self.diverges
.replace(Diverges
::Maybe
);
95 // #55810: Type check patterns first so we get types for all bindings.
97 self.check_pat_top(&arm
.pat
, scrutinee_ty
, Some(scrut
.span
), true);
100 // Now typecheck the blocks.
102 // The result of the match is the common supertype of all the
103 // arms. Start out the value as bottom, since it's the, well,
104 // bottom the type lattice, and we'll be moving up the lattice as
105 // we process each arm. (Note that any match with 0 arms is matching
106 // on any empty type and is therefore unreachable; should the flow
107 // of execution reach it, we will panic, so bottom is an appropriate
108 // type in that case)
109 let mut all_arms_diverge
= Diverges
::WarnedAlways
;
111 let expected
= orig_expected
.adjust_for_branches(self);
114 let coerce_first
= match expected
{
115 // We don't coerce to `()` so that if the match expression is a
116 // statement it's branches can have any consistent type. That allows
117 // us to give better error messages (pointing to a usually better
118 // arm for inconsistent arms or to the whole match when a `()` type
120 Expectation
::ExpectHasType(ety
) if ety
!= self.tcx
.mk_unit() => ety
,
121 _
=> self.next_ty_var(TypeVariableOrigin
{
122 kind
: TypeVariableOriginKind
::MiscVariable
,
126 CoerceMany
::with_coercion_sites(coerce_first
, arms
)
129 let mut other_arms
= vec
![]; // Used only for diagnostics.
130 let mut prior_arm_ty
= None
;
131 for (i
, arm
) in arms
.iter().enumerate() {
132 if let Some(g
) = &arm
.guard
{
133 self.diverges
.set(Diverges
::Maybe
);
135 hir
::Guard
::If(e
) => {
136 self.check_expr_has_type_or_error(e
, tcx
.types
.bool
, |_
| {}
);
138 hir
::Guard
::IfLet(pat
, e
) => {
139 let scrutinee_ty
= self.demand_scrutinee_type(
141 pat
.contains_explicit_ref_binding(),
144 self.check_pat_top(&pat
, scrutinee_ty
, None
, true);
149 self.diverges
.set(Diverges
::Maybe
);
150 let arm_ty
= if source_if
153 && self.if_fallback_coercion(
157 |hir_id
, span
| self.maybe_get_coercion_reason(hir_id
, span
),
161 // Only call this if this is not an `if` expr with an expected type and no `else`
162 // clause to avoid duplicated type errors. (#60254)
163 self.check_expr_with_expectation(&arm
.body
, expected
)
165 all_arms_diverge
&= self.diverges
.get();
167 let opt_suggest_box_span
=
168 self.opt_suggest_box_span(arm
.body
.span
, arm_ty
, orig_expected
);
171 let then_expr
= &arms
[0].body
;
172 match (i
, if_no_else
) {
173 (0, _
) => coercion
.coerce(self, &self.misc(expr
.span
), &arm
.body
, arm_ty
),
174 (_
, true) => {}
// Handled above to avoid duplicated type errors (#60254).
176 let then_ty
= prior_arm_ty
.unwrap();
177 let cause
= self.if_cause(
183 opt_suggest_box_span
,
185 coercion
.coerce(self, &cause
, &arm
.body
, arm_ty
);
189 let (arm_span
, semi_span
) =
190 self.get_appropriate_arm_semicolon_removal_span(&arms
, i
, prior_arm_ty
, arm_ty
);
191 let (span
, code
) = match i
{
192 // The reason for the first arm to fail is not that the match arms diverge,
193 // but rather that there's a prior obligation that doesn't hold.
194 0 => (arm_span
, ObligationCauseCode
::BlockTailExpression(arm
.body
.hir_id
)),
197 ObligationCauseCode
::MatchExpressionArm(box MatchExpressionArmCause
{
199 scrut_span
: scrut
.span
,
202 prior_arms
: other_arms
.clone(),
203 last_ty
: prior_arm_ty
.unwrap(),
204 scrut_hir_id
: scrut
.hir_id
,
205 opt_suggest_box_span
,
209 let cause
= self.cause(span
, code
);
211 // This is the moral equivalent of `coercion.coerce(self, cause, arm.body, arm_ty)`.
212 // We use it this way to be able to expand on the potential error and detect when a
213 // `match` tail statement could be a tail expression instead. If so, we suggest
214 // removing the stray semicolon.
215 coercion
.coerce_inner(
220 Some(&mut |err
: &mut DiagnosticBuilder
<'_
>| {
221 let can_coerce_to_return_ty
= match self.ret_coercion
.as_ref() {
222 Some(ret_coercion
) if self.in_tail_expr
=> {
223 let ret_ty
= ret_coercion
.borrow().expected_ty();
224 let ret_ty
= self.inh
.infcx
.shallow_resolve(ret_ty
);
225 self.can_coerce(arm_ty
, ret_ty
)
226 && prior_arm_ty
.map_or(true, |t
| self.can_coerce(t
, ret_ty
))
227 // The match arms need to unify for the case of `impl Trait`.
228 && !matches
!(ret_ty
.kind(), ty
::Opaque(..))
232 if let (Expectation
::IsLast(stmt
), Some(ret
), true) =
233 (orig_expected
, self.ret_type_span
, can_coerce_to_return_ty
)
235 let semi_span
= expr
.span
.shrink_to_hi().with_hi(stmt
.hi());
236 let mut ret_span
: MultiSpan
= semi_span
.into();
237 ret_span
.push_span_label(
239 "this could be implicitly returned but it is a statement, not a \
243 ret_span
.push_span_label(
245 "the `match` arms can conform to this return type".to_owned(),
247 ret_span
.push_span_label(
249 "the `match` is a statement because of this semicolon, consider \
255 "you might have meant to return the `match` expression",
257 err
.tool_only_span_suggestion(
259 "remove this semicolon",
261 Applicability
::MaybeIncorrect
,
268 other_arms
.push(arm_span
);
269 if other_arms
.len() > 5 {
270 other_arms
.remove(0);
273 prior_arm_ty
= Some(arm_ty
);
276 // If all of the arms in the `match` diverge,
277 // and we're dealing with an actual `match` block
278 // (as opposed to a `match` desugared from something else'),
279 // we can emit a better note. Rather than pointing
280 // at a diverging expression in an arbitrary arm,
281 // we can point at the entire `match` expression
282 if let (Diverges
::Always { .. }
, hir
::MatchSource
::Normal
) = (all_arms_diverge
, match_src
) {
283 all_arms_diverge
= Diverges
::Always
{
286 "any code following this `match` expression is unreachable, as all arms diverge",
291 // We won't diverge unless the scrutinee or all arms diverge.
292 self.diverges
.set(scrut_diverges
| all_arms_diverge
);
294 coercion
.complete(self)
297 fn get_appropriate_arm_semicolon_removal_span(
299 arms
: &'tcx
[hir
::Arm
<'tcx
>],
301 prior_arm_ty
: Option
<Ty
<'tcx
>>,
303 ) -> (Span
, Option
<(Span
, StatementAsExpression
)>) {
305 let (arm_span
, mut semi_span
) = if let hir
::ExprKind
::Block(blk
, _
) = &arm
.body
.kind
{
306 self.find_block_span(blk
, prior_arm_ty
)
308 (arm
.body
.span
, None
)
310 if semi_span
.is_none() && i
> 0 {
311 if let hir
::ExprKind
::Block(blk
, _
) = &arms
[i
- 1].body
.kind
{
312 let (_
, semi_span_prev
) = self.find_block_span(blk
, Some(arm_ty
));
313 semi_span
= semi_span_prev
;
316 (arm_span
, semi_span
)
319 /// When the previously checked expression (the scrutinee) diverges,
320 /// warn the user about the match arms being unreachable.
321 fn warn_arms_when_scrutinee_diverges(
323 arms
: &'tcx
[hir
::Arm
<'tcx
>],
324 source
: hir
::MatchSource
,
326 use hir
::MatchSource
::*;
327 let msg
= match source
{
328 IfLetDesugar { .. }
=> "block in `if` expression",
329 WhileDesugar { .. }
| WhileLetDesugar { .. }
=> "block in `while` expression",
333 self.warn_if_unreachable(arm
.body
.hir_id
, arm
.body
.span
, msg
);
337 /// Handle the fallback arm of a desugared if(-let) like a missing else.
339 /// Returns `true` if there was an error forcing the coercion to the `()` type.
340 pub(crate) fn if_fallback_coercion
<F
, T
>(
343 then_expr
: &'tcx hir
::Expr
<'tcx
>,
344 coercion
: &mut CoerceMany
<'tcx
, '_
, T
>,
348 F
: Fn(hir
::HirId
, Span
) -> Option
<(Span
, String
)>,
351 // If this `if` expr is the parent's function return expr,
352 // the cause of the type coercion is the return type, point at it. (#25228)
353 let ret_reason
= ret_reason(then_expr
.hir_id
, span
);
354 let cause
= self.cause(span
, ObligationCauseCode
::IfExpressionWithNoElse
);
355 let mut error
= false;
356 coercion
.coerce_forced_unit(
360 if let Some((span
, msg
)) = &ret_reason
{
361 err
.span_label(*span
, msg
.as_str());
362 } else if let ExprKind
::Block(block
, _
) = &then_expr
.kind
{
363 if let Some(expr
) = &block
.expr
{
364 err
.span_label(expr
.span
, "found here".to_string());
367 err
.note("`if` expressions without `else` evaluate to `()`");
368 err
.help("consider adding an `else` block that evaluates to the expected type");
371 ret_reason
.is_none(),
376 create_maybe_get_coercion_reason
!(
377 maybe_get_coercion_reason
,
378 |hir
: rustc_middle
::hir
::map
::Map
<'a
>, id
| {
379 let arm_id
= hir
.get_parent_node(id
);
380 let match_id
= hir
.get_parent_node(arm_id
);
381 let containing_id
= hir
.get_parent_node(match_id
);
382 hir
.get(containing_id
)
386 create_maybe_get_coercion_reason
!(
387 maybe_get_coercion_reason_if
,
388 |hir
: rustc_middle
::hir
::map
::Map
<'a
>, id
| {
389 let rslt
= hir
.get_parent_node(hir
.get_parent_node(id
));
394 pub(crate) fn if_cause(
397 then_expr
: &'tcx hir
::Expr
<'tcx
>,
398 else_expr
: &'tcx hir
::Expr
<'tcx
>,
401 opt_suggest_box_span
: Option
<Span
>,
402 ) -> ObligationCause
<'tcx
> {
403 let mut outer_sp
= if self.tcx
.sess
.source_map().is_multiline(span
) {
404 // The `if`/`else` isn't in one line in the output, include some context to make it
405 // clear it is an if/else expression:
407 // LL | let x = if true {
410 // || ----- expected because of this
413 // || ^^^^^ expected `i32`, found `u32`
415 // ||_____- `if` and `else` have incompatible types
419 // The entire expression is in one line, only point at the arms
421 // LL | let x = if true { 10i32 } else { 10u32 };
422 // | ----- ^^^^^ expected `i32`, found `u32`
424 // | expected because of this
429 let mut remove_semicolon
= None
;
430 let error_sp
= if let ExprKind
::Block(block
, _
) = &else_expr
.kind
{
431 let (error_sp
, semi_sp
) = self.find_block_span(block
, Some(then_ty
));
432 remove_semicolon
= semi_sp
;
433 if block
.expr
.is_none() && block
.stmts
.is_empty() {
434 // Avoid overlapping spans that aren't as readable:
436 // 2 | let x = if true {
439 // | | - expected because of this
446 // | |______if and else have incompatible types
447 // | expected integer, found `()`
449 // by not pointing at the entire expression:
451 // 2 | let x = if true {
452 // | ------- `if` and `else` have incompatible types
454 // | - expected because of this
459 // | |_____^ expected integer, found `()`
461 if outer_sp
.is_some() {
462 outer_sp
= Some(self.tcx
.sess
.source_map().guess_head_span(span
));
467 // shouldn't happen unless the parser has done something weird
471 // Compute `Span` of `then` part of `if`-expression.
472 let then_sp
= if let ExprKind
::Block(block
, _
) = &then_expr
.kind
{
473 let (then_sp
, semi_sp
) = self.find_block_span(block
, Some(else_ty
));
474 remove_semicolon
= remove_semicolon
.or(semi_sp
);
475 if block
.expr
.is_none() && block
.stmts
.is_empty() {
476 outer_sp
= None
; // same as in `error_sp`; cleanup output
480 // shouldn't happen unless the parser has done something weird
484 // Finally construct the cause:
487 ObligationCauseCode
::IfExpression(box IfExpressionCause
{
491 semicolon
: remove_semicolon
,
492 opt_suggest_box_span
,
497 fn demand_scrutinee_type(
499 scrut
: &'tcx hir
::Expr
<'tcx
>,
500 contains_ref_bindings
: Option
<hir
::Mutability
>,
503 // Not entirely obvious: if matches may create ref bindings, we want to
504 // use the *precise* type of the scrutinee, *not* some supertype, as
505 // the "scrutinee type" (issue #23116).
507 // arielb1 [writes here in this comment thread][c] that there
508 // is certainly *some* potential danger, e.g., for an example
511 // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
514 // let Foo(x) = f()[0];
517 // Then if the pattern matches by reference, we want to match
518 // `f()[0]` as a lexpr, so we can't allow it to be
519 // coerced. But if the pattern matches by value, `f()[0]` is
520 // still syntactically a lexpr, but we *do* want to allow
523 // However, *likely* we are ok with allowing coercions to
524 // happen if there are no explicit ref mut patterns - all
525 // implicit ref mut patterns must occur behind a reference, so
526 // they will have the "correct" variance and lifetime.
528 // This does mean that the following pattern would be legal:
533 // impl Deref for Foo {
534 // type Target = Bar;
535 // fn deref(&self) -> &Bar { &self.0 }
537 // impl DerefMut for Foo {
538 // fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
540 // fn foo(x: &mut Foo) {
542 // let Bar(z): &mut Bar = x;
545 // assert_eq!(foo.0.0, 42);
549 // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
550 // is problematic as the HIR is being scraped, but ref bindings may be
551 // implicit after #42640. We need to make sure that pat_adjustments
552 // (once introduced) is populated by the time we get here.
555 if let Some(m
) = contains_ref_bindings
{
556 self.check_expr_with_needs(scrut
, Needs
::maybe_mut_place(m
))
558 self.check_expr(scrut
)
560 // ...but otherwise we want to use any supertype of the
561 // scrutinee. This is sort of a workaround, see note (*) in
562 // `check_pat` for some details.
563 let scrut_ty
= self.next_ty_var(TypeVariableOrigin
{
564 kind
: TypeVariableOriginKind
::TypeInference
,
567 self.check_expr_has_type_or_error(scrut
, scrut_ty
, |_
| {}
);
574 block
: &'tcx hir
::Block
<'tcx
>,
575 expected_ty
: Option
<Ty
<'tcx
>>,
576 ) -> (Span
, Option
<(Span
, StatementAsExpression
)>) {
577 if let Some(expr
) = &block
.expr
{
579 } else if let Some(stmt
) = block
.stmts
.last() {
580 // possibly incorrect trailing `;` in the else arm
581 (stmt
.span
, expected_ty
.and_then(|ty
| self.could_remove_semicolon(block
, ty
)))
583 // empty block; point at its entirety
588 // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait`
589 // we check if the different arms would work with boxed trait objects instead and
590 // provide a structured suggestion in that case.
591 pub(crate) fn opt_suggest_box_span(
594 outer_ty
: &'tcx TyS
<'tcx
>,
595 orig_expected
: Expectation
<'tcx
>,
597 match (orig_expected
, self.ret_coercion_impl_trait
.map(|ty
| (self.body_id
.owner
, ty
))) {
598 (Expectation
::ExpectHasType(expected
), Some((id
, ty
)))
599 if self.in_tail_expr
&& self.can_coerce(outer_ty
, expected
) =>
601 let impl_trait_ret_ty
=
602 self.infcx
.instantiate_opaque_types(id
, self.body_id
, self.param_env
, ty
, span
);
603 let mut suggest_box
= !impl_trait_ret_ty
.obligations
.is_empty();
604 for o
in impl_trait_ret_ty
.obligations
{
605 match o
.predicate
.kind().skip_binder() {
606 ty
::PredicateKind
::Trait(t
, constness
) => {
607 let pred
= ty
::PredicateKind
::Trait(
609 trait_ref
: ty
::TraitRef
{
611 substs
: self.infcx
.tcx
.mk_substs_trait(outer_ty
, &[]),
616 let obl
= Obligation
::new(
619 pred
.to_predicate(self.infcx
.tcx
),
621 suggest_box
&= self.infcx
.predicate_must_hold_modulo_regions(&obl
);
623 // We've encountered some obligation that didn't hold, so the
624 // return expression can't just be boxed. We don't need to
625 // evaluate the rest of the obligations.
632 // If all the obligations hold (or there are no obligations) the tail expression
633 // we can suggest to return a boxed trait object instead of an opaque type.
634 if suggest_box { self.ret_type_span }
else { None }
641 fn arms_contain_ref_bindings(arms
: &'tcx
[hir
::Arm
<'tcx
>]) -> Option
<hir
::Mutability
> {
642 arms
.iter().filter_map(|a
| a
.pat
.contains_explicit_ref_binding()).max_by_key(|m
| match *m
{
643 hir
::Mutability
::Mut
=> 1,
644 hir
::Mutability
::Not
=> 0,