Skip to content

[Draft] Supertrait item resolution in subtrait impls #143527

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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
16 changes: 15 additions & 1 deletion compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::{cmp, fmt};

pub use GenericArgs::*;
pub use UnsafeSource::*;
pub use rustc_ast_ir::{Movability, Mutability, Pinnedness};
pub use rustc_ast_ir::{Movability, Mutability, Pinnedness, TraitRefSource};
use rustc_data_structures::packed::Pu128;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::stack::ensure_sufficient_stack;
Expand Down Expand Up @@ -1386,6 +1386,7 @@ impl Expr {
ThinVec::new(),
path.clone(),
TraitBoundModifiers::NONE,
TraitRefSource::Any,
self.span,
Parens::No,
))),
Expand Down Expand Up @@ -3382,25 +3383,38 @@ pub struct PolyTraitRef {
/// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
pub trait_ref: TraitRef,

/// The source of this trait ref
/// and whether this trait ref should be regarded as
/// a nominal subtrait-supertrait relation.
pub source: TraitRefSource,

pub span: Span,

/// When `Yes`, the first and last character of `span` are an opening
/// and a closing paren respectively.
pub parens: Parens,
}

impl PolyTraitRef {
pub fn is_supertrait(&self) -> bool {
matches!(self.source, TraitRefSource::Supertrait)
}
}

impl PolyTraitRef {
pub fn new(
generic_params: ThinVec<GenericParam>,
path: Path,
modifiers: TraitBoundModifiers,
source: TraitRefSource,
span: Span,
parens: Parens,
) -> Self {
PolyTraitRef {
bound_generic_params: generic_params,
modifiers,
trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
source,
span,
parens,
}
Expand Down
11 changes: 6 additions & 5 deletions compiler/rustc_ast/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
pub use rustc_ast_ir::visit::VisitorResult;
pub use rustc_ast_ir::{try_visit, visit_opt, walk_list, walk_visitable_list};
use rustc_span::def_id::LocalDefId;
use rustc_span::source_map::Spanned;
use rustc_span::{Ident, Span};
use thin_vec::ThinVec;
Expand Down Expand Up @@ -52,15 +53,15 @@ pub enum BoundKind {

/// Super traits of a trait.
/// E.g., `trait A: B`
SuperTraits,
SuperTraits { subtrait: LocalDefId },
}
impl BoundKind {
pub fn descr(self) -> &'static str {
match self {
BoundKind::Bound => "bounds",
BoundKind::Impl => "`impl Trait`",
BoundKind::TraitObject => "`dyn` trait object bounds",
BoundKind::SuperTraits => "supertrait bounds",
BoundKind::SuperTraits { .. } => "supertrait bounds",
}
}
}
Expand Down Expand Up @@ -266,8 +267,8 @@ macro_rules! common_visitor_and_walkers {
walk_trait_ref(self, t)
}

fn visit_param_bound(&mut self, bounds: &$($lt)? $($mut)? GenericBound, _ctxt: BoundKind) -> Self::Result {
walk_param_bound(self, bounds)
fn visit_param_bound(&mut self, bound: &$($lt)? $($mut)? GenericBound, _ctxt: BoundKind) -> Self::Result {
walk_param_bound(self, bound)
}

fn visit_precise_capturing_arg(&mut self, arg: &$($lt)? $($mut)? PreciseCapturingArg) -> Self::Result {
Expand Down Expand Up @@ -1142,7 +1143,7 @@ macro_rules! common_visitor_and_walkers {
vis: &mut V,
p: &$($lt)? $($mut)? PolyTraitRef,
) -> V::Result {
let PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ } = p;
let PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, .. } = p;
try_visit!(visit_modifiers(vis, modifiers));
try_visit!(visit_generic_params(vis, bound_generic_params));
try_visit!(vis.visit_trait_ref(trait_ref));
Expand Down
18 changes: 18 additions & 0 deletions compiler/rustc_ast_ir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,21 @@ pub enum Pinnedness {
Not,
Pinned,
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
#[cfg_attr(
feature = "nightly",
derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
)]
pub enum TraitRefSource {
/// This source excludes all of the other relationships
Any,
/// The trait ref source establishes a subtrait-supertrait
/// relationship
Supertrait,
/// The trait ref source establishes a subtrait-supertrait
/// relationship and we are obliged to assert that the supertrait
/// is a marker trait and generate an automatic `impl` for this
/// marker trait
SupertraitAutoImpl,
}
10 changes: 8 additions & 2 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1208,6 +1208,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
bound_generic_params: ThinVec::new(),
modifiers: TraitBoundModifiers::NONE,
trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
source: TraitRefSource::Any,
span: t.span,
parens: ast::Parens::No,
},
Expand Down Expand Up @@ -2018,7 +2019,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let bound_generic_params =
self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params);
let trait_ref = self.lower_trait_ref(p.modifiers, &p.trait_ref, itctx);
let modifiers = self.lower_trait_bound_modifiers(p.modifiers);
let modifiers = self.lower_trait_bound_modifiers(p.modifiers, p.source);
hir::PolyTraitRef {
bound_generic_params,
modifiers,
Expand Down Expand Up @@ -2253,8 +2254,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_trait_bound_modifiers(
&mut self,
modifiers: TraitBoundModifiers,
source: TraitRefSource,
) -> hir::TraitBoundModifiers {
hir::TraitBoundModifiers { constness: modifiers.constness, polarity: modifiers.polarity }
hir::TraitBoundModifiers {
constness: modifiers.constness,
polarity: modifiers.polarity,
source,
}
}

// Helper methods for building HIR.
Expand Down
20 changes: 15 additions & 5 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use rustc_session::lint::builtin::{
PATTERNS_IN_FNS_WITHOUT_BODY,
};
use rustc_session::lint::{BuiltinLintDiag, LintBuffer};
use rustc_span::def_id::{DefIndex, LocalDefId};
use rustc_span::{Ident, Span, kw, sym};
use rustc_target::spec::{AbiMap, AbiMapping};
use thin_vec::thin_vec;
Expand Down Expand Up @@ -1149,7 +1150,14 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
is_const_trait.is_none().then(|| TildeConstReason::Trait { span: item.span });
self.with_tilde_const(disallowed, |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
walk_list!(
this,
visit_param_bound,
bounds,
BoundKind::SuperTraits {
subtrait: LocalDefId { local_def_index: DefIndex::ZERO }
}
)
});
self.with_in_trait(item.span, is_const_trait, |this| {
walk_list!(this, visit_assoc_item, items, AssocCtxt::Trait);
Expand Down Expand Up @@ -1373,9 +1381,11 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
match bound {
GenericBound::Trait(trait_ref) => {
match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
(BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_))
if !self.features.more_maybe_bounds() =>
{
(
BoundKind::SuperTraits { .. },
BoundConstness::Never,
BoundPolarity::Maybe(_),
) if !self.features.more_maybe_bounds() => {
self.sess
.create_feature_err(
errors::OptionalTraitSupertrait {
Expand Down Expand Up @@ -1438,7 +1448,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
GenericBound::Outlives(_) => {}
GenericBound::Use(_, span) => match ctxt {
BoundKind::Impl => {}
BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits => {
BoundKind::Bound | BoundKind::TraitObject | BoundKind::SuperTraits { .. } => {
self.dcx().emit_err(errors::PreciseCapturingNotAllowedHere {
loc: ctxt.descr(),
span: *span,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_expand/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ impl<'a> ExtCtxt<'a> {
asyncness: ast::BoundAsyncness::Normal,
},
trait_ref: self.trait_ref(path),
source: ast::TraitRefSource::Any,
span,
parens: ast::Parens::No,
}
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,10 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"),
ErrorFollowing, EncodeCrossCrate::No,
),
rustc_attr!(
TEST, rustc_supertrait_in_subtrait_impl, Normal, template!(Word),
WarnFollowing, EncodeCrossCrate::Yes,
),
];

pub fn is_builtin_attr_name(name: Symbol) -> bool {
Expand Down
12 changes: 8 additions & 4 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_ast::{
pub use rustc_ast::{
AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
MetaItemInner, MetaItemLit, Movability, Mutability, TraitRefSource, UnOp,
};
use rustc_attr_data_structures::AttributeKind;
use rustc_data_structures::fingerprint::Fingerprint;
Expand Down Expand Up @@ -707,11 +707,15 @@ pub enum GenericArgsParentheses {
pub struct TraitBoundModifiers {
pub constness: BoundConstness,
pub polarity: BoundPolarity,
pub source: TraitRefSource,
}

impl TraitBoundModifiers {
pub const NONE: Self =
TraitBoundModifiers { constness: BoundConstness::Never, polarity: BoundPolarity::Positive };
pub const NONE: Self = TraitBoundModifiers {
constness: BoundConstness::Never,
polarity: BoundPolarity::Positive,
source: TraitRefSource::Any,
};
}

#[derive(Clone, Copy, Debug, HashStable_Generic)]
Expand Down Expand Up @@ -4966,7 +4970,7 @@ mod size_asserts {
static_assert_size!(ForeignItem<'_>, 96);
static_assert_size!(ForeignItemKind<'_>, 56);
static_assert_size!(GenericArg<'_>, 16);
static_assert_size!(GenericBound<'_>, 64);
static_assert_size!(GenericBound<'_>, 72);
static_assert_size!(Generics<'_>, 56);
static_assert_size!(Impl<'_>, 80);
static_assert_size!(ImplItem<'_>, 88);
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub(crate) fn provide(providers: &mut Providers) {
predicates_of: predicates_of::predicates_of,
explicit_predicates_of: predicates_of::explicit_predicates_of,
explicit_super_predicates_of: predicates_of::explicit_super_predicates_of,
supertrait_auto_impls: predicates_of::supertrait_auto_impls,
explicit_implied_predicates_of: predicates_of::explicit_implied_predicates_of,
explicit_supertraits_containing_assoc_item:
predicates_of::explicit_supertraits_containing_assoc_item,
Expand Down
27 changes: 27 additions & 0 deletions compiler/rustc_hir_analysis/src/collect/predicates_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,33 @@ pub(super) fn implied_predicates_with_filter<'tcx>(
ty::EarlyBinder::bind(implied_bounds)
}

/// This query collects supertraits that should be implicitly `impl`ed
/// within the context of a subtrait `impl`.
/// In doing so, this subtrait may authorise the compiler to generate `impl`s
/// on marker supertraits.
/// This query also reports the authorisation.
pub(super) fn supertrait_auto_impls<'tcx>(
tcx: TyCtxt<'tcx>,
trait_def_id: LocalDefId,
) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, hir::TraitRefSource)]> {
let Node::Item(item) = tcx.hir_node_by_def_id(trait_def_id) else {
bug!("trait_def_id {trait_def_id:?} is not an item");
};

let superbounds = match item.kind {
hir::ItemKind::Trait(_, _, _, _, supertraits, _)
| hir::ItemKind::TraitAlias(_, _, supertraits) => supertraits,
_ => span_bug!(item.span, "supertrait_auto_impls invoked on non-trait"),
};

let icx = ItemCtxt::new(tcx, trait_def_id);

let self_param_ty = tcx.types.self_param;
let mut bounds = vec![];
icx.lowerer().lower_supertrait_auto_impls(self_param_ty, superbounds, &mut bounds);
ty::EarlyBinder::bind(&*tcx.arena.alloc_from_iter(bounds))
}

// Make sure when elaborating supertraits, probing for associated types, etc.,
// we really truly are elaborating clauses that have `ty` as their self type.
// This is very important since downstream code relies on this being correct.
Expand Down
44 changes: 43 additions & 1 deletion compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {

match hir_bound {
hir::GenericBound::Trait(poly_trait_ref) => {
let hir::TraitBoundModifiers { constness, polarity } = poly_trait_ref.modifiers;
let hir::TraitBoundModifiers { constness, polarity, source: _ } =
poly_trait_ref.modifiers;
let _ = self.lower_poly_trait_ref(
&poly_trait_ref.trait_ref,
poly_trait_ref.span,
Expand Down Expand Up @@ -516,6 +517,47 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
}
}

pub(crate) fn lower_supertrait_auto_impls<'hir>(
&self,
param_ty: Ty<'tcx>,
hir_bounds: impl IntoIterator<Item = &'hir hir::GenericBound<'tcx>>,
supertrait_auto_impl: &mut Vec<(ty::Clause<'tcx>, hir::TraitRefSource)>,
) where
'tcx: 'hir,
{
let predicate_filter = PredicateFilter::SelfOnly;
for hir_bound in hir_bounds {
if self.should_skip_sizedness_bound(hir_bound) {
continue;
}
let hir::GenericBound::Trait(poly_trait_ref) = hir_bound else { continue };
let hir::TraitBoundModifiers { constness, polarity, source } = poly_trait_ref.modifiers;
if !matches!(
source,
hir::TraitRefSource::Supertrait | hir::TraitRefSource::SupertraitAutoImpl
) {
continue;
}
let mut bounds = vec![];
let _ = self.lower_poly_trait_ref(
&poly_trait_ref.trait_ref,
poly_trait_ref.span,
constness,
polarity,
param_ty,
&mut bounds,
predicate_filter,
);
supertrait_auto_impl.extend(bounds.into_iter().filter_map(|(clause, _)| {
if matches!(clause.kind().skip_binder(), ty::ClauseKind::Trait(..)) {
Some((clause, source))
} else {
None
}
}));
}
}

/// Lower an associated item constraint from the HIR into `bounds`.
///
/// ### A Note on Binders
Expand Down
9 changes: 8 additions & 1 deletion compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,14 @@ impl<'a> State<'a> {
}

fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
let hir::TraitBoundModifiers { constness, polarity } = t.modifiers;
let hir::TraitBoundModifiers { constness, polarity, source } = t.modifiers;
match source {
ast::TraitRefSource::Any | ast::TraitRefSource::Supertrait => {}
ast::TraitRefSource::SupertraitAutoImpl => {
self.word("auto");
self.word("impl");
}
}
match constness {
hir::BoundConstness::Never => {}
hir::BoundConstness::Always(_) => self.word("const"),
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,11 @@ impl<'a> CrateMetadataRef<'a> {
}
}

fn get_module_supertraits(self, id: DefIndex, sess: &'a Session) -> impl Iterator<Item = DefId> {
let supertraits = self.root.tables.module_supertraits.get(self, id);
supertraits.decode((self, sess)).into_iter()
}

fn is_ctfe_mir_available(self, id: DefIndex) -> bool {
self.root.tables.mir_for_ctfe.get(self, id).is_some()
}
Expand Down
Loading
Loading