Skip to content
Merged
15 changes: 15 additions & 0 deletions compiler/rustc_attr_ir/src/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,15 @@ impl fmt::Display for AutoDiffItem {
}
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[derive(StableHash, Encodable, Decodable, PrintAttribute)]
pub enum RustcAssertVarianceKind {
Covariant,
Invariant,
Contravariant,
Bivariant,
Comment on lines +724 to +727

@clarfonthey clarfonthey Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know it technically doesn't matter for the implementation, but I do kinda wish these were:

Suggested change
Covariant,
Invariant,
Contravariant,
Bivariant,
Invariant = 0b00,
Covariant = 0b01,
Contravariant = 0b10,
Bivariant = 0b11,

so that they internally represent the variance a bit better, even if we don't rely on that.

View changes since the review

@RuleOfSix RuleOfSix Oct 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this idea, but it seems more relevant for rustc_type_ir::Variance since that's what's actually used by the compiler to represent variance.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(also worth asking whether these two types should be different at all)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rather not that rustc_attr_ir depends on rustc_type_ir, or the other way around.

It could live earlier in the crate graph, in rustc_structures, but moving it would also mean moving a lot of Variance related methods out of rustc_type_ir. So merging these two comes with downsides.

}

#[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
pub struct UnstableRemovedFeature {
pub feature: Symbol,
Expand Down Expand Up @@ -1145,6 +1154,12 @@ pub enum AttributeKind {
/// Represents `#[rustc_as_ptr]` (used by the `dangling_pointers_from_temporaries` lint).
RustcAsPtr,

/// Represents `#[rustc_assert_variance]`.
RustcAssertVariance {
span: Span,
kind: RustcAssertVarianceKind,
},

/// Represents `#[rustc_autodiff]`.
RustcAutodiff(Option<Box<RustcAutodiff>>),

Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_attr_ir/src/encode_cross_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl AttributeKind {
RustcAllowIncoherentImpl(..) => No,
RustcAllowLifetimeDependentSpecialization => No,
RustcAsPtr => Yes,
RustcAssertVariance { .. } => No,
RustcAutodiff(..) => Yes,
RustcBodyStability { .. } => No,
RustcBuiltinMacro { .. } => Yes,
Expand Down Expand Up @@ -323,6 +324,7 @@ impl AttributeKind {
RustcAllowIncoherentImpl(..) => false,
RustcAllowLifetimeDependentSpecialization => false,
RustcAsPtr => false,
RustcAssertVariance { .. } => false,
RustcAutodiff(..) => false,
RustcBodyStability { .. } => false,
RustcBuiltinMacro { .. } => false,
Expand Down
55 changes: 53 additions & 2 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::path::PathBuf;
use rustc_ast::{GenericParamKind, ItemKind, LitIntType, LitKind, MetaItemLit};
use rustc_attr_ir::lang_items::LangItem;
use rustc_attr_ir::{
BorrowckGraphvizFormatKind, CguFields, CguKind, RustcCleanAttribute, RustcCleanQueries,
RustcMirKind,
BorrowckGraphvizFormatKind, CguFields, CguKind, RustcAssertVarianceKind, RustcCleanAttribute,
RustcCleanQueries, RustcMirKind,
};
use rustc_data_structures::fx::FxHashMap;
use rustc_feature::AttributeStability;
Expand Down Expand Up @@ -1168,3 +1168,54 @@ impl NoArgsAttributeParser for RustcCanonicalSymbolParser {
);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcCanonicalSymbol;
}

pub(crate) struct RustcAssertVarianceParser;

impl SingleAttributeParser for RustcAssertVarianceParser {
const PATH: &[Symbol] = &[sym::rustc_assert_variance];

const STABILITY: AttributeStability = unstable!(rustc_attrs);

const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[
Allow(Target::TypeParam),
Allow(Target::LifetimeParam),
Allow(Target::ConstParam),

@clarfonthey clarfonthey Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can const parameters be anything other than invariant? 😨

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not to my knowledge. It's more there for syntactic completeness so that the attribute can attach to any generic parameter.

]);

const TEMPLATE: AttributeTemplate =
template!(OneOf: &[sym::covariant, sym::invariant, sym::contravariant, sym::bivariant]);

fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option<AttributeKind> {
let arg = cx.expect_single_element_list(args, cx.attr_span)?;

let mut fail_arg = |span| {
cx.adcx().expected_specific_argument(
span,
&[sym::covariant, sym::invariant, sym::contravariant, sym::bivariant],
)
};

let Some(arg) = arg.meta_item_no_args() else {
fail_arg(arg.span());
return None;
};

let Some(arg) = arg.ident() else {
fail_arg(arg.span());
return None;
};

let kind = match arg.name {
sym::covariant => RustcAssertVarianceKind::Covariant,
sym::invariant => RustcAssertVarianceKind::Invariant,
sym::contravariant => RustcAssertVarianceKind::Contravariant,
sym::bivariant => RustcAssertVarianceKind::Bivariant,
_ => {
fail_arg(arg.span);
return None;
}
};

Some(AttributeKind::RustcAssertVariance { span: cx.attr_span, kind })
}
}
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ attribute_parsers!(
Single<ReexportTestHarnessMainParser>,
Single<RustcAbiParser>,
Single<RustcAllocatorZeroedVariantParser>,
Single<RustcAssertVarianceParser>,
Single<RustcAutodiffParser>,
Single<RustcBuiltinMacroParser>,
Single<RustcDeprecatedSafe2024Parser>,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[
// types (as well as any others in future).
sym::rustc_lint_opt_deny_field_access,
sym::rustc_diagnostic_opaque,
sym::rustc_assert_variance,

// ==========================================================================
// Internal attributes, Const related:
Expand Down
70 changes: 68 additions & 2 deletions compiler/rustc_passes/src/check_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_attr_ir::lang_items::LangItem;
use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
use rustc_attr_ir::{
Attribute, AttributeKind, DocAttribute, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
OptimizeAttr, ReprAttr, find_attr,
OptimizeAttr, ReprAttr, RustcAssertVarianceKind, find_attr,
};
use rustc_attr_parsing::AttributeParser;
use rustc_data_structures::thin_vec::ThinVec;
Expand All @@ -37,7 +37,7 @@ use rustc_middle::hir::nested_filter;
use rustc_middle::query::Providers;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized};
use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized, Variance};
use rustc_session::diagnostics::feature_err;
use rustc_span::edition::Edition;
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug, sym};
Expand Down Expand Up @@ -223,6 +223,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
AttributeKind::Linkage(_linkage, span) => {
self.check_linkage(*span, hir_id, target, item)
}
AttributeKind::RustcAssertVariance { span: attr_span, kind } => {
self.check_rustc_assert_variance(span, *attr_span, hir_id, target, *kind);
}

// All of the following attributes have no specific checks.
// tidy-alphabetical-start
Expand Down Expand Up @@ -1417,6 +1420,69 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
_ => {}
}
}

fn check_rustc_assert_variance(

@fmease fmease Oct 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In PR #161351 I moved a #[rustc_dump*] impl out of check_attr because I believe this module is meant to only contain complex target & validity checks for attributes, not however their "business logic".

I guess rustc_hir_analysis would be a good fit here, too?

View changes since the review

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see no harm in it being in check_attr, stuff like "is #[may_dangle] on a Drop impl" is also in check_attr. Happy to cede to wherever you think this fits best though.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I just thought y'all wanted to yeet check_attr.rs at some point & have parsing & validity checks in rustc_attr_parsing in which case it would be better not to add onto it but I don't know if that's still the plan / even feasible.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a decent amount of "need to run queries etc for this check" code in check_attr, so getting rid of check_attr entirely isn't going to happen sadly.

&self,
span: Span,
attr_span: Span,
hir_id: HirId,
target: Target,
kind: RustcAssertVarianceKind,
) {
// If the target is invalid the parser has already emitted an error
if !matches!(target, Target::TypeParam | Target::LifetimeParam | Target::ConstParam) {
return;
}

let Node::GenericParam(param) = self.tcx.hir_node(hir_id) else { return };
let owner = hir_id.owner.to_def_id();
let variances = self.tcx.variances_of(owner);
let generics = self.tcx.generics_of(owner);

let variance = generics
.own_params
.iter()
.zip(variances.iter())
.filter(|(other_param, _)| other_param.def_id == param.def_id.to_def_id())
.map(|(_, variance)| variance)
.nth(0)
.expect("generic parameter should have variance");

match (kind, variance) {
(RustcAssertVarianceKind::Covariant, Variance::Covariant) => {}
(RustcAssertVarianceKind::Invariant, Variance::Invariant) => {}
(RustcAssertVarianceKind::Contravariant, Variance::Contravariant) => {}
(RustcAssertVarianceKind::Bivariant, Variance::Bivariant) => {}
(asserted, actual) => {
let expected_variance = match asserted {
RustcAssertVarianceKind::Covariant => sym::covariant,
RustcAssertVarianceKind::Invariant => sym::invariant,
RustcAssertVarianceKind::Contravariant => sym::contravariant,
RustcAssertVarianceKind::Bivariant => sym::bivariant,
};

let actual_variance = match actual {
Variance::Covariant => sym::covariant,
Variance::Invariant => sym::invariant,
Variance::Contravariant => sym::contravariant,
Variance::Bivariant => sym::bivariant,
};

let item_ident = self.tcx.item_ident(owner);

let note = diagnostics::RustcAssertVarianceFailedNote { span: attr_span };
self.tcx.dcx().emit_err(diagnostics::RustcAssertVarianceFailed {
item_span: self.tcx.def_span(owner),
note,
param_ident: param.name.ident(),
param_span: span,
item_ident,
expected_variance,
actual_variance,
});
}
}
}
}

impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
Expand Down
22 changes: 22 additions & 0 deletions compiler/rustc_passes/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1079,3 +1079,25 @@ pub(crate) struct RustcAtumSuggestion {
)]
pub unstable_mod_span: Span,
}

#[derive(Diagnostic)]
#[diag("`{$item_ident}` is expected to be {$expected_variance} in `{$param_ident}` but is not")]
pub(crate) struct RustcAssertVarianceFailed {
#[primary_span]
pub item_span: Span,
#[subdiagnostic]
pub note: RustcAssertVarianceFailedNote,
#[label("`{$item_ident}` is {$actual_variance} in `{$param_ident}`")]
pub param_span: Span,
pub param_ident: Ident,
pub item_ident: Ident,
pub expected_variance: Symbol,
pub actual_variance: Symbol,
}

#[derive(Subdiagnostic)]
#[note("required by this attribute")]
pub(crate) struct RustcAssertVarianceFailedNote {
#[primary_span]
pub span: Span,
}
5 changes: 5 additions & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ symbols! {
bits,
bitxor,
bitxor_assign,
bivariant,
black_box,
block,
blocking,
Expand Down Expand Up @@ -747,6 +748,7 @@ symbols! {
contracts_ensures,
contracts_internals,
contracts_requires,
contravariant,
convert,
coprocessor,
copy,
Expand All @@ -769,6 +771,7 @@ symbols! {
coroutines,
cos,
count,
covariant,
covariant_unsafe_cell,
coverage,
coverage_attribute,
Expand Down Expand Up @@ -1189,6 +1192,7 @@ symbols! {
into_try_type,
intra_doc_pointers,
intrinsics,
invariant,
irrefutable_let_patterns,
is,
is_auto,
Expand Down Expand Up @@ -1817,6 +1821,7 @@ symbols! {
rustc_allowed_through_unstable_modules,
rustc_always_gca,
rustc_as_ptr,
rustc_assert_variance,
rustc_attrs,
rustc_autodiff,
rustc_builtin_macro,
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ impl<T: ?Sized> From<BoxRaw<T>> for NonNull<T> {
// The declaration of the `Box` struct must be kept in sync with the
// compiler or ICEs will happen.
pub struct Box<
T: ?Sized,
#[rustc_assert_variance(covariant)] T: ?Sized,
#[stable(feature = "allocator_api", since = "1.100.0")] A: Allocator = Global,
>(BoxRaw<T>, A);

Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/rcs/arc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ macro_rules! acquire {
note = "consider using `Arc::clone`"
)]
pub struct Arc<
T: ?Sized,
#[rustc_assert_variance(covariant)] T: ?Sized,
// FIXME: When stabilizing this parameter, the `AllocatorNightly`
// bound on the `From<Box>` impl *must* be weaked to `Allocator`,
// as `Box` is fundamental!
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/rcs/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ use crate::vec::Vec;
// repr(align(2)) (forcing alignment to at least 2) is required because usize
// has 1-byte alignment on AVR.
#[repr(C, align(2))]
struct RcInner<T: ?Sized> {
struct RcInner<#[rustc_assert_variance(covariant)] T: ?Sized> {
strong: Cell<usize>,
weak: Cell<usize>,
value: T,
Expand Down Expand Up @@ -323,7 +323,7 @@ fn rc_inner_layout_for_value_layout(layout: Layout) -> Layout {
)]

pub struct Rc<
T: ?Sized,
#[rustc_assert_variance(covariant)] T: ?Sized,
// FIXME: When stabilizing this parameter, the `AllocatorNightly`
// bound on the `From<Box>` impl *must* be weaked to `Allocator`,
// as `Box` is fundamental!
Expand Down
8 changes: 4 additions & 4 deletions library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ pub use once::OnceCell;
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
#[rustc_pub_transparent]
pub struct Cell<T: ?Sized> {
pub struct Cell<#[rustc_assert_variance(invariant)] T: ?Sized> {
value: UnsafeCell<T>,
}

Expand Down Expand Up @@ -849,7 +849,7 @@ impl<T: CloneFromCell> Cell<T> {
/// See the [module-level documentation](self) for more.
#[rustc_diagnostic_item = "RefCell"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T: ?Sized> {
pub struct RefCell<#[rustc_assert_variance(invariant)] T: ?Sized> {
borrow: Cell<BorrowCounter>,
// Stores the location of the earliest currently active borrow.
// This gets updated whenever we go from having zero borrows
Expand Down Expand Up @@ -2308,7 +2308,7 @@ impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
#[rustc_pub_transparent]
pub struct UnsafeCell<T: ?Sized> {
pub struct UnsafeCell<#[rustc_assert_variance(invariant)] T: ?Sized> {
value: T,
}

Expand Down Expand Up @@ -2603,7 +2603,7 @@ impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafeCell<U>> for UnsafeCell<T>
#[repr(transparent)]
#[rustc_diagnostic_item = "SyncUnsafeCell"]
#[rustc_pub_transparent]
pub struct SyncUnsafeCell<T: ?Sized> {
pub struct SyncUnsafeCell<#[rustc_assert_variance(invariant)] T: ?Sized> {
value: UnsafeCell<T>,
}

Expand Down
2 changes: 1 addition & 1 deletion library/core/src/cell/covariant_unsafe_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::ptr::{self, NonNull};
// hardcode its variance to be **co**variant in `T`, even though it is wrapping `UnsafeCell` which
// is **in**variant in `T`.
#[lang = "covariant_unsafe_cell"]
pub struct CovariantUnsafeCell<T: ?Sized>(UnsafeCell<T>);
pub struct CovariantUnsafeCell<#[rustc_assert_variance(covariant)] T: ?Sized>(UnsafeCell<T>);

#[unstable(feature = "covariant_unsafe_cell", issue = "159735")]
impl<T: ?Sized> !Sync for CovariantUnsafeCell<T> {}
Expand Down
5 changes: 4 additions & 1 deletion library/core/src/cell/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ enum State<T, F> {
/// // 92
/// ```
#[stable(feature = "lazy_cell", since = "1.80.0")]
pub struct LazyCell<T, F = fn() -> T> {
pub struct LazyCell<
#[rustc_assert_variance(invariant)] T,
#[rustc_assert_variance(invariant)] F = fn() -> T,
> {
state: UnsafeCell<State<T, F>>,
}

Expand Down
2 changes: 1 addition & 1 deletion library/core/src/cell/once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use crate::{fmt, mem};
/// assert!(cell.get().is_some());
/// ```
#[stable(feature = "once_cell", since = "1.70.0")]
pub struct OnceCell<T> {
pub struct OnceCell<#[rustc_assert_variance(invariant)] T> {
// Invariant: written to at most once.
inner: UnsafeCell<Option<T>>,
}
Expand Down
Loading
Loading