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