1 //! Least upper bound. See [`lattice`].
3 use super::combine::CombineFields;
4 use super::lattice::{self, LatticeDir};
8 use crate::infer::combine::ConstEquateRelation;
9 use crate::traits::{ObligationCause, PredicateObligation};
10 use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
11 use rustc_middle::ty::{self, Ty, TyCtxt};
13 /// "Least upper bound" (common supertype)
14 pub struct Lub<'combine, 'infcx, 'tcx> {
15 fields: &'combine mut CombineFields<'infcx, 'tcx>,
19 impl<'combine, 'infcx, 'tcx> Lub<'combine, 'infcx, 'tcx> {
21 fields: &'combine mut CombineFields<'infcx, 'tcx>,
23 ) -> Lub<'combine, 'infcx, 'tcx> {
24 Lub { fields, a_is_expected }
28 impl<'tcx> TypeRelation<'tcx> for Lub<'_, '_, 'tcx> {
29 fn tag(&self) -> &'static str {
33 fn tcx(&self) -> TyCtxt<'tcx> {
37 fn param_env(&self) -> ty::ParamEnv<'tcx> {
41 fn a_is_expected(&self) -> bool {
45 fn relate_with_variance<T: Relate<'tcx>>(
47 variance: ty::Variance,
48 _info: ty::VarianceDiagInfo<'tcx>,
51 ) -> RelateResult<'tcx, T> {
53 ty::Invariant => self.fields.equate(self.a_is_expected).relate(a, b),
54 ty::Covariant => self.relate(a, b),
55 // FIXME(#41044) -- not correct, need test
56 ty::Bivariant => Ok(a),
57 ty::Contravariant => self.fields.glb(self.a_is_expected).relate(a, b),
61 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
62 lattice::super_lattice_tys(self, a, b)
69 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
70 debug!("{}.regions({:?}, {:?})", self.tag(), a, b);
72 let origin = Subtype(Box::new(self.fields.trace.clone()));
73 Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().lub_regions(
85 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
86 self.fields.infcx.super_combine_consts(self, a, b)
91 a: ty::Binder<'tcx, T>,
92 b: ty::Binder<'tcx, T>,
93 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
97 debug!("binders(a={:?}, b={:?})", a, b);
99 // When higher-ranked types are involved, computing the LUB is
100 // very challenging, switch to invariance. This is obviously
101 // overly conservative but works ok in practice.
102 self.relate_with_variance(ty::Variance::Invariant, ty::VarianceDiagInfo::default(), a, b)?;
107 impl<'tcx> ConstEquateRelation<'tcx> for Lub<'_, '_, 'tcx> {
108 fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>) {
109 self.fields.add_const_equate_obligation(self.a_is_expected, a, b);
113 impl<'combine, 'infcx, 'tcx> LatticeDir<'infcx, 'tcx> for Lub<'combine, 'infcx, 'tcx> {
114 fn infcx(&self) -> &'infcx InferCtxt<'infcx, 'tcx> {
118 fn cause(&self) -> &ObligationCause<'tcx> {
119 &self.fields.trace.cause
122 fn add_obligations(&mut self, obligations: Vec<PredicateObligation<'tcx>>) {
123 self.fields.obligations.extend(obligations)
126 fn relate_bound(&mut self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
127 let mut sub = self.fields.sub(self.a_is_expected);
133 fn define_opaque_types(&self) -> bool {
134 self.fields.define_opaque_types