diff --git a/src/librustc_infer/infer/canonical/query_response.rs b/src/librustc_infer/infer/canonical/query_response.rs index 5cba581b9dffb..0dbebac7e36c6 100644 --- a/src/librustc_infer/infer/canonical/query_response.rs +++ b/src/librustc_infer/infer/canonical/query_response.rs @@ -525,28 +525,25 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> { result_subst: &'a CanonicalVarValues<'tcx>, ) -> impl Iterator> + 'a + Captures<'tcx> { unsubstituted_region_constraints.iter().map(move |constraint| { - let constraint = substitute_value(self.tcx, result_subst, constraint); - let ty::OutlivesPredicate(k1, r2) = constraint.skip_binder(); // restored below + let ty::OutlivesPredicate(k1, r2) = + substitute_value(self.tcx, result_subst, constraint).skip_binder(); - Obligation::new( - cause.clone(), - param_env, - match k1.unpack() { - GenericArgKind::Lifetime(r1) => ty::PredicateKind::RegionOutlives( - ty::Binder::bind(ty::OutlivesPredicate(r1, r2)), - ) - .to_predicate(self.tcx), - GenericArgKind::Type(t1) => ty::PredicateKind::TypeOutlives(ty::Binder::bind( - ty::OutlivesPredicate(t1, r2), - )) - .to_predicate(self.tcx), - GenericArgKind::Const(..) => { - // Consts cannot outlive one another, so we don't expect to - // ecounter this branch. - span_bug!(cause.span, "unexpected const outlives {:?}", constraint); - } - }, - ) + let predicate = match k1.unpack() { + GenericArgKind::Lifetime(r1) => { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2)) + } + GenericArgKind::Type(t1) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t1, r2)) + } + GenericArgKind::Const(..) => { + // Consts cannot outlive one another, so we don't expect to + // encounter this branch. + span_bug!(cause.span, "unexpected const outlives {:?}", constraint); + } + } + .potentially_quantified(self.tcx, ty::PredicateKind::ForAll); + + Obligation::new(cause.clone(), param_env, predicate) }) } @@ -666,10 +663,8 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for QueryTypeRelatingDelegate<'_, 'tcx> { self.obligations.push(Obligation { cause: self.cause.clone(), param_env: self.param_env, - predicate: ty::PredicateKind::RegionOutlives(ty::Binder::dummy(ty::OutlivesPredicate( - sup, sub, - ))) - .to_predicate(self.infcx.tcx), + predicate: ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(sup, sub)) + .to_predicate(self.infcx.tcx), recursion_depth: 0, }); } diff --git a/src/librustc_infer/infer/combine.rs b/src/librustc_infer/infer/combine.rs index c63464e5baec9..5b4d91de3ca92 100644 --- a/src/librustc_infer/infer/combine.rs +++ b/src/librustc_infer/infer/combine.rs @@ -308,7 +308,7 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { self.obligations.push(Obligation::new( self.trace.cause.clone(), self.param_env, - ty::PredicateKind::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx), + ty::PredicateAtom::WellFormed(b_ty.into()).to_predicate(self.infcx.tcx), )); } @@ -400,9 +400,9 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { b: &'tcx ty::Const<'tcx>, ) { let predicate = if a_is_expected { - ty::PredicateKind::ConstEquate(a, b) + ty::PredicateAtom::ConstEquate(a, b) } else { - ty::PredicateKind::ConstEquate(b, a) + ty::PredicateAtom::ConstEquate(b, a) }; self.obligations.push(Obligation::new( self.trace.cause.clone(), diff --git a/src/librustc_infer/infer/outlives/mod.rs b/src/librustc_infer/infer/outlives/mod.rs index 541a2f18045c4..a1e7f1fa3e5e7 100644 --- a/src/librustc_infer/infer/outlives/mod.rs +++ b/src/librustc_infer/infer/outlives/mod.rs @@ -6,23 +6,29 @@ pub mod verify; use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty; +use rustc_middle::ty::fold::TypeFoldable; pub fn explicit_outlives_bounds<'tcx>( param_env: ty::ParamEnv<'tcx>, ) -> impl Iterator> + 'tcx { debug!("explicit_outlives_bounds()"); - param_env.caller_bounds().into_iter().filter_map(move |predicate| match predicate.kind() { - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => None, - ty::PredicateKind::RegionOutlives(ref data) => data - .no_bound_vars() - .map(|ty::OutlivesPredicate(r_a, r_b)| OutlivesBound::RegionSubRegion(r_b, r_a)), - }) + param_env + .caller_bounds() + .into_iter() + .map(ty::Predicate::skip_binders) + .filter(|atom| !atom.has_escaping_bound_vars()) + .filter_map(move |atom| match atom { + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => None, + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { + Some(OutlivesBound::RegionSubRegion(r_b, r_a)) + } + }) } diff --git a/src/librustc_infer/infer/sub.rs b/src/librustc_infer/infer/sub.rs index d190f7e434298..4f860c77d6541 100644 --- a/src/librustc_infer/infer/sub.rs +++ b/src/librustc_infer/infer/sub.rs @@ -100,11 +100,11 @@ impl TypeRelation<'tcx> for Sub<'combine, 'infcx, 'tcx> { self.fields.obligations.push(Obligation::new( self.fields.trace.cause.clone(), self.fields.param_env, - ty::PredicateKind::Subtype(ty::Binder::dummy(ty::SubtypePredicate { + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a_is_expected: self.a_is_expected, a, b, - })) + }) .to_predicate(self.tcx()), )); diff --git a/src/librustc_infer/traits/util.rs b/src/librustc_infer/traits/util.rs index 4ae7e417a8f67..93fc7f1f3b8a7 100644 --- a/src/librustc_infer/traits/util.rs +++ b/src/librustc_infer/traits/util.rs @@ -3,51 +3,20 @@ use smallvec::smallvec; use crate::traits::{Obligation, ObligationCause, PredicateObligation}; use rustc_data_structures::fx::FxHashSet; use rustc_middle::ty::outlives::Component; -use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, TyCtxt, WithConstness}; +use rustc_middle::ty::{self, ToPredicate, TyCtxt, WithConstness}; use rustc_span::Span; pub fn anonymize_predicate<'tcx>( tcx: TyCtxt<'tcx>, pred: ty::Predicate<'tcx>, ) -> ty::Predicate<'tcx> { - let kind = pred.kind(); - let new = match kind { - &ty::PredicateKind::Trait(ref data, constness) => { - ty::PredicateKind::Trait(tcx.anonymize_late_bound_regions(data), constness) + match pred.kind() { + ty::PredicateKind::ForAll(binder) => { + let new = ty::PredicateKind::ForAll(tcx.anonymize_late_bound_regions(binder)); + tcx.reuse_or_mk_predicate(pred, new) } - - ty::PredicateKind::RegionOutlives(data) => { - ty::PredicateKind::RegionOutlives(tcx.anonymize_late_bound_regions(data)) - } - - ty::PredicateKind::TypeOutlives(data) => { - ty::PredicateKind::TypeOutlives(tcx.anonymize_late_bound_regions(data)) - } - - ty::PredicateKind::Projection(data) => { - ty::PredicateKind::Projection(tcx.anonymize_late_bound_regions(data)) - } - - &ty::PredicateKind::WellFormed(data) => ty::PredicateKind::WellFormed(data), - - &ty::PredicateKind::ObjectSafe(data) => ty::PredicateKind::ObjectSafe(data), - - &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) - } - - ty::PredicateKind::Subtype(data) => { - ty::PredicateKind::Subtype(tcx.anonymize_late_bound_regions(data)) - } - - &ty::PredicateKind::ConstEvaluatable(def_id, substs) => { - ty::PredicateKind::ConstEvaluatable(def_id, substs) - } - - ty::PredicateKind::ConstEquate(c1, c2) => ty::PredicateKind::ConstEquate(c1, c2), - }; - - if new != *kind { new.to_predicate(tcx) } else { pred } + ty::PredicateKind::Atom(_) => pred, + } } struct PredicateSet<'tcx> { @@ -158,15 +127,16 @@ impl Elaborator<'tcx> { fn elaborate(&mut self, obligation: &PredicateObligation<'tcx>) { let tcx = self.visited.tcx; - match obligation.predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => { + + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) => { // Get predicates declared on the trait. let predicates = tcx.super_predicates_of(data.def_id()); - let obligations = predicates.predicates.iter().map(|(pred, span)| { + let obligations = predicates.predicates.iter().map(|&(pred, span)| { predicate_obligation( - pred.subst_supertrait(tcx, &data.to_poly_trait_ref()), - Some(*span), + pred.subst_supertrait(tcx, &ty::Binder::bind(data.trait_ref)), + Some(span), ) }); debug!("super_predicates: data={:?}", data); @@ -180,36 +150,36 @@ impl Elaborator<'tcx> { self.stack.extend(obligations); } - ty::PredicateKind::WellFormed(..) => { + ty::PredicateAtom::WellFormed(..) => { // Currently, we do not elaborate WF predicates, // although we easily could. } - ty::PredicateKind::ObjectSafe(..) => { + ty::PredicateAtom::ObjectSafe(..) => { // Currently, we do not elaborate object-safe // predicates. } - ty::PredicateKind::Subtype(..) => { + ty::PredicateAtom::Subtype(..) => { // Currently, we do not "elaborate" predicates like `X <: Y`, // though conceivably we might. } - ty::PredicateKind::Projection(..) => { + ty::PredicateAtom::Projection(..) => { // Nothing to elaborate in a projection predicate. } - ty::PredicateKind::ClosureKind(..) => { + ty::PredicateAtom::ClosureKind(..) => { // Nothing to elaborate when waiting for a closure's kind to be inferred. } - ty::PredicateKind::ConstEvaluatable(..) => { + ty::PredicateAtom::ConstEvaluatable(..) => { // Currently, we do not elaborate const-evaluatable // predicates. } - ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ConstEquate(..) => { // Currently, we do not elaborate const-equate // predicates. } - ty::PredicateKind::RegionOutlives(..) => { + ty::PredicateAtom::RegionOutlives(..) => { // Nothing to elaborate from `'a: 'b`. } - ty::PredicateKind::TypeOutlives(ref data) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => { // We know that `T: 'a` for some type `T`. We can // often elaborate this. For example, if we know that // `[U]: 'a`, that implies that `U: 'a`. Similarly, if @@ -224,8 +194,6 @@ impl Elaborator<'tcx> { // consider this as evidence that `T: 'static`, but // I'm a bit wary of such constructions and so for now // I want to be conservative. --nmatsakis - let ty_max = data.skip_binder().0; - let r_min = data.skip_binder().1; if r_min.is_late_bound() { return; } @@ -241,16 +209,16 @@ impl Elaborator<'tcx> { if r.is_late_bound() { None } else { - Some(ty::PredicateKind::RegionOutlives(ty::Binder::dummy( - ty::OutlivesPredicate(r, r_min), + Some(ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate( + r, r_min, ))) } } Component::Param(p) => { let ty = tcx.mk_ty_param(p.index, p.name); - Some(ty::PredicateKind::TypeOutlives(ty::Binder::dummy( - ty::OutlivesPredicate(ty, r_min), + Some(ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate( + ty, r_min, ))) } @@ -331,8 +299,8 @@ impl<'tcx, I: Iterator>> Iterator for FilterToT fn next(&mut self) -> Option> { while let Some(obligation) = self.base_iterator.next() { - if let ty::PredicateKind::Trait(data, _) = obligation.predicate.kind() { - return Some(data.to_poly_trait_ref()); + if let Some(data) = obligation.predicate.to_opt_poly_trait_ref() { + return Some(data); } } None diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 5c4be715add79..a45817beea164 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -1202,13 +1202,13 @@ declare_lint_pass!( impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { use rustc_middle::ty::fold::TypeFoldable; - use rustc_middle::ty::PredicateKind::*; + use rustc_middle::ty::PredicateAtom::*; if cx.tcx.features().trivial_bounds { let def_id = cx.tcx.hir().local_def_id(item.hir_id); let predicates = cx.tcx.predicates_of(def_id); for &(predicate, span) in predicates.predicates { - let predicate_kind_name = match predicate.kind() { + let predicate_kind_name = match predicate.skip_binders() { Trait(..) => "Trait", TypeOutlives(..) | RegionOutlives(..) => "Lifetime", @@ -1497,14 +1497,11 @@ impl ExplicitOutlivesRequirements { ) -> Vec> { inferred_outlives .iter() - .filter_map(|(pred, _)| match pred.kind() { - ty::PredicateKind::RegionOutlives(outlives) => { - let outlives = outlives.skip_binder(); - match outlives.0 { - ty::ReEarlyBound(ebr) if ebr.index == index => Some(outlives.1), - _ => None, - } - } + .filter_map(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a { + ty::ReEarlyBound(ebr) if ebr.index == index => Some(b), + _ => None, + }, _ => None, }) .collect() @@ -1516,10 +1513,9 @@ impl ExplicitOutlivesRequirements { ) -> Vec> { inferred_outlives .iter() - .filter_map(|(pred, _)| match pred.kind() { - ty::PredicateKind::TypeOutlives(outlives) => { - let outlives = outlives.skip_binder(); - outlives.0.is_param(index).then_some(outlives.1) + .filter_map(|(pred, _)| match pred.skip_binders() { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(a, b)) => { + a.is_param(index).then_some(b) } _ => None, }) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 6d6c7b24101ca..dcb44ab644498 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -146,11 +146,11 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ty::Opaque(def, _) => { let mut has_emitted = false; for (predicate, _) in cx.tcx.predicates_of(def).predicates { - if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = - predicate.kind() + // We only look at the `DefId`, so it is safe to skip the binder here. + if let ty::PredicateAtom::Trait(ref poly_trait_predicate, _) = + predicate.skip_binders() { - let trait_ref = poly_trait_predicate.skip_binder().trait_ref; - let def_id = trait_ref.def_id; + let def_id = poly_trait_predicate.trait_ref.def_id; let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix,); if check_must_use_def(cx, def_id, span, descr_pre, descr_post) { diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs index 3dd57eea2348f..eeb58a0c55a3e 100644 --- a/src/librustc_middle/ty/context.rs +++ b/src/librustc_middle/ty/context.rs @@ -102,7 +102,6 @@ impl<'tcx> CtxtInterners<'tcx> { projs: Default::default(), place_elems: Default::default(), const_: Default::default(), - chalk_environment_clause_list: Default::default(), } } @@ -2128,16 +2127,25 @@ impl<'tcx> TyCtxt<'tcx> { #[allow(rustc::usage_of_ty_tykind)] #[inline] - pub fn mk_ty(&self, st: TyKind<'tcx>) -> Ty<'tcx> { + pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { self.interners.intern_ty(st) } #[inline] - pub fn mk_predicate(&self, kind: PredicateKind<'tcx>) -> Predicate<'tcx> { + pub fn mk_predicate(self, kind: PredicateKind<'tcx>) -> Predicate<'tcx> { let inner = self.interners.intern_predicate(kind); Predicate { inner } } + #[inline] + pub fn reuse_or_mk_predicate( + self, + pred: Predicate<'tcx>, + kind: PredicateKind<'tcx>, + ) -> Predicate<'tcx> { + if *pred.kind() != kind { self.mk_predicate(kind) } else { pred } + } + pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> { match tm { ast::IntTy::Isize => self.types.isize, diff --git a/src/librustc_middle/ty/flags.rs b/src/librustc_middle/ty/flags.rs index 11a8bedb6605b..27f50c240db67 100644 --- a/src/librustc_middle/ty/flags.rs +++ b/src/librustc_middle/ty/flags.rs @@ -203,55 +203,49 @@ impl FlagComputation { fn add_predicate_kind(&mut self, kind: &ty::PredicateKind<'_>) { match kind { - ty::PredicateKind::Trait(trait_pred, _constness) => { + ty::PredicateKind::ForAll(binder) => { let mut computation = FlagComputation::new(); - computation.add_substs(trait_pred.skip_binder().trait_ref.substs); - self.add_bound_computation(computation); - } - ty::PredicateKind::RegionOutlives(poly_outlives) => { - let mut computation = FlagComputation::new(); - let ty::OutlivesPredicate(a, b) = poly_outlives.skip_binder(); - computation.add_region(a); - computation.add_region(b); + computation.add_predicate_atom(binder.skip_binder()); self.add_bound_computation(computation); } - ty::PredicateKind::TypeOutlives(poly_outlives) => { - let mut computation = FlagComputation::new(); - let ty::OutlivesPredicate(ty, region) = poly_outlives.skip_binder(); - computation.add_ty(ty); - computation.add_region(region); + &ty::PredicateKind::Atom(atom) => self.add_predicate_atom(atom), + } + } - self.add_bound_computation(computation); + fn add_predicate_atom(&mut self, atom: ty::PredicateAtom<'_>) { + match atom { + ty::PredicateAtom::Trait(trait_pred, _constness) => { + self.add_substs(trait_pred.trait_ref.substs); } - ty::PredicateKind::Subtype(poly_subtype) => { - let mut computation = FlagComputation::new(); - let ty::SubtypePredicate { a_is_expected: _, a, b } = poly_subtype.skip_binder(); - computation.add_ty(a); - computation.add_ty(b); - - self.add_bound_computation(computation); + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(a, b)) => { + self.add_region(a); + self.add_region(b); } - &ty::PredicateKind::Projection(projection) => { - let mut computation = FlagComputation::new(); - let ty::ProjectionPredicate { projection_ty, ty } = projection.skip_binder(); - computation.add_projection_ty(projection_ty); - computation.add_ty(ty); - - self.add_bound_computation(computation); + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { + self.add_ty(ty); + self.add_region(region); + } + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { + self.add_ty(a); + self.add_ty(b); + } + ty::PredicateAtom::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { + self.add_projection_ty(projection_ty); + self.add_ty(ty); } - ty::PredicateKind::WellFormed(arg) => { - self.add_substs(slice::from_ref(arg)); + ty::PredicateAtom::WellFormed(arg) => { + self.add_substs(slice::from_ref(&arg)); } - ty::PredicateKind::ObjectSafe(_def_id) => {} - ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { + ty::PredicateAtom::ObjectSafe(_def_id) => {} + ty::PredicateAtom::ClosureKind(_def_id, substs, _kind) => { self.add_substs(substs); } - ty::PredicateKind::ConstEvaluatable(_def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(_def_id, substs) => { self.add_substs(substs); } - ty::PredicateKind::ConstEquate(expected, found) => { + ty::PredicateAtom::ConstEquate(expected, found) => { self.add_const(expected); self.add_const(found); } diff --git a/src/librustc_middle/ty/mod.rs b/src/librustc_middle/ty/mod.rs index a5ddcdfdb0408..d1c6d3be5f4bb 100644 --- a/src/librustc_middle/ty/mod.rs +++ b/src/librustc_middle/ty/mod.rs @@ -1018,7 +1018,7 @@ crate struct PredicateInner<'tcx> { } #[cfg(target_arch = "x86_64")] -static_assert_size!(PredicateInner<'_>, 40); +static_assert_size!(PredicateInner<'_>, 48); #[derive(Clone, Copy, Lift)] pub struct Predicate<'tcx> { @@ -1048,6 +1048,44 @@ impl<'tcx> Predicate<'tcx> { pub fn kind(self) -> &'tcx PredicateKind<'tcx> { &self.inner.kind } + + /// Returns the inner `PredicateAtom`. + /// + /// The returned atom may contain unbound variables bound to binders skipped in this method. + /// It is safe to reapply binders to the given atom. + /// + /// Note that this method panics in case this predicate has unbound variables. + pub fn skip_binders(self) -> PredicateAtom<'tcx> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder.skip_binder(), + &PredicateKind::Atom(atom) => { + debug_assert!(!atom.has_escaping_bound_vars()); + atom + } + } + } + + /// Returns the inner `PredicateAtom`. + /// + /// Note that this method does not check if the predicate has unbound variables. + /// + /// Rebinding the returned atom can causes the previously bound variables + /// to end up at the wrong binding level. + pub fn skip_binders_unchecked(self) -> PredicateAtom<'tcx> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder.skip_binder(), + &PredicateKind::Atom(atom) => atom, + } + } + + /// Allows using a `Binder>` even if the given predicate previously + /// contained unbound variables by shifting these variables outwards. + pub fn bound_atom(self, tcx: TyCtxt<'tcx>) -> Binder> { + match self.kind() { + &PredicateKind::ForAll(binder) => binder, + &PredicateKind::Atom(atom) => Binder::wrap_nonbinding(tcx, atom), + } + } } impl<'a, 'tcx> HashStable> for Predicate<'tcx> { @@ -1068,6 +1106,14 @@ impl<'a, 'tcx> HashStable> for Predicate<'tcx> { #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)] #[derive(HashStable, TypeFoldable)] pub enum PredicateKind<'tcx> { + /// `for<'a>: ...` + ForAll(Binder>), + Atom(PredicateAtom<'tcx>), +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)] +#[derive(HashStable, TypeFoldable)] +pub enum PredicateAtom<'tcx> { /// Corresponds to `where Foo: Bar`. `Foo` here would be /// the `Self` type of the trait reference and `A`, `B`, and `C` /// would be the type parameters. @@ -1075,17 +1121,17 @@ pub enum PredicateKind<'tcx> { /// A trait predicate will have `Constness::Const` if it originates /// from a bound on a `const fn` without the `?const` opt-out (e.g., /// `const fn foobar() {}`). - Trait(PolyTraitPredicate<'tcx>, Constness), + Trait(TraitPredicate<'tcx>, Constness), /// `where 'a: 'b` - RegionOutlives(PolyRegionOutlivesPredicate<'tcx>), + RegionOutlives(RegionOutlivesPredicate<'tcx>), /// `where T: 'a` - TypeOutlives(PolyTypeOutlivesPredicate<'tcx>), + TypeOutlives(TypeOutlivesPredicate<'tcx>), /// `where ::Name == X`, approximately. /// See the `ProjectionPredicate` struct for details. - Projection(PolyProjectionPredicate<'tcx>), + Projection(ProjectionPredicate<'tcx>), /// No syntax: `T` well-formed. WellFormed(GenericArg<'tcx>), @@ -1099,7 +1145,7 @@ pub enum PredicateKind<'tcx> { ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind), /// `T1 <: T2` - Subtype(PolySubtypePredicate<'tcx>), + Subtype(SubtypePredicate<'tcx>), /// Constant initializer must evaluate successfully. ConstEvaluatable(ty::WithOptConstParam, SubstsRef<'tcx>), @@ -1108,6 +1154,22 @@ pub enum PredicateKind<'tcx> { ConstEquate(&'tcx Const<'tcx>, &'tcx Const<'tcx>), } +impl<'tcx> PredicateAtom<'tcx> { + /// Wraps `self` with the given qualifier if this predicate has any unbound variables. + pub fn potentially_quantified( + self, + tcx: TyCtxt<'tcx>, + qualifier: impl FnOnce(Binder>) -> PredicateKind<'tcx>, + ) -> Predicate<'tcx> { + if self.has_escaping_bound_vars() { + qualifier(Binder::bind(self)) + } else { + PredicateKind::Atom(self) + } + .to_predicate(tcx) + } +} + /// The crate outlives map is computed during typeck and contains the /// outlives of every item in the local crate. You should not use it /// directly, because to do so will make your pass dependent on the @@ -1119,7 +1181,7 @@ pub struct CratePredicatesMap<'tcx> { /// For each struct with outlive bounds, maps to a vector of the /// predicate of its outlive bounds. If an item has no outlives /// bounds, it will have no entry. - pub predicates: FxHashMap, Span)]>, + pub predicates: FxHashMap, Span)]>, } impl<'tcx> Predicate<'tcx> { @@ -1132,7 +1194,7 @@ impl<'tcx> Predicate<'tcx> { self, tcx: TyCtxt<'tcx>, trait_ref: &ty::PolyTraitRef<'tcx>, - ) -> ty::Predicate<'tcx> { + ) -> Predicate<'tcx> { // The interaction between HRTB and supertraits is not entirely // obvious. Let me walk you (and myself) through an example. // @@ -1192,39 +1254,10 @@ impl<'tcx> Predicate<'tcx> { // substitution code expects equal binding levels in the values // from the substitution and the value being substituted into, and // this trick achieves that). - - let substs = &trait_ref.skip_binder().substs; - let kind = self.kind(); - let new = match kind { - &PredicateKind::Trait(ref binder, constness) => { - PredicateKind::Trait(binder.map_bound(|data| data.subst(tcx, substs)), constness) - } - PredicateKind::Subtype(binder) => { - PredicateKind::Subtype(binder.map_bound(|data| data.subst(tcx, substs))) - } - PredicateKind::RegionOutlives(binder) => { - PredicateKind::RegionOutlives(binder.map_bound(|data| data.subst(tcx, substs))) - } - PredicateKind::TypeOutlives(binder) => { - PredicateKind::TypeOutlives(binder.map_bound(|data| data.subst(tcx, substs))) - } - PredicateKind::Projection(binder) => { - PredicateKind::Projection(binder.map_bound(|data| data.subst(tcx, substs))) - } - &PredicateKind::WellFormed(data) => PredicateKind::WellFormed(data.subst(tcx, substs)), - &PredicateKind::ObjectSafe(trait_def_id) => PredicateKind::ObjectSafe(trait_def_id), - &PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { - PredicateKind::ClosureKind(closure_def_id, closure_substs.subst(tcx, substs), kind) - } - &PredicateKind::ConstEvaluatable(def_id, const_substs) => { - PredicateKind::ConstEvaluatable(def_id, const_substs.subst(tcx, substs)) - } - PredicateKind::ConstEquate(c1, c2) => { - PredicateKind::ConstEquate(c1.subst(tcx, substs), c2.subst(tcx, substs)) - } - }; - - if new != *kind { new.to_predicate(tcx) } else { self } + let substs = trait_ref.skip_binder().substs; + let pred = self.skip_binders(); + let new = pred.subst(tcx, substs); + if new != pred { new.potentially_quantified(tcx, PredicateKind::ForAll) } else { self } } } @@ -1349,86 +1382,87 @@ impl ToPredicate<'tcx> for PredicateKind<'tcx> { } } -impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { +impl ToPredicate<'tcx> for PredicateAtom<'tcx> { + #[inline(always)] fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - ty::PredicateKind::Trait( - ty::Binder::dummy(ty::TraitPredicate { trait_ref: self.value }), - self.constness, - ) - .to_predicate(tcx) + debug_assert!(!self.has_escaping_bound_vars(), "escaping bound vars for {:?}", self); + tcx.mk_predicate(PredicateKind::Atom(self)) } } -impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&TraitRef<'tcx>> { +impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - ty::PredicateKind::Trait( - ty::Binder::dummy(ty::TraitPredicate { trait_ref: *self.value }), - self.constness, - ) - .to_predicate(tcx) + PredicateAtom::Trait(ty::TraitPredicate { trait_ref: self.value }, self.constness) + .to_predicate(tcx) } } impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness) - .to_predicate(tcx) + ConstnessAnd { + value: self.value.map_bound(|trait_ref| ty::TraitPredicate { trait_ref }), + constness: self.constness, + } + .to_predicate(tcx) } } -impl<'tcx> ToPredicate<'tcx> for ConstnessAnd<&PolyTraitRef<'tcx>> { +impl<'tcx> ToPredicate<'tcx> for ConstnessAnd> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - ty::PredicateKind::Trait(self.value.to_poly_trait_predicate(), self.constness) - .to_predicate(tcx) + PredicateAtom::Trait(self.value.skip_binder(), self.constness) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - PredicateKind::RegionOutlives(self).to_predicate(tcx) + PredicateAtom::RegionOutlives(self.skip_binder()) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - PredicateKind::TypeOutlives(self).to_predicate(tcx) + PredicateAtom::TypeOutlives(self.skip_binder()) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> { fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { - PredicateKind::Projection(self).to_predicate(tcx) + PredicateAtom::Projection(self.skip_binder()) + .potentially_quantified(tcx, PredicateKind::ForAll) } } impl<'tcx> Predicate<'tcx> { pub fn to_opt_poly_trait_ref(self) -> Option> { - match self.kind() { - &PredicateKind::Trait(ref t, _) => Some(t.to_poly_trait_ref()), - PredicateKind::Projection(..) - | PredicateKind::Subtype(..) - | PredicateKind::RegionOutlives(..) - | PredicateKind::WellFormed(..) - | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) - | PredicateKind::TypeOutlives(..) - | PredicateKind::ConstEvaluatable(..) - | PredicateKind::ConstEquate(..) => None, + match self.skip_binders() { + PredicateAtom::Trait(t, _) => Some(ty::Binder::bind(t.trait_ref)), + PredicateAtom::Projection(..) + | PredicateAtom::Subtype(..) + | PredicateAtom::RegionOutlives(..) + | PredicateAtom::WellFormed(..) + | PredicateAtom::ObjectSafe(..) + | PredicateAtom::ClosureKind(..) + | PredicateAtom::TypeOutlives(..) + | PredicateAtom::ConstEvaluatable(..) + | PredicateAtom::ConstEquate(..) => None, } } pub fn to_opt_type_outlives(self) -> Option> { - match self.kind() { - &PredicateKind::TypeOutlives(data) => Some(data), - PredicateKind::Trait(..) - | PredicateKind::Projection(..) - | PredicateKind::Subtype(..) - | PredicateKind::RegionOutlives(..) - | PredicateKind::WellFormed(..) - | PredicateKind::ObjectSafe(..) - | PredicateKind::ClosureKind(..) - | PredicateKind::ConstEvaluatable(..) - | PredicateKind::ConstEquate(..) => None, + match self.skip_binders() { + PredicateAtom::TypeOutlives(data) => Some(ty::Binder::bind(data)), + PredicateAtom::Trait(..) + | PredicateAtom::Projection(..) + | PredicateAtom::Subtype(..) + | PredicateAtom::RegionOutlives(..) + | PredicateAtom::WellFormed(..) + | PredicateAtom::ObjectSafe(..) + | PredicateAtom::ClosureKind(..) + | PredicateAtom::ConstEvaluatable(..) + | PredicateAtom::ConstEquate(..) => None, } } } @@ -1692,7 +1726,7 @@ pub struct ParamEnv<'tcx> { // Specifically, the low bit represents Reveal, with 0 meaning `UserFacing` // and 1 meaning `All`. The rest is the pointer. // - // This relies on the List> type having at least 2-byte + // This relies on the List> type having at least 2-byte // alignment. Lists start with a usize and are repr(C) so this should be // fine; there is a debug_assert in the constructor as well. // @@ -1706,7 +1740,7 @@ pub struct ParamEnv<'tcx> { /// /// Note: This is packed into the `packed_data` usize above, use the /// `caller_bounds()` method to access it. - caller_bounds: PhantomData<&'tcx List>>, + caller_bounds: PhantomData<&'tcx List>>, /// Typically, this is `Reveal::UserFacing`, but during codegen we /// want `Reveal::All`. @@ -1784,7 +1818,7 @@ impl<'tcx> ParamEnv<'tcx> { } #[inline] - pub fn caller_bounds(self) -> &'tcx List> { + pub fn caller_bounds(self) -> &'tcx List> { // mask out bottom bit unsafe { &*((self.packed_data & (!1)) as *const _) } } @@ -1809,7 +1843,7 @@ impl<'tcx> ParamEnv<'tcx> { /// Construct a trait environment with the given set of predicates. #[inline] pub fn new( - caller_bounds: &'tcx List>, + caller_bounds: &'tcx List>, reveal: Reveal, def_id: Option, ) -> Self { diff --git a/src/librustc_middle/ty/print/pretty.rs b/src/librustc_middle/ty/print/pretty.rs index 043d85cb6efa6..3bb9c20370e8c 100644 --- a/src/librustc_middle/ty/print/pretty.rs +++ b/src/librustc_middle/ty/print/pretty.rs @@ -572,7 +572,14 @@ pub trait PrettyPrinter<'tcx>: let mut is_sized = false; p!(write("impl")); for predicate in bounds.predicates { - if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() { + // Note: We can't use `to_opt_poly_trait_ref` here as `predicate` + // may contain unbound variables. We therefore do this manually. + // + // FIXME(lcnr): Find out why exactly this is the case :) + if let ty::PredicateAtom::Trait(pred, _) = + predicate.bound_atom(self.tcx()).skip_binder() + { + let trait_ref = ty::Binder::bind(pred.trait_ref); // Don't print +Sized, but rather +?Sized if absent. if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() { is_sized = true; @@ -2006,38 +2013,45 @@ define_print_and_forward_display! { ty::Predicate<'tcx> { match self.kind() { - &ty::PredicateKind::Trait(ref data, constness) => { + &ty::PredicateKind::Atom(atom) => p!(print(atom)), + ty::PredicateKind::ForAll(binder) => p!(print(binder)), + } + } + + ty::PredicateAtom<'tcx> { + match *self { + ty::PredicateAtom::Trait(ref data, constness) => { if let hir::Constness::Const = constness { p!(write("const ")); } p!(print(data)) } - ty::PredicateKind::Subtype(predicate) => p!(print(predicate)), - ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)), - ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)), - ty::PredicateKind::Projection(predicate) => p!(print(predicate)), - ty::PredicateKind::WellFormed(arg) => p!(print(arg), write(" well-formed")), - &ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)), + ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)), + ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)), + ty::PredicateAtom::Projection(predicate) => p!(print(predicate)), + ty::PredicateAtom::WellFormed(arg) => p!(print(arg), write(" well-formed")), + ty::PredicateAtom::ObjectSafe(trait_def_id) => { p!(write("the trait `"), - print_def_path(trait_def_id, &[]), - write("` is object-safe")) + print_def_path(trait_def_id, &[]), + write("` is object-safe")) } - &ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => { p!(write("the closure `"), - print_value_path(closure_def_id, &[]), - write("` implements the trait `{}`", kind)) + print_value_path(closure_def_id, &[]), + write("` implements the trait `{}`", kind)) } - &ty::PredicateKind::ConstEvaluatable(def, substs) => { + ty::PredicateAtom::ConstEvaluatable(def, substs) => { p!(write("the constant `"), - print_value_path(def.did, substs), - write("` can be evaluated")) + print_value_path(def.did, substs), + write("` can be evaluated")) } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { p!(write("the constant `"), - print(c1), - write("` equals `"), - print(c2), - write("`")) + print(c1), + write("` equals `"), + print(c2), + write("`")) } } } diff --git a/src/librustc_middle/ty/structural_impls.rs b/src/librustc_middle/ty/structural_impls.rs index f04bfe648fb78..21b8d7101a304 100644 --- a/src/librustc_middle/ty/structural_impls.rs +++ b/src/librustc_middle/ty/structural_impls.rs @@ -226,27 +226,36 @@ impl fmt::Debug for ty::Predicate<'tcx> { impl fmt::Debug for ty::PredicateKind<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - ty::PredicateKind::Trait(ref a, constness) => { + ty::PredicateKind::ForAll(binder) => write!(f, "ForAll({:?})", binder), + ty::PredicateKind::Atom(atom) => write!(f, "{:?}", atom), + } + } +} + +impl fmt::Debug for ty::PredicateAtom<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + ty::PredicateAtom::Trait(ref a, constness) => { if let hir::Constness::Const = constness { write!(f, "const ")?; } a.fmt(f) } - ty::PredicateKind::Subtype(ref pair) => pair.fmt(f), - ty::PredicateKind::RegionOutlives(ref pair) => pair.fmt(f), - ty::PredicateKind::TypeOutlives(ref pair) => pair.fmt(f), - ty::PredicateKind::Projection(ref pair) => pair.fmt(f), - ty::PredicateKind::WellFormed(data) => write!(f, "WellFormed({:?})", data), - ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::Subtype(ref pair) => pair.fmt(f), + ty::PredicateAtom::RegionOutlives(ref pair) => pair.fmt(f), + ty::PredicateAtom::TypeOutlives(ref pair) => pair.fmt(f), + ty::PredicateAtom::Projection(ref pair) => pair.fmt(f), + ty::PredicateAtom::WellFormed(data) => write!(f, "WellFormed({:?})", data), + ty::PredicateAtom::ObjectSafe(trait_def_id) => { write!(f, "ObjectSafe({:?})", trait_def_id) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind) } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs) } - ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), + ty::PredicateAtom::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), } } } @@ -476,37 +485,45 @@ impl<'a, 'tcx> Lift<'tcx> for ty::ExistentialProjection<'a> { impl<'a, 'tcx> Lift<'tcx> for ty::PredicateKind<'a> { type Lifted = ty::PredicateKind<'tcx>; + fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { + match self { + ty::PredicateKind::ForAll(binder) => tcx.lift(binder).map(ty::PredicateKind::ForAll), + ty::PredicateKind::Atom(atom) => tcx.lift(atom).map(ty::PredicateKind::Atom), + } + } +} + +impl<'a, 'tcx> Lift<'tcx> for ty::PredicateAtom<'a> { + type Lifted = ty::PredicateAtom<'tcx>; fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { match *self { - ty::PredicateKind::Trait(ref binder, constness) => { - tcx.lift(binder).map(|binder| ty::PredicateKind::Trait(binder, constness)) - } - ty::PredicateKind::Subtype(ref binder) => { - tcx.lift(binder).map(ty::PredicateKind::Subtype) + ty::PredicateAtom::Trait(ref data, constness) => { + tcx.lift(data).map(|data| ty::PredicateAtom::Trait(data, constness)) } - ty::PredicateKind::RegionOutlives(ref binder) => { - tcx.lift(binder).map(ty::PredicateKind::RegionOutlives) + ty::PredicateAtom::Subtype(ref data) => tcx.lift(data).map(ty::PredicateAtom::Subtype), + ty::PredicateAtom::RegionOutlives(ref data) => { + tcx.lift(data).map(ty::PredicateAtom::RegionOutlives) } - ty::PredicateKind::TypeOutlives(ref binder) => { - tcx.lift(binder).map(ty::PredicateKind::TypeOutlives) + ty::PredicateAtom::TypeOutlives(ref data) => { + tcx.lift(data).map(ty::PredicateAtom::TypeOutlives) } - ty::PredicateKind::Projection(ref binder) => { - tcx.lift(binder).map(ty::PredicateKind::Projection) + ty::PredicateAtom::Projection(ref data) => { + tcx.lift(data).map(ty::PredicateAtom::Projection) } - ty::PredicateKind::WellFormed(ty) => tcx.lift(&ty).map(ty::PredicateKind::WellFormed), - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::WellFormed(ty) => tcx.lift(&ty).map(ty::PredicateAtom::WellFormed), + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { tcx.lift(&closure_substs).map(|closure_substs| { - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) }) } - ty::PredicateKind::ObjectSafe(trait_def_id) => { - Some(ty::PredicateKind::ObjectSafe(trait_def_id)) + ty::PredicateAtom::ObjectSafe(trait_def_id) => { + Some(ty::PredicateAtom::ObjectSafe(trait_def_id)) } - ty::PredicateKind::ConstEvaluatable(def_id, substs) => { - tcx.lift(&substs).map(|substs| ty::PredicateKind::ConstEvaluatable(def_id, substs)) + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { + tcx.lift(&substs).map(|substs| ty::PredicateAtom::ConstEvaluatable(def_id, substs)) } - ty::PredicateKind::ConstEquate(c1, c2) => { - tcx.lift(&(c1, c2)).map(|(c1, c2)| ty::PredicateKind::ConstEquate(c1, c2)) + ty::PredicateAtom::ConstEquate(c1, c2) => { + tcx.lift(&(c1, c2)).map(|(c1, c2)| ty::PredicateAtom::ConstEquate(c1, c2)) } } } @@ -998,7 +1015,7 @@ impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> { impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> { fn super_fold_with>(&self, folder: &mut F) -> Self { let new = ty::PredicateKind::super_fold_with(&self.inner.kind, folder); - if new != self.inner.kind { folder.tcx().mk_predicate(new) } else { *self } + folder.tcx().reuse_or_mk_predicate(*self, new) } fn super_visit_with>(&self, visitor: &mut V) -> bool { diff --git a/src/librustc_middle/ty/sty.rs b/src/librustc_middle/ty/sty.rs index 03bf51c95c5a3..df8fa4d73ddf1 100644 --- a/src/librustc_middle/ty/sty.rs +++ b/src/librustc_middle/ty/sty.rs @@ -652,8 +652,7 @@ impl<'tcx> Binder> { Binder(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) } ExistentialPredicate::Projection(p) => { - ty::PredicateKind::Projection(Binder(p.with_self_ty(tcx, self_ty))) - .to_predicate(tcx) + Binder(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) } ExistentialPredicate::AutoTrait(did) => { let trait_ref = @@ -896,6 +895,22 @@ impl Binder { Binder(value) } + /// Wraps `value` in a binder without actually binding any currently + /// unbound variables. + /// + /// Note that this will shift all debrujin indices of escaping bound variables + /// by 1 to avoid accidential captures. + pub fn wrap_nonbinding(tcx: TyCtxt<'tcx>, value: T) -> Binder + where + T: TypeFoldable<'tcx>, + { + if value.has_escaping_bound_vars() { + Binder::bind(super::fold::shift_vars(tcx, &value, 1)) + } else { + Binder::dummy(value) + } + } + /// Skips the binder and returns the "bound" value. This is a /// risky thing to do because it's easy to get confused about /// De Bruijn indices and the like. It is usually better to @@ -980,6 +995,15 @@ impl Binder { } } +impl Binder> { + pub fn transpose(self) -> Option> { + match self.0 { + Some(v) => Some(Binder(v)), + None => None, + } + } +} + /// Represents the projection of an associated type. In explicit UFCS /// form this would be written `>::N`. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)] diff --git a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs index cc8a5e0768cba..a0d99ac33c04e 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_errors.rs @@ -589,10 +589,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut found = false; for predicate in bounds.predicates { - if let ty::PredicateKind::TypeOutlives(binder) = predicate.kind() { - if let ty::OutlivesPredicate(_, ty::RegionKind::ReStatic) = - binder.skip_binder() - { + if let ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_, r)) = + predicate.skip_binders() + { + if let ty::RegionKind::ReStatic = r { found = true; break; } else { diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index bede9b22bbb0a..bc5c144cd742c 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -27,8 +27,8 @@ use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts}; use rustc_middle::ty::{ - self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, - ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex, + self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPredicate, Ty, + TyCtxt, UserType, UserTypeAnnotationIndex, WithConstness, }; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::VariantIdx; @@ -1021,7 +1021,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } self.prove_predicate( - ty::PredicateKind::WellFormed(inferred_ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(inferred_ty.into()).to_predicate(self.tcx()), Locations::All(span), ConstraintCategory::TypeAnnotation, ); @@ -1273,7 +1273,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { obligations.obligations.push(traits::Obligation::new( ObligationCause::dummy(), param_env, - ty::PredicateKind::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx), + ty::PredicateAtom::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx), )); obligations.add( infcx @@ -1617,7 +1617,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.check_call_dest(body, term, &sig, destination, term_location); self.prove_predicates( - sig.inputs_and_output.iter().map(|ty| ty::PredicateKind::WellFormed(ty.into())), + sig.inputs_and_output.iter().map(|ty| ty::PredicateAtom::WellFormed(ty.into())), term_location.to_locations(), ConstraintCategory::Boring, ); @@ -2022,18 +2022,14 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { traits::ObligationCauseCode::RepeatVec(should_suggest), ), self.param_env, - ty::PredicateKind::Trait( - ty::Binder::bind(ty::TraitPredicate { - trait_ref: ty::TraitRef::new( - self.tcx().require_lang_item( - CopyTraitLangItem, - Some(self.last_span), - ), - tcx.mk_substs_trait(ty, &[]), - ), - }), - hir::Constness::NotConst, - ) + ty::Binder::bind(ty::TraitRef::new( + self.tcx().require_lang_item( + CopyTraitLangItem, + Some(self.last_span), + ), + tcx.mk_substs_trait(ty, &[]), + )) + .without_const() .to_predicate(self.tcx()), ), &traits::SelectionError::Unimplemented, @@ -2706,8 +2702,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { category: ConstraintCategory, ) { self.prove_predicates( - Some(ty::PredicateKind::Trait( - trait_ref.to_poly_trait_ref().to_poly_trait_predicate(), + Some(ty::PredicateAtom::Trait( + ty::TraitPredicate { trait_ref }, hir::Constness::NotConst, )), locations, diff --git a/src/librustc_mir/monomorphize/polymorphize.rs b/src/librustc_mir/monomorphize/polymorphize.rs index 071b9bb971139..562f512c5dacf 100644 --- a/src/librustc_mir/monomorphize/polymorphize.rs +++ b/src/librustc_mir/monomorphize/polymorphize.rs @@ -131,9 +131,9 @@ fn mark_used_by_predicates<'tcx>( let predicates = tcx.explicit_predicates_of(def_id); debug!("mark_parameters_used_in_predicates: predicates_of={:?}", predicates); for (predicate, _) in predicates.predicates { - match predicate.kind() { - ty::PredicateKind::Trait(predicate, ..) => { - let trait_ref = predicate.skip_binder().trait_ref; + match predicate.skip_binders() { + ty::PredicateAtom::Trait(predicate, ..) => { + let trait_ref = predicate.trait_ref; if is_self_ty_used(unused_parameters, trait_ref.self_ty()) { for ty in trait_ref.substs.types() { debug!("unused_generic_params: (trait) ty={:?}", ty); @@ -141,12 +141,11 @@ fn mark_used_by_predicates<'tcx>( } } } - ty::PredicateKind::Projection(predicate, ..) => { - let self_ty = predicate.skip_binder().projection_ty.self_ty(); + ty::PredicateAtom::Projection(proj, ..) => { + let self_ty = proj.projection_ty.self_ty(); if is_self_ty_used(unused_parameters, self_ty) { - let ty = predicate.ty(); - debug!("unused_generic_params: (projection) ty={:?}", ty); - mark_ty(unused_parameters, ty.skip_binder()); + debug!("unused_generic_params: (projection ty={:?}", proj.ty); + mark_ty(unused_parameters, proj.ty); } } _ => (), diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs index 52b1eba3b93c2..de7d7f27186f2 100644 --- a/src/librustc_mir/transform/qualify_min_const_fn.rs +++ b/src/librustc_mir/transform/qualify_min_const_fn.rs @@ -24,27 +24,27 @@ pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) - loop { let predicates = tcx.predicates_of(current); for (predicate, _) in predicates.predicates { - match predicate.kind() { - ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::Projection(_) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => continue, - ty::PredicateKind::ObjectSafe(_) => { + match predicate.skip_binders() { + ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::Projection(_) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => continue, + ty::PredicateAtom::ObjectSafe(_) => { bug!("object safe predicate on function: {:#?}", predicate) } - ty::PredicateKind::ClosureKind(..) => { + ty::PredicateAtom::ClosureKind(..) => { bug!("closure kind predicate on function: {:#?}", predicate) } - ty::PredicateKind::Subtype(_) => { + ty::PredicateAtom::Subtype(_) => { bug!("subtype predicate on function: {:#?}", predicate) } - &ty::PredicateKind::Trait(pred, constness) => { + ty::PredicateAtom::Trait(pred, constness) => { if Some(pred.def_id()) == tcx.lang_items().sized_trait() { continue; } - match pred.skip_binder().self_ty().kind { + match pred.self_ty().kind { ty::Param(ref p) => { // Allow `T: ?const Trait` if constness == hir::Constness::NotConst diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 1ecb0320744ff..9c5fb4ce73450 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -68,10 +68,7 @@ trait DefIdVisitor<'tcx> { } } -struct DefIdVisitorSkeleton<'v, 'tcx, V> -where - V: DefIdVisitor<'tcx> + ?Sized, -{ +struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> { def_id_visitor: &'v mut V, visited_opaque_tys: FxHashSet, dummy: PhantomData>, @@ -87,34 +84,28 @@ where || (!self.def_id_visitor.shallow() && substs.visit_with(self)) } + fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> bool { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(ty::TraitPredicate { trait_ref }, _) => { + self.visit_trait(trait_ref) + } + ty::PredicateAtom::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { + ty.visit_with(self) + || self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx())) + } + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { + ty.visit_with(self) + } + ty::PredicateAtom::RegionOutlives(..) => false, + _ => bug!("unexpected predicate: {:?}", predicate), + } + } + fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> bool { let ty::GenericPredicates { parent: _, predicates } = predicates; - for (predicate, _span) in predicates { - match predicate.kind() { - ty::PredicateKind::Trait(poly_predicate, _) => { - let ty::TraitPredicate { trait_ref } = poly_predicate.skip_binder(); - if self.visit_trait(trait_ref) { - return true; - } - } - ty::PredicateKind::Projection(poly_predicate) => { - let ty::ProjectionPredicate { projection_ty, ty } = - poly_predicate.skip_binder(); - if ty.visit_with(self) { - return true; - } - if self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx())) { - return true; - } - } - ty::PredicateKind::TypeOutlives(poly_predicate) => { - let ty::OutlivesPredicate(ty, _region) = poly_predicate.skip_binder(); - if ty.visit_with(self) { - return true; - } - } - ty::PredicateKind::RegionOutlives(..) => {} - _ => bug!("unexpected predicate: {:?}", predicate), + for &(predicate, _span) in predicates { + if self.visit_predicate(predicate) { + return true; } } false diff --git a/src/librustc_trait_selection/opaque_types.rs b/src/librustc_trait_selection/opaque_types.rs index b60531833bd41..b84ad93341e81 100644 --- a/src/librustc_trait_selection/opaque_types.rs +++ b/src/librustc_trait_selection/opaque_types.rs @@ -1154,8 +1154,8 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> { debug!("instantiate_opaque_types: ty_var={:?}", ty_var); for predicate in &bounds.predicates { - if let ty::PredicateKind::Projection(projection) = predicate.kind() { - if projection.skip_binder().ty.references_error() { + if let ty::PredicateAtom::Projection(projection) = predicate.skip_binders() { + if projection.ty.references_error() { // No point on adding these obligations since there's a type error involved. return ty_var; } @@ -1252,17 +1252,17 @@ crate fn required_region_bounds( traits::elaborate_predicates(tcx, predicates) .filter_map(|obligation| { debug!("required_region_bounds(obligation={:?})", obligation); - match obligation.predicate.kind() { - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => None, - ty::PredicateKind::TypeOutlives(predicate) => { + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => None, + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => { // Search for a bound of the form `erased_self_ty // : 'a`, but be wary of something like `for<'a> // erased_self_ty : 'a` (we interpret a @@ -1272,7 +1272,6 @@ crate fn required_region_bounds( // it's kind of a moot point since you could never // construct such an object, but this seems // correct even if that code changes). - let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder(); if t == &erased_self_ty && !r.has_escaping_bound_vars() { Some(*r) } else { diff --git a/src/librustc_trait_selection/traits/auto_trait.rs b/src/librustc_trait_selection/traits/auto_trait.rs index 8c8550d377a6e..6fe67509660bc 100644 --- a/src/librustc_trait_selection/traits/auto_trait.rs +++ b/src/librustc_trait_selection/traits/auto_trait.rs @@ -344,8 +344,7 @@ impl AutoTraitFinder<'tcx> { already_visited.remove(&pred); self.add_user_pred( &mut user_computed_preds, - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) - .to_predicate(self.tcx), + pred.without_const().to_predicate(self.tcx), ); predicates.push_back(pred); } else { @@ -408,21 +407,21 @@ impl AutoTraitFinder<'tcx> { /// under which a type implements an auto trait. A trait predicate involving /// a HRTB means that the type needs to work with any choice of lifetime, /// not just one specific lifetime (e.g., `'static`). - fn add_user_pred<'c>( + fn add_user_pred( &self, - user_computed_preds: &mut FxHashSet>, - new_pred: ty::Predicate<'c>, + user_computed_preds: &mut FxHashSet>, + new_pred: ty::Predicate<'tcx>, ) { let mut should_add_new = true; user_computed_preds.retain(|&old_pred| { if let ( - ty::PredicateKind::Trait(new_trait, _), - ty::PredicateKind::Trait(old_trait, _), - ) = (new_pred.kind(), old_pred.kind()) + ty::PredicateAtom::Trait(new_trait, _), + ty::PredicateAtom::Trait(old_trait, _), + ) = (new_pred.skip_binders(), old_pred.skip_binders()) { if new_trait.def_id() == old_trait.def_id() { - let new_substs = new_trait.skip_binder().trait_ref.substs; - let old_substs = old_trait.skip_binder().trait_ref.substs; + let new_substs = new_trait.trait_ref.substs; + let old_substs = old_trait.trait_ref.substs; if !new_substs.types().eq(old_substs.types()) { // We can't compare lifetimes if the types are different, @@ -618,11 +617,12 @@ impl AutoTraitFinder<'tcx> { ) -> bool { let dummy_cause = ObligationCause::dummy(); - for (obligation, mut predicate) in nested.map(|o| (o.clone(), o.predicate)) { - let is_new_pred = fresh_preds.insert(self.clean_pred(select.infcx(), predicate)); + for obligation in nested { + let is_new_pred = + fresh_preds.insert(self.clean_pred(select.infcx(), obligation.predicate)); // Resolve any inference variables that we can, to help selection succeed - predicate = select.infcx().resolve_vars_if_possible(&predicate); + let predicate = select.infcx().resolve_vars_if_possible(&obligation.predicate); // We only add a predicate as a user-displayable bound if // it involves a generic parameter, and doesn't contain @@ -636,17 +636,19 @@ impl AutoTraitFinder<'tcx> { // // We check this by calling is_of_param on the relevant types // from the various possible predicates - match predicate.kind() { - &ty::PredicateKind::Trait(p, _) => { - if self.is_param_no_infer(p.skip_binder().trait_ref.substs) + + match predicate.skip_binders() { + ty::PredicateAtom::Trait(p, _) => { + if self.is_param_no_infer(p.trait_ref.substs) && !only_projections && is_new_pred { self.add_user_pred(computed_preds, predicate); } - predicates.push_back(p); + predicates.push_back(ty::Binder::bind(p)); } - &ty::PredicateKind::Projection(p) => { + ty::PredicateAtom::Projection(p) => { + let p = ty::Binder::bind(p); debug!( "evaluate_nested_obligations: examining projection predicate {:?}", predicate @@ -758,7 +760,7 @@ impl AutoTraitFinder<'tcx> { } } Ok(None) => { - // It's ok not to make progress when hvave no inference variables - + // It's ok not to make progress when have no inference variables - // in that case, we were only performing unifcation to check if an // error occurred (which would indicate that it's impossible for our // type to implement the auto trait). @@ -771,12 +773,14 @@ impl AutoTraitFinder<'tcx> { } } } - &ty::PredicateKind::RegionOutlives(binder) => { + ty::PredicateAtom::RegionOutlives(binder) => { + let binder = ty::Binder::bind(binder); if select.infcx().region_outlives_predicate(&dummy_cause, binder).is_err() { return false; } } - &ty::PredicateKind::TypeOutlives(binder) => { + ty::PredicateAtom::TypeOutlives(binder) => { + let binder = ty::Binder::bind(binder); match ( binder.no_bound_vars(), binder.map_bound_ref(|pred| pred.0).no_bound_vars(), diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 112de68466084..349fa68a4da99 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -255,9 +255,11 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .emit(); return; } - match obligation.predicate.kind() { - ty::PredicateKind::Trait(ref trait_predicate, _) => { - let trait_predicate = self.resolve_vars_if_possible(trait_predicate); + + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(trait_predicate, _) => { + let trait_predicate = ty::Binder::bind(trait_predicate); + let trait_predicate = self.resolve_vars_if_possible(&trait_predicate); if self.tcx.sess.has_errors() && trait_predicate.references_error() { return; @@ -503,14 +505,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ); trait_pred }); - let unit_obligation = Obligation { - predicate: ty::PredicateKind::Trait( - predicate, - hir::Constness::NotConst, - ) - .to_predicate(self.tcx), - ..obligation.clone() - }; + let unit_obligation = + obligation.with(predicate.without_const().to_predicate(tcx)); if self.predicate_may_hold(&unit_obligation) { err.note( "the trait is implemented for `()`. \ @@ -526,15 +522,16 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { err } - ty::PredicateKind::Subtype(ref predicate) => { + ty::PredicateAtom::Subtype(predicate) => { // Errors for Subtype predicates show up as // `FulfillmentErrorCode::CodeSubtypeError`, // not selection error. span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate) } - ty::PredicateKind::RegionOutlives(ref predicate) => { - let predicate = self.resolve_vars_if_possible(predicate); + ty::PredicateAtom::RegionOutlives(predicate) => { + let predicate = ty::Binder::bind(predicate); + let predicate = self.resolve_vars_if_possible(&predicate); let err = self .region_outlives_predicate(&obligation.cause, predicate) .err() @@ -549,7 +546,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => { + ty::PredicateAtom::Projection(..) | ty::PredicateAtom::TypeOutlives(..) => { let predicate = self.resolve_vars_if_possible(&obligation.predicate); struct_span_err!( self.tcx.sess, @@ -560,12 +557,12 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - &ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::ObjectSafe(trait_def_id) => { let violations = self.tcx.object_safety_violations(trait_def_id); report_object_safety_error(self.tcx, span, trait_def_id, violations) } - &ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { let found_kind = self.closure_kind(closure_substs).unwrap(); let closure_span = self.tcx.sess.source_map().guess_head_span( @@ -624,7 +621,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { return; } - ty::PredicateKind::WellFormed(ty) => { + ty::PredicateAtom::WellFormed(ty) => { if !self.tcx.sess.opts.debugging_opts.chalk { // WF predicates cannot themselves make // errors. They can only block due to @@ -642,7 +639,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { } } - ty::PredicateKind::ConstEvaluatable(..) => { + ty::PredicateAtom::ConstEvaluatable(..) => { // Errors for `ConstEvaluatable` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. @@ -653,7 +650,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ) } - ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ConstEquate(..) => { // Errors for `ConstEquate` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. @@ -1089,8 +1086,11 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { return true; } - let (cond, error) = match (cond.kind(), error.kind()) { - (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error, _)) => (cond, error), + // FIXME: It should be possible to deal with `ForAll` in a cleaner way. + let (cond, error) = match (cond.skip_binders(), error.skip_binders()) { + (ty::PredicateAtom::Trait(..), ty::PredicateAtom::Trait(error, _)) => { + (cond, ty::Binder::bind(error)) + } _ => { // FIXME: make this work in other cases too. return false; @@ -1098,9 +1098,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { }; for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) { - if let ty::PredicateKind::Trait(implication, _) = obligation.predicate.kind() { + if let ty::PredicateAtom::Trait(implication, _) = obligation.predicate.skip_binders() { let error = error.to_poly_trait_ref(); - let implication = implication.to_poly_trait_ref(); + let implication = ty::Binder::bind(implication.trait_ref); // FIXME: I'm just not taking associated types at all here. // Eventually I'll need to implement param-env-aware // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic. @@ -1178,12 +1178,12 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { // // this can fail if the problem was higher-ranked, in which // cause I have no idea for a good error message. - if let ty::PredicateKind::Projection(ref data) = predicate.kind() { + if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() { let mut selcx = SelectionContext::new(self); let (data, _) = self.replace_bound_vars_with_fresh_vars( obligation.cause.span, infer::LateBoundRegionConversionTime::HigherRankedType, - data, + &ty::Binder::bind(data), ); let mut obligations = vec![]; let normalized_ty = super::normalize_projection_type( @@ -1470,9 +1470,9 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { return; } - let mut err = match predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => { - let trait_ref = data.to_poly_trait_ref(); + let mut err = match predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) => { + let trait_ref = ty::Binder::bind(data.trait_ref); let self_ty = trait_ref.skip_binder().self_ty(); debug!("self_ty {:?} {:?} trait_ref {:?}", self_ty, self_ty.kind, trait_ref); @@ -1570,7 +1570,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { err } - ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { // Same hacky approach as above to avoid deluging user // with error messages. if arg.references_error() || self.tcx.sess.has_errors() { @@ -1590,20 +1590,20 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { } } - ty::PredicateKind::Subtype(ref data) => { + ty::PredicateAtom::Subtype(data) => { if data.references_error() || self.tcx.sess.has_errors() { // no need to overload user in such cases return; } - let SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder(); + let SubtypePredicate { a_is_expected: _, a, b } = data; // both must be type variables, or the other would've been instantiated assert!(a.is_ty_var() && b.is_ty_var()); self.need_type_info_err(body_id, span, a, ErrorCode::E0282) } - ty::PredicateKind::Projection(ref data) => { - let trait_ref = data.to_poly_trait_ref(self.tcx); + ty::PredicateAtom::Projection(data) => { + let trait_ref = ty::Binder::bind(data).to_poly_trait_ref(self.tcx); let self_ty = trait_ref.skip_binder().self_ty(); - let ty = data.skip_binder().ty; + let ty = data.ty; if predicate.references_error() { return; } @@ -1724,16 +1724,16 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { obligation: &PredicateObligation<'tcx>, ) { let (pred, item_def_id, span) = - match (obligation.predicate.kind(), &obligation.cause.code.peel_derives()) { + match (obligation.predicate.skip_binders(), obligation.cause.code.peel_derives()) { ( - ty::PredicateKind::Trait(pred, _), - ObligationCauseCode::BindingObligation(item_def_id, span), + ty::PredicateAtom::Trait(pred, _), + &ObligationCauseCode::BindingObligation(item_def_id, span), ) => (pred, item_def_id, span), _ => return, }; let node = match ( - self.tcx.hir().get_if_local(*item_def_id), + self.tcx.hir().get_if_local(item_def_id), Some(pred.def_id()) == self.tcx.lang_items().sized_trait(), ) { (Some(node), true) => node, @@ -1744,7 +1744,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { None => return, }; for param in generics.params { - if param.span != *span + if param.span != span || param.bounds.iter().any(|bound| { bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id()) == self.tcx.lang_items().sized_trait() diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 432abee6d1cf9..13f8c71a629a9 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -1300,10 +1300,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // the type. The last generator (`outer_generator` below) has information about where the // bound was introduced. At least one generator should be present for this diagnostic to be // modified. - let (mut trait_ref, mut target_ty) = match obligation.predicate.kind() { - ty::PredicateKind::Trait(p, _) => { - (Some(p.skip_binder().trait_ref), Some(p.skip_binder().self_ty())) - } + let (mut trait_ref, mut target_ty) = match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(p, _) => (Some(p.trait_ref), Some(p.self_ty())), _ => (None, None), }; let mut generator = None; diff --git a/src/librustc_trait_selection/traits/fulfill.rs b/src/librustc_trait_selection/traits/fulfill.rs index c6c76028f857c..2eda1ce595a7d 100644 --- a/src/librustc_trait_selection/traits/fulfill.rs +++ b/src/librustc_trait_selection/traits/fulfill.rs @@ -3,10 +3,11 @@ use rustc_data_structures::obligation_forest::ProcessResult; use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation}; use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor}; use rustc_errors::ErrorReported; -use rustc_infer::traits::{TraitEngine, TraitEngineExt as _}; +use rustc_infer::traits::{TraitEngine, TraitEngineExt as _, TraitObligation}; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::error::ExpectedFound; -use rustc_middle::ty::{self, Const, ToPolyTraitRef, Ty, TypeFoldable}; +use rustc_middle::ty::ToPredicate; +use rustc_middle::ty::{self, Binder, Const, Ty, TypeFoldable}; use std::marker::PhantomData; use super::project; @@ -20,6 +21,7 @@ use super::{FulfillmentError, FulfillmentErrorCode}; use super::{ObligationCause, PredicateObligation}; use crate::traits::error_reporting::InferCtxtExt as _; +use crate::traits::project::PolyProjectionObligation; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> { @@ -318,267 +320,222 @@ impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> { let infcx = self.selcx.infcx(); match obligation.predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => { - let trait_obligation = obligation.with(*data); - - if obligation.predicate.is_global() { - // no type variables present, can use evaluation for better caching. - // FIXME: consider caching errors too. - if infcx.predicate_must_hold_considering_regions(&obligation) { - debug!( - "selecting trait `{:?}` at depth {} evaluated to holds", - data, obligation.recursion_depth - ); - return ProcessResult::Changed(vec![]); - } + ty::PredicateKind::ForAll(binder) => match binder.skip_binder() { + // Evaluation will discard candidates using the leak check. + // This means we need to pass it the bound version of our + // predicate. + ty::PredicateAtom::Trait(trait_ref, _constness) => { + let trait_obligation = obligation.with(Binder::bind(trait_ref)); + + self.process_trait_obligation( + obligation, + trait_obligation, + &mut pending_obligation.stalled_on, + ) } + ty::PredicateAtom::Projection(data) => { + let project_obligation = obligation.with(Binder::bind(data)); - match self.selcx.select(&trait_obligation) { - Ok(Some(impl_source)) => { - debug!( - "selecting trait `{:?}` at depth {} yielded Ok(Some)", - data, obligation.recursion_depth - ); - ProcessResult::Changed(mk_pending(impl_source.nested_obligations())) - } - Ok(None) => { - debug!( - "selecting trait `{:?}` at depth {} yielded Ok(None)", - data, obligation.recursion_depth - ); - - // This is a bit subtle: for the most part, the - // only reason we can fail to make progress on - // trait selection is because we don't have enough - // information about the types in the trait. - pending_obligation.stalled_on = - trait_ref_infer_vars(self.selcx, data.to_poly_trait_ref()); - - debug!( - "process_predicate: pending obligation {:?} now stalled on {:?}", - infcx.resolve_vars_if_possible(obligation), - pending_obligation.stalled_on - ); + self.process_projection_obligation( + project_obligation, + &mut pending_obligation.stalled_on, + ) + } + ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::ObjectSafe(_) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(_) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => { + let (pred, _) = infcx.replace_bound_vars_with_placeholders(binder); + ProcessResult::Changed(mk_pending(vec![ + obligation.with(pred.to_predicate(self.selcx.tcx())), + ])) + } + }, + &ty::PredicateKind::Atom(atom) => match atom { + ty::PredicateAtom::Trait(ref data, _) => { + let trait_obligation = obligation.with(Binder::dummy(*data)); + + self.process_trait_obligation( + obligation, + trait_obligation, + &mut pending_obligation.stalled_on, + ) + } - ProcessResult::Unchanged + ty::PredicateAtom::RegionOutlives(data) => { + match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) { + Ok(()) => ProcessResult::Changed(vec![]), + Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)), } - Err(selection_err) => { - info!( - "selecting trait `{:?}` at depth {} yielded Err", - data, obligation.recursion_depth - ); + } - ProcessResult::Error(CodeSelectionError(selection_err)) + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => { + if self.register_region_obligations { + self.selcx.infcx().register_region_obligation_with_cause( + t_a, + r_b, + &obligation.cause, + ); } + ProcessResult::Changed(vec![]) } - } - &ty::PredicateKind::RegionOutlives(binder) => { - match infcx.region_outlives_predicate(&obligation.cause, binder) { - Ok(()) => ProcessResult::Changed(vec![]), - Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)), + ty::PredicateAtom::Projection(ref data) => { + let project_obligation = obligation.with(Binder::dummy(*data)); + + self.process_projection_obligation( + project_obligation, + &mut pending_obligation.stalled_on, + ) } - } - ty::PredicateKind::TypeOutlives(ref binder) => { - // Check if there are higher-ranked vars. - match binder.no_bound_vars() { - // If there are, inspect the underlying type further. - None => { - // Convert from `Binder>` to `Binder`. - let binder = binder.map_bound_ref(|pred| pred.0); - - // Check if the type has any bound vars. - match binder.no_bound_vars() { - // If so, this obligation is an error (for now). Eventually we should be - // able to support additional cases here, like `for<'a> &'a str: 'a`. - // NOTE: this is duplicate-implemented between here and fulfillment. - None => ProcessResult::Error(CodeSelectionError(Unimplemented)), - // Otherwise, we have something of the form - // `for<'a> T: 'a where 'a not in T`, which we can treat as - // `T: 'static`. - Some(t_a) => { - let r_static = self.selcx.tcx().lifetimes.re_static; - if self.register_region_obligations { - self.selcx.infcx().register_region_obligation_with_cause( - t_a, - r_static, - &obligation.cause, - ); - } - ProcessResult::Changed(vec![]) - } - } - } - // If there aren't, register the obligation. - Some(ty::OutlivesPredicate(t_a, r_b)) => { - if self.register_region_obligations { - self.selcx.infcx().register_region_obligation_with_cause( - t_a, - r_b, - &obligation.cause, - ); - } + ty::PredicateAtom::ObjectSafe(trait_def_id) => { + if !self.selcx.tcx().is_object_safe(trait_def_id) { + ProcessResult::Error(CodeSelectionError(Unimplemented)) + } else { ProcessResult::Changed(vec![]) } } - } - ty::PredicateKind::Projection(ref data) => { - let project_obligation = obligation.with(*data); - match project::poly_project_and_unify_type(self.selcx, &project_obligation) { - Ok(None) => { - let tcx = self.selcx.tcx(); - pending_obligation.stalled_on = - trait_ref_infer_vars(self.selcx, data.to_poly_trait_ref(tcx)); - ProcessResult::Unchanged + ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => { + match self.selcx.infcx().closure_kind(closure_substs) { + Some(closure_kind) => { + if closure_kind.extends(kind) { + ProcessResult::Changed(vec![]) + } else { + ProcessResult::Error(CodeSelectionError(Unimplemented)) + } + } + None => ProcessResult::Unchanged, } - Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)), - Err(e) => ProcessResult::Error(CodeProjectionError(e)), } - } - &ty::PredicateKind::ObjectSafe(trait_def_id) => { - if !self.selcx.tcx().is_object_safe(trait_def_id) { - ProcessResult::Error(CodeSelectionError(Unimplemented)) - } else { - ProcessResult::Changed(vec![]) - } - } - - &ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { - match self.selcx.infcx().closure_kind(closure_substs) { - Some(closure_kind) => { - if closure_kind.extends(kind) { - ProcessResult::Changed(vec![]) - } else { - ProcessResult::Error(CodeSelectionError(Unimplemented)) + ty::PredicateAtom::WellFormed(arg) => { + match wf::obligations( + self.selcx.infcx(), + obligation.param_env, + obligation.cause.body_id, + arg, + obligation.cause.span, + ) { + None => { + pending_obligation.stalled_on = + vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()]; + ProcessResult::Unchanged } + Some(os) => ProcessResult::Changed(mk_pending(os)), } - None => ProcessResult::Unchanged, } - } - &ty::PredicateKind::WellFormed(arg) => { - match wf::obligations( - self.selcx.infcx(), - obligation.param_env, - obligation.cause.body_id, - arg, - obligation.cause.span, - ) { - None => { - pending_obligation.stalled_on = - vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()]; - ProcessResult::Unchanged + ty::PredicateAtom::Subtype(subtype) => { + match self.selcx.infcx().subtype_predicate( + &obligation.cause, + obligation.param_env, + Binder::dummy(subtype), + ) { + None => { + // None means that both are unresolved. + pending_obligation.stalled_on = vec![ + TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(), + TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(), + ]; + ProcessResult::Unchanged + } + Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), + Some(Err(err)) => { + let expected_found = + ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b); + ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( + expected_found, + err, + )) + } } - Some(os) => ProcessResult::Changed(mk_pending(os)), } - } - &ty::PredicateKind::Subtype(subtype) => { - match self.selcx.infcx().subtype_predicate( - &obligation.cause, - obligation.param_env, - subtype, - ) { - None => { - // None means that both are unresolved. - pending_obligation.stalled_on = vec![ - TyOrConstInferVar::maybe_from_ty(subtype.skip_binder().a).unwrap(), - TyOrConstInferVar::maybe_from_ty(subtype.skip_binder().b).unwrap(), - ]; - ProcessResult::Unchanged - } - Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), - Some(Err(err)) => { - let expected_found = ExpectedFound::new( - subtype.skip_binder().a_is_expected, - subtype.skip_binder().a, - subtype.skip_binder().b, - ); - ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( - expected_found, - err, - )) + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { + match self.selcx.infcx().const_eval_resolve( + obligation.param_env, + def_id, + substs, + None, + Some(obligation.cause.span), + ) { + Ok(_) => ProcessResult::Changed(vec![]), + Err(err) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err))), } } - } - &ty::PredicateKind::ConstEvaluatable(def_id, substs) => { - match self.selcx.infcx().const_eval_resolve( - obligation.param_env, - def_id, - substs, - None, - Some(obligation.cause.span), - ) { - Ok(_) => ProcessResult::Changed(vec![]), - Err(err) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err))), - } - } - - ty::PredicateKind::ConstEquate(c1, c2) => { - debug!("equating consts: c1={:?} c2={:?}", c1, c2); - - let stalled_on = &mut pending_obligation.stalled_on; - - let mut evaluate = |c: &'tcx Const<'tcx>| { - if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val { - match self.selcx.infcx().const_eval_resolve( - obligation.param_env, - def, - substs, - promoted, - Some(obligation.cause.span), - ) { - Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)), - Err(ErrorHandled::TooGeneric) => { - stalled_on.append( - &mut substs - .types() - .filter_map(|ty| TyOrConstInferVar::maybe_from_ty(ty)) - .collect(), - ); - Err(ErrorHandled::TooGeneric) + ty::PredicateAtom::ConstEquate(c1, c2) => { + debug!("equating consts: c1={:?} c2={:?}", c1, c2); + + let stalled_on = &mut pending_obligation.stalled_on; + + let mut evaluate = |c: &'tcx Const<'tcx>| { + if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val { + match self.selcx.infcx().const_eval_resolve( + obligation.param_env, + def, + substs, + promoted, + Some(obligation.cause.span), + ) { + Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)), + Err(ErrorHandled::TooGeneric) => { + stalled_on.append( + &mut substs + .types() + .filter_map(|ty| TyOrConstInferVar::maybe_from_ty(ty)) + .collect(), + ); + Err(ErrorHandled::TooGeneric) + } + Err(err) => Err(err), } - Err(err) => Err(err), + } else { + Ok(c) } - } else { - Ok(c) - } - }; - - match (evaluate(c1), evaluate(c2)) { - (Ok(c1), Ok(c2)) => { - match self - .selcx - .infcx() - .at(&obligation.cause, obligation.param_env) - .eq(c1, c2) - { - Ok(_) => ProcessResult::Changed(vec![]), - Err(err) => { - ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError( - ExpectedFound::new(true, c1, c2), - err, - )) + }; + + match (evaluate(c1), evaluate(c2)) { + (Ok(c1), Ok(c2)) => { + match self + .selcx + .infcx() + .at(&obligation.cause, obligation.param_env) + .eq(c1, c2) + { + Ok(_) => ProcessResult::Changed(vec![]), + Err(err) => ProcessResult::Error( + FulfillmentErrorCode::CodeConstEquateError( + ExpectedFound::new(true, c1, c2), + err, + ), + ), } } - } - (Err(ErrorHandled::Reported(ErrorReported)), _) - | (_, Err(ErrorHandled::Reported(ErrorReported))) => ProcessResult::Error( - CodeSelectionError(ConstEvalFailure(ErrorHandled::Reported(ErrorReported))), - ), - (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => span_bug!( - obligation.cause.span(self.selcx.tcx()), - "ConstEquate: const_eval_resolve returned an unexpected error" - ), - (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => { - ProcessResult::Unchanged + (Err(ErrorHandled::Reported(ErrorReported)), _) + | (_, Err(ErrorHandled::Reported(ErrorReported))) => { + ProcessResult::Error(CodeSelectionError(ConstEvalFailure( + ErrorHandled::Reported(ErrorReported), + ))) + } + (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => { + span_bug!( + obligation.cause.span(self.selcx.tcx()), + "ConstEquate: const_eval_resolve returned an unexpected error" + ) + } + (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => { + ProcessResult::Unchanged + } } } - } + }, } } @@ -598,6 +555,87 @@ impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> { } } +impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { + fn process_trait_obligation( + &mut self, + obligation: &PredicateObligation<'tcx>, + trait_obligation: TraitObligation<'tcx>, + stalled_on: &mut Vec>, + ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { + let infcx = self.selcx.infcx(); + if obligation.predicate.is_global() { + // no type variables present, can use evaluation for better caching. + // FIXME: consider caching errors too. + if infcx.predicate_must_hold_considering_regions(obligation) { + debug!( + "selecting trait `{:?}` at depth {} evaluated to holds", + obligation.predicate, obligation.recursion_depth + ); + return ProcessResult::Changed(vec![]); + } + } + + match self.selcx.select(&trait_obligation) { + Ok(Some(impl_source)) => { + debug!( + "selecting trait `{:?}` at depth {} yielded Ok(Some)", + trait_obligation.predicate, obligation.recursion_depth + ); + ProcessResult::Changed(mk_pending(impl_source.nested_obligations())) + } + Ok(None) => { + debug!( + "selecting trait `{:?}` at depth {} yielded Ok(None)", + trait_obligation.predicate, obligation.recursion_depth + ); + + // This is a bit subtle: for the most part, the + // only reason we can fail to make progress on + // trait selection is because we don't have enough + // information about the types in the trait. + *stalled_on = trait_ref_infer_vars( + self.selcx, + trait_obligation.predicate.map_bound(|pred| pred.trait_ref), + ); + + debug!( + "process_predicate: pending obligation {:?} now stalled on {:?}", + infcx.resolve_vars_if_possible(obligation), + stalled_on + ); + + ProcessResult::Unchanged + } + Err(selection_err) => { + info!( + "selecting trait `{:?}` at depth {} yielded Err", + trait_obligation.predicate, obligation.recursion_depth + ); + + ProcessResult::Error(CodeSelectionError(selection_err)) + } + } + } + + fn process_projection_obligation( + &mut self, + project_obligation: PolyProjectionObligation<'tcx>, + stalled_on: &mut Vec>, + ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { + match project::poly_project_and_unify_type(self.selcx, &project_obligation) { + Ok(None) => { + *stalled_on = trait_ref_infer_vars( + self.selcx, + project_obligation.predicate.to_poly_trait_ref(self.selcx.tcx()), + ); + ProcessResult::Unchanged + } + Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)), + Err(e) => ProcessResult::Error(CodeProjectionError(e)), + } + } +} + /// Returns the set of inference variables contained in a trait ref. fn trait_ref_infer_vars<'a, 'tcx>( selcx: &mut SelectionContext<'a, 'tcx>, @@ -606,7 +644,7 @@ fn trait_ref_infer_vars<'a, 'tcx>( selcx .infcx() .resolve_vars_if_possible(&trait_ref) - .skip_binder() // ok b/c this check doesn't care about regions + .skip_binder() .substs .iter() // FIXME(eddyb) try using `skip_current_subtree` to skip everything that diff --git a/src/librustc_trait_selection/traits/mod.rs b/src/librustc_trait_selection/traits/mod.rs index 1c3755222495e..afa48c2f76cf8 100644 --- a/src/librustc_trait_selection/traits/mod.rs +++ b/src/librustc_trait_selection/traits/mod.rs @@ -328,8 +328,8 @@ pub fn normalize_param_env_or_error<'tcx>( // This works fairly well because trait matching does not actually care about param-env // TypeOutlives predicates - these are normally used by regionck. let outlives_predicates: Vec<_> = predicates - .drain_filter(|predicate| match predicate.kind() { - ty::PredicateKind::TypeOutlives(..) => true, + .drain_filter(|predicate| match predicate.skip_binders() { + ty::PredicateAtom::TypeOutlives(..) => true, _ => false, }) .collect(); diff --git a/src/librustc_trait_selection/traits/object_safety.rs b/src/librustc_trait_selection/traits/object_safety.rs index f00d668e1ae50..c003e4f806873 100644 --- a/src/librustc_trait_selection/traits/object_safety.rs +++ b/src/librustc_trait_selection/traits/object_safety.rs @@ -245,16 +245,12 @@ fn predicates_reference_self( .iter() .map(|(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp)) .filter_map(|(predicate, &sp)| { - match predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(ref data, _) => { // In the case of a trait predicate, we can skip the "self" type. - if data.skip_binder().trait_ref.substs[1..].iter().any(has_self_ty) { - Some(sp) - } else { - None - } + if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } } - ty::PredicateKind::Projection(ref data) => { + ty::PredicateAtom::Projection(ref data) => { // And similarly for projections. This should be redundant with // the previous check because any projection should have a // matching `Trait` predicate with the same inputs, but we do @@ -267,23 +263,20 @@ fn predicates_reference_self( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - if data.skip_binder().projection_ty.trait_ref(tcx).substs[1..] - .iter() - .any(has_self_ty) - { + if data.projection_ty.trait_ref(tcx).substs[1..].iter().any(has_self_ty) { Some(sp) } else { None } } - ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => None, + ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => None, } }) .collect() @@ -305,20 +298,19 @@ fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool { let predicates = tcx.predicates_of(def_id); let predicates = predicates.instantiate_identity(tcx).predicates; elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| { - match obligation.predicate.kind() { - ty::PredicateKind::Trait(ref trait_pred, _) => { - trait_pred.def_id() == sized_def_id - && trait_pred.skip_binder().self_ty().is_param(0) + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(ref trait_pred, _) => { + trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0) } - ty::PredicateKind::Projection(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => false, + ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => false, } }) } diff --git a/src/librustc_trait_selection/traits/project.rs b/src/librustc_trait_selection/traits/project.rs index c08198ec373b8..717b7e2fe574f 100644 --- a/src/librustc_trait_selection/traits/project.rs +++ b/src/librustc_trait_selection/traits/project.rs @@ -664,23 +664,25 @@ fn prune_cache_value_obligations<'a, 'tcx>( let mut obligations: Vec<_> = result .obligations .iter() - .filter(|obligation| match obligation.predicate.kind() { - // We found a `T: Foo` predicate, let's check - // if `U` references any unresolved type - // variables. In principle, we only care if this - // projection can help resolve any of the type - // variables found in `result.value` -- but we just - // check for any type variables here, for fear of - // indirect obligations (e.g., we project to `?0`, - // but we have `T: Foo` and `?1: Bar`). - ty::PredicateKind::Projection(ref data) => { - infcx.unresolved_type_vars(&data.ty()).is_some() - } + .filter(|obligation| { + match obligation.predicate.skip_binders() { + // We found a `T: Foo` predicate, let's check + // if `U` references any unresolved type + // variables. In principle, we only care if this + // projection can help resolve any of the type + // variables found in `result.value` -- but we just + // check for any type variables here, for fear of + // indirect obligations (e.g., we project to `?0`, + // but we have `T: Foo` and `?1: Bar`). + ty::PredicateAtom::Projection(data) => { + infcx.unresolved_type_vars(&ty::Binder::bind(data.ty)).is_some() + } - // We are only interested in `T: Foo` predicates, whre - // `U` references one of `unresolved_type_vars`. =) - _ => false, + // We are only interested in `T: Foo` predicates, whre + // `U` references one of `unresolved_type_vars`. =) + _ => false, + } }) .cloned() .collect(); @@ -931,7 +933,8 @@ fn assemble_candidates_from_predicates<'cx, 'tcx>( let infcx = selcx.infcx(); for predicate in env_predicates { debug!("assemble_candidates_from_predicates: predicate={:?}", predicate); - if let &ty::PredicateKind::Projection(data) = predicate.kind() { + if let ty::PredicateAtom::Projection(data) = predicate.skip_binders() { + let data = ty::Binder::bind(data); let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id; let is_match = same_def_id @@ -1221,11 +1224,12 @@ fn confirm_object_candidate<'cx, 'tcx>( // select only those projections that are actually projecting an // item with the correct name - let env_predicates = env_predicates.filter_map(|o| match o.predicate.kind() { - &ty::PredicateKind::Projection(data) - if data.projection_def_id() == obligation.predicate.item_def_id => + + let env_predicates = env_predicates.filter_map(|o| match o.predicate.skip_binders() { + ty::PredicateAtom::Projection(data) + if data.projection_ty.item_def_id == obligation.predicate.item_def_id => { - Some(data) + Some(ty::Binder::bind(data)) } _ => None, }); diff --git a/src/librustc_trait_selection/traits/query/type_op/prove_predicate.rs b/src/librustc_trait_selection/traits/query/type_op/prove_predicate.rs index 5c8719da14e6f..93ddcb6855400 100644 --- a/src/librustc_trait_selection/traits/query/type_op/prove_predicate.rs +++ b/src/librustc_trait_selection/traits/query/type_op/prove_predicate.rs @@ -15,10 +15,10 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { // `&T`, accounts for about 60% percentage of the predicates // we have to prove. No need to canonicalize and all that for // such cases. - if let ty::PredicateKind::Trait(trait_ref, _) = key.value.predicate.kind() { + if let ty::PredicateAtom::Trait(trait_ref, _) = key.value.predicate.skip_binders() { if let Some(sized_def_id) = tcx.lang_items().sized_trait() { if trait_ref.def_id() == sized_def_id { - if trait_ref.skip_binder().self_ty().is_trivially_sized(tcx) { + if trait_ref.self_ty().is_trivially_sized(tcx) { return Some(()); } } diff --git a/src/librustc_trait_selection/traits/select/confirmation.rs b/src/librustc_trait_selection/traits/select/confirmation.rs index fa970589bbbf6..a04636af5796a 100644 --- a/src/librustc_trait_selection/traits/select/confirmation.rs +++ b/src/librustc_trait_selection/traits/select/confirmation.rs @@ -532,7 +532,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligations.push(Obligation::new( obligation.cause.clone(), obligation.param_env, - ty::PredicateKind::ClosureKind(closure_def_id, substs, kind) + ty::PredicateAtom::ClosureKind(closure_def_id, substs, kind) .to_predicate(self.tcx()), )); } diff --git a/src/librustc_trait_selection/traits/select/mod.rs b/src/librustc_trait_selection/traits/select/mod.rs index 5dc5fb797ff6c..4123f2938261c 100644 --- a/src/librustc_trait_selection/traits/select/mod.rs +++ b/src/librustc_trait_selection/traits/select/mod.rs @@ -35,7 +35,9 @@ use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::fast_reject; use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef}; -use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{ + self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness, +}; use rustc_span::symbol::sym; use std::cell::{Cell, RefCell}; @@ -406,14 +408,16 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { None => self.check_recursion_limit(&obligation, &obligation)?, } - match obligation.predicate.kind() { - &ty::PredicateKind::Trait(t, _) => { + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(t, _) => { + let t = ty::Binder::bind(t); debug_assert!(!t.has_escaping_bound_vars()); let obligation = obligation.with(t); self.evaluate_trait_predicate_recursively(previous_stack, obligation) } - &ty::PredicateKind::Subtype(p) => { + ty::PredicateAtom::Subtype(p) => { + let p = ty::Binder::bind(p); // Does this code ever run? match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) { Some(Ok(InferOk { mut obligations, .. })) => { @@ -428,7 +432,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - &ty::PredicateKind::WellFormed(arg) => match wf::obligations( + ty::PredicateAtom::WellFormed(arg) => match wf::obligations( self.infcx, obligation.param_env, obligation.cause.body_id, @@ -442,12 +446,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { None => Ok(EvaluatedToAmbig), }, - ty::PredicateKind::TypeOutlives(..) | ty::PredicateKind::RegionOutlives(..) => { + ty::PredicateAtom::TypeOutlives(..) | ty::PredicateAtom::RegionOutlives(..) => { // We do not consider region relationships when evaluating trait matches. Ok(EvaluatedToOkModuloRegions) } - &ty::PredicateKind::ObjectSafe(trait_def_id) => { + ty::PredicateAtom::ObjectSafe(trait_def_id) => { if self.tcx().is_object_safe(trait_def_id) { Ok(EvaluatedToOk) } else { @@ -455,7 +459,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - &ty::PredicateKind::Projection(data) => { + ty::PredicateAtom::Projection(data) => { + let data = ty::Binder::bind(data); let project_obligation = obligation.with(data); match project::poly_project_and_unify_type(self, &project_obligation) { Ok(Some(mut subobligations)) => { @@ -476,7 +481,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - &ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { + ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => { match self.infcx.closure_kind(closure_substs) { Some(closure_kind) => { if closure_kind.extends(kind) { @@ -489,7 +494,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - &ty::PredicateKind::ConstEvaluatable(def_id, substs) => { + ty::PredicateAtom::ConstEvaluatable(def_id, substs) => { match self.tcx().const_eval_resolve( obligation.param_env, def_id, @@ -503,7 +508,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { debug!("evaluate_predicate_recursively: equating consts c1={:?} c2={:?}", c1, c2); let evaluate = |c: &'tcx ty::Const<'tcx>| { @@ -669,10 +674,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // if the regions match exactly. let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth); let tcx = self.tcx(); - let cycle = cycle.map(|stack| { - ty::PredicateKind::Trait(stack.obligation.predicate, hir::Constness::NotConst) - .to_predicate(tcx) - }); + let cycle = + cycle.map(|stack| stack.obligation.predicate.without_const().to_predicate(tcx)); if self.coinductive_match(cycle) { debug!("evaluate_stack({:?}) --> recursive, coinductive", stack.fresh_trait_ref); Some(EvaluatedToOk) @@ -786,8 +789,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { - let result = match predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()), + let result = match predicate.skip_binders() { + ty::PredicateAtom::Trait(ref data, _) => self.tcx().trait_is_auto(data.def_id()), _ => false, }; debug!("coinductive_predicate({:?}) = {:?}", predicate, result); @@ -1295,8 +1298,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; let matching_bound = predicates.iter().find_map(|bound| { - if let ty::PredicateKind::Trait(bound, _) = bound.kind() { - let bound = bound.to_poly_trait_ref(); + if let ty::PredicateAtom::Trait(pred, _) = bound.skip_binders() { + let bound = ty::Binder::bind(pred.trait_ref); if self.infcx.probe(|_| { self.match_projection(obligation, bound, placeholder_trait_predicate.trait_ref) }) { diff --git a/src/librustc_trait_selection/traits/util.rs b/src/librustc_trait_selection/traits/util.rs index d3484b8af89fd..cc8997078e0f0 100644 --- a/src/librustc_trait_selection/traits/util.rs +++ b/src/librustc_trait_selection/traits/util.rs @@ -59,8 +59,8 @@ impl<'tcx> TraitAliasExpansionInfo<'tcx> { ); } - pub fn trait_ref(&self) -> &ty::PolyTraitRef<'tcx> { - &self.top().0 + pub fn trait_ref(&self) -> ty::PolyTraitRef<'tcx> { + self.top().0 } pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) { @@ -109,7 +109,7 @@ impl<'tcx> TraitAliasExpander<'tcx> { // Don't recurse if this trait alias is already on the stack for the DFS search. let anon_pred = anonymize_predicate(tcx, pred); - if item.path.iter().rev().skip(1).any(|(tr, _)| { + if item.path.iter().rev().skip(1).any(|&(tr, _)| { anonymize_predicate(tcx, tr.without_const().to_predicate(tcx)) == anon_pred }) { return false; diff --git a/src/librustc_trait_selection/traits/wf.rs b/src/librustc_trait_selection/traits/wf.rs index 0e445e1e53bba..d225b10834a6b 100644 --- a/src/librustc_trait_selection/traits/wf.rs +++ b/src/librustc_trait_selection/traits/wf.rs @@ -93,30 +93,29 @@ pub fn predicate_obligations<'a, 'tcx>( ) -> Vec> { let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None }; - // (*) ok to skip binders, because wf code is prepared for it - match predicate.kind() { - ty::PredicateKind::Trait(t, _) => { - wf.compute_trait_ref(&t.skip_binder().trait_ref, Elaborate::None); // (*) + // It's ok to skip the binder here because wf code is prepared for it + match predicate.skip_binders() { + ty::PredicateAtom::Trait(t, _) => { + wf.compute_trait_ref(&t.trait_ref, Elaborate::None); } - ty::PredicateKind::RegionOutlives(..) => {} - ty::PredicateKind::TypeOutlives(t) => { - wf.compute(t.skip_binder().0.into()); + ty::PredicateAtom::RegionOutlives(..) => {} + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { + wf.compute(ty.into()); } - ty::PredicateKind::Projection(t) => { - let t = t.skip_binder(); // (*) + ty::PredicateAtom::Projection(t) => { wf.compute_projection(t.projection_ty); wf.compute(t.ty.into()); } - &ty::PredicateKind::WellFormed(arg) => { + ty::PredicateAtom::WellFormed(arg) => { wf.compute(arg); } - ty::PredicateKind::ObjectSafe(_) => {} - ty::PredicateKind::ClosureKind(..) => {} - ty::PredicateKind::Subtype(data) => { - wf.compute(data.skip_binder().a.into()); // (*) - wf.compute(data.skip_binder().b.into()); // (*) + ty::PredicateAtom::ObjectSafe(_) => {} + ty::PredicateAtom::ClosureKind(..) => {} + ty::PredicateAtom::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => { + wf.compute(a.into()); + wf.compute(b.into()); } - &ty::PredicateKind::ConstEvaluatable(def, substs) => { + ty::PredicateAtom::ConstEvaluatable(def, substs) => { let obligations = wf.nominal_obligations(def.did, substs); wf.out.extend(obligations); @@ -124,7 +123,7 @@ pub fn predicate_obligations<'a, 'tcx>( wf.compute(arg); } } - &ty::PredicateKind::ConstEquate(c1, c2) => { + ty::PredicateAtom::ConstEquate(c1, c2) => { wf.compute(c1.into()); wf.compute(c2.into()); } @@ -176,7 +175,7 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( trait_ref: &ty::TraitRef<'tcx>, item: Option<&hir::Item<'tcx>>, cause: &mut traits::ObligationCause<'tcx>, - pred: &ty::Predicate<'_>, + pred: &ty::Predicate<'tcx>, mut trait_assoc_items: impl Iterator, ) { debug!( @@ -192,15 +191,16 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span, _ => impl_item_ref.span, }; - match pred.kind() { - ty::PredicateKind::Projection(proj) => { + + // It is fine to skip the binder as we don't care about regions here. + match pred.skip_binders() { + ty::PredicateAtom::Projection(proj) => { // The obligation comes not from the current `impl` nor the `trait` being implemented, // but rather from a "second order" obligation, where an associated type has a // projection coming from another associated type. See // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and // `traits-assoc-type-in-supertrait-bad.rs`. - let kind = &proj.ty().skip_binder().kind; - if let ty::Projection(projection_ty) = kind { + if let ty::Projection(projection_ty) = proj.ty.kind { let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id); if let Some(impl_item_span) = items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span) @@ -209,15 +209,13 @@ fn extend_cause_with_original_assoc_item_obligation<'tcx>( } } } - ty::PredicateKind::Trait(pred, _) => { + ty::PredicateAtom::Trait(pred, _) => { // An associated item obligation born out of the `trait` failed to be met. An example // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`. debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred); - if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = - &pred.skip_binder().self_ty().kind - { + if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = pred.self_ty().kind { if let Some(impl_item_span) = trait_assoc_items - .find(|i| i.def_id == *item_def_id) + .find(|i| i.def_id == item_def_id) .and_then(|trait_assoc_item| { items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span) }) @@ -316,7 +314,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { traits::Obligation::new( new_cause, param_env, - ty::PredicateKind::WellFormed(arg).to_predicate(tcx), + ty::PredicateAtom::WellFormed(arg).to_predicate(tcx), ) }), ); @@ -373,7 +371,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let obligations = self.nominal_obligations(def.did, substs); self.out.extend(obligations); - let predicate = ty::PredicateKind::ConstEvaluatable(def, substs) + let predicate = ty::PredicateAtom::ConstEvaluatable(def, substs) .to_predicate(self.tcx()); let cause = self.cause(traits::MiscObligation); self.out.push(traits::Obligation::new( @@ -395,7 +393,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.out.push(traits::Obligation::new( cause, self.param_env, - ty::PredicateKind::WellFormed(resolved_constant.into()) + ty::PredicateAtom::WellFormed(resolved_constant.into()) .to_predicate(self.tcx()), )); } @@ -481,10 +479,8 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.out.push(traits::Obligation::new( cause, param_env, - ty::PredicateKind::TypeOutlives(ty::Binder::dummy( - ty::OutlivesPredicate(rty, r), - )) - .to_predicate(self.tcx()), + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(rty, r)) + .to_predicate(self.tcx()), )); } } @@ -574,7 +570,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { traits::Obligation::new( cause.clone(), param_env, - ty::PredicateKind::ObjectSafe(did).to_predicate(tcx), + ty::PredicateAtom::ObjectSafe(did).to_predicate(tcx), ) })); } @@ -600,7 +596,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.out.push(traits::Obligation::new( cause, param_env, - ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx()), )); } else { // Yes, resolved, proceed with the result. diff --git a/src/librustc_traits/chalk/lowering.rs b/src/librustc_traits/chalk/lowering.rs index ed021e5b9de1b..75785076d9ac1 100644 --- a/src/librustc_traits/chalk/lowering.rs +++ b/src/librustc_traits/chalk/lowering.rs @@ -78,10 +78,12 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment chalk_ir::InEnvironment>> { let clauses = self.environment.into_iter().filter_map(|clause| match clause { ChalkEnvironmentClause::Predicate(predicate) => { - match predicate.kind() { - ty::PredicateKind::Trait(predicate, _) => { + // FIXME(chalk): forall + match predicate.bound_atom(interner.tcx).skip_binder() { + ty::PredicateAtom::Trait(predicate, _) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); Some( chalk_ir::ProgramClauseData(chalk_ir::Binders::new( @@ -99,9 +101,10 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment { + ty::PredicateAtom::RegionOutlives(predicate) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); Some( chalk_ir::ProgramClauseData(chalk_ir::Binders::new( @@ -123,10 +126,11 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment None, - ty::PredicateKind::Projection(predicate) => { + ty::PredicateAtom::TypeOutlives(_) => None, + ty::PredicateAtom::Projection(predicate) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); Some( chalk_ir::ProgramClauseData(chalk_ir::Binders::new( @@ -144,12 +148,12 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment { + ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => { bug!("unexpected predicate {}", predicate) } } @@ -181,11 +185,15 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predicate<'tcx> { fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData> { - match self.kind() { - ty::PredicateKind::Trait(predicate, _) => predicate.lower_into(interner), - ty::PredicateKind::RegionOutlives(predicate) => { + // FIXME(chalk): forall + match self.bound_atom(interner.tcx).skip_binder() { + ty::PredicateAtom::Trait(predicate, _) => { + ty::Binder::bind(predicate).lower_into(interner) + } + ty::PredicateAtom::RegionOutlives(predicate) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); chalk_ir::GoalData::Quantified( chalk_ir::QuantifierKind::ForAll, @@ -202,20 +210,34 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi ) } // FIXME(chalk): TypeOutlives - ty::PredicateKind::TypeOutlives(_predicate) => { + ty::PredicateAtom::TypeOutlives(_predicate) => { chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) } - ty::PredicateKind::Projection(predicate) => predicate.lower_into(interner), - ty::PredicateKind::WellFormed(arg) => match arg.unpack() { + ty::PredicateAtom::Projection(predicate) => { + ty::Binder::bind(predicate).lower_into(interner) + } + ty::PredicateAtom::WellFormed(arg) => match arg.unpack() { GenericArgKind::Type(ty) => match ty.kind { // FIXME(chalk): In Chalk, a placeholder is WellFormed if it // `FromEnv`. However, when we "lower" Params, we don't update // the environment. ty::Placeholder(..) => chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)), - _ => chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed( - chalk_ir::WellFormed::Ty(ty.lower_into(interner)), - )), + _ => { + let (ty, binders, _named_regions) = + collect_bound_vars(interner, interner.tcx, &ty::Binder::bind(ty)); + + chalk_ir::GoalData::Quantified( + chalk_ir::QuantifierKind::ForAll, + chalk_ir::Binders::new( + binders, + chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed( + chalk_ir::WellFormed::Ty(ty.lower_into(interner)), + )) + .intern(interner), + ), + ) + } }, // FIXME(chalk): handle well formed consts GenericArgKind::Const(..) => { @@ -224,18 +246,18 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predi GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt), }, - ty::PredicateKind::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal( - chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(*t)), + ty::PredicateAtom::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal( + chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(t)), ), // FIXME(chalk): other predicates // // We can defer this, but ultimately we'll want to express // some of these in terms of chalk operations. - ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => { + ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => { chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) } } @@ -532,19 +554,22 @@ impl<'tcx> LowerInto<'tcx, Option, ) -> Option>> { - match &self.kind() { - ty::PredicateKind::Trait(predicate, _) => { + // FIXME(chalk): forall + match self.bound_atom(interner.tcx).skip_binder() { + ty::PredicateAtom::Trait(predicate, _) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); Some(chalk_ir::Binders::new( binders, chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)), )) } - ty::PredicateKind::RegionOutlives(predicate) => { + ty::PredicateAtom::RegionOutlives(predicate) => { + let predicate = ty::Binder::bind(predicate); let (predicate, binders, _named_regions) = - collect_bound_vars(interner, interner.tcx, predicate); + collect_bound_vars(interner, interner.tcx, &predicate); Some(chalk_ir::Binders::new( binders, @@ -554,15 +579,15 @@ impl<'tcx> LowerInto<'tcx, Option None, - ty::PredicateKind::Projection(_predicate) => None, - ty::PredicateKind::WellFormed(_ty) => None, - - ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => bug!("unexpected predicate {}", &self), + ty::PredicateAtom::TypeOutlives(_predicate) => None, + ty::PredicateAtom::Projection(_predicate) => None, + ty::PredicateAtom::WellFormed(_ty) => None, + + ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => bug!("unexpected predicate {}", &self), } } } @@ -632,7 +657,9 @@ crate fn collect_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>>( } (0..parameters.len()).for_each(|i| { - parameters.get(&(i as u32)).expect(&format!("Skipped bound var index `{:?}`.", i)); + parameters + .get(&(i as u32)) + .or_else(|| bug!("Skipped bound var index: ty={:?}, parameters={:?}", ty, parameters)); }); let binders = chalk_ir::VariableKinds::from(interner, parameters.into_iter().map(|(_, v)| v)); diff --git a/src/librustc_traits/implied_outlives_bounds.rs b/src/librustc_traits/implied_outlives_bounds.rs index bda3da120e958..de3096eac9b19 100644 --- a/src/librustc_traits/implied_outlives_bounds.rs +++ b/src/librustc_traits/implied_outlives_bounds.rs @@ -95,29 +95,25 @@ fn compute_implied_outlives_bounds<'tcx>( implied_bounds.extend(obligations.into_iter().flat_map(|obligation| { assert!(!obligation.has_escaping_bound_vars()); match obligation.predicate.kind() { - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => vec![], - - &ty::PredicateKind::WellFormed(arg) => { - wf_args.push(arg); - vec![] - } + &ty::PredicateKind::ForAll(..) => vec![], + &ty::PredicateKind::Atom(atom) => match atom { + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => vec![], + ty::PredicateAtom::WellFormed(arg) => { + wf_args.push(arg); + vec![] + } - ty::PredicateKind::RegionOutlives(ref data) => match data.no_bound_vars() { - None => vec![], - Some(ty::OutlivesPredicate(r_a, r_b)) => { + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => { vec![OutlivesBound::RegionSubRegion(r_b, r_a)] } - }, - ty::PredicateKind::TypeOutlives(ref data) => match data.no_bound_vars() { - None => vec![], - Some(ty::OutlivesPredicate(ty_a, r_b)) => { + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => { let ty_a = infcx.resolve_vars_if_possible(&ty_a); let mut components = smallvec![]; tcx.push_outlives_components(ty_a, &mut components); diff --git a/src/librustc_traits/normalize_erasing_regions.rs b/src/librustc_traits/normalize_erasing_regions.rs index 7092515af0882..83aee31a39f3c 100644 --- a/src/librustc_traits/normalize_erasing_regions.rs +++ b/src/librustc_traits/normalize_erasing_regions.rs @@ -39,16 +39,16 @@ fn normalize_generic_arg_after_erasing_regions<'tcx>( }) } -fn not_outlives_predicate(p: &ty::Predicate<'_>) -> bool { - match p.kind() { - ty::PredicateKind::RegionOutlives(..) | ty::PredicateKind::TypeOutlives(..) => false, - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => true, +fn not_outlives_predicate(p: &ty::Predicate<'tcx>) -> bool { + match p.skip_binders() { + ty::PredicateAtom::RegionOutlives(..) | ty::PredicateAtom::TypeOutlives(..) => false, + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => true, } } diff --git a/src/librustc_traits/type_op.rs b/src/librustc_traits/type_op.rs index 9cc9a35b38b8a..139ed6dcd350c 100644 --- a/src/librustc_traits/type_op.rs +++ b/src/librustc_traits/type_op.rs @@ -140,7 +140,7 @@ impl AscribeUserTypeCx<'me, 'tcx> { self.relate(self_ty, Variance::Invariant, impl_self_ty)?; self.prove_predicate( - ty::PredicateKind::WellFormed(impl_self_ty.into()).to_predicate(self.tcx()), + ty::PredicateAtom::WellFormed(impl_self_ty.into()).to_predicate(self.tcx()), ); } @@ -155,7 +155,7 @@ impl AscribeUserTypeCx<'me, 'tcx> { // them? This would only be relevant if some input // type were ill-formed but did not appear in `ty`, // which...could happen with normalization... - self.prove_predicate(ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx())); + self.prove_predicate(ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx())); Ok(()) } } diff --git a/src/librustc_ty/ty.rs b/src/librustc_ty/ty.rs index c99bc8a47e33b..7f954dacf3e89 100644 --- a/src/librustc_ty/ty.rs +++ b/src/librustc_ty/ty.rs @@ -392,23 +392,23 @@ fn associated_type_projection_predicates( let predicates = item_predicates.filter_map(|obligation| { let pred = obligation.predicate; - match pred.kind() { - ty::PredicateKind::Trait(tr, _) => { - if let ty::Projection(p) = tr.skip_binder().self_ty().kind { + match pred.skip_binders() { + ty::PredicateAtom::Trait(tr, _) => { + if let ty::Projection(p) = tr.self_ty().kind { if p == assoc_item_ty { return Some(pred); } } } - ty::PredicateKind::Projection(proj) => { - if let ty::Projection(p) = proj.skip_binder().projection_ty.self_ty().kind { + ty::PredicateAtom::Projection(proj) => { + if let ty::Projection(p) = proj.projection_ty.self_ty().kind { if p == assoc_item_ty { return Some(pred); } } } - ty::PredicateKind::TypeOutlives(outlives) => { - if let ty::Projection(p) = outlives.skip_binder().0.kind { + ty::PredicateAtom::TypeOutlives(outlives) => { + if let ty::Projection(p) = outlives.0.kind { if p == assoc_item_ty { return Some(pred); } @@ -443,25 +443,24 @@ fn opaque_type_projection_predicates( let filtered_predicates = predicates.filter_map(|obligation| { let pred = obligation.predicate; - match pred.kind() { - ty::PredicateKind::Trait(tr, _) => { - if let ty::Opaque(opaque_def_id, opaque_substs) = tr.skip_binder().self_ty().kind { + match pred.skip_binders() { + ty::PredicateAtom::Trait(tr, _) => { + if let ty::Opaque(opaque_def_id, opaque_substs) = tr.self_ty().kind { if opaque_def_id == def_id && opaque_substs == substs { return Some(pred); } } } - ty::PredicateKind::Projection(proj) => { - if let ty::Opaque(opaque_def_id, opaque_substs) = - proj.skip_binder().projection_ty.self_ty().kind + ty::PredicateAtom::Projection(proj) => { + if let ty::Opaque(opaque_def_id, opaque_substs) = proj.projection_ty.self_ty().kind { if opaque_def_id == def_id && opaque_substs == substs { return Some(pred); } } } - ty::PredicateKind::TypeOutlives(outlives) => { - if let ty::Opaque(opaque_def_id, opaque_substs) = outlives.skip_binder().0.kind { + ty::PredicateAtom::TypeOutlives(outlives) => { + if let ty::Opaque(opaque_def_id, opaque_substs) = outlives.0.kind { if opaque_def_id == def_id && opaque_substs == substs { return Some(pred); } @@ -471,7 +470,7 @@ fn opaque_type_projection_predicates( } } // These can come from elaborating other predicates - ty::PredicateKind::RegionOutlives(_) => return None, + ty::PredicateAtom::RegionOutlives(_) => return None, _ => {} } tcx.sess.delay_span_bug( diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 21b5f5c9033e6..79d2f104a525f 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1705,8 +1705,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", obligation.predicate ); - match obligation.predicate.kind() { - ty::PredicateKind::Trait(pred, _) => { + + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(pred, _) => { + let pred = ty::Binder::bind(pred); associated_types.entry(span).or_default().extend( tcx.associated_items(pred.def_id()) .in_definition_order() @@ -1714,7 +1716,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .map(|item| item.def_id), ); } - &ty::PredicateKind::Projection(pred) => { + ty::PredicateAtom::Projection(pred) => { + let pred = ty::Binder::bind(pred); // A `Self` within the original bound will be substituted with a // `trait_object_dummy_self`, so check for that. let references_self = diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 8b18e759026b1..255f611cfa357 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -206,11 +206,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { obligation.predicate ); - if let &ty::PredicateKind::Projection(proj_predicate) = obligation.predicate.kind() + if let ty::PredicateAtom::Projection(proj_predicate) = + obligation.predicate.skip_binders() { // Given a Projection predicate, we can potentially infer // the complete signature. - self.deduce_sig_from_projection(Some(obligation.cause.span), proj_predicate) + self.deduce_sig_from_projection( + Some(obligation.cause.span), + ty::Binder::bind(proj_predicate), + ) } else { None } @@ -627,8 +631,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // where R is the return type we are expecting. This type `T` // will be our output. let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| { - if let &ty::PredicateKind::Projection(proj_predicate) = obligation.predicate.kind() { - self.deduce_future_output_from_projection(obligation.cause.span, proj_predicate) + if let ty::PredicateAtom::Projection(proj_predicate) = + obligation.predicate.skip_binders() + { + self.deduce_future_output_from_projection( + obligation.cause.span, + ty::Binder::bind(proj_predicate), + ) } else { None } diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 5cf2e2d64100c..c7e9b97e2dbde 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -582,18 +582,18 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { while !queue.is_empty() { let obligation = queue.remove(0); debug!("coerce_unsized resolve step: {:?}", obligation); - let trait_pred = match obligation.predicate.kind() { - &ty::PredicateKind::Trait(trait_pred, _) + let trait_pred = match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(trait_pred, _) if traits.contains(&trait_pred.def_id()) => { if unsize_did == trait_pred.def_id() { - let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); + let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); if let ty::Tuple(..) = unsize_ty.kind { debug!("coerce_unsized: found unsized tuple coercion"); has_unsized_tuple_coercion = true; } } - trait_pred + ty::Binder::bind(trait_pred) } _ => { coercion.obligations.push(obligation); diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index f6991120f3479..88c47b38ccc40 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -226,12 +226,12 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( // could be extended easily also to the other `Predicate`. let predicate_matches_closure = |p: Predicate<'tcx>| { let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env); - match (predicate.kind(), p.kind()) { - (&ty::PredicateKind::Trait(a, _), &ty::PredicateKind::Trait(b, _)) => { - relator.relate(a, b).is_ok() + match (predicate.skip_binders(), p.skip_binders()) { + (ty::PredicateAtom::Trait(a, _), ty::PredicateAtom::Trait(b, _)) => { + relator.relate(ty::Binder::bind(a), ty::Binder::bind(b)).is_ok() } - (&ty::PredicateKind::Projection(a), &ty::PredicateKind::Projection(b)) => { - relator.relate(a, b).is_ok() + (ty::PredicateAtom::Projection(a), ty::PredicateAtom::Projection(b)) => { + relator.relate(ty::Binder::bind(a), ty::Binder::bind(b)).is_ok() } _ => predicate == p, } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index ed84095ae6b0c..41e37ee975252 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -447,21 +447,24 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { }; traits::elaborate_predicates(self.tcx, predicates.predicates.iter().copied()) - .filter_map(|obligation| match obligation.predicate.kind() { - ty::PredicateKind::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => { + // We don't care about regions here. + .filter_map(|obligation| match obligation.predicate.skip_binders() { + ty::PredicateAtom::Trait(trait_pred, _) if trait_pred.def_id() == sized_def_id => { let span = predicates .predicates .iter() .zip(predicates.spans.iter()) .find_map( - |(p, span)| if *p == obligation.predicate { Some(*span) } else { None }, + |(p, span)| { + if *p == obligation.predicate { Some(*span) } else { None } + }, ) .unwrap_or(rustc_span::DUMMY_SP); Some((trait_pred, span)) } _ => None, }) - .find_map(|(trait_pred, span)| match trait_pred.skip_binder().self_ty().kind { + .find_map(|(trait_pred, span)| match trait_pred.self_ty().kind { ty::Dynamic(..) => Some(span), _ => None, }) diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 64dce3e1738e3..c9a4df0317abc 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -399,7 +399,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { obligations.push(traits::Obligation::new( cause, self.param_env, - ty::PredicateKind::WellFormed(method_ty.into()).to_predicate(tcx), + ty::PredicateAtom::WellFormed(method_ty.into()).to_predicate(tcx), )); let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig }; diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 9c5e3cbc93844..106df847a05cf 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -798,25 +798,28 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // FIXME: do we want to commit to this behavior for param bounds? debug!("assemble_inherent_candidates_from_param(param_ty={:?})", param_ty); - let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| match predicate - .kind() - { - ty::PredicateKind::Trait(ref trait_predicate, _) => { - match trait_predicate.skip_binder().trait_ref.self_ty().kind { - ty::Param(ref p) if *p == param_ty => Some(trait_predicate.to_poly_trait_ref()), - _ => None, - } - } - ty::PredicateKind::Subtype(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::RegionOutlives(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::TypeOutlives(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => None, - }); + let bounds = + self.param_env.caller_bounds().iter().map(ty::Predicate::skip_binders).filter_map( + |predicate| match predicate { + ty::PredicateAtom::Trait(trait_predicate, _) => { + match trait_predicate.trait_ref.self_ty().kind { + ty::Param(ref p) if *p == param_ty => { + Some(ty::Binder::bind(trait_predicate.trait_ref)) + } + _ => None, + } + } + ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::RegionOutlives(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::TypeOutlives(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => None, + }, + ); self.elaborate_bounds(bounds, |this, poly_trait_ref, item| { let trait_ref = this.erase_late_bound_regions(&poly_trait_ref); diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index b9f1f8064c861..ae2cf6daf5350 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -570,12 +570,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let mut type_params = FxHashMap::default(); let mut bound_spans = vec![]; + let mut collect_type_param_suggestions = - |self_ty: Ty<'_>, parent_pred: &ty::Predicate<'_>, obligation: &str| { - if let (ty::Param(_), ty::PredicateKind::Trait(p, _)) = - (&self_ty.kind, parent_pred.kind()) + |self_ty: Ty<'tcx>, parent_pred: &ty::Predicate<'tcx>, obligation: &str| { + // We don't care about regions here, so it's fine to skip the binder here. + if let (ty::Param(_), ty::PredicateAtom::Trait(p, _)) = + (&self_ty.kind, parent_pred.skip_binders()) { - if let ty::Adt(def, _) = p.skip_binder().trait_ref.self_ty().kind { + if let ty::Adt(def, _) = p.trait_ref.self_ty().kind { let node = def.did.as_local().map(|def_id| { self.tcx.hir().get(self.tcx.hir().as_local_hir_id(def_id)) }); @@ -625,8 +627,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; let mut format_pred = |pred: ty::Predicate<'tcx>| { - match pred.kind() { - ty::PredicateKind::Projection(pred) => { + match pred.skip_binders() { + ty::PredicateAtom::Projection(pred) => { + let pred = ty::Binder::bind(pred); // `::Item = String`. let trait_ref = pred.skip_binder().projection_ty.trait_ref(self.tcx); @@ -644,7 +647,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bound_span_label(trait_ref.self_ty(), &obligation, &quiet); Some((obligation, trait_ref.self_ty())) } - ty::PredicateKind::Trait(poly_trait_ref, _) => { + ty::PredicateAtom::Trait(poly_trait_ref, _) => { + let poly_trait_ref = ty::Binder::bind(poly_trait_ref); let p = poly_trait_ref.skip_binder().trait_ref; let self_ty = p.self_ty(); let path = p.print_only_trait_path(); @@ -950,12 +954,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // this isn't perfect (that is, there are cases when // implementing a trait would be legal but is rejected // here). - unsatisfied_predicates.iter().all(|(p, _)| match p.kind() { - // Hide traits if they are present in predicates as they can be fixed without - // having to implement them. - ty::PredicateKind::Trait(t, _) => t.def_id() == info.def_id, - ty::PredicateKind::Projection(p) => p.item_def_id() == info.def_id, - _ => false, + unsatisfied_predicates.iter().all(|(p, _)| { + match p.skip_binders() { + // Hide traits if they are present in predicates as they can be fixed without + // having to implement them. + ty::PredicateAtom::Trait(t, _) => t.def_id() == info.def_id, + ty::PredicateAtom::Projection(p) => { + p.projection_ty.item_def_id == info.def_id + } + _ => false, + } }) && (type_is_local || info.def_id.is_local()) && self .associated_item(info.def_id, item_name, Namespace::ValueNS) diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 6e77aba30506a..6cefc99f7b171 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -2392,26 +2392,26 @@ fn missing_items_err( } /// Resugar `ty::GenericPredicates` in a way suitable to be used in structured suggestions. -fn bounds_from_generic_predicates( - tcx: TyCtxt<'_>, - predicates: ty::GenericPredicates<'_>, +fn bounds_from_generic_predicates<'tcx>( + tcx: TyCtxt<'tcx>, + predicates: ty::GenericPredicates<'tcx>, ) -> (String, String) { - let mut types: FxHashMap, Vec> = FxHashMap::default(); + let mut types: FxHashMap, Vec> = FxHashMap::default(); let mut projections = vec![]; for (predicate, _) in predicates.predicates { debug!("predicate {:?}", predicate); - match predicate.kind() { - ty::PredicateKind::Trait(trait_predicate, _) => { - let entry = types.entry(trait_predicate.skip_binder().self_ty()).or_default(); - let def_id = trait_predicate.skip_binder().def_id(); + match predicate.skip_binders() { + ty::PredicateAtom::Trait(trait_predicate, _) => { + let entry = types.entry(trait_predicate.self_ty()).or_default(); + let def_id = trait_predicate.def_id(); if Some(def_id) != tcx.lang_items().sized_trait() { // Type params are `Sized` by default, do not add that restriction to the list // if it is a positive requirement. - entry.push(trait_predicate.skip_binder().def_id()); + entry.push(trait_predicate.def_id()); } } - ty::PredicateKind::Projection(projection_pred) => { - projections.push(projection_pred); + ty::PredicateAtom::Projection(projection_pred) => { + projections.push(ty::Binder::bind(projection_pred)); } _ => {} } @@ -2456,11 +2456,11 @@ fn bounds_from_generic_predicates( } /// Return placeholder code for the given function. -fn fn_sig_suggestion( - tcx: TyCtxt<'_>, - sig: ty::FnSig<'_>, +fn fn_sig_suggestion<'tcx>( + tcx: TyCtxt<'tcx>, + sig: ty::FnSig<'tcx>, ident: Ident, - predicates: ty::GenericPredicates<'_>, + predicates: ty::GenericPredicates<'tcx>, assoc: &ty::AssocItem, ) -> String { let args = sig @@ -2938,10 +2938,8 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { parent: None, predicates: tcx.arena.alloc_from_iter( self.param_env.caller_bounds().iter().filter_map(|predicate| { - match predicate.kind() { - ty::PredicateKind::Trait(ref data, _) - if data.skip_binder().self_ty().is_param(index) => - { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) if data.self_ty().is_param(index) => { // HACK(eddyb) should get the original `Span`. let span = tcx.def_span(def_id); Some((predicate, span)) @@ -3612,7 +3610,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.register_predicate(traits::Obligation::new( cause, self.param_env, - ty::PredicateKind::WellFormed(arg).to_predicate(self.tcx), + ty::PredicateAtom::WellFormed(arg).to_predicate(self.tcx), )); } @@ -3893,29 +3891,31 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .borrow() .pending_obligations() .into_iter() - .filter_map(move |obligation| match obligation.predicate.kind() { - ty::PredicateKind::Projection(ref data) => { - Some((data.to_poly_trait_ref(self.tcx), obligation)) - } - ty::PredicateKind::Trait(ref data, _) => { - Some((data.to_poly_trait_ref(), obligation)) + .filter_map(move |obligation| { + match obligation.predicate.skip_binders() { + ty::PredicateAtom::Projection(data) => { + Some((ty::Binder::bind(data).to_poly_trait_ref(self.tcx), obligation)) + } + ty::PredicateAtom::Trait(data, _) => { + Some((ty::Binder::bind(data).to_poly_trait_ref(), obligation)) + } + ty::PredicateAtom::Subtype(..) => None, + ty::PredicateAtom::RegionOutlives(..) => None, + ty::PredicateAtom::TypeOutlives(..) => None, + ty::PredicateAtom::WellFormed(..) => None, + ty::PredicateAtom::ObjectSafe(..) => None, + ty::PredicateAtom::ConstEvaluatable(..) => None, + ty::PredicateAtom::ConstEquate(..) => None, + // N.B., this predicate is created by breaking down a + // `ClosureType: FnFoo()` predicate, where + // `ClosureType` represents some `Closure`. It can't + // possibly be referring to the current closure, + // because we haven't produced the `Closure` for + // this closure yet; this is exactly why the other + // code is looking for a self type of a unresolved + // inference variable. + ty::PredicateAtom::ClosureKind(..) => None, } - ty::PredicateKind::Subtype(..) => None, - ty::PredicateKind::RegionOutlives(..) => None, - ty::PredicateKind::TypeOutlives(..) => None, - ty::PredicateKind::WellFormed(..) => None, - ty::PredicateKind::ObjectSafe(..) => None, - ty::PredicateKind::ConstEvaluatable(..) => None, - ty::PredicateKind::ConstEquate(..) => None, - // N.B., this predicate is created by breaking down a - // `ClosureType: FnFoo()` predicate, where - // `ClosureType` represents some `Closure`. It can't - // possibly be referring to the current closure, - // because we haven't produced the `Closure` for - // this closure yet; this is exactly why the other - // code is looking for a self type of a unresolved - // inference variable. - ty::PredicateKind::ClosureKind(..) => None, }) .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root)) } @@ -4225,7 +4225,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// the corresponding argument's expression span instead of the `fn` call path span. fn point_at_arg_instead_of_call_if_possible( &self, - errors: &mut Vec>, + errors: &mut Vec>, final_arg_types: &[(usize, Ty<'tcx>, Ty<'tcx>)], call_sp: Span, args: &'tcx [hir::Expr<'tcx>], @@ -4244,7 +4244,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } - if let ty::PredicateKind::Trait(predicate, _) = error.obligation.predicate.kind() { + if let ty::PredicateAtom::Trait(predicate, _) = + error.obligation.predicate.skip_binders() + { // Collect the argument position for all arguments that could have caused this // `FulfillmentError`. let mut referenced_in = final_arg_types @@ -4255,7 +4257,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = self.resolve_vars_if_possible(&ty); // We walk the argument type because the argument's type could have // been `Option`, but the `FulfillmentError` references `T`. - if ty.walk().any(|arg| arg == predicate.skip_binder().self_ty().into()) { + if ty.walk().any(|arg| arg == predicate.self_ty().into()) { Some(i) } else { None @@ -4284,15 +4286,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// instead of the `fn` call path span. fn point_at_type_arg_instead_of_call_if_possible( &self, - errors: &mut Vec>, + errors: &mut Vec>, call_expr: &'tcx hir::Expr<'tcx>, ) { if let hir::ExprKind::Call(path, _) = &call_expr.kind { if let hir::ExprKind::Path(qpath) = &path.kind { if let hir::QPath::Resolved(_, path) = &qpath { for error in errors { - if let ty::PredicateKind::Trait(predicate, _) = - error.obligation.predicate.kind() + if let ty::PredicateAtom::Trait(predicate, _) = + error.obligation.predicate.skip_binders() { // If any of the type arguments in this path segment caused the // `FullfillmentError`, point at its span (#61860). @@ -4313,7 +4315,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { let ty = AstConv::ast_ty_to_ty(self, hir_ty); let ty = self.resolve_vars_if_possible(&ty); - if ty == predicate.skip_binder().self_ty() { + if ty == predicate.self_ty() { error.obligation.cause.make_mut().span = hir_ty.span; } } @@ -5365,12 +5367,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item_def_id, }; - let predicate = - ty::PredicateKind::Projection(ty::Binder::bind(ty::ProjectionPredicate { - projection_ty, - ty: expected, - })) - .to_predicate(self.tcx); + let predicate = ty::PredicateAtom::Projection(ty::ProjectionPredicate { + projection_ty, + ty: expected, + }) + .potentially_quantified(self.tcx, ty::PredicateKind::ForAll); let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate); debug!("suggest_missing_await: trying obligation {:?}", obligation); diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index dabae6cbc4137..50d9a1ebd2c24 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -429,7 +429,7 @@ fn check_type_defn<'tcx, F>( fcx.register_predicate(traits::Obligation::new( cause, fcx.param_env, - ty::PredicateKind::ConstEvaluatable( + ty::PredicateAtom::ConstEvaluatable( ty::WithOptConstParam::unknown(discr_def_id.to_def_id()), discr_substs, ) diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index acf68be1176dd..76439af79f351 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -552,10 +552,8 @@ fn type_param_predicates( let extra_predicates = extend.into_iter().chain( icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true)) .into_iter() - .filter(|(predicate, _)| match predicate.kind() { - ty::PredicateKind::Trait(ref data, _) => { - data.skip_binder().self_ty().is_param(index) - } + .filter(|(predicate, _)| match predicate.skip_binders() { + ty::PredicateAtom::Trait(data, _) => data.self_ty().is_param(index), _ => false, }), ); @@ -1006,7 +1004,7 @@ fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredi // which will, in turn, reach indirect supertraits. for &(pred, span) in superbounds { debug!("superbound: {:?}", pred); - if let ty::PredicateKind::Trait(bound, _) = pred.kind() { + if let ty::PredicateAtom::Trait(bound, _) = pred.skip_binders() { tcx.at(span).super_predicates_of(bound.def_id()); } } @@ -1932,8 +1930,8 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat let re_root_empty = tcx.lifetimes.re_root_empty; let predicate = ty::OutlivesPredicate(ty, re_root_empty); predicates.push(( - ty::PredicateKind::TypeOutlives(ty::Binder::bind(predicate)) - .to_predicate(tcx), + ty::PredicateAtom::TypeOutlives(predicate) + .potentially_quantified(tcx, ty::PredicateKind::ForAll), span, )); } @@ -1961,9 +1959,9 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat &hir::GenericBound::Outlives(ref lifetime) => { let region = AstConv::ast_region_to_region(&icx, lifetime, None); - let pred = ty::Binder::bind(ty::OutlivesPredicate(ty, region)); predicates.push(( - ty::PredicateKind::TypeOutlives(pred).to_predicate(tcx), + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, region)) + .potentially_quantified(tcx, ty::PredicateKind::ForAll), lifetime.span, )) } @@ -1980,9 +1978,9 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat } _ => bug!(), }; - let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2)); + let pred = ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate(r1, r2)); - (ty::PredicateKind::RegionOutlives(pred).to_predicate(icx.tcx), span) + (pred.potentially_quantified(icx.tcx, ty::PredicateKind::ForAll), span) })) } @@ -2110,8 +2108,9 @@ fn predicates_from_bound<'tcx>( } hir::GenericBound::Outlives(ref lifetime) => { let region = astconv.ast_region_to_region(lifetime, None); - let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region)); - vec![(ty::PredicateKind::TypeOutlives(pred).to_predicate(astconv.tcx()), lifetime.span)] + let pred = ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(param_ty, region)) + .potentially_quantified(astconv.tcx(), ty::PredicateKind::ForAll); + vec![(pred, lifetime.span)] } } } diff --git a/src/librustc_typeck/constrained_generic_params.rs b/src/librustc_typeck/constrained_generic_params.rs index 34497d12a4ece..7c80315ee194d 100644 --- a/src/librustc_typeck/constrained_generic_params.rs +++ b/src/librustc_typeck/constrained_generic_params.rs @@ -180,11 +180,9 @@ pub fn setup_constraining_predicates<'tcx>( changed = false; for j in i..predicates.len() { - if let ty::PredicateKind::Projection(ref poly_projection) = predicates[j].0.kind() { - // Note that we can skip binder here because the impl - // trait ref never contains any late-bound regions. - let projection = poly_projection.skip_binder(); - + // Note that we don't have to care about binders here, + // as the impl trait ref never contains any late-bound regions. + if let ty::PredicateAtom::Projection(projection) = predicates[j].0.skip_binders() { // Special case: watch out for some kind of sneaky attempt // to project out an associated type defined by this very // trait. diff --git a/src/librustc_typeck/impl_wf_check/min_specialization.rs b/src/librustc_typeck/impl_wf_check/min_specialization.rs index e4bffedd620b9..8257c6ce92547 100644 --- a/src/librustc_typeck/impl_wf_check/min_specialization.rs +++ b/src/librustc_typeck/impl_wf_check/min_specialization.rs @@ -198,9 +198,9 @@ fn unconstrained_parent_impl_substs<'tcx>( // the functions in `cgp` add the constrained parameters to a list of // unconstrained parameters. for (predicate, _) in impl_generic_predicates.predicates.iter() { - if let ty::PredicateKind::Projection(proj) = predicate.kind() { - let projection_ty = proj.skip_binder().projection_ty; - let projected_ty = proj.skip_binder().ty; + if let ty::PredicateAtom::Projection(proj) = predicate.skip_binders() { + let projection_ty = proj.projection_ty; + let projected_ty = proj.ty; let unbound_trait_ref = projection_ty.trait_ref(tcx); if Some(unbound_trait_ref) == impl_trait_ref { @@ -359,13 +359,13 @@ fn check_predicates<'tcx>( fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) { debug!("can_specialize_on(predicate = {:?})", predicate); - match predicate.kind() { + match predicate.skip_binders() { // Global predicates are either always true or always false, so we // are fine to specialize on. _ if predicate.is_global() => (), // We allow specializing on explicitly marked traits with no associated // items. - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { + ty::PredicateAtom::Trait(pred, hir::Constness::NotConst) => { if !matches!( trait_predicate_kind(tcx, predicate), Some(TraitSpecializationKind::Marker) @@ -392,19 +392,19 @@ fn trait_predicate_kind<'tcx>( tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, ) -> Option { - match predicate.kind() { - ty::PredicateKind::Trait(pred, hir::Constness::NotConst) => { + match predicate.skip_binders() { + ty::PredicateAtom::Trait(pred, hir::Constness::NotConst) => { Some(tcx.trait_def(pred.def_id()).specialization_kind) } - ty::PredicateKind::Trait(_, hir::Constness::Const) - | ty::PredicateKind::RegionOutlives(_) - | ty::PredicateKind::TypeOutlives(_) - | ty::PredicateKind::Projection(_) - | ty::PredicateKind::WellFormed(_) - | ty::PredicateKind::Subtype(_) - | ty::PredicateKind::ObjectSafe(_) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => None, + ty::PredicateAtom::Trait(_, hir::Constness::Const) + | ty::PredicateAtom::RegionOutlives(_) + | ty::PredicateAtom::TypeOutlives(_) + | ty::PredicateAtom::Projection(_) + | ty::PredicateAtom::WellFormed(_) + | ty::PredicateAtom::Subtype(_) + | ty::PredicateAtom::ObjectSafe(_) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => None, } } diff --git a/src/librustc_typeck/outlives/explicit.rs b/src/librustc_typeck/outlives/explicit.rs index 5740cc224cc57..135960a4c1114 100644 --- a/src/librustc_typeck/outlives/explicit.rs +++ b/src/librustc_typeck/outlives/explicit.rs @@ -29,9 +29,8 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { // process predicates and convert to `RequiredPredicates` entry, see below for &(predicate, span) in predicates.predicates { - match predicate.kind() { - ty::PredicateKind::TypeOutlives(predicate) => { - let OutlivesPredicate(ref ty, ref reg) = predicate.skip_binder(); + match predicate.skip_binders() { + ty::PredicateAtom::TypeOutlives(OutlivesPredicate(ref ty, ref reg)) => { insert_outlives_predicate( tcx, (*ty).into(), @@ -41,8 +40,7 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { ) } - ty::PredicateKind::RegionOutlives(predicate) => { - let OutlivesPredicate(ref reg1, ref reg2) = predicate.skip_binder(); + ty::PredicateAtom::RegionOutlives(OutlivesPredicate(ref reg1, ref reg2)) => { insert_outlives_predicate( tcx, (*reg1).into(), @@ -52,14 +50,14 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> { ) } - ty::PredicateKind::Trait(..) - | ty::PredicateKind::Projection(..) - | ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::Subtype(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => (), + ty::PredicateAtom::Trait(..) + | ty::PredicateAtom::Projection(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => (), } } diff --git a/src/librustc_typeck/outlives/mod.rs b/src/librustc_typeck/outlives/mod.rs index cc5858314597c..5dc7ac9fa0d4e 100644 --- a/src/librustc_typeck/outlives/mod.rs +++ b/src/librustc_typeck/outlives/mod.rs @@ -3,7 +3,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::GenericArgKind; -use rustc_middle::ty::{self, CratePredicatesMap, ToPredicate, TyCtxt}; +use rustc_middle::ty::{self, CratePredicatesMap, TyCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; @@ -31,8 +31,12 @@ fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate let mut pred: Vec = predicates .iter() .map(|(out_pred, _)| match out_pred.kind() { - ty::PredicateKind::RegionOutlives(p) => p.to_string(), - ty::PredicateKind::TypeOutlives(p) => p.to_string(), + ty::PredicateKind::Atom(ty::PredicateAtom::RegionOutlives(p)) => { + p.to_string() + } + ty::PredicateKind::Atom(ty::PredicateAtom::TypeOutlives(p)) => { + p.to_string() + } err => bug!("unexpected predicate {:?}", err), }) .collect(); @@ -85,17 +89,15 @@ fn inferred_outlives_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CratePredica |(ty::OutlivesPredicate(kind1, region2), &span)| { match kind1.unpack() { GenericArgKind::Type(ty1) => Some(( - ty::PredicateKind::TypeOutlives(ty::Binder::bind( - ty::OutlivesPredicate(ty1, region2), - )) - .to_predicate(tcx), + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty1, region2)) + .potentially_quantified(tcx, ty::PredicateKind::ForAll), span, )), GenericArgKind::Lifetime(region1) => Some(( - ty::PredicateKind::RegionOutlives(ty::Binder::bind( - ty::OutlivesPredicate(region1, region2), + ty::PredicateAtom::RegionOutlives(ty::OutlivesPredicate( + region1, region2, )) - .to_predicate(tcx), + .potentially_quantified(tcx, ty::PredicateKind::ForAll), span, )), GenericArgKind::Const(_) => { diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 3a798158c8bc6..98d8f100b27d9 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -315,12 +315,12 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { tcx: TyCtxt<'tcx>, pred: ty::Predicate<'tcx>, ) -> FxHashSet { - let regions = match pred.kind() { - ty::PredicateKind::Trait(poly_trait_pred, _) => { - tcx.collect_referenced_late_bound_regions(&poly_trait_pred) + let regions = match pred.skip_binders() { + ty::PredicateAtom::Trait(poly_trait_pred, _) => { + tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(poly_trait_pred)) } - ty::PredicateKind::Projection(poly_proj_pred) => { - tcx.collect_referenced_late_bound_regions(&poly_proj_pred) + ty::PredicateAtom::Projection(poly_proj_pred) => { + tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(poly_proj_pred)) } _ => return FxHashSet::default(), }; @@ -465,8 +465,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { .iter() .filter(|p| { !orig_bounds.contains(p) - || match p.kind() { - ty::PredicateKind::Trait(pred, _) => pred.def_id() == sized_trait, + || match p.skip_binders() { + ty::PredicateAtom::Trait(pred, _) => pred.def_id() == sized_trait, _ => false, } }) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 94d95115dcdbc..cc3a60c596ae7 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -480,18 +480,18 @@ impl Clean for hir::WherePredicate<'_> { impl<'a> Clean> for ty::Predicate<'a> { fn clean(&self, cx: &DocContext<'_>) -> Option { - match self.kind() { - ty::PredicateKind::Trait(ref pred, _) => Some(pred.clean(cx)), - ty::PredicateKind::Subtype(ref pred) => Some(pred.clean(cx)), - ty::PredicateKind::RegionOutlives(ref pred) => pred.clean(cx), - ty::PredicateKind::TypeOutlives(ref pred) => pred.clean(cx), - ty::PredicateKind::Projection(ref pred) => Some(pred.clean(cx)), + match self.skip_binders() { + ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)), + ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx), + ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx), + ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)), - ty::PredicateKind::WellFormed(..) - | ty::PredicateKind::ObjectSafe(..) - | ty::PredicateKind::ClosureKind(..) - | ty::PredicateKind::ConstEvaluatable(..) - | ty::PredicateKind::ConstEquate(..) => panic!("not user writable"), + ty::PredicateAtom::Subtype(..) + | ty::PredicateAtom::WellFormed(..) + | ty::PredicateAtom::ObjectSafe(..) + | ty::PredicateAtom::ClosureKind(..) + | ty::PredicateAtom::ConstEvaluatable(..) + | ty::PredicateAtom::ConstEquate(..) => panic!("not user writable"), } } } @@ -506,20 +506,11 @@ impl<'a> Clean for ty::PolyTraitPredicate<'a> { } } -impl<'tcx> Clean for ty::PolySubtypePredicate<'tcx> { - fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate { - panic!( - "subtype predicates are an internal rustc artifact \ - and should not be seen by rustdoc" - ) - } -} - impl<'tcx> Clean> - for ty::PolyOutlivesPredicate, ty::Region<'tcx>> + for ty::OutlivesPredicate, ty::Region<'tcx>> { fn clean(&self, cx: &DocContext<'_>) -> Option { - let ty::OutlivesPredicate(a, b) = self.skip_binder(); + let ty::OutlivesPredicate(a, b) = self; if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) { return None; @@ -532,9 +523,9 @@ impl<'tcx> Clean> } } -impl<'tcx> Clean> for ty::PolyOutlivesPredicate, ty::Region<'tcx>> { +impl<'tcx> Clean> for ty::OutlivesPredicate, ty::Region<'tcx>> { fn clean(&self, cx: &DocContext<'_>) -> Option { - let ty::OutlivesPredicate(ty, lt) = self.skip_binder(); + let ty::OutlivesPredicate(ty, lt) = self; if let ty::ReEmpty(_) = lt { return None; @@ -547,9 +538,9 @@ impl<'tcx> Clean> for ty::PolyOutlivesPredicate, } } -impl<'tcx> Clean for ty::PolyProjectionPredicate<'tcx> { +impl<'tcx> Clean for ty::ProjectionPredicate<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { - let ty::ProjectionPredicate { projection_ty, ty } = self.skip_binder(); + let ty::ProjectionPredicate { projection_ty, ty } = self; WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) } } } @@ -754,19 +745,24 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, ty::GenericPredicates<'tcx .flat_map(|(p, _)| { let mut projection = None; let param_idx = (|| { - if let Some(trait_ref) = p.to_opt_poly_trait_ref() { - if let ty::Param(param) = trait_ref.skip_binder().self_ty().kind { - return Some(param.index); + match p.skip_binders() { + ty::PredicateAtom::Trait(pred, _constness) => { + if let ty::Param(param) = pred.self_ty().kind { + return Some(param.index); + } } - } else if let Some(outlives) = p.to_opt_type_outlives() { - if let ty::Param(param) = outlives.skip_binder().0.kind { - return Some(param.index); + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { + if let ty::Param(param) = ty.kind { + return Some(param.index); + } } - } else if let ty::PredicateKind::Projection(p) = p.kind() { - if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind { - projection = Some(p); - return Some(param.index); + ty::PredicateAtom::Projection(p) => { + if let ty::Param(param) = p.projection_ty.self_ty().kind { + projection = Some(ty::Binder::bind(p)); + return Some(param.index); + } } + _ => (), } None @@ -1655,16 +1651,19 @@ impl<'tcx> Clean for Ty<'tcx> { .predicates .iter() .filter_map(|predicate| { - let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() { - tr - } else if let ty::PredicateKind::TypeOutlives(pred) = predicate.kind() { - // these should turn up at the end - if let Some(r) = pred.skip_binder().1.clean(cx) { - regions.push(GenericBound::Outlives(r)); + // Note: The substs of opaque types can contain unbound variables, + // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here. + let trait_ref = match predicate.bound_atom(cx.tcx).skip_binder() { + ty::PredicateAtom::Trait(tr, _constness) => { + ty::Binder::bind(tr.trait_ref) + } + ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => { + if let Some(r) = reg.clean(cx) { + regions.push(GenericBound::Outlives(r)); + } + return None; } - return None; - } else { - return None; + _ => return None, }; if let Some(sized) = cx.tcx.lang_items().sized_trait() { @@ -1678,8 +1677,9 @@ impl<'tcx> Clean for Ty<'tcx> { .predicates .iter() .filter_map(|pred| { - if let ty::PredicateKind::Projection(proj) = pred.kind() { - let proj = proj.skip_binder(); + if let ty::PredicateAtom::Projection(proj) = + pred.bound_atom(cx.tcx).skip_binder() + { if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() { diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 37c613f41224a..0f995a60c22fd 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -141,12 +141,8 @@ fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) .predicates .iter() .filter_map(|(pred, _)| { - if let ty::PredicateKind::Trait(ref pred, _) = pred.kind() { - if pred.skip_binder().trait_ref.self_ty() == self_ty { - Some(pred.def_id()) - } else { - None - } + if let ty::PredicateAtom::Trait(pred, _) = pred.skip_binders() { + if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None } } else { None } diff --git a/src/test/ui/issues/issue-26217.stderr b/src/test/ui/issues/issue-26217.stderr index be9da569f8be1..b1625536d4202 100644 --- a/src/test/ui/issues/issue-26217.stderr +++ b/src/test/ui/issues/issue-26217.stderr @@ -4,7 +4,7 @@ error[E0477]: the type `&'a i32` does not fulfill the required lifetime LL | foo::<&'a i32>(); | ^^^^^^^^^^^^^^ | - = note: type must satisfy the static lifetime + = note: type must outlive any other region error: aborting due to previous error diff --git a/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr b/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr index 7cc4357a704c0..1361117f6c4da 100644 --- a/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr +++ b/src/test/ui/specialization/min_specialization/repeated_projection_type.stderr @@ -1,4 +1,4 @@ -error: cannot specialize on `Binder(ProjectionPredicate(ProjectionTy { substs: [V], item_def_id: DefId(0:6 ~ repeated_projection_type[317d]::Id[0]::This[0]) }, (I,)))` +error: cannot specialize on `ProjectionPredicate(ProjectionTy { substs: [V], item_def_id: DefId(0:6 ~ repeated_projection_type[317d]::Id[0]::This[0]) }, (I,))` --> $DIR/repeated_projection_type.rs:19:1 | LL | / impl> X for V { diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index 92c7e66a0eb85..0fdb5b8c2a48e 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -3,7 +3,7 @@ use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, FnDecl, HirId}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::{Opaque, PredicateKind::Trait, ToPolyTraitRef}; +use rustc_middle::ty::{Opaque, PredicateAtom::Trait}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, Span}; use rustc_trait_selection::traits::error_reporting::suggestions::InferCtxtExt; @@ -91,12 +91,11 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { cx.tcx.infer_ctxt().enter(|infcx| { for FulfillmentError { obligation, .. } in send_errors { infcx.maybe_note_obligation_cause_for_async_await(db, &obligation); - if let Trait(trait_pred, _) = obligation.predicate.kind() { - let trait_ref = trait_pred.to_poly_trait_ref(); - db.note(&*format!( + if let Trait(trait_pred, _) = obligation.predicate.skip_binders() { + db.note(&format!( "`{}` doesn't implement `{}`", - trait_ref.skip_binder().self_ty(), - trait_ref.print_only_trait_path(), + trait_pred.self_ty(), + trait_pred.trait_ref.print_only_trait_path(), )); } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 97cc58023f55e..2c70183d87666 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1558,13 +1558,10 @@ impl<'tcx> LateLintPass<'tcx> for Methods { // if return type is impl trait, check the associated types if let ty::Opaque(def_id, _) = ret_ty.kind { // one of the associated types must be Self - for predicate in cx.tcx.predicates_of(def_id).predicates { - if let ty::PredicateKind::Projection(poly_projection_predicate) = predicate.0.kind() { - let binder = poly_projection_predicate.ty(); - let associated_type = binder.skip_binder(); - + for &(predicate, _span) in cx.tcx.predicates_of(def_id).predicates { + if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() { // walk the associated type and check for Self - if contains_self_ty(associated_type) { + if contains_self_ty(projection_predicate.ty) { return; } } diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 81774b617ac2e..0957787774498 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -114,12 +114,12 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter()) .filter(|p| !p.is_global()) .filter_map(|obligation| { - if let ty::PredicateKind::Trait(poly_trait_ref, _) = obligation.predicate.kind() { - if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars() - { + // Note that we do not want to deal with qualified predicates here. + if let ty::PredicateKind::Atom(ty::PredicateAtom::Trait(pred, _)) = obligation.predicate.kind() { + if pred.def_id() == sized_trait { return None; } - Some(poly_trait_ref) + Some(pred) } else { None } @@ -159,14 +159,13 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { } } - // // * Exclude a type that is specifically bounded by `Borrow`. // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`, // `serde::Serialize`) let (implements_borrow_trait, all_borrowable_trait) = { let preds = preds .iter() - .filter(|t| t.skip_binder().self_ty() == ty) + .filter(|t| t.self_ty() == ty) .collect::>(); ( @@ -174,8 +173,13 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { !preds.is_empty() && { let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty); preds.iter().all(|t| { - let ty_params = &t.skip_binder().trait_ref.substs.iter().skip(1).collect::>(); - implements_trait(cx, ty_empty_region, t.def_id(), ty_params) + let ty_params = t + .trait_ref + .substs + .iter() + .skip(1) + .collect::>(); + implements_trait(cx, ty_empty_region, t.def_id(), &ty_params) }) }, ) diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index ac6f3d125bb42..679aaec9fcd6c 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -4,7 +4,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; -use rustc_middle::ty::{GenericPredicates, PredicateKind, ProjectionPredicate, TraitPredicate}; +use rustc_middle::ty::{GenericPredicates, PredicateAtom, ProjectionPredicate, TraitPredicate}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{BytePos, Span}; @@ -42,8 +42,8 @@ fn get_trait_predicates_for_trait_id<'tcx>( let mut preds = Vec::new(); for (pred, _) in generics.predicates { if_chain! { - if let PredicateKind::Trait(poly_trait_pred, _) = pred.kind(); - let trait_pred = cx.tcx.erase_late_bound_regions(&poly_trait_pred); + if let PredicateAtom::Trait(poly_trait_pred, _) = pred.skip_binders(); + let trait_pred = cx.tcx.erase_late_bound_regions(&ty::Binder::bind(poly_trait_pred)); if let Some(trait_def_id) = trait_id; if trait_def_id == trait_pred.trait_ref.def_id; then { @@ -60,8 +60,8 @@ fn get_projection_pred<'tcx>( pred: TraitPredicate<'tcx>, ) -> Option> { generics.predicates.iter().find_map(|(proj_pred, _)| { - if let PredicateKind::Projection(proj_pred) = proj_pred.kind() { - let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred); + if let ty::PredicateAtom::Projection(proj_pred) = proj_pred.skip_binders() { + let projection_pred = cx.tcx.erase_late_bound_regions(&ty::Binder::bind(proj_pred)); if projection_pred.projection_ty.substs == pred.trait_ref.substs { return Some(projection_pred); } diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index a4bee1c278059..655b1133cf74f 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -1263,8 +1263,8 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(ref def_id, _) => { for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates { - if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = predicate.kind() { - if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() { + if let ty::PredicateAtom::Trait(trait_predicate, _) = predicate.skip_binders() { + if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() { return true; } }