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