Auto merge of #125076 - compiler-errors:alias-term, r=lcnr

Split out `ty::AliasTerm` from `ty::AliasTy`

Splitting out `AliasTerm` (for use in project and normalizes goals) and `AliasTy` (for use in `ty::Alias`)

r? lcnr
This commit is contained in:
bors 2024-05-13 22:20:43 +00:00
commit 34582118af
73 changed files with 695 additions and 458 deletions

View file

@ -1010,7 +1010,8 @@ fn any_param_predicate_mentions(
clauses.iter().any(|pred| {
match pred.kind().skip_binder() {
ty::ClauseKind::Trait(data) if data.self_ty() == ty => {}
ty::ClauseKind::Projection(data) if data.projection_ty.self_ty() == ty => {}
ty::ClauseKind::Projection(data)
if data.projection_term.self_ty() == ty => {}
_ => return false,
}
tcx.any_free_region_meets(pred, |r| *r == ty::ReEarlyParam(region))

View file

@ -2206,7 +2206,7 @@ fn param_env_with_gat_bounds<'tcx>(
_ => predicates.push(
ty::Binder::bind_with_vars(
ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, trait_ty.def_id, rebased_args),
projection_term: ty::AliasTerm::new(tcx, trait_ty.def_id, rebased_args),
term: normalize_impl_ty.into(),
},
bound_vars,

View file

@ -344,9 +344,10 @@ fn bounds_from_generic_predicates<'tcx>(
let mut projections_str = vec![];
for projection in &projections {
let p = projection.skip_binder();
let alias_ty = p.projection_ty;
if bound == tcx.parent(alias_ty.def_id) && alias_ty.self_ty() == ty {
let name = tcx.item_name(alias_ty.def_id);
if bound == tcx.parent(p.projection_term.def_id)
&& p.projection_term.self_ty() == ty
{
let name = tcx.item_name(p.projection_term.def_id);
projections_str.push(format!("{} = {}", name, p.term));
}
}

View file

@ -40,7 +40,7 @@ fn associated_type_bounds<'tcx>(
let bounds_from_parent = trait_predicates.predicates.iter().copied().filter(|(pred, _)| {
match pred.kind().skip_binder() {
ty::ClauseKind::Trait(tr) => tr.self_ty() == item_ty,
ty::ClauseKind::Projection(proj) => proj.projection_ty.self_ty() == item_ty,
ty::ClauseKind::Projection(proj) => proj.projection_term.self_ty() == item_ty,
ty::ClauseKind::TypeOutlives(outlives) => outlives.0 == item_ty,
_ => false,
}

View file

@ -446,7 +446,9 @@ pub(super) fn explicit_predicates_of<'tcx>(
.copied()
.filter(|(pred, _)| match pred.kind().skip_binder() {
ty::ClauseKind::Trait(tr) => !is_assoc_item_ty(tr.self_ty()),
ty::ClauseKind::Projection(proj) => !is_assoc_item_ty(proj.projection_ty.self_ty()),
ty::ClauseKind::Projection(proj) => {
!is_assoc_item_ty(proj.projection_term.self_ty())
}
ty::ClauseKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
_ => true,
})

View file

@ -198,7 +198,7 @@ pub fn setup_constraining_predicates<'tcx>(
// Special case: watch out for some kind of sneaky attempt
// to project out an associated type defined by this very
// trait.
let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
let unbound_trait_ref = projection.projection_term.trait_ref(tcx);
if Some(unbound_trait_ref) == impl_trait_ref {
continue;
}
@ -208,7 +208,7 @@ pub fn setup_constraining_predicates<'tcx>(
// `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
// Then the projection only applies if `T` is known, but it still
// does not determine `U`.
let inputs = parameters_for(tcx, projection.projection_ty, true);
let inputs = parameters_for(tcx, projection.projection_term, true);
let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(p));
if !relies_only_on_inputs {
continue;

View file

@ -327,7 +327,7 @@ pub(super) fn lower_assoc_item_binding(
})
.or_insert(binding.span);
let projection_ty = if let ty::AssocKind::Fn = assoc_kind {
let projection_term = if let ty::AssocKind::Fn = assoc_kind {
let mut emitted_bad_param_err = None;
// If we have an method return type bound, then we need to instantiate
// the method's early bound params with suitable late-bound params.
@ -381,7 +381,7 @@ pub(super) fn lower_assoc_item_binding(
let output = if let ty::Alias(ty::Projection, alias_ty) = *output.skip_binder().kind()
&& tcx.is_impl_trait_in_trait(alias_ty.def_id)
{
alias_ty
alias_ty.into()
} else {
return Err(tcx.dcx().emit_err(crate::errors::ReturnTypeNotationOnNonRpitit {
span: binding.span,
@ -422,10 +422,7 @@ pub(super) fn lower_assoc_item_binding(
);
debug!(?alias_args);
// Note that we're indeed also using `AliasTy` (alias *type*) for associated
// *constants* to represent *const projections*. Alias *term* would be a more
// appropriate name but alas.
ty::AliasTy::new(tcx, assoc_item.def_id, alias_args)
ty::AliasTerm::new(tcx, assoc_item.def_id, alias_args)
});
// Provide the resolved type of the associated constant to `type_of(AnonConst)`.
@ -462,7 +459,7 @@ pub(super) fn lower_assoc_item_binding(
// for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
// for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
let late_bound_in_projection_ty =
tcx.collect_constrained_late_bound_regions(projection_ty);
tcx.collect_constrained_late_bound_regions(projection_term);
let late_bound_in_term =
tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
debug!(?late_bound_in_projection_ty);
@ -491,8 +488,10 @@ pub(super) fn lower_assoc_item_binding(
bounds.push_projection_bound(
tcx,
projection_ty
.map_bound(|projection_ty| ty::ProjectionPredicate { projection_ty, term }),
projection_term.map_bound(|projection_term| ty::ProjectionPredicate {
projection_term,
term,
}),
binding.span,
);
}
@ -502,6 +501,8 @@ pub(super) fn lower_assoc_item_binding(
// NOTE: If `only_self_bounds` is true, do NOT expand this associated type bound into
// a trait predicate, since we only want to add predicates for the `Self` type.
if !only_self_bounds.0 {
let projection_ty = projection_term
.map_bound(|projection_term| projection_term.expect_ty(self.tcx()));
// Calling `skip_binder` is okay, because `lower_bounds` expects the `param_ty`
// parameter to have a skipped binder.
let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder());

View file

@ -626,25 +626,17 @@ pub(crate) fn complain_about_inherent_assoc_ty_not_found(
let bound_predicate = pred.kind();
match bound_predicate.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
let pred = bound_predicate.rebind(pred);
// `<Foo as Iterator>::Item = String`.
let projection_ty = pred.skip_binder().projection_ty;
let projection_term = pred.projection_term;
let quiet_projection_term =
projection_term.with_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
let args_with_infer_self = tcx.mk_args_from_iter(
std::iter::once(Ty::new_var(tcx, ty::TyVid::ZERO).into())
.chain(projection_ty.args.iter().skip(1)),
);
let term = pred.term;
let obligation = format!("{projection_term} = {term}");
let quiet = format!("{quiet_projection_term} = {term}");
let quiet_projection_ty =
ty::AliasTy::new(tcx, projection_ty.def_id, args_with_infer_self);
let term = pred.skip_binder().term;
let obligation = format!("{projection_ty} = {term}");
let quiet = format!("{quiet_projection_ty} = {term}");
bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
Some((obligation, projection_ty.self_ty()))
bound_span_label(projection_term.self_ty(), &obligation, &quiet);
Some((obligation, projection_term.self_ty()))
}
ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
let p = poly_trait_ref.trait_ref;

View file

@ -281,11 +281,11 @@ pub(super) fn lower_trait_object_ty(
let existential_projections = projection_bounds.iter().map(|(bound, _)| {
bound.map_bound(|mut b| {
assert_eq!(b.projection_ty.self_ty(), dummy_self);
assert_eq!(b.projection_term.self_ty(), dummy_self);
// Like for trait refs, verify that `dummy_self` did not leak inside default type
// parameters.
let references_self = b.projection_ty.args.iter().skip(1).any(|arg| {
let references_self = b.projection_term.args.iter().skip(1).any(|arg| {
if arg.walk().any(|arg| arg == dummy_self.into()) {
return true;
}
@ -295,7 +295,7 @@ pub(super) fn lower_trait_object_ty(
let guar = tcx
.dcx()
.span_delayed_bug(span, "trait object projection bounds reference `Self`");
b.projection_ty = replace_dummy_self_with_error(tcx, b.projection_ty, guar);
b.projection_term = replace_dummy_self_with_error(tcx, b.projection_term, guar);
}
ty::ExistentialProjection::erase_self_ty(tcx, b)

View file

@ -258,23 +258,20 @@ fn unconstrained_parent_impl_args<'tcx>(
// unconstrained parameters.
for (clause, _) in impl_generic_predicates.predicates.iter() {
if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder() {
let projection_ty = proj.projection_ty;
let projected_ty = proj.term;
let unbound_trait_ref = projection_ty.trait_ref(tcx);
let unbound_trait_ref = proj.projection_term.trait_ref(tcx);
if Some(unbound_trait_ref) == impl_trait_ref {
continue;
}
unconstrained_parameters.extend(cgp::parameters_for(tcx, projection_ty, true));
unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.projection_term, true));
for param in cgp::parameters_for(tcx, projected_ty, false) {
for param in cgp::parameters_for(tcx, proj.term, false) {
if !unconstrained_parameters.contains(&param) {
constrained_params.insert(param.0);
}
}
unconstrained_parameters.extend(cgp::parameters_for(tcx, projected_ty, true));
unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.term, true));
}
}
@ -495,11 +492,11 @@ fn check_specialization_on<'tcx>(
.emit())
}
}
ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => Err(tcx
ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_term, term }) => Err(tcx
.dcx()
.struct_span_err(
span,
format!("cannot specialize on associated type `{projection_ty} == {term}`",),
format!("cannot specialize on associated type `{projection_term} == {term}`",),
)
.emit()),
ty::ClauseKind::ConstArgHasType(..) => {

View file

@ -167,7 +167,7 @@ fn visit_ty(&mut self, t: Ty<'tcx>) {
}
}
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_ty: ty::AliasTy { args, .. },
projection_term: ty::AliasTerm { args, .. },
term,
}) => {
for arg in &args[1..] {

View file

@ -575,7 +575,7 @@ fn confirm_builtin_call(
self.misc(span),
self.param_env,
ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(
projection_term: ty::AliasTerm::new(
self.tcx,
fn_once_output_def_id,
[arg_ty.into(), fn_sig.inputs()[0].into(), const_param],

View file

@ -415,7 +415,7 @@ fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
// many viable options, so pick the most restrictive.
let trait_def_id = match bound_predicate.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
Some(data.projection_ty.trait_def_id(self.tcx))
Some(data.projection_term.trait_def_id(self.tcx))
}
ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => Some(data.def_id()),
_ => None,
@ -476,7 +476,7 @@ fn deduce_sig_from_projection(
_ => return None,
}
let arg_param_ty = projection.skip_binder().projection_ty.args.type_at(1);
let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
debug!(?arg_param_ty);
@ -931,7 +931,7 @@ fn deduce_future_output_from_projection(
};
// Check that this is a projection from the `Future` trait.
let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
let trait_def_id = predicate.projection_term.trait_def_id(self.tcx);
let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
if trait_def_id != future_trait {
debug!("deduce_future_output_from_projection: not a future");
@ -941,11 +941,11 @@ fn deduce_future_output_from_projection(
// The `Future` trait has only one associated item, `Output`,
// so check that this is what we see.
let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
if output_assoc_item != predicate.projection_ty.def_id {
if output_assoc_item != predicate.projection_term.def_id {
span_bug!(
cause_span,
"projecting associated item `{:?}` from future, which is not Output `{:?}`",
predicate.projection_ty.def_id,
predicate.projection_term.def_id,
output_assoc_item,
);
}

View file

@ -37,7 +37,7 @@ pub fn adjust_fulfillment_error_for_expr_obligation(
ty::ClauseKind::Trait(pred) => {
(pred.trait_ref.args.to_vec(), Some(pred.self_ty().into()))
}
ty::ClauseKind::Projection(pred) => (pred.projection_ty.args.to_vec(), None),
ty::ClauseKind::Projection(pred) => (pred.projection_term.args.to_vec(), None),
ty::ClauseKind::ConstArgHasType(arg, ty) => (vec![ty.into(), arg.into()], None),
ty::ClauseKind::ConstEvaluatable(e) => (vec![e.into()], None),
_ => return false,

View file

@ -38,7 +38,7 @@ fn predicate_has_self_ty(
self.type_matches_expected_vid(expected_vid, data.self_ty())
}
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
self.type_matches_expected_vid(expected_vid, data.projection_ty.self_ty())
self.type_matches_expected_vid(expected_vid, data.projection_term.self_ty())
}
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
| ty::PredicateKind::Subtype(..)

View file

@ -47,7 +47,6 @@
use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
use super::{CandidateSource, MethodError, NoMatchData};
use rustc_hir::intravisit::Visitor;
use std::iter;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
@ -173,7 +172,7 @@ fn is_iterator_predicate(predicate: ty::Predicate<'_>, tcx: TyCtxt<'_>) -> bool
}
}
}
ty::Slice(..) | ty::Adt(..) | ty::Alias(ty::AliasKind::Opaque, _) => {
ty::Slice(..) | ty::Adt(..) | ty::Alias(ty::Opaque, _) => {
for unsatisfied in unsatisfied_predicates.iter() {
if is_iterator_predicate(unsatisfied.0, self.tcx) {
return true;
@ -788,26 +787,20 @@ pub fn report_no_match_method_error(
ty::PredicateKind::Clause(ty::ClauseKind::Projection(pred)) => {
let pred = bound_predicate.rebind(pred);
// `<Foo as Iterator>::Item = String`.
let projection_ty = pred.skip_binder().projection_ty;
let args_with_infer_self = tcx.mk_args_from_iter(
iter::once(Ty::new_var(tcx, ty::TyVid::ZERO).into())
.chain(projection_ty.args.iter().skip(1)),
);
let quiet_projection_ty =
ty::AliasTy::new(tcx, projection_ty.def_id, args_with_infer_self);
let projection_term = pred.skip_binder().projection_term;
let quiet_projection_term =
projection_term.with_self_ty(tcx, Ty::new_var(tcx, ty::TyVid::ZERO));
let term = pred.skip_binder().term;
let obligation = format!("{projection_ty} = {term}");
let obligation = format!("{projection_term} = {term}");
let quiet = with_forced_trimmed_paths!(format!(
"{} = {}",
quiet_projection_ty, term
quiet_projection_term, term
));
bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
Some((obligation, projection_ty.self_ty()))
bound_span_label(projection_term.self_ty(), &obligation, &quiet);
Some((obligation, projection_term.self_ty()))
}
ty::PredicateKind::Clause(ty::ClauseKind::Trait(poly_trait_ref)) => {
let p = poly_trait_ref.trait_ref;

View file

@ -431,6 +431,20 @@ fn to_trace(
}
impl<'tcx> ToTrace<'tcx> for ty::AliasTy<'tcx> {
fn to_trace(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,
a: Self,
b: Self,
) -> TypeTrace<'tcx> {
TypeTrace {
cause: cause.clone(),
values: Aliases(ExpectedFound::new(a_is_expected, a.into(), b.into())),
}
}
}
impl<'tcx> ToTrace<'tcx> for ty::AliasTerm<'tcx> {
fn to_trace(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,

View file

@ -411,7 +411,7 @@ pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
.kind()
.map_bound(|kind| match kind {
ty::ClauseKind::Projection(projection_predicate)
if projection_predicate.projection_ty.def_id == item_def_id =>
if projection_predicate.projection_term.def_id == item_def_id =>
{
projection_predicate.term.ty()
}

View file

@ -404,7 +404,7 @@ fn defining_opaque_types(&self) -> &'tcx ty::List<LocalDefId> {
pub enum ValuePairs<'tcx> {
Regions(ExpectedFound<ty::Region<'tcx>>),
Terms(ExpectedFound<ty::Term<'tcx>>),
Aliases(ExpectedFound<ty::AliasTy<'tcx>>),
Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),

View file

@ -588,7 +588,7 @@ pub fn add_item_bounds_for_hidden_type(
&& !tcx.is_impl_trait_in_trait(projection_ty.def_id)
&& !self.next_trait_solver() =>
{
self.infer_projection(
self.projection_ty_to_infer(
param_env,
projection_ty,
cause.clone(),

View file

@ -12,7 +12,7 @@ impl<'tcx> InferCtxt<'tcx> {
/// of the given projection. This allows us to proceed with projections
/// while they cannot be resolved yet due to missing information or
/// simply due to the lack of access to the trait resolution machinery.
pub fn infer_projection(
pub fn projection_ty_to_infer(
&self,
param_env: ty::ParamEnv<'tcx>,
projection_ty: ty::AliasTy<'tcx>,
@ -24,7 +24,7 @@ pub fn infer_projection(
let def_id = projection_ty.def_id;
let ty_var = self.next_ty_var(self.tcx.def_span(def_id));
let projection = ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::Projection(
ty::ProjectionPredicate { projection_ty, term: ty_var.into() },
ty::ProjectionPredicate { projection_term: projection_ty.into(), term: ty_var.into() },
)));
let obligation =
Obligation::with_depth(self.tcx, cause, recursion_depth, param_env, projection);

View file

@ -102,7 +102,7 @@ pub fn instantiate_ty_var<R: ObligationEmittingRelation<'tcx>>(
// instead create a new inference variable `?normalized_source`, emitting
// `Projection(normalized_source, ?ty_normalized)` and `?normalized_source <: generalized_ty`.
relation.register_predicates([ty::ProjectionPredicate {
projection_ty: data,
projection_term: data.into(),
term: generalized_ty.into(),
}]);
}

View file

@ -27,7 +27,7 @@
pub use self::project::MismatchedProjectionTypes;
pub(crate) use self::project::UndoLog;
pub use self::project::{
Normalized, NormalizedTy, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey,
Normalized, NormalizedTerm, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey,
ProjectionCacheStorage, Reveal,
};
pub use rustc_middle::traits::*;

View file

@ -8,7 +8,7 @@
snapshot_map::{self, SnapshotMapRef, SnapshotMapStorage},
undo_log::Rollback,
};
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty;
pub use rustc_middle::traits::{EvaluationResult, Reveal};
@ -26,7 +26,7 @@ pub struct Normalized<'tcx, T> {
pub obligations: Vec<PredicateObligation<'tcx>>,
}
pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
pub type NormalizedTerm<'tcx> = Normalized<'tcx, ty::Term<'tcx>>;
impl<'tcx, T> Normalized<'tcx, T> {
pub fn with<U>(self, value: U) -> Normalized<'tcx, U> {
@ -77,13 +77,13 @@ pub struct ProjectionCacheStorage<'tcx> {
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct ProjectionCacheKey<'tcx> {
ty: ty::AliasTy<'tcx>,
term: ty::AliasTerm<'tcx>,
param_env: ty::ParamEnv<'tcx>,
}
impl<'tcx> ProjectionCacheKey<'tcx> {
pub fn new(ty: ty::AliasTy<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
Self { ty, param_env }
pub fn new(term: ty::AliasTerm<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Self {
Self { term, param_env }
}
}
@ -93,8 +93,8 @@ pub enum ProjectionCacheEntry<'tcx> {
Ambiguous,
Recur,
Error,
NormalizedTy {
ty: Normalized<'tcx, ty::Term<'tcx>>,
NormalizedTerm {
ty: NormalizedTerm<'tcx>,
/// If we were able to successfully evaluate the
/// corresponding cache entry key during predicate
/// evaluation, then this field stores the final
@ -175,11 +175,7 @@ pub fn try_start(
}
/// Indicates that `key` was normalized to `value`.
pub fn insert_term(
&mut self,
key: ProjectionCacheKey<'tcx>,
value: Normalized<'tcx, ty::Term<'tcx>>,
) {
pub fn insert_term(&mut self, key: ProjectionCacheKey<'tcx>, value: NormalizedTerm<'tcx>) {
debug!(
"ProjectionCacheEntry::insert_ty: adding cache entry: key={:?}, value={:?}",
key, value
@ -190,7 +186,7 @@ pub fn insert_term(
return;
}
let fresh_key =
map.insert(key, ProjectionCacheEntry::NormalizedTy { ty: value, complete: None });
map.insert(key, ProjectionCacheEntry::NormalizedTerm { ty: value, complete: None });
assert!(!fresh_key, "never started projecting `{key:?}`");
}
@ -201,13 +197,16 @@ pub fn insert_term(
pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>, result: EvaluationResult) {
let mut map = self.map();
match map.get(&key) {
Some(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
Some(ProjectionCacheEntry::NormalizedTerm { ty, complete: _ }) => {
info!("ProjectionCacheEntry::complete({:?}) - completing {:?}", key, ty);
let mut ty = ty.clone();
if result.must_apply_considering_regions() {
ty.obligations = vec![];
}
map.insert(key, ProjectionCacheEntry::NormalizedTy { ty, complete: Some(result) });
map.insert(
key,
ProjectionCacheEntry::NormalizedTerm { ty, complete: Some(result) },
);
}
ref value => {
// Type inference could "strand behind" old cache entries. Leave
@ -219,7 +218,7 @@ pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>, result: EvaluationResu
pub fn is_complete(&mut self, key: ProjectionCacheKey<'tcx>) -> Option<EvaluationResult> {
self.map().get(&key).and_then(|res| match res {
ProjectionCacheEntry::NormalizedTy { ty: _, complete } => *complete,
ProjectionCacheEntry::NormalizedTerm { ty: _, complete } => *complete,
_ => None,
})
}

View file

@ -107,8 +107,11 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
return;
}
let proj_ty =
Ty::new_projection(cx.tcx, proj.projection_ty.def_id, proj.projection_ty.args);
let proj_ty = Ty::new_projection(
cx.tcx,
proj.projection_term.def_id,
proj.projection_term.args,
);
// For every instance of the projection type in the bounds,
// replace them with the term we're assigning to the associated
// type in our opaque type.
@ -123,8 +126,8 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
// with `impl Send: OtherTrait`.
for (assoc_pred, assoc_pred_span) in cx
.tcx
.explicit_item_bounds(proj.projection_ty.def_id)
.iter_instantiated_copied(cx.tcx, proj.projection_ty.args)
.explicit_item_bounds(proj.projection_term.def_id)
.iter_instantiated_copied(cx.tcx, proj.projection_term.args)
{
let assoc_pred = assoc_pred.fold_with(proj_replacer);
let Ok(assoc_pred) = traits::fully_normalize(

View file

@ -132,6 +132,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
type RegionOutlivesPredicate = ty::RegionOutlivesPredicate<'tcx>;
type TypeOutlivesPredicate = ty::TypeOutlivesPredicate<'tcx>;
type ProjectionPredicate = ty::ProjectionPredicate<'tcx>;
type AliasTerm = ty::AliasTerm<'tcx>;
type NormalizesTo = ty::NormalizesTo<'tcx>;
type SubtypePredicate = ty::SubtypePredicate<'tcx>;
type CoercePredicate = ty::CoercePredicate<'tcx>;

View file

@ -294,10 +294,10 @@ fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) {
self.add_ty(b);
}
ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_ty,
projection_term,
term,
})) => {
self.add_alias_ty(projection_ty);
self.add_alias_term(projection_term);
self.add_term(term);
}
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
@ -313,7 +313,7 @@ fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) {
}
ty::PredicateKind::Ambiguous => {}
ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term }) => {
self.add_alias_ty(alias);
self.add_alias_term(alias);
self.add_term(term);
}
ty::PredicateKind::AliasRelate(t1, t2, _) => {
@ -410,6 +410,10 @@ fn add_alias_ty(&mut self, alias_ty: ty::AliasTy<'_>) {
self.add_args(alias_ty.args);
}
fn add_alias_term(&mut self, alias_term: ty::AliasTerm<'_>) {
self.add_args(alias_term.args);
}
fn add_args(&mut self, args: &[GenericArg<'_>]) {
for kind in args {
match kind.unpack() {

View file

@ -110,11 +110,11 @@
};
pub use self::rvalue_scopes::RvalueScopes;
pub use self::sty::{
AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
ClosureArgs, ClosureArgsParts, CoroutineArgs, CoroutineArgsParts, CoroutineClosureArgs,
CoroutineClosureArgsParts, CoroutineClosureSignature, FnSig, GenSig, InlineConstArgs,
InlineConstArgsParts, ParamConst, ParamTy, PolyFnSig, TyKind, TypeAndMut, UpvarArgs,
VarianceDiagInfo,
AliasTerm, AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind,
CanonicalPolyFnSig, ClosureArgs, ClosureArgsParts, CoroutineArgs, CoroutineArgsParts,
CoroutineClosureArgs, CoroutineClosureArgsParts, CoroutineClosureSignature, FnSig, GenSig,
InlineConstArgs, InlineConstArgsParts, ParamConst, ParamTy, PolyFnSig, TyKind, TypeAndMut,
UpvarArgs, VarianceDiagInfo,
};
pub use self::trait_def::TraitDef;
pub use self::typeck_results::{
@ -629,15 +629,14 @@ pub fn into_arg(self) -> GenericArg<'tcx> {
}
}
/// This function returns the inner `AliasTy` for a `ty::Alias` or `ConstKind::Unevaluated`.
pub fn to_alias_ty(&self, tcx: TyCtxt<'tcx>) -> Option<AliasTy<'tcx>> {
pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
match self.unpack() {
TermKind::Ty(ty) => match *ty.kind() {
ty::Alias(_kind, alias_ty) => Some(alias_ty),
ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
_ => None,
},
TermKind::Const(ct) => match ct.kind() {
ConstKind::Unevaluated(uv) => Some(AliasTy::new(tcx, uv.def, uv.args)),
ConstKind::Unevaluated(uv) => Some(uv.into()),
_ => None,
},
}

View file

@ -503,7 +503,7 @@ impl<'tcx> PolyProjectionPredicate<'tcx> {
/// Returns the `DefId` of the trait of the associated item being projected.
#[inline]
pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
self.skip_binder().projection_ty.trait_def_id(tcx)
self.skip_binder().projection_term.trait_def_id(tcx)
}
/// Get the [PolyTraitRef] required for this projection to be well formed.
@ -516,7 +516,7 @@ pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> {
// This is because here `self` has a `Binder` and so does our
// return value, so we are preserving the number of binding
// levels.
self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx))
self.map_bound(|predicate| predicate.projection_term.trait_ref(tcx))
}
pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
@ -529,7 +529,7 @@ pub fn term(&self) -> Binder<'tcx, Term<'tcx>> {
/// associated type, which is in `tcx.associated_item(projection_def_id()).container`.
pub fn projection_def_id(&self) -> DefId {
// Ok to skip binder since trait `DefId` does not care about regions.
self.skip_binder().projection_ty.def_id
self.skip_binder().projection_term.def_id
}
}

View file

@ -1277,7 +1277,7 @@ fn insert_trait_and_projection(
fn pretty_print_inherent_projection(
&mut self,
alias_ty: ty::AliasTy<'tcx>,
alias_ty: ty::AliasTerm<'tcx>,
) -> Result<(), PrintError> {
let def_key = self.tcx().def_key(alias_ty.def_id);
self.path_generic_args(
@ -3111,7 +3111,7 @@ macro_rules! define_print_and_forward_display {
}
ty::ProjectionPredicate<'tcx> {
p!(print(self.projection_ty), " == ");
p!(print(self.projection_term), " == ");
cx.reset_type_limit();
p!(print(self.term))
}
@ -3206,20 +3206,29 @@ macro_rules! define_print_and_forward_display {
}
ty::AliasTy<'tcx> {
if let DefKind::Impl { of_trait: false } = cx.tcx().def_kind(cx.tcx().parent(self.def_id)) {
p!(pretty_print_inherent_projection(*self))
} else {
// If we're printing verbosely, or don't want to invoke queries
// (`is_impl_trait_in_trait`), then fall back to printing the def path.
// This is likely what you want if you're debugging the compiler anyways.
if !(cx.should_print_verbose() || with_reduced_queries())
&& cx.tcx().is_impl_trait_in_trait(self.def_id)
{
return cx.pretty_print_opaque_impl_type(self.def_id, self.args);
} else {
p!(print_def_path(self.def_id, self.args));
}
let alias_term: ty::AliasTerm<'tcx> = (*self).into();
p!(print(alias_term))
}
ty::AliasTerm<'tcx> {
match self.kind(cx.tcx()) {
ty::AliasTermKind::InherentTy => p!(pretty_print_inherent_projection(*self)),
ty::AliasTermKind::ProjectionTy
| ty::AliasTermKind::WeakTy
| ty::AliasTermKind::OpaqueTy
| ty::AliasTermKind::UnevaluatedConst
| ty::AliasTermKind::ProjectionConst => {
// If we're printing verbosely, or don't want to invoke queries
// (`is_impl_trait_in_trait`), then fall back to printing the def path.
// This is likely what you want if you're debugging the compiler anyways.
if !(cx.should_print_verbose() || with_reduced_queries())
&& cx.tcx().is_impl_trait_in_trait(self.def_id)
{
return cx.pretty_print_opaque_impl_type(self.def_id, self.args);
} else {
p!(print_def_path(self.def_id, self.args));
}
}
}
}

View file

@ -10,7 +10,6 @@
GenericArgKind, GenericArgsRef, ImplSubject, Term, TermKind, Ty, TyCtxt, TypeFoldable,
};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_macros::TypeVisitable;
use rustc_target::spec::abi;
@ -227,8 +226,8 @@ fn relate<R: TypeRelation<'tcx>>(
if a.def_id != b.def_id {
Err(TypeError::ProjectionMismatched(expected_found(a.def_id, b.def_id)))
} else {
let args = match relation.tcx().def_kind(a.def_id) {
DefKind::OpaqueTy => relate_args_with_variances(
let args = match a.kind(relation.tcx()) {
ty::Opaque => relate_args_with_variances(
relation,
a.def_id,
relation.tcx().variances_of(a.def_id),
@ -236,16 +235,46 @@ fn relate<R: TypeRelation<'tcx>>(
b.args,
false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
)?,
DefKind::AssocTy | DefKind::AssocConst | DefKind::TyAlias => {
ty::Projection | ty::Weak | ty::Inherent => {
relate_args_invariantly(relation, a.args, b.args)?
}
def => bug!("unknown alias DefKind: {def:?}"),
};
Ok(ty::AliasTy::new(relation.tcx(), a.def_id, args))
}
}
}
impl<'tcx> Relate<'tcx> for ty::AliasTerm<'tcx> {
fn relate<R: TypeRelation<'tcx>>(
relation: &mut R,
a: ty::AliasTerm<'tcx>,
b: ty::AliasTerm<'tcx>,
) -> RelateResult<'tcx, ty::AliasTerm<'tcx>> {
if a.def_id != b.def_id {
Err(TypeError::ProjectionMismatched(expected_found(a.def_id, b.def_id)))
} else {
let args = match a.kind(relation.tcx()) {
ty::AliasTermKind::OpaqueTy => relate_args_with_variances(
relation,
a.def_id,
relation.tcx().variances_of(a.def_id),
a.args,
b.args,
false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
)?,
ty::AliasTermKind::ProjectionTy
| ty::AliasTermKind::WeakTy
| ty::AliasTermKind::InherentTy
| ty::AliasTermKind::UnevaluatedConst
| ty::AliasTermKind::ProjectionConst => {
relate_args_invariantly(relation, a.args, b.args)?
}
};
Ok(ty::AliasTerm::new(relation.tcx(), a.def_id, args))
}
}
}
impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
fn relate<R: TypeRelation<'tcx>>(
relation: &mut R,

View file

@ -410,7 +410,7 @@ fn fmt<Infcx: InferCtxtLike<Interner = TyCtxt<'tcx>>>(
crate::ty::BoundRegionKind,
crate::ty::AssocItem,
crate::ty::AssocKind,
crate::ty::AliasKind,
crate::ty::AliasTyKind,
crate::ty::Placeholder<crate::ty::BoundRegion>,
crate::ty::Placeholder<crate::ty::BoundTy>,
crate::ty::Placeholder<ty::BoundVar>,

View file

@ -1105,14 +1105,14 @@ fn into_diag_arg(self) -> DiagArgValue {
}
}
/// Represents the projection of an associated type.
/// Represents the unprojected term of a projection goal.
///
/// * For a projection, this would be `<Ty as Trait<...>>::N<...>`.
/// * For an inherent projection, this would be `Ty::N<...>`.
/// * For an opaque type, there is no explicit syntax.
#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
pub struct AliasTy<'tcx> {
pub struct AliasTerm<'tcx> {
/// The parameters of the associated or opaque item.
///
/// For a projection, these are the generic parameters for the trait and the
@ -1137,18 +1137,37 @@ pub struct AliasTy<'tcx> {
/// aka. `tcx.parent(def_id)`.
pub def_id: DefId,
/// This field exists to prevent the creation of `AliasTy` without using
/// [AliasTy::new].
_use_alias_ty_new_instead: (),
/// This field exists to prevent the creation of `AliasTerm` without using
/// [AliasTerm::new].
_use_alias_term_new_instead: (),
}
impl<'tcx> rustc_type_ir::inherent::AliasTy<TyCtxt<'tcx>> for AliasTy<'tcx> {
// FIXME: Remove these when we uplift `AliasTerm`
use crate::ty::{DebugWithInfcx, InferCtxtLike, WithInfcx};
impl<'tcx> std::fmt::Debug for AliasTerm<'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
WithInfcx::with_no_infcx(self).fmt(f)
}
}
impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for AliasTerm<'tcx> {
fn fmt<Infcx: InferCtxtLike<Interner = TyCtxt<'tcx>>>(
this: WithInfcx<'_, Infcx, &Self>,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
f.debug_struct("AliasTerm")
.field("args", &this.map(|data| data.args))
.field("def_id", &this.data.def_id)
.finish()
}
}
impl<'tcx> rustc_type_ir::inherent::AliasTerm<TyCtxt<'tcx>> for AliasTerm<'tcx> {
fn new(
interner: TyCtxt<'tcx>,
trait_def_id: DefId,
args: impl IntoIterator<Item: Into<ty::GenericArg<'tcx>>>,
) -> Self {
AliasTy::new(interner, trait_def_id, args)
AliasTerm::new(interner, trait_def_id, args)
}
fn def_id(self) -> DefId {
@ -1172,6 +1191,182 @@ fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
}
}
impl<'tcx> AliasTerm<'tcx> {
pub fn new(
tcx: TyCtxt<'tcx>,
def_id: DefId,
args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
) -> AliasTerm<'tcx> {
let args = tcx.check_and_mk_args(def_id, args);
AliasTerm { def_id, args, _use_alias_term_new_instead: () }
}
pub fn expect_ty(self, tcx: TyCtxt<'tcx>) -> AliasTy<'tcx> {
match self.kind(tcx) {
ty::AliasTermKind::ProjectionTy
| ty::AliasTermKind::InherentTy
| ty::AliasTermKind::OpaqueTy
| ty::AliasTermKind::WeakTy => {}
ty::AliasTermKind::UnevaluatedConst | ty::AliasTermKind::ProjectionConst => {
bug!("Cannot turn `UnevaluatedConst` into `AliasTy`")
}
}
ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }
}
pub fn kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasTermKind {
match tcx.def_kind(self.def_id) {
DefKind::AssocTy => {
if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(self.def_id)) {
ty::AliasTermKind::InherentTy
} else {
ty::AliasTermKind::ProjectionTy
}
}
DefKind::OpaqueTy => ty::AliasTermKind::OpaqueTy,
DefKind::TyAlias => ty::AliasTermKind::WeakTy,
DefKind::AnonConst => ty::AliasTermKind::UnevaluatedConst,
DefKind::AssocConst => ty::AliasTermKind::ProjectionConst,
kind => bug!("unexpected DefKind in AliasTy: {kind:?}"),
}
}
}
/// The following methods work only with (trait) associated item projections.
impl<'tcx> AliasTerm<'tcx> {
pub fn self_ty(self) -> Ty<'tcx> {
self.args.type_at(0)
}
pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
AliasTerm::new(
tcx,
self.def_id,
[self_ty.into()].into_iter().chain(self.args.iter().skip(1)),
)
}
pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
match tcx.def_kind(self.def_id) {
DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.def_id),
kind => bug!("expected a projection AliasTy; found {kind:?}"),
}
}
/// Extracts the underlying trait reference from this projection.
/// For example, if this is a projection of `<T as Iterator>::Item`,
/// then this function would return a `T: Iterator` trait reference.
///
/// NOTE: This will drop the args for generic associated types
/// consider calling [Self::trait_ref_and_own_args] to get those
/// as well.
pub fn trait_ref(self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
let def_id = self.trait_def_id(tcx);
ty::TraitRef::new(tcx, def_id, self.args.truncate_to(tcx, tcx.generics_of(def_id)))
}
/// Extracts the underlying trait reference and own args from this projection.
/// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
/// then this function would return a `T: StreamingIterator` trait reference and `['a]` as the own args
pub fn trait_ref_and_own_args(
self,
tcx: TyCtxt<'tcx>,
) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
let trait_def_id = self.trait_def_id(tcx);
let trait_generics = tcx.generics_of(trait_def_id);
(
ty::TraitRef::new(tcx, trait_def_id, self.args.truncate_to(tcx, trait_generics)),
&self.args[trait_generics.count()..],
)
}
pub fn to_term(self, tcx: TyCtxt<'tcx>) -> ty::Term<'tcx> {
match self.kind(tcx) {
ty::AliasTermKind::ProjectionTy => Ty::new_alias(
tcx,
ty::Projection,
AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () },
)
.into(),
ty::AliasTermKind::InherentTy => Ty::new_alias(
tcx,
ty::Inherent,
AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () },
)
.into(),
ty::AliasTermKind::OpaqueTy => Ty::new_alias(
tcx,
ty::Opaque,
AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () },
)
.into(),
ty::AliasTermKind::WeakTy => Ty::new_alias(
tcx,
ty::Weak,
AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () },
)
.into(),
ty::AliasTermKind::UnevaluatedConst | ty::AliasTermKind::ProjectionConst => {
ty::Const::new_unevaluated(
tcx,
ty::UnevaluatedConst::new(self.def_id, self.args),
tcx.type_of(self.def_id).instantiate(tcx, self.args),
)
.into()
}
}
}
}
impl<'tcx> From<AliasTy<'tcx>> for AliasTerm<'tcx> {
fn from(ty: AliasTy<'tcx>) -> Self {
AliasTerm { args: ty.args, def_id: ty.def_id, _use_alias_term_new_instead: () }
}
}
impl<'tcx> From<ty::UnevaluatedConst<'tcx>> for AliasTerm<'tcx> {
fn from(ct: ty::UnevaluatedConst<'tcx>) -> Self {
AliasTerm { args: ct.args, def_id: ct.def, _use_alias_term_new_instead: () }
}
}
/// Represents the projection of an associated, opaque, or lazy-type-alias type.
///
/// * For a projection, this would be `<Ty as Trait<...>>::N<...>`.
/// * For an inherent projection, this would be `Ty::N<...>`.
/// * For an opaque type, there is no explicit syntax.
#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
#[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
pub struct AliasTy<'tcx> {
/// The parameters of the associated or opaque type.
///
/// For a projection, these are the generic parameters for the trait and the
/// GAT parameters, if there are any.
///
/// For an inherent projection, they consist of the self type and the GAT parameters,
/// if there are any.
///
/// For RPIT the generic parameters are for the generics of the function,
/// while for TAIT it is used for the generic parameters of the alias.
pub args: GenericArgsRef<'tcx>,
/// The `DefId` of the `TraitItem` or `ImplItem` for the associated type `N` depending on whether
/// this is a projection or an inherent projection or the `DefId` of the `OpaqueType` item if
/// this is an opaque.
///
/// During codegen, `tcx.type_of(def_id)` can be used to get the type of the
/// underlying type if the type is an opaque.
///
/// Note that if this is an associated type, this is not the `DefId` of the
/// `TraitRef` containing this associated type, which is in `tcx.associated_item(def_id).container`,
/// aka. `tcx.parent(def_id)`.
pub def_id: DefId,
/// This field exists to prevent the creation of `AliasT` without using
/// [AliasTy::new].
_use_alias_ty_new_instead: (),
}
impl<'tcx> AliasTy<'tcx> {
pub fn new(
tcx: TyCtxt<'tcx>,
@ -1182,7 +1377,7 @@ pub fn new(
ty::AliasTy { def_id, args, _use_alias_ty_new_instead: () }
}
pub fn kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasKind {
pub fn kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasTyKind {
match tcx.def_kind(self.def_id) {
DefKind::AssocTy
if let DefKind::Impl { of_trait: false } =
@ -1199,24 +1394,7 @@ pub fn kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasKind {
/// Whether this alias type is an opaque.
pub fn is_opaque(self, tcx: TyCtxt<'tcx>) -> bool {
matches!(self.opt_kind(tcx), Some(ty::Opaque))
}
/// FIXME: rename `AliasTy` to `AliasTerm` and always handle
/// constants. This function can then be removed.
pub fn opt_kind(self, tcx: TyCtxt<'tcx>) -> Option<ty::AliasKind> {
match tcx.def_kind(self.def_id) {
DefKind::AssocTy
if let DefKind::Impl { of_trait: false } =
tcx.def_kind(tcx.parent(self.def_id)) =>
{
Some(ty::Inherent)
}
DefKind::AssocTy => Some(ty::Projection),
DefKind::OpaqueTy => Some(ty::Opaque),
DefKind::TyAlias => Some(ty::Weak),
_ => None,
}
matches!(self.kind(tcx), ty::Opaque)
}
pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
@ -1224,7 +1402,7 @@ pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
}
}
/// The following methods work only with associated type projections.
/// The following methods work only with (trait) associated type projections.
impl<'tcx> AliasTy<'tcx> {
pub fn self_ty(self) -> Ty<'tcx> {
self.args.type_at(0)
@ -1233,10 +1411,7 @@ pub fn self_ty(self) -> Ty<'tcx> {
pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
AliasTy::new(tcx, self.def_id, [self_ty.into()].into_iter().chain(self.args.iter().skip(1)))
}
}
/// The following methods work only with trait associated type projections.
impl<'tcx> AliasTy<'tcx> {
pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
match tcx.def_kind(self.def_id) {
DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.def_id),
@ -1251,7 +1426,6 @@ pub fn trait_ref_and_own_args(
self,
tcx: TyCtxt<'tcx>,
) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
debug_assert!(matches!(tcx.def_kind(self.def_id), DefKind::AssocTy | DefKind::AssocConst));
let trait_def_id = self.trait_def_id(tcx);
let trait_generics = tcx.generics_of(trait_def_id);
(
@ -1541,7 +1715,7 @@ pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> T
#[inline]
pub fn new_alias(
tcx: TyCtxt<'tcx>,
kind: ty::AliasKind,
kind: ty::AliasTyKind,
alias_ty: ty::AliasTy<'tcx>,
) -> Ty<'tcx> {
debug_assert_matches!(

View file

@ -1086,7 +1086,7 @@ fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
{
p.kind()
.rebind(ty::ProjectionPredicate {
projection_ty: projection_pred.projection_ty.fold_with(self),
projection_term: projection_pred.projection_term.fold_with(self),
// Don't fold the term on the RHS of the projection predicate.
// This is because for default trait methods with RPITITs, we
// install a `NormalizesTo(Projection(RPITIT) -> Opaque(RPITIT))`

View file

@ -535,8 +535,7 @@ fn apply_combinator(
}
// If projection of Discriminant then compare with `Ty::discriminant_ty`
if let ty::Alias(ty::AliasKind::Projection, ty::AliasTy { args, def_id, .. }) =
expected_ty.kind()
if let ty::Alias(ty::Projection, ty::AliasTy { args, def_id, .. }) = expected_ty.kind()
&& Some(*def_id) == self.tcx.lang_items().discriminant_type()
&& args.first().unwrap().as_type().unwrap().discriminant_ty(self.tcx) == operand_ty
{

View file

@ -117,7 +117,7 @@ fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
}
fn visit_projection_ty(&mut self, projection: ty::AliasTy<'tcx>) -> V::Result {
fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
let tcx = self.def_id_visitor.tcx();
let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
try_visit!(self.visit_trait(trait_ref));
@ -135,9 +135,12 @@ fn visit_clause(&mut self, clause: ty::Clause<'tcx>) -> V::Result {
ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
self.visit_trait(trait_ref)
}
ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term: projection_ty,
term,
}) => {
try_visit!(term.visit_with(self));
self.visit_projection_ty(projection_ty)
self.visit_projection_term(projection_ty)
}
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => ty.visit_with(self),
ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
@ -226,7 +229,7 @@ fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
return if V::SHALLOW {
V::Result::output()
} else if kind == ty::Projection {
self.visit_projection_ty(data)
self.visit_projection_term(data.into())
} else {
V::Result::from_branch(
data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),

View file

@ -9,7 +9,7 @@
use crate::rustc_smir::{alloc, Stable, Tables};
impl<'tcx> Stable<'tcx> for ty::AliasKind {
impl<'tcx> Stable<'tcx> for ty::AliasTyKind {
type T = stable_mir::ty::AliasKind;
fn stable(&self, _: &mut Tables<'_>) -> Self::T {
match self {
@ -29,6 +29,14 @@ fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
}
}
impl<'tcx> Stable<'tcx> for ty::AliasTerm<'tcx> {
type T = stable_mir::ty::AliasTerm;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
let ty::AliasTerm { args, def_id, .. } = self;
stable_mir::ty::AliasTerm { def_id: tables.alias_def(*def_id), args: args.stable(tables) }
}
}
impl<'tcx> Stable<'tcx> for ty::DynKind {
type T = stable_mir::ty::DynKind;
@ -715,9 +723,9 @@ impl<'tcx> Stable<'tcx> for ty::ProjectionPredicate<'tcx> {
type T = stable_mir::ty::ProjectionPredicate;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
let ty::ProjectionPredicate { projection_ty, term } = self;
let ty::ProjectionPredicate { projection_term, term } = self;
stable_mir::ty::ProjectionPredicate {
projection_ty: projection_ty.stable(tables),
projection_term: projection_term.stable(tables),
term: term.unpack().stable(tables),
}
}

View file

@ -29,7 +29,7 @@ pub(super) fn compute_alias_relate_goal(
let Goal { param_env, predicate: (lhs, rhs, direction) } = goal;
// Structurally normalize the lhs.
let lhs = if let Some(alias) = lhs.to_alias_ty(self.tcx()) {
let lhs = if let Some(alias) = lhs.to_alias_term() {
let term = self.next_term_infer_of_kind(lhs);
self.add_normalizes_to_goal(goal.with(tcx, ty::NormalizesTo { alias, term }));
term
@ -38,7 +38,7 @@ pub(super) fn compute_alias_relate_goal(
};
// Structurally normalize the rhs.
let rhs = if let Some(alias) = rhs.to_alias_ty(self.tcx()) {
let rhs = if let Some(alias) = rhs.to_alias_term() {
let term = self.next_term_infer_of_kind(rhs);
self.add_normalizes_to_goal(goal.with(tcx, ty::NormalizesTo { alias, term }));
term
@ -56,7 +56,7 @@ pub(super) fn compute_alias_relate_goal(
ty::AliasRelationDirection::Equate => ty::Variance::Invariant,
ty::AliasRelationDirection::Subtype => ty::Variance::Covariant,
};
match (lhs.to_alias_ty(tcx), rhs.to_alias_ty(tcx)) {
match (lhs.to_alias_term(), rhs.to_alias_term()) {
(None, None) => {
self.relate(param_env, lhs, variance, rhs)?;
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)

View file

@ -699,7 +699,7 @@ pub(in crate::solve) fn predicates_for_object_candidate<'tcx>(
old_ty,
None,
"{} has two generic parameters: {} and {}",
proj.projection_ty,
proj.projection_term,
proj.term,
old_ty.unwrap()
);
@ -740,7 +740,11 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
// FIXME: Technically this equate could be fallible...
self.nested.extend(
self.ecx
.eq_and_get_goals(self.param_env, alias_ty, proj.projection_ty)
.eq_and_get_goals(
self.param_env,
alias_ty,
proj.projection_term.expect_ty(self.ecx.tcx()),
)
.expect("expected to be able to unify goal projection with dyn's projection"),
);
proj.term.ty().unwrap()

View file

@ -748,7 +748,7 @@ pub(super) fn eq<T: ToTrace<'tcx>>(
pub(super) fn relate_rigid_alias_non_alias(
&mut self,
param_env: ty::ParamEnv<'tcx>,
alias: ty::AliasTy<'tcx>,
alias: ty::AliasTerm<'tcx>,
variance: ty::Variance,
term: ty::Term<'tcx>,
) -> Result<(), NoSolution> {
@ -765,13 +765,13 @@ pub(super) fn relate_rigid_alias_non_alias(
// Alternatively we could modify `Equate` for this case by adding another
// variant to `StructurallyRelateAliases`.
let identity_args = self.fresh_args_for_item(alias.def_id);
let rigid_ctor = ty::AliasTy::new(tcx, alias.def_id, identity_args);
let ctor_ty = rigid_ctor.to_ty(tcx);
let rigid_ctor = ty::AliasTerm::new(tcx, alias.def_id, identity_args);
let ctor_term = rigid_ctor.to_term(tcx);
let InferOk { value: (), obligations } = self
.infcx
.at(&ObligationCause::dummy(), param_env)
.trace(term, ctor_ty.into())
.eq_structurally_relating_aliases(term, ctor_ty.into())?;
.trace(term, ctor_term)
.eq_structurally_relating_aliases(term, ctor_term)?;
debug_assert!(obligations.is_empty());
self.relate(param_env, alias, variance, rigid_ctor)
} else {

View file

@ -7,7 +7,7 @@
use rustc_infer::traits::TraitEngineExt;
use rustc_infer::traits::{FulfillmentError, Obligation, TraitEngine};
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::{self, AliasTy, Ty, TyCtxt, UniverseIndex};
use rustc_middle::ty::{self, Ty, TyCtxt, UniverseIndex};
use rustc_middle::ty::{FallibleTypeFolder, TypeFolder, TypeSuperFoldable};
use rustc_middle::ty::{TypeFoldable, TypeVisitableExt};
@ -63,7 +63,7 @@ fn normalize_alias_ty(
};
self.at.infcx.err_ctxt().report_overflow_error(
OverflowCause::DeeplyNormalize(data),
OverflowCause::DeeplyNormalize(data.into()),
self.at.cause.span,
true,
|_| {},
@ -108,7 +108,7 @@ fn normalize_unevaluated_const(
let recursion_limit = tcx.recursion_limit();
if !recursion_limit.value_within_limit(self.depth) {
self.at.infcx.err_ctxt().report_overflow_error(
OverflowCause::DeeplyNormalize(ty::AliasTy::new(tcx, uv.def, uv.args)),
OverflowCause::DeeplyNormalize(uv.into()),
self.at.cause.span,
true,
|_| {},
@ -122,10 +122,7 @@ fn normalize_unevaluated_const(
tcx,
self.at.cause.clone(),
self.at.param_env,
ty::NormalizesTo {
alias: AliasTy::new(tcx, uv.def, uv.args),
term: new_infer_ct.into(),
},
ty::NormalizesTo { alias: uv.into(), term: new_infer_ct.into() },
);
let result = if infcx.predicate_may_hold(&obligation) {

View file

@ -15,7 +15,7 @@ pub(super) fn normalize_inherent_associated_type(
goal: Goal<'tcx, ty::NormalizesTo<'tcx>>,
) -> QueryResult<'tcx> {
let tcx = self.tcx();
let inherent = goal.predicate.alias;
let inherent = goal.predicate.alias.expect_ty(tcx);
let impl_def_id = tcx.parent(inherent.def_id);
let impl_args = self.fresh_args_for_item(impl_def_id);

View file

@ -41,19 +41,8 @@ pub(super) fn compute_normalizes_to_goal(
Ok(res) => Ok(res),
Err(NoSolution) => {
let Goal { param_env, predicate: NormalizesTo { alias, term } } = goal;
if alias.opt_kind(self.tcx()).is_some() {
self.relate_rigid_alias_non_alias(
param_env,
alias,
ty::Variance::Invariant,
term,
)?;
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
} else {
// FIXME(generic_const_exprs): we currently do not support rigid
// unevaluated constants.
Err(NoSolution)
}
self.relate_rigid_alias_non_alias(param_env, alias, ty::Variance::Invariant, term)?;
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
}
}
}
@ -133,7 +122,7 @@ fn probe_and_match_goal_against_assumption(
ecx.eq(
goal.param_env,
goal.predicate.alias,
assumption_projection_pred.projection_ty,
assumption_projection_pred.projection_term,
)?;
ecx.instantiate_normalizes_to_term(goal, assumption_projection_pred.term);
@ -374,7 +363,7 @@ fn consider_builtin_fn_trait_candidates(
let pred = tupled_inputs_and_output
.map_bound(|(inputs, output)| ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(
projection_term: ty::AliasTerm::new(
tcx,
goal.predicate.def_id(),
[goal.predicate.self_ty(), inputs],
@ -426,9 +415,9 @@ fn consider_builtin_async_fn_trait_candidates(
output_coroutine_ty,
coroutine_return_ty,
}| {
let (projection_ty, term) = match tcx.item_name(goal.predicate.def_id()) {
let (projection_term, term) = match tcx.item_name(goal.predicate.def_id()) {
sym::CallOnceFuture => (
ty::AliasTy::new(
ty::AliasTerm::new(
tcx,
goal.predicate.def_id(),
[goal.predicate.self_ty(), tupled_inputs_ty],
@ -436,7 +425,7 @@ fn consider_builtin_async_fn_trait_candidates(
output_coroutine_ty.into(),
),
sym::CallRefFuture => (
ty::AliasTy::new(
ty::AliasTerm::new(
tcx,
goal.predicate.def_id(),
[
@ -448,7 +437,7 @@ fn consider_builtin_async_fn_trait_candidates(
output_coroutine_ty.into(),
),
sym::Output => (
ty::AliasTy::new(
ty::AliasTerm::new(
tcx,
goal.predicate.def_id(),
[
@ -460,7 +449,7 @@ fn consider_builtin_async_fn_trait_candidates(
),
name => bug!("no such associated type: {name}"),
};
ty::ProjectionPredicate { projection_ty, term }
ty::ProjectionPredicate { projection_term, term }
},
)
.to_predicate(tcx);
@ -637,7 +626,7 @@ fn consider_builtin_future_candidate(
CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
goal,
ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(ecx.tcx(), goal.predicate.def_id(), [self_ty]),
projection_term: ty::AliasTerm::new(ecx.tcx(), goal.predicate.def_id(), [self_ty]),
term,
}
.to_predicate(tcx),
@ -669,7 +658,7 @@ fn consider_builtin_iterator_candidate(
CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
goal,
ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(ecx.tcx(), goal.predicate.def_id(), [self_ty]),
projection_term: ty::AliasTerm::new(ecx.tcx(), goal.predicate.def_id(), [self_ty]),
term,
}
.to_predicate(tcx),
@ -753,7 +742,7 @@ fn consider_builtin_coroutine_candidate(
CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
goal,
ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(
projection_term: ty::AliasTerm::new(
ecx.tcx(),
goal.predicate.def_id(),
[self_ty, coroutine.resume_ty()],

View file

@ -11,19 +11,7 @@ pub(super) fn compute_projection_goal(
goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
) -> QueryResult<'tcx> {
let tcx = self.tcx();
let projection_term = match goal.predicate.term.unpack() {
ty::TermKind::Ty(_) => goal.predicate.projection_ty.to_ty(tcx).into(),
ty::TermKind::Const(_) => ty::Const::new_unevaluated(
tcx,
ty::UnevaluatedConst::new(
goal.predicate.projection_ty.def_id,
goal.predicate.projection_ty.args,
),
tcx.type_of(goal.predicate.projection_ty.def_id)
.instantiate(tcx, goal.predicate.projection_ty.args),
)
.into(),
};
let projection_term = goal.predicate.projection_term.to_term(tcx);
let goal = goal.with(
tcx,
ty::PredicateKind::AliasRelate(

View file

@ -540,11 +540,11 @@ fn map_vid_to_region<'cx>(
finished_map
}
fn is_param_no_infer(&self, args: GenericArgsRef<'_>) -> bool {
fn is_param_no_infer(&self, args: GenericArgsRef<'tcx>) -> bool {
self.is_of_param(args.type_at(0)) && !args.types().any(|t| t.has_infer_types())
}
pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
pub fn is_of_param(&self, ty: Ty<'tcx>) -> bool {
match ty.kind() {
ty::Param(_) => true,
ty::Alias(ty::Projection, p) => self.is_of_param(p.self_ty()),
@ -552,9 +552,9 @@ pub fn is_of_param(&self, ty: Ty<'_>) -> bool {
}
}
fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool {
fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool {
if let Some(ty) = p.term().skip_binder().ty() {
matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_ty)
matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_term.expect_ty(self.tcx))
} else {
false
}
@ -612,7 +612,7 @@ fn evaluate_nested_obligations(
// an inference variable.
// Additionally, we check if we've seen this predicate before,
// to avoid rendering duplicate bounds to the user.
if self.is_param_no_infer(p.skip_binder().projection_ty.args)
if self.is_param_no_infer(p.skip_binder().projection_term.args)
&& !p.term().skip_binder().has_infer_types()
&& is_new_pred
{
@ -684,7 +684,7 @@ fn evaluate_nested_obligations(
// and turn them into an explicit negative impl for our type.
debug!("Projecting and unifying projection predicate {:?}", predicate);
match project::poly_project_and_unify_type(selcx, &obligation.with(self.tcx, p))
match project::poly_project_and_unify_term(selcx, &obligation.with(self.tcx, p))
{
ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
debug!(

View file

@ -1096,11 +1096,11 @@ fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr))) => tr.trait_ref,
Some(ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)))
if matches!(
infcx.tcx.def_kind(proj.projection_ty.def_id),
infcx.tcx.def_kind(proj.projection_term.def_id),
DefKind::AssocTy | DefKind::AssocConst
) =>
{
proj.projection_ty.trait_ref(infcx.tcx)
proj.projection_term.trait_ref(infcx.tcx)
}
_ => return,
};

View file

@ -1105,9 +1105,9 @@ fn extract_callable_info(
.iter()
.find_map(|pred| {
if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
&& Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
&& Some(proj.projection_term.def_id) == self.tcx.lang_items().fn_once_output()
// args tuple will always be args[1]
&& let ty::Tuple(args) = proj.projection_ty.args.type_at(1).kind()
&& let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
{
Some((
DefIdOrName::DefId(def_id),
@ -1149,10 +1149,10 @@ fn extract_callable_info(
};
param_env.caller_bounds().iter().find_map(|pred| {
if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
&& Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output()
&& proj.projection_ty.self_ty() == found
&& Some(proj.projection_term.def_id) == self.tcx.lang_items().fn_once_output()
&& proj.projection_term.self_ty() == found
// args tuple will always be args[1]
&& let ty::Tuple(args) = proj.projection_ty.args.type_at(1).kind()
&& let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
{
Some((
name,
@ -3846,11 +3846,11 @@ fn note_function_argument_obligation<G: EmissionGuarantee>(
&& let Some(found) = failed_pred.skip_binder().term.ty()
{
type_diffs = vec![Sorts(ty::error::ExpectedFound {
expected: Ty::new_alias(
self.tcx,
ty::Projection,
where_pred.skip_binder().projection_ty,
),
expected: where_pred
.skip_binder()
.projection_term
.expect_ty(self.tcx)
.to_ty(self.tcx),
found,
})];
}
@ -4275,7 +4275,7 @@ fn probe_assoc_types_at_expr(
// This corresponds to `<ExprTy as Iterator>::Item = _`.
let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(self.tcx, proj.def_id, args),
projection_term: ty::AliasTerm::new(self.tcx, proj.def_id, args),
term: ty.into(),
}),
));
@ -4972,7 +4972,7 @@ fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
let ty::ClauseKind::Projection(proj) = clause else {
return;
};
let name = tcx.item_name(proj.projection_ty.def_id);
let name = tcx.item_name(proj.projection_term.def_id);
let mut predicates = generics.predicates.iter().peekable();
let mut prev: Option<&hir::WhereBoundPredicate<'_>> = None;
while let Some(pred) = predicates.next() {

View file

@ -63,7 +63,7 @@
pub use rustc_infer::traits::error_reporting::*;
pub enum OverflowCause<'tcx> {
DeeplyNormalize(ty::AliasTy<'tcx>),
DeeplyNormalize(ty::AliasTerm<'tcx>),
TraitSolver(ty::Predicate<'tcx>),
}
@ -247,10 +247,10 @@ fn with_short_path<'tcx, T>(tcx: TyCtxt<'tcx>, value: T) -> String
}
let mut err = match cause {
OverflowCause::DeeplyNormalize(alias_ty) => {
let alias_ty = self.resolve_vars_if_possible(alias_ty);
let kind = alias_ty.opt_kind(self.tcx).map_or("alias", |k| k.descr());
let alias_str = with_short_path(self.tcx, alias_ty);
OverflowCause::DeeplyNormalize(alias_term) => {
let alias_term = self.resolve_vars_if_possible(alias_term);
let kind = alias_term.kind(self.tcx).descr();
let alias_str = with_short_path(self.tcx, alias_term);
struct_span_code_err!(
self.dcx(),
span,
@ -1469,7 +1469,7 @@ fn can_match_projection(
);
let param_env = ty::ParamEnv::empty();
self.can_eq(param_env, goal.projection_ty, assumption.projection_ty)
self.can_eq(param_env, goal.projection_term, assumption.projection_term)
&& self.can_eq(param_env, goal.term, assumption.term)
}
@ -1584,23 +1584,7 @@ fn report_projection_error(
infer::BoundRegionConversionTime::HigherRankedType,
bound_predicate.rebind(data),
);
let unnormalized_term = match data.term.unpack() {
ty::TermKind::Ty(_) => Ty::new_projection(
self.tcx,
data.projection_ty.def_id,
data.projection_ty.args,
)
.into(),
ty::TermKind::Const(ct) => ty::Const::new_unevaluated(
self.tcx,
ty::UnevaluatedConst {
def: data.projection_ty.def_id,
args: data.projection_ty.args,
},
ct.ty(),
)
.into(),
};
let unnormalized_term = data.projection_term.to_term(self.tcx);
// FIXME(-Znext-solver): For diagnostic purposes, it would be nice
// to deeply normalize this type.
let normalized_term =
@ -1665,13 +1649,13 @@ fn report_projection_error(
return None;
};
let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_ty.def_id)?;
let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_term.def_id)?;
let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
let mut associated_items = vec![];
self.tcx.for_each_relevant_impl(
self.tcx.trait_of_item(proj.projection_ty.def_id)?,
proj.projection_ty.self_ty(),
self.tcx.trait_of_item(proj.projection_term.def_id)?,
proj.projection_term.self_ty(),
|impl_def_id| {
associated_items.extend(
self.tcx
@ -1740,11 +1724,11 @@ fn maybe_detailed_projection_msg(
normalized_ty: ty::Term<'tcx>,
expected_ty: ty::Term<'tcx>,
) -> Option<String> {
let trait_def_id = pred.projection_ty.trait_def_id(self.tcx);
let self_ty = pred.projection_ty.self_ty();
let trait_def_id = pred.projection_term.trait_def_id(self.tcx);
let self_ty = pred.projection_term.self_ty();
with_forced_trimmed_paths! {
if Some(pred.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() {
if Some(pred.projection_term.def_id) == self.tcx.lang_items().fn_once_output() {
let fn_kind = self_ty.prefix_string(self.tcx);
let item = match self_ty.kind() {
ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
@ -2623,14 +2607,14 @@ fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) -> Erro
}
if let Err(guar) =
self.tcx.ensure().coherent_trait(self.tcx.parent(data.projection_ty.def_id))
self.tcx.ensure().coherent_trait(self.tcx.parent(data.projection_term.def_id))
{
// Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
// other `Foo` impls are incoherent.
return guar;
}
let arg = data
.projection_ty
.projection_term
.args
.iter()
.chain(Some(data.term.into_arg()))

View file

@ -771,13 +771,13 @@ fn process_projection_obligation(
}
}
match project::poly_project_and_unify_type(&mut self.selcx, &project_obligation) {
match project::poly_project_and_unify_term(&mut self.selcx, &project_obligation) {
ProjectAndUnifyResult::Holds(os) => ProcessResult::Changed(mk_pending(os)),
ProjectAndUnifyResult::FailedNormalization => {
stalled_on.clear();
stalled_on.extend(args_infer_vars(
&self.selcx,
project_obligation.predicate.map_bound(|pred| pred.projection_ty.args),
project_obligation.predicate.map_bound(|pred| pred.projection_term.args),
));
ProcessResult::Unchanged
}

View file

@ -52,7 +52,7 @@
pub use self::object_safety::is_vtable_safe_method;
pub use self::object_safety::object_safety_violations_for_assoc_item;
pub use self::object_safety::ObjectSafetyViolation;
pub use self::project::{normalize_inherent_projection, normalize_projection_type};
pub use self::project::{normalize_inherent_projection, normalize_projection_ty};
pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
pub use self::specialize::specialization_graph::FutureCompatOverlapError;

View file

@ -213,7 +213,7 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let recursion_limit = self.interner().recursion_limit();
if !recursion_limit.value_within_limit(self.depth) {
self.selcx.infcx.err_ctxt().report_overflow_error(
OverflowCause::DeeplyNormalize(data),
OverflowCause::DeeplyNormalize(data.into()),
self.cause.span,
true,
|_| {},
@ -238,7 +238,7 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
// register an obligation to *later* project, since we know
// there won't be bound vars there.
let data = data.fold_with(self);
let normalized_ty = project::normalize_projection_type(
let normalized_ty = project::normalize_projection_ty(
self.selcx,
self.param_env,
data,
@ -273,10 +273,10 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let (data, mapped_regions, mapped_types, mapped_consts) =
BoundVarReplacer::replace_bound_vars(infcx, &mut self.universes, data);
let data = data.fold_with(self);
let normalized_ty = project::opt_normalize_projection_type(
let normalized_ty = project::opt_normalize_projection_term(
self.selcx,
self.param_env,
data,
data.into(),
self.cause.clone(),
self.depth,
self.obligations,
@ -309,7 +309,7 @@ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let recursion_limit = self.interner().recursion_limit();
if !recursion_limit.value_within_limit(self.depth) {
self.selcx.infcx.err_ctxt().report_overflow_error(
OverflowCause::DeeplyNormalize(data),
OverflowCause::DeeplyNormalize(data.into()),
self.cause.span,
false,
|diag| {

View file

@ -305,7 +305,7 @@ fn predicate_references_self<'tcx>(
//
// This is ALT2 in issue #56288, see that for discussion of the
// possible alternatives.
data.projection_ty.args[1..].iter().any(has_self_ty).then_some(sp)
data.projection_term.args[1..].iter().any(has_self_ty).then_some(sp)
}
ty::ClauseKind::ConstArgHasType(_ct, ty) => has_self_ty(&ty.into()).then_some(sp),

View file

@ -12,7 +12,7 @@
use super::Selection;
use super::SelectionContext;
use super::SelectionError;
use super::{Normalized, NormalizedTy, ProjectionCacheEntry, ProjectionCacheKey};
use super::{Normalized, NormalizedTerm, ProjectionCacheEntry, ProjectionCacheKey};
use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::traits::BuiltinImplSource;
use rustc_middle::traits::ImplSource;
@ -44,7 +44,7 @@
pub type ProjectionObligation<'tcx> = Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::AliasTy<'tcx>>;
pub type ProjectionTermObligation<'tcx> = Obligation<'tcx, ty::AliasTerm<'tcx>>;
pub(super) struct InProgress;
@ -182,7 +182,7 @@ pub(super) enum ProjectAndUnifyResult<'tcx> {
/// If successful, this may result in additional obligations. Also returns
/// the projection cache key used to track these additional obligations.
#[instrument(level = "debug", skip(selcx))]
pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
pub(super) fn poly_project_and_unify_term<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &PolyProjectionObligation<'tcx>,
) -> ProjectAndUnifyResult<'tcx> {
@ -193,7 +193,7 @@ pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
let new_universe = infcx.universe();
let placeholder_obligation = obligation.with(infcx.tcx, placeholder_predicate);
match project_and_unify_type(selcx, &placeholder_obligation) {
match project_and_unify_term(selcx, &placeholder_obligation) {
ProjectAndUnifyResult::MismatchedProjectionTypes(e) => Err(e),
ProjectAndUnifyResult::Holds(obligations)
if old_universe != new_universe
@ -233,19 +233,19 @@ pub(super) fn poly_project_and_unify_type<'cx, 'tcx>(
/// ```
/// If successful, this may result in additional obligations.
///
/// See [poly_project_and_unify_type] for an explanation of the return value.
/// See [poly_project_and_unify_term] for an explanation of the return value.
#[instrument(level = "debug", skip(selcx))]
fn project_and_unify_type<'cx, 'tcx>(
fn project_and_unify_term<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionObligation<'tcx>,
) -> ProjectAndUnifyResult<'tcx> {
let mut obligations = vec![];
let infcx = selcx.infcx;
let normalized = match opt_normalize_projection_type(
let normalized = match opt_normalize_projection_term(
selcx,
obligation.param_env,
obligation.predicate.projection_ty,
obligation.predicate.projection_term,
obligation.cause.clone(),
obligation.recursion_depth,
&mut obligations,
@ -291,7 +291,7 @@ fn project_and_unify_type<'cx, 'tcx>(
/// there are unresolved type variables in the projection, we will
/// instantiate it with a fresh type variable `$X` and generate a new
/// obligation `<T as Trait>::Item == $X` for later.
pub fn normalize_projection_type<'a, 'b, 'tcx>(
pub fn normalize_projection_ty<'a, 'b, 'tcx>(
selcx: &'a mut SelectionContext<'b, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
projection_ty: ty::AliasTy<'tcx>,
@ -299,10 +299,10 @@ pub fn normalize_projection_type<'a, 'b, 'tcx>(
depth: usize,
obligations: &mut Vec<PredicateObligation<'tcx>>,
) -> Term<'tcx> {
opt_normalize_projection_type(
opt_normalize_projection_term(
selcx,
param_env,
projection_ty,
projection_ty.into(),
cause.clone(),
depth,
obligations,
@ -314,7 +314,10 @@ pub fn normalize_projection_type<'a, 'b, 'tcx>(
// and a deferred predicate to resolve this when more type
// information is available.
selcx.infcx.infer_projection(param_env, projection_ty, cause, depth + 1, obligations).into()
selcx
.infcx
.projection_ty_to_infer(param_env, projection_ty, cause, depth + 1, obligations)
.into()
})
}
@ -329,10 +332,10 @@ pub fn normalize_projection_type<'a, 'b, 'tcx>(
/// function takes an obligations vector and appends to it directly, which is
/// slightly uglier but avoids the need for an extra short-lived allocation.
#[instrument(level = "debug", skip(selcx, param_env, cause, obligations))]
pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
pub(super) fn opt_normalize_projection_term<'a, 'b, 'tcx>(
selcx: &'a mut SelectionContext<'b, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
projection_ty: ty::AliasTy<'tcx>,
projection_term: ty::AliasTerm<'tcx>,
cause: ObligationCause<'tcx>,
depth: usize,
obligations: &mut Vec<PredicateObligation<'tcx>>,
@ -344,8 +347,8 @@ pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
// mode, which could lead to using incorrect cache results.
let use_cache = !selcx.is_intercrate();
let projection_ty = infcx.resolve_vars_if_possible(projection_ty);
let cache_key = ProjectionCacheKey::new(projection_ty, param_env);
let projection_term = infcx.resolve_vars_if_possible(projection_term);
let cache_key = ProjectionCacheKey::new(projection_term, param_env);
// FIXME(#20304) For now, I am caching here, which is good, but it
// means we don't capture the type variables that are created in
@ -393,7 +396,7 @@ pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
debug!("recur cache");
return Err(InProgress);
}
Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => {
Err(ProjectionCacheEntry::NormalizedTerm { ty, complete: _ }) => {
// This is the hottest path in this function.
//
// If we find the value in the cache, then return it along
@ -411,14 +414,14 @@ pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
}
Err(ProjectionCacheEntry::Error) => {
debug!("opt_normalize_projection_type: found error");
let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
let result = normalize_to_error(selcx, param_env, projection_term, cause, depth);
obligations.extend(result.obligations);
return Ok(Some(result.value.into()));
}
}
let obligation =
Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_ty);
Obligation::with_depth(selcx.tcx(), cause.clone(), depth, param_env, projection_term);
match project(selcx, &obligation) {
Ok(Projected::Progress(Progress {
@ -481,7 +484,7 @@ pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
if use_cache {
infcx.inner.borrow_mut().projection_cache().error(cache_key);
}
let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth);
let result = normalize_to_error(selcx, param_env, projection_term, cause, depth);
obligations.extend(result.obligations);
Ok(Some(result.value.into()))
}
@ -510,19 +513,33 @@ pub(super) fn opt_normalize_projection_type<'a, 'b, 'tcx>(
fn normalize_to_error<'a, 'tcx>(
selcx: &SelectionContext<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
projection_ty: ty::AliasTy<'tcx>,
projection_term: ty::AliasTerm<'tcx>,
cause: ObligationCause<'tcx>,
depth: usize,
) -> NormalizedTy<'tcx> {
let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx()));
) -> NormalizedTerm<'tcx> {
let trait_ref = ty::Binder::dummy(projection_term.trait_ref(selcx.tcx()));
let new_value = match projection_term.kind(selcx.tcx()) {
ty::AliasTermKind::ProjectionTy
| ty::AliasTermKind::InherentTy
| ty::AliasTermKind::OpaqueTy
| ty::AliasTermKind::WeakTy => selcx.infcx.next_ty_var(cause.span).into(),
ty::AliasTermKind::UnevaluatedConst | ty::AliasTermKind::ProjectionConst => selcx
.infcx
.next_const_var(
selcx
.tcx()
.type_of(projection_term.def_id)
.instantiate(selcx.tcx(), projection_term.args),
cause.span,
)
.into(),
};
let trait_obligation = Obligation {
cause,
recursion_depth: depth,
param_env,
predicate: trait_ref.to_predicate(selcx.tcx()),
};
let tcx = selcx.infcx.tcx;
let new_value = selcx.infcx.next_ty_var(tcx.def_span(projection_ty.def_id));
Normalized { value: new_value, obligations: vec![trait_obligation] }
}
@ -676,7 +693,7 @@ fn with_addl_obligations(mut self, mut obligations: Vec<PredicateObligation<'tcx
#[instrument(level = "info", skip(selcx))]
fn project<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) {
// This should really be an immediate error, but some existing code
@ -751,7 +768,7 @@ fn project<'cx, 'tcx>(
/// there that can answer this question.
fn assemble_candidates_from_param_env<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate_set: &mut ProjectionCandidateSet<'tcx>,
) {
assemble_candidates_from_predicates(
@ -776,7 +793,7 @@ fn assemble_candidates_from_param_env<'cx, 'tcx>(
/// Here, for example, we could conclude that the result is `i32`.
fn assemble_candidates_from_trait_def<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate_set: &mut ProjectionCandidateSet<'tcx>,
) {
debug!("assemble_candidates_from_trait_def(..)");
@ -834,7 +851,7 @@ fn assemble_candidates_from_trait_def<'cx, 'tcx>(
/// `dyn Iterator<Item = ()>: Iterator` again.
fn assemble_candidates_from_object_ty<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate_set: &mut ProjectionCandidateSet<'tcx>,
) {
debug!("assemble_candidates_from_object_ty(..)");
@ -878,7 +895,7 @@ fn assemble_candidates_from_object_ty<'cx, 'tcx>(
)]
fn assemble_candidates_from_predicates<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate_set: &mut ProjectionCandidateSet<'tcx>,
ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionCandidate<'tcx>,
env_predicates: impl Iterator<Item = ty::Clause<'tcx>>,
@ -926,7 +943,7 @@ fn assemble_candidates_from_predicates<'cx, 'tcx>(
#[instrument(level = "debug", skip(selcx, obligation, candidate_set))]
fn assemble_candidates_from_impls<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate_set: &mut ProjectionCandidateSet<'tcx>,
) {
// If we are resolving `<T as TraitRef<...>>::Item == Type`,
@ -1254,7 +1271,7 @@ fn assemble_candidates_from_impls<'cx, 'tcx>(
fn confirm_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
candidate: ProjectionCandidate<'tcx>,
) -> Progress<'tcx> {
debug!(?obligation, ?candidate, "confirm_candidate");
@ -1286,7 +1303,7 @@ fn confirm_candidate<'cx, 'tcx>(
fn confirm_select_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
impl_source: Selection<'tcx>,
) -> Progress<'tcx> {
match impl_source {
@ -1334,7 +1351,7 @@ fn confirm_select_candidate<'cx, 'tcx>(
fn confirm_coroutine_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
@ -1378,7 +1395,7 @@ fn confirm_coroutine_candidate<'cx, 'tcx>(
};
let predicate = ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, obligation.predicate.def_id, trait_ref.args),
projection_term: ty::AliasTerm::new(tcx, obligation.predicate.def_id, trait_ref.args),
term: ty.into(),
};
@ -1389,7 +1406,7 @@ fn confirm_coroutine_candidate<'cx, 'tcx>(
fn confirm_future_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
@ -1422,7 +1439,7 @@ fn confirm_future_candidate<'cx, 'tcx>(
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Output);
let predicate = ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, obligation.predicate.def_id, trait_ref.args),
projection_term: ty::AliasTerm::new(tcx, obligation.predicate.def_id, trait_ref.args),
term: return_ty.into(),
};
@ -1433,7 +1450,7 @@ fn confirm_future_candidate<'cx, 'tcx>(
fn confirm_iterator_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let self_ty = selcx.infcx.shallow_resolve(obligation.predicate.self_ty());
@ -1464,7 +1481,7 @@ fn confirm_iterator_candidate<'cx, 'tcx>(
debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Item);
let predicate = ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, obligation.predicate.def_id, trait_ref.args),
projection_term: ty::AliasTerm::new(tcx, obligation.predicate.def_id, trait_ref.args),
term: yield_ty.into(),
};
@ -1475,7 +1492,7 @@ fn confirm_iterator_candidate<'cx, 'tcx>(
fn confirm_async_iterator_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let ty::Coroutine(_, args) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind()
@ -1514,7 +1531,7 @@ fn confirm_async_iterator_candidate<'cx, 'tcx>(
let item_ty = args.type_at(0);
let predicate = ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, obligation.predicate.def_id, trait_ref.args),
projection_term: ty::AliasTerm::new(tcx, obligation.predicate.def_id, trait_ref.args),
term: item_ty.into(),
};
@ -1525,7 +1542,7 @@ fn confirm_async_iterator_candidate<'cx, 'tcx>(
fn confirm_builtin_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
data: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let tcx = selcx.tcx();
@ -1583,8 +1600,10 @@ fn confirm_builtin_candidate<'cx, 'tcx>(
bug!("unexpected builtin trait with associated type: {:?}", obligation.predicate);
};
let predicate =
ty::ProjectionPredicate { projection_ty: ty::AliasTy::new(tcx, item_def_id, args), term };
let predicate = ty::ProjectionPredicate {
projection_term: ty::AliasTerm::new(tcx, item_def_id, args),
term,
};
confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
.with_addl_obligations(obligations)
@ -1593,7 +1612,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>(
fn confirm_fn_pointer_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let tcx = selcx.tcx();
@ -1629,7 +1648,7 @@ fn confirm_fn_pointer_candidate<'cx, 'tcx>(
fn confirm_closure_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let tcx = selcx.tcx();
@ -1728,7 +1747,7 @@ fn confirm_closure_candidate<'cx, 'tcx>(
fn confirm_callable_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
fn_sig: ty::PolyFnSig<'tcx>,
flag: util::TupleArgumentsFlag,
fn_host_effect: ty::Const<'tcx>,
@ -1749,7 +1768,7 @@ fn confirm_callable_candidate<'cx, 'tcx>(
fn_host_effect,
)
.map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(tcx, fn_once_output_def_id, trait_ref.args),
projection_term: ty::AliasTerm::new(tcx, fn_once_output_def_id, trait_ref.args),
term: ret_type.into(),
});
@ -1758,7 +1777,7 @@ fn confirm_callable_candidate<'cx, 'tcx>(
fn confirm_async_closure_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let tcx = selcx.tcx();
@ -1837,13 +1856,13 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
sym::Output => sig.return_ty,
name => bug!("no such associated type: {name}"),
};
let projection_ty = match item_name {
sym::CallOnceFuture | sym::Output => ty::AliasTy::new(
let projection_term = match item_name {
sym::CallOnceFuture | sym::Output => ty::AliasTerm::new(
tcx,
obligation.predicate.def_id,
[self_ty, sig.tupled_inputs_ty],
),
sym::CallRefFuture => ty::AliasTy::new(
sym::CallRefFuture => ty::AliasTerm::new(
tcx,
obligation.predicate.def_id,
[ty::GenericArg::from(self_ty), sig.tupled_inputs_ty.into(), env_region.into()],
@ -1852,7 +1871,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
};
args.coroutine_closure_sig()
.rebind(ty::ProjectionPredicate { projection_ty, term: term.into() })
.rebind(ty::ProjectionPredicate { projection_term, term: term.into() })
}
ty::FnDef(..) | ty::FnPtr(..) => {
let bound_sig = self_ty.fn_sig(tcx);
@ -1872,13 +1891,13 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
}
name => bug!("no such associated type: {name}"),
};
let projection_ty = match item_name {
sym::CallOnceFuture | sym::Output => ty::AliasTy::new(
let projection_term = match item_name {
sym::CallOnceFuture | sym::Output => ty::AliasTerm::new(
tcx,
obligation.predicate.def_id,
[self_ty, Ty::new_tup(tcx, sig.inputs())],
),
sym::CallRefFuture => ty::AliasTy::new(
sym::CallRefFuture => ty::AliasTerm::new(
tcx,
obligation.predicate.def_id,
[
@ -1890,7 +1909,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
name => bug!("no such associated type: {name}"),
};
bound_sig.rebind(ty::ProjectionPredicate { projection_ty, term: term.into() })
bound_sig.rebind(ty::ProjectionPredicate { projection_term, term: term.into() })
}
ty::Closure(_, args) => {
let args = args.as_closure();
@ -1911,11 +1930,11 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
}
name => bug!("no such associated type: {name}"),
};
let projection_ty = match item_name {
let projection_term = match item_name {
sym::CallOnceFuture | sym::Output => {
ty::AliasTy::new(tcx, obligation.predicate.def_id, [self_ty, sig.inputs()[0]])
ty::AliasTerm::new(tcx, obligation.predicate.def_id, [self_ty, sig.inputs()[0]])
}
sym::CallRefFuture => ty::AliasTy::new(
sym::CallRefFuture => ty::AliasTerm::new(
tcx,
obligation.predicate.def_id,
[ty::GenericArg::from(self_ty), sig.inputs()[0].into(), env_region.into()],
@ -1923,7 +1942,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
name => bug!("no such associated type: {name}"),
};
bound_sig.rebind(ty::ProjectionPredicate { projection_ty, term: term.into() })
bound_sig.rebind(ty::ProjectionPredicate { projection_term, term: term.into() })
}
_ => bug!("expected callable type for AsyncFn candidate"),
};
@ -1934,7 +1953,7 @@ fn confirm_async_closure_candidate<'cx, 'tcx>(
fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: Vec<PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let [
@ -1951,7 +1970,7 @@ fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>(
};
let predicate = ty::ProjectionPredicate {
projection_ty: ty::AliasTy::new(
projection_term: ty::AliasTerm::new(
selcx.tcx(),
obligation.predicate.def_id,
obligation.predicate.args,
@ -1973,7 +1992,7 @@ fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>(
fn confirm_param_env_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
poly_cache_entry: ty::PolyProjectionPredicate<'tcx>,
potentially_unnormalized_candidate: bool,
) -> Progress<'tcx> {
@ -1987,7 +2006,7 @@ fn confirm_param_env_candidate<'cx, 'tcx>(
poly_cache_entry,
);
let cache_projection = cache_entry.projection_ty;
let cache_projection = cache_entry.projection_term;
let mut nested_obligations = Vec::new();
let obligation_projection = obligation.predicate;
let obligation_projection = ensure_sufficient_stack(|| {
@ -2042,7 +2061,7 @@ fn confirm_param_env_candidate<'cx, 'tcx>(
fn confirm_impl_candidate<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
) -> Progress<'tcx> {
let tcx = selcx.tcx();
@ -2103,7 +2122,7 @@ fn confirm_impl_candidate<'cx, 'tcx>(
// associated type itself.
fn assoc_ty_own_obligations<'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
nested: &mut Vec<PredicateObligation<'tcx>>,
) {
let tcx = selcx.tcx();
@ -2165,7 +2184,7 @@ fn from_poly_projection_obligation(
// from a specific call to `opt_normalize_projection_type` - if
// there's no precise match, the original cache entry is "stranded"
// anyway.
infcx.resolve_vars_if_possible(predicate.projection_ty),
infcx.resolve_vars_if_possible(predicate.projection_term),
obligation.param_env,
)
})

View file

@ -222,7 +222,7 @@ fn try_fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
.infcx
.err_ctxt()
.build_overflow_error(
OverflowCause::DeeplyNormalize(data),
OverflowCause::DeeplyNormalize(data.into()),
self.cause.span,
true,
)

View file

@ -945,7 +945,7 @@ fn need_migrate_deref_output_trait_object(
}
self.infcx.probe(|_| {
let ty = traits::normalize_projection_type(
let ty = traits::normalize_projection_ty(
self,
param_env,
ty::AliasTy::new(tcx, tcx.lang_items().deref_target()?, trait_ref.args),

View file

@ -8,7 +8,7 @@
use super::coherence::{self, Conflict};
use super::const_evaluatable;
use super::project;
use super::project::ProjectionTyObligation;
use super::project::ProjectionTermObligation;
use super::util;
use super::util::closure_trait_ref_and_return_type;
use super::wf;
@ -809,7 +809,7 @@ fn evaluate_predicate_recursively<'o>(
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
let data = bound_predicate.rebind(data);
let project_obligation = obligation.with(self.tcx(), data);
match project::poly_project_and_unify_type(self, &project_obligation) {
match project::poly_project_and_unify_term(self, &project_obligation) {
ProjectAndUnifyResult::Holds(mut subobligations) => {
'compute_res: {
// If we've previously marked this projection as 'complete', then
@ -1734,7 +1734,7 @@ fn where_clause_may_apply<'o>(
/// in cases like #91762.
pub(super) fn match_projection_projections(
&mut self,
obligation: &ProjectionTyObligation<'tcx>,
obligation: &ProjectionTermObligation<'tcx>,
env_predicate: PolyProjectionPredicate<'tcx>,
potentially_unnormalized_candidates: bool,
) -> ProjectionMatchesProjection {
@ -1753,12 +1753,12 @@ pub(super) fn match_projection_projections(
obligation.param_env,
obligation.cause.clone(),
obligation.recursion_depth + 1,
infer_predicate.projection_ty,
infer_predicate.projection_term,
&mut nested_obligations,
)
})
} else {
infer_predicate.projection_ty
infer_predicate.projection_term
};
let is_match = self

View file

@ -166,11 +166,8 @@ pub fn clause_obligations<'tcx>(
wf.compute(ty.into());
}
ty::ClauseKind::Projection(t) => {
wf.compute_alias(t.projection_ty);
wf.compute(match t.term.unpack() {
ty::TermKind::Ty(ty) => ty.into(),
ty::TermKind::Const(c) => c.into(),
})
wf.compute_alias_term(t.projection_term);
wf.compute(t.term.into_arg());
}
ty::ClauseKind::ConstArgHasType(ct, ty) => {
wf.compute(ct.into());
@ -440,7 +437,13 @@ fn compute_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
/// Pushes the obligations required for an alias (except inherent) to be WF
/// into `self.out`.
fn compute_alias(&mut self, data: ty::AliasTy<'tcx>) {
fn compute_alias_ty(&mut self, data: ty::AliasTy<'tcx>) {
self.compute_alias_term(data.into());
}
/// Pushes the obligations required for an alias (except inherent) to be WF
/// into `self.out`.
fn compute_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
// A projection is well-formed if
//
// (a) its predicates hold (*)
@ -699,7 +702,7 @@ fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
}
ty::Alias(ty::Projection | ty::Opaque | ty::Weak, data) => {
self.compute_alias(data);
self.compute_alias_ty(data);
return; // Subtree handled by compute_projection.
}
ty::Alias(ty::Inherent, data) => {

View file

@ -34,14 +34,8 @@ fn normalize_canonicalized_projection_ty<'tcx>(
let selcx = &mut SelectionContext::new(ocx.infcx);
let cause = ObligationCause::dummy();
let mut obligations = vec![];
let answer = traits::normalize_projection_type(
selcx,
param_env,
goal,
cause,
0,
&mut obligations,
);
let answer =
traits::normalize_projection_ty(selcx, param_env, goal, cause, 0, &mut obligations);
ocx.register_obligations(obligations);
// #112047: With projections and opaques, we are able to create opaques that
// are recursive (given some generic parameters of the opaque's type variables).

View file

@ -215,7 +215,7 @@ fn visit_ty(&mut self, ty: Ty<'tcx>) {
self.predicates.push(
ty::Binder::bind_with_vars(
ty::ProjectionPredicate {
projection_ty: shifted_alias_ty,
projection_term: shifted_alias_ty.into(),
term: default_ty.into(),
},
self.bound_vars,

View file

@ -90,8 +90,7 @@ pub trait BoundVars<I: Interner> {
fn has_no_bound_vars(&self) -> bool;
}
// FIXME: Uplift `AliasTy`
pub trait AliasTy<I: Interner>: Copy + DebugWithInfcx<I> + Hash + Eq + Sized {
pub trait AliasTerm<I: Interner>: Copy + DebugWithInfcx<I> + Hash + Eq + Sized {
fn new(
interner: I,
trait_def_id: I::DefId,

View file

@ -39,7 +39,7 @@ pub trait Interner:
// Kinds of tys
type Ty: Ty<Self>;
type Tys: Copy + Debug + Hash + Eq + IntoIterator<Item = Self::Ty>;
type AliasTy: AliasTy<Self>;
type AliasTy: Copy + DebugWithInfcx<Self> + Hash + Eq + Sized;
type ParamTy: Copy + Debug + Hash + Eq;
type BoundTy: Copy + Debug + Hash + Eq;
type PlaceholderTy: PlaceholderLike;
@ -74,6 +74,7 @@ pub trait Interner:
type RegionOutlivesPredicate: Copy + Debug + Hash + Eq;
type TypeOutlivesPredicate: Copy + Debug + Hash + Eq;
type ProjectionPredicate: Copy + Debug + Hash + Eq;
type AliasTerm: AliasTerm<Self>;
type NormalizesTo: Copy + Debug + Hash + Eq;
type SubtypePredicate: Copy + Debug + Hash + Eq;
type CoercePredicate: Copy + Debug + Hash + Eq;

View file

@ -54,7 +54,7 @@
pub use region_kind::*;
pub use ty_info::*;
pub use ty_kind::*;
pub use AliasKind::*;
pub use AliasTyKind::*;
pub use DynKind::*;
pub use InferTy::*;
pub use RegionKind::*;

View file

@ -1,6 +1,7 @@
use std::fmt;
use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable};
#[cfg(feature = "nightly")]
use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable};
use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic};
use crate::inherent::*;
@ -283,7 +284,7 @@ pub fn with_self_ty(&self, tcx: I, self_ty: I::Ty) -> ProjectionPredicate<I> {
debug_assert!(!self_ty.has_escaping_bound_vars());
ProjectionPredicate {
projection_ty: I::AliasTy::new(
projection_term: I::AliasTerm::new(
tcx,
self.def_id,
[self_ty.into()].into_iter().chain(self.args),
@ -294,16 +295,50 @@ pub fn with_self_ty(&self, tcx: I, self_ty: I::Ty) -> ProjectionPredicate<I> {
pub fn erase_self_ty(tcx: I, projection_predicate: ProjectionPredicate<I>) -> Self {
// Assert there is a Self.
projection_predicate.projection_ty.args().type_at(0);
projection_predicate.projection_term.args().type_at(0);
Self {
def_id: projection_predicate.projection_ty.def_id(),
args: tcx.mk_args(&projection_predicate.projection_ty.args()[1..]),
def_id: projection_predicate.projection_term.def_id(),
args: tcx.mk_args(&projection_predicate.projection_term.args()[1..]),
term: projection_predicate.term,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))]
pub enum AliasTermKind {
/// A projection `<Type as Trait>::AssocType`.
/// Can get normalized away if monomorphic enough.
ProjectionTy,
/// An associated type in an inherent `impl`
InherentTy,
/// An opaque type (usually from `impl Trait` in type aliases or function return types)
/// Can only be normalized away in RevealAll mode
OpaqueTy,
/// A type alias that actually checks its trait bounds.
/// Currently only used if the type alias references opaque types.
/// Can always be normalized away.
WeakTy,
/// An unevaluated const coming from a generic const expression.
UnevaluatedConst,
/// An unevaluated const coming from an associated const.
ProjectionConst,
}
impl AliasTermKind {
pub fn descr(self) -> &'static str {
match self {
AliasTermKind::ProjectionTy => "associated type",
AliasTermKind::ProjectionConst => "associated const",
AliasTermKind::InherentTy => "inherent associated type",
AliasTermKind::OpaqueTy => "opaque type",
AliasTermKind::WeakTy => "type alias",
AliasTermKind::UnevaluatedConst => "unevaluated constant",
}
}
}
/// This kind of predicate has no *direct* correspondent in the
/// syntax, but it roughly corresponds to the syntactic forms:
///
@ -327,31 +362,31 @@ pub fn erase_self_ty(tcx: I, projection_predicate: ProjectionPredicate<I>) -> Se
#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))]
pub struct ProjectionPredicate<I: Interner> {
pub projection_ty: I::AliasTy,
pub projection_term: I::AliasTerm,
pub term: I::Term,
}
impl<I: Interner> ProjectionPredicate<I> {
pub fn self_ty(self) -> I::Ty {
self.projection_ty.self_ty()
self.projection_term.self_ty()
}
pub fn with_self_ty(self, tcx: I, self_ty: I::Ty) -> ProjectionPredicate<I> {
Self { projection_ty: self.projection_ty.with_self_ty(tcx, self_ty), ..self }
Self { projection_term: self.projection_term.with_self_ty(tcx, self_ty), ..self }
}
pub fn trait_def_id(self, tcx: I) -> I::DefId {
self.projection_ty.trait_def_id(tcx)
self.projection_term.trait_def_id(tcx)
}
pub fn def_id(self) -> I::DefId {
self.projection_ty.def_id()
self.projection_term.def_id()
}
}
impl<I: Interner> fmt::Debug for ProjectionPredicate<I> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ProjectionPredicate({:?}, {:?})", self.projection_ty, self.term)
write!(f, "ProjectionPredicate({:?}, {:?})", self.projection_term, self.term)
}
}
@ -368,7 +403,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))]
pub struct NormalizesTo<I: Interner> {
pub alias: I::AliasTy,
pub alias: I::AliasTerm,
pub term: I::Term,
}

View file

@ -31,7 +31,7 @@ pub enum DynKind {
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))]
pub enum AliasKind {
pub enum AliasTyKind {
/// A projection `<Type as Trait>::AssocType`.
/// Can get normalized away if monomorphic enough.
Projection,
@ -46,13 +46,13 @@ pub enum AliasKind {
Weak,
}
impl AliasKind {
impl AliasTyKind {
pub fn descr(self) -> &'static str {
match self {
AliasKind::Projection => "associated type",
AliasKind::Inherent => "inherent associated type",
AliasKind::Opaque => "opaque type",
AliasKind::Weak => "type alias",
AliasTyKind::Projection => "associated type",
AliasTyKind::Inherent => "inherent associated type",
AliasTyKind::Opaque => "opaque type",
AliasTyKind::Weak => "type alias",
}
}
}
@ -201,7 +201,7 @@ pub enum TyKind<I: Interner> {
/// A projection, opaque type, weak type alias, or inherent associated type.
/// All of these types are represented as pairs of def-id and args, and can
/// be normalized, so they are grouped conceptually.
Alias(AliasKind, I::AliasTy),
Alias(AliasTyKind, I::AliasTy),
/// A type parameter; for example, `T` in `fn f<T>(x: T) {}`.
Param(I::ParamTy),

View file

@ -897,6 +897,12 @@ pub struct AliasTy {
pub args: GenericArgs,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AliasTerm {
pub def_id: AliasDef,
pub args: GenericArgs,
}
pub type PolyFnSig = Binder<FnSig>;
#[derive(Clone, Debug, Eq, PartialEq)]
@ -1350,7 +1356,7 @@ pub struct TraitPredicate {
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjectionPredicate {
pub projection_ty: AliasTy,
pub projection_term: AliasTerm,
pub term: TermKind,
}

View file

@ -453,7 +453,15 @@ fn clean_projection_predicate<'tcx>(
cx: &mut DocContext<'tcx>,
) -> WherePredicate {
WherePredicate::EqPredicate {
lhs: clean_projection(pred.map_bound(|p| p.projection_ty), cx, None),
lhs: clean_projection(
pred.map_bound(|p| {
// FIXME: This needs to be made resilient for `AliasTerm`s that
// are associated consts.
p.projection_term.expect_ty(cx.tcx)
}),
cx,
None,
),
rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
}
}
@ -838,7 +846,7 @@ fn clean_ty_generics<'tcx>(
}
}
ty::ClauseKind::Projection(p) => {
if let ty::Param(param) = p.projection_ty.self_ty().kind() {
if let ty::Param(param) = p.projection_term.self_ty().kind() {
projection = Some(bound_p.rebind(p));
return Some(param.index);
}
@ -857,7 +865,15 @@ fn clean_ty_generics<'tcx>(
bounds.extend(pred.get_bounds().into_iter().flatten().cloned());
if let Some(proj) = projection
&& let lhs = clean_projection(proj.map_bound(|p| p.projection_ty), cx, None)
&& let lhs = clean_projection(
proj.map_bound(|p| {
// FIXME: This needs to be made resilient for `AliasTerm`s that
// are associated consts.
p.projection_term.expect_ty(cx.tcx)
}),
cx,
None,
)
&& let Some((_, trait_did, name)) = lhs.projection()
{
impl_trait_proj.entry(param_idx).or_default().push((
@ -2126,7 +2142,10 @@ pub(crate) fn clean_middle_ty<'tcx>(
// HACK(compiler-errors): Doesn't actually matter what self
// type we put here, because we're only using the GAT's args.
.with_self_ty(cx.tcx, cx.tcx.types.self_param)
.projection_ty
.projection_term
// FIXME: This needs to be made resilient for `AliasTerm`s
// that are associated consts.
.expect_ty(cx.tcx)
}),
cx,
),
@ -2284,10 +2303,12 @@ fn clean_middle_opaque_bounds<'tcx>(
.iter()
.filter_map(|bound| {
if let ty::ClauseKind::Projection(proj) = bound.kind().skip_binder() {
if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
if proj.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder() {
Some(TypeBinding {
assoc: projection_to_path_segment(
bound.kind().rebind(proj.projection_ty),
// FIXME: This needs to be made resilient for `AliasTerm`s that
// are associated consts.
bound.kind().rebind(proj.projection_term.expect_ty(cx.tcx)),
cx,
),
kind: TypeBindingKind::Equality {

View file

@ -417,7 +417,7 @@ fn get_input_traits_and_projections<'tcx>(
}
},
ClauseKind::Projection(projection_predicate) => {
if projection_predicate.projection_ty.self_ty() == input {
if projection_predicate.projection_term.self_ty() == input {
projection_predicates.push(projection_predicate);
}
},

View file

@ -320,11 +320,11 @@ fn is_mixed_projection_predicate<'tcx>(
&& (term_param_ty.index as usize) < generics.parent_count
{
// The inner-most self type is a type parameter from the current function.
let mut projection_ty = projection_predicate.projection_ty;
let mut projection_term = projection_predicate.projection_term;
loop {
match projection_ty.self_ty().kind() {
match *projection_term.self_ty().kind() {
ty::Alias(ty::Projection, inner_projection_ty) => {
projection_ty = *inner_projection_ty;
projection_term = inner_projection_ty.into();
},
ty::Param(param_ty) => {
return (param_ty.index as usize) >= generics.parent_count;
@ -404,14 +404,11 @@ fn replace_types<'tcx>(
// The `replaced.insert(...)` check provides some protection against infinite loops.
if replaced.insert(param_ty.index) {
for projection_predicate in projection_predicates {
if projection_predicate.projection_ty.self_ty() == param_ty.to_ty(cx.tcx)
if projection_predicate.projection_term.self_ty() == param_ty.to_ty(cx.tcx)
&& let Some(term_ty) = projection_predicate.term.ty()
&& let ty::Param(term_param_ty) = term_ty.kind()
{
let projection = cx.tcx.mk_ty_from_kind(ty::Alias(
ty::Projection,
projection_predicate.projection_ty.with_self_ty(cx.tcx, new_ty),
));
let projection = projection_predicate.projection_term.with_self_ty(cx.tcx, new_ty).expect_ty(cx.tcx).to_ty(cx.tcx);
if let Ok(projected_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, projection)
&& args[term_param_ty.index as usize] != GenericArg::from(projected_ty)

View file

@ -66,7 +66,7 @@ fn get_projection_pred<'tcx>(
let projection_pred = cx
.tcx
.instantiate_bound_regions_with_erased(proj_pred.kind().rebind(pred));
if projection_pred.projection_ty.args == trait_pred.trait_ref.args {
if projection_pred.projection_term.args == trait_pred.trait_ref.args {
return Some(projection_pred);
}
}

View file

@ -795,7 +795,7 @@ fn sig_from_bounds<'tcx>(
inputs = Some(i);
},
ty::ClauseKind::Projection(p)
if Some(p.projection_ty.def_id) == lang_items.fn_once_output() && p.projection_ty.self_ty() == ty =>
if Some(p.projection_term.def_id) == lang_items.fn_once_output() && p.projection_term.self_ty() == ty =>
{
if output.is_some() {
// Multiple different fn trait impls. Is this even allowed?
@ -834,7 +834,7 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option
}
inputs = Some(i);
},
ty::ClauseKind::Projection(p) if Some(p.projection_ty.def_id) == lang_items.fn_once_output() => {
ty::ClauseKind::Projection(p) if Some(p.projection_term.def_id) == lang_items.fn_once_output() => {
if output.is_some() {
// Multiple different fn trait impls. Is this even allowed?
return None;

View file

@ -1,5 +1,6 @@
//@ aux-crate:assoc_const_equality=assoc-const-equality.rs
//@ edition:2021
//@ ignore-test (FIXME: #125092)
#![crate_name = "user"]

View file

@ -11,7 +11,6 @@ impl TraitWAssocConst for impl Demo { //~ ERROR E0404
fn foo<A: TraitWAssocConst<A=32>>() { //~ ERROR E0658
foo::<Demo>()();
//~^ ERROR is not satisfied
//~| ERROR type mismatch
//~| ERROR expected function, found `()`
}
@ -19,6 +18,5 @@ fn main<A: TraitWAssocConst<A=32>>() {
//~^ ERROR E0658
//~| ERROR E0131
foo::<Demo>();
//~^ ERROR type mismatch
//~| ERROR is not satisfied
//~^ ERROR is not satisfied
}

View file

@ -26,7 +26,7 @@ LL | fn foo<A: TraitWAssocConst<A=32>>() {
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
error[E0658]: associated const equality is incomplete
--> $DIR/issue-105330.rs:18:29
--> $DIR/issue-105330.rs:17:29
|
LL | fn main<A: TraitWAssocConst<A=32>>() {
| ^^^^
@ -44,7 +44,7 @@ LL | impl TraitWAssocConst for impl Demo {
= note: `impl Trait` is only allowed in arguments and return types of functions and methods
error[E0131]: `main` function is not allowed to have generic parameters
--> $DIR/issue-105330.rs:18:8
--> $DIR/issue-105330.rs:17:8
|
LL | fn main<A: TraitWAssocConst<A=32>>() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` cannot have generic parameters
@ -61,20 +61,6 @@ note: required by a bound in `foo`
LL | fn foo<A: TraitWAssocConst<A=32>>() {
| ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `foo`
error[E0271]: type mismatch resolving `<Demo as TraitWAssocConst>::A == 32`
--> $DIR/issue-105330.rs:12:11
|
LL | foo::<Demo>()();
| ^^^^ expected `32`, found `<Demo as TraitWAssocConst>::A`
|
= note: expected constant `32`
found constant `<Demo as TraitWAssocConst>::A`
note: required by a bound in `foo`
--> $DIR/issue-105330.rs:11:28
|
LL | fn foo<A: TraitWAssocConst<A=32>>() {
| ^^^^ required by this bound in `foo`
error[E0618]: expected function, found `()`
--> $DIR/issue-105330.rs:12:5
|
@ -86,7 +72,7 @@ LL | foo::<Demo>()();
| call expression requires function
error[E0277]: the trait bound `Demo: TraitWAssocConst` is not satisfied
--> $DIR/issue-105330.rs:21:11
--> $DIR/issue-105330.rs:20:11
|
LL | foo::<Demo>();
| ^^^^ the trait `TraitWAssocConst` is not implemented for `Demo`
@ -97,21 +83,7 @@ note: required by a bound in `foo`
LL | fn foo<A: TraitWAssocConst<A=32>>() {
| ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `foo`
error[E0271]: type mismatch resolving `<Demo as TraitWAssocConst>::A == 32`
--> $DIR/issue-105330.rs:21:11
|
LL | foo::<Demo>();
| ^^^^ expected `32`, found `<Demo as TraitWAssocConst>::A`
|
= note: expected constant `32`
found constant `<Demo as TraitWAssocConst>::A`
note: required by a bound in `foo`
--> $DIR/issue-105330.rs:11:28
|
LL | fn foo<A: TraitWAssocConst<A=32>>() {
| ^^^^ required by this bound in `foo`
error: aborting due to 9 previous errors
error: aborting due to 11 previous errors
Some errors have detailed explanations: E0131, E0271, E0277, E0404, E0562, E0618, E0658.
Some errors have detailed explanations: E0131, E0277, E0404, E0562, E0618, E0658.
For more information about an error, try `rustc --explain E0131`.