Skip to content

Commit b4c4664

Browse files
committed
Auto merge of #118118 - spastorino:do-not-erase-late-bound-regions-on-iat, r=compiler-errors
Do not erase late bound regions when selecting inherent associated types In the fix for #97156 we would want the following code: ```rust #![feature(inherent_associated_types)] #![allow(incomplete_features)] struct Foo<T>(T); impl Foo<fn(&'static ())> { type Assoc = u32; } trait Other {} impl Other for u32 {} // FIXME(inherent_associated_types): Avoid emitting two diagnostics (they only differ in span). // FIXME(inherent_associated_types): Enhancement: Spruce up the diagnostic by saying something like // "implementation is not general enough" as is done for traits via // `try_report_trait_placeholder_mismatch`. fn bar(_: Foo<for<'a> fn(&'a ())>::Assoc) {} //~^ ERROR mismatched types //~| ERROR mismatched types fn main() {} ``` to fail with ... ``` error[E0220]: associated type `Assoc` not found for `Foo<for<'a> fn(&'a ())>` in the current scope --> tests/ui/associated-inherent-types/issue-109789.rs:18:36 | 4 | struct Foo<T>(T); | ------------- associated item `Assoc` not found for this struct ... 18 | fn bar(_: Foo<for<'a> fn(&'a ())>::Assoc) {} | ^^^^^ associated item not found in `Foo<for<'a> fn(&'a ())>` | = note: the associated type was found for - `Foo<fn(&'static ())>` error: aborting due to previous error For more information about this error, try `rustc --explain E0220`. ``` This PR fixes the ICE we are currently getting "was a subtype of Foo<Binder(fn(&ReStatic ()), [])> during selection but now it is not" Also fixes #112631 r? `@lcnr`
2 parents 9f15a88 + 440f46d commit b4c4664

File tree

5 files changed

+128
-117
lines changed

5 files changed

+128
-117
lines changed

compiler/rustc_hir_analysis/src/astconv/mod.rs

+92-115
Original file line numberDiff line numberDiff line change
@@ -26,21 +26,21 @@ use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
2626
use rustc_hir::def_id::{DefId, LocalDefId};
2727
use rustc_hir::intravisit::{walk_generics, Visitor as _};
2828
use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
29-
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
29+
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
3030
use rustc_infer::traits::ObligationCause;
3131
use rustc_middle::middle::stability::AllowUnstable;
3232
use rustc_middle::ty::GenericParamDefKind;
3333
use rustc_middle::ty::{
34-
self, Const, GenericArgKind, GenericArgsRef, IsSuggestable, Ty, TyCtxt, TypeVisitableExt,
34+
self, Const, GenericArgKind, GenericArgsRef, IsSuggestable, ParamEnv, Ty, TyCtxt,
35+
TypeVisitableExt,
3536
};
3637
use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
3738
use rustc_span::edit_distance::find_best_match_for_name;
3839
use rustc_span::symbol::{kw, Ident, Symbol};
3940
use rustc_span::{sym, BytePos, Span, DUMMY_SP};
4041
use rustc_target::spec::abi;
4142
use rustc_trait_selection::traits::wf::object_region_bounds;
42-
use rustc_trait_selection::traits::{self, NormalizeExt, ObligationCtxt};
43-
use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
43+
use rustc_trait_selection::traits::{self, ObligationCtxt};
4444

4545
use std::fmt::Display;
4646
use std::slice;
@@ -1606,133 +1606,110 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
16061606
// FIXME(inherent_associated_types): Acquiring the ParamEnv this early leads to cycle errors
16071607
// when inside of an ADT (#108491) or where clause.
16081608
let param_env = tcx.param_env(block.owner);
1609-
let cause = ObligationCause::misc(span, block.owner.def_id);
16101609

1611-
let mut fulfillment_errors = Vec::new();
1612-
let mut applicable_candidates: Vec<_> = infcx.probe(|_| {
1613-
// Regions are not considered during selection.
1614-
let self_ty = self_ty
1615-
.fold_with(&mut BoundVarEraser { tcx, universe: infcx.create_next_universe() });
1616-
1617-
struct BoundVarEraser<'tcx> {
1618-
tcx: TyCtxt<'tcx>,
1619-
universe: ty::UniverseIndex,
1620-
}
1621-
1622-
// FIXME(non_lifetime_binders): Don't assign the same universe to each placeholder.
1623-
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for BoundVarEraser<'tcx> {
1624-
fn interner(&self) -> TyCtxt<'tcx> {
1625-
self.tcx
1626-
}
1610+
let mut universes = if self_ty.has_escaping_bound_vars() {
1611+
vec![None; self_ty.outer_exclusive_binder().as_usize()]
1612+
} else {
1613+
vec![]
1614+
};
16271615

1628-
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1629-
// FIXME(@lcnr): This is broken, erasing bound regions
1630-
// impacts selection as it results in different types.
1631-
if r.is_bound() { self.tcx.lifetimes.re_erased } else { r }
1632-
}
1616+
let (impl_, (assoc_item, def_scope)) =
1617+
crate::traits::project::with_replaced_escaping_bound_vars(
1618+
infcx,
1619+
&mut universes,
1620+
self_ty,
1621+
|self_ty| {
1622+
self.select_inherent_assoc_type_candidates(
1623+
infcx, name, span, self_ty, param_env, candidates,
1624+
)
1625+
},
1626+
)?;
1627+
1628+
self.check_assoc_ty(assoc_item, name, def_scope, block, span);
1629+
1630+
// FIXME(fmease): Currently creating throwaway `parent_args` to please
1631+
// `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to
1632+
// not require the parent args logic.
1633+
let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1634+
let args = self.create_args_for_associated_item(span, assoc_item, segment, parent_args);
1635+
let args = tcx.mk_args_from_iter(
1636+
std::iter::once(ty::GenericArg::from(self_ty))
1637+
.chain(args.into_iter().skip(parent_args.len())),
1638+
);
16331639

1634-
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1635-
match *ty.kind() {
1636-
ty::Bound(_, bv) => Ty::new_placeholder(
1637-
self.tcx,
1638-
ty::PlaceholderType { universe: self.universe, bound: bv },
1639-
),
1640-
_ => ty.super_fold_with(self),
1641-
}
1642-
}
1640+
let ty = Ty::new_alias(tcx, ty::Inherent, ty::AliasTy::new(tcx, assoc_item, args));
16431641

1644-
fn fold_const(
1645-
&mut self,
1646-
ct: ty::Const<'tcx>,
1647-
) -> <TyCtxt<'tcx> as rustc_type_ir::Interner>::Const {
1648-
assert!(!ct.ty().has_escaping_bound_vars());
1649-
1650-
match ct.kind() {
1651-
ty::ConstKind::Bound(_, bv) => ty::Const::new_placeholder(
1652-
self.tcx,
1653-
ty::PlaceholderConst { universe: self.universe, bound: bv },
1654-
ct.ty(),
1655-
),
1656-
_ => ct.super_fold_with(self),
1657-
}
1658-
}
1659-
}
1642+
Ok(Some((ty, assoc_item)))
1643+
}
16601644

1661-
let InferOk { value: self_ty, obligations } =
1662-
infcx.at(&cause, param_env).normalize(self_ty);
1645+
fn select_inherent_assoc_type_candidates(
1646+
&self,
1647+
infcx: &InferCtxt<'tcx>,
1648+
name: Ident,
1649+
span: Span,
1650+
self_ty: Ty<'tcx>,
1651+
param_env: ParamEnv<'tcx>,
1652+
candidates: Vec<(DefId, (DefId, DefId))>,
1653+
) -> Result<(DefId, (DefId, DefId)), ErrorGuaranteed> {
1654+
let tcx = self.tcx();
1655+
let mut fulfillment_errors = Vec::new();
16631656

1664-
candidates
1665-
.iter()
1666-
.copied()
1667-
.filter(|&(impl_, _)| {
1668-
infcx.probe(|_| {
1669-
let ocx = ObligationCtxt::new(infcx);
1670-
ocx.register_obligations(obligations.clone());
1671-
1672-
let impl_args = infcx.fresh_args_for_item(span, impl_);
1673-
let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
1674-
let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1675-
1676-
// Check that the self types can be related.
1677-
if ocx.eq(&ObligationCause::dummy(), param_env, impl_ty, self_ty).is_err() {
1678-
return false;
1679-
}
1657+
let applicable_candidates: Vec<_> = candidates
1658+
.iter()
1659+
.copied()
1660+
.filter(|&(impl_, _)| {
1661+
infcx.probe(|_| {
1662+
let ocx = ObligationCtxt::new(infcx);
1663+
let self_ty = ocx.normalize(&ObligationCause::dummy(), param_env, self_ty);
1664+
1665+
let impl_args = infcx.fresh_args_for_item(span, impl_);
1666+
let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
1667+
let impl_ty = ocx.normalize(&ObligationCause::dummy(), param_env, impl_ty);
1668+
1669+
// Check that the self types can be related.
1670+
if ocx.eq(&ObligationCause::dummy(), param_env, impl_ty, self_ty).is_err() {
1671+
return false;
1672+
}
16801673

1681-
// Check whether the impl imposes obligations we have to worry about.
1682-
let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
1683-
let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds);
1684-
let impl_obligations = traits::predicates_for_generics(
1685-
|_, _| cause.clone(),
1686-
param_env,
1687-
impl_bounds,
1688-
);
1689-
ocx.register_obligations(impl_obligations);
1674+
// Check whether the impl imposes obligations we have to worry about.
1675+
let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
1676+
let impl_bounds =
1677+
ocx.normalize(&ObligationCause::dummy(), param_env, impl_bounds);
1678+
let impl_obligations = traits::predicates_for_generics(
1679+
|_, _| ObligationCause::dummy(),
1680+
param_env,
1681+
impl_bounds,
1682+
);
1683+
ocx.register_obligations(impl_obligations);
16901684

1691-
let mut errors = ocx.select_where_possible();
1692-
if !errors.is_empty() {
1693-
fulfillment_errors.append(&mut errors);
1694-
return false;
1695-
}
1685+
let mut errors = ocx.select_where_possible();
1686+
if !errors.is_empty() {
1687+
fulfillment_errors.append(&mut errors);
1688+
return false;
1689+
}
16961690

1697-
true
1698-
})
1691+
true
16991692
})
1700-
.collect()
1701-
});
1693+
})
1694+
.collect();
17021695

1703-
if applicable_candidates.len() > 1 {
1704-
return Err(self.complain_about_ambiguous_inherent_assoc_type(
1696+
match &applicable_candidates[..] {
1697+
&[] => Err(self.complain_about_inherent_assoc_type_not_found(
17051698
name,
1706-
applicable_candidates.into_iter().map(|(_, (candidate, _))| candidate).collect(),
1699+
self_ty,
1700+
candidates,
1701+
fulfillment_errors,
17071702
span,
1708-
));
1709-
}
1703+
)),
17101704

1711-
if let Some((impl_, (assoc_item, def_scope))) = applicable_candidates.pop() {
1712-
self.check_assoc_ty(assoc_item, name, def_scope, block, span);
1713-
1714-
// FIXME(fmease): Currently creating throwaway `parent_args` to please
1715-
// `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to
1716-
// not require the parent args logic.
1717-
let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1718-
let args = self.create_args_for_associated_item(span, assoc_item, segment, parent_args);
1719-
let args = tcx.mk_args_from_iter(
1720-
std::iter::once(ty::GenericArg::from(self_ty))
1721-
.chain(args.into_iter().skip(parent_args.len())),
1722-
);
1723-
1724-
let ty = Ty::new_alias(tcx, ty::Inherent, ty::AliasTy::new(tcx, assoc_item, args));
1705+
&[applicable_candidate] => Ok(applicable_candidate),
17251706

1726-
return Ok(Some((ty, assoc_item)));
1707+
&[_, ..] => Err(self.complain_about_ambiguous_inherent_assoc_type(
1708+
name,
1709+
applicable_candidates.into_iter().map(|(_, (candidate, _))| candidate).collect(),
1710+
span,
1711+
)),
17271712
}
1728-
1729-
Err(self.complain_about_inherent_assoc_type_not_found(
1730-
name,
1731-
self_ty,
1732-
candidates,
1733-
fulfillment_errors,
1734-
span,
1735-
))
17361713
}
17371714

17381715
fn lookup_assoc_ty(

compiler/rustc_trait_selection/src/traits/project.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -1454,7 +1454,18 @@ pub fn compute_inherent_assoc_ty_args<'a, 'b, 'tcx>(
14541454

14551455
// Infer the generic parameters of the impl by unifying the
14561456
// impl type with the self type of the projection.
1457-
let self_ty = alias_ty.self_ty();
1457+
let mut self_ty = alias_ty.self_ty();
1458+
if !selcx.infcx.next_trait_solver() {
1459+
self_ty = normalize_with_depth_to(
1460+
selcx,
1461+
param_env,
1462+
cause.clone(),
1463+
depth + 1,
1464+
self_ty,
1465+
obligations,
1466+
);
1467+
}
1468+
14581469
match selcx.infcx.at(&cause, param_env).eq(DefineOpaqueTypes::No, impl_ty, self_ty) {
14591470
Ok(mut ok) => obligations.append(&mut ok.obligations),
14601471
Err(_) => {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// check-pass
2+
3+
#![feature(inherent_associated_types)]
4+
#![allow(incomplete_features)]
5+
6+
struct Foo<T>(T);
7+
8+
impl<'a> Foo<fn(&'a ())> {
9+
type Assoc = &'a ();
10+
}
11+
12+
fn bar(_: for<'a> fn(Foo<fn(Foo<fn(&'static ())>::Assoc)>::Assoc)) {}
13+
14+
fn main() {}

tests/ui/associated-inherent-types/issue-111404-1.rs

+1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@ impl<'a> Foo<fn(&'a ())> {
99

1010
fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
1111
//~^ ERROR higher-ranked subtype error
12+
//~| ERROR higher-ranked subtype error
1213

1314
fn main() {}

tests/ui/associated-inherent-types/issue-111404-1.stderr

+9-1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,13 @@ error: higher-ranked subtype error
44
LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
55
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66

7-
error: aborting due to 1 previous error
7+
error: higher-ranked subtype error
8+
--> $DIR/issue-111404-1.rs:10:1
9+
|
10+
LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
|
13+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
14+
15+
error: aborting due to 2 previous errors
816

0 commit comments

Comments
 (0)