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