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