1 ///////////////////////////////////////////////////////////////////////////
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.
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.
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.
25 use super::equate
::Equate
;
29 use super::type_variable
::TypeVariableValue
;
30 use super::{InferCtxt, MiscVariable, TypeTrace}
;
31 use crate::traits
::{Obligation, PredicateObligations}
;
32 use rustc_data_structures
::sso
::SsoHashMap
;
33 use rustc_hir
::def_id
::DefId
;
34 use rustc_middle
::infer
::unify_key
::{ConstVarValue, ConstVariableValue}
;
35 use rustc_middle
::infer
::unify_key
::{ConstVariableOrigin, ConstVariableOriginKind}
;
36 use rustc_middle
::traits
::ObligationCause
;
37 use rustc_middle
::ty
::error
::{ExpectedFound, TypeError}
;
38 use rustc_middle
::ty
::relate
::{self, Relate, RelateResult, TypeRelation}
;
39 use rustc_middle
::ty
::subst
::SubstsRef
;
40 use rustc_middle
::ty
::{self, InferConst, ToPredicate, Ty, TyCtxt, TypeFoldable}
;
41 use rustc_middle
::ty
::{IntType, UintType}
;
42 use rustc_span
::{Span, DUMMY_SP}
;
45 pub struct CombineFields
<'infcx
, 'tcx
> {
46 pub infcx
: &'infcx InferCtxt
<'infcx
, 'tcx
>,
47 pub trace
: TypeTrace
<'tcx
>,
48 pub cause
: Option
<ty
::relate
::Cause
>,
49 pub param_env
: ty
::ParamEnv
<'tcx
>,
50 pub obligations
: PredicateObligations
<'tcx
>,
51 /// Whether we should define opaque types
52 /// or just treat them opaquely.
53 /// Currently only used to prevent predicate
54 /// matching from matching anything against opaque
56 pub define_opaque_types
: bool
,
59 #[derive(Copy, Clone, Debug)]
60 pub enum RelationDir
{
66 impl<'infcx
, 'tcx
> InferCtxt
<'infcx
, 'tcx
> {
67 pub fn super_combine_tys
<R
>(
72 ) -> RelateResult
<'tcx
, Ty
<'tcx
>>
74 R
: TypeRelation
<'tcx
>,
76 let a_is_expected
= relation
.a_is_expected();
78 match (a
.kind(), b
.kind()) {
79 // Relate integral variables to other types
80 (&ty
::Infer(ty
::IntVar(a_id
)), &ty
::Infer(ty
::IntVar(b_id
))) => {
83 .int_unification_table()
84 .unify_var_var(a_id
, b_id
)
85 .map_err(|e
| int_unification_error(a_is_expected
, e
))?
;
88 (&ty
::Infer(ty
::IntVar(v_id
)), &ty
::Int(v
)) => {
89 self.unify_integral_variable(a_is_expected
, v_id
, IntType(v
))
91 (&ty
::Int(v
), &ty
::Infer(ty
::IntVar(v_id
))) => {
92 self.unify_integral_variable(!a_is_expected
, v_id
, IntType(v
))
94 (&ty
::Infer(ty
::IntVar(v_id
)), &ty
::Uint(v
)) => {
95 self.unify_integral_variable(a_is_expected
, v_id
, UintType(v
))
97 (&ty
::Uint(v
), &ty
::Infer(ty
::IntVar(v_id
))) => {
98 self.unify_integral_variable(!a_is_expected
, v_id
, UintType(v
))
101 // Relate floating-point variables to other types
102 (&ty
::Infer(ty
::FloatVar(a_id
)), &ty
::Infer(ty
::FloatVar(b_id
))) => {
105 .float_unification_table()
106 .unify_var_var(a_id
, b_id
)
107 .map_err(|e
| float_unification_error(relation
.a_is_expected(), e
))?
;
110 (&ty
::Infer(ty
::FloatVar(v_id
)), &ty
::Float(v
)) => {
111 self.unify_float_variable(a_is_expected
, v_id
, v
)
113 (&ty
::Float(v
), &ty
::Infer(ty
::FloatVar(v_id
))) => {
114 self.unify_float_variable(!a_is_expected
, v_id
, v
)
117 // All other cases of inference are errors
118 (&ty
::Infer(_
), _
) | (_
, &ty
::Infer(_
)) => {
119 Err(TypeError
::Sorts(ty
::relate
::expected_found(relation
, a
, b
)))
122 _
=> ty
::relate
::super_relate_tys(relation
, a
, b
),
126 pub fn super_combine_consts
<R
>(
131 ) -> RelateResult
<'tcx
, ty
::Const
<'tcx
>>
133 R
: ConstEquateRelation
<'tcx
>,
135 debug
!("{}.consts({:?}, {:?})", relation
.tag(), a
, b
);
140 let a
= self.shallow_resolve(a
);
141 let b
= self.shallow_resolve(b
);
143 let a_is_expected
= relation
.a_is_expected();
145 match (a
.val(), b
.val()) {
147 ty
::ConstKind
::Infer(InferConst
::Var(a_vid
)),
148 ty
::ConstKind
::Infer(InferConst
::Var(b_vid
)),
152 .const_unification_table()
153 .unify_var_var(a_vid
, b_vid
)
154 .map_err(|e
| const_unification_error(a_is_expected
, e
))?
;
158 // All other cases of inference with other variables are errors.
159 (ty
::ConstKind
::Infer(InferConst
::Var(_
)), ty
::ConstKind
::Infer(_
))
160 | (ty
::ConstKind
::Infer(_
), ty
::ConstKind
::Infer(InferConst
::Var(_
))) => {
161 bug
!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var)")
164 (ty
::ConstKind
::Infer(InferConst
::Var(vid
)), _
) => {
165 return self.unify_const_variable(relation
.param_env(), vid
, b
, a_is_expected
);
168 (_
, ty
::ConstKind
::Infer(InferConst
::Var(vid
))) => {
169 return self.unify_const_variable(relation
.param_env(), vid
, a
, !a_is_expected
);
171 (ty
::ConstKind
::Unevaluated(..), _
) if self.tcx
.lazy_normalization() => {
172 // FIXME(#59490): Need to remove the leak check to accommodate
173 // escaping bound variables here.
174 if !a
.has_escaping_bound_vars() && !b
.has_escaping_bound_vars() {
175 relation
.const_equate_obligation(a
, b
);
179 (_
, ty
::ConstKind
::Unevaluated(..)) if self.tcx
.lazy_normalization() => {
180 // FIXME(#59490): Need to remove the leak check to accommodate
181 // escaping bound variables here.
182 if !a
.has_escaping_bound_vars() && !b
.has_escaping_bound_vars() {
183 relation
.const_equate_obligation(a
, b
);
190 ty
::relate
::super_relate_consts(relation
, a
, b
)
193 /// Unifies the const variable `target_vid` with the given constant.
195 /// This also tests if the given const `ct` contains an inference variable which was previously
196 /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct`
197 /// would result in an infinite type as we continuously replace an inference variable
198 /// in `ct` with `ct` itself.
200 /// This is especially important as unevaluated consts use their parents generics.
201 /// They therefore often contain unused substs, making these errors far more likely.
203 /// A good example of this is the following:
205 /// ```compile_fail,E0308
206 /// #![feature(generic_const_exprs)]
208 /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
213 /// let mut arr = Default::default();
218 /// Here `3 + 4` ends up as `ConstKind::Unevaluated` which uses the generics
219 /// of `fn bind` (meaning that its substs contain `N`).
221 /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
222 /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
224 /// As `3 + 4` contains `N` in its substs, this must not succeed.
226 /// See `src/test/ui/const-generics/occurs-check/` for more examples where this is relevant.
227 #[instrument(level = "debug", skip(self))]
228 fn unify_const_variable(
230 param_env
: ty
::ParamEnv
<'tcx
>,
231 target_vid
: ty
::ConstVid
<'tcx
>,
233 vid_is_expected
: bool
,
234 ) -> RelateResult
<'tcx
, ty
::Const
<'tcx
>> {
235 let (for_universe
, span
) = {
236 let mut inner
= self.inner
.borrow_mut();
237 let variable_table
= &mut inner
.const_unification_table();
238 let var_value
= variable_table
.probe_value(target_vid
);
239 match var_value
.val
{
240 ConstVariableValue
::Known { value }
=> {
241 bug
!("instantiating {:?} which has a known value {:?}", target_vid
, value
)
243 ConstVariableValue
::Unknown { universe }
=> (universe
, var_value
.origin
.span
),
246 let value
= ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid }
251 .const_unification_table()
255 origin
: ConstVariableOrigin
{
256 kind
: ConstVariableOriginKind
::ConstInference
,
259 val
: ConstVariableValue
::Known { value }
,
263 .map_err(|e
| const_unification_error(vid_is_expected
, e
))
266 fn unify_integral_variable(
268 vid_is_expected
: bool
,
270 val
: ty
::IntVarValue
,
271 ) -> RelateResult
<'tcx
, Ty
<'tcx
>> {
274 .int_unification_table()
275 .unify_var_value(vid
, Some(val
))
276 .map_err(|e
| int_unification_error(vid_is_expected
, e
))?
;
278 IntType(v
) => Ok(self.tcx
.mk_mach_int(v
)),
279 UintType(v
) => Ok(self.tcx
.mk_mach_uint(v
)),
283 fn unify_float_variable(
285 vid_is_expected
: bool
,
288 ) -> RelateResult
<'tcx
, Ty
<'tcx
>> {
291 .float_unification_table()
292 .unify_var_value(vid
, Some(ty
::FloatVarValue(val
)))
293 .map_err(|e
| float_unification_error(vid_is_expected
, e
))?
;
294 Ok(self.tcx
.mk_mach_float(val
))
298 impl<'infcx
, 'tcx
> CombineFields
<'infcx
, 'tcx
> {
299 pub fn tcx(&self) -> TyCtxt
<'tcx
> {
303 pub fn equate
<'a
>(&'a
mut self, a_is_expected
: bool
) -> Equate
<'a
, 'infcx
, 'tcx
> {
304 Equate
::new(self, a_is_expected
)
307 pub fn sub
<'a
>(&'a
mut self, a_is_expected
: bool
) -> Sub
<'a
, 'infcx
, 'tcx
> {
308 Sub
::new(self, a_is_expected
)
311 pub fn lub
<'a
>(&'a
mut self, a_is_expected
: bool
) -> Lub
<'a
, 'infcx
, 'tcx
> {
312 Lub
::new(self, a_is_expected
)
315 pub fn glb
<'a
>(&'a
mut self, a_is_expected
: bool
) -> Glb
<'a
, 'infcx
, 'tcx
> {
316 Glb
::new(self, a_is_expected
)
319 /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
320 /// The idea is that we should ensure that the type `a_ty` is equal
321 /// to, a subtype of, or a supertype of (respectively) the type
322 /// to which `b_vid` is bound.
324 /// Since `b_vid` has not yet been instantiated with a type, we
325 /// will first instantiate `b_vid` with a *generalized* version
326 /// of `a_ty`. Generalization introduces other inference
327 /// variables wherever subtyping could occur.
328 #[instrument(skip(self), level = "debug")]
335 ) -> RelateResult
<'tcx
, ()> {
336 use self::RelationDir
::*;
338 // Get the actual variable that b_vid has been inferred to
339 debug_assert
!(self.infcx
.inner
.borrow_mut().type_variables().probe(b_vid
).is_unknown());
341 // Generalize type of `a_ty` appropriately depending on the
342 // direction. As an example, assume:
344 // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
345 // inference variable,
346 // - and `dir` == `SubtypeOf`.
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
)?
;
354 self.infcx
.inner
.borrow_mut().type_variables().instantiate(b_vid
, b_ty
);
357 self.obligations
.push(Obligation
::new(
358 self.trace
.cause
.clone(),
360 ty
::Binder
::dummy(ty
::PredicateKind
::WellFormed(b_ty
.into()))
361 .to_predicate(self.infcx
.tcx
),
365 // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
367 // FIXME(#16847): This code is non-ideal because all these subtype
368 // relations wind up attributed to the same spans. We need
369 // to associate causes/spans with each of the relations in
370 // the stack to get this right.
372 EqTo
=> self.equate(a_is_expected
).relate(a_ty
, b_ty
),
373 SubtypeOf
=> self.sub(a_is_expected
).relate(a_ty
, b_ty
),
374 SupertypeOf
=> self.sub(a_is_expected
).relate_with_variance(
376 ty
::VarianceDiagInfo
::default(),
385 /// Attempts to generalize `ty` for the type variable `for_vid`.
386 /// This checks for cycle -- that is, whether the type `ty`
387 /// references `for_vid`. The `dir` is the "direction" for which we
388 /// a performing the generalization (i.e., are we producing a type
389 /// that can be used as a supertype etc).
393 /// - `for_vid` is a "root vid"
394 #[instrument(skip(self), level = "trace")]
400 ) -> RelateResult
<'tcx
, Generalization
<'tcx
>> {
401 // Determine the ambient variance within which `ty` appears.
402 // The surrounding equation is:
406 // where `op` is either `==`, `<:`, or `:>`. This maps quite
408 let ambient_variance
= match dir
{
409 RelationDir
::EqTo
=> ty
::Invariant
,
410 RelationDir
::SubtypeOf
=> ty
::Covariant
,
411 RelationDir
::SupertypeOf
=> ty
::Contravariant
,
414 trace
!(?ambient_variance
);
416 let for_universe
= match self.infcx
.inner
.borrow_mut().type_variables().probe(for_vid
) {
417 v @ TypeVariableValue
::Known { .. }
=> {
418 bug
!("instantiating {:?} which has a known value {:?}", for_vid
, v
,)
420 TypeVariableValue
::Unknown { universe }
=> universe
,
423 trace
!(?for_universe
);
426 let mut generalize
= Generalizer
{
428 cause
: &self.trace
.cause
,
429 for_vid_sub_root
: self.infcx
.inner
.borrow_mut().type_variables().sub_root_var(for_vid
),
434 param_env
: self.param_env
,
435 cache
: SsoHashMap
::new(),
438 let ty
= match generalize
.relate(ty
, ty
) {
441 debug
!(?e
, "failure");
445 let needs_wf
= generalize
.needs_wf
;
446 trace
!(?ty
, ?needs_wf
, "success");
447 Ok(Generalization { ty, needs_wf }
)
450 pub fn add_const_equate_obligation(
456 let predicate
= if a_is_expected
{
457 ty
::PredicateKind
::ConstEquate(a
, b
)
459 ty
::PredicateKind
::ConstEquate(b
, a
)
461 self.obligations
.push(Obligation
::new(
462 self.trace
.cause
.clone(),
464 ty
::Binder
::dummy(predicate
).to_predicate(self.tcx()),
469 struct Generalizer
<'cx
, 'tcx
> {
470 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
472 /// The span, used when creating new type variables and things.
473 cause
: &'cx ObligationCause
<'tcx
>,
475 /// The vid of the type variable that is in the process of being
476 /// instantiated; if we find this within the type we are folding,
477 /// that means we would have created a cyclic type.
478 for_vid_sub_root
: ty
::TyVid
,
480 /// The universe of the type variable that is in the process of
481 /// being instantiated. Any fresh variables that we create in this
482 /// process should be in that same universe.
483 for_universe
: ty
::UniverseIndex
,
485 /// Track the variance as we descend into the type.
486 ambient_variance
: ty
::Variance
,
488 /// See the field `needs_wf` in `Generalization`.
491 /// The root type that we are generalizing. Used when reporting cycles.
494 param_env
: ty
::ParamEnv
<'tcx
>,
496 cache
: SsoHashMap
<Ty
<'tcx
>, RelateResult
<'tcx
, Ty
<'tcx
>>>,
499 /// Result from a generalization operation. This includes
500 /// not only the generalized type, but also a bool flag
501 /// indicating whether further WF checks are needed.
502 struct Generalization
<'tcx
> {
505 /// If true, then the generalized type may not be well-formed,
506 /// even if the source type is well-formed, so we should add an
507 /// additional check to enforce that it is. This arises in
508 /// particular around 'bivariant' type parameters that are only
509 /// constrained by a where-clause. As an example, imagine a type:
511 /// struct Foo<A, B> where A: Iterator<Item = B> {
515 /// here, `A` will be covariant, but `B` is
516 /// unconstrained. However, whatever it is, for `Foo` to be WF, it
517 /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
518 /// then after generalization we will wind up with a type like
519 /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
520 /// ?D>` (or `>:`), we will wind up with the requirement that `?A
521 /// <: ?C`, but no particular relationship between `?B` and `?D`
522 /// (after all, we do not know the variance of the normalized form
523 /// of `A::Item` with respect to `A`). If we do nothing else, this
524 /// may mean that `?D` goes unconstrained (as in #41677). So, in
525 /// this scenario where we create a new type variable in a
526 /// bivariant context, we set the `needs_wf` flag to true. This
527 /// will force the calling code to check that `WF(Foo<?C, ?D>)`
528 /// holds, which in turn implies that `?C::Item == ?D`. So once
529 /// `?C` is constrained, that should suffice to restrict `?D`.
533 impl<'tcx
> TypeRelation
<'tcx
> for Generalizer
<'_
, 'tcx
> {
534 fn tcx(&self) -> TyCtxt
<'tcx
> {
537 fn param_env(&self) -> ty
::ParamEnv
<'tcx
> {
541 fn tag(&self) -> &'
static str {
545 fn a_is_expected(&self) -> bool
{
551 a
: ty
::Binder
<'tcx
, T
>,
552 b
: ty
::Binder
<'tcx
, T
>,
553 ) -> RelateResult
<'tcx
, ty
::Binder
<'tcx
, T
>>
557 Ok(a
.rebind(self.relate(a
.skip_binder(), b
.skip_binder())?
))
560 fn relate_item_substs(
563 a_subst
: SubstsRef
<'tcx
>,
564 b_subst
: SubstsRef
<'tcx
>,
565 ) -> RelateResult
<'tcx
, SubstsRef
<'tcx
>> {
566 if self.ambient_variance
== ty
::Variance
::Invariant
{
567 // Avoid fetching the variance if we are in an invariant
568 // context; no need, and it can induce dependency cycles
570 relate
::relate_substs(self, a_subst
, b_subst
)
572 let tcx
= self.tcx();
573 let opt_variances
= tcx
.variances_of(item_def_id
);
574 relate
::relate_substs_with_variances(
584 fn relate_with_variance
<T
: Relate
<'tcx
>>(
586 variance
: ty
::Variance
,
587 _info
: ty
::VarianceDiagInfo
<'tcx
>,
590 ) -> RelateResult
<'tcx
, T
> {
591 let old_ambient_variance
= self.ambient_variance
;
592 self.ambient_variance
= self.ambient_variance
.xform(variance
);
594 let result
= self.relate(a
, b
);
595 self.ambient_variance
= old_ambient_variance
;
599 fn tys(&mut self, t
: Ty
<'tcx
>, t2
: Ty
<'tcx
>) -> RelateResult
<'tcx
, Ty
<'tcx
>> {
600 assert_eq
!(t
, t2
); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
602 if let Some(result
) = self.cache
.get(&t
) {
603 return result
.clone();
605 debug
!("generalize: t={:?}", t
);
607 // Check to see whether the type we are generalizing references
608 // any other type variable related to `vid` via
609 // subtyping. This is basically our "occurs check", preventing
610 // us from creating infinitely sized types.
611 let result
= match *t
.kind() {
612 ty
::Infer(ty
::TyVar(vid
)) => {
613 let vid
= self.infcx
.inner
.borrow_mut().type_variables().root_var(vid
);
614 let sub_vid
= self.infcx
.inner
.borrow_mut().type_variables().sub_root_var(vid
);
615 if sub_vid
== self.for_vid_sub_root
{
616 // If sub-roots are equal, then `for_vid` and
617 // `vid` are related via subtyping.
618 Err(TypeError
::CyclicTy(self.root_ty
))
620 let probe
= self.infcx
.inner
.borrow_mut().type_variables().probe(vid
);
622 TypeVariableValue
::Known { value: u }
=> {
623 debug
!("generalize: known value {:?}", u
);
626 TypeVariableValue
::Unknown { universe }
=> {
627 match self.ambient_variance
{
628 // Invariant: no need to make a fresh type variable.
630 if self.for_universe
.can_name(universe
) {
635 // Bivariant: make a fresh var, but we
636 // may need a WF predicate. See
637 // comment on `needs_wf` field for
639 ty
::Bivariant
=> self.needs_wf
= true,
641 // Co/contravariant: this will be
642 // sufficiently constrained later on.
643 ty
::Covariant
| ty
::Contravariant
=> (),
647 *self.infcx
.inner
.borrow_mut().type_variables().var_origin(vid
);
648 let new_var_id
= self
653 .new_var(self.for_universe
, origin
);
654 let u
= self.tcx().mk_ty_var(new_var_id
);
656 // Record that we replaced `vid` with `new_var_id` as part of a generalization
657 // operation. This is needed to detect cyclic types. To see why, see the
658 // docs in the `type_variables` module.
659 self.infcx
.inner
.borrow_mut().type_variables().sub(vid
, new_var_id
);
660 debug
!("generalize: replacing original vid={:?} with new={:?}", vid
, u
);
666 ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
)) => {
667 // No matter what mode we are in,
668 // integer/floating-point types must be equal to be
672 _
=> relate
::super_relate_tys(self, t
, t
),
675 self.cache
.insert(t
, result
.clone());
682 r2
: ty
::Region
<'tcx
>,
683 ) -> RelateResult
<'tcx
, ty
::Region
<'tcx
>> {
684 assert_eq
!(r
, r2
); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
686 debug
!("generalize: regions r={:?}", r
);
689 // Never make variables for regions bound within the type itself,
690 // nor for erased regions.
691 ty
::ReLateBound(..) | ty
::ReErased
=> {
695 ty
::RePlaceholder(..)
699 | ty
::ReEarlyBound(..)
700 | ty
::ReFree(..) => {
701 // see common code below
705 // If we are in an invariant context, we can re-use the region
706 // as is, unless it happens to be in some universe that we
707 // can't name. (In the case of a region *variable*, we could
708 // use it if we promoted it into our universe, but we don't
710 if let ty
::Invariant
= self.ambient_variance
{
711 let r_universe
= self.infcx
.universe_of_region(r
);
712 if self.for_universe
.can_name(r_universe
) {
717 // FIXME: This is non-ideal because we don't give a
718 // very descriptive origin for this region variable.
719 Ok(self.infcx
.next_region_var_in_universe(MiscVariable(self.cause
.span
), self.for_universe
))
726 ) -> RelateResult
<'tcx
, ty
::Const
<'tcx
>> {
727 assert_eq
!(c
, c2
); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
730 ty
::ConstKind
::Infer(InferConst
::Var(vid
)) => {
731 let mut inner
= self.infcx
.inner
.borrow_mut();
732 let variable_table
= &mut inner
.const_unification_table();
733 let var_value
= variable_table
.probe_value(vid
);
734 match var_value
.val
{
735 ConstVariableValue
::Known { value: u }
=> {
739 ConstVariableValue
::Unknown { universe }
=> {
740 if self.for_universe
.can_name(universe
) {
743 let new_var_id
= variable_table
.new_key(ConstVarValue
{
744 origin
: var_value
.origin
,
745 val
: ConstVariableValue
::Unknown { universe: self.for_universe }
,
747 Ok(self.tcx().mk_const_var(new_var_id
, c
.ty()))
752 ty
::ConstKind
::Unevaluated(ty
::Unevaluated { def, substs, promoted }
)
753 if self.tcx().lazy_normalization() =>
755 assert_eq
!(promoted
, None
);
756 let substs
= self.relate_with_variance(
757 ty
::Variance
::Invariant
,
758 ty
::VarianceDiagInfo
::default(),
762 Ok(self.tcx().mk_const(ty
::ConstS
{
764 val
: ty
::ConstKind
::Unevaluated(ty
::Unevaluated { def, substs, promoted }
),
767 _
=> relate
::super_relate_consts(self, c
, c
),
772 pub trait ConstEquateRelation
<'tcx
>: TypeRelation
<'tcx
> {
773 /// Register an obligation that both constants must be equal to each other.
775 /// If they aren't equal then the relation doesn't hold.
776 fn const_equate_obligation(&mut self, a
: ty
::Const
<'tcx
>, b
: ty
::Const
<'tcx
>);
779 pub trait RelateResultCompare
<'tcx
, T
> {
780 fn compare
<F
>(&self, t
: T
, f
: F
) -> RelateResult
<'tcx
, T
>
782 F
: FnOnce() -> TypeError
<'tcx
>;
785 impl<'tcx
, T
: Clone
+ PartialEq
> RelateResultCompare
<'tcx
, T
> for RelateResult
<'tcx
, T
> {
786 fn compare
<F
>(&self, t
: T
, f
: F
) -> RelateResult
<'tcx
, T
>
788 F
: FnOnce() -> TypeError
<'tcx
>,
790 self.clone().and_then(|s
| if s
== t { self.clone() }
else { Err(f()) }
)
794 pub fn const_unification_error
<'tcx
>(
796 (a
, b
): (ty
::Const
<'tcx
>, ty
::Const
<'tcx
>),
797 ) -> TypeError
<'tcx
> {
798 TypeError
::ConstMismatch(ExpectedFound
::new(a_is_expected
, a
, b
))
801 fn int_unification_error
<'tcx
>(
803 v
: (ty
::IntVarValue
, ty
::IntVarValue
),
804 ) -> TypeError
<'tcx
> {
806 TypeError
::IntMismatch(ExpectedFound
::new(a_is_expected
, a
, b
))
809 fn float_unification_error
<'tcx
>(
811 v
: (ty
::FloatVarValue
, ty
::FloatVarValue
),
812 ) -> TypeError
<'tcx
> {
813 let (ty
::FloatVarValue(a
), ty
::FloatVarValue(b
)) = v
;
814 TypeError
::FloatMismatch(ExpectedFound
::new(a_is_expected
, a
, b
))
817 struct ConstInferUnifier
<'cx
, 'tcx
> {
818 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
822 param_env
: ty
::ParamEnv
<'tcx
>,
824 for_universe
: ty
::UniverseIndex
,
826 /// The vid of the const variable that is in the process of being
827 /// instantiated; if we find this within the const we are folding,
828 /// that means we would have created a cyclic const.
829 target_vid
: ty
::ConstVid
<'tcx
>,
832 // We use `TypeRelation` here to propagate `RelateResult` upwards.
834 // Both inputs are expected to be the same.
835 impl<'tcx
> TypeRelation
<'tcx
> for ConstInferUnifier
<'_
, 'tcx
> {
836 fn tcx(&self) -> TyCtxt
<'tcx
> {
840 fn param_env(&self) -> ty
::ParamEnv
<'tcx
> {
844 fn tag(&self) -> &'
static str {
848 fn a_is_expected(&self) -> bool
{
852 fn relate_with_variance
<T
: Relate
<'tcx
>>(
854 _variance
: ty
::Variance
,
855 _info
: ty
::VarianceDiagInfo
<'tcx
>,
858 ) -> RelateResult
<'tcx
, T
> {
859 // We don't care about variance here.
865 a
: ty
::Binder
<'tcx
, T
>,
866 b
: ty
::Binder
<'tcx
, T
>,
867 ) -> RelateResult
<'tcx
, ty
::Binder
<'tcx
, T
>>
871 Ok(a
.rebind(self.relate(a
.skip_binder(), b
.skip_binder())?
))
874 #[tracing::instrument(level = "debug", skip(self))]
875 fn tys(&mut self, t
: Ty
<'tcx
>, _t
: Ty
<'tcx
>) -> RelateResult
<'tcx
, Ty
<'tcx
>> {
876 debug_assert_eq
!(t
, _t
);
877 debug
!("ConstInferUnifier: t={:?}", t
);
880 &ty
::Infer(ty
::TyVar(vid
)) => {
881 let vid
= self.infcx
.inner
.borrow_mut().type_variables().root_var(vid
);
882 let probe
= self.infcx
.inner
.borrow_mut().type_variables().probe(vid
);
884 TypeVariableValue
::Known { value: u }
=> {
885 debug
!("ConstOccursChecker: known value {:?}", u
);
888 TypeVariableValue
::Unknown { universe }
=> {
889 if self.for_universe
.can_name(universe
) {
894 *self.infcx
.inner
.borrow_mut().type_variables().var_origin(vid
);
895 let new_var_id
= self
900 .new_var(self.for_universe
, origin
);
901 let u
= self.tcx().mk_ty_var(new_var_id
);
903 "ConstInferUnifier: replacing original vid={:?} with new={:?}",
910 ty
::Infer(ty
::IntVar(_
) | ty
::FloatVar(_
)) => Ok(t
),
911 _
=> relate
::super_relate_tys(self, t
, t
),
918 _r
: ty
::Region
<'tcx
>,
919 ) -> RelateResult
<'tcx
, ty
::Region
<'tcx
>> {
920 debug_assert_eq
!(r
, _r
);
921 debug
!("ConstInferUnifier: r={:?}", r
);
924 // Never make variables for regions bound within the type itself,
925 // nor for erased regions.
926 ty
::ReLateBound(..) | ty
::ReErased
=> {
930 ty
::RePlaceholder(..)
934 | ty
::ReEarlyBound(..)
935 | ty
::ReFree(..) => {
936 // see common code below
940 let r_universe
= self.infcx
.universe_of_region(r
);
941 if self.for_universe
.can_name(r_universe
) {
944 // FIXME: This is non-ideal because we don't give a
945 // very descriptive origin for this region variable.
946 Ok(self.infcx
.next_region_var_in_universe(MiscVariable(self.span
), self.for_universe
))
950 #[tracing::instrument(level = "debug", skip(self))]
955 ) -> RelateResult
<'tcx
, ty
::Const
<'tcx
>> {
956 debug_assert_eq
!(c
, _c
);
957 debug
!("ConstInferUnifier: c={:?}", c
);
960 ty
::ConstKind
::Infer(InferConst
::Var(vid
)) => {
961 // Check if the current unification would end up
962 // unifying `target_vid` with a const which contains
963 // an inference variable which is unioned with `target_vid`.
965 // Not doing so can easily result in stack overflows.
970 .const_unification_table()
971 .unioned(self.target_vid
, vid
)
973 return Err(TypeError
::CyclicConst(c
));
977 self.infcx
.inner
.borrow_mut().const_unification_table().probe_value(vid
);
978 match var_value
.val
{
979 ConstVariableValue
::Known { value: u }
=> self.consts(u
, u
),
980 ConstVariableValue
::Unknown { universe }
=> {
981 if self.for_universe
.can_name(universe
) {
985 self.infcx
.inner
.borrow_mut().const_unification_table().new_key(
987 origin
: var_value
.origin
,
988 val
: ConstVariableValue
::Unknown
{
989 universe
: self.for_universe
,
993 Ok(self.tcx().mk_const_var(new_var_id
, c
.ty()))
998 ty
::ConstKind
::Unevaluated(ty
::Unevaluated { def, substs, promoted }
)
999 if self.tcx().lazy_normalization() =>
1001 assert_eq
!(promoted
, None
);
1002 let substs
= self.relate_with_variance(
1003 ty
::Variance
::Invariant
,
1004 ty
::VarianceDiagInfo
::default(),
1008 Ok(self.tcx().mk_const(ty
::ConstS
{
1010 val
: ty
::ConstKind
::Unevaluated(ty
::Unevaluated { def, substs, promoted }
),
1013 _
=> relate
::super_relate_consts(self, c
, c
),