Skip to content

Commit

Permalink
Auto merge of rust-lang#118118 - spastorino:do-not-erase-late-bound-r…
Browse files Browse the repository at this point in the history
…egions-on-iat, r=<try>

Do not erase late bound regions when selecting inherent associated types

In the fix for rust-lang#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 rust-lang#112631

r? `@lcnr`
  • Loading branch information
bors committed Nov 24, 2023
2 parents b06258c + 42fc2f9 commit 2fe97f4
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 125 deletions.
221 changes: 105 additions & 116 deletions compiler/rustc_hir_analysis/src/astconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,21 @@ use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::{walk_generics, Visitor as _};
use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_infer::traits::ObligationCause;
use rustc_infer::traits::{Obligation, ObligationCause};
use rustc_middle::middle::stability::AllowUnstable;
use rustc_middle::ty::GenericParamDefKind;
use rustc_middle::ty::{
self, Const, GenericArgKind, GenericArgsRef, IsSuggestable, Ty, TyCtxt, TypeVisitableExt,
self, Const, GenericArgKind, GenericArgsRef, IsSuggestable, ParamEnv, Predicate, Ty, TyCtxt,
TypeFoldable, TypeVisitableExt,
};
use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::symbol::{kw, Ident, Symbol};
use rustc_span::{sym, BytePos, Span, DUMMY_SP};
use rustc_target::spec::abi;
use rustc_trait_selection::solve::eval_ctxt::canonical::EagerResolver;
use rustc_trait_selection::traits::wf::object_region_bounds;
use rustc_trait_selection::traits::{self, NormalizeExt, ObligationCtxt};
use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};

use std::fmt::Display;
use std::slice;
Expand Down Expand Up @@ -1608,134 +1609,122 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let param_env = tcx.param_env(block.owner);
let cause = ObligationCause::misc(span, block.owner.def_id);

let mut fulfillment_errors = Vec::new();
let mut applicable_candidates: Vec<_> = infcx.probe(|_| {
// Regions are not considered during selection.
let self_ty = self_ty
.fold_with(&mut BoundVarEraser { tcx, universe: infcx.create_next_universe() });

struct BoundVarEraser<'tcx> {
tcx: TyCtxt<'tcx>,
universe: ty::UniverseIndex,
}

// FIXME(non_lifetime_binders): Don't assign the same universe to each placeholder.
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for BoundVarEraser<'tcx> {
fn interner(&self) -> TyCtxt<'tcx> {
self.tcx
}
let mut universes = if self_ty.has_escaping_bound_vars() {
vec![None; self_ty.outer_exclusive_binder().as_usize()]
} else {
vec![]
};

fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
// FIXME(@lcnr): This is broken, erasing bound regions
// impacts selection as it results in different types.
if r.is_bound() { self.tcx.lifetimes.re_erased } else { r }
}
crate::traits::project::with_replaced_escaping_bound_vars(
infcx,
&mut universes,
self_ty,
|self_ty| {
let tcx = self.tcx();
let InferOk { value: self_ty, obligations } =
infcx.at(&cause, param_env).normalize(self_ty);

let (impl_, (assoc_item, def_scope)) = self.select_inherent_assoc_type_candidates(
infcx,
name,
span,
self_ty,
cause,
param_env,
obligations,
candidates,
)?;

self.check_assoc_ty(assoc_item, name, def_scope, block, span);

// FIXME(fmease): Currently creating throwaway `parent_args` to please
// `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to
// not require the parent args logic.
let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
let args =
self.create_args_for_associated_item(span, assoc_item, segment, parent_args);
let args = tcx.mk_args_from_iter(
std::iter::once(ty::GenericArg::from(self_ty))
.chain(args.into_iter().skip(parent_args.len())),
);

fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
match *ty.kind() {
ty::Bound(_, bv) => Ty::new_placeholder(
self.tcx,
ty::PlaceholderType { universe: self.universe, bound: bv },
),
_ => ty.super_fold_with(self),
}
}
let ty = Ty::new_alias(tcx, ty::Inherent, ty::AliasTy::new(tcx, assoc_item, args));
let ty = ty.fold_with(&mut EagerResolver { infcx });

fn fold_const(
&mut self,
ct: ty::Const<'tcx>,
) -> <TyCtxt<'tcx> as rustc_type_ir::Interner>::Const {
assert!(!ct.ty().has_escaping_bound_vars());

match ct.kind() {
ty::ConstKind::Bound(_, bv) => ty::Const::new_placeholder(
self.tcx,
ty::PlaceholderConst { universe: self.universe, bound: bv },
ct.ty(),
),
_ => ct.super_fold_with(self),
}
}
}
Ok(Some((ty, assoc_item)))
},
)
}

let InferOk { value: self_ty, obligations } =
infcx.at(&cause, param_env).normalize(self_ty);
fn select_inherent_assoc_type_candidates(
&self,
infcx: &InferCtxt<'tcx>,
name: Ident,
span: Span,
self_ty: Ty<'tcx>,
cause: ObligationCause<'tcx>,
param_env: ParamEnv<'tcx>,
obligations: Vec<Obligation<'tcx, Predicate<'tcx>>>,
candidates: Vec<(DefId, (DefId, DefId))>,
) -> Result<(DefId, (DefId, DefId)), ErrorGuaranteed> {
let tcx = self.tcx();
let mut fulfillment_errors = Vec::new();

candidates
.iter()
.copied()
.filter(|&(impl_, _)| {
infcx.probe(|_| {
let ocx = ObligationCtxt::new(infcx);
ocx.register_obligations(obligations.clone());

let impl_args = infcx.fresh_args_for_item(span, impl_);
let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
let impl_ty = ocx.normalize(&cause, param_env, impl_ty);

// Check that the self types can be related.
// FIXME(inherent_associated_types): Should we use `eq` here? Method probing uses
// `sup` for this situtation, too. What for? To constrain inference variables?
if ocx.sup(&ObligationCause::dummy(), param_env, impl_ty, self_ty).is_err()
{
return false;
}
let applicable_candidates: Vec<_> = candidates
.iter()
.copied()
.filter(|&(impl_, _)| {
infcx.probe(|_| {
let ocx = ObligationCtxt::new(infcx);
ocx.register_obligations(obligations.clone());

let impl_args = infcx.fresh_args_for_item(span, impl_);
let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
let impl_ty = ocx.normalize(&cause, param_env, impl_ty);

// Check that the self types can be related.
if ocx.eq(&ObligationCause::dummy(), param_env, impl_ty, self_ty).is_err() {
return false;
}

// Check whether the impl imposes obligations we have to worry about.
let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds);
let impl_obligations = traits::predicates_for_generics(
|_, _| cause.clone(),
param_env,
impl_bounds,
);
ocx.register_obligations(impl_obligations);
// Check whether the impl imposes obligations we have to worry about.
let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds);
let impl_obligations = traits::predicates_for_generics(
|_, _| cause.clone(),
param_env,
impl_bounds,
);
ocx.register_obligations(impl_obligations);

let mut errors = ocx.select_where_possible();
if !errors.is_empty() {
fulfillment_errors.append(&mut errors);
return false;
}
let mut errors = ocx.select_where_possible();
if !errors.is_empty() {
fulfillment_errors.append(&mut errors);
return false;
}

true
})
true
})
.collect()
});
})
.collect();

if applicable_candidates.len() > 1 {
return Err(self.complain_about_ambiguous_inherent_assoc_type(
match &applicable_candidates[..] {
&[] => Err(self.complain_about_inherent_assoc_type_not_found(
name,
applicable_candidates.into_iter().map(|(_, (candidate, _))| candidate).collect(),
self_ty,
candidates,
fulfillment_errors,
span,
));
}

if let Some((impl_, (assoc_item, def_scope))) = applicable_candidates.pop() {
self.check_assoc_ty(assoc_item, name, def_scope, block, span);

// FIXME(fmease): Currently creating throwaway `parent_args` to please
// `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to
// not require the parent args logic.
let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
let args = self.create_args_for_associated_item(span, assoc_item, segment, parent_args);
let args = tcx.mk_args_from_iter(
std::iter::once(ty::GenericArg::from(self_ty))
.chain(args.into_iter().skip(parent_args.len())),
);
)),

let ty = Ty::new_alias(tcx, ty::Inherent, ty::AliasTy::new(tcx, assoc_item, args));
&[applicable_candidate] => Ok(applicable_candidate),

return Ok(Some((ty, assoc_item)));
&[_, ..] => Err(self.complain_about_ambiguous_inherent_assoc_type(
name,
applicable_candidates.into_iter().map(|(_, (candidate, _))| candidate).collect(),
span,
)),
}

Err(self.complain_about_inherent_assoc_type_not_found(
name,
self_ty,
candidates,
fulfillment_errors,
span,
))
}

fn lookup_assoc_ty(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
}

/// Resolves ty, region, and const vars to their inferred values or their root vars.
struct EagerResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'tcx>,
pub struct EagerResolver<'a, 'tcx> {
pub infcx: &'a InferCtxt<'tcx>,
}

impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EagerResolver<'_, 'tcx> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use super::{search_graph, GoalEvaluationKind};
use super::{search_graph::SearchGraph, Goal};
pub use select::InferCtxtSelectExt;

mod canonical;
pub mod canonical;
mod commit_if_ok;
mod probe;
mod select;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/solve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use rustc_middle::ty::{
mod alias_relate;
mod assembly;
mod canonicalize;
mod eval_ctxt;
pub mod eval_ctxt;
mod fulfill;
pub mod inspect;
mod normalize;
Expand Down
22 changes: 18 additions & 4 deletions compiler/rustc_trait_selection/src/traits/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> {
&mut self,
t: ty::Binder<'tcx, T>,
) -> ty::Binder<'tcx, T> {
if !t.has_placeholders() && !t.has_infer_regions() {
if !t.has_placeholders() && !t.has_infer() {
return t;
}
self.current_index.shift_in(1);
Expand Down Expand Up @@ -1048,6 +1048,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> {
}

fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
let ty = self.infcx.shallow_resolve(ty);
match *ty.kind() {
ty::Placeholder(p) => {
let replace_var = self.mapped_types.get(&p);
Expand All @@ -1063,16 +1064,23 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> {
);
Ty::new_bound(self.infcx.tcx, db, *replace_var)
}
None => ty,
None => {
if ty.has_infer() {
ty.super_fold_with(self)
} else {
ty
}
}
}
}

_ if ty.has_placeholders() || ty.has_infer_regions() => ty.super_fold_with(self),
_ if ty.has_placeholders() || ty.has_infer() => ty.super_fold_with(self),
_ => ty,
}
}

fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
let ct = self.infcx.shallow_resolve(ct);
if let ty::ConstKind::Placeholder(p) = ct.kind() {
let replace_var = self.mapped_consts.get(&p);
match replace_var {
Expand All @@ -1087,7 +1095,13 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> {
);
ty::Const::new_bound(self.infcx.tcx, db, *replace_var, ct.ty())
}
None => ct,
None => {
if ct.has_infer() {
ct.super_fold_with(self)
} else {
ct
}
}
}
} else {
ct.super_fold_with(self)
Expand Down
1 change: 1 addition & 0 deletions tests/ui/associated-inherent-types/issue-111404-1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ impl<'a> Foo<fn(&'a ())> {

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

fn main() {}
10 changes: 9 additions & 1 deletion tests/ui/associated-inherent-types/issue-111404-1.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,13 @@ error: higher-ranked subtype error
LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error
error: higher-ranked subtype error
--> $DIR/issue-111404-1.rs:10:1
|
LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`

error: aborting due to 2 previous errors

0 comments on commit 2fe97f4

Please sign in to comment.