Skip to content

Commit

Permalink
Auto merge of #112006 - kylematsuda:earlybinder-private, r=jackh726
Browse files Browse the repository at this point in the history
Make `EarlyBinder`'s inner value private

Currently, `EarlyBinder(T)`'s inner value is public, which allows implicitly skipping the binder by indexing into the tuple struct (i.e., `x.0`). `@lcnr` suggested making `EarlyBinder`'s inner value private so users are required to explicitly call `skip_binder` (#105779 (comment)) .

This PR makes the inner value private, adds `EarlyBinder::new` for constructing a new instance, and replaces uses of `x.0` with `x.skip_binder()` (or similar). It also adds some documentation to `EarlyBinder::skip_binder` explaining how to skip the binder of `&EarlyBinder<T>` to get `&T` now that the inner value is private (since previously we could just do `&x.0`).

r? `@lcnr`
  • Loading branch information
bors committed May 28, 2023
2 parents 3fae1b9 + c29c212 commit 1c53407
Show file tree
Hide file tree
Showing 56 changed files with 123 additions and 113 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/src/common.rs
Expand Up @@ -361,7 +361,7 @@ impl<'tcx> FunctionCx<'_, '_, 'tcx> {
self.instance.subst_mir_and_normalize_erasing_regions(
self.tcx,
ty::ParamEnv::reveal_all(),
ty::EarlyBinder(value),
ty::EarlyBinder::new(value),
)
}

Expand Down
Expand Up @@ -93,7 +93,7 @@ fn make_mir_scope<'ll, 'tcx>(
let callee = cx.tcx.subst_and_normalize_erasing_regions(
instance.substs,
ty::ParamEnv::reveal_all(),
ty::EarlyBinder(callee),
ty::EarlyBinder::new(callee),
);
let callee_fn_abi = cx.fn_abi_of_instance(callee, ty::List::empty());
cx.dbg_scope_fn(callee, callee_fn_abi, None)
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/mir/mod.rs
Expand Up @@ -111,7 +111,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
self.instance.subst_mir_and_normalize_erasing_regions(
self.cx.tcx(),
ty::ParamEnv::reveal_all(),
ty::EarlyBinder(value),
ty::EarlyBinder::new(value),
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/eval_context.rs
Expand Up @@ -497,7 +497,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
.try_subst_mir_and_normalize_erasing_regions(
*self.tcx,
self.param_env,
ty::EarlyBinder(value),
ty::EarlyBinder::new(value),
)
.map_err(|_| err_inval!(TooGeneric))
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/astconv/mod.rs
Expand Up @@ -1278,7 +1278,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// params (and trait ref's late bound params). This logic is very similar to
// `Predicate::subst_supertrait`, and it's no coincidence why.
let shifted_output = tcx.shift_bound_var_indices(num_bound_vars, output);
let subst_output = ty::EarlyBinder(shifted_output).subst(tcx, substs);
let subst_output = ty::EarlyBinder::new(shifted_output).subst(tcx, substs);

let bound_vars = tcx.late_bound_vars(binding.hir_id);
ty::Binder::bind_with_vars(subst_output, bound_vars)
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Expand Up @@ -794,14 +794,14 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
})
});
debug!(%ty);
collected_tys.insert(def_id, ty::EarlyBinder(ty));
collected_tys.insert(def_id, ty::EarlyBinder::new(ty));
}
Err(err) => {
let reported = tcx.sess.delay_span_bug(
return_span,
format!("could not fully resolve: {ty} => {err:?}"),
);
collected_tys.insert(def_id, ty::EarlyBinder(tcx.ty_error(reported)));
collected_tys.insert(def_id, ty::EarlyBinder::new(tcx.ty_error(reported)));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/dropck.rs
Expand Up @@ -128,7 +128,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
// We don't need to normalize this param-env or anything, since we're only
// substituting it with free params, so no additional param-env normalization
// can occur on top of what has been done in the param_env query itself.
let param_env = ty::EarlyBinder(tcx.param_env(adt_def_id))
let param_env = ty::EarlyBinder::new(tcx.param_env(adt_def_id))
.subst(tcx, adt_to_impl_substs)
.with_constness(tcx.constness(drop_impl_def_id));

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/wfcheck.rs
Expand Up @@ -1398,7 +1398,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id
}
let mut param_count = CountParams::default();
let has_region = pred.visit_with(&mut param_count).is_break();
let substituted_pred = ty::EarlyBinder(pred).subst(tcx, substs);
let substituted_pred = ty::EarlyBinder::new(pred).subst(tcx, substs);
// Don't check non-defaulted params, dependent defaults (including lifetimes)
// or preds with multiple params.
if substituted_pred.has_non_region_param() || param_count.params.len() > 1 || has_region
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/collect.rs
Expand Up @@ -1124,7 +1124,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig<
bug!("unexpected sort of node in fn_sig(): {:?}", x);
}
};
ty::EarlyBinder(output)
ty::EarlyBinder::new(output)
}

fn infer_return_ty_for_fn_sig<'tcx>(
Expand Down Expand Up @@ -1312,7 +1312,7 @@ fn impl_trait_ref(
check_impl_constness(tcx, impl_.constness, ast_trait_ref),
)
})
.map(ty::EarlyBinder)
.map(ty::EarlyBinder::new)
}

fn check_impl_constness(
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/collect/item_bounds.rs
Expand Up @@ -86,7 +86,7 @@ pub(super) fn explicit_item_bounds(
Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
let item = tcx.hir().get_by_def_id(opaque_def_id.expect_local()).expect_item();
let opaque_ty = item.expect_opaque_ty();
return ty::EarlyBinder(opaque_type_bounds(
return ty::EarlyBinder::new(opaque_type_bounds(
tcx,
opaque_def_id.expect_local(),
opaque_ty.bounds,
Expand Down Expand Up @@ -124,7 +124,7 @@ pub(super) fn explicit_item_bounds(
}
_ => bug!("item_bounds called on {:?}", def_id),
};
ty::EarlyBinder(bounds)
ty::EarlyBinder::new(bounds)
}

pub(super) fn item_bounds(
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/collect/type_of.rs
Expand Up @@ -323,7 +323,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty
return map[&assoc_item.trait_item_def_id.unwrap()];
}
Err(_) => {
return ty::EarlyBinder(tcx.ty_error_with_message(
return ty::EarlyBinder::new(tcx.ty_error_with_message(
DUMMY_SP,
"Could not collect return position impl trait in trait tys",
));
Expand Down Expand Up @@ -497,7 +497,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty
bug!("unexpected sort of node in type_of(): {:?}", x);
}
};
ty::EarlyBinder(output)
ty::EarlyBinder::new(output)
}

fn infer_placeholder_type<'a>(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/outlives/explicit.rs
Expand Up @@ -68,7 +68,7 @@ impl<'tcx> ExplicitPredicatesMap<'tcx> {
}
}

ty::EarlyBinder(required_predicates)
ty::EarlyBinder::new(required_predicates)
})
}
}
13 changes: 8 additions & 5 deletions compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs
Expand Up @@ -68,12 +68,13 @@ pub(super) fn infer_predicates(
// Therefore mark `predicates_added` as true and which will ensure
// we walk the crates again and re-calculate predicates for all
// items.
let item_predicates_len: usize =
global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.0.len());
let item_predicates_len: usize = global_inferred_outlives
.get(&item_did.to_def_id())
.map_or(0, |p| p.as_ref().skip_binder().len());
if item_required_predicates.len() > item_predicates_len {
predicates_added = true;
global_inferred_outlives
.insert(item_did.to_def_id(), ty::EarlyBinder(item_required_predicates));
.insert(item_did.to_def_id(), ty::EarlyBinder::new(item_required_predicates));
}
}

Expand Down Expand Up @@ -137,7 +138,9 @@ fn insert_required_predicates_to_be_wf<'tcx>(
// 'a` holds for `Foo`.
debug!("Adt");
if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did()) {
for (unsubstituted_predicate, &span) in &unsubstituted_predicates.0 {
for (unsubstituted_predicate, &span) in
unsubstituted_predicates.as_ref().skip_binder()
{
// `unsubstituted_predicate` is `U: 'b` in the
// example above. So apply the substitution to
// get `T: 'a` (or `predicate`):
Expand Down Expand Up @@ -251,7 +254,7 @@ fn check_explicit_predicates<'tcx>(
);
let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);

for (outlives_predicate, &span) in &explicit_predicates.0 {
for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
debug!("outlives_predicate = {:?}", &outlives_predicate);

// Careful: If we are inferring the effects of a `dyn Trait<..>`
Expand Down
37 changes: 20 additions & 17 deletions compiler/rustc_hir_analysis/src/outlives/mod.rs
Expand Up @@ -98,24 +98,27 @@ fn inferred_outlives_crate(tcx: TyCtxt<'_>, (): ()) -> CratePredicatesMap<'_> {
let predicates = global_inferred_outlives
.iter()
.map(|(&def_id, set)| {
let predicates = &*tcx.arena.alloc_from_iter(set.0.iter().filter_map(
|(ty::OutlivesPredicate(kind1, region2), &span)| {
match kind1.unpack() {
GenericArgKind::Type(ty1) => Some((
ty::Clause::TypeOutlives(ty::OutlivesPredicate(ty1, *region2)),
span,
)),
GenericArgKind::Lifetime(region1) => Some((
ty::Clause::RegionOutlives(ty::OutlivesPredicate(region1, *region2)),
span,
)),
GenericArgKind::Const(_) => {
// Generic consts don't impose any constraints.
None
let predicates =
&*tcx.arena.alloc_from_iter(set.as_ref().skip_binder().iter().filter_map(
|(ty::OutlivesPredicate(kind1, region2), &span)| {
match kind1.unpack() {
GenericArgKind::Type(ty1) => Some((
ty::Clause::TypeOutlives(ty::OutlivesPredicate(ty1, *region2)),
span,
)),
GenericArgKind::Lifetime(region1) => Some((
ty::Clause::RegionOutlives(ty::OutlivesPredicate(
region1, *region2,
)),
span,
)),
GenericArgKind::Const(_) => {
// Generic consts don't impose any constraints.
None
}
}
}
},
));
},
));
(def_id, predicates)
})
.collect();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Expand Up @@ -1386,7 +1386,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// the referenced item.
let ty = tcx.type_of(def_id);
assert!(!substs.has_escaping_bound_vars());
assert!(!ty.0.has_escaping_bound_vars());
assert!(!ty.skip_binder().has_escaping_bound_vars());
let ty_substituted = self.normalize(span, ty.subst(tcx, substs));

if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/outlives/verify.rs
Expand Up @@ -293,7 +293,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
) -> impl Iterator<Item = ty::Region<'tcx>> {
let tcx = self.tcx;
let bounds = tcx.item_bounds(alias_ty.def_id);
trace!("{:#?}", bounds.0);
trace!("{:#?}", bounds.skip_binder());
bounds
.subst_iter(tcx, alias_ty.substs)
.filter_map(|p| p.to_opt_type_outlives())
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/decoder.rs
Expand Up @@ -851,7 +851,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
} else {
tcx.arena.alloc_from_iter(lazy.decode((self, tcx)))
};
ty::EarlyBinder(&*output)
ty::EarlyBinder::new(&*output)
}

fn get_variant(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Expand Up @@ -1727,7 +1727,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
ty::Closure(_, substs) => {
let constness = self.tcx.constness(def_id.to_def_id());
self.tables.constness.set_some(def_id.to_def_id().index, constness);
record!(self.tables.fn_sig[def_id.to_def_id()] <- ty::EarlyBinder(substs.as_closure().sig()));
record!(self.tables.fn_sig[def_id.to_def_id()] <- ty::EarlyBinder::new(substs.as_closure().sig()));
}

_ => bug!("closure that is neither generator nor closure"),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/mod.rs
Expand Up @@ -476,7 +476,7 @@ impl<'tcx> Body<'tcx> {
/// Returns the return type; it always return first element from `local_decls` array.
#[inline]
pub fn bound_return_ty(&self) -> ty::EarlyBinder<Ty<'tcx>> {
ty::EarlyBinder(self.local_decls[RETURN_PLACE].ty)
ty::EarlyBinder::new(self.local_decls[RETURN_PLACE].ty)
}

/// Gets the location of the terminator for the given block.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/adt.rs
Expand Up @@ -573,7 +573,7 @@ impl<'tcx> AdtDef<'tcx> {
/// Due to normalization being eager, this applies even if
/// the associated type is behind a pointer (e.g., issue #31299).
pub fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> ty::EarlyBinder<&'tcx [Ty<'tcx>]> {
ty::EarlyBinder(tcx.adt_sized_constraint(self.did()))
ty::EarlyBinder::new(tcx.adt_sized_constraint(self.did()))
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/consts.rs
Expand Up @@ -254,5 +254,5 @@ pub fn const_param_default(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBind
"`const_param_default` expected a generic parameter with a constant"
),
};
ty::EarlyBinder(Const::from_anon_const(tcx, default_def_id))
ty::EarlyBinder::new(Const::from_anon_const(tcx, default_def_id))
}
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/generics.rs
Expand Up @@ -343,7 +343,7 @@ impl<'tcx> GenericPredicates<'tcx> {
substs: SubstsRef<'tcx>,
) -> impl Iterator<Item = (Predicate<'tcx>, Span)> + DoubleEndedIterator + ExactSizeIterator
{
EarlyBinder(self.predicates).subst_iter_copied(tcx, substs)
EarlyBinder::new(self.predicates).subst_iter_copied(tcx, substs)
}

#[instrument(level = "debug", skip(self, tcx))]
Expand All @@ -358,7 +358,7 @@ impl<'tcx> GenericPredicates<'tcx> {
}
instantiated
.predicates
.extend(self.predicates.iter().map(|(p, _)| EarlyBinder(*p).subst(tcx, substs)));
.extend(self.predicates.iter().map(|(p, _)| EarlyBinder::new(*p).subst(tcx, substs)));
instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp));
}

Expand Down
Expand Up @@ -158,7 +158,7 @@ impl<'tcx> InhabitedPredicate<'tcx> {
fn subst_opt(self, tcx: TyCtxt<'tcx>, substs: ty::SubstsRef<'tcx>) -> Option<Self> {
match self {
Self::ConstIsZero(c) => {
let c = ty::EarlyBinder(c).subst(tcx, substs);
let c = ty::EarlyBinder::new(c).subst(tcx, substs);
let pred = match c.kind().try_to_target_usize(tcx) {
Some(0) => Self::True,
Some(1..) => Self::False,
Expand All @@ -167,7 +167,7 @@ impl<'tcx> InhabitedPredicate<'tcx> {
Some(pred)
}
Self::GenericType(t) => {
Some(ty::EarlyBinder(t).subst(tcx, substs).inhabited_predicate(tcx))
Some(ty::EarlyBinder::new(t).subst(tcx, substs).inhabited_predicate(tcx))
}
Self::And(&[a, b]) => match a.subst_opt(tcx, substs) {
None => b.subst_opt(tcx, substs).map(|b| a.and(tcx, b)),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Expand Up @@ -764,7 +764,7 @@ impl<'tcx> Predicate<'tcx> {
let shifted_pred =
tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder());
// 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1>
let new = EarlyBinder(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
let new = EarlyBinder::new(shifted_pred).subst(tcx, trait_ref.skip_binder().substs);
// 3) ['x] + ['b] -> ['x, 'b]
let bound_vars =
tcx.mk_bound_variable_kinds_from_iter(trait_bound_vars.iter().chain(pred_bound_vars));
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/mod.rs
Expand Up @@ -123,7 +123,7 @@ pub trait Printer<'tcx>: Sized {
impl_trait_ref.map(|i| i.subst(self.tcx(), substs)),
)
} else {
(self_ty.0, impl_trait_ref.map(|i| i.0))
(self_ty.subst_identity(), impl_trait_ref.map(|i| i.subst_identity()))
};
self.print_impl_path(def_id, substs, self_ty, impl_trait_ref)
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/sty.rs
Expand Up @@ -568,7 +568,7 @@ impl<'tcx> GeneratorSubsts<'tcx> {
let layout = tcx.generator_layout(def_id).unwrap();
layout.variant_fields.iter().map(move |variant| {
variant.iter().map(move |field| {
ty::EarlyBinder(layout.field_tys[*field].ty).subst(tcx, self.substs)
ty::EarlyBinder::new(layout.field_tys[*field].ty).subst(tcx, self.substs)
})
})
}
Expand Down Expand Up @@ -2366,7 +2366,7 @@ impl<'tcx> Ty<'tcx> {

ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),

ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
ty::Adt(def, _substs) => def.sized_constraint(tcx).skip_binder().is_empty(),

ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) => false,

Expand Down
9 changes: 8 additions & 1 deletion compiler/rustc_middle/src/ty/subst.rs
Expand Up @@ -538,13 +538,17 @@ impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>> for &'tcx
/// [`subst_identity`](EarlyBinder::subst_identity) or [`skip_binder`](EarlyBinder::skip_binder).
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Encodable, Decodable, HashStable)]
pub struct EarlyBinder<T>(pub T);
pub struct EarlyBinder<T>(T);

/// For early binders, you should first call `subst` before using any visitors.
impl<'tcx, T> !TypeFoldable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {}
impl<'tcx, T> !TypeVisitable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {}

impl<T> EarlyBinder<T> {
pub fn new(inner: T) -> EarlyBinder<T> {
EarlyBinder(inner)
}

pub fn as_ref(&self) -> EarlyBinder<&T> {
EarlyBinder(&self.0)
}
Expand Down Expand Up @@ -582,6 +586,9 @@ impl<T> EarlyBinder<T> {
/// arguments of an `FnSig`). Otherwise, consider using
/// [`subst_identity`](EarlyBinder::subst_identity).
///
/// To skip the binder on `x: &EarlyBinder<T>` to obtain `&T`, leverage
/// [`EarlyBinder::as_ref`](EarlyBinder::as_ref): `x.as_ref().skip_binder()`.
///
/// See also [`Binder::skip_binder`](super::Binder::skip_binder), which is
/// the analogous operation on [`super::Binder`].
pub fn skip_binder(self) -> T {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/util.rs
Expand Up @@ -709,7 +709,7 @@ impl<'tcx> TyCtxt<'tcx> {
.as_ref()
.map_or_else(|| [].iter(), |l| l.field_tys.iter())
.filter(|decl| !decl.ignore_for_traits)
.map(|decl| ty::EarlyBinder(decl.ty))
.map(|decl| ty::EarlyBinder::new(decl.ty))
}

/// Normalizes all opaque types in the given value, replacing them
Expand Down

0 comments on commit 1c53407

Please sign in to comment.