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