use crate::infer::InferCtxt;
use crate::opaque_types::required_region_bounds;
use crate::traits;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::LangItem;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc_span::Span;
use std::iter;
use std::rc::Rc;
pub fn obligations<'a, 'tcx>(
infcx: &InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body_id: hir::HirId,
recursion_depth: usize,
arg: GenericArg<'tcx>,
span: Span,
) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
let arg = match arg.unpack() {
GenericArgKind::Type(ty) => {
match ty.kind() {
ty::Infer(ty::TyVar(_)) => {
let resolved_ty = infcx.shallow_resolve(ty);
if resolved_ty == ty {
return None;
}
resolved_ty
}
_ => ty,
}
.into()
}
GenericArgKind::Const(ct) => {
match ct.val {
ty::ConstKind::Infer(infer) => {
let resolved = infcx.shallow_resolve(infer);
if resolved == infer {
return None;
}
infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Infer(resolved), ty: ct.ty })
}
_ => ct,
}
.into()
}
GenericArgKind::Lifetime(..) => return Some(Vec::new()),
};
let mut wf =
WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth, item: None };
wf.compute(arg);
debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
let result = wf.normalize();
debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
Some(result)
}
pub fn trait_obligations<'a, 'tcx>(
infcx: &InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body_id: hir::HirId,
trait_ref: &ty::TraitRef<'tcx>,
span: Span,
item: Option<&'tcx hir::Item<'tcx>>,
) -> Vec<traits::PredicateObligation<'tcx>> {
let mut wf =
WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth: 0, item };
wf.compute_trait_ref(trait_ref, Elaborate::All);
wf.normalize()
}
pub fn predicate_obligations<'a, 'tcx>(
infcx: &InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body_id: hir::HirId,
predicate: ty::Predicate<'tcx>,
span: Span,
) -> Vec<traits::PredicateObligation<'tcx>> {
let mut wf = WfPredicates {
infcx,
param_env,
body_id,
span,
out: vec![],
recursion_depth: 0,
item: None,
};
match predicate.skip_binders() {
ty::PredicateAtom::Trait(t, _) => {
wf.compute_trait_ref(&t.trait_ref, Elaborate::None);
}
ty::PredicateAtom::RegionOutlives(..) => {}
ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
wf.compute(ty.into());
}
ty::PredicateAtom::Projection(t) => {
wf.compute_projection(t.projection_ty);
wf.compute(t.ty.into());
}
ty::PredicateAtom::WellFormed(arg) => {
wf.compute(arg);
}
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::PredicateAtom::ConstEvaluatable(def, substs) => {
let obligations = wf.nominal_obligations(def.did, substs);
wf.out.extend(obligations);
for arg in substs.iter() {
wf.compute(arg);
}
}
ty::PredicateAtom::ConstEquate(c1, c2) => {
wf.compute(c1.into());
wf.compute(c2.into());
}
ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
bug!("TypeWellFormedFromEnv is only used for Chalk")
}
}
wf.normalize()
}
struct WfPredicates<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body_id: hir::HirId,
span: Span,
out: Vec<traits::PredicateObligation<'tcx>>,
recursion_depth: usize,
item: Option<&'tcx hir::Item<'tcx>>,
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Elaborate {
All,
None,
}
fn extend_cause_with_original_assoc_item_obligation<'tcx>(
tcx: TyCtxt<'tcx>,
trait_ref: &ty::TraitRef<'tcx>,
item: Option<&hir::Item<'tcx>>,
cause: &mut traits::ObligationCause<'tcx>,
pred: &ty::Predicate<'tcx>,
mut trait_assoc_items: impl Iterator<Item = &'tcx ty::AssocItem>,
) {
debug!(
"extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
trait_ref, item, cause, pred
);
let items = match item {
Some(hir::Item { kind: hir::ItemKind::Impl { items, .. }, .. }) => items,
_ => return,
};
let fix_span =
|impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind {
hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
_ => impl_item_ref.span,
};
match pred.skip_binders() {
ty::PredicateAtom::Projection(proj) => {
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)
{
cause.make_mut().span = impl_item_span;
}
}
}
ty::PredicateAtom::Trait(pred, _) => {
debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
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)
.and_then(|trait_assoc_item| {
items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span)
})
{
cause.make_mut().span = impl_item_span;
}
}
}
_ => {}
}
}
impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
traits::ObligationCause::new(self.span, self.body_id, code)
}
fn normalize(mut self) -> Vec<traits::PredicateObligation<'tcx>> {
let cause = self.cause(traits::MiscObligation);
let infcx = &mut self.infcx;
let param_env = self.param_env;
let mut obligations = Vec::with_capacity(self.out.len());
for mut obligation in self.out {
assert!(!obligation.has_escaping_bound_vars());
let mut selcx = traits::SelectionContext::new(infcx);
let normalized_predicate = traits::project::normalize_with_depth_to(
&mut selcx,
param_env,
cause.clone(),
self.recursion_depth,
obligation.predicate,
&mut obligations,
);
obligation.predicate = normalized_predicate;
obligations.push(obligation);
}
obligations
}
fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
let tcx = self.infcx.tcx;
let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
debug!("compute_trait_ref obligations {:?}", obligations);
let cause = self.cause(traits::MiscObligation);
let param_env = self.param_env;
let depth = self.recursion_depth;
let item = self.item;
let extend = |obligation: traits::PredicateObligation<'tcx>| {
let mut cause = cause.clone();
if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
let derived_cause = traits::DerivedObligationCause {
parent_trait_ref,
parent_code: Rc::new(obligation.cause.code.clone()),
};
cause.make_mut().code =
traits::ObligationCauseCode::DerivedObligation(derived_cause);
}
extend_cause_with_original_assoc_item_obligation(
tcx,
trait_ref,
item,
&mut cause,
&obligation.predicate,
tcx.associated_items(trait_ref.def_id).in_definition_order(),
);
traits::Obligation::with_depth(cause, depth, param_env, obligation.predicate)
};
if let Elaborate::All = elaborate {
let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
let implied_obligations = implied_obligations.map(extend);
self.out.extend(implied_obligations);
} else {
self.out.extend(obligations);
}
let tcx = self.tcx();
self.out.extend(
trait_ref
.substs
.iter()
.enumerate()
.filter(|(_, arg)| {
matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
})
.filter(|(_, arg)| !arg.has_escaping_bound_vars())
.map(|(i, arg)| {
let mut new_cause = cause.clone();
if i == 0 {
if let Some(hir::ItemKind::Impl { self_ty, .. }) = item.map(|i| &i.kind) {
new_cause.make_mut().span = self_ty.span;
}
}
traits::Obligation::with_depth(
new_cause,
depth,
param_env,
ty::PredicateAtom::WellFormed(arg).to_predicate(tcx),
)
}),
);
}
fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
let obligations = self.nominal_obligations(data.item_def_id, data.substs);
self.out.extend(obligations);
let tcx = self.tcx();
let cause = self.cause(traits::MiscObligation);
let param_env = self.param_env;
let depth = self.recursion_depth;
self.out.extend(
data.substs
.iter()
.filter(|arg| {
matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
})
.filter(|arg| !arg.has_escaping_bound_vars())
.map(|arg| {
traits::Obligation::with_depth(
cause.clone(),
depth,
param_env,
ty::PredicateAtom::WellFormed(arg).to_predicate(tcx),
)
}),
);
}
fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
if !subty.has_escaping_bound_vars() {
let cause = self.cause(cause);
let trait_ref = ty::TraitRef {
def_id: self.infcx.tcx.require_lang_item(LangItem::Sized, None),
substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
};
self.out.push(traits::Obligation::with_depth(
cause,
self.recursion_depth,
self.param_env,
trait_ref.without_const().to_predicate(self.infcx.tcx),
));
}
}
fn compute(&mut self, arg: GenericArg<'tcx>) {
let mut walker = arg.walk();
let param_env = self.param_env;
let depth = self.recursion_depth;
while let Some(arg) = walker.next() {
let ty = match arg.unpack() {
GenericArgKind::Type(ty) => ty,
GenericArgKind::Lifetime(_) => continue,
GenericArgKind::Const(constant) => {
match constant.val {
ty::ConstKind::Unevaluated(def, substs, promoted) => {
assert!(promoted.is_none());
let obligations = self.nominal_obligations(def.did, substs);
self.out.extend(obligations);
let predicate = ty::PredicateAtom::ConstEvaluatable(def, substs)
.to_predicate(self.tcx());
let cause = self.cause(traits::MiscObligation);
self.out.push(traits::Obligation::with_depth(
cause,
self.recursion_depth,
self.param_env,
predicate,
));
}
ty::ConstKind::Infer(infer) => {
let resolved = self.infcx.shallow_resolve(infer);
if resolved != infer {
let cause = self.cause(traits::MiscObligation);
let resolved_constant = self.infcx.tcx.mk_const(ty::Const {
val: ty::ConstKind::Infer(resolved),
..*constant
});
self.out.push(traits::Obligation::with_depth(
cause,
self.recursion_depth,
self.param_env,
ty::PredicateAtom::WellFormed(resolved_constant.into())
.to_predicate(self.tcx()),
));
}
}
ty::ConstKind::Error(_)
| ty::ConstKind::Param(_)
| ty::ConstKind::Bound(..)
| ty::ConstKind::Placeholder(..) => {
}
ty::ConstKind::Value(..) => {
}
}
continue;
}
};
match *ty.kind() {
ty::Bool
| ty::Char
| ty::Int(..)
| ty::Uint(..)
| ty::Float(..)
| ty::Error(_)
| ty::Str
| ty::GeneratorWitness(..)
| ty::Never
| ty::Param(_)
| ty::Bound(..)
| ty::Placeholder(..)
| ty::Foreign(..) => {
}
ty::Infer(ty::IntVar(_)) => {}
ty::Infer(ty::FloatVar(_)) => {}
ty::Slice(subty) => {
self.require_sized(subty, traits::SliceOrArrayElem);
}
ty::Array(subty, _) => {
self.require_sized(subty, traits::SliceOrArrayElem);
}
ty::Tuple(ref tys) => {
if let Some((_last, rest)) = tys.split_last() {
for elem in rest {
self.require_sized(elem.expect_ty(), traits::TupleElem);
}
}
}
ty::RawPtr(_) => {
}
ty::Projection(data) => {
walker.skip_current_subtree();
self.compute_projection(data);
}
ty::Adt(def, substs) => {
let obligations = self.nominal_obligations(def.did, substs);
self.out.extend(obligations);
}
ty::FnDef(did, substs) => {
let obligations = self.nominal_obligations(did, substs);
self.out.extend(obligations);
}
ty::Ref(r, rty, _) => {
if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
self.out.push(traits::Obligation::with_depth(
cause,
depth,
param_env,
ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(rty, r))
.to_predicate(self.tcx()),
));
}
}
ty::Generator(..) => {
}
ty::Closure(_, substs) => {
walker.skip_current_subtree();
self.compute(substs.as_closure().tupled_upvars_ty().into());
}
ty::FnPtr(_) => {
}
ty::Opaque(did, substs) => {
if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
let obligations = self.nominal_obligations(did, substs);
self.out.extend(obligations);
}
}
ty::Dynamic(data, r) => {
self.from_object_ty(ty, data, r);
let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
if !defer_to_coercion {
let cause = self.cause(traits::MiscObligation);
let component_traits = data.auto_traits().chain(data.principal_def_id());
let tcx = self.tcx();
self.out.extend(component_traits.map(|did| {
traits::Obligation::with_depth(
cause.clone(),
depth,
param_env,
ty::PredicateAtom::ObjectSafe(did).to_predicate(tcx),
)
}));
}
}
ty::Infer(_) => {
let ty = self.infcx.shallow_resolve(ty);
if let ty::Infer(ty::TyVar(_)) = ty.kind() {
let cause = self.cause(traits::MiscObligation);
self.out.push(traits::Obligation::with_depth(
cause,
self.recursion_depth,
param_env,
ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx()),
));
} else {
self.compute(ty.into());
}
}
}
}
}
fn nominal_obligations(
&mut self,
def_id: DefId,
substs: SubstsRef<'tcx>,
) -> Vec<traits::PredicateObligation<'tcx>> {
let predicates = self.infcx.tcx.predicates_of(def_id);
let mut origins = vec![def_id; predicates.predicates.len()];
let mut head = predicates;
while let Some(parent) = head.parent {
head = self.infcx.tcx.predicates_of(parent);
origins.extend(iter::repeat(parent).take(head.predicates.len()));
}
let predicates = predicates.instantiate(self.infcx.tcx, substs);
debug_assert_eq!(predicates.predicates.len(), origins.len());
predicates
.predicates
.into_iter()
.zip(predicates.spans.into_iter())
.zip(origins.into_iter().rev())
.map(|((pred, span), origin_def_id)| {
let cause = self.cause(traits::BindingObligation(origin_def_id, span));
traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
})
.filter(|pred| !pred.has_escaping_bound_vars())
.collect()
}
fn from_object_ty(
&mut self,
ty: Ty<'tcx>,
data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
region: ty::Region<'tcx>,
) {
if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
let explicit_bound = region;
self.out.reserve(implicit_bounds.len());
for implicit_bound in implicit_bounds {
let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
let outlives =
ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
self.out.push(traits::Obligation::with_depth(
cause,
self.recursion_depth,
self.param_env,
outlives.to_predicate(self.infcx.tcx),
));
}
}
}
}
pub fn object_region_bounds<'tcx>(
tcx: TyCtxt<'tcx>,
existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
) -> Vec<ty::Region<'tcx>> {
let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
let predicates = existential_predicates.iter().filter_map(|predicate| {
if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
None
} else {
Some(predicate.with_self_ty(tcx, open_ty))
}
});
required_region_bounds(tcx, open_ty, predicates)
}