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