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