]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_infer/src/infer/combine.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_infer / src / infer / combine.rs
CommitLineData
1a4d82fc
JJ
1///////////////////////////////////////////////////////////////////////////
2// # Type combining
3//
4// There are four type combiners: equate, sub, lub, and glb. Each
5// implements the trait `Combine` and contains methods for combining
6// two instances of various things and yielding a new instance. These
7// combiner methods always yield a `Result<T>`. There is a lot of
8// common code for these operations, implemented as default methods on
9// the `Combine` trait.
10//
11// Each operation may have side-effects on the inference context,
12// though these can be unrolled using snapshots. On success, the
13// LUB/GLB operations return the appropriate bound. The Eq and Sub
14// operations generally return the first operand.
15//
16// ## Contravariance
17//
18// When you are relating two things which have a contravariant
19// relationship, you should use `contratys()` or `contraregions()`,
20// rather than inversing the order of arguments! This is necessary
21// because the order of arguments is not relevant for LUB and GLB. It
22// is also useful to track which value is the "expected" value in
23// terms of error reporting.
24
c295e0f8 25use super::equate::Equate;
1a4d82fc
JJ
26use super::glb::Glb;
27use super::lub::Lub;
28use super::sub::Sub;
0531ce1d 29use super::type_variable::TypeVariableValue;
dfeec247 30use super::unify_key::replace_if_possible;
dc9dc135
XL
31use super::unify_key::{ConstVarValue, ConstVariableValue};
32use super::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
dfeec247 33use super::{InferCtxt, MiscVariable, TypeTrace};
1a4d82fc 34
dfeec247 35use crate::traits::{Obligation, PredicateObligations};
1a4d82fc 36
29967ef6 37use rustc_data_structures::sso::SsoHashMap;
dfeec247 38use rustc_hir::def_id::DefId;
3dfed10e 39use rustc_middle::traits::ObligationCause;
ba9703b0
XL
40use rustc_middle::ty::error::TypeError;
41use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation};
42use rustc_middle::ty::subst::SubstsRef;
f9f354fc 43use rustc_middle::ty::{self, InferConst, ToPredicate, Ty, TyCtxt, TypeFoldable};
ba9703b0 44use rustc_middle::ty::{IntType, UintType};
1b1a35ee 45use rustc_span::{Span, DUMMY_SP};
1a4d82fc 46
1a4d82fc 47#[derive(Clone)]
dc9dc135
XL
48pub struct CombineFields<'infcx, 'tcx> {
49 pub infcx: &'infcx InferCtxt<'infcx, 'tcx>,
1a4d82fc 50 pub trace: TypeTrace<'tcx>,
e9174d1e 51 pub cause: Option<ty::relate::Cause>,
7cac9316 52 pub param_env: ty::ParamEnv<'tcx>,
54a0048b 53 pub obligations: PredicateObligations<'tcx>,
1a4d82fc
JJ
54}
55
e74abb32 56#[derive(Copy, Clone, Debug)]
cc61c64b 57pub enum RelationDir {
dfeec247
XL
58 SubtypeOf,
59 SupertypeOf,
60 EqTo,
cc61c64b
XL
61}
62
dc9dc135
XL
63impl<'infcx, 'tcx> InferCtxt<'infcx, 'tcx> {
64 pub fn super_combine_tys<R>(
65 &self,
66 relation: &mut R,
67 a: Ty<'tcx>,
68 b: Ty<'tcx>,
69 ) -> RelateResult<'tcx, Ty<'tcx>>
70 where
71 R: TypeRelation<'tcx>,
a7813a04
XL
72 {
73 let a_is_expected = relation.a_is_expected();
1a4d82fc 74
1b1a35ee 75 match (a.kind(), b.kind()) {
a7813a04 76 // Relate integral variables to other types
b7449926 77 (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
74b04a01 78 self.inner
a7813a04 79 .borrow_mut()
f9f354fc 80 .int_unification_table()
a7813a04
XL
81 .unify_var_var(a_id, b_id)
82 .map_err(|e| int_unification_error(a_is_expected, e))?;
83 Ok(a)
84 }
b7449926 85 (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
a7813a04
XL
86 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
87 }
b7449926 88 (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
a7813a04
XL
89 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
90 }
b7449926 91 (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
a7813a04
XL
92 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
93 }
b7449926 94 (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
a7813a04
XL
95 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
96 }
1a4d82fc 97
a7813a04 98 // Relate floating-point variables to other types
b7449926 99 (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
74b04a01 100 self.inner
a7813a04 101 .borrow_mut()
f9f354fc 102 .float_unification_table()
a7813a04
XL
103 .unify_var_var(a_id, b_id)
104 .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
105 Ok(a)
106 }
b7449926 107 (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
a7813a04
XL
108 self.unify_float_variable(a_is_expected, v_id, v)
109 }
b7449926 110 (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
a7813a04
XL
111 self.unify_float_variable(!a_is_expected, v_id, v)
112 }
1a4d82fc 113
a7813a04 114 // All other cases of inference are errors
dfeec247 115 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
f035d41b 116 Err(TypeError::Sorts(ty::relate::expected_found(relation, a, b)))
a7813a04 117 }
1a4d82fc 118
dfeec247 119 _ => ty::relate::super_relate_tys(relation, a, b),
1a4d82fc
JJ
120 }
121 }
122
48663c56
XL
123 pub fn super_combine_consts<R>(
124 &self,
125 relation: &mut R,
126 a: &'tcx ty::Const<'tcx>,
127 b: &'tcx ty::Const<'tcx>,
128 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>
129 where
f9f354fc 130 R: ConstEquateRelation<'tcx>,
48663c56 131 {
94222f64
XL
132 let a = self.tcx.expose_default_const_substs(a);
133 let b = self.tcx.expose_default_const_substs(b);
e1599b0c 134 debug!("{}.consts({:?}, {:?})", relation.tag(), a, b);
dfeec247
XL
135 if a == b {
136 return Ok(a);
137 }
e1599b0c 138
f9f354fc
XL
139 let a = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), a);
140 let b = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), b);
e1599b0c 141
48663c56
XL
142 let a_is_expected = relation.a_is_expected();
143
144 match (a.val, b.val) {
dfeec247
XL
145 (
146 ty::ConstKind::Infer(InferConst::Var(a_vid)),
147 ty::ConstKind::Infer(InferConst::Var(b_vid)),
148 ) => {
74b04a01 149 self.inner
48663c56 150 .borrow_mut()
f9f354fc 151 .const_unification_table()
48663c56
XL
152 .unify_var_var(a_vid, b_vid)
153 .map_err(|e| const_unification_error(a_is_expected, e))?;
154 return Ok(a);
155 }
156
157 // All other cases of inference with other variables are errors.
dfeec247
XL
158 (ty::ConstKind::Infer(InferConst::Var(_)), ty::ConstKind::Infer(_))
159 | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(InferConst::Var(_))) => {
60c5eb7d 160 bug!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var)")
48663c56
XL
161 }
162
60c5eb7d 163 (ty::ConstKind::Infer(InferConst::Var(vid)), _) => {
1b1a35ee 164 return self.unify_const_variable(relation.param_env(), vid, b, a_is_expected);
48663c56
XL
165 }
166
60c5eb7d 167 (_, ty::ConstKind::Infer(InferConst::Var(vid))) => {
1b1a35ee 168 return self.unify_const_variable(relation.param_env(), vid, a, !a_is_expected);
48663c56 169 }
f9f354fc 170 (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => {
3dfed10e 171 // FIXME(#59490): Need to remove the leak check to accommodate
f9f354fc
XL
172 // escaping bound variables here.
173 if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
174 relation.const_equate_obligation(a, b);
175 }
176 return Ok(b);
177 }
178 (_, ty::ConstKind::Unevaluated(..)) if self.tcx.lazy_normalization() => {
3dfed10e 179 // FIXME(#59490): Need to remove the leak check to accommodate
f9f354fc
XL
180 // escaping bound variables here.
181 if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() {
182 relation.const_equate_obligation(a, b);
183 }
184 return Ok(a);
185 }
48663c56
XL
186 _ => {}
187 }
188
189 ty::relate::super_relate_consts(relation, a, b)
190 }
191
1b1a35ee
XL
192 /// Unifies the const variable `target_vid` with the given constant.
193 ///
194 /// This also tests if the given const `ct` contains an inference variable which was previously
195 /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct`
cdc7bbd5 196 /// would result in an infinite type as we continuously replace an inference variable
1b1a35ee
XL
197 /// in `ct` with `ct` itself.
198 ///
199 /// This is especially important as unevaluated consts use their parents generics.
200 /// They therefore often contain unused substs, making these errors far more likely.
201 ///
202 /// A good example of this is the following:
203 ///
204 /// ```rust
94222f64 205 /// #![feature(generic_const_exprs)]
1b1a35ee
XL
206 ///
207 /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
208 /// todo!()
209 /// }
210 ///
211 /// fn main() {
212 /// let mut arr = Default::default();
213 /// arr = bind(arr);
214 /// }
215 /// ```
216 ///
217 /// Here `3 + 4` ends up as `ConstKind::Unevaluated` which uses the generics
218 /// of `fn bind` (meaning that its substs contain `N`).
219 ///
220 /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
221 /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
222 ///
223 /// As `3 + 4` contains `N` in its substs, this must not succeed.
224 ///
225 /// See `src/test/ui/const-generics/occurs-check/` for more examples where this is relevant.
6a06907d 226 #[instrument(level = "debug", skip(self))]
1b1a35ee 227 fn unify_const_variable(
48663c56 228 &self,
1b1a35ee
XL
229 param_env: ty::ParamEnv<'tcx>,
230 target_vid: ty::ConstVid<'tcx>,
231 ct: &'tcx ty::Const<'tcx>,
48663c56 232 vid_is_expected: bool,
48663c56 233 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
1b1a35ee
XL
234 let (for_universe, span) = {
235 let mut inner = self.inner.borrow_mut();
236 let variable_table = &mut inner.const_unification_table();
237 let var_value = variable_table.probe_value(target_vid);
238 match var_value.val {
239 ConstVariableValue::Known { value } => {
240 bug!("instantiating {:?} which has a known value {:?}", target_vid, value)
241 }
242 ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span),
243 }
244 };
245 let value = ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid }
246 .relate(ct, ct)?;
247
74b04a01 248 self.inner
48663c56 249 .borrow_mut()
f9f354fc 250 .const_unification_table()
dfeec247 251 .unify_var_value(
1b1a35ee 252 target_vid,
dfeec247
XL
253 ConstVarValue {
254 origin: ConstVariableOrigin {
255 kind: ConstVariableOriginKind::ConstInference,
256 span: DUMMY_SP,
257 },
258 val: ConstVariableValue::Known { value },
dc9dc135 259 },
dfeec247 260 )
1b1a35ee
XL
261 .map(|()| value)
262 .map_err(|e| const_unification_error(vid_is_expected, e))
48663c56
XL
263 }
264
dfeec247
XL
265 fn unify_integral_variable(
266 &self,
267 vid_is_expected: bool,
268 vid: ty::IntVid,
269 val: ty::IntVarValue,
270 ) -> RelateResult<'tcx, Ty<'tcx>> {
74b04a01 271 self.inner
a7813a04 272 .borrow_mut()
f9f354fc 273 .int_unification_table()
0531ce1d 274 .unify_var_value(vid, Some(val))
a7813a04
XL
275 .map_err(|e| int_unification_error(vid_is_expected, e))?;
276 match val {
277 IntType(v) => Ok(self.tcx.mk_mach_int(v)),
278 UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
279 }
1a4d82fc 280 }
1a4d82fc 281
dfeec247
XL
282 fn unify_float_variable(
283 &self,
284 vid_is_expected: bool,
285 vid: ty::FloatVid,
5869c6ff 286 val: ty::FloatTy,
dfeec247 287 ) -> RelateResult<'tcx, Ty<'tcx>> {
74b04a01 288 self.inner
a7813a04 289 .borrow_mut()
f9f354fc 290 .float_unification_table()
0531ce1d 291 .unify_var_value(vid, Some(ty::FloatVarValue(val)))
a7813a04
XL
292 .map_err(|e| float_unification_error(vid_is_expected, e))?;
293 Ok(self.tcx.mk_mach_float(val))
294 }
c34b1796
AL
295}
296
dc9dc135
XL
297impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
298 pub fn tcx(&self) -> TyCtxt<'tcx> {
c34b1796
AL
299 self.infcx.tcx
300 }
301
dc9dc135 302 pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> {
5bcae85e 303 Equate::new(self, a_is_expected)
1a4d82fc
JJ
304 }
305
dc9dc135 306 pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> {
5bcae85e 307 Sub::new(self, a_is_expected)
c34b1796
AL
308 }
309
dc9dc135 310 pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> {
5bcae85e 311 Lub::new(self, a_is_expected)
c34b1796
AL
312 }
313
dc9dc135 314 pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> {
5bcae85e 315 Glb::new(self, a_is_expected)
1a4d82fc
JJ
316 }
317
9fa01778
XL
318 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
319 /// The idea is that we should ensure that the type `a_ty` is equal
cc61c64b
XL
320 /// to, a subtype of, or a supertype of (respectively) the type
321 /// to which `b_vid` is bound.
322 ///
323 /// Since `b_vid` has not yet been instantiated with a type, we
324 /// will first instantiate `b_vid` with a *generalized* version
325 /// of `a_ty`. Generalization introduces other inference
326 /// variables wherever subtyping could occur.
dfeec247
XL
327 pub fn instantiate(
328 &mut self,
329 a_ty: Ty<'tcx>,
330 dir: RelationDir,
331 b_vid: ty::TyVid,
332 a_is_expected: bool,
333 ) -> RelateResult<'tcx, ()> {
cc61c64b 334 use self::RelationDir::*;
1a4d82fc 335
cc61c64b 336 // Get the actual variable that b_vid has been inferred to
f9f354fc 337 debug_assert!(self.infcx.inner.borrow_mut().type_variables().probe(b_vid).is_unknown());
1a4d82fc 338
cc61c64b
XL
339 debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
340
341 // Generalize type of `a_ty` appropriately depending on the
342 // direction. As an example, assume:
343 //
344 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
345 // inference variable,
346 // - and `dir` == `SubtypeOf`.
347 //
348 // Then the generalized form `b_ty` would be `&'?2 ?3`, where
349 // `'?2` and `?3` are fresh region/type inference
350 // variables. (Down below, we will relate `a_ty <: b_ty`,
351 // adding constraints like `'x: '?2` and `?1 <: ?3`.)
352 let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
dfeec247
XL
353 debug!(
354 "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
355 a_ty, dir, b_vid, b_ty
356 );
f9f354fc 357 self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty);
cc61c64b
XL
358
359 if needs_wf {
dfeec247
XL
360 self.obligations.push(Obligation::new(
361 self.trace.cause.clone(),
362 self.param_env,
c295e0f8
XL
363 ty::Binder::dummy(ty::PredicateKind::WellFormed(b_ty.into()))
364 .to_predicate(self.infcx.tcx),
dfeec247 365 ));
1a4d82fc
JJ
366 }
367
cc61c64b
XL
368 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
369 //
370 // FIXME(#16847): This code is non-ideal because all these subtype
371 // relations wind up attributed to the same spans. We need
372 // to associate causes/spans with each of the relations in
373 // the stack to get this right.
374 match dir {
f035d41b
XL
375 EqTo => self.equate(a_is_expected).relate(a_ty, b_ty),
376 SubtypeOf => self.sub(a_is_expected).relate(a_ty, b_ty),
17df50a5
XL
377 SupertypeOf => self.sub(a_is_expected).relate_with_variance(
378 ty::Contravariant,
379 ty::VarianceDiagInfo::default(),
380 a_ty,
381 b_ty,
382 ),
cc61c64b
XL
383 }?;
384
1a4d82fc
JJ
385 Ok(())
386 }
387
cc61c64b
XL
388 /// Attempts to generalize `ty` for the type variable `for_vid`.
389 /// This checks for cycle -- that is, whether the type `ty`
390 /// references `for_vid`. The `dir` is the "direction" for which we
391 /// a performing the generalization (i.e., are we producing a type
392 /// that can be used as a supertype etc).
393 ///
394 /// Preconditions:
395 ///
396 /// - `for_vid` is a "root vid"
dfeec247
XL
397 fn generalize(
398 &self,
399 ty: Ty<'tcx>,
400 for_vid: ty::TyVid,
401 dir: RelationDir,
402 ) -> RelateResult<'tcx, Generalization<'tcx>> {
13cf67c4 403 debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
cc61c64b
XL
404 // Determine the ambient variance within which `ty` appears.
405 // The surrounding equation is:
406 //
407 // ty [op] ty2
408 //
409 // where `op` is either `==`, `<:`, or `:>`. This maps quite
410 // naturally.
411 let ambient_variance = match dir {
412 RelationDir::EqTo => ty::Invariant,
413 RelationDir::SubtypeOf => ty::Covariant,
414 RelationDir::SupertypeOf => ty::Contravariant,
415 };
416
0731742a
XL
417 debug!("generalize: ambient_variance = {:?}", ambient_variance);
418
f9f354fc 419 let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) {
dfeec247 420 v @ TypeVariableValue::Known { .. } => {
1b1a35ee 421 bug!("instantiating {:?} which has a known value {:?}", for_vid, v,)
dfeec247 422 }
0731742a
XL
423 TypeVariableValue::Unknown { universe } => universe,
424 };
425
426 debug!("generalize: for_universe = {:?}", for_universe);
3dfed10e 427 debug!("generalize: trace = {:?}", self.trace);
0731742a 428
c34b1796
AL
429 let mut generalize = Generalizer {
430 infcx: self.infcx,
3dfed10e 431 cause: &self.trace.cause,
f9f354fc 432 for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid),
0731742a 433 for_universe,
041b39d2 434 ambient_variance,
cc61c64b 435 needs_wf: false,
ff7c6d11 436 root_ty: ty,
416331ca 437 param_env: self.param_env,
29967ef6 438 cache: SsoHashMap::new(),
c34b1796 439 };
cc61c64b 440
f035d41b 441 let ty = match generalize.relate(ty, ty) {
13cf67c4
XL
442 Ok(ty) => ty,
443 Err(e) => {
444 debug!("generalize: failure {:?}", e);
445 return Err(e);
446 }
447 };
cc61c64b 448 let needs_wf = generalize.needs_wf;
13cf67c4 449 debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
cc61c64b 450 Ok(Generalization { ty, needs_wf })
1a4d82fc 451 }
f9f354fc
XL
452
453 pub fn add_const_equate_obligation(
454 &mut self,
455 a_is_expected: bool,
456 a: &'tcx ty::Const<'tcx>,
457 b: &'tcx ty::Const<'tcx>,
458 ) {
459 let predicate = if a_is_expected {
5869c6ff 460 ty::PredicateKind::ConstEquate(a, b)
f9f354fc 461 } else {
5869c6ff 462 ty::PredicateKind::ConstEquate(b, a)
f9f354fc
XL
463 };
464 self.obligations.push(Obligation::new(
465 self.trace.cause.clone(),
466 self.param_env,
c295e0f8 467 ty::Binder::dummy(predicate).to_predicate(self.tcx()),
f9f354fc
XL
468 ));
469 }
1a4d82fc
JJ
470}
471
dc9dc135
XL
472struct Generalizer<'cx, 'tcx> {
473 infcx: &'cx InferCtxt<'cx, 'tcx>,
ff7c6d11 474
9fa01778 475 /// The span, used when creating new type variables and things.
3dfed10e 476 cause: &'cx ObligationCause<'tcx>,
ff7c6d11
XL
477
478 /// The vid of the type variable that is in the process of being
479 /// instantiated; if we find this within the type we are folding,
480 /// that means we would have created a cyclic type.
cc61c64b 481 for_vid_sub_root: ty::TyVid,
ff7c6d11 482
0731742a
XL
483 /// The universe of the type variable that is in the process of
484 /// being instantiated. Any fresh variables that we create in this
485 /// process should be in that same universe.
486 for_universe: ty::UniverseIndex,
487
ff7c6d11 488 /// Track the variance as we descend into the type.
cc61c64b 489 ambient_variance: ty::Variance,
ff7c6d11
XL
490
491 /// See the field `needs_wf` in `Generalization`.
492 needs_wf: bool,
493
494 /// The root type that we are generalizing. Used when reporting cycles.
495 root_ty: Ty<'tcx>,
416331ca
XL
496
497 param_env: ty::ParamEnv<'tcx>,
6c58768f 498
29967ef6 499 cache: SsoHashMap<Ty<'tcx>, RelateResult<'tcx, Ty<'tcx>>>,
cc61c64b
XL
500}
501
502/// Result from a generalization operation. This includes
503/// not only the generalized type, but also a bool flag
83c7162d 504/// indicating whether further WF checks are needed.
cc61c64b
XL
505struct Generalization<'tcx> {
506 ty: Ty<'tcx>,
507
508 /// If true, then the generalized type may not be well-formed,
509 /// even if the source type is well-formed, so we should add an
510 /// additional check to enforce that it is. This arises in
511 /// particular around 'bivariant' type parameters that are only
512 /// constrained by a where-clause. As an example, imagine a type:
513 ///
9fa01778 514 /// struct Foo<A, B> where A: Iterator<Item = B> {
cc61c64b
XL
515 /// data: A
516 /// }
517 ///
518 /// here, `A` will be covariant, but `B` is
519 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
520 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
521 /// then after generalization we will wind up with a type like
522 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
523 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
524 /// <: ?C`, but no particular relationship between `?B` and `?D`
525 /// (after all, we do not know the variance of the normalized form
526 /// of `A::Item` with respect to `A`). If we do nothing else, this
9fa01778 527 /// may mean that `?D` goes unconstrained (as in #41677). So, in
cc61c64b
XL
528 /// this scenario where we create a new type variable in a
529 /// bivariant context, we set the `needs_wf` flag to true. This
530 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
531 /// holds, which in turn implies that `?C::Item == ?D`. So once
532 /// `?C` is constrained, that should suffice to restrict `?D`.
533 needs_wf: bool,
1a4d82fc
JJ
534}
535
dc9dc135
XL
536impl TypeRelation<'tcx> for Generalizer<'_, 'tcx> {
537 fn tcx(&self) -> TyCtxt<'tcx> {
1a4d82fc
JJ
538 self.infcx.tcx
539 }
dfeec247
XL
540 fn param_env(&self) -> ty::ParamEnv<'tcx> {
541 self.param_env
542 }
1a4d82fc 543
cc61c64b
XL
544 fn tag(&self) -> &'static str {
545 "Generalizer"
546 }
547
548 fn a_is_expected(&self) -> bool {
549 true
550 }
551
dfeec247
XL
552 fn binders<T>(
553 &mut self,
cdc7bbd5
XL
554 a: ty::Binder<'tcx, T>,
555 b: ty::Binder<'tcx, T>,
556 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
dfeec247
XL
557 where
558 T: Relate<'tcx>,
cc61c64b 559 {
fc512014 560 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
cc61c64b
XL
561 }
562
dfeec247
XL
563 fn relate_item_substs(
564 &mut self,
565 item_def_id: DefId,
566 a_subst: SubstsRef<'tcx>,
567 b_subst: SubstsRef<'tcx>,
568 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
cc61c64b
XL
569 if self.ambient_variance == ty::Variance::Invariant {
570 // Avoid fetching the variance if we are in an invariant
571 // context; no need, and it can induce dependency cycles
0731742a 572 // (e.g., #41849).
cc61c64b
XL
573 relate::relate_substs(self, None, a_subst, b_subst)
574 } else {
7cac9316
XL
575 let opt_variances = self.tcx().variances_of(item_def_id);
576 relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
cc61c64b
XL
577 }
578 }
579
dfeec247
XL
580 fn relate_with_variance<T: Relate<'tcx>>(
581 &mut self,
582 variance: ty::Variance,
17df50a5 583 _info: ty::VarianceDiagInfo<'tcx>,
f035d41b
XL
584 a: T,
585 b: T,
dfeec247 586 ) -> RelateResult<'tcx, T> {
cc61c64b
XL
587 let old_ambient_variance = self.ambient_variance;
588 self.ambient_variance = self.ambient_variance.xform(variance);
589
590 let result = self.relate(a, b);
591 self.ambient_variance = old_ambient_variance;
592 result
593 }
594
595 fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
596 assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
597
6c58768f
XL
598 if let Some(result) = self.cache.get(&t) {
599 return result.clone();
600 }
0731742a
XL
601 debug!("generalize: t={:?}", t);
602
48663c56 603 // Check to see whether the type we are generalizing references
cc61c64b
XL
604 // any other type variable related to `vid` via
605 // subtyping. This is basically our "occurs check", preventing
606 // us from creating infinitely sized types.
1b1a35ee 607 let result = match *t.kind() {
b7449926 608 ty::Infer(ty::TyVar(vid)) => {
f9f354fc
XL
609 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
610 let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid);
cc61c64b
XL
611 if sub_vid == self.for_vid_sub_root {
612 // If sub-roots are equal, then `for_vid` and
613 // `vid` are related via subtyping.
e74abb32 614 Err(TypeError::CyclicTy(self.root_ty))
1a4d82fc 615 } else {
f9f354fc 616 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
74b04a01 617 match probe {
0531ce1d 618 TypeVariableValue::Known { value: u } => {
0731742a 619 debug!("generalize: known value {:?}", u);
f035d41b 620 self.relate(u, u)
cc61c64b 621 }
83c7162d 622 TypeVariableValue::Unknown { universe } => {
cc61c64b
XL
623 match self.ambient_variance {
624 // Invariant: no need to make a fresh type variable.
0731742a
XL
625 ty::Invariant => {
626 if self.for_universe.can_name(universe) {
627 return Ok(t);
628 }
629 }
cc61c64b
XL
630
631 // Bivariant: make a fresh var, but we
632 // may need a WF predicate. See
633 // comment on `needs_wf` field for
634 // more info.
635 ty::Bivariant => self.needs_wf = true,
636
637 // Co/contravariant: this will be
638 // sufficiently constrained later on.
639 ty::Covariant | ty::Contravariant => (),
640 }
641
74b04a01 642 let origin =
f9f354fc
XL
643 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
644 let new_var_id = self
645 .infcx
646 .inner
647 .borrow_mut()
648 .type_variables()
c295e0f8 649 .new_var(self.for_universe, origin);
532ac7d7 650 let u = self.tcx().mk_ty_var(new_var_id);
94222f64
XL
651
652 // Record that we replaced `vid` with `new_var_id` as part of a generalization
653 // operation. This is needed to detect cyclic types. To see why, see the
654 // docs in the `type_variables` module.
655 self.infcx.inner.borrow_mut().type_variables().sub(vid, new_var_id);
dfeec247 656 debug!("generalize: replacing original vid={:?} with new={:?}", vid, u);
e74abb32 657 Ok(u)
54a0048b 658 }
1a4d82fc
JJ
659 }
660 }
661 }
ba9703b0 662 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
cc61c64b
XL
663 // No matter what mode we are in,
664 // integer/floating-point types must be equal to be
665 // relatable.
666 Ok(t)
667 }
dfeec247 668 _ => relate::super_relate_tys(self, t, t),
6c58768f
XL
669 };
670
671 self.cache.insert(t, result.clone());
672 return result;
1a4d82fc
JJ
673 }
674
dfeec247
XL
675 fn regions(
676 &mut self,
677 r: ty::Region<'tcx>,
678 r2: ty::Region<'tcx>,
679 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
cc61c64b
XL
680 assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
681
0731742a
XL
682 debug!("generalize: regions r={:?}", r);
683
9e0c209e 684 match *r {
3157f602
XL
685 // Never make variables for regions bound within the type itself,
686 // nor for erased regions.
dfeec247 687 ty::ReLateBound(..) | ty::ReErased => {
cc61c64b
XL
688 return Ok(r);
689 }
1a4d82fc 690
dfeec247
XL
691 ty::RePlaceholder(..)
692 | ty::ReVar(..)
74b04a01 693 | ty::ReEmpty(_)
dfeec247 694 | ty::ReStatic
dfeec247
XL
695 | ty::ReEarlyBound(..)
696 | ty::ReFree(..) => {
0731742a 697 // see common code below
1a4d82fc 698 }
0731742a 699 }
ff7c6d11 700
0731742a
XL
701 // If we are in an invariant context, we can re-use the region
702 // as is, unless it happens to be in some universe that we
703 // can't name. (In the case of a region *variable*, we could
704 // use it if we promoted it into our universe, but we don't
705 // bother.)
706 if let ty::Invariant = self.ambient_variance {
707 let r_universe = self.infcx.universe_of_region(r);
708 if self.for_universe.can_name(r_universe) {
709 return Ok(r);
ff7c6d11 710 }
1a4d82fc
JJ
711 }
712
713 // FIXME: This is non-ideal because we don't give a
714 // very descriptive origin for this region variable.
3dfed10e 715 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe))
1a4d82fc 716 }
48663c56
XL
717
718 fn consts(
719 &mut self,
720 c: &'tcx ty::Const<'tcx>,
dfeec247 721 c2: &'tcx ty::Const<'tcx>,
48663c56
XL
722 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
723 assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
724
e74abb32 725 match c.val {
60c5eb7d 726 ty::ConstKind::Infer(InferConst::Var(vid)) => {
f9f354fc
XL
727 let mut inner = self.infcx.inner.borrow_mut();
728 let variable_table = &mut inner.const_unification_table();
e74abb32
XL
729 let var_value = variable_table.probe_value(vid);
730 match var_value.val {
fc512014
XL
731 ConstVariableValue::Known { value: u } => {
732 drop(inner);
733 self.relate(u, u)
734 }
e74abb32
XL
735 ConstVariableValue::Unknown { universe } => {
736 if self.for_universe.can_name(universe) {
737 Ok(c)
738 } else {
739 let new_var_id = variable_table.new_key(ConstVarValue {
740 origin: var_value.origin,
741 val: ConstVariableValue::Unknown { universe: self.for_universe },
742 });
743 Ok(self.tcx().mk_const_var(new_var_id, c.ty))
744 }
48663c56 745 }
48663c56
XL
746 }
747 }
94222f64
XL
748 ty::ConstKind::Unevaluated(uv) if self.tcx().lazy_normalization() => {
749 assert_eq!(uv.promoted, None);
750 let substs = uv.substs(self.tcx());
17df50a5
XL
751 let substs = self.relate_with_variance(
752 ty::Variance::Invariant,
753 ty::VarianceDiagInfo::default(),
754 substs,
755 substs,
756 )?;
cdc7bbd5
XL
757 Ok(self.tcx().mk_const(ty::Const {
758 ty: c.ty,
94222f64 759 val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(uv.def, substs)),
cdc7bbd5
XL
760 }))
761 }
e74abb32 762 _ => relate::super_relate_consts(self, c, c),
48663c56
XL
763 }
764 }
1a4d82fc 765}
c34b1796 766
f9f354fc
XL
767pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> {
768 /// Register an obligation that both constants must be equal to each other.
769 ///
770 /// If they aren't equal then the relation doesn't hold.
771 fn const_equate_obligation(&mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>);
772}
773
c34b1796 774pub trait RelateResultCompare<'tcx, T> {
dfeec247
XL
775 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
776 where
e9174d1e 777 F: FnOnce() -> TypeError<'tcx>;
c34b1796
AL
778}
779
dfeec247
XL
780impl<'tcx, T: Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
781 fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T>
782 where
e9174d1e 783 F: FnOnce() -> TypeError<'tcx>,
c34b1796 784 {
dfeec247 785 self.clone().and_then(|s| if s == t { self.clone() } else { Err(f()) })
c34b1796
AL
786 }
787}
788
48663c56
XL
789pub fn const_unification_error<'tcx>(
790 a_is_expected: bool,
791 (a, b): (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>),
792) -> TypeError<'tcx> {
f035d41b 793 TypeError::ConstMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
48663c56
XL
794}
795
dfeec247
XL
796fn int_unification_error<'tcx>(
797 a_is_expected: bool,
798 v: (ty::IntVarValue, ty::IntVarValue),
799) -> TypeError<'tcx> {
c34b1796 800 let (a, b) = v;
f035d41b 801 TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
c34b1796
AL
802}
803
dfeec247
XL
804fn float_unification_error<'tcx>(
805 a_is_expected: bool,
806 v: (ty::FloatVarValue, ty::FloatVarValue),
807) -> TypeError<'tcx> {
0531ce1d 808 let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
f035d41b 809 TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, a, b))
c34b1796 810}
1b1a35ee
XL
811
812struct ConstInferUnifier<'cx, 'tcx> {
813 infcx: &'cx InferCtxt<'cx, 'tcx>,
814
815 span: Span,
816
817 param_env: ty::ParamEnv<'tcx>,
818
819 for_universe: ty::UniverseIndex,
820
821 /// The vid of the const variable that is in the process of being
822 /// instantiated; if we find this within the const we are folding,
823 /// that means we would have created a cyclic const.
824 target_vid: ty::ConstVid<'tcx>,
825}
826
827// We use `TypeRelation` here to propagate `RelateResult` upwards.
828//
829// Both inputs are expected to be the same.
830impl TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> {
831 fn tcx(&self) -> TyCtxt<'tcx> {
832 self.infcx.tcx
833 }
834
835 fn param_env(&self) -> ty::ParamEnv<'tcx> {
836 self.param_env
837 }
838
839 fn tag(&self) -> &'static str {
840 "ConstInferUnifier"
841 }
842
843 fn a_is_expected(&self) -> bool {
844 true
845 }
846
847 fn relate_with_variance<T: Relate<'tcx>>(
848 &mut self,
849 _variance: ty::Variance,
17df50a5 850 _info: ty::VarianceDiagInfo<'tcx>,
1b1a35ee
XL
851 a: T,
852 b: T,
853 ) -> RelateResult<'tcx, T> {
854 // We don't care about variance here.
855 self.relate(a, b)
856 }
857
858 fn binders<T>(
859 &mut self,
cdc7bbd5
XL
860 a: ty::Binder<'tcx, T>,
861 b: ty::Binder<'tcx, T>,
862 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
1b1a35ee
XL
863 where
864 T: Relate<'tcx>,
865 {
fc512014 866 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
1b1a35ee
XL
867 }
868
869 fn tys(&mut self, t: Ty<'tcx>, _t: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
870 debug_assert_eq!(t, _t);
871 debug!("ConstInferUnifier: t={:?}", t);
872
873 match t.kind() {
874 &ty::Infer(ty::TyVar(vid)) => {
875 let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid);
876 let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid);
877 match probe {
878 TypeVariableValue::Known { value: u } => {
879 debug!("ConstOccursChecker: known value {:?}", u);
880 self.tys(u, u)
881 }
882 TypeVariableValue::Unknown { universe } => {
883 if self.for_universe.can_name(universe) {
884 return Ok(t);
885 }
886
887 let origin =
888 *self.infcx.inner.borrow_mut().type_variables().var_origin(vid);
c295e0f8
XL
889 let new_var_id = self
890 .infcx
891 .inner
892 .borrow_mut()
893 .type_variables()
894 .new_var(self.for_universe, origin);
1b1a35ee
XL
895 let u = self.tcx().mk_ty_var(new_var_id);
896 debug!(
897 "ConstInferUnifier: replacing original vid={:?} with new={:?}",
898 vid, u
899 );
900 Ok(u)
901 }
902 }
903 }
fc512014 904 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => Ok(t),
1b1a35ee
XL
905 _ => relate::super_relate_tys(self, t, t),
906 }
907 }
908
909 fn regions(
910 &mut self,
911 r: ty::Region<'tcx>,
912 _r: ty::Region<'tcx>,
913 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
914 debug_assert_eq!(r, _r);
915 debug!("ConstInferUnifier: r={:?}", r);
916
917 match r {
918 // Never make variables for regions bound within the type itself,
919 // nor for erased regions.
920 ty::ReLateBound(..) | ty::ReErased => {
921 return Ok(r);
922 }
923
924 ty::RePlaceholder(..)
925 | ty::ReVar(..)
926 | ty::ReEmpty(_)
927 | ty::ReStatic
928 | ty::ReEarlyBound(..)
929 | ty::ReFree(..) => {
930 // see common code below
931 }
932 }
933
934 let r_universe = self.infcx.universe_of_region(r);
935 if self.for_universe.can_name(r_universe) {
936 return Ok(r);
937 } else {
938 // FIXME: This is non-ideal because we don't give a
939 // very descriptive origin for this region variable.
940 Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
941 }
942 }
943
944 fn consts(
945 &mut self,
946 c: &'tcx ty::Const<'tcx>,
947 _c: &'tcx ty::Const<'tcx>,
948 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
949 debug_assert_eq!(c, _c);
950 debug!("ConstInferUnifier: c={:?}", c);
951
952 match c.val {
953 ty::ConstKind::Infer(InferConst::Var(vid)) => {
954 let mut inner = self.infcx.inner.borrow_mut();
955 let variable_table = &mut inner.const_unification_table();
956
957 // Check if the current unification would end up
958 // unifying `target_vid` with a const which contains
959 // an inference variable which is unioned with `target_vid`.
960 //
961 // Not doing so can easily result in stack overflows.
962 if variable_table.unioned(self.target_vid, vid) {
963 return Err(TypeError::CyclicConst(c));
964 }
965
966 let var_value = variable_table.probe_value(vid);
967 match var_value.val {
968 ConstVariableValue::Known { value: u } => self.consts(u, u),
969 ConstVariableValue::Unknown { universe } => {
970 if self.for_universe.can_name(universe) {
971 Ok(c)
972 } else {
973 let new_var_id = variable_table.new_key(ConstVarValue {
974 origin: var_value.origin,
975 val: ConstVariableValue::Unknown { universe: self.for_universe },
976 });
977 Ok(self.tcx().mk_const_var(new_var_id, c.ty))
978 }
979 }
980 }
981 }
94222f64
XL
982 ty::ConstKind::Unevaluated(uv) if self.tcx().lazy_normalization() => {
983 assert_eq!(uv.promoted, None);
984 let substs = uv.substs(self.tcx());
17df50a5
XL
985 let substs = self.relate_with_variance(
986 ty::Variance::Invariant,
987 ty::VarianceDiagInfo::default(),
988 substs,
989 substs,
990 )?;
cdc7bbd5
XL
991 Ok(self.tcx().mk_const(ty::Const {
992 ty: c.ty,
94222f64 993 val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(uv.def, substs)),
cdc7bbd5
XL
994 }))
995 }
1b1a35ee
XL
996 _ => relate::super_relate_consts(self, c, c),
997 }
998 }
999}