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_ast::{ast, AttrStyle, Attribute, Lit, LitKind, NestedMetaItem};
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::{pluralize, struct_span_err, Applicability};
10 use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
12 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_hir::{self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID};
15 use rustc_hir::{MethodKind, Target};
16 use rustc_middle::hir::nested_filter;
17 use rustc_middle::ty::query::Providers;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_session::lint::builtin::{
20 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
22 use rustc_session::parse::feature_err;
23 use rustc_span::symbol::{sym, Symbol};
24 use rustc_span::{MultiSpan, Span, DUMMY_SP};
25 use std::collections::hash_map::Entry;
27 pub(crate) fn target_from_impl_item<'tcx>(
29 impl_item: &hir::ImplItem<'_>,
31 match impl_item.kind {
32 hir::ImplItemKind::Const(..) => Target::AssocConst,
33 hir::ImplItemKind::Fn(..) => {
34 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id());
35 let containing_item = tcx.hir().expect_item(parent_hir_id);
36 let containing_impl_is_for_trait = match &containing_item.kind {
37 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
38 _ => bug!("parent of an ImplItem must be an Impl"),
40 if containing_impl_is_for_trait {
41 Target::Method(MethodKind::Trait { body: true })
43 Target::Method(MethodKind::Inherent)
46 hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
50 #[derive(Clone, Copy)]
52 Item(&'tcx Item<'tcx>),
53 ForeignItem(&'tcx ForeignItem<'tcx>),
56 struct CheckAttrVisitor<'tcx> {
60 impl CheckAttrVisitor<'_> {
61 /// Checks any attribute.
67 item: Option<ItemLike<'_>>,
69 let mut doc_aliases = FxHashMap::default();
70 let mut is_valid = true;
71 let mut specified_inline = None;
72 let mut seen = FxHashMap::default();
73 let attrs = self.tcx.hir().attrs(hir_id);
75 let attr_is_valid = match attr.name_or_empty() {
76 sym::inline => self.check_inline(hir_id, attr, span, target),
77 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
78 sym::marker => self.check_marker(hir_id, attr, span, target),
79 sym::rustc_must_implement_one_of => {
80 self.check_rustc_must_implement_one_of(attr, span, target)
82 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
83 sym::track_caller => {
84 self.check_track_caller(hir_id, attr.span, attrs, span, target)
86 sym::doc => self.check_doc_attrs(
90 &mut specified_inline,
93 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
94 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
95 sym::rustc_layout_scalar_valid_range_start
96 | sym::rustc_layout_scalar_valid_range_end => {
97 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
99 sym::allow_internal_unstable => {
100 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
102 sym::rustc_allow_const_fn_unstable => {
103 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
105 sym::naked => self.check_naked(hir_id, attr, span, target),
106 sym::rustc_legacy_const_generics => {
107 self.check_rustc_legacy_const_generics(&attr, span, target, item)
109 sym::rustc_lint_query_instability => {
110 self.check_rustc_lint_query_instability(&attr, span, target)
114 | sym::rustc_if_this_changed
115 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
116 sym::cmse_nonsecure_entry => self.check_cmse_nonsecure_entry(attr, span, target),
117 sym::default_method_body_is_const => {
118 self.check_default_method_body_is_const(attr, span, target)
120 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
121 sym::must_use => self.check_must_use(hir_id, &attr, span, target),
122 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
123 sym::rustc_const_unstable
124 | sym::rustc_const_stable
127 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
130 is_valid &= attr_is_valid;
133 match attr.name_or_empty() {
134 sym::cold => self.check_cold(hir_id, attr, span, target),
135 sym::link => self.check_link(hir_id, attr, span, target),
136 sym::link_name => self.check_link_name(hir_id, attr, span, target),
137 sym::link_section => self.check_link_section(hir_id, attr, span, target),
138 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
139 sym::deprecated | sym::rustc_deprecated => {
140 self.check_deprecated(hir_id, attr, span, target)
142 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
143 sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]),
144 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
145 sym::macro_export => self.check_macro_export(hir_id, attr, target),
146 sym::ignore | sym::should_panic | sym::proc_macro_derive => {
147 self.check_generic_attr(hir_id, attr, target, &[Target::Fn])
149 sym::automatically_derived => {
150 self.check_generic_attr(hir_id, attr, target, &[Target::Impl])
152 sym::no_implicit_prelude => {
153 self.check_generic_attr(hir_id, attr, target, &[Target::Mod])
158 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
160 if hir_id != CRATE_HIR_ID {
161 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
162 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
164 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
165 let msg = match attr.style {
166 ast::AttrStyle::Outer => {
167 "crate-level attribute should be an inner attribute: add an exclamation \
170 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
172 lint.build(msg).emit()
177 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
178 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
181 // Warn on useless empty attributes.
183 attr.name_or_empty(),
191 | sym::target_feature
192 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
194 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
195 lint.build("unused attribute")
198 "remove this attribute",
200 Applicability::MachineApplicable,
203 "attribute `{}` with an empty list has no effect",
215 if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
216 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
219 self.check_repr(attrs, span, target, item, hir_id);
220 self.check_used(attrs, target);
223 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
224 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
226 "`#[{}]` is ignored on struct fields, match arms and macro defs",
230 "this was previously accepted by the compiler but is \
231 being phased out; it will become a hard error in \
235 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
236 for more information",
242 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
243 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
244 lint.build(&format!("`#[{}]` is ignored on struct fields and match arms", sym))
246 "this was previously accepted by the compiler but is \
247 being phased out; it will become a hard error in \
251 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
252 for more information",
258 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
259 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
263 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
264 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
265 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
266 lint.build("`#[inline]` is ignored on function prototypes").emit()
270 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
271 // just a lint, because we previously erroneously allowed it and some crates used it
272 // accidentally, to to be compatible with crates depending on them, we can't throw an
274 Target::AssocConst => {
275 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
276 lint.build("`#[inline]` is ignored on constants")
278 "this was previously accepted by the compiler but is \
279 being phased out; it will become a hard error in \
283 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
284 for more information",
290 // FIXME(#80564): Same for fields, arms, and macro defs
291 Target::Field | Target::Arm | Target::MacroDef => {
292 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
300 "attribute should be applied to function or closure",
302 .span_label(span, "not a function or closure")
309 fn check_generic_attr(
314 allowed_targets: &[Target],
316 if !allowed_targets.iter().any(|t| t == &target) {
317 let name = attr.name_or_empty();
318 let mut i = allowed_targets.iter();
320 let b = i.next().map_or_else(String::new, |t| t.to_string() + "s");
321 let supported_names = i.enumerate().fold(b, |mut b, (i, allowed_target)| {
322 if allowed_targets.len() > 2 && i == allowed_targets.len() - 2 {
323 b.push_str(", and ");
324 } else if allowed_targets.len() == 2 && i == allowed_targets.len() - 2 {
330 b.push_str(&(allowed_target.to_string() + "s"));
333 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
334 lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names))
340 /// Checks if `#[naked]` is applied to a function definition.
341 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
344 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
345 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
346 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
347 // erroneously allowed it and some crates used it accidentally, to to be compatible
348 // with crates depending on them, we can't throw an error here.
349 Target::Field | Target::Arm | Target::MacroDef => {
350 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
358 "attribute should be applied to a function definition",
360 .span_label(span, "not a function definition")
367 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
368 fn check_cmse_nonsecure_entry(&self, attr: &Attribute, span: Span, target: Target) -> bool {
371 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
377 "attribute should be applied to a function definition",
379 .span_label(span, "not a function definition")
386 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
387 fn check_track_caller(
396 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
401 "cannot use `#[track_caller]` with `#[naked]`",
406 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
407 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
408 // `#[track_caller]` attribute with just a lint, because we previously
409 // erroneously allowed it and some crates used it accidentally, to to be compatible
410 // with crates depending on them, we can't throw an error here.
411 Target::Field | Target::Arm | Target::MacroDef => {
413 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
422 "attribute should be applied to function"
424 .span_label(span, "not a function")
431 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
432 fn check_non_exhaustive(
440 Target::Struct | Target::Enum | Target::Variant => true,
441 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
442 // `#[non_exhaustive]` attribute with just a lint, because we previously
443 // erroneously allowed it and some crates used it accidentally, to to be compatible
444 // with crates depending on them, we can't throw an error here.
445 Target::Field | Target::Arm | Target::MacroDef => {
446 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
454 "attribute can only be applied to a struct or enum"
456 .span_label(span, "not a struct or enum")
463 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
464 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
466 Target::Trait => true,
467 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
468 // `#[marker]` attribute with just a lint, because we previously
469 // erroneously allowed it and some crates used it accidentally, to to be compatible
470 // with crates depending on them, we can't throw an error here.
471 Target::Field | Target::Arm | Target::MacroDef => {
472 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
478 .struct_span_err(attr.span, "attribute can only be applied to a trait")
479 .span_label(span, "not a trait")
486 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
487 fn check_rustc_must_implement_one_of(
494 Target::Trait => true,
498 .struct_span_err(attr.span, "attribute can only be applied to a trait")
499 .span_label(span, "not a trait")
506 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
507 fn check_target_feature(
516 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
517 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
518 // crates used this, so only emit a warning.
519 Target::Statement => {
520 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
521 lint.build("attribute should be applied to a function")
523 "this was previously accepted by the compiler but is \
524 being phased out; it will become a hard error in \
527 .span_label(span, "not a function")
532 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
533 // `#[target_feature]` attribute with just a lint, because we previously
534 // erroneously allowed it and some crates used it accidentally, to to be compatible
535 // with crates depending on them, we can't throw an error here.
536 Target::Field | Target::Arm | Target::MacroDef => {
537 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
543 .struct_span_err(attr.span, "attribute should be applied to a function")
544 .span_label(span, "not a function")
551 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
556 &format!("doc {0} attribute expects a string: #[doc({0} = \"a\")]", attr_name),
561 fn check_doc_alias_value(
563 meta: &NestedMetaItem,
568 aliases: &mut FxHashMap<String, Span>,
571 let err_fn = move |span: Span, msg: &str| {
575 "`#[doc(alias{})]` {}",
576 if is_list { "(\"...\")" } else { " = \"...\"" },
582 if doc_alias.is_empty() {
584 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
585 "attribute cannot have empty value",
589 doc_alias.chars().find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
591 self.tcx.sess.span_err(
592 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
594 "{:?} character isn't allowed in `#[doc(alias{})]`",
596 if is_list { "(\"...\")" } else { " = \"...\"" },
601 if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
603 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
604 "cannot start or end with ' '",
607 if let Some(err) = match target {
608 Target::Impl => Some("implementation block"),
609 Target::ForeignMod => Some("extern block"),
611 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
612 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
613 if Target::from_item(containing_item) == Target::Impl {
614 Some("type alias in implementation block")
619 Target::AssocConst => {
620 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
621 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
622 // We can't link to trait impl's consts.
623 let err = "associated constant in trait implementation block";
624 match containing_item.kind {
625 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
629 // we check the validity of params elsewhere
630 Target::Param => return false,
633 return err_fn(meta.span(), &format!("isn't allowed on {}", err));
635 let item_name = self.tcx.hir().name(hir_id);
636 if item_name.as_str() == doc_alias {
637 return err_fn(meta.span(), "is the same as the item's name");
639 let span = meta.span();
640 if let Err(entry) = aliases.try_insert(doc_alias.to_owned(), span) {
641 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, span, |lint| {
642 lint.build("doc alias is duplicated")
643 .span_label(*entry.entry.get(), "first defined here")
652 meta: &NestedMetaItem,
655 aliases: &mut FxHashMap<String, Span>,
657 if let Some(values) = meta.meta_item_list() {
661 Some(l) => match l.kind {
662 LitKind::Str(s, _) => {
663 if !self.check_doc_alias_value(
679 "`#[doc(alias(\"a\"))]` expects string literals",
690 "`#[doc(alias(\"a\"))]` expects string literals",
698 } else if let Some(doc_alias) = meta.value_str().map(|s| s.to_string()) {
699 self.check_doc_alias_value(meta, &doc_alias, hir_id, target, false, aliases)
705 "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of \
706 strings `#[doc(alias(\"a\", \"b\"))]`",
713 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
714 let doc_keyword = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
715 if doc_keyword.is_empty() {
716 self.doc_attr_str_error(meta, "keyword");
719 match self.tcx.hir().find(hir_id).and_then(|node| match node {
720 hir::Node::Item(item) => Some(&item.kind),
723 Some(ItemKind::Mod(ref module)) => {
724 if !module.item_ids.is_empty() {
729 "`#[doc(keyword = \"...\")]` can only be used on empty modules",
740 "`#[doc(keyword = \"...\")]` can only be used on modules",
746 if !rustc_lexer::is_ident(&doc_keyword) {
750 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
751 &format!("`{}` is not a valid identifier", doc_keyword),
759 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
761 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
762 /// if there are conflicting attributes for one item.
764 /// `specified_inline` is used to keep track of whether we have
765 /// already seen an inlining attribute for this item.
766 /// If so, `specified_inline` holds the value and the span of
767 /// the first `inline`/`no_inline` attribute.
771 meta: &NestedMetaItem,
774 specified_inline: &mut Option<(bool, Span)>,
776 if target == Target::Use || target == Target::ExternCrate {
777 let do_inline = meta.name_or_empty() == sym::inline;
778 if let Some((prev_inline, prev_span)) = *specified_inline {
779 if do_inline != prev_inline {
780 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
781 spans.push_span_label(prev_span, String::from("this attribute..."));
782 spans.push_span_label(
784 String::from("...conflicts with this attribute"),
788 .struct_span_err(spans, "conflicting doc inlining attributes")
789 .help("remove one of the conflicting attributes")
795 *specified_inline = Some((do_inline, meta.span()));
799 self.tcx.struct_span_lint_hir(
800 INVALID_DOC_ATTRIBUTES,
804 let mut err = lint.build(
805 "this attribute can only be applied to a `use` item",
807 err.span_label(meta.span(), "only applicable on `use` items");
808 if attr.style == AttrStyle::Outer {
810 self.tcx.hir().span(hir_id),
814 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#inline-and-no_inline for more information")
822 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
823 fn check_attr_not_crate_level(
825 meta: &NestedMetaItem,
829 if CRATE_HIR_ID == hir_id {
835 "`#![doc({} = \"...\")]` isn't allowed as a crate-level attribute",
845 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
846 fn check_attr_crate_level(
849 meta: &NestedMetaItem,
852 if hir_id != CRATE_HIR_ID {
853 self.tcx.struct_span_lint_hir(
854 INVALID_DOC_ATTRIBUTES,
858 let mut err = lint.build(
859 "this attribute can only be applied at the crate level",
861 if attr.style == AttrStyle::Outer && self.tcx.hir().get_parent_item(hir_id) == CRATE_DEF_ID {
863 self.tcx.sess.source_map().span_to_snippet(attr.span)
866 err.span_suggestion_verbose(
868 "to apply to the crate, use an inner attribute",
870 Applicability::MaybeIncorrect,
875 "to apply to the crate, use an inner attribute",
879 err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#at-the-crate-level for more information")
888 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
890 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
891 let mut is_valid = true;
892 if let Some(metas) = meta.meta_item_list() {
893 for i_meta in metas {
894 match i_meta.name_or_empty() {
895 sym::attr | sym::no_crate_inject => {}
897 self.tcx.struct_span_lint_hir(
898 INVALID_DOC_ATTRIBUTES,
903 "unknown `doc(test)` attribute `{}`",
904 rustc_ast_pretty::pprust::path_to_string(
905 &i_meta.meta_item().unwrap().path
916 self.tcx.struct_span_lint_hir(INVALID_DOC_ATTRIBUTES, hir_id, meta.span(), |lint| {
917 lint.build("`#[doc(test(...)]` takes a list of attributes").emit();
924 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
926 /// `specified_inline` should be initialized to `None` and kept for the scope
927 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
929 /// [`check_doc_inline`]: Self::check_doc_inline
935 specified_inline: &mut Option<(bool, Span)>,
936 aliases: &mut FxHashMap<String, Span>,
938 let mut is_valid = true;
940 if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) {
942 if let Some(i_meta) = meta.meta_item() {
943 match i_meta.name_or_empty() {
945 if !self.check_attr_not_crate_level(&meta, hir_id, "alias")
946 || !self.check_doc_alias(&meta, hir_id, target, aliases) =>
952 if !self.check_attr_not_crate_level(&meta, hir_id, "keyword")
953 || !self.check_doc_keyword(&meta, hir_id) =>
958 sym::html_favicon_url
960 | sym::html_playground_url
961 | sym::issue_tracker_base_url
963 | sym::html_no_source
965 if !self.check_attr_crate_level(&attr, &meta, hir_id) =>
970 sym::inline | sym::no_inline
971 if !self.check_doc_inline(
982 // no_default_passes: deprecated
983 // passes: deprecated
984 // plugins: removed, but rustdoc warns about it itself
989 | sym::html_favicon_url
991 | sym::html_no_source
992 | sym::html_playground_url
995 | sym::issue_tracker_base_url
998 | sym::no_default_passes
1000 | sym::notable_trait
1002 | sym::plugins => {}
1005 if !self.check_test_attr(&meta, hir_id) {
1011 if !self.tcx.features().rustdoc_internals {
1012 self.tcx.struct_span_lint_hir(
1013 INVALID_DOC_ATTRIBUTES,
1017 let mut diag = lint.build(
1018 "`doc(primitive)` should never have been stable",
1027 self.tcx.struct_span_lint_hir(
1028 INVALID_DOC_ATTRIBUTES,
1032 let mut diag = lint.build(&format!(
1033 "unknown `doc` attribute `{}`",
1034 rustc_ast_pretty::pprust::path_to_string(&i_meta.path),
1036 if i_meta.has_name(sym::spotlight) {
1038 "`doc(spotlight)` was renamed to `doc(notable_trait)`",
1040 diag.span_suggestion_short(
1042 "use `notable_trait` instead",
1043 String::from("notable_trait"),
1044 Applicability::MachineApplicable,
1046 diag.note("`doc(spotlight)` is now a no-op");
1048 if i_meta.has_name(sym::include) {
1049 if let Some(value) = i_meta.value_str() {
1050 // if there are multiple attributes, the suggestion would suggest deleting all of them, which is incorrect
1051 let applicability = if list.len() == 1 {
1052 Applicability::MachineApplicable
1054 Applicability::MaybeIncorrect
1056 let inner = if attr.style == AttrStyle::Inner {
1061 diag.span_suggestion(
1062 attr.meta().unwrap().span,
1063 "use `doc = include_str!` instead",
1065 "#{}[doc = include_str!(\"{}\")]",
1079 self.tcx.struct_span_lint_hir(
1080 INVALID_DOC_ATTRIBUTES,
1084 lint.build(&"invalid `doc` attribute").emit();
1095 /// Warns against some misuses of `#[pass_by_value]`
1096 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1098 Target::Struct | Target::Enum | Target::TyAlias => true,
1104 "`pass_by_value` attribute should be applied to a struct, enum or type alias.",
1106 .span_label(span, "is not a struct, enum or type alias")
1113 /// Warns against some misuses of `#[must_use]`
1114 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1115 let node = self.tcx.hir().get(hir_id);
1116 if let Some(fn_node) = node.fn_kind() {
1117 if let rustc_hir::IsAsync::Async = fn_node.asyncness() {
1118 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1120 "`must_use` attribute on `async` functions \
1121 applies to the anonymous `Future` returned by the \
1122 function, not the value within",
1126 "this attribute does nothing, the `Future`s \
1127 returned by async functions are already `must_use`",
1142 // `impl Trait` in return position can trip
1143 // `unused_must_use` if `Trait` is marked as
1147 let article = match target {
1152 | Target::Expression
1154 | Target::AssocConst
1155 | Target::AssocTy => "an",
1159 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1160 lint.build(&format!(
1161 "`#[must_use]` has no effect when applied to {article} {target}"
1167 // For now, its always valid
1171 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1172 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1174 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1178 .struct_span_err(attr.span, "`must_not_suspend` attribute should be applied to a struct, enum, or trait")
1179 .span_label(span, "is not a struct, enum, or trait")
1186 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1187 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1189 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1190 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1191 // `#[cold]` attribute with just a lint, because we previously
1192 // erroneously allowed it and some crates used it accidentally, to to be compatible
1193 // with crates depending on them, we can't throw an error here.
1194 Target::Field | Target::Arm | Target::MacroDef => {
1195 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1198 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1199 // this, so only emit a warning.
1200 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1201 lint.build("attribute should be applied to a function")
1203 "this was previously accepted by the compiler but is \
1204 being phased out; it will become a hard error in \
1207 .span_label(span, "not a function")
1214 /// Checks if `#[link]` is applied to an item other than a foreign module.
1215 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1217 Target::ForeignMod => {}
1219 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1220 let mut diag = lint.build("attribute should be applied to an `extern` block");
1222 "this was previously accepted by the compiler but is \
1223 being phased out; it will become a hard error in \
1227 diag.span_label(span, "not an `extern` block");
1234 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1235 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1237 Target::ForeignFn | Target::ForeignStatic => {}
1238 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1239 // `#[link_name]` attribute with just a lint, because we previously
1240 // erroneously allowed it and some crates used it accidentally, to to be compatible
1241 // with crates depending on them, we can't throw an error here.
1242 Target::Field | Target::Arm | Target::MacroDef => {
1243 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1246 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1247 // used this, so only emit a warning.
1248 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1250 lint.build("attribute should be applied to a foreign function or static");
1252 "this was previously accepted by the compiler but is \
1253 being phased out; it will become a hard error in \
1258 if let Target::ForeignMod = target {
1259 if let Some(value) = attr.value_str() {
1262 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
1265 diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
1269 diag.span_label(span, "not a foreign function or static");
1276 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1277 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1279 Target::ExternCrate => true,
1280 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1281 // `#[no_link]` attribute with just a lint, because we previously
1282 // erroneously allowed it and some crates used it accidentally, to to be compatible
1283 // with crates depending on them, we can't throw an error here.
1284 Target::Field | Target::Arm | Target::MacroDef => {
1285 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1293 "attribute should be applied to an `extern crate` item",
1295 .span_label(span, "not an `extern crate` item")
1302 fn is_impl_item(&self, hir_id: HirId) -> bool {
1303 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1306 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1307 fn check_export_name(
1315 Target::Static | Target::Fn => true,
1316 Target::Method(..) if self.is_impl_item(hir_id) => true,
1317 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1318 // `#[export_name]` attribute with just a lint, because we previously
1319 // erroneously allowed it and some crates used it accidentally, to to be compatible
1320 // with crates depending on them, we can't throw an error here.
1321 Target::Field | Target::Arm | Target::MacroDef => {
1322 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1330 "attribute should be applied to a free function, impl method or static",
1332 .span_label(span, "not a free function, impl method or static")
1339 fn check_rustc_layout_scalar_valid_range(
1345 if target != Target::Struct {
1348 .struct_span_err(attr.span, "attribute should be applied to a struct")
1349 .span_label(span, "not a struct")
1354 let Some(list) = attr.meta_item_list() else {
1358 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
1363 .struct_span_err(attr.span, "expected exactly one integer literal argument")
1369 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1370 fn check_rustc_legacy_const_generics(
1375 item: Option<ItemLike<'_>>,
1377 let is_function = matches!(target, Target::Fn | Target::Method(..));
1381 .struct_span_err(attr.span, "attribute should be applied to a function")
1382 .span_label(span, "not a function")
1387 let Some(list) = attr.meta_item_list() else {
1388 // The attribute form is validated on AST.
1392 let Some(ItemLike::Item(Item {
1393 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1396 bug!("should be a function item");
1399 for param in generics.params {
1401 hir::GenericParamKind::Const { .. } => {}
1407 "#[rustc_legacy_const_generics] functions must \
1408 only have const generics",
1410 .span_label(param.span, "non-const generic parameter")
1417 if list.len() != generics.params.len() {
1422 "#[rustc_legacy_const_generics] must have one index for each generic parameter",
1424 .span_label(generics.span, "generic parameters")
1429 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1430 let mut invalid_args = vec![];
1432 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1433 if *val >= arg_count {
1434 let span = meta.span();
1437 .struct_span_err(span, "index exceeds number of arguments")
1441 "there {} only {} argument{}",
1442 if arg_count != 1 { "are" } else { "is" },
1444 pluralize!(arg_count)
1451 invalid_args.push(meta.span());
1455 if !invalid_args.is_empty() {
1458 .struct_span_err(invalid_args, "arguments should be non-negative integers")
1466 fn check_rustc_lint_query_instability(
1472 let is_function = matches!(target, Target::Fn | Target::Method(..));
1476 .struct_span_err(attr.span, "attribute should be applied to a function")
1477 .span_label(span, "not a function")
1485 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1486 /// option is passed to the compiler.
1487 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1488 if self.tcx.sess.opts.debugging_opts.query_dep_graph {
1493 .struct_span_err(attr.span, "attribute requires -Z query-dep-graph to be enabled")
1499 /// Checks if `#[link_section]` is applied to a function or static.
1500 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1502 Target::Static | Target::Fn | Target::Method(..) => {}
1503 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1504 // `#[link_section]` attribute with just a lint, because we previously
1505 // erroneously allowed it and some crates used it accidentally, to to be compatible
1506 // with crates depending on them, we can't throw an error here.
1507 Target::Field | Target::Arm | Target::MacroDef => {
1508 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1511 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1512 // crates used this, so only emit a warning.
1513 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1514 lint.build("attribute should be applied to a function or static")
1516 "this was previously accepted by the compiler but is \
1517 being phased out; it will become a hard error in \
1520 .span_label(span, "not a function or static")
1527 /// Checks if `#[no_mangle]` is applied to a function or static.
1528 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1530 Target::Static | Target::Fn => {}
1531 Target::Method(..) if self.is_impl_item(hir_id) => {}
1532 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1533 // `#[no_mangle]` attribute with just a lint, because we previously
1534 // erroneously allowed it and some crates used it accidentally, to to be compatible
1535 // with crates depending on them, we can't throw an error here.
1536 Target::Field | Target::Arm | Target::MacroDef => {
1537 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1539 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1540 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1541 // otherwise the error seems odd
1542 Target::ForeignFn | Target::ForeignStatic => {
1543 let foreign_item_kind = match target {
1544 Target::ForeignFn => "function",
1545 Target::ForeignStatic => "static",
1546 _ => unreachable!(),
1548 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1549 lint.build(&format!(
1550 "`#[no_mangle]` has no effect on a foreign {}",
1554 "this was previously accepted by the compiler but is \
1555 being phased out; it will become a hard error in \
1558 .span_label(span, format!("foreign {}", foreign_item_kind))
1559 .note("symbol names in extern blocks are not mangled")
1562 "remove this attribute",
1564 Applicability::MachineApplicable,
1570 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1571 // crates used this, so only emit a warning.
1572 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1574 "attribute should be applied to a free function, impl method or static",
1577 "this was previously accepted by the compiler but is \
1578 being phased out; it will become a hard error in \
1581 .span_label(span, "not a free function, impl method or static")
1588 /// Checks if the `#[repr]` attributes on `item` are valid.
1591 attrs: &[Attribute],
1594 item: Option<ItemLike<'_>>,
1597 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1600 // #[repr(bar, align(8))]
1602 let hints: Vec<_> = attrs
1604 .filter(|attr| attr.has_name(sym::repr))
1605 .filter_map(|attr| attr.meta_item_list())
1609 let mut int_reprs = 0;
1610 let mut is_c = false;
1611 let mut is_simd = false;
1612 let mut is_transparent = false;
1614 for hint in &hints {
1615 if !hint.is_meta_item() {
1620 "meta item in `repr` must be an identifier"
1626 let (article, allowed_targets) = match hint.name_or_empty() {
1630 Target::Struct | Target::Union | Target::Enum => continue,
1631 _ => ("a", "struct, enum, or union"),
1635 if let (Target::Fn, true) = (target, !self.tcx.features().fn_align) {
1637 &self.tcx.sess.parse_sess,
1640 "`repr(align)` attributes on functions are unstable",
1646 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1647 _ => ("a", "struct, enum, function, or union"),
1651 if target != Target::Struct && target != Target::Union {
1652 ("a", "struct or union")
1659 if target != Target::Struct {
1665 sym::transparent => {
1666 is_transparent = true;
1668 Target::Struct | Target::Union | Target::Enum => continue,
1669 _ => ("a", "struct, enum, or union"),
1673 if !self.tcx.features().enabled(sym::no_niche) {
1675 &self.tcx.sess.parse_sess,
1678 "the attribute `repr(no_niche)` is currently unstable",
1683 Target::Struct | Target::Enum => continue,
1684 _ => ("a", "struct or enum"),
1700 if target != Target::Enum {
1711 "unrecognized representation hint"
1724 &format!("attribute should be applied to {} {}", article, allowed_targets)
1726 .span_label(span, &format!("not {} {}", article, allowed_targets))
1730 // Just point at all repr hints if there are any incompatibilities.
1731 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1732 let hint_spans = hints.iter().map(|hint| hint.span());
1734 // Error on repr(transparent, <anything else apart from no_niche>).
1735 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
1736 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
1737 if is_transparent && non_no_niche_count > 1 {
1738 let hint_spans: Vec<_> = hint_spans.clone().collect();
1743 "transparent {} cannot have other repr hints",
1748 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1750 || (is_simd && is_c)
1753 && item.map_or(false, |item| {
1754 if let ItemLike::Item(item) = item {
1755 return is_c_like_enum(item);
1760 self.tcx.struct_span_lint_hir(
1761 CONFLICTING_REPR_HINTS,
1763 hint_spans.collect::<Vec<Span>>(),
1765 lint.build("conflicting representation hints")
1766 .code(rustc_errors::error_code!(E0566))
1773 fn check_used(&self, attrs: &[Attribute], target: Target) {
1774 let mut used_linker_span = None;
1775 let mut used_compiler_span = None;
1776 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1777 if target != Target::Static {
1780 .span_err(attr.span, "attribute must be applied to a `static` variable");
1782 let inner = attr.meta_item_list();
1783 match inner.as_deref() {
1784 Some([item]) if item.has_name(sym::linker) => {
1785 if used_linker_span.is_none() {
1786 used_linker_span = Some(attr.span);
1789 Some([item]) if item.has_name(sym::compiler) => {
1790 if used_compiler_span.is_none() {
1791 used_compiler_span = Some(attr.span);
1795 // This error case is handled in rustc_typeck::collect.
1798 // Default case (compiler) when arg isn't defined.
1799 if used_compiler_span.is_none() {
1800 used_compiler_span = Some(attr.span);
1805 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1806 let spans = vec![linker_span, compiler_span];
1811 "`used(compiler)` and `used(linker)` can't be used together",
1817 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1818 /// (Allows proc_macro functions)
1819 fn check_allow_internal_unstable(
1825 attrs: &[Attribute],
1827 debug!("Checking target: {:?}", target);
1831 if self.tcx.sess.is_proc_macro_attr(attr) {
1832 debug!("Is proc macro attr");
1836 debug!("Is not proc macro attr");
1839 Target::MacroDef => true,
1840 // FIXME(#80564): We permit struct fields and match arms to have an
1841 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1842 // erroneously allowed it and some crates used it accidentally, to to be compatible
1843 // with crates depending on them, we can't throw an error here.
1844 Target::Field | Target::Arm => {
1845 self.inline_attr_str_error_without_macro_def(
1848 "allow_internal_unstable",
1855 .struct_span_err(attr.span, "attribute should be applied to a macro")
1856 .span_label(span, "not a macro")
1863 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1864 /// (Allows proc_macro functions)
1865 fn check_rustc_allow_const_fn_unstable(
1873 Target::Fn | Target::Method(_)
1874 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id)) =>
1878 // FIXME(#80564): We permit struct fields and match arms to have an
1879 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1880 // erroneously allowed it and some crates used it accidentally, to to be compatible
1881 // with crates depending on them, we can't throw an error here.
1882 Target::Field | Target::Arm | Target::MacroDef => {
1883 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1889 .struct_span_err(attr.span, "attribute should be applied to `const fn`")
1890 .span_label(span, "not a `const fn`")
1897 /// default_method_body_is_const should only be applied to trait methods with default bodies.
1898 fn check_default_method_body_is_const(
1905 Target::Method(MethodKind::Trait { body: true }) => true,
1911 "attribute should be applied to a trait method with body",
1913 .span_label(span, "not a trait method or missing a body")
1920 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1922 Target::Expression => {
1925 .struct_span_err(attr.span, "attribute cannot be applied to an expression")
1933 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
1935 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
1936 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1937 lint.build("attribute is ignored here").emit();
1944 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1945 let name = attr.name_or_empty();
1947 Target::ExternCrate | Target::Mod => {}
1949 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1950 lint.build(&format!(
1951 "`#[{name}]` only has an effect on `extern crate` and modules"
1959 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1960 if target != Target::MacroDef {
1961 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1962 lint.build("`#[macro_export]` only has an effect on macro definitions").emit();
1967 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1968 if target != Target::Fn {
1969 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1970 lint.build("`#[plugin_registrar]` only has an effect on functions").emit();
1976 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1977 type NestedFilter = nested_filter::OnlyBodies;
1979 fn nested_visit_map(&mut self) -> Self::Map {
1983 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1984 // Historically we've run more checks on non-exported than exported macros,
1985 // so this lets us continue to run them while maintaining backwards compatibility.
1986 // In the long run, the checks should be harmonized.
1987 if let ItemKind::Macro(ref macro_def, _) = item.kind {
1988 let def_id = item.def_id.to_def_id();
1989 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
1990 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1994 let target = Target::from_item(item);
1995 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1996 intravisit::walk_item(self, item)
1999 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2000 let target = Target::from_generic_param(generic_param);
2001 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2002 intravisit::walk_generic_param(self, generic_param)
2005 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2006 let target = Target::from_trait_item(trait_item);
2007 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2008 intravisit::walk_trait_item(self, trait_item)
2011 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2012 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2013 intravisit::walk_field_def(self, struct_field);
2016 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2017 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2018 intravisit::walk_arm(self, arm);
2021 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2022 let target = Target::from_foreign_item(f_item);
2023 self.check_attributes(
2027 Some(ItemLike::ForeignItem(f_item)),
2029 intravisit::walk_foreign_item(self, f_item)
2032 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2033 let target = target_from_impl_item(self.tcx, impl_item);
2034 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2035 intravisit::walk_impl_item(self, impl_item)
2038 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2039 // When checking statements ignore expressions, they will be checked later.
2040 if let hir::StmtKind::Local(ref l) = stmt.kind {
2041 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2043 intravisit::walk_stmt(self, stmt)
2046 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2047 let target = match expr.kind {
2048 hir::ExprKind::Closure(..) => Target::Closure,
2049 _ => Target::Expression,
2052 self.check_attributes(expr.hir_id, expr.span, target, None);
2053 intravisit::walk_expr(self, expr)
2058 variant: &'tcx hir::Variant<'tcx>,
2059 generics: &'tcx hir::Generics<'tcx>,
2062 self.check_attributes(variant.id, variant.span, Target::Variant, None);
2063 intravisit::walk_variant(self, variant, generics, item_id)
2066 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2067 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2069 intravisit::walk_param(self, param);
2073 fn is_c_like_enum(item: &Item<'_>) -> bool {
2074 if let ItemKind::Enum(ref def, _) = item.kind {
2075 for variant in def.variants {
2076 match variant.data {
2077 hir::VariantData::Unit(..) => { /* continue */ }
2087 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2089 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2090 // Check for builtin attributes at the crate level
2091 // which were unsuccessfully resolved due to cannot determine
2092 // resolution for the attribute macro error.
2093 const ATTRS_TO_CHECK: &[Symbol] = &[
2097 sym::automatically_derived,
2103 sym::global_allocator,
2108 // This function should only be called with crate attributes
2109 // which are inner attributes always but lets check to make sure
2110 if attr.style == AttrStyle::Inner {
2111 for attr_to_check in ATTRS_TO_CHECK {
2112 if attr.has_name(*attr_to_check) {
2113 let mut err = tcx.sess.struct_span_err(
2116 "`{}` attribute cannot be used at crate level",
2117 attr_to_check.to_ident_string()
2120 // Only emit an error with a suggestion if we can create a
2121 // string out of the attribute span
2122 if let Ok(src) = tcx.sess.source_map().span_to_snippet(attr.span) {
2123 let replacement = src.replace("#!", "#");
2124 err.span_suggestion_verbose(
2126 "perhaps you meant to use an outer attribute",
2128 rustc_errors::Applicability::MachineApplicable,
2138 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2139 let attrs = tcx.hir().attrs(item.hir_id());
2142 if attr.has_name(sym::inline) {
2147 "attribute should be applied to function or closure",
2149 .span_label(attr.span, "not a function or closure")
2155 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2156 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
2157 tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor());
2158 if module_def_id.is_top_level_module() {
2159 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2160 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2164 pub(crate) fn provide(providers: &mut Providers) {
2165 *providers = Providers { check_mod_attrs, ..*providers };
2168 fn check_duplicates(
2172 duplicates: AttributeDuplicates,
2173 seen: &mut FxHashMap<Symbol, Span>,
2175 use AttributeDuplicates::*;
2176 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2181 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2182 match seen.entry(attr.name_or_empty()) {
2183 Entry::Occupied(mut entry) => {
2184 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2185 let to_remove = entry.insert(attr.span);
2186 (to_remove, attr.span)
2188 (attr.span, *entry.get())
2190 tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, this, |lint| {
2191 let mut db = lint.build("unused attribute");
2192 db.span_note(other, "attribute also specified here").span_suggestion(
2194 "remove this attribute",
2196 Applicability::MachineApplicable,
2198 if matches!(duplicates, FutureWarnFollowing | FutureWarnPreceding) {
2200 "this was previously accepted by the compiler but is \
2201 being phased out; it will become a hard error in \
2208 Entry::Vacant(entry) => {
2209 entry.insert(attr.span);
2213 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2214 Entry::Occupied(mut entry) => {
2215 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2216 let to_remove = entry.insert(attr.span);
2217 (to_remove, attr.span)
2219 (attr.span, *entry.get())
2224 &format!("multiple `{}` attributes", attr.name_or_empty()),
2226 .span_note(other, "attribute also specified here")
2229 "remove this attribute",
2231 Applicability::MachineApplicable,
2235 Entry::Vacant(entry) => {
2236 entry.insert(attr.span);