]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/sub.rs
Replacing bound vars is actually instantiating a binder
[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             (
134                 &ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, .. }),
135                 &ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, .. }),
136             ) if a_def_id == b_def_id => {
137                 self.fields.infcx.super_combine_tys(self, a, b)?;
138                 Ok(a)
139             }
140             (&ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }), _)
141             | (_, &ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }))
142                 if self.fields.define_opaque_types && def_id.is_local() =>
143             {
144                 self.fields.obligations.extend(
145                     infcx
146                         .handle_opaque_type(
147                             a,
148                             b,
149                             self.a_is_expected,
150                             &self.fields.trace.cause,
151                             self.param_env(),
152                         )?
153                         .obligations,
154                 );
155                 Ok(a)
156             }
157             // Optimization of GeneratorWitness relation since we know that all
158             // free regions are replaced with bound regions during construction.
159             // This greatly speeds up subtyping of GeneratorWitness.
160             (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
161                 let a_types = infcx.tcx.anonymize_bound_vars(a_types);
162                 let b_types = infcx.tcx.anonymize_bound_vars(b_types);
163                 if a_types.bound_vars() == b_types.bound_vars() {
164                     let (a_types, b_types) = infcx.instantiate_binder_with_placeholders(
165                         a_types.map_bound(|a_types| (a_types, b_types.skip_binder())),
166                     );
167                     for (a, b) in std::iter::zip(a_types, b_types) {
168                         self.relate(a, b)?;
169                     }
170                     Ok(a)
171                 } else {
172                     Err(ty::error::TypeError::Sorts(ty::relate::expected_found(self, a, b)))
173                 }
174             }
175
176             _ => {
177                 self.fields.infcx.super_combine_tys(self, a, b)?;
178                 Ok(a)
179             }
180         }
181     }
182
183     fn regions(
184         &mut self,
185         a: ty::Region<'tcx>,
186         b: ty::Region<'tcx>,
187     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
188         debug!("{}.regions({:?}, {:?}) self.cause={:?}", self.tag(), a, b, self.fields.cause);
189
190         // FIXME -- we have more fine-grained information available
191         // from the "cause" field, we could perhaps give more tailored
192         // error messages.
193         let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone()));
194         // Subtype(&'a u8, &'b u8) => Outlives('a: 'b) => SubRegion('b, 'a)
195         self.fields
196             .infcx
197             .inner
198             .borrow_mut()
199             .unwrap_region_constraints()
200             .make_subregion(origin, b, a);
201
202         Ok(a)
203     }
204
205     fn consts(
206         &mut self,
207         a: ty::Const<'tcx>,
208         b: ty::Const<'tcx>,
209     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
210         self.fields.infcx.super_combine_consts(self, a, b)
211     }
212
213     fn binders<T>(
214         &mut self,
215         a: ty::Binder<'tcx, T>,
216         b: ty::Binder<'tcx, T>,
217     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
218     where
219         T: Relate<'tcx>,
220     {
221         // A binder is always a subtype of itself if it's structually equal to itself
222         if a == b {
223             return Ok(a);
224         }
225
226         self.fields.higher_ranked_sub(a, b, self.a_is_expected)?;
227         Ok(a)
228     }
229 }
230
231 impl<'tcx> ConstEquateRelation<'tcx> for Sub<'_, '_, 'tcx> {
232     fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>) {
233         self.fields.add_const_equate_obligation(self.a_is_expected, a, b);
234     }
235 }