]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/sub.rs
Use "must be init" instead of "must not be uninit" everywhere
[rust.git] / compiler / rustc_infer / src / infer / sub.rs
1 use super::combine::{CombineFields, RelationDir};
2 use super::SubregionOrigin;
3
4 use crate::infer::combine::ConstEquateRelation;
5 use crate::traits::Obligation;
6 use rustc_middle::ty::relate::{Cause, Relate, RelateResult, TypeRelation};
7 use rustc_middle::ty::visit::TypeVisitable;
8 use rustc_middle::ty::TyVar;
9 use rustc_middle::ty::{self, Ty, TyCtxt};
10 use std::mem;
11
12 /// Ensures `a` is made a subtype of `b`. Returns `a` on success.
13 pub struct Sub<'combine, 'a, 'tcx> {
14     fields: &'combine mut CombineFields<'a, 'tcx>,
15     a_is_expected: bool,
16 }
17
18 impl<'combine, 'infcx, 'tcx> Sub<'combine, 'infcx, 'tcx> {
19     pub fn new(
20         f: &'combine mut CombineFields<'infcx, 'tcx>,
21         a_is_expected: bool,
22     ) -> Sub<'combine, 'infcx, 'tcx> {
23         Sub { fields: f, a_is_expected }
24     }
25
26     fn with_expected_switched<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
27         self.a_is_expected = !self.a_is_expected;
28         let result = f(self);
29         self.a_is_expected = !self.a_is_expected;
30         result
31     }
32 }
33
34 impl<'tcx> TypeRelation<'tcx> for Sub<'_, '_, 'tcx> {
35     fn tag(&self) -> &'static str {
36         "Sub"
37     }
38
39     fn intercrate(&self) -> bool {
40         self.fields.infcx.intercrate
41     }
42
43     fn tcx(&self) -> TyCtxt<'tcx> {
44         self.fields.infcx.tcx
45     }
46
47     fn param_env(&self) -> ty::ParamEnv<'tcx> {
48         self.fields.param_env
49     }
50
51     fn a_is_expected(&self) -> bool {
52         self.a_is_expected
53     }
54
55     fn mark_ambiguous(&mut self) {
56         self.fields.mark_ambiguous()
57     }
58
59     fn with_cause<F, R>(&mut self, cause: Cause, f: F) -> R
60     where
61         F: FnOnce(&mut Self) -> R,
62     {
63         debug!("sub with_cause={:?}", cause);
64         let old_cause = mem::replace(&mut self.fields.cause, Some(cause));
65         let r = f(self);
66         debug!("sub old_cause={:?}", old_cause);
67         self.fields.cause = old_cause;
68         r
69     }
70
71     fn relate_with_variance<T: Relate<'tcx>>(
72         &mut self,
73         variance: ty::Variance,
74         _info: ty::VarianceDiagInfo<'tcx>,
75         a: T,
76         b: T,
77     ) -> RelateResult<'tcx, T> {
78         match variance {
79             ty::Invariant => self.fields.equate(self.a_is_expected).relate(a, b),
80             ty::Covariant => self.relate(a, b),
81             ty::Bivariant => Ok(a),
82             ty::Contravariant => self.with_expected_switched(|this| this.relate(b, a)),
83         }
84     }
85
86     #[instrument(skip(self), level = "debug")]
87     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
88         if a == b {
89             return Ok(a);
90         }
91
92         let infcx = self.fields.infcx;
93         let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a);
94         let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b);
95
96         match (a.kind(), b.kind()) {
97             (&ty::Infer(TyVar(_)), &ty::Infer(TyVar(_))) => {
98                 // Shouldn't have any LBR here, so we can safely put
99                 // this under a binder below without fear of accidental
100                 // capture.
101                 assert!(!a.has_escaping_bound_vars());
102                 assert!(!b.has_escaping_bound_vars());
103
104                 // can't make progress on `A <: B` if both A and B are
105                 // type variables, so record an obligation.
106                 self.fields.obligations.push(Obligation::new(
107                     self.tcx(),
108                     self.fields.trace.cause.clone(),
109                     self.fields.param_env,
110                     ty::Binder::dummy(ty::PredicateKind::Subtype(ty::SubtypePredicate {
111                         a_is_expected: self.a_is_expected,
112                         a,
113                         b,
114                     })),
115                 ));
116
117                 Ok(a)
118             }
119             (&ty::Infer(TyVar(a_id)), _) => {
120                 self.fields.instantiate(b, RelationDir::SupertypeOf, a_id, !self.a_is_expected)?;
121                 Ok(a)
122             }
123             (_, &ty::Infer(TyVar(b_id))) => {
124                 self.fields.instantiate(a, RelationDir::SubtypeOf, b_id, self.a_is_expected)?;
125                 Ok(a)
126             }
127
128             (&ty::Error(e), _) | (_, &ty::Error(e)) => {
129                 infcx.set_tainted_by_errors(e);
130                 Ok(self.tcx().ty_error_with_guaranteed(e))
131             }
132
133             (&ty::Opaque(a_def_id, _), &ty::Opaque(b_def_id, _)) if a_def_id == b_def_id => {
134                 self.fields.infcx.super_combine_tys(self, a, b)?;
135                 Ok(a)
136             }
137             (&ty::Opaque(did, ..), _) | (_, &ty::Opaque(did, ..))
138                 if self.fields.define_opaque_types && did.is_local() =>
139             {
140                 self.fields.obligations.extend(
141                     infcx
142                         .handle_opaque_type(
143                             a,
144                             b,
145                             self.a_is_expected,
146                             &self.fields.trace.cause,
147                             self.param_env(),
148                         )?
149                         .obligations,
150                 );
151                 Ok(a)
152             }
153             // Optimization of GeneratorWitness relation since we know that all
154             // free regions are replaced with bound regions during construction.
155             // This greatly speeds up subtyping of GeneratorWitness.
156             (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
157                 let a_types = infcx.tcx.anonymize_bound_vars(a_types);
158                 let b_types = infcx.tcx.anonymize_bound_vars(b_types);
159                 if a_types.bound_vars() == b_types.bound_vars() {
160                     let (a_types, b_types) = infcx.replace_bound_vars_with_placeholders(
161                         a_types.map_bound(|a_types| (a_types, b_types.skip_binder())),
162                     );
163                     for (a, b) in std::iter::zip(a_types, b_types) {
164                         self.relate(a, b)?;
165                     }
166                     Ok(a)
167                 } else {
168                     Err(ty::error::TypeError::Sorts(ty::relate::expected_found(self, a, b)))
169                 }
170             }
171
172             _ => {
173                 self.fields.infcx.super_combine_tys(self, a, b)?;
174                 Ok(a)
175             }
176         }
177     }
178
179     fn regions(
180         &mut self,
181         a: ty::Region<'tcx>,
182         b: ty::Region<'tcx>,
183     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
184         debug!("{}.regions({:?}, {:?}) self.cause={:?}", self.tag(), a, b, self.fields.cause);
185
186         // FIXME -- we have more fine-grained information available
187         // from the "cause" field, we could perhaps give more tailored
188         // error messages.
189         let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone()));
190         self.fields
191             .infcx
192             .inner
193             .borrow_mut()
194             .unwrap_region_constraints()
195             .make_subregion(origin, a, b);
196
197         Ok(a)
198     }
199
200     fn consts(
201         &mut self,
202         a: ty::Const<'tcx>,
203         b: ty::Const<'tcx>,
204     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
205         self.fields.infcx.super_combine_consts(self, a, b)
206     }
207
208     fn binders<T>(
209         &mut self,
210         a: ty::Binder<'tcx, T>,
211         b: ty::Binder<'tcx, T>,
212     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
213     where
214         T: Relate<'tcx>,
215     {
216         self.fields.higher_ranked_sub(a, b, self.a_is_expected)?;
217         Ok(a)
218     }
219 }
220
221 impl<'tcx> ConstEquateRelation<'tcx> for Sub<'_, '_, 'tcx> {
222     fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>) {
223         self.fields.add_const_equate_obligation(self.a_is_expected, a, b);
224     }
225 }