1 use super::combine::{CombineFields, RelationDir};
2 use super::SubregionOrigin;
4 use crate::infer::combine::ConstEquateRelation;
5 use crate::infer::{TypeVariableOrigin, TypeVariableOriginKind};
6 use crate::traits::Obligation;
7 use rustc_middle::ty::error::{ExpectedFound, TypeError};
8 use rustc_middle::ty::relate::{Cause, Relate, RelateResult, TypeRelation};
9 use rustc_middle::ty::visit::TypeVisitable;
10 use rustc_middle::ty::TyVar;
11 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt};
14 /// Ensures `a` is made a subtype of `b`. Returns `a` on success.
15 pub struct Sub<'combine, 'infcx, 'tcx> {
16 fields: &'combine mut CombineFields<'infcx, 'tcx>,
20 impl<'combine, 'infcx, 'tcx> Sub<'combine, 'infcx, 'tcx> {
22 f: &'combine mut CombineFields<'infcx, 'tcx>,
24 ) -> Sub<'combine, 'infcx, 'tcx> {
25 Sub { fields: f, a_is_expected }
28 fn with_expected_switched<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
29 self.a_is_expected = !self.a_is_expected;
31 self.a_is_expected = !self.a_is_expected;
36 impl<'tcx> TypeRelation<'tcx> for Sub<'_, '_, 'tcx> {
37 fn tag(&self) -> &'static str {
40 fn tcx(&self) -> TyCtxt<'tcx> {
44 fn param_env(&self) -> ty::ParamEnv<'tcx> {
48 fn a_is_expected(&self) -> bool {
52 fn with_cause<F, R>(&mut self, cause: Cause, f: F) -> R
54 F: FnOnce(&mut Self) -> R,
56 debug!("sub with_cause={:?}", cause);
57 let old_cause = mem::replace(&mut self.fields.cause, Some(cause));
59 debug!("sub old_cause={:?}", old_cause);
60 self.fields.cause = old_cause;
64 fn relate_with_variance<T: Relate<'tcx>>(
66 variance: ty::Variance,
67 _info: ty::VarianceDiagInfo<'tcx>,
70 ) -> RelateResult<'tcx, T> {
72 ty::Invariant => self.fields.equate(self.a_is_expected).relate(a, b),
73 ty::Covariant => self.relate(a, b),
74 ty::Bivariant => Ok(a),
75 ty::Contravariant => self.with_expected_switched(|this| this.relate(b, a)),
79 #[instrument(skip(self), level = "debug")]
80 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
85 let infcx = self.fields.infcx;
86 let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a);
87 let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b);
89 match (a.kind(), b.kind()) {
90 (&ty::Infer(TyVar(_)), &ty::Infer(TyVar(_))) => {
91 // Shouldn't have any LBR here, so we can safely put
92 // this under a binder below without fear of accidental
94 assert!(!a.has_escaping_bound_vars());
95 assert!(!b.has_escaping_bound_vars());
97 // can't make progress on `A <: B` if both A and B are
98 // type variables, so record an obligation.
99 self.fields.obligations.push(Obligation::new(
100 self.fields.trace.cause.clone(),
101 self.fields.param_env,
102 ty::Binder::dummy(ty::PredicateKind::Subtype(ty::SubtypePredicate {
103 a_is_expected: self.a_is_expected,
107 .to_predicate(self.tcx()),
112 (&ty::Infer(TyVar(a_id)), _) => {
113 self.fields.instantiate(b, RelationDir::SupertypeOf, a_id, !self.a_is_expected)?;
116 (_, &ty::Infer(TyVar(b_id))) => {
117 self.fields.instantiate(a, RelationDir::SubtypeOf, b_id, self.a_is_expected)?;
121 (&ty::Error(_), _) | (_, &ty::Error(_)) => {
122 infcx.set_tainted_by_errors();
123 Ok(self.tcx().ty_error())
126 (&ty::Opaque(a_def_id, _), &ty::Opaque(b_def_id, _)) if a_def_id == b_def_id => {
127 self.fields.infcx.super_combine_tys(self, a, b)?;
130 (&ty::Opaque(did, ..), _) | (_, &ty::Opaque(did, ..))
131 if self.fields.define_opaque_types && did.is_local() =>
133 let mut generalize = |ty, ty_is_expected| {
134 let var = infcx.next_ty_var_id_in_universe(
136 kind: TypeVariableOriginKind::MiscVariable,
137 span: self.fields.trace.cause.span,
139 ty::UniverseIndex::ROOT,
141 self.fields.instantiate(ty, RelationDir::SubtypeOf, var, ty_is_expected)?;
142 Ok(infcx.tcx.mk_ty_var(var))
144 let (a, b) = if self.a_is_expected { (a, b) } else { (b, a) };
145 let (ga, gb) = match (a.kind(), b.kind()) {
146 (&ty::Opaque(..), _) => (a, generalize(b, true)?),
147 (_, &ty::Opaque(..)) => (generalize(a, false)?, b),
150 self.fields.obligations.extend(
152 .handle_opaque_type(ga, gb, true, &self.fields.trace.cause, self.param_env())
153 // Don't leak any generalized type variables out of this
154 // subtyping relation in the case of a type error.
156 let (ga, gb) = self.fields.infcx.resolve_vars_if_possible((ga, gb));
157 if let TypeError::Sorts(sorts) = err && sorts.expected == ga && sorts.found == gb {
158 TypeError::Sorts(ExpectedFound { expected: a, found: b })
167 // Optimization of GeneratorWitness relation since we know that all
168 // free regions are replaced with bound regions during construction.
169 // This greatly speeds up subtyping of GeneratorWitness.
170 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
171 let a_types = infcx.tcx.anonymize_bound_vars(a_types);
172 let b_types = infcx.tcx.anonymize_bound_vars(b_types);
173 if a_types.bound_vars() == b_types.bound_vars() {
174 let (a_types, b_types) = infcx.replace_bound_vars_with_placeholders(
175 a_types.map_bound(|a_types| (a_types, b_types.skip_binder())),
177 for (a, b) in std::iter::zip(a_types, b_types) {
182 Err(ty::error::TypeError::Sorts(ty::relate::expected_found(self, a, b)))
187 self.fields.infcx.super_combine_tys(self, a, b)?;
197 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
198 debug!("{}.regions({:?}, {:?}) self.cause={:?}", self.tag(), a, b, self.fields.cause);
200 // FIXME -- we have more fine-grained information available
201 // from the "cause" field, we could perhaps give more tailored
203 let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone()));
208 .unwrap_region_constraints()
209 .make_subregion(origin, a, b);
218 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
219 self.fields.infcx.super_combine_consts(self, a, b)
224 a: ty::Binder<'tcx, T>,
225 b: ty::Binder<'tcx, T>,
226 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
230 self.fields.higher_ranked_sub(a, b, self.a_is_expected)?;
235 impl<'tcx> ConstEquateRelation<'tcx> for Sub<'_, '_, 'tcx> {
236 fn const_equate_obligation(&mut self, a: ty::Const<'tcx>, b: ty::Const<'tcx>) {
237 self.fields.add_const_equate_obligation(self.a_is_expected, a, b);