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