rustc_hir_typeck/
expectation.rs

1use rustc_middle::traits::ObligationCause;
2use rustc_middle::ty::{self, Ty};
3use rustc_span::Span;
4
5use super::Expectation::*;
6use super::FnCtxt;
7
8/// When type-checking an expression, we propagate downward
9/// whatever type hint we are able in the form of an `Expectation`.
10#[derive(Copy, Clone, Debug)]
11pub(crate) enum Expectation<'tcx> {
12    /// We know nothing about what type this expression should have.
13    NoExpectation,
14
15    /// This expression should have the type given (or some subtype).
16    ExpectHasType(Ty<'tcx>),
17
18    /// This expression will be cast to the `Ty`.
19    ExpectCastableToType(Ty<'tcx>),
20
21    /// This rvalue expression will be wrapped in `&` or `Box` and coerced
22    /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
23    ExpectRvalueLikeUnsized(Ty<'tcx>),
24}
25
26impl<'a, 'tcx> Expectation<'tcx> {
27    // Disregard "castable to" expectations because they
28    // can lead us astray. Consider for example `if cond
29    // {22} else {c} as u8` -- if we propagate the
30    // "castable to u8" constraint to 22, it will pick the
31    // type 22u8, which is overly constrained (c might not
32    // be a u8). In effect, the problem is that the
33    // "castable to" expectation is not the tightest thing
34    // we can say, so we want to drop it in this case.
35    // The tightest thing we can say is "must unify with
36    // else branch". Note that in the case of a "has type"
37    // constraint, this limitation does not hold.
38
39    // If the expected type is just a type variable, then don't use
40    // an expected type. Otherwise, we might write parts of the type
41    // when checking the 'then' block which are incompatible with the
42    // 'else' branch.
43    pub(super) fn try_structurally_resolve_and_adjust_for_branches(
44        &self,
45        fcx: &FnCtxt<'a, 'tcx>,
46        span: Span,
47    ) -> Expectation<'tcx> {
48        match *self {
49            ExpectHasType(ety) => {
50                let ety = fcx.try_structurally_resolve_type(span, ety);
51                if !ety.is_ty_var() { ExpectHasType(ety) } else { NoExpectation }
52            }
53            ExpectRvalueLikeUnsized(ety) => ExpectRvalueLikeUnsized(ety),
54            _ => NoExpectation,
55        }
56    }
57
58    /// Provides an expectation for an rvalue expression given an *optional*
59    /// hint, which is not required for type safety (the resulting type might
60    /// be checked higher up, as is the case with `&expr` and `box expr`), but
61    /// is useful in determining the concrete type.
62    ///
63    /// The primary use case is where the expected type is a wide pointer,
64    /// like `&[isize]`. For example, consider the following statement:
65    ///
66    ///    let x: &[isize] = &[1, 2, 3];
67    ///
68    /// In this case, the expected type for the `&[1, 2, 3]` expression is
69    /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
70    /// expectation `ExpectHasType([isize])`, that would be too strong --
71    /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
72    /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
73    /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
74    /// which still is useful, because it informs integer literals and the like.
75    /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
76    /// for examples of where this comes up,.
77    pub(super) fn rvalue_hint(fcx: &FnCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
78        let span = match ty.kind() {
79            ty::Adt(adt_def, _) => fcx.tcx.def_span(adt_def.did()),
80            _ => fcx.tcx.def_span(fcx.body_id),
81        };
82        let cause = ObligationCause::misc(span, fcx.body_id);
83
84        // FIXME: This is not right, even in the old solver...
85        match fcx.tcx.struct_tail_raw(ty, &cause, |ty| ty, || {}).kind() {
86            ty::Slice(_) | ty::Str | ty::Dynamic(..) => ExpectRvalueLikeUnsized(ty),
87            _ => ExpectHasType(ty),
88        }
89    }
90
91    /// Resolves `expected` by a single level if it is a variable. If
92    /// there is no expected type or resolution is not possible (e.g.,
93    /// no constraints yet present), just returns `self`.
94    fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) -> Expectation<'tcx> {
95        match self {
96            NoExpectation => NoExpectation,
97            ExpectCastableToType(t) => ExpectCastableToType(fcx.resolve_vars_if_possible(t)),
98            ExpectHasType(t) => ExpectHasType(fcx.resolve_vars_if_possible(t)),
99            ExpectRvalueLikeUnsized(t) => ExpectRvalueLikeUnsized(fcx.resolve_vars_if_possible(t)),
100        }
101    }
102
103    pub(super) fn to_option(self, fcx: &FnCtxt<'a, 'tcx>) -> Option<Ty<'tcx>> {
104        match self.resolve(fcx) {
105            NoExpectation => None,
106            ExpectCastableToType(ty) | ExpectHasType(ty) | ExpectRvalueLikeUnsized(ty) => Some(ty),
107        }
108    }
109
110    /// It sometimes happens that we want to turn an expectation into
111    /// a **hard constraint** (i.e., something that must be satisfied
112    /// for the program to type-check). `only_has_type` will return
113    /// such a constraint, if it exists.
114    pub(super) fn only_has_type(self, fcx: &FnCtxt<'a, 'tcx>) -> Option<Ty<'tcx>> {
115        match self {
116            ExpectHasType(ty) => Some(fcx.resolve_vars_if_possible(ty)),
117            NoExpectation | ExpectCastableToType(_) | ExpectRvalueLikeUnsized(_) => None,
118        }
119    }
120
121    /// Like `only_has_type`, but instead of returning `None` if no
122    /// hard constraint exists, creates a fresh type variable.
123    pub(super) fn coercion_target_type(self, fcx: &FnCtxt<'a, 'tcx>, span: Span) -> Ty<'tcx> {
124        self.only_has_type(fcx).unwrap_or_else(|| fcx.next_ty_var(span))
125    }
126}