Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Require TAITs to appear in the signature of items that register a hidden type #107073

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions compiler/rustc_hir_analysis/src/collect/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit;
use rustc_hir::intravisit::Visitor;
use rustc_hir::{HirId, Node};
use rustc_infer::infer::opaque_types::may_define_opaque_type;
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::print::with_forced_trimmed_paths;
use rustc_middle::ty::subst::InternalSubsts;
Expand Down Expand Up @@ -589,6 +590,12 @@ fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> T
debug!("no constraint: no typeck results");
return;
}

if !may_define_opaque_type(self.tcx, item_def_id, self.def_id) {
debug!("no constraint: does not have TAIT in signature");
return;
}

// Calling `mir_borrowck` can lead to cycle errors through
// const-checking, avoid calling it if we don't have to.
// ```rust
Expand Down
8 changes: 6 additions & 2 deletions compiler/rustc_hir_typeck/src/inherited.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,18 @@ pub struct InheritedBuilder<'tcx> {
}

impl<'tcx> Inherited<'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
pub fn build(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
mk_defining_use_anchor: impl FnOnce(LocalDefId) -> DefiningAnchor,
) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;

InheritedBuilder {
infcx: tcx
.infer_ctxt()
.ignoring_regions()
.with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)),
.with_opaque_type_inference(mk_defining_use_anchor(hir_owner.def_id)),
def_id,
typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
}
Expand Down
16 changes: 14 additions & 2 deletions compiler/rustc_hir_typeck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pub use diverges::Diverges;
pub use expectation::Expectation;
pub use fn_ctxt::*;
pub use inherited::{Inherited, InheritedBuilder};
use rustc_infer::infer::DefiningAnchor;

use crate::check::check_fn;
use crate::coercion::DynamicCoerceMany;
Expand Down Expand Up @@ -199,12 +200,23 @@ fn typeck_with_fallback<'tcx>(
});
let body = tcx.hir().body(body_id);

let typeck_results = Inherited::build(tcx, def_id).enter(|inh| {
let fn_sig_infer = fn_sig.map_or(false, |fn_sig| {
rustc_hir_analysis::collect::get_infer_ret_ty(&fn_sig.decl.output).is_some()
});

let mk_defining_use_anchor = |def_id| {
// In case we are inferring the return signature (via `_` types), ignore defining use
// rules, as we'll error out anyway. This helps improve diagnostics, which otherwise
// may just see `ty::Error` instead of `ty::Alias(Opaque, _)` and not produce better errors.
if fn_sig_infer { DefiningAnchor::Bubble } else { DefiningAnchor::Bind(def_id) }
};

let typeck_results = Inherited::build(tcx, def_id, mk_defining_use_anchor).enter(|inh| {
let param_env = tcx.param_env(def_id);
let mut fcx = FnCtxt::new(&inh, param_env, body.value.hir_id);

if let Some(hir::FnSig { header, decl, .. }) = fn_sig {
let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() {
let fn_sig = if fn_sig_infer {
fcx.astconv().ty_of_fn(id, header.unsafety, header.abi, decl, None, None)
} else {
tcx.fn_sig(def_id)
Expand Down
133 changes: 127 additions & 6 deletions compiler/rustc_infer/src/infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ use crate::traits;
use hir::def::DefKind;
use hir::def_id::{DefId, LocalDefId};
use hir::{HirId, OpaqueTyOrigin};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::vec_map::VecMap;
use rustc_hir as hir;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::fold::BottomUpFolder;
use rustc_middle::ty::GenericArgKind;
use rustc_middle::ty::{
self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
TypeVisitable, TypeVisitor,
};
use rustc_middle::ty::{DefIdTree, GenericArgKind};
use rustc_span::Span;

use std::ops::ControlFlow;
Expand Down Expand Up @@ -373,7 +374,6 @@ impl<'tcx> InferCtxt<'tcx> {

#[instrument(skip(self), level = "trace", ret)]
pub fn opaque_type_origin(&self, def_id: LocalDefId, span: Span) -> 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,
DefiningAnchor::Bind(bind) => bind,
Expand All @@ -394,9 +394,7 @@ impl<'tcx> InferCtxt<'tcx> {
// Anonymous `impl Trait`
hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id,
// Named `type Foo = impl Bar;`
hir::OpaqueTyOrigin::TyAlias => {
may_define_opaque_type(self.tcx, parent_def_id, opaque_hir_id)
}
hir::OpaqueTyOrigin::TyAlias => may_define_opaque_type(self.tcx, parent_def_id, def_id),
};
trace!(?origin);
in_definition_scope.then_some(*origin)
Expand Down Expand Up @@ -639,11 +637,134 @@ impl<'tcx> InferCtxt<'tcx> {
/// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
/// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
/// For the above example, this function returns `true` for `f1` and `false` for `f2`.
fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
#[instrument(skip(tcx), level = "trace", ret)]
pub fn may_define_opaque_type<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
opaque_def_id: LocalDefId,
) -> bool {
if tcx.is_closure(def_id.to_def_id()) {
return may_define_opaque_type(
tcx,
tcx.parent(def_id.to_def_id()).expect_local(),
opaque_def_id,
);
}

let param_env = tcx.param_env(def_id);
let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(opaque_def_id);
let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);

// Named opaque types can be defined by any siblings or children of siblings.
let scope = tcx.hir().get_defining_scope(opaque_hir_id);

// When doing checks within the opaque type itself
if def_id != opaque_def_id
// When the opaque type is defined in the body of a function, the function may access it.
&& hir_id != scope
{
trace!(parent = ?tcx.parent(opaque_def_id.to_def_id()));
fn has_tait<'tcx>(
val: impl TypeVisitable<'tcx>,
opaque_def_id: LocalDefId,
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> bool {
struct Visitor<'tcx> {
opaque_def_id: DefId,
tcx: TyCtxt<'tcx>,
seen: FxHashSet<Ty<'tcx>>,
param_env: ty::ParamEnv<'tcx>,
}
impl<'tcx> TypeVisitor<'tcx> for Visitor<'tcx> {
type BreakTy = ();

#[instrument(skip(self), level = "trace", ret)]
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
// Erase all lifetimes, they can't affect anything, but recursion
// may cause late bound regions to differ, because the type visitor
// can't erase them in `visit_binder`.
let t = t.fold_with(&mut BottomUpFolder {
tcx: self.tcx,
ct_op: |c| c,
ty_op: |t| t,
lt_op: |_| self.tcx.lifetimes.re_erased,
});
if !self.seen.insert(t) {
return ControlFlow::Continue(());
}
match t.kind() {
ty::Alias(ty::Opaque, alias) => {
if alias.def_id == self.opaque_def_id {
return ControlFlow::Break(());
}
for (pred, _span) in self
.tcx
.bound_explicit_item_bounds(alias.def_id)
.subst_iter_copied(self.tcx, alias.substs)
{
pred.visit_with(self)?;
}
}
ty::Alias(ty::Projection, _) => {
if let Ok(proj) =
self.tcx.try_normalize_erasing_regions(self.param_env, t)
{
proj.visit_with(self)?;
}
}
// Types that have opaque type fields must get walked manually, they
// would not be seen by the type visitor otherwise.
ty::Adt(adt_def, substs) => {
for variant in adt_def.variants() {
for field in &variant.fields {
field.ty(self.tcx, substs).visit_with(self)?;
}
}
}
_ => (),
}
t.super_visit_with(self)
}
}
val.visit_with(&mut Visitor {
opaque_def_id: opaque_def_id.to_def_id(),
tcx,
seen: Default::default(),
param_env,
})
.is_break()
}
let tait_in_fn_sig = match tcx.def_kind(def_id) {
DefKind::AssocFn | DefKind::Fn => {
has_tait(tcx.fn_sig(def_id.to_def_id()), opaque_def_id, tcx, param_env)
}
// Opaque types in types of contsts
DefKind::Static(_) | DefKind::Const | DefKind::AssocConst => {
has_tait(tcx.type_of(def_id.to_def_id()), opaque_def_id, tcx, param_env)
}
// Nested opaque types
DefKind::OpaqueTy => has_tait(
tcx.bound_explicit_item_bounds(def_id.to_def_id()).skip_binder(),
opaque_def_id,
tcx,
param_env,
),
_ => false,
};
trace!(?tait_in_fn_sig);
if !tait_in_fn_sig
&& !has_tait(
tcx.predicates_of(def_id.to_def_id()).predicates,
opaque_def_id,
tcx,
param_env,
)
{
return false;
}
}

// We walk up the node tree until we hit the root or the scope of the opaque type.
while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
hir_id = tcx.hir().get_parent_item(hir_id).into();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/normalize_erasing_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl<'tcx> TryNormalizeAfterErasingRegionsFolder<'tcx> {
TryNormalizeAfterErasingRegionsFolder { tcx, param_env }
}

#[instrument(skip(self), level = "debug")]
#[instrument(skip(self), level = "debug", ret)]
fn try_normalize_generic_arg_after_erasing_regions(
&self,
arg: ty::GenericArg<'tcx>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
use rustc_middle::ty::{self, Clause, EarlyBinder, ParamTy, PredicateKind, ProjectionPredicate, TraitPredicate, Ty};
use rustc_span::{sym, Symbol};
use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause};
use rustc_infer::infer::DefiningAnchor;

use super::UNNECESSARY_TO_OWNED;

Expand Down Expand Up @@ -370,7 +371,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty<
if let ItemKind::Fn(_, _, body_id) = &item.kind
&& let output_ty = return_ty(cx, item.hir_id())
&& let local_def_id = cx.tcx.hir().local_def_id(item.hir_id())
&& Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
&& Inherited::build(cx.tcx, local_def_id, DefiningAnchor::Bind).enter(|inherited| {
let fn_ctxt = FnCtxt::new(inherited, cx.param_env, item.hir_id());
fn_ctxt.can_coerce(ty, output_ty)
}) {
Expand Down
3 changes: 2 additions & 1 deletion src/tools/clippy/clippy_lints/src/transmute/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use rustc_hir_typeck::{cast, FnCtxt, Inherited};
use rustc_lint::LateContext;
use rustc_middle::ty::{cast::CastKind, Ty};
use rustc_span::DUMMY_SP;
use rustc_infer::infer::DefiningAnchor;

// check if the component types of the transmuted collection and the result have different ABI,
// size or alignment
Expand Down Expand Up @@ -45,7 +46,7 @@ fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>
let hir_id = e.hir_id;
let local_def_id = hir_id.owner.def_id;

Inherited::build(cx.tcx, local_def_id).enter(|inherited| {
Inherited::build(cx.tcx, local_def_id, DefiningAnchor::Bind).enter(|inherited| {
let fn_ctxt = FnCtxt::new(inherited, cx.param_env, hir_id);

// If we already have errors, we can't be sure we can pointer cast.
Expand Down
Loading