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