Skip to content
Open
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
3 changes: 2 additions & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1567,9 +1567,10 @@ pub static BUILTIN_ATTRIBUTE_MAP: LazyLock<FxHashMap<Symbol, &BuiltinAttribute>>
map
});

pub fn is_stable_diagnostic_attribute(sym: Symbol, _features: &Features) -> bool {
pub fn is_stable_diagnostic_attribute(sym: Symbol, features: &Features) -> bool {
match sym {
sym::on_unimplemented | sym::do_not_recommend => true,
sym::on_const => features.diagnostic_on_const(),
_ => false,
}
}
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,8 @@ declare_features! (
(incomplete, deref_patterns, "1.79.0", Some(87121)),
/// Allows deriving the From trait on single-field structs.
(unstable, derive_from, "1.91.0", Some(144889)),
/// Allows giving non-const impls custom diagnostic messages if attempted to be used as const
(unstable, diagnostic_on_const, "CURRENT_RUSTC_VERSION", Some(143874)),
/// Allows `#[doc(cfg(...))]`.
(unstable, doc_cfg, "1.21.0", Some(43781)),
/// Allows `#[doc(masked)]`.
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(),
tcx.ensure_ok().type_of(def_id);
tcx.ensure_ok().predicates_of(def_id);
tcx.ensure_ok().associated_items(def_id);
check_diagnostic_attrs(tcx, def_id);
if of_trait {
let impl_trait_header = tcx.impl_trait_header(def_id);
res = res.and(
Expand All @@ -828,7 +829,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(),
tcx.ensure_ok().predicates_of(def_id);
tcx.ensure_ok().associated_items(def_id);
let assoc_items = tcx.associated_items(def_id);
check_on_unimplemented(tcx, def_id);
check_diagnostic_attrs(tcx, def_id);

for &assoc_item in assoc_items.in_definition_order() {
match assoc_item.kind {
Expand Down Expand Up @@ -1078,7 +1079,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(),
})
}

pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, def_id: LocalDefId) {
pub(super) fn check_diagnostic_attrs(tcx: TyCtxt<'_>, def_id: LocalDefId) {
// an error would be reported if this fails.
let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
}
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_passes/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ passes_deprecated_annotation_has_no_effect =
passes_deprecated_attribute =
deprecated attribute must be paired with either stable or unstable attribute

passes_diagnostic_diagnostic_on_const_only_for_trait_impls =
`#[diagnostic::on_const]` can only be applied to trait impls

passes_diagnostic_diagnostic_on_unimplemented_only_for_traits =
`#[diagnostic::on_unimplemented]` can only be applied to trait definitions

Expand Down
19 changes: 19 additions & 0 deletions compiler/rustc_passes/src/check_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ use crate::{errors, fluent_generated as fluent};
#[diag(passes_diagnostic_diagnostic_on_unimplemented_only_for_traits)]
struct DiagnosticOnUnimplementedOnlyForTraits;

#[derive(LintDiagnostic)]
#[diag(passes_diagnostic_diagnostic_on_const_only_for_trait_impls)]
struct DiagnosticOnConstOnlyForTraitImpls;

fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
match impl_item.kind {
hir::ImplItemKind::Const(..) => Target::AssocConst,
Expand Down Expand Up @@ -296,6 +300,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
[sym::diagnostic, sym::on_unimplemented, ..] => {
self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
}
[sym::diagnostic, sym::on_const, ..] => {
self.check_diagnostic_on_const(attr.span(), hir_id, target)
}
[sym::thread_local, ..] => self.check_thread_local(attr, span, target),
[sym::doc, ..] => self.check_doc_attrs(
attr,
Expand Down Expand Up @@ -519,6 +526,18 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
}
}

/// Checks if `#[diagnostic::on_const]` is applied to a trait impl
fn check_diagnostic_on_const(&self, attr_span: Span, hir_id: HirId, target: Target) {
if !matches!(target, Target::Impl { of_trait: true }) {
self.tcx.emit_node_span_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
hir_id,
attr_span,
DiagnosticOnConstOnlyForTraitImpls,
);
}
}
Comment on lines +529 to +539
Copy link
Contributor

@estebank estebank Nov 7, 2025

Choose a reason for hiding this comment

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

Should we also check that the impl is not const? Otherwise the annotation is fully inert in that case, right?


/// Checks if an `#[inline]` is applied to a function or a closure.
fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
match target {
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_resolve/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,10 +687,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
&& let [namespace, attribute, ..] = &*path.segments
&& namespace.ident.name == sym::diagnostic
&& ![sym::on_unimplemented, sym::do_not_recommend].contains(&attribute.ident.name)
&& ![sym::on_unimplemented, sym::do_not_recommend, sym::on_const]
.contains(&attribute.ident.name)
{
let typo_name = find_best_match_for_name(
&[sym::on_unimplemented, sym::do_not_recommend],
&[sym::on_unimplemented, sym::do_not_recommend, sym::on_const],
attribute.ident.name,
Some(5),
);
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,7 @@ symbols! {
destructuring_assignment,
diagnostic,
diagnostic_namespace,
diagnostic_on_const,
dialect,
direct,
discriminant_kind,
Expand Down Expand Up @@ -1587,6 +1588,7 @@ symbols! {
old_name,
omit_gdb_pretty_printer_section,
on,
on_const,
on_unimplemented,
opaque,
opaque_module_name_placeholder: "<opaque>",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use super::{
};
use crate::error_reporting::TypeErrCtxt;
use crate::error_reporting::infer::TyCategory;
use crate::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
use crate::error_reporting::traits::report_dyn_incompatibility;
use crate::errors::{ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn};
use crate::infer::{self, InferCtxt, InferCtxtExt as _};
Expand Down Expand Up @@ -586,7 +587,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
}

ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
self.report_host_effect_error(bound_predicate.rebind(predicate), obligation.param_env, span)
self.report_host_effect_error(bound_predicate.rebind(predicate), &obligation, span)
}

ty::PredicateKind::Subtype(predicate) => {
Expand Down Expand Up @@ -807,20 +808,18 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
fn report_host_effect_error(
&self,
predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
param_env: ty::ParamEnv<'tcx>,
main_obligation: &PredicateObligation<'tcx>,
span: Span,
) -> Diag<'a> {
// FIXME(const_trait_impl): We should recompute the predicate with `[const]`
// if it's `const`, and if it holds, explain that this bound only
// *conditionally* holds. If that fails, we should also do selection
// to drill this down to an impl or built-in source, so we can
// point at it and explain that while the trait *is* implemented,
// that implementation is not const.
// *conditionally* holds.
let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
trait_ref: predicate.trait_ref,
polarity: ty::PredicatePolarity::Positive,
});
let mut file = None;

let err_msg = self.get_standard_error_message(
trait_ref,
None,
Expand All @@ -831,18 +830,21 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
);
let mut diag = struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
*diag.long_ty_path() = file;
if !self.predicate_may_hold(&Obligation::new(
let obligation = Obligation::new(
self.tcx,
ObligationCause::dummy(),
param_env,
main_obligation.param_env,
trait_ref,
)) {
);
if !self.predicate_may_hold(&obligation) {
diag.downgrade_to_delayed_bug();
}
for candidate in self.find_similar_impl_candidates(trait_ref) {
let CandidateSimilarity::Exact { .. } = candidate.similarity else { continue };
let impl_did = candidate.impl_def_id;
let trait_did = candidate.trait_ref.def_id;

if let Ok(Some(ImplSource::UserDefined(impl_data))) =
SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref.skip_binder()))
{
let impl_did = impl_data.impl_def_id;
let trait_did = trait_ref.def_id();
let impl_span = self.tcx.def_span(impl_did);
let trait_name = self.tcx.item_name(trait_did);

Expand All @@ -864,6 +866,42 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
impl_span,
format!("trait `{trait_name}` is implemented but not `const`"),
);

let (condition_options, format_args) = self.on_unimplemented_components(
trait_ref,
main_obligation,
diag.long_ty_path(),
);

if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, impl_did)
{
let note = command.evaluate(
self.tcx,
predicate.skip_binder().trait_ref,
&condition_options,
&format_args,
);
let OnUnimplementedNote {
message,
label,
notes,
parent_label,
append_const_msg: _,
} = note;

if let Some(message) = message {
diag.primary_message(message);
}
if let Some(label) = label {
diag.span_label(impl_span, label);
}
for note in notes {
diag.note(note);
}
if let Some(parent_label) = parent_label {
diag.span_label(impl_span, parent_label);
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit};
use rustc_errors::codes::*;
use rustc_errors::{ErrorGuaranteed, struct_span_code_err};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{AttrArgs, Attribute};
use rustc_macros::LintDiagnostic;
Expand Down Expand Up @@ -103,7 +104,27 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
if trait_pred.polarity() != ty::PredicatePolarity::Positive {
return OnUnimplementedNote::default();
}
let (condition_options, format_args) =
self.on_unimplemented_components(trait_pred, obligation, long_ty_path);
if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, trait_pred.def_id())
{
command.evaluate(
self.tcx,
trait_pred.skip_binder().trait_ref,
&condition_options,
&format_args,
)
} else {
OnUnimplementedNote::default()
}
}

pub(crate) fn on_unimplemented_components(
&self,
trait_pred: ty::PolyTraitPredicate<'tcx>,
obligation: &PredicateObligation<'tcx>,
long_ty_path: &mut Option<PathBuf>,
) -> (ConditionOptions, FormatArgs<'tcx>) {
let (def_id, args) = self
.impl_similar_to(trait_pred, obligation)
.unwrap_or_else(|| (trait_pred.def_id(), trait_pred.skip_binder().trait_ref.args));
Expand Down Expand Up @@ -293,12 +314,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
.collect();

let format_args = FormatArgs { this, trait_sugared, generic_args, item_context };

if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, def_id) {
command.evaluate(self.tcx, trait_pred.trait_ref, &condition_options, &format_args)
} else {
OnUnimplementedNote::default()
}
(condition_options, format_args)
}
}

Expand All @@ -325,7 +341,7 @@ pub struct OnUnimplementedDirective {
}

/// For the `#[rustc_on_unimplemented]` attribute
#[derive(Default)]
#[derive(Default, Debug)]
pub struct OnUnimplementedNote {
pub message: Option<String>,
pub label: Option<String>,
Expand Down Expand Up @@ -562,17 +578,21 @@ impl<'tcx> OnUnimplementedDirective {
}

pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<Option<Self>, ErrorGuaranteed> {
if !tcx.is_trait(item_def_id) {
let attr = if tcx.is_trait(item_def_id) {
sym::on_unimplemented
} else if let DefKind::Impl { of_trait: true } = tcx.def_kind(item_def_id) {
sym::on_const
} else {
// It could be a trait_alias (`trait MyTrait = SomeOtherTrait`)
// or an implementation (`impl MyTrait for Foo {}`)
//
// We don't support those.
return Ok(None);
}
};
if let Some(attr) = tcx.get_attr(item_def_id, sym::rustc_on_unimplemented) {
return Self::parse_attribute(attr, false, tcx, item_def_id);
} else {
tcx.get_attrs_by_path(item_def_id, &[sym::diagnostic, sym::on_unimplemented])
tcx.get_attrs_by_path(item_def_id, &[sym::diagnostic, attr])
.filter_map(|attr| Self::parse_attribute(attr, true, tcx, item_def_id).transpose())
.try_fold(None, |aggr: Option<Self>, directive| {
let directive = directive?;
Expand Down
1 change: 1 addition & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
#![feature(decl_macro)]
#![feature(deprecated_suggestion)]
#![feature(derive_const)]
#![feature(diagnostic_on_const)]
#![feature(doc_cfg)]
#![feature(doc_notable_trait)]
#![feature(extern_types)]
Expand Down
16 changes: 16 additions & 0 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,10 @@ impl<T, const N: usize> *const [T; N] {

/// Pointer equality is by address, as produced by the [`<*const T>::addr`](pointer::addr) method.
#[stable(feature = "rust1", since = "1.0.0")]
#[diagnostic::on_const(
message = "pointers cannot be reliably compared during const eval",
note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
)]
impl<T: PointeeSized> PartialEq for *const T {
#[inline]
#[allow(ambiguous_wide_pointer_comparisons)]
Expand All @@ -1576,10 +1580,18 @@ impl<T: PointeeSized> PartialEq for *const T {

/// Pointer equality is an equivalence relation.
#[stable(feature = "rust1", since = "1.0.0")]
#[diagnostic::on_const(
message = "pointers cannot be reliably compared during const eval",
note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
)]
impl<T: PointeeSized> Eq for *const T {}

/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
#[stable(feature = "rust1", since = "1.0.0")]
#[diagnostic::on_const(
message = "pointers cannot be reliably compared during const eval",
note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
)]
impl<T: PointeeSized> Ord for *const T {
#[inline]
#[allow(ambiguous_wide_pointer_comparisons)]
Expand All @@ -1596,6 +1608,10 @@ impl<T: PointeeSized> Ord for *const T {

/// Pointer comparison is by address, as produced by the `[`<*const T>::addr`](pointer::addr)` method.
#[stable(feature = "rust1", since = "1.0.0")]
#[diagnostic::on_const(
message = "pointers cannot be reliably compared during const eval",
note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
)]
impl<T: PointeeSized> PartialOrd for *const T {
#[inline]
#[allow(ambiguous_wide_pointer_comparisons)]
Expand Down
Loading
Loading