Skip to content

Commit

Permalink
Use the opaque_types_defined_by query to cheaply check for whether a …
Browse files Browse the repository at this point in the history
…hidden type may be registered for an opaque type
  • Loading branch information
oli-obk committed May 12, 2023
1 parent 6ae803e commit 4e92f76
Show file tree
Hide file tree
Showing 17 changed files with 368 additions and 162 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let ty::subst::GenericArgKind::Type(ty) = ty.unpack()
&& let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *ty.kind()
&& let Some(def_id) = def_id.as_local()
&& self.opaque_type_origin(def_id, self.param_env).is_some() {
&& self.opaque_type_origin(def_id).is_some() {
return None;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use crate::infer::opaque_types::may_define_impl_trait_in_assoc_ty_modulo_sig;

use super::TypeErrCtxt;
use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
use rustc_errors::{pluralize, Diagnostic, MultiSpan};
use rustc_hir as hir;
use rustc_middle::traits::ObligationCauseCode::{self, MiscObligation};
use rustc_hir::def::DefKind;
use rustc_middle::traits::ObligationCauseCode;
use rustc_middle::ty::error::ExpectedFound;
use rustc_middle::ty::print::Printer;
use rustc_middle::{
Expand Down Expand Up @@ -258,9 +257,9 @@ impl<T> Trait<T> for X {
);
}
}
(ty::Alias(ty::Opaque, alias), _) | (_, ty::Alias(ty::Opaque, alias)) if matches!(cause.code(), MiscObligation) => {
if let Some(def_id) = alias.def_id.as_local() {
if may_define_impl_trait_in_assoc_ty_modulo_sig(tcx, body_owner_def_id.expect_local(), def_id).is_some() {
(ty::Alias(ty::Opaque, alias), _) | (_, ty::Alias(ty::Opaque, alias)) if alias.def_id.is_local() && matches!(tcx.def_kind(body_owner_def_id), DefKind::AssocFn | DefKind::AssocConst) => {
if tcx.is_type_alias_impl_trait(alias.def_id) {
if !tcx.opaque_types_defined_by(body_owner_def_id.expect_local()).contains(&alias.def_id.expect_local()) {
diag.span_note(tcx.def_span(body_owner_def_id), "\
this item must have the opaque type in its signature \
in order to be able to register hidden types");
Expand Down
126 changes: 8 additions & 118 deletions compiler/rustc_infer/src/infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use super::{DefineOpaqueTypes, InferResult};
use crate::errors::OpaqueHiddenTypeDiag;
use crate::infer::{DefiningAnchor, InferCtxt, InferOk};
use crate::traits;
use hir::def::DefKind;
use hir::def_id::{DefId, LocalDefId};
use hir::OpaqueTyOrigin;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::Lrc;
use rustc_hir as hir;
use rustc_middle::traits::ObligationCause;
Expand Down Expand Up @@ -54,9 +53,7 @@ impl<'tcx> InferCtxt<'tcx> {
}
let mut obligations = vec![];
let replace_opaque_type = |def_id: DefId| {
def_id
.as_local()
.map_or(false, |def_id| self.opaque_type_origin(def_id, param_env).is_some())
def_id.as_local().map_or(false, |def_id| self.opaque_type_origin(def_id).is_some())
};
let value = value.fold_with(&mut BottomUpFolder {
tcx: self.tcx,
Expand Down Expand Up @@ -141,7 +138,7 @@ impl<'tcx> InferCtxt<'tcx> {
// let x = || foo(); // returns the Opaque assoc with `foo`
// }
// ```
self.opaque_type_origin(def_id, param_env)?
self.opaque_type_origin(def_id)?
}
DefiningAnchor::Bubble => self.opaque_type_origin_unchecked(def_id),
DefiningAnchor::Error => return None,
Expand All @@ -152,9 +149,8 @@ impl<'tcx> InferCtxt<'tcx> {
// no one encounters it in practice.
// It does occur however in `fn fut() -> impl Future<Output = i32> { async { 42 } }`,
// where it is of no concern, so we only check for TAITs.
if let Some(OpaqueTyOrigin::TyAlias { .. }) = b_def_id
.as_local()
.and_then(|b_def_id| self.opaque_type_origin(b_def_id, param_env))
if let Some(OpaqueTyOrigin::TyAlias { .. }) =
b_def_id.as_local().and_then(|b_def_id| self.opaque_type_origin(b_def_id))
{
self.tcx.sess.emit_err(OpaqueHiddenTypeDiag {
span: cause.span,
Expand Down Expand Up @@ -370,12 +366,8 @@ impl<'tcx> InferCtxt<'tcx> {

/// Returns the origin of the opaque type `def_id` if we're currently
/// in its defining scope.
#[instrument(skip(self, param_env), level = "trace", ret)]
pub fn opaque_type_origin(
&self,
def_id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
) -> Option<OpaqueTyOrigin> {
#[instrument(skip(self), level = "trace", ret)]
pub fn opaque_type_origin(&self, def_id: LocalDefId) -> Option<OpaqueTyOrigin> {
let opaque_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
let parent_def_id = match self.defining_use_anchor {
DefiningAnchor::Bubble | DefiningAnchor::Error => return None,
Expand All @@ -391,7 +383,7 @@ impl<'tcx> InferCtxt<'tcx> {
// Named `type Foo = impl Bar;`
hir::OpaqueTyOrigin::TyAlias { in_assoc_ty } => {
if in_assoc_ty {
may_define_impl_trait_in_assoc_ty(self.tcx, parent_def_id, def_id, param_env)
self.tcx.opaque_types_defined_by(parent_def_id).contains(&def_id)
} else {
may_define_opaque_type(self.tcx, parent_def_id, opaque_hir_id)
}
Expand Down Expand Up @@ -654,105 +646,3 @@ fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hi
);
res
}

#[derive(Debug, TypeVisitable, Clone)]
/// Helper datastructure containing the signature
/// that the opaque type extraction logic uses for determining
/// whether an opaque type may have its hidden types registered
/// by an item.
enum FnSigOrTy<'tcx> {
FnSig(ty::PolyFnSig<'tcx>),
Ty(Ty<'tcx>),
}

/// Checks that the item may register hidden types for the
/// opaque type, if the opaque type shows up in its signature.
#[instrument(level = "debug", skip(tcx), ret)]
pub fn may_define_impl_trait_in_assoc_ty_modulo_sig<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
opaque_def_id: LocalDefId,
) -> Option<impl TypeVisitable<TyCtxt<'tcx>>> {
let sig = match tcx.def_kind(def_id) {
DefKind::AssocFn => FnSigOrTy::FnSig(tcx.fn_sig(def_id).subst_identity()),
DefKind::AssocConst | DefKind::AssocTy => {
FnSigOrTy::Ty(tcx.type_of(def_id).subst_identity())
}
_ => return None,
};
let impl_id = tcx.local_parent(def_id);
trace!(?impl_id);
let mut assoc_id = opaque_def_id;
// Peel nested opaque types.
while let DefKind::OpaqueTy = tcx.def_kind(assoc_id) {
trace!(?assoc_id);
assoc_id = tcx.local_parent(assoc_id);
}
trace!(?assoc_id);
if !matches!(tcx.def_kind(assoc_id), DefKind::AssocTy) {
tcx.sess
.delay_span_bug(tcx.def_span(opaque_def_id), format!("{:?}", tcx.def_kind(assoc_id)));
}
let assoc_impl_id = tcx.local_parent(assoc_id);
trace!(?assoc_impl_id);

if impl_id != assoc_impl_id {
return None;
}

Some(sig)
}

#[instrument(level = "debug", skip(tcx, param_env), ret)]
fn may_define_impl_trait_in_assoc_ty<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
opaque_def_id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
) -> bool {
let Some(sig) = may_define_impl_trait_in_assoc_ty_modulo_sig(tcx, def_id, opaque_def_id) else {
return false;
};

struct Visitor<'tcx> {
opaque_def_id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
tcx: TyCtxt<'tcx>,
seen: FxHashSet<LocalDefId>,
}

impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Visitor<'tcx> {
type BreakTy = ();
#[instrument(level = "trace", skip(self), ret)]
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
// FIXME(oli-obk): We should be checking if the associated type
// is mentioned instead of normalizing to find the opaque type.
// But that requires a way to figure out that a projection refers
// to a specific opaque type. That is probably doable by checking for
// `Self` as the `substs[0]`.
let normalized_ty = self.tcx.normalize_erasing_regions(self.param_env, ty);
if let ty::Alias(ty::Opaque, alias) = normalized_ty.kind() {
if let Some(def_id) = alias.def_id.as_local() {
trace!(?alias.def_id);
if def_id == self.opaque_def_id {
return ControlFlow::Break(());
}

if self.seen.insert(def_id) {
// Look into nested obligations like `impl Trait<Assoc = impl OtherTrait>`.
for (pred, _) in self
.tcx
.explicit_item_bounds(alias.def_id)
.subst_iter_copied(self.tcx, alias.substs)
{
pred.visit_with(self)?;
}
}
}
}
normalized_ty.super_visit_with(self)
}
}
sig.visit_with(&mut Visitor { opaque_def_id, param_env, tcx, seen: Default::default() })
.is_break()
}
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/query/erase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ impl EraseType for ty::Binder<'_, ty::FnSig<'_>> {
type Result = [u8; size_of::<ty::Binder<'static, ty::FnSig<'static>>>()];
}

impl EraseType for ty::Binder<'_, &'_ ty::List<Ty<'_>>> {
type Result = [u8; size_of::<ty::Binder<'static, &'static ty::List<Ty<'static>>>>()];
}

impl<T0, T1> EraseType for (&'_ T0, &'_ T1) {
type Result = [u8; size_of::<(&'static (), &'static ())>()];
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1265,7 +1265,7 @@ impl<'tcx> AliasTy<'tcx> {

/// Extracts the underlying trait reference and own substs from this projection.
/// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
/// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
/// then this function would return a `T: StreamingIterator` trait reference and `['a]` as the own substs
pub fn trait_ref_and_own_substs(
self,
tcx: TyCtxt<'tcx>,
Expand Down
15 changes: 13 additions & 2 deletions compiler/rustc_middle/src/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ pub struct Discr<'tcx> {
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CheckRegions {
No,
/// Only permit early bound regions. This is useful for Adts which
/// can never have late bound regions.
OnlyEarlyBound,
/// Permit both late bound and early bound regions. Use this for functions,
/// which frequently have late bound regions.
Bound,
}

#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -471,15 +476,21 @@ impl<'tcx> TyCtxt<'tcx> {
ignore_regions: CheckRegions,
) -> Result<(), NotUniqueParam<'tcx>> {
let mut seen = GrowableBitSet::default();
let mut seen_late = FxHashSet::default();
for arg in substs {
match arg.unpack() {
GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
(CheckRegions::OnlyEarlyBound, ty::ReEarlyBound(p)) => {
(CheckRegions::Bound, ty::ReLateBound(di, reg)) => {
if !seen_late.insert((di, reg)) {
return Err(NotUniqueParam::DuplicateParam(lt.into()));
}
}
(CheckRegions::OnlyEarlyBound | CheckRegions::Bound, ty::ReEarlyBound(p)) => {
if !seen.insert(p.index) {
return Err(NotUniqueParam::DuplicateParam(lt.into()));
}
}
(CheckRegions::OnlyEarlyBound, _) => {
(CheckRegions::OnlyEarlyBound | CheckRegions::Bound, _) => {
return Err(NotUniqueParam::NotParam(lt.into()));
}
(CheckRegions::No, _) => {}
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_ty_utils/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,11 @@ ty_utils_multiple_array_fields_simd_type = monomorphising SIMD type `{$ty}` with
ty_utils_oversized_simd_type = monomorphising SIMD type `{$ty}` of length greater than {$max_lanes}
ty_utils_non_primitive_simd_type = monomorphising SIMD type `{$ty}` with a non-primitive-scalar (integer/float/pointer) element type `{$e_ty}`
ty_utils_impl_trait_duplicate_arg = non-defining opaque type use in defining scope
.label = generic argument `{$arg}` used twice
.note = for this opaque type
ty_utils_impl_trait_not_param = non-defining opaque type use in defining scope
.label = argument `{$arg}` is not a generic parameter
.note = for this opaque type
24 changes: 23 additions & 1 deletion compiler/rustc_ty_utils/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Errors emitted by ty_utils

use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_middle::ty::Ty;
use rustc_middle::ty::{GenericArg, Ty};
use rustc_span::Span;

#[derive(Diagnostic)]
Expand Down Expand Up @@ -100,3 +100,25 @@ pub struct NonPrimitiveSimdType<'tcx> {
pub ty: Ty<'tcx>,
pub e_ty: Ty<'tcx>,
}

#[derive(Diagnostic)]
#[diag(ty_utils_impl_trait_duplicate_arg)]
pub struct DuplicateArg<'tcx> {
pub arg: GenericArg<'tcx>,
#[primary_span]
#[label]
pub span: Span,
#[note]
pub opaque_span: Span,
}

#[derive(Diagnostic)]
#[diag(ty_utils_impl_trait_not_param)]
pub struct NotParam<'tcx> {
pub arg: GenericArg<'tcx>,
#[primary_span]
#[label]
pub span: Span,
#[note]
pub opaque_span: Span,
}
Loading

0 comments on commit 4e92f76

Please sign in to comment.