Skip to content

Port #[non_exhaustive] to the new attribute parsing infrastructure #143085

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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: 3 additions & 0 deletions compiler/rustc_attr_data_structures/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,9 @@ pub enum AttributeKind {
/// Represents `#[no_mangle]`
NoMangle(Span),

/// Represents `#[non_exhaustive]`
NonExhaustive(Span),

/// Represents `#[optimize(size|speed)]`
Optimize(OptimizeAttr, Span),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ impl AttributeKind {
ExportName { .. } => Yes,
Inline(..) => No,
MacroTransparency(..) => Yes,
NonExhaustive(..) => Yes,
Repr(..) => No,
Stability { .. } => Yes,
Cold(..) => No,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/attributes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub(crate) mod inline;
pub(crate) mod lint_helpers;
pub(crate) mod loop_match;
pub(crate) mod must_use;
pub(crate) mod non_exhaustive;
pub(crate) mod repr;
pub(crate) mod semantics;
pub(crate) mod stability;
Expand Down
25 changes: 25 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use rustc_attr_data_structures::AttributeKind;
use rustc_feature::{AttributeTemplate, template};
use rustc_span::{Symbol, sym};

use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser};
use crate::context::{AcceptContext, Stage};
use crate::parser::ArgParser;

pub(crate) struct NonExhaustiveParser;

impl<S: Stage> SingleAttributeParser<S> for NonExhaustiveParser {
const PATH: &[Symbol] = &[sym::non_exhaustive];
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;

const TEMPLATE: AttributeTemplate = template!(Word);

fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
if let Err(span) = args.no_args() {
cx.expected_no_args(span);
return None;
}
Some(AttributeKind::NonExhaustive(cx.attr_span))
}
}
2 changes: 2 additions & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
use crate::attributes::lint_helpers::{AsPtrParser, PubTransparentParser};
use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser};
use crate::attributes::must_use::MustUseParser;
use crate::attributes::non_exhaustive::NonExhaustiveParser;
use crate::attributes::repr::{AlignParser, ReprParser};
use crate::attributes::semantics::MayDangleParser;
use crate::attributes::stability::{
Expand Down Expand Up @@ -123,6 +124,7 @@ attribute_parsers!(
Single<MayDangleParser>,
Single<MustUseParser>,
Single<NoMangleParser>,
Single<NonExhaustiveParser>,
Single<OptimizeParser>,
Single<PubTransparentParser>,
Single<RustcForceInlineParser>,
Expand Down
8 changes: 5 additions & 3 deletions compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1057,9 +1057,11 @@ fn lower_variant<'tcx>(
fields,
parent_did.to_def_id(),
recovered,
adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive)
|| variant_did
.is_some_and(|variant_did| tcx.has_attr(variant_did, sym::non_exhaustive)),
adt_kind == AdtKind::Struct
&& find_attr!(tcx.get_all_attrs(parent_did), AttributeKind::NonExhaustive(..))
|| variant_did.is_some_and(|variant_did| {
find_attr!(tcx.get_all_attrs(variant_did), AttributeKind::NonExhaustive(..))
}),
)
}

Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_middle/src/ty/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::ops::Range;
use std::str;

use rustc_abi::{FIRST_VARIANT, ReprOptions, VariantIdx};
use rustc_attr_data_structures::{AttributeKind, find_attr};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::intern::Interned;
Expand Down Expand Up @@ -278,7 +279,9 @@ impl AdtDefData {
debug!("AdtDef::new({:?}, {:?}, {:?}, {:?})", did, kind, variants, repr);
let mut flags = AdtFlags::NO_ADT_FLAGS;

if kind == AdtKind::Enum && tcx.has_attr(did, sym::non_exhaustive) {
if kind == AdtKind::Enum
&& find_attr!(tcx.get_all_attrs(did), AttributeKind::NonExhaustive(..))
{
debug!("found non-exhaustive variant list for {:?}", did);
flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_parse/src/validate_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ fn emit_malformed_attribute(
| sym::cold
| sym::naked
| sym::no_mangle
| sym::non_exhaustive
| sym::must_use
| sym::track_caller
) {
Expand Down
16 changes: 8 additions & 8 deletions compiler/rustc_passes/src/check_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
Attribute::Parsed(AttributeKind::TrackCaller(attr_span)) => {
self.check_track_caller(hir_id, *attr_span, attrs, span, target)
}
Attribute::Parsed(AttributeKind::NonExhaustive(attr_span)) => {
self.check_non_exhaustive(hir_id, *attr_span, span, target, item)
}
Attribute::Parsed(
AttributeKind::BodyStability { .. }
| AttributeKind::ConstStabilityIndirect
Expand Down Expand Up @@ -213,7 +216,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
[sym::no_sanitize, ..] => {
self.check_no_sanitize(attr, span, target)
}
[sym::non_exhaustive, ..] => self.check_non_exhaustive(hir_id, attr, span, target, item),
[sym::marker, ..] => self.check_marker(hir_id, attr, span, target),
[sym::target_feature, ..] => {
self.check_target_feature(hir_id, attr, span, target, attrs)
Expand Down Expand Up @@ -749,7 +751,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
fn check_non_exhaustive(
&self,
hir_id: HirId,
attr: &Attribute,
attr_span: Span,
span: Span,
target: Target,
item: Option<ItemLike<'_>>,
Expand All @@ -764,7 +766,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
&& fields.iter().any(|f| f.default.is_some())
{
self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
attr_span: attr.span(),
attr_span,
defn_span: span,
});
}
Expand All @@ -775,13 +777,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
// erroneously allowed it and some crates used it accidentally, to be compatible
// with crates depending on them, we can't throw an error here.
Target::Field | Target::Arm | Target::MacroDef => {
self.inline_attr_str_error_with_macro_def(hir_id, attr.span(), "non_exhaustive");
self.inline_attr_str_error_with_macro_def(hir_id, attr_span, "non_exhaustive");
}
_ => {
self.dcx().emit_err(errors::NonExhaustiveWrongLocation {
attr_span: attr.span(),
defn_span: span,
});
self.dcx()
.emit_err(errors::NonExhaustiveWrongLocation { attr_span, defn_span: span });
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use rustc_ast::{
self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemInner, MetaItemKind, ModKind, NodeId, Path,
};
use rustc_ast_pretty::pprust;
use rustc_attr_data_structures::{self as attr, Stability};
use rustc_attr_data_structures::{self as attr, AttributeKind, Stability, find_attr};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_errors::codes::*;
Expand Down Expand Up @@ -1998,9 +1998,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Otherwise, point out if the struct has any private fields.
if let Some(def_id) = res.opt_def_id()
&& !def_id.is_local()
&& let Some(attr) = self.tcx.get_attr(def_id, sym::non_exhaustive)
&& let Some(attr_span) = find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::NonExhaustive(span) => *span)
{
non_exhaustive = Some(attr.span());
non_exhaustive = Some(attr_span);
} else if let Some(span) = ctor_fields_span {
let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
err.subdiagnostic(label);
Expand Down
3 changes: 2 additions & 1 deletion src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2746,7 +2746,8 @@ fn add_without_unwanted_attributes<'hir>(
attrs.push((Cow::Owned(attr), import_parent));
}
}
hir::Attribute::Parsed(..) if is_inline => {
// FIXME: make sure to exclude `#[cfg_trace]` here when it is ported to the new parsers
hir::Attribute::Parsed(..) => {
Copy link
Contributor Author

@JonathanBrouwer JonathanBrouwer Jun 27, 2025

Choose a reason for hiding this comment

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

This PR is blocked on #143083, because it needs it to get a passing CI.
This PR contains that PR as a commit. Other than that, this should be reviewable.

attrs.push((Cow::Owned(attr), import_parent));
}
_ => {}
Expand Down
6 changes: 4 additions & 2 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use arrayvec::ArrayVec;
use itertools::Either;
use rustc_abi::{ExternAbi, VariantIdx};
use rustc_attr_data_structures::{
AttributeKind, ConstStability, Deprecation, Stability, StableSince,
AttributeKind, ConstStability, Deprecation, Stability, StableSince, find_attr,
};
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
use rustc_hir::def::{CtorKind, DefKind, Res};
Expand Down Expand Up @@ -621,7 +621,7 @@ impl Item {
}

pub(crate) fn is_non_exhaustive(&self) -> bool {
self.attrs.other_attrs.iter().any(|a| a.has_name(sym::non_exhaustive))
find_attr!(&self.attrs.other_attrs, AttributeKind::NonExhaustive(..))
}

/// Returns a documentation-level item type from the item.
Expand Down Expand Up @@ -760,6 +760,8 @@ impl Item {
} else if let hir::Attribute::Parsed(AttributeKind::ExportName { name, .. }) = attr
{
Some(format!("#[export_name = \"{name}\"]"))
} else if let hir::Attribute::Parsed(AttributeKind::NonExhaustive(..)) = attr {
Some("#[non_exhaustive]".to_string())
} else if is_json {
match attr {
// rustdoc-json stores this in `Item::deprecation`, so we
Expand Down
6 changes: 4 additions & 2 deletions src/tools/clippy/clippy_lints/src/exhaustive_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use rustc_errors::Applicability;
use rustc_hir::{Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::sym;
use rustc_attr_data_structures::AttributeKind;
use rustc_attr_data_structures::find_attr;


declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -85,7 +87,7 @@ impl LateLintPass<'_> for ExhaustiveItems {
};
if cx.effective_visibilities.is_exported(item.owner_id.def_id)
&& let attrs = cx.tcx.hir_attrs(item.hir_id())
&& !attrs.iter().any(|a| a.has_name(sym::non_exhaustive))
&& !find_attr!(attrs, AttributeKind::NonExhaustive(..))
&& fields.iter().all(|f| cx.tcx.visibility(f.def_id).is_public())
{
span_lint_and_then(cx, lint, item.span, msg, |diag| {
Expand Down
13 changes: 7 additions & 6 deletions src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ use clippy_utils::is_doc_hidden;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet_indent;
use itertools::Itertools;
use rustc_ast::attr;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Applicability;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
use rustc_hir::{Expr, ExprKind, Item, ItemKind, QPath, TyKind, VariantData};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
use rustc_span::def_id::LocalDefId;
use rustc_span::{Span, sym};
use rustc_span::Span;
use rustc_attr_data_structures::find_attr;
use rustc_attr_data_structures::AttributeKind;

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -93,7 +94,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
.then_some((v.def_id, v.span))
});
if let Ok((id, span)) = iter.exactly_one()
&& !attr::contains_name(cx.tcx.hir_attrs(item.hir_id()), sym::non_exhaustive)
&& !find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::NonExhaustive(..))
{
self.potential_enums.push((item.owner_id.def_id, id, item.span, span));
}
Expand All @@ -113,10 +114,10 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
item.span,
"this seems like a manual implementation of the non-exhaustive pattern",
|diag| {
if let Some(non_exhaustive) =
attr::find_by_name(cx.tcx.hir_attrs(item.hir_id()), sym::non_exhaustive)
if let Some(non_exhaustive_span) =
find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::NonExhaustive(span) => *span)
{
diag.span_note(non_exhaustive.span(), "the struct is already non-exhaustive");
diag.span_note(non_exhaustive_span, "the struct is already non-exhaustive");
} else {
let indent = snippet_indent(cx, item.span).unwrap_or_default();
diag.span_suggestion_verbose(
Expand Down
9 changes: 5 additions & 4 deletions src/tools/clippy/clippy_utils/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use rustc_middle::ty::{AdtDef, TyCtxt};
use rustc_session::Session;
use rustc_span::{Span, Symbol};
use std::str::FromStr;

use rustc_attr_data_structures::find_attr;
use crate::source::SpanRangeExt;
use crate::{sym, tokenize_with_text};
use rustc_attr_data_structures::AttributeKind;

/// Deprecation status of attributes known by Clippy.
pub enum DeprecationStatus {
Expand Down Expand Up @@ -165,13 +166,13 @@ pub fn is_doc_hidden(attrs: &[impl AttributeExt]) -> bool {

pub fn has_non_exhaustive_attr(tcx: TyCtxt<'_>, adt: AdtDef<'_>) -> bool {
adt.is_variant_list_non_exhaustive()
|| tcx.has_attr(adt.did(), sym::non_exhaustive)
|| find_attr!(tcx.get_all_attrs(adt.did()), AttributeKind::NonExhaustive(..))
|| adt.variants().iter().any(|variant_def| {
variant_def.is_field_list_non_exhaustive() || tcx.has_attr(variant_def.def_id, sym::non_exhaustive)
variant_def.is_field_list_non_exhaustive() || find_attr!(tcx.get_all_attrs(variant_def.def_id), AttributeKind::NonExhaustive(..))
})
|| adt
.all_fields()
.any(|field_def| tcx.has_attr(field_def.did, sym::non_exhaustive))
.any(|field_def| find_attr!(tcx.get_all_attrs(field_def.did), AttributeKind::NonExhaustive(..)))
}

/// Checks if the given span contains a `#[cfg(..)]` attribute
Expand Down
12 changes: 12 additions & 0 deletions tests/rustdoc/attributes-re-export.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//@ edition:2021
#![crate_name = "re_export"]

//@ has 're_export/fn.thingy2.html' '//pre[@class="rust item-decl"]' '#[no_mangle]'
pub use thingymod::thingy as thingy2;

mod thingymod {
#[no_mangle]
pub fn thingy() {

}
}
24 changes: 12 additions & 12 deletions tests/ui/lint/unused/unused-attr-duplicate.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,6 @@ LL | #[should_panic]
| ^^^^^^^^^^^^^^^
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:66:1
|
LL | #[non_exhaustive]
| ^^^^^^^^^^^^^^^^^ help: remove this attribute
|
note: attribute also specified here
--> $DIR/unused-attr-duplicate.rs:65:1
|
LL | #[non_exhaustive]
| ^^^^^^^^^^^^^^^^^

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:70:1
|
Expand Down Expand Up @@ -227,6 +215,18 @@ LL | #[must_use]
| ^^^^^^^^^^^
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:66:1
|
LL | #[non_exhaustive]
| ^^^^^^^^^^^^^^^^^ help: remove this attribute
|
note: attribute also specified here
--> $DIR/unused-attr-duplicate.rs:65:1
|
LL | #[non_exhaustive]
| ^^^^^^^^^^^^^^^^^

error: unused attribute
--> $DIR/unused-attr-duplicate.rs:74:1
|
Expand Down
10 changes: 7 additions & 3 deletions tests/ui/rfcs/rfc-2008-non-exhaustive/invalid-attribute.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
error: malformed `non_exhaustive` attribute input
error[E0565]: malformed `non_exhaustive` attribute input
--> $DIR/invalid-attribute.rs:1:1
|
LL | #[non_exhaustive(anything)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[non_exhaustive]`
| ^^^^^^^^^^^^^^^^----------^
| | |
| | didn't expect any arguments here
| help: must be of the form: `#[non_exhaustive]`

error[E0701]: attribute should be applied to a struct or enum
--> $DIR/invalid-attribute.rs:5:1
Expand All @@ -27,4 +30,5 @@ LL | | }

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0701`.
Some errors have detailed explanations: E0565, E0701.
For more information about an error, try `rustc --explain E0565`.
Loading