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),
100 sym::cmse_nonsecure_entry => self.check_cmse_nonsecure_entry(attr, span, target),
104 match attr.name_or_empty() {
105 sym::cold => self.check_cold(hir_id, attr, span, target),
106 sym::link_name => self.check_link_name(hir_id, attr, span, target),
107 sym::link_section => self.check_link_section(hir_id, attr, span, target),
108 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
117 if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
118 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
121 self.check_repr(attrs, span, target, item, hir_id);
122 self.check_used(attrs, target);
125 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
126 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
128 "`#[{}]` is ignored on struct fields, match arms and macro defs",
132 "this was previously accepted by the compiler but is \
133 being phased out; it will become a hard error in \
137 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
138 for more information",
144 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
145 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
146 lint.build(&format!("`#[{}]` is ignored on struct fields and match arms", sym))
148 "this was previously accepted by the compiler but is \
149 being phased out; it will become a hard error in \
153 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
154 for more information",
160 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
161 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
165 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
166 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
167 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
168 lint.build("`#[inline]` is ignored on function prototypes").emit()
172 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
173 // just a lint, because we previously erroneously allowed it and some crates used it
174 // accidentally, to to be compatible with crates depending on them, we can't throw an
176 Target::AssocConst => {
177 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
178 lint.build("`#[inline]` is ignored on constants")
180 "this was previously accepted by the compiler but is \
181 being phased out; it will become a hard error in \
185 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
186 for more information",
192 // FIXME(#80564): Same for fields, arms, and macro defs
193 Target::Field | Target::Arm | Target::MacroDef => {
194 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
202 "attribute should be applied to function or closure",
204 .span_label(*span, "not a function or closure")
211 /// Checks if `#[naked]` is applied to a function definition.
212 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
215 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
216 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
217 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
218 // erroneously allowed it and some crates used it accidentally, to to be compatible
219 // with crates depending on them, we can't throw an error here.
220 Target::Field | Target::Arm | Target::MacroDef => {
221 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
229 "attribute should be applied to a function definition",
231 .span_label(*span, "not a function definition")
238 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
239 fn check_cmse_nonsecure_entry(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
242 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
248 "attribute should be applied to a function definition",
250 .span_label(*span, "not a function definition")
257 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
258 fn check_track_caller(
262 attrs: &'hir [Attribute],
267 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
272 "cannot use `#[track_caller]` with `#[naked]`",
277 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
278 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
279 // `#[track_caller]` attribute with just a lint, because we previously
280 // erroneously allowed it and some crates used it accidentally, to to be compatible
281 // with crates depending on them, we can't throw an error here.
282 Target::Field | Target::Arm | Target::MacroDef => {
284 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
293 "attribute should be applied to function"
295 .span_label(*span, "not a function")
302 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
303 fn check_non_exhaustive(
311 Target::Struct | Target::Enum | Target::Variant => true,
312 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
313 // `#[non_exhaustive]` attribute with just a lint, because we previously
314 // erroneously allowed it and some crates used it accidentally, to to be compatible
315 // with crates depending on them, we can't throw an error here.
316 Target::Field | Target::Arm | Target::MacroDef => {
317 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
325 "attribute can only be applied to a struct or enum"
327 .span_label(*span, "not a struct or enum")
334 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
335 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
337 Target::Trait => true,
338 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
339 // `#[marker]` attribute with just a lint, because we previously
340 // erroneously allowed it and some crates used it accidentally, to to be compatible
341 // with crates depending on them, we can't throw an error here.
342 Target::Field | Target::Arm | Target::MacroDef => {
343 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
349 .struct_span_err(attr.span, "attribute can only be applied to a trait")
350 .span_label(*span, "not a trait")
357 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
358 fn check_target_feature(
367 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
368 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
369 // crates used this, so only emit a warning.
370 Target::Statement => {
371 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
372 lint.build("attribute should be applied to a function")
374 "this was previously accepted by the compiler but is \
375 being phased out; it will become a hard error in \
378 .span_label(*span, "not a function")
383 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
384 // `#[target_feature]` attribute with just a lint, because we previously
385 // erroneously allowed it and some crates used it accidentally, to to be compatible
386 // with crates depending on them, we can't throw an error here.
387 Target::Field | Target::Arm | Target::MacroDef => {
388 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
394 .struct_span_err(attr.span, "attribute should be applied to a function")
395 .span_label(*span, "not a function")
402 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
407 &format!("doc {0} attribute expects a string: #[doc({0} = \"a\")]", attr_name),
412 fn check_doc_alias_value(
414 meta: &NestedMetaItem,
421 let err_fn = move |span: Span, msg: &str| {
425 "`#[doc(alias{})]` {}",
426 if is_list { "(\"...\")" } else { " = \"...\"" },
432 if doc_alias.is_empty() {
434 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
435 "attribute cannot have empty value",
439 doc_alias.chars().find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
441 self.tcx.sess.span_err(
442 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
444 "{:?} character isn't allowed in `#[doc(alias{})]`",
446 if is_list { "(\"...\")" } else { " = \"...\"" },
451 if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
453 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
454 "cannot start or end with ' '",
457 if let Some(err) = match target {
458 Target::Impl => Some("implementation block"),
459 Target::ForeignMod => Some("extern block"),
461 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
462 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
463 if Target::from_item(containing_item) == Target::Impl {
464 Some("type alias in implementation block")
469 Target::AssocConst => {
470 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
471 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
472 // We can't link to trait impl's consts.
473 let err = "associated constant in trait implementation block";
474 match containing_item.kind {
475 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
479 // we check the validity of params elsewhere
480 Target::Param => return false,
483 return err_fn(meta.span(), &format!("isn't allowed on {}", err));
485 let item_name = self.tcx.hir().name(hir_id);
486 if &*item_name.as_str() == doc_alias {
487 return err_fn(meta.span(), "is the same as the item's name");
492 fn check_doc_alias(&self, meta: &NestedMetaItem, hir_id: HirId, target: Target) -> bool {
493 if let Some(values) = meta.meta_item_list() {
497 Some(l) => match l.kind {
498 LitKind::Str(s, _) => {
499 if !self.check_doc_alias_value(v, &s.as_str(), hir_id, target, true) {
508 "`#[doc(alias(\"a\"))]` expects string literals",
519 "`#[doc(alias(\"a\"))]` expects string literals",
527 } else if let Some(doc_alias) = meta.value_str().map(|s| s.to_string()) {
528 self.check_doc_alias_value(meta, &doc_alias, hir_id, target, false)
534 "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of \
535 strings `#[doc(alias(\"a\", \"b\"))]`",
542 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
543 let doc_keyword = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
544 if doc_keyword.is_empty() {
545 self.doc_attr_str_error(meta, "keyword");
548 match self.tcx.hir().find(hir_id).and_then(|node| match node {
549 hir::Node::Item(item) => Some(&item.kind),
552 Some(ItemKind::Mod(ref module)) => {
553 if !module.item_ids.is_empty() {
558 "`#[doc(keyword = \"...\")]` can only be used on empty modules",
569 "`#[doc(keyword = \"...\")]` can only be used on modules",
575 if !rustc_lexer::is_ident(&doc_keyword) {
579 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
580 &format!("`{}` is not a valid identifier", doc_keyword),
588 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
590 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
591 /// if there are conflicting attributes for one item.
593 /// `specified_inline` is used to keep track of whether we have
594 /// already seen an inlining attribute for this item.
595 /// If so, `specified_inline` holds the value and the span of
596 /// the first `inline`/`no_inline` attribute.
600 meta: &NestedMetaItem,
603 specified_inline: &mut Option<(bool, Span)>,
605 if target == Target::Use || target == Target::ExternCrate {
606 let do_inline = meta.name_or_empty() == sym::inline;
607 if let Some((prev_inline, prev_span)) = *specified_inline {
608 if do_inline != prev_inline {
609 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
610 spans.push_span_label(prev_span, String::from("this attribute..."));
611 spans.push_span_label(
613 String::from("...conflicts with this attribute"),
617 .struct_span_err(spans, "conflicting doc inlining attributes")
618 .help("remove one of the conflicting attributes")
624 *specified_inline = Some((do_inline, meta.span()));
628 self.tcx.struct_span_lint_hir(
629 INVALID_DOC_ATTRIBUTES,
633 let mut err = lint.build(
634 "this attribute can only be applied to a `use` item",
636 err.span_label(meta.span(), "only applicable on `use` items");
637 if attr.style == AttrStyle::Outer {
639 self.tcx.hir().span(hir_id),
643 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#docno_inlinedocinline for more information")
651 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
652 fn check_attr_not_crate_level(
654 meta: &NestedMetaItem,
658 if CRATE_HIR_ID == hir_id {
664 "`#![doc({} = \"...\")]` isn't allowed as a crate-level attribute",
674 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
675 fn check_attr_crate_level(
678 meta: &NestedMetaItem,
681 if hir_id != CRATE_HIR_ID {
682 self.tcx.struct_span_lint_hir(
683 INVALID_DOC_ATTRIBUTES,
687 let mut err = lint.build(
688 "this attribute can only be applied at the crate level",
690 if attr.style == AttrStyle::Outer && self.tcx.hir().get_parent_item(hir_id) == CRATE_HIR_ID {
692 self.tcx.sess.source_map().span_to_snippet(attr.span)
695 err.span_suggestion_verbose(
697 "to apply to the crate, use an inner attribute",
699 Applicability::MaybeIncorrect,
704 "to apply to the crate, use an inner attribute",
708 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#at-the-crate-level for more information")
717 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
719 /// `specified_inline` should be initialized to `None` and kept for the scope
720 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
722 /// [`check_doc_inline`]: Self::check_doc_inline
728 specified_inline: &mut Option<(bool, Span)>,
730 let mut is_valid = true;
732 if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) {
734 if let Some(i_meta) = meta.meta_item() {
735 match i_meta.name_or_empty() {
737 if !self.check_attr_not_crate_level(&meta, hir_id, "alias")
738 || !self.check_doc_alias(&meta, hir_id, target) =>
744 if !self.check_attr_not_crate_level(&meta, hir_id, "keyword")
745 || !self.check_doc_keyword(&meta, hir_id) =>
750 sym::html_favicon_url
752 | sym::html_playground_url
753 | sym::issue_tracker_base_url
755 | sym::html_no_source
757 if !self.check_attr_crate_level(&attr, &meta, hir_id) =>
762 sym::inline | sym::no_inline
763 if !self.check_doc_inline(
774 // no_default_passes: deprecated
775 // passes: deprecated
776 // plugins: removed, but rustdoc warns about it itself
780 | sym::html_favicon_url
782 | sym::html_no_source
783 | sym::html_playground_url
786 | sym::issue_tracker_base_url
789 | sym::no_default_passes
798 self.tcx.struct_span_lint_hir(
799 INVALID_DOC_ATTRIBUTES,
803 let mut diag = lint.build(&format!(
804 "unknown `doc` attribute `{}`",
805 rustc_ast_pretty::pprust::path_to_string(&i_meta.path),
807 if i_meta.has_name(sym::spotlight) {
809 "`doc(spotlight)` was renamed to `doc(notable_trait)`",
811 diag.span_suggestion_short(
813 "use `notable_trait` instead",
814 String::from("notable_trait"),
815 Applicability::MachineApplicable,
817 diag.note("`doc(spotlight)` is now a no-op");
819 if i_meta.has_name(sym::include) {
820 if let Some(value) = i_meta.value_str() {
821 // if there are multiple attributes, the suggestion would suggest deleting all of them, which is incorrect
822 let applicability = if list.len() == 1 {
823 Applicability::MachineApplicable
825 Applicability::MaybeIncorrect
827 let inner = if attr.style == AttrStyle::Inner {
832 diag.span_suggestion(
833 attr.meta().unwrap().span,
834 "use `doc = include_str!` instead",
836 "#{}[doc = include_str!(\"{}\")]",
850 self.tcx.struct_span_lint_hir(
851 INVALID_DOC_ATTRIBUTES,
855 lint.build(&format!("invalid `doc` attribute")).emit();
866 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
867 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
869 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
870 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
871 // `#[cold]` attribute with just a lint, because we previously
872 // erroneously allowed it and some crates used it accidentally, to to be compatible
873 // with crates depending on them, we can't throw an error here.
874 Target::Field | Target::Arm | Target::MacroDef => {
875 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
878 // FIXME: #[cold] was previously allowed on non-functions and some crates used
879 // this, so only emit a warning.
880 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
881 lint.build("attribute should be applied to a function")
883 "this was previously accepted by the compiler but is \
884 being phased out; it will become a hard error in \
887 .span_label(*span, "not a function")
894 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
895 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
897 Target::ForeignFn | Target::ForeignStatic => {}
898 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
899 // `#[link_name]` attribute with just a lint, because we previously
900 // erroneously allowed it and some crates used it accidentally, to to be compatible
901 // with crates depending on them, we can't throw an error here.
902 Target::Field | Target::Arm | Target::MacroDef => {
903 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
906 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
907 // used this, so only emit a warning.
908 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
910 lint.build("attribute should be applied to a foreign function or static");
912 "this was previously accepted by the compiler but is \
913 being phased out; it will become a hard error in \
918 if let Target::ForeignMod = target {
919 if let Some(value) = attr.value_str() {
922 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
925 diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
929 diag.span_label(*span, "not a foreign function or static");
936 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
937 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
939 Target::ExternCrate => true,
940 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
941 // `#[no_link]` attribute with just a lint, because we previously
942 // erroneously allowed it and some crates used it accidentally, to to be compatible
943 // with crates depending on them, we can't throw an error here.
944 Target::Field | Target::Arm | Target::MacroDef => {
945 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
953 "attribute should be applied to an `extern crate` item",
955 .span_label(*span, "not an `extern crate` item")
962 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
963 fn check_export_name(
971 Target::Static | Target::Fn | Target::Method(..) => true,
972 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
973 // `#[export_name]` attribute with just a lint, because we previously
974 // erroneously allowed it and some crates used it accidentally, to to be compatible
975 // with crates depending on them, we can't throw an error here.
976 Target::Field | Target::Arm | Target::MacroDef => {
977 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
985 "attribute should be applied to a function or static",
987 .span_label(*span, "not a function or static")
994 fn check_rustc_layout_scalar_valid_range(
1000 if target != Target::Struct {
1003 .struct_span_err(attr.span, "attribute should be applied to a struct")
1004 .span_label(*span, "not a struct")
1009 let list = match attr.meta_item_list() {
1010 None => return false,
1014 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
1019 .struct_span_err(attr.span, "expected exactly one integer literal argument")
1025 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1026 fn check_rustc_legacy_const_generics(
1031 item: Option<ItemLike<'_>>,
1033 let is_function = matches!(target, Target::Fn | Target::Method(..));
1037 .struct_span_err(attr.span, "attribute should be applied to a function")
1038 .span_label(*span, "not a function")
1043 let list = match attr.meta_item_list() {
1044 // The attribute form is validated on AST.
1045 None => return false,
1049 let (decl, generics) = match item {
1050 Some(ItemLike::Item(Item {
1051 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1053 })) => (decl, generics),
1054 _ => bug!("should be a function item"),
1057 for param in generics.params {
1059 hir::GenericParamKind::Const { .. } => {}
1065 "#[rustc_legacy_const_generics] functions must \
1066 only have const generics",
1068 .span_label(param.span, "non-const generic parameter")
1075 if list.len() != generics.params.len() {
1080 "#[rustc_legacy_const_generics] must have one index for each generic parameter",
1082 .span_label(generics.span, "generic parameters")
1087 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1088 let mut invalid_args = vec![];
1090 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1091 if *val >= arg_count {
1092 let span = meta.span();
1095 .struct_span_err(span, "index exceeds number of arguments")
1099 "there {} only {} argument{}",
1100 if arg_count != 1 { "are" } else { "is" },
1102 pluralize!(arg_count)
1109 invalid_args.push(meta.span());
1113 if !invalid_args.is_empty() {
1116 .struct_span_err(invalid_args, "arguments should be non-negative integers")
1124 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1125 /// option is passed to the compiler.
1126 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1127 if self.tcx.sess.opts.debugging_opts.query_dep_graph {
1132 .struct_span_err(attr.span, "attribute requires -Z query-dep-graph to be enabled")
1138 /// Checks if `#[link_section]` is applied to a function or static.
1139 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1141 Target::Static | Target::Fn | Target::Method(..) => {}
1142 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1143 // `#[link_section]` attribute with just a lint, because we previously
1144 // erroneously allowed it and some crates used it accidentally, to to be compatible
1145 // with crates depending on them, we can't throw an error here.
1146 Target::Field | Target::Arm | Target::MacroDef => {
1147 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1150 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1151 // crates used this, so only emit a warning.
1152 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1153 lint.build("attribute should be applied to a function or static")
1155 "this was previously accepted by the compiler but is \
1156 being phased out; it will become a hard error in \
1159 .span_label(*span, "not a function or static")
1166 /// Checks if `#[no_mangle]` is applied to a function or static.
1167 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1169 Target::Static | Target::Fn | Target::Method(..) => {}
1170 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1171 // `#[no_mangle]` attribute with just a lint, because we previously
1172 // erroneously allowed it and some crates used it accidentally, to to be compatible
1173 // with crates depending on them, we can't throw an error here.
1174 Target::Field | Target::Arm | Target::MacroDef => {
1175 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1178 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1179 // crates used this, so only emit a warning.
1180 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1181 lint.build("attribute should be applied to a function or static")
1183 "this was previously accepted by the compiler but is \
1184 being phased out; it will become a hard error in \
1187 .span_label(*span, "not a function or static")
1194 /// Checks if the `#[repr]` attributes on `item` are valid.
1197 attrs: &'hir [Attribute],
1200 item: Option<ItemLike<'_>>,
1203 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1206 // #[repr(bar, align(8))]
1208 let hints: Vec<_> = attrs
1210 .filter(|attr| attr.has_name(sym::repr))
1211 .filter_map(|attr| attr.meta_item_list())
1215 let mut int_reprs = 0;
1216 let mut is_c = false;
1217 let mut is_simd = false;
1218 let mut is_transparent = false;
1220 for hint in &hints {
1221 if !hint.is_meta_item() {
1226 "meta item in `repr` must be an identifier"
1232 let (article, allowed_targets) = match hint.name_or_empty() {
1236 Target::Struct | Target::Union | Target::Enum => continue,
1237 _ => ("a", "struct, enum, or union"),
1241 if let (Target::Fn, true) = (target, !self.tcx.features().fn_align) {
1243 &self.tcx.sess.parse_sess,
1246 "`repr(align)` attributes on functions are unstable",
1252 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1253 _ => ("a", "struct, enum, function, or union"),
1257 if target != Target::Struct && target != Target::Union {
1258 ("a", "struct or union")
1265 if target != Target::Struct {
1271 sym::transparent => {
1272 is_transparent = true;
1274 Target::Struct | Target::Union | Target::Enum => continue,
1275 _ => ("a", "struct, enum, or union"),
1279 if !self.tcx.features().enabled(sym::no_niche) {
1281 &self.tcx.sess.parse_sess,
1284 "the attribute `repr(no_niche)` is currently unstable",
1289 Target::Struct | Target::Enum => continue,
1290 _ => ("a", "struct or enum"),
1306 if target != Target::Enum {
1317 "unrecognized representation hint"
1330 &format!("attribute should be applied to {} {}", article, allowed_targets)
1332 .span_label(*span, &format!("not {} {}", article, allowed_targets))
1336 // Just point at all repr hints if there are any incompatibilities.
1337 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1338 let hint_spans = hints.iter().map(|hint| hint.span());
1340 // Error on repr(transparent, <anything else apart from no_niche>).
1341 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
1342 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
1343 if is_transparent && non_no_niche_count > 1 {
1344 let hint_spans: Vec<_> = hint_spans.clone().collect();
1349 "transparent {} cannot have other repr hints",
1354 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1356 || (is_simd && is_c)
1359 && item.map_or(false, |item| {
1360 if let ItemLike::Item(item) = item {
1361 return is_c_like_enum(item);
1366 self.tcx.struct_span_lint_hir(
1367 CONFLICTING_REPR_HINTS,
1369 hint_spans.collect::<Vec<Span>>(),
1371 lint.build("conflicting representation hints")
1372 .code(rustc_errors::error_code!(E0566))
1379 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
1381 if attr.has_name(sym::used) && target != Target::Static {
1384 .span_err(attr.span, "attribute must be applied to a `static` variable");
1389 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1390 /// (Allows proc_macro functions)
1391 fn check_allow_internal_unstable(
1397 attrs: &[Attribute],
1399 debug!("Checking target: {:?}", target);
1403 if self.tcx.sess.is_proc_macro_attr(attr) {
1404 debug!("Is proc macro attr");
1408 debug!("Is not proc macro attr");
1411 Target::MacroDef => true,
1412 // FIXME(#80564): We permit struct fields and match arms to have an
1413 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1414 // erroneously allowed it and some crates used it accidentally, to to be compatible
1415 // with crates depending on them, we can't throw an error here.
1416 Target::Field | Target::Arm => {
1417 self.inline_attr_str_error_without_macro_def(
1420 "allow_internal_unstable",
1427 .struct_span_err(attr.span, "attribute should be applied to a macro")
1428 .span_label(*span, "not a macro")
1435 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1436 /// (Allows proc_macro functions)
1437 fn check_rustc_allow_const_fn_unstable(
1445 Target::Fn | Target::Method(_)
1446 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id)) =>
1450 // FIXME(#80564): We permit struct fields and match arms to have an
1451 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1452 // erroneously allowed it and some crates used it accidentally, to to be compatible
1453 // with crates depending on them, we can't throw an error here.
1454 Target::Field | Target::Arm | Target::MacroDef => {
1455 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1461 .struct_span_err(attr.span, "attribute should be applied to `const fn`")
1462 .span_label(*span, "not a `const fn`")
1470 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1471 type Map = Map<'tcx>;
1473 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1474 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1477 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1478 let target = Target::from_item(item);
1479 self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item)));
1480 intravisit::walk_item(self, item)
1483 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1484 let target = Target::from_generic_param(generic_param);
1485 self.check_attributes(generic_param.hir_id, &generic_param.span, target, None);
1486 intravisit::walk_generic_param(self, generic_param)
1489 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1490 let target = Target::from_trait_item(trait_item);
1491 self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None);
1492 intravisit::walk_trait_item(self, trait_item)
1495 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1496 self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None);
1497 intravisit::walk_field_def(self, struct_field);
1500 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1501 self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None);
1502 intravisit::walk_arm(self, arm);
1505 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1506 let target = Target::from_foreign_item(f_item);
1507 self.check_attributes(
1511 Some(ItemLike::ForeignItem(f_item)),
1513 intravisit::walk_foreign_item(self, f_item)
1516 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1517 let target = target_from_impl_item(self.tcx, impl_item);
1518 self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None);
1519 intravisit::walk_impl_item(self, impl_item)
1522 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1523 // When checking statements ignore expressions, they will be checked later.
1524 if let hir::StmtKind::Local(ref l) = stmt.kind {
1525 self.check_attributes(l.hir_id, &stmt.span, Target::Statement, None);
1527 intravisit::walk_stmt(self, stmt)
1530 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1531 let target = match expr.kind {
1532 hir::ExprKind::Closure(..) => Target::Closure,
1533 _ => Target::Expression,
1536 self.check_attributes(expr.hir_id, &expr.span, target, None);
1537 intravisit::walk_expr(self, expr)
1542 variant: &'tcx hir::Variant<'tcx>,
1543 generics: &'tcx hir::Generics<'tcx>,
1546 self.check_attributes(variant.id, &variant.span, Target::Variant, None);
1547 intravisit::walk_variant(self, variant, generics, item_id)
1550 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1551 self.check_attributes(macro_def.hir_id(), ¯o_def.span, Target::MacroDef, None);
1552 intravisit::walk_macro_def(self, macro_def);
1555 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1556 self.check_attributes(param.hir_id, ¶m.span, Target::Param, None);
1558 intravisit::walk_param(self, param);
1562 fn is_c_like_enum(item: &Item<'_>) -> bool {
1563 if let ItemKind::Enum(ref def, _) = item.kind {
1564 for variant in def.variants {
1565 match variant.data {
1566 hir::VariantData::Unit(..) => { /* continue */ }
1576 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1577 const ATTRS_TO_CHECK: &[Symbol] = &[
1581 sym::automatically_derived,
1587 for attr_to_check in ATTRS_TO_CHECK {
1588 if tcx.sess.check_name(attr, *attr_to_check) {
1593 "`{}` attribute cannot be used at crate level",
1594 attr_to_check.to_ident_string()
1603 fn check_invalid_macro_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1605 if tcx.sess.check_name(attr, sym::inline) {
1610 "attribute should be applied to function or closure",
1612 .span_label(attr.span, "not a function or closure")
1618 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1619 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
1620 tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor());
1621 tcx.hir().visit_exported_macros_in_krate(check_attr_visitor);
1622 check_invalid_macro_level_attr(tcx, tcx.hir().krate().non_exported_macro_attrs);
1623 if module_def_id.is_top_level_module() {
1624 check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None);
1625 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
1629 pub(crate) fn provide(providers: &mut Providers) {
1630 *providers = Providers { check_mod_attrs, ..*providers };