]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/_match.rs
Remove non-descriptive boolean from search_for_structural_match_violation
[rust.git] / compiler / rustc_typeck / src / check / _match.rs
1 use crate::check::coercion::{AsCoercionSite, CoerceMany};
2 use crate::check::{Diverges, Expectation, FnCtxt, Needs};
3 use rustc_errors::{Applicability, 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, TypeVisitable};
8 use rustc_span::Span;
9 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
10 use rustc_trait_selection::traits::{
11     IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
12 };
13
14 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15     #[instrument(skip(self), level = "debug")]
16     pub fn check_match(
17         &self,
18         expr: &'tcx hir::Expr<'tcx>,
19         scrut: &'tcx hir::Expr<'tcx>,
20         arms: &'tcx [hir::Arm<'tcx>],
21         orig_expected: Expectation<'tcx>,
22         match_src: hir::MatchSource,
23     ) -> Ty<'tcx> {
24         let tcx = self.tcx;
25
26         let acrb = arms_contain_ref_bindings(arms);
27         let scrutinee_ty = self.demand_scrutinee_type(scrut, acrb, arms.is_empty());
28         debug!(?scrutinee_ty);
29
30         // If there are no arms, that is a diverging match; a special case.
31         if arms.is_empty() {
32             self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
33             return tcx.types.never;
34         }
35
36         self.warn_arms_when_scrutinee_diverges(arms);
37
38         // Otherwise, we have to union together the types that the arms produce and so forth.
39         let scrut_diverges = self.diverges.replace(Diverges::Maybe);
40
41         // #55810: Type check patterns first so we get types for all bindings.
42         for arm in arms {
43             self.check_pat_top(&arm.pat, scrutinee_ty, Some(scrut.span), true);
44         }
45
46         // Now typecheck the blocks.
47         //
48         // The result of the match is the common supertype of all the
49         // arms. Start out the value as bottom, since it's the, well,
50         // bottom the type lattice, and we'll be moving up the lattice as
51         // we process each arm. (Note that any match with 0 arms is matching
52         // on any empty type and is therefore unreachable; should the flow
53         // of execution reach it, we will panic, so bottom is an appropriate
54         // type in that case)
55         let mut all_arms_diverge = Diverges::WarnedAlways;
56
57         let expected = orig_expected.adjust_for_branches(self);
58         debug!(?expected);
59
60         let mut coercion = {
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
66                 // is required).
67                 Expectation::ExpectHasType(ety) if ety != self.tcx.mk_unit() => ety,
68                 _ => self.next_ty_var(TypeVariableOrigin {
69                     kind: TypeVariableOriginKind::MiscVariable,
70                     span: expr.span,
71                 }),
72             };
73             CoerceMany::with_coercion_sites(coerce_first, arms)
74         };
75
76         let mut other_arms = vec![]; // Used only for diagnostics.
77         let mut prior_arm = None;
78         for arm in arms {
79             if let Some(g) = &arm.guard {
80                 self.diverges.set(Diverges::Maybe);
81                 match g {
82                     hir::Guard::If(e) => {
83                         self.check_expr_has_type_or_error(e, tcx.types.bool, |_| {});
84                     }
85                     hir::Guard::IfLet(l) => {
86                         self.check_expr_let(l);
87                     }
88                 };
89             }
90
91             self.diverges.set(Diverges::Maybe);
92
93             let arm_ty = self.check_expr_with_expectation(&arm.body, expected);
94             all_arms_diverge &= self.diverges.get();
95
96             let opt_suggest_box_span = self.opt_suggest_box_span(arm_ty, orig_expected);
97
98             let (arm_block_id, arm_span) = if let hir::ExprKind::Block(blk, _) = arm.body.kind {
99                 (Some(blk.hir_id), self.find_block_span(blk))
100             } else {
101                 (None, arm.body.span)
102             };
103
104             let (span, code) = match prior_arm {
105                 // The reason for the first arm to fail is not that the match arms diverge,
106                 // but rather that there's a prior obligation that doesn't hold.
107                 None => (arm_span, ObligationCauseCode::BlockTailExpression(arm.body.hir_id)),
108                 Some((prior_arm_block_id, prior_arm_ty, prior_arm_span)) => (
109                     expr.span,
110                     ObligationCauseCode::MatchExpressionArm(Box::new(MatchExpressionArmCause {
111                         arm_block_id,
112                         arm_span,
113                         arm_ty,
114                         prior_arm_block_id,
115                         prior_arm_ty,
116                         prior_arm_span,
117                         scrut_span: scrut.span,
118                         source: match_src,
119                         prior_arms: other_arms.clone(),
120                         scrut_hir_id: scrut.hir_id,
121                         opt_suggest_box_span,
122                     })),
123                 ),
124             };
125             let cause = self.cause(span, code);
126
127             // This is the moral equivalent of `coercion.coerce(self, cause, arm.body, arm_ty)`.
128             // We use it this way to be able to expand on the potential error and detect when a
129             // `match` tail statement could be a tail expression instead. If so, we suggest
130             // removing the stray semicolon.
131             coercion.coerce_inner(
132                 self,
133                 &cause,
134                 Some(&arm.body),
135                 arm_ty,
136                 Some(&mut |err| {
137                     let Some(ret) = self.ret_type_span else {
138                         return;
139                     };
140                     let Expectation::IsLast(stmt) = orig_expected else {
141                         return
142                     };
143                     let can_coerce_to_return_ty = match self.ret_coercion.as_ref() {
144                         Some(ret_coercion) if self.in_tail_expr => {
145                             let ret_ty = ret_coercion.borrow().expected_ty();
146                             let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
147                             self.can_coerce(arm_ty, ret_ty)
148                                 && prior_arm.map_or(true, |(_, t, _)| self.can_coerce(t, ret_ty))
149                                 // The match arms need to unify for the case of `impl Trait`.
150                                 && !matches!(ret_ty.kind(), ty::Opaque(..))
151                         }
152                         _ => false,
153                     };
154                     if !can_coerce_to_return_ty {
155                         return;
156                     }
157
158                     let semi_span = expr.span.shrink_to_hi().with_hi(stmt.hi());
159                     let mut ret_span: MultiSpan = semi_span.into();
160                     ret_span.push_span_label(
161                         expr.span,
162                         "this could be implicitly returned but it is a statement, not a \
163                             tail expression",
164                     );
165                     ret_span
166                         .push_span_label(ret, "the `match` arms can conform to this return type");
167                     ret_span.push_span_label(
168                         semi_span,
169                         "the `match` is a statement because of this semicolon, consider \
170                             removing it",
171                     );
172                     err.span_note(
173                         ret_span,
174                         "you might have meant to return the `match` expression",
175                     );
176                     err.tool_only_span_suggestion(
177                         semi_span,
178                         "remove this semicolon",
179                         "",
180                         Applicability::MaybeIncorrect,
181                     );
182                 }),
183                 false,
184             );
185
186             other_arms.push(arm_span);
187             if other_arms.len() > 5 {
188                 other_arms.remove(0);
189             }
190
191             prior_arm = Some((arm_block_id, arm_ty, arm_span));
192         }
193
194         // If all of the arms in the `match` diverge,
195         // and we're dealing with an actual `match` block
196         // (as opposed to a `match` desugared from something else'),
197         // we can emit a better note. Rather than pointing
198         // at a diverging expression in an arbitrary arm,
199         // we can point at the entire `match` expression
200         if let (Diverges::Always { .. }, hir::MatchSource::Normal) = (all_arms_diverge, match_src) {
201             all_arms_diverge = Diverges::Always {
202                 span: expr.span,
203                 custom_note: Some(
204                     "any code following this `match` expression is unreachable, as all arms diverge",
205                 ),
206             };
207         }
208
209         // We won't diverge unless the scrutinee or all arms diverge.
210         self.diverges.set(scrut_diverges | all_arms_diverge);
211
212         let match_ty = coercion.complete(self);
213         debug!(?match_ty);
214         match_ty
215     }
216
217     /// When the previously checked expression (the scrutinee) diverges,
218     /// warn the user about the match arms being unreachable.
219     fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [hir::Arm<'tcx>]) {
220         for arm in arms {
221             self.warn_if_unreachable(arm.body.hir_id, arm.body.span, "arm");
222         }
223     }
224
225     /// Handle the fallback arm of a desugared if(-let) like a missing else.
226     ///
227     /// Returns `true` if there was an error forcing the coercion to the `()` type.
228     pub(super) fn if_fallback_coercion<T>(
229         &self,
230         span: Span,
231         then_expr: &'tcx hir::Expr<'tcx>,
232         coercion: &mut CoerceMany<'tcx, '_, T>,
233     ) -> bool
234     where
235         T: AsCoercionSite,
236     {
237         // If this `if` expr is the parent's function return expr,
238         // the cause of the type coercion is the return type, point at it. (#25228)
239         let ret_reason = self.maybe_get_coercion_reason(then_expr.hir_id, span);
240         let cause = self.cause(span, ObligationCauseCode::IfExpressionWithNoElse);
241         let mut error = false;
242         coercion.coerce_forced_unit(
243             self,
244             &cause,
245             &mut |err| {
246                 if let Some((span, msg)) = &ret_reason {
247                     err.span_label(*span, msg);
248                 } else if let ExprKind::Block(block, _) = &then_expr.kind
249                     && let Some(expr) = &block.expr
250                 {
251                     err.span_label(expr.span, "found here");
252                 }
253                 err.note("`if` expressions without `else` evaluate to `()`");
254                 err.help("consider adding an `else` block that evaluates to the expected type");
255                 error = true;
256             },
257             ret_reason.is_none(),
258         );
259         error
260     }
261
262     fn maybe_get_coercion_reason(&self, hir_id: hir::HirId, sp: Span) -> Option<(Span, String)> {
263         let node = {
264             let rslt = self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(hir_id));
265             self.tcx.hir().get(rslt)
266         };
267         if let hir::Node::Block(block) = node {
268             // check that the body's parent is an fn
269             let parent = self
270                 .tcx
271                 .hir()
272                 .get(self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(block.hir_id)));
273             if let (Some(expr), hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })) =
274                 (&block.expr, parent)
275             {
276                 // check that the `if` expr without `else` is the fn body's expr
277                 if expr.span == sp {
278                     return self.get_fn_decl(hir_id).and_then(|(fn_decl, _)| {
279                         let span = fn_decl.output.span();
280                         let snippet = self.tcx.sess.source_map().span_to_snippet(span).ok()?;
281                         Some((span, format!("expected `{snippet}` because of this return type")))
282                     });
283                 }
284             }
285         }
286         if let hir::Node::Local(hir::Local { ty: Some(_), pat, .. }) = node {
287             return Some((pat.span, "expected because of this assignment".to_string()));
288         }
289         None
290     }
291
292     pub(crate) fn if_cause(
293         &self,
294         span: Span,
295         then_expr: &'tcx hir::Expr<'tcx>,
296         else_expr: &'tcx hir::Expr<'tcx>,
297         then_ty: Ty<'tcx>,
298         else_ty: Ty<'tcx>,
299         opt_suggest_box_span: Option<Span>,
300     ) -> ObligationCause<'tcx> {
301         let mut outer_span = if self.tcx.sess.source_map().is_multiline(span) {
302             // The `if`/`else` isn't in one line in the output, include some context to make it
303             // clear it is an if/else expression:
304             // ```
305             // LL |      let x = if true {
306             //    | _____________-
307             // LL ||         10i32
308             //    ||         ----- expected because of this
309             // LL ||     } else {
310             // LL ||         10u32
311             //    ||         ^^^^^ expected `i32`, found `u32`
312             // LL ||     };
313             //    ||_____- `if` and `else` have incompatible types
314             // ```
315             Some(span)
316         } else {
317             // The entire expression is in one line, only point at the arms
318             // ```
319             // LL |     let x = if true { 10i32 } else { 10u32 };
320             //    |                       -----          ^^^^^ expected `i32`, found `u32`
321             //    |                       |
322             //    |                       expected because of this
323             // ```
324             None
325         };
326
327         let (error_sp, else_id) = if let ExprKind::Block(block, _) = &else_expr.kind {
328             let block = block.innermost_block();
329
330             // Avoid overlapping spans that aren't as readable:
331             // ```
332             // 2 |        let x = if true {
333             //   |   _____________-
334             // 3 |  |         3
335             //   |  |         - expected because of this
336             // 4 |  |     } else {
337             //   |  |____________^
338             // 5 | ||
339             // 6 | ||     };
340             //   | ||     ^
341             //   | ||_____|
342             //   | |______if and else have incompatible types
343             //   |        expected integer, found `()`
344             // ```
345             // by not pointing at the entire expression:
346             // ```
347             // 2 |       let x = if true {
348             //   |               ------- `if` and `else` have incompatible types
349             // 3 |           3
350             //   |           - expected because of this
351             // 4 |       } else {
352             //   |  ____________^
353             // 5 | |
354             // 6 | |     };
355             //   | |_____^ expected integer, found `()`
356             // ```
357             if block.expr.is_none() && block.stmts.is_empty()
358                 && let Some(outer_span) = &mut outer_span
359             {
360                 *outer_span = self.tcx.sess.source_map().guess_head_span(*outer_span);
361             }
362
363             (self.find_block_span(block), block.hir_id)
364         } else {
365             (else_expr.span, else_expr.hir_id)
366         };
367
368         let then_id = if let ExprKind::Block(block, _) = &then_expr.kind {
369             let block = block.innermost_block();
370             // Exclude overlapping spans
371             if block.expr.is_none() && block.stmts.is_empty() {
372                 outer_span = None;
373             }
374             block.hir_id
375         } else {
376             then_expr.hir_id
377         };
378
379         // Finally construct the cause:
380         self.cause(
381             error_sp,
382             ObligationCauseCode::IfExpression(Box::new(IfExpressionCause {
383                 else_id,
384                 then_id,
385                 then_ty,
386                 else_ty,
387                 outer_span,
388                 opt_suggest_box_span,
389             })),
390         )
391     }
392
393     pub(super) fn demand_scrutinee_type(
394         &self,
395         scrut: &'tcx hir::Expr<'tcx>,
396         contains_ref_bindings: Option<hir::Mutability>,
397         no_arms: bool,
398     ) -> Ty<'tcx> {
399         // Not entirely obvious: if matches may create ref bindings, we want to
400         // use the *precise* type of the scrutinee, *not* some supertype, as
401         // the "scrutinee type" (issue #23116).
402         //
403         // arielb1 [writes here in this comment thread][c] that there
404         // is certainly *some* potential danger, e.g., for an example
405         // like:
406         //
407         // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956
408         //
409         // ```
410         // let Foo(x) = f()[0];
411         // ```
412         //
413         // Then if the pattern matches by reference, we want to match
414         // `f()[0]` as a lexpr, so we can't allow it to be
415         // coerced. But if the pattern matches by value, `f()[0]` is
416         // still syntactically a lexpr, but we *do* want to allow
417         // coercions.
418         //
419         // However, *likely* we are ok with allowing coercions to
420         // happen if there are no explicit ref mut patterns - all
421         // implicit ref mut patterns must occur behind a reference, so
422         // they will have the "correct" variance and lifetime.
423         //
424         // This does mean that the following pattern would be legal:
425         //
426         // ```
427         // struct Foo(Bar);
428         // struct Bar(u32);
429         // impl Deref for Foo {
430         //     type Target = Bar;
431         //     fn deref(&self) -> &Bar { &self.0 }
432         // }
433         // impl DerefMut for Foo {
434         //     fn deref_mut(&mut self) -> &mut Bar { &mut self.0 }
435         // }
436         // fn foo(x: &mut Foo) {
437         //     {
438         //         let Bar(z): &mut Bar = x;
439         //         *z = 42;
440         //     }
441         //     assert_eq!(foo.0.0, 42);
442         // }
443         // ```
444         //
445         // FIXME(tschottdorf): don't call contains_explicit_ref_binding, which
446         // is problematic as the HIR is being scraped, but ref bindings may be
447         // implicit after #42640. We need to make sure that pat_adjustments
448         // (once introduced) is populated by the time we get here.
449         //
450         // See #44848.
451         if let Some(m) = contains_ref_bindings {
452             self.check_expr_with_needs(scrut, Needs::maybe_mut_place(m))
453         } else if no_arms {
454             self.check_expr(scrut)
455         } else {
456             // ...but otherwise we want to use any supertype of the
457             // scrutinee. This is sort of a workaround, see note (*) in
458             // `check_pat` for some details.
459             let scrut_ty = self.next_ty_var(TypeVariableOrigin {
460                 kind: TypeVariableOriginKind::TypeInference,
461                 span: scrut.span,
462             });
463             self.check_expr_has_type_or_error(scrut, scrut_ty, |_| {});
464             scrut_ty
465         }
466     }
467
468     // When we have a `match` as a tail expression in a `fn` with a returned `impl Trait`
469     // we check if the different arms would work with boxed trait objects instead and
470     // provide a structured suggestion in that case.
471     pub(crate) fn opt_suggest_box_span(
472         &self,
473         outer_ty: Ty<'tcx>,
474         orig_expected: Expectation<'tcx>,
475     ) -> Option<Span> {
476         match orig_expected {
477             Expectation::ExpectHasType(expected)
478                 if self.in_tail_expr
479                     && self.ret_coercion.as_ref()?.borrow().merged_ty().has_opaque_types()
480                     && self.can_coerce(outer_ty, expected) =>
481             {
482                 let obligations = self.fulfillment_cx.borrow().pending_obligations();
483                 let mut suggest_box = !obligations.is_empty();
484                 for o in obligations {
485                     match o.predicate.kind().skip_binder() {
486                         ty::PredicateKind::Trait(t) => {
487                             let pred =
488                                 ty::Binder::dummy(ty::PredicateKind::Trait(ty::TraitPredicate {
489                                     trait_ref: ty::TraitRef {
490                                         def_id: t.def_id(),
491                                         substs: self.infcx.tcx.mk_substs_trait(outer_ty, &[]),
492                                     },
493                                     constness: t.constness,
494                                     polarity: t.polarity,
495                                 }));
496                             let obl = Obligation::new(
497                                 o.cause.clone(),
498                                 self.param_env,
499                                 pred.to_predicate(self.infcx.tcx),
500                             );
501                             suggest_box &= self.infcx.predicate_must_hold_modulo_regions(&obl);
502                             if !suggest_box {
503                                 // We've encountered some obligation that didn't hold, so the
504                                 // return expression can't just be boxed. We don't need to
505                                 // evaluate the rest of the obligations.
506                                 break;
507                             }
508                         }
509                         _ => {}
510                     }
511                 }
512                 // If all the obligations hold (or there are no obligations) the tail expression
513                 // we can suggest to return a boxed trait object instead of an opaque type.
514                 if suggest_box { self.ret_type_span } else { None }
515             }
516             _ => None,
517         }
518     }
519 }
520
521 fn arms_contain_ref_bindings<'tcx>(arms: &'tcx [hir::Arm<'tcx>]) -> Option<hir::Mutability> {
522     arms.iter().filter_map(|a| a.pat.contains_explicit_ref_binding()).max_by_key(|m| match *m {
523         hir::Mutability::Mut => 1,
524         hir::Mutability::Not => 0,
525     })
526 }