1 //! This module implements some validity checks for attributes.
2 //! In particular it verifies that `#[inline]` and `#[repr]` attributes are
3 //! attached to items that actually support them and if there are
4 //! conflicts between multiple such attributes attached to the same
7 use rustc_middle::hir::map::Map;
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::TyCtxt;
11 use rustc_ast::{AttrStyle, Attribute, Lit, LitKind, NestedMetaItem};
12 use rustc_errors::{pluralize, struct_span_err, Applicability};
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
16 use rustc_hir::{self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID};
17 use rustc_hir::{MethodKind, Target};
18 use rustc_session::lint::builtin::{
19 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
21 use rustc_session::parse::feature_err;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{MultiSpan, Span, DUMMY_SP};
25 pub(crate) fn target_from_impl_item<'tcx>(
27 impl_item: &hir::ImplItem<'_>,
29 match impl_item.kind {
30 hir::ImplItemKind::Const(..) => Target::AssocConst,
31 hir::ImplItemKind::Fn(..) => {
32 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id());
33 let containing_item = tcx.hir().expect_item(parent_hir_id);
34 let containing_impl_is_for_trait = match &containing_item.kind {
35 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
36 _ => bug!("parent of an ImplItem must be an Impl"),
38 if containing_impl_is_for_trait {
39 Target::Method(MethodKind::Trait { body: true })
41 Target::Method(MethodKind::Inherent)
44 hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
48 #[derive(Clone, Copy)]
50 Item(&'tcx Item<'tcx>),
51 ForeignItem(&'tcx ForeignItem<'tcx>),
54 struct CheckAttrVisitor<'tcx> {
58 impl CheckAttrVisitor<'tcx> {
59 /// Checks any attribute.
65 item: Option<ItemLike<'_>>,
67 let mut is_valid = true;
68 let mut specified_inline = None;
69 let attrs = self.tcx.hir().attrs(hir_id);
71 is_valid &= match attr.name_or_empty() {
72 sym::inline => self.check_inline(hir_id, attr, span, target),
73 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
74 sym::marker => self.check_marker(hir_id, attr, span, target),
75 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
76 sym::track_caller => {
77 self.check_track_caller(hir_id, &attr.span, attrs, span, target)
79 sym::doc => self.check_doc_attrs(attr, hir_id, target, &mut specified_inline),
80 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
81 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
82 sym::rustc_layout_scalar_valid_range_start
83 | sym::rustc_layout_scalar_valid_range_end => {
84 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
86 sym::allow_internal_unstable => {
87 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
89 sym::rustc_allow_const_fn_unstable => {
90 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
92 sym::naked => self.check_naked(hir_id, attr, span, target),
93 sym::rustc_legacy_const_generics => {
94 self.check_rustc_legacy_const_generics(&attr, span, target, item)
98 | sym::rustc_if_this_changed
99 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
103 match attr.name_or_empty() {
104 sym::cold => self.check_cold(hir_id, attr, span, target),
105 sym::link_name => self.check_link_name(hir_id, attr, span, target),
106 sym::link_section => self.check_link_section(hir_id, attr, span, target),
107 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
116 if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
117 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
120 self.check_repr(attrs, span, target, item, hir_id);
121 self.check_used(attrs, target);
124 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
125 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
127 "`#[{}]` is ignored on struct fields, match arms and macro defs",
131 "this was previously accepted by the compiler but is \
132 being phased out; it will become a hard error in \
136 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
137 for more information",
143 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
144 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
145 lint.build(&format!("`#[{}]` is ignored on struct fields and match arms", sym))
147 "this was previously accepted by the compiler but is \
148 being phased out; it will become a hard error in \
152 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
153 for more information",
159 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
160 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
164 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
165 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
166 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
167 lint.build("`#[inline]` is ignored on function prototypes").emit()
171 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
172 // just a lint, because we previously erroneously allowed it and some crates used it
173 // accidentally, to to be compatible with crates depending on them, we can't throw an
175 Target::AssocConst => {
176 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
177 lint.build("`#[inline]` is ignored on constants")
179 "this was previously accepted by the compiler but is \
180 being phased out; it will become a hard error in \
184 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
185 for more information",
191 // FIXME(#80564): Same for fields, arms, and macro defs
192 Target::Field | Target::Arm | Target::MacroDef => {
193 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
201 "attribute should be applied to function or closure",
203 .span_label(*span, "not a function or closure")
210 /// Checks if `#[naked]` is applied to a function definition.
211 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
214 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
215 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
216 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
217 // erroneously allowed it and some crates used it accidentally, to to be compatible
218 // with crates depending on them, we can't throw an error here.
219 Target::Field | Target::Arm | Target::MacroDef => {
220 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
228 "attribute should be applied to a function definition",
230 .span_label(*span, "not a function definition")
237 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
238 fn check_track_caller(
242 attrs: &'hir [Attribute],
247 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
252 "cannot use `#[track_caller]` with `#[naked]`",
257 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
258 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
259 // `#[track_caller]` attribute with just a lint, because we previously
260 // erroneously allowed it and some crates used it accidentally, to to be compatible
261 // with crates depending on them, we can't throw an error here.
262 Target::Field | Target::Arm | Target::MacroDef => {
264 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
273 "attribute should be applied to function"
275 .span_label(*span, "not a function")
282 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
283 fn check_non_exhaustive(
291 Target::Struct | Target::Enum | Target::Variant => true,
292 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
293 // `#[non_exhaustive]` attribute with just a lint, because we previously
294 // erroneously allowed it and some crates used it accidentally, to to be compatible
295 // with crates depending on them, we can't throw an error here.
296 Target::Field | Target::Arm | Target::MacroDef => {
297 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
305 "attribute can only be applied to a struct or enum"
307 .span_label(*span, "not a struct or enum")
314 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
315 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
317 Target::Trait => true,
318 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
319 // `#[marker]` attribute with just a lint, because we previously
320 // erroneously allowed it and some crates used it accidentally, to to be compatible
321 // with crates depending on them, we can't throw an error here.
322 Target::Field | Target::Arm | Target::MacroDef => {
323 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
329 .struct_span_err(attr.span, "attribute can only be applied to a trait")
330 .span_label(*span, "not a trait")
337 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
338 fn check_target_feature(
347 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
348 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
349 // crates used this, so only emit a warning.
350 Target::Statement => {
351 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
352 lint.build("attribute should be applied to a function")
354 "this was previously accepted by the compiler but is \
355 being phased out; it will become a hard error in \
358 .span_label(*span, "not a function")
363 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
364 // `#[target_feature]` attribute with just a lint, because we previously
365 // erroneously allowed it and some crates used it accidentally, to to be compatible
366 // with crates depending on them, we can't throw an error here.
367 Target::Field | Target::Arm | Target::MacroDef => {
368 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
374 .struct_span_err(attr.span, "attribute should be applied to a function")
375 .span_label(*span, "not a function")
382 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
387 &format!("doc {0} attribute expects a string: #[doc({0} = \"a\")]", attr_name),
392 fn check_doc_alias_value(
394 meta: &NestedMetaItem,
401 let err_fn = move |span: Span, msg: &str| {
405 "`#[doc(alias{})]` {}",
406 if is_list { "(\"...\")" } else { " = \"...\"" },
412 if doc_alias.is_empty() {
414 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
415 "attribute cannot have empty value",
419 doc_alias.chars().find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
421 self.tcx.sess.span_err(
422 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
424 "{:?} character isn't allowed in `#[doc(alias{})]`",
426 if is_list { "(\"...\")" } else { " = \"...\"" },
431 if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
433 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
434 "cannot start or end with ' '",
437 if let Some(err) = match target {
438 Target::Impl => Some("implementation block"),
439 Target::ForeignMod => Some("extern block"),
441 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
442 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
443 if Target::from_item(containing_item) == Target::Impl {
444 Some("type alias in implementation block")
449 Target::AssocConst => {
450 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
451 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
452 // We can't link to trait impl's consts.
453 let err = "associated constant in trait implementation block";
454 match containing_item.kind {
455 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
461 return err_fn(meta.span(), &format!("isn't allowed on {}", err));
463 let item_name = self.tcx.hir().name(hir_id);
464 if &*item_name.as_str() == doc_alias {
465 return err_fn(meta.span(), "is the same as the item's name");
470 fn check_doc_alias(&self, meta: &NestedMetaItem, hir_id: HirId, target: Target) -> bool {
471 if let Some(values) = meta.meta_item_list() {
475 Some(l) => match l.kind {
476 LitKind::Str(s, _) => {
477 if !self.check_doc_alias_value(v, &s.as_str(), hir_id, target, true) {
486 "`#[doc(alias(\"a\"))]` expects string literals",
497 "`#[doc(alias(\"a\"))]` expects string literals",
505 } else if let Some(doc_alias) = meta.value_str().map(|s| s.to_string()) {
506 self.check_doc_alias_value(meta, &doc_alias, hir_id, target, false)
512 "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of \
513 strings `#[doc(alias(\"a\", \"b\"))]`",
520 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
521 let doc_keyword = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
522 if doc_keyword.is_empty() {
523 self.doc_attr_str_error(meta, "keyword");
526 match self.tcx.hir().expect_item(hir_id).kind {
527 ItemKind::Mod(ref module) => {
528 if !module.item_ids.is_empty() {
533 "`#[doc(keyword = \"...\")]` can only be used on empty modules",
544 "`#[doc(keyword = \"...\")]` can only be used on modules",
550 if !rustc_lexer::is_ident(&doc_keyword) {
554 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
555 &format!("`{}` is not a valid identifier", doc_keyword),
563 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
565 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
566 /// if there are conflicting attributes for one item.
568 /// `specified_inline` is used to keep track of whether we have
569 /// already seen an inlining attribute for this item.
570 /// If so, `specified_inline` holds the value and the span of
571 /// the first `inline`/`no_inline` attribute.
575 meta: &NestedMetaItem,
578 specified_inline: &mut Option<(bool, Span)>,
580 if target == Target::Use || target == Target::ExternCrate {
581 let do_inline = meta.name_or_empty() == sym::inline;
582 if let Some((prev_inline, prev_span)) = *specified_inline {
583 if do_inline != prev_inline {
584 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
585 spans.push_span_label(prev_span, String::from("this attribute..."));
586 spans.push_span_label(
588 String::from("...conflicts with this attribute"),
592 .struct_span_err(spans, "conflicting doc inlining attributes")
593 .help("remove one of the conflicting attributes")
599 *specified_inline = Some((do_inline, meta.span()));
603 self.tcx.struct_span_lint_hir(
604 INVALID_DOC_ATTRIBUTES,
608 let mut err = lint.build(
609 "this attribute can only be applied to a `use` item",
611 err.span_label(meta.span(), "only applicable on `use` items");
612 if attr.style == AttrStyle::Outer {
614 self.tcx.hir().span(hir_id),
618 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#docno_inlinedocinline for more information")
626 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
627 fn check_attr_not_crate_level(
629 meta: &NestedMetaItem,
633 if CRATE_HIR_ID == hir_id {
639 "`#![doc({} = \"...\")]` isn't allowed as a crate-level attribute",
649 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
650 fn check_attr_crate_level(
653 meta: &NestedMetaItem,
656 if hir_id != CRATE_HIR_ID {
657 self.tcx.struct_span_lint_hir(
658 INVALID_DOC_ATTRIBUTES,
662 let mut err = lint.build(
663 "this attribute can only be applied at the crate level",
665 if attr.style == AttrStyle::Outer && self.tcx.hir().get_parent_item(hir_id) == CRATE_HIR_ID {
667 self.tcx.sess.source_map().span_to_snippet(attr.span)
670 err.span_suggestion_verbose(
672 "to apply to the crate, use an inner attribute",
674 Applicability::MaybeIncorrect,
679 "to apply to the crate, use an inner attribute",
683 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#at-the-crate-level for more information")
692 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
694 /// `specified_inline` should be initialized to `None` and kept for the scope
695 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
697 /// [`check_doc_inline`]: Self::check_doc_inline
703 specified_inline: &mut Option<(bool, Span)>,
705 let mut is_valid = true;
707 if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) {
709 if let Some(i_meta) = meta.meta_item() {
710 match i_meta.name_or_empty() {
712 if !self.check_attr_not_crate_level(&meta, hir_id, "alias")
713 || !self.check_doc_alias(&meta, hir_id, target) =>
719 if !self.check_attr_not_crate_level(&meta, hir_id, "keyword")
720 || !self.check_doc_keyword(&meta, hir_id) =>
725 sym::html_favicon_url
727 | sym::html_playground_url
728 | sym::issue_tracker_base_url
730 | sym::html_no_source
732 if !self.check_attr_crate_level(&attr, &meta, hir_id) =>
737 sym::inline | sym::no_inline
738 if !self.check_doc_inline(
749 // no_default_passes: deprecated
750 // passes: deprecated
751 // plugins: removed, but rustdoc warns about it itself
755 | sym::html_favicon_url
757 | sym::html_no_source
758 | sym::html_playground_url
761 | sym::issue_tracker_base_url
764 | sym::no_default_passes
773 self.tcx.struct_span_lint_hir(
774 INVALID_DOC_ATTRIBUTES,
778 let mut diag = lint.build(&format!(
779 "unknown `doc` attribute `{}`",
780 rustc_ast_pretty::pprust::path_to_string(&i_meta.path),
782 if i_meta.has_name(sym::spotlight) {
784 "`doc(spotlight)` was renamed to `doc(notable_trait)`",
786 diag.span_suggestion_short(
788 "use `notable_trait` instead",
789 String::from("notable_trait"),
790 Applicability::MachineApplicable,
792 diag.note("`doc(spotlight)` is now a no-op");
794 if i_meta.has_name(sym::include) {
795 if let Some(value) = i_meta.value_str() {
796 // if there are multiple attributes, the suggestion would suggest deleting all of them, which is incorrect
797 let applicability = if list.len() == 1 {
798 Applicability::MachineApplicable
800 Applicability::MaybeIncorrect
802 let inner = if attr.style == AttrStyle::Inner {
807 diag.span_suggestion(
808 attr.meta().unwrap().span,
809 "use `doc = include_str!` instead",
811 "#{}[doc = include_str!(\"{}\")]",
825 self.tcx.struct_span_lint_hir(
826 INVALID_DOC_ATTRIBUTES,
830 lint.build(&format!("invalid `doc` attribute")).emit();
841 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
842 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
844 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
845 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
846 // `#[cold]` attribute with just a lint, because we previously
847 // erroneously allowed it and some crates used it accidentally, to to be compatible
848 // with crates depending on them, we can't throw an error here.
849 Target::Field | Target::Arm | Target::MacroDef => {
850 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
853 // FIXME: #[cold] was previously allowed on non-functions and some crates used
854 // this, so only emit a warning.
855 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
856 lint.build("attribute should be applied to a function")
858 "this was previously accepted by the compiler but is \
859 being phased out; it will become a hard error in \
862 .span_label(*span, "not a function")
869 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
870 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
872 Target::ForeignFn | Target::ForeignStatic => {}
873 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
874 // `#[link_name]` attribute with just a lint, because we previously
875 // erroneously allowed it and some crates used it accidentally, to to be compatible
876 // with crates depending on them, we can't throw an error here.
877 Target::Field | Target::Arm | Target::MacroDef => {
878 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
881 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
882 // used this, so only emit a warning.
883 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
885 lint.build("attribute should be applied to a foreign function or static");
887 "this was previously accepted by the compiler but is \
888 being phased out; it will become a hard error in \
893 if let Target::ForeignMod = target {
894 if let Some(value) = attr.value_str() {
897 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
900 diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
904 diag.span_label(*span, "not a foreign function or static");
911 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
912 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
914 Target::ExternCrate => true,
915 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
916 // `#[no_link]` attribute with just a lint, because we previously
917 // erroneously allowed it and some crates used it accidentally, to to be compatible
918 // with crates depending on them, we can't throw an error here.
919 Target::Field | Target::Arm | Target::MacroDef => {
920 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
928 "attribute should be applied to an `extern crate` item",
930 .span_label(*span, "not an `extern crate` item")
937 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
938 fn check_export_name(
946 Target::Static | Target::Fn | Target::Method(..) => true,
947 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
948 // `#[export_name]` attribute with just a lint, because we previously
949 // erroneously allowed it and some crates used it accidentally, to to be compatible
950 // with crates depending on them, we can't throw an error here.
951 Target::Field | Target::Arm | Target::MacroDef => {
952 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
960 "attribute should be applied to a function or static",
962 .span_label(*span, "not a function or static")
969 fn check_rustc_layout_scalar_valid_range(
975 if target != Target::Struct {
978 .struct_span_err(attr.span, "attribute should be applied to a struct")
979 .span_label(*span, "not a struct")
984 let list = match attr.meta_item_list() {
985 None => return false,
989 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
994 .struct_span_err(attr.span, "expected exactly one integer literal argument")
1000 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1001 fn check_rustc_legacy_const_generics(
1006 item: Option<ItemLike<'_>>,
1008 let is_function = matches!(target, Target::Fn | Target::Method(..));
1012 .struct_span_err(attr.span, "attribute should be applied to a function")
1013 .span_label(*span, "not a function")
1018 let list = match attr.meta_item_list() {
1019 // The attribute form is validated on AST.
1020 None => return false,
1024 let (decl, generics) = match item {
1025 Some(ItemLike::Item(Item {
1026 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1028 })) => (decl, generics),
1029 _ => bug!("should be a function item"),
1032 for param in generics.params {
1034 hir::GenericParamKind::Const { .. } => {}
1040 "#[rustc_legacy_const_generics] functions must \
1041 only have const generics",
1043 .span_label(param.span, "non-const generic parameter")
1050 if list.len() != generics.params.len() {
1055 "#[rustc_legacy_const_generics] must have one index for each generic parameter",
1057 .span_label(generics.span, "generic parameters")
1062 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1063 let mut invalid_args = vec![];
1065 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1066 if *val >= arg_count {
1067 let span = meta.span();
1070 .struct_span_err(span, "index exceeds number of arguments")
1074 "there {} only {} argument{}",
1075 if arg_count != 1 { "are" } else { "is" },
1077 pluralize!(arg_count)
1084 invalid_args.push(meta.span());
1088 if !invalid_args.is_empty() {
1091 .struct_span_err(invalid_args, "arguments should be non-negative integers")
1099 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1100 /// option is passed to the compiler.
1101 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1102 if self.tcx.sess.opts.debugging_opts.query_dep_graph {
1107 .struct_span_err(attr.span, "attribute requires -Z query-dep-graph to be enabled")
1113 /// Checks if `#[link_section]` is applied to a function or static.
1114 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1116 Target::Static | Target::Fn | Target::Method(..) => {}
1117 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1118 // `#[link_section]` attribute with just a lint, because we previously
1119 // erroneously allowed it and some crates used it accidentally, to to be compatible
1120 // with crates depending on them, we can't throw an error here.
1121 Target::Field | Target::Arm | Target::MacroDef => {
1122 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1125 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1126 // crates used this, so only emit a warning.
1127 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1128 lint.build("attribute should be applied to a function or static")
1130 "this was previously accepted by the compiler but is \
1131 being phased out; it will become a hard error in \
1134 .span_label(*span, "not a function or static")
1141 /// Checks if `#[no_mangle]` is applied to a function or static.
1142 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1144 Target::Static | Target::Fn | Target::Method(..) => {}
1145 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1146 // `#[no_mangle]` attribute with just a lint, because we previously
1147 // erroneously allowed it and some crates used it accidentally, to to be compatible
1148 // with crates depending on them, we can't throw an error here.
1149 Target::Field | Target::Arm | Target::MacroDef => {
1150 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1153 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1154 // crates used this, so only emit a warning.
1155 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1156 lint.build("attribute should be applied to a function or static")
1158 "this was previously accepted by the compiler but is \
1159 being phased out; it will become a hard error in \
1162 .span_label(*span, "not a function or static")
1169 /// Checks if the `#[repr]` attributes on `item` are valid.
1172 attrs: &'hir [Attribute],
1175 item: Option<ItemLike<'_>>,
1178 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1181 // #[repr(bar, align(8))]
1183 let hints: Vec<_> = attrs
1185 .filter(|attr| attr.has_name(sym::repr))
1186 .filter_map(|attr| attr.meta_item_list())
1190 let mut int_reprs = 0;
1191 let mut is_c = false;
1192 let mut is_simd = false;
1193 let mut is_transparent = false;
1195 for hint in &hints {
1196 if !hint.is_meta_item() {
1201 "meta item in `repr` must be an identifier"
1207 let (article, allowed_targets) = match hint.name_or_empty() {
1211 Target::Struct | Target::Union | Target::Enum => continue,
1212 _ => ("a", "struct, enum, or union"),
1216 if let (Target::Fn, true) = (target, !self.tcx.features().fn_align) {
1218 &self.tcx.sess.parse_sess,
1221 "`repr(align)` attributes on functions are unstable",
1227 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1228 _ => ("a", "struct, enum, function, or union"),
1232 if target != Target::Struct && target != Target::Union {
1233 ("a", "struct or union")
1240 if target != Target::Struct {
1246 sym::transparent => {
1247 is_transparent = true;
1249 Target::Struct | Target::Union | Target::Enum => continue,
1250 _ => ("a", "struct, enum, or union"),
1254 if !self.tcx.features().enabled(sym::no_niche) {
1256 &self.tcx.sess.parse_sess,
1259 "the attribute `repr(no_niche)` is currently unstable",
1264 Target::Struct | Target::Enum => continue,
1265 _ => ("a", "struct or enum"),
1281 if target != Target::Enum {
1292 "unrecognized representation hint"
1305 &format!("attribute should be applied to {} {}", article, allowed_targets)
1307 .span_label(*span, &format!("not {} {}", article, allowed_targets))
1311 // Just point at all repr hints if there are any incompatibilities.
1312 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1313 let hint_spans = hints.iter().map(|hint| hint.span());
1315 // Error on repr(transparent, <anything else apart from no_niche>).
1316 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
1317 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
1318 if is_transparent && non_no_niche_count > 1 {
1319 let hint_spans: Vec<_> = hint_spans.clone().collect();
1324 "transparent {} cannot have other repr hints",
1329 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1331 || (is_simd && is_c)
1334 && item.map_or(false, |item| {
1335 if let ItemLike::Item(item) = item {
1336 return is_c_like_enum(item);
1341 self.tcx.struct_span_lint_hir(
1342 CONFLICTING_REPR_HINTS,
1344 hint_spans.collect::<Vec<Span>>(),
1346 lint.build("conflicting representation hints")
1347 .code(rustc_errors::error_code!(E0566))
1354 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
1356 if attr.has_name(sym::used) && target != Target::Static {
1359 .span_err(attr.span, "attribute must be applied to a `static` variable");
1364 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1365 /// (Allows proc_macro functions)
1366 fn check_allow_internal_unstable(
1372 attrs: &[Attribute],
1374 debug!("Checking target: {:?}", target);
1378 if self.tcx.sess.is_proc_macro_attr(attr) {
1379 debug!("Is proc macro attr");
1383 debug!("Is not proc macro attr");
1386 Target::MacroDef => true,
1387 // FIXME(#80564): We permit struct fields and match arms to have an
1388 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1389 // erroneously allowed it and some crates used it accidentally, to to be compatible
1390 // with crates depending on them, we can't throw an error here.
1391 Target::Field | Target::Arm => {
1392 self.inline_attr_str_error_without_macro_def(
1395 "allow_internal_unstable",
1402 .struct_span_err(attr.span, "attribute should be applied to a macro")
1403 .span_label(*span, "not a macro")
1410 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1411 /// (Allows proc_macro functions)
1412 fn check_rustc_allow_const_fn_unstable(
1420 Target::Fn | Target::Method(_)
1421 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id)) =>
1425 // FIXME(#80564): We permit struct fields and match arms to have an
1426 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1427 // erroneously allowed it and some crates used it accidentally, to to be compatible
1428 // with crates depending on them, we can't throw an error here.
1429 Target::Field | Target::Arm | Target::MacroDef => {
1430 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1436 .struct_span_err(attr.span, "attribute should be applied to `const fn`")
1437 .span_label(*span, "not a `const fn`")
1445 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1446 type Map = Map<'tcx>;
1448 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1449 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1452 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1453 let target = Target::from_item(item);
1454 self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item)));
1455 intravisit::walk_item(self, item)
1458 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1459 let target = Target::from_generic_param(generic_param);
1460 self.check_attributes(generic_param.hir_id, &generic_param.span, target, None);
1461 intravisit::walk_generic_param(self, generic_param)
1464 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1465 let target = Target::from_trait_item(trait_item);
1466 self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None);
1467 intravisit::walk_trait_item(self, trait_item)
1470 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1471 self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None);
1472 intravisit::walk_field_def(self, struct_field);
1475 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1476 self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None);
1477 intravisit::walk_arm(self, arm);
1480 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1481 let target = Target::from_foreign_item(f_item);
1482 self.check_attributes(
1486 Some(ItemLike::ForeignItem(f_item)),
1488 intravisit::walk_foreign_item(self, f_item)
1491 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1492 let target = target_from_impl_item(self.tcx, impl_item);
1493 self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None);
1494 intravisit::walk_impl_item(self, impl_item)
1497 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1498 // When checking statements ignore expressions, they will be checked later.
1499 if let hir::StmtKind::Local(ref l) = stmt.kind {
1500 self.check_attributes(l.hir_id, &stmt.span, Target::Statement, None);
1502 intravisit::walk_stmt(self, stmt)
1505 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1506 let target = match expr.kind {
1507 hir::ExprKind::Closure(..) => Target::Closure,
1508 _ => Target::Expression,
1511 self.check_attributes(expr.hir_id, &expr.span, target, None);
1512 intravisit::walk_expr(self, expr)
1517 variant: &'tcx hir::Variant<'tcx>,
1518 generics: &'tcx hir::Generics<'tcx>,
1521 self.check_attributes(variant.id, &variant.span, Target::Variant, None);
1522 intravisit::walk_variant(self, variant, generics, item_id)
1525 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1526 self.check_attributes(macro_def.hir_id(), ¯o_def.span, Target::MacroDef, None);
1527 intravisit::walk_macro_def(self, macro_def);
1530 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1531 self.check_attributes(param.hir_id, ¶m.span, Target::Param, None);
1533 intravisit::walk_param(self, param);
1537 fn is_c_like_enum(item: &Item<'_>) -> bool {
1538 if let ItemKind::Enum(ref def, _) = item.kind {
1539 for variant in def.variants {
1540 match variant.data {
1541 hir::VariantData::Unit(..) => { /* continue */ }
1551 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1552 const ATTRS_TO_CHECK: &[Symbol] = &[
1556 sym::automatically_derived,
1562 for attr_to_check in ATTRS_TO_CHECK {
1563 if tcx.sess.check_name(attr, *attr_to_check) {
1568 "`{}` attribute cannot be used at crate level",
1569 attr_to_check.to_ident_string()
1578 fn check_invalid_macro_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1580 if tcx.sess.check_name(attr, sym::inline) {
1585 "attribute should be applied to function or closure",
1587 .span_label(attr.span, "not a function or closure")
1593 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1594 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
1595 tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor());
1596 tcx.hir().visit_exported_macros_in_krate(check_attr_visitor);
1597 check_invalid_macro_level_attr(tcx, tcx.hir().krate().non_exported_macro_attrs);
1598 if module_def_id.is_top_level_module() {
1599 check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None);
1600 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
1604 pub(crate) fn provide(providers: &mut Providers) {
1605 *providers = Providers { check_mod_attrs, ..*providers };