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
8 use rustc_ast::{ast, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_errors::{fluent, struct_span_err, Applicability, MultiSpan};
11 use rustc_expand::base::resolve_path;
12 use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
14 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::{self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID};
17 use rustc_hir::{MethodKind, Target};
18 use rustc_middle::hir::nested_filter;
19 use rustc_middle::ty::query::Providers;
20 use rustc_middle::ty::TyCtxt;
21 use rustc_session::lint::builtin::{
22 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
24 use rustc_session::parse::feature_err;
25 use rustc_span::symbol::{kw, sym, Symbol};
26 use rustc_span::{Span, DUMMY_SP};
27 use rustc_target::spec::abi::Abi;
28 use std::collections::hash_map::Entry;
30 pub(crate) fn target_from_impl_item<'tcx>(
32 impl_item: &hir::ImplItem<'_>,
34 match impl_item.kind {
35 hir::ImplItemKind::Const(..) => Target::AssocConst,
36 hir::ImplItemKind::Fn(..) => {
37 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id());
38 let containing_item = tcx.hir().expect_item(parent_hir_id);
39 let containing_impl_is_for_trait = match &containing_item.kind {
40 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
41 _ => bug!("parent of an ImplItem must be an Impl"),
43 if containing_impl_is_for_trait {
44 Target::Method(MethodKind::Trait { body: true })
46 Target::Method(MethodKind::Inherent)
49 hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
53 #[derive(Clone, Copy)]
55 Item(&'tcx Item<'tcx>),
56 ForeignItem(&'tcx ForeignItem<'tcx>),
59 struct CheckAttrVisitor<'tcx> {
63 impl CheckAttrVisitor<'_> {
64 /// Checks any attribute.
70 item: Option<ItemLike<'_>>,
72 let mut doc_aliases = FxHashMap::default();
73 let mut is_valid = true;
74 let mut specified_inline = None;
75 let mut seen = FxHashMap::default();
76 let attrs = self.tcx.hir().attrs(hir_id);
78 let attr_is_valid = match attr.name_or_empty() {
79 sym::inline => self.check_inline(hir_id, attr, span, target),
80 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
81 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
82 sym::marker => self.check_marker(hir_id, attr, span, target),
83 sym::rustc_must_implement_one_of => {
84 self.check_rustc_must_implement_one_of(attr, span, target)
86 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
87 sym::thread_local => self.check_thread_local(attr, span, target),
88 sym::track_caller => {
89 self.check_track_caller(hir_id, attr.span, attrs, span, target)
91 sym::doc => self.check_doc_attrs(
95 &mut specified_inline,
98 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
99 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
100 sym::rustc_layout_scalar_valid_range_start
101 | sym::rustc_layout_scalar_valid_range_end => {
102 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
104 sym::allow_internal_unstable => {
105 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
107 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
108 sym::rustc_allow_const_fn_unstable => {
109 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
111 sym::rustc_std_internal_symbol => {
112 self.check_rustc_std_internal_symbol(&attr, span, target)
114 sym::naked => self.check_naked(hir_id, attr, span, target),
115 sym::rustc_legacy_const_generics => {
116 self.check_rustc_legacy_const_generics(&attr, span, target, item)
118 sym::rustc_lint_query_instability => {
119 self.check_rustc_lint_query_instability(&attr, span, target)
121 sym::rustc_lint_diagnostics => {
122 self.check_rustc_lint_diagnostics(&attr, span, target)
124 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
125 sym::rustc_lint_opt_deny_field_access => {
126 self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
130 | sym::rustc_if_this_changed
131 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
132 sym::cmse_nonsecure_entry => self.check_cmse_nonsecure_entry(attr, span, target),
133 sym::const_trait => self.check_const_trait(attr, span, target),
134 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
135 sym::must_use => self.check_must_use(hir_id, &attr, span, target),
136 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
137 sym::rustc_allow_incoherent_impl => {
138 self.check_allow_incoherent_impl(&attr, span, target)
140 sym::rustc_has_incoherent_inherent_impls => {
141 self.check_has_incoherent_inherent_impls(&attr, span, target)
143 sym::rustc_const_unstable
144 | sym::rustc_const_stable
147 | sym::rustc_allowed_through_unstable_modules
148 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
149 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
152 is_valid &= attr_is_valid;
155 match attr.name_or_empty() {
156 sym::cold => self.check_cold(hir_id, attr, span, target),
157 sym::link => self.check_link(hir_id, attr, span, target),
158 sym::link_name => self.check_link_name(hir_id, attr, span, target),
159 sym::link_section => self.check_link_section(hir_id, attr, span, target),
160 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
161 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
162 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
163 sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]),
164 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
165 sym::macro_export => self.check_macro_export(hir_id, attr, target),
166 sym::ignore | sym::should_panic | sym::proc_macro_derive => {
167 self.check_generic_attr(hir_id, attr, target, &[Target::Fn])
169 sym::automatically_derived => {
170 self.check_generic_attr(hir_id, attr, target, &[Target::Impl])
172 sym::no_implicit_prelude => {
173 self.check_generic_attr(hir_id, attr, target, &[Target::Mod])
178 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
180 if hir_id != CRATE_HIR_ID {
181 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
182 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
185 ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
189 errors::OuterCrateLevelAttr,
191 ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
195 errors::InnerCrateLevelAttr,
201 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
202 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
205 self.check_unused_attribute(hir_id, attr)
212 // FIXME(@lcnr): this doesn't belong here.
213 if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
214 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
217 self.check_repr(attrs, span, target, item, hir_id);
218 self.check_used(attrs, target);
221 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
222 self.tcx.emit_spanned_lint(
226 errors::IgnoredAttrWithMacro { sym },
230 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
231 self.tcx.emit_spanned_lint(
235 errors::IgnoredAttr { sym },
239 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
240 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
244 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
245 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
246 self.tcx.emit_spanned_lint(
250 errors::IgnoredInlineAttrFnProto,
254 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
255 // just a lint, because we previously erroneously allowed it and some crates used it
256 // accidentally, to to be compatible with crates depending on them, we can't throw an
258 Target::AssocConst => {
259 self.tcx.emit_spanned_lint(
263 errors::IgnoredInlineAttrConstants,
267 // FIXME(#80564): Same for fields, arms, and macro defs
268 Target::Field | Target::Arm | Target::MacroDef => {
269 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
273 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
274 attr_span: attr.span,
282 /// Checks if a `#[no_coverage]` is applied directly to a function
283 fn check_no_coverage(
291 // no_coverage on function is fine
294 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
296 // function prototypes can't be covered
297 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
298 self.tcx.emit_spanned_lint(
302 errors::IgnoredNoCoverageFnProto,
307 Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
308 self.tcx.emit_spanned_lint(
312 errors::IgnoredNoCoveragePropagate,
317 Target::Expression | Target::Statement | Target::Arm => {
318 self.tcx.emit_spanned_lint(
322 errors::IgnoredNoCoverageFnDefn,
328 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
329 attr_span: attr.span,
337 fn check_generic_attr(
342 allowed_targets: &[Target],
344 if !allowed_targets.iter().any(|t| t == &target) {
345 let name = attr.name_or_empty();
346 let mut i = allowed_targets.iter();
348 let b = i.next().map_or_else(String::new, |t| t.to_string() + "s");
349 let supported_names = i.enumerate().fold(b, |mut b, (i, allowed_target)| {
350 if allowed_targets.len() > 2 && i == allowed_targets.len() - 2 {
351 b.push_str(", and ");
352 } else if allowed_targets.len() == 2 && i == allowed_targets.len() - 2 {
358 b.push_str(&(allowed_target.to_string() + "s"));
361 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
362 lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names))
368 /// Checks if `#[naked]` is applied to a function definition.
369 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
372 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
373 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
374 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
375 // erroneously allowed it and some crates used it accidentally, to to be compatible
376 // with crates depending on them, we can't throw an error here.
377 Target::Field | Target::Arm | Target::MacroDef => {
378 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
382 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
383 attr_span: attr.span,
391 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
392 fn check_cmse_nonsecure_entry(&self, attr: &Attribute, span: Span, target: Target) -> bool {
395 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
397 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
398 attr_span: attr.span,
406 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
407 fn check_track_caller(
416 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
417 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
420 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
421 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
422 // `#[track_caller]` attribute with just a lint, because we previously
423 // erroneously allowed it and some crates used it accidentally, to to be compatible
424 // with crates depending on them, we can't throw an error here.
425 Target::Field | Target::Arm | Target::MacroDef => {
427 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
434 .emit_err(errors::TrackedCallerWrongLocation { attr_span, defn_span: span });
440 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
441 fn check_non_exhaustive(
449 Target::Struct | Target::Enum | Target::Variant => true,
450 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
451 // `#[non_exhaustive]` attribute with just a lint, because we previously
452 // erroneously allowed it and some crates used it accidentally, to to be compatible
453 // with crates depending on them, we can't throw an error here.
454 Target::Field | Target::Arm | Target::MacroDef => {
455 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
459 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
460 attr_span: attr.span,
468 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
469 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
471 Target::Trait => true,
472 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
473 // `#[marker]` attribute with just a lint, because we previously
474 // erroneously allowed it and some crates used it accidentally, to to be compatible
475 // with crates depending on them, we can't throw an error here.
476 Target::Field | Target::Arm | Target::MacroDef => {
477 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
481 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
482 attr_span: attr.span,
490 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
491 fn check_rustc_must_implement_one_of(
498 Target::Trait => true,
500 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
501 attr_span: attr.span,
509 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
510 fn check_target_feature(
519 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
520 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
521 // crates used this, so only emit a warning.
522 Target::Statement => {
523 self.tcx.emit_spanned_lint(
527 errors::TargetFeatureOnStatement,
531 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
532 // `#[target_feature]` attribute with just a lint, because we previously
533 // erroneously allowed it and some crates used it accidentally, to to be compatible
534 // with crates depending on them, we can't throw an error here.
535 Target::Field | Target::Arm | Target::MacroDef => {
536 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
540 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
541 attr_span: attr.span,
549 /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
550 fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
552 Target::ForeignStatic | Target::Static => true,
554 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
555 attr_span: attr.span,
563 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
564 self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
567 fn check_doc_alias_value(
569 meta: &NestedMetaItem,
574 aliases: &mut FxHashMap<String, Span>,
577 let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
579 &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
580 if doc_alias == kw::Empty {
581 tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
585 let doc_alias_str = doc_alias.as_str();
586 if let Some(c) = doc_alias_str
588 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
590 tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
593 if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
594 tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
598 let span = meta.span();
599 if let Some(location) = match target {
600 Target::Impl => Some("implementation block"),
601 Target::ForeignMod => Some("extern block"),
603 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
604 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
605 if Target::from_item(containing_item) == Target::Impl {
606 Some("type alias in implementation block")
611 Target::AssocConst => {
612 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
613 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
614 // We can't link to trait impl's consts.
615 let err = "associated constant in trait implementation block";
616 match containing_item.kind {
617 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
621 // we check the validity of params elsewhere
622 Target::Param => return false,
625 tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
628 let item_name = self.tcx.hir().name(hir_id);
629 if item_name == doc_alias {
630 tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
633 if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
634 self.tcx.emit_spanned_lint(
638 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
646 meta: &NestedMetaItem,
649 aliases: &mut FxHashMap<String, Span>,
651 if let Some(values) = meta.meta_item_list() {
655 Some(l) => match l.kind {
656 LitKind::Str(s, _) => {
657 if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
664 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
669 self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
675 } else if let Some(doc_alias) = meta.value_str() {
676 self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
678 self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
683 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
684 let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
685 if doc_keyword == kw::Empty {
686 self.doc_attr_str_error(meta, "keyword");
689 match self.tcx.hir().find(hir_id).and_then(|node| match node {
690 hir::Node::Item(item) => Some(&item.kind),
693 Some(ItemKind::Mod(ref module)) => {
694 if !module.item_ids.is_empty() {
695 self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
700 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
704 if !rustc_lexer::is_ident(doc_keyword.as_str()) {
705 self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
706 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
714 fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
715 match self.tcx.hir().find(hir_id).and_then(|node| match node {
716 hir::Node::Item(item) => Some(&item.kind),
719 Some(ItemKind::Impl(ref i)) => {
720 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
721 || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
722 bare_fn_ty.decl.inputs.len() == 1
727 self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
732 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
739 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
741 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
742 /// if there are conflicting attributes for one item.
744 /// `specified_inline` is used to keep track of whether we have
745 /// already seen an inlining attribute for this item.
746 /// If so, `specified_inline` holds the value and the span of
747 /// the first `inline`/`no_inline` attribute.
751 meta: &NestedMetaItem,
754 specified_inline: &mut Option<(bool, Span)>,
756 if target == Target::Use || target == Target::ExternCrate {
757 let do_inline = meta.name_or_empty() == sym::inline;
758 if let Some((prev_inline, prev_span)) = *specified_inline {
759 if do_inline != prev_inline {
760 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
761 spans.push_span_label(prev_span, fluent::passes::doc_inline_conflict_first);
762 spans.push_span_label(meta.span(), fluent::passes::doc_inline_conflict_second);
763 self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
768 *specified_inline = Some((do_inline, meta.span()));
772 self.tcx.emit_spanned_lint(
773 INVALID_DOC_ATTRIBUTES,
776 errors::DocInlineOnlyUse {
777 attr_span: meta.span(),
778 item_span: (attr.style == AttrStyle::Outer)
779 .then(|| self.tcx.hir().span(hir_id)),
786 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
787 fn check_attr_not_crate_level(
789 meta: &NestedMetaItem,
793 if CRATE_HIR_ID == hir_id {
794 self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
800 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
801 fn check_attr_crate_level(
804 meta: &NestedMetaItem,
807 if hir_id != CRATE_HIR_ID {
808 self.tcx.struct_span_lint_hir(INVALID_DOC_ATTRIBUTES, hir_id, meta.span(), |lint| {
809 let mut err = lint.build(fluent::passes::attr_crate_level);
810 if attr.style == AttrStyle::Outer
811 && self.tcx.hir().get_parent_item(hir_id) == CRATE_DEF_ID
813 if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
815 err.span_suggestion_verbose(
817 fluent::passes::suggestion,
819 Applicability::MaybeIncorrect,
822 err.span_help(attr.span, fluent::passes::help);
825 err.note(fluent::passes::note).emit();
832 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
834 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
835 let mut is_valid = true;
836 if let Some(metas) = meta.meta_item_list() {
837 for i_meta in metas {
838 match i_meta.name_or_empty() {
839 sym::attr | sym::no_crate_inject => {}
841 self.tcx.emit_spanned_lint(
842 INVALID_DOC_ATTRIBUTES,
845 errors::DocTestUnknown {
846 path: rustc_ast_pretty::pprust::path_to_string(
847 &i_meta.meta_item().unwrap().path,
856 self.tcx.emit_spanned_lint(
857 INVALID_DOC_ATTRIBUTES,
860 errors::DocTestTakesList,
867 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
869 /// `specified_inline` should be initialized to `None` and kept for the scope
870 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
872 /// [`check_doc_inline`]: Self::check_doc_inline
878 specified_inline: &mut Option<(bool, Span)>,
879 aliases: &mut FxHashMap<String, Span>,
881 let mut is_valid = true;
883 if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
885 if let Some(i_meta) = meta.meta_item() {
886 match i_meta.name_or_empty() {
888 if !self.check_attr_not_crate_level(meta, hir_id, "alias")
889 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
895 if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
896 || !self.check_doc_keyword(meta, hir_id) =>
902 if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
903 || !self.check_doc_fake_variadic(meta, hir_id) =>
908 sym::html_favicon_url
910 | sym::html_playground_url
911 | sym::issue_tracker_base_url
913 | sym::html_no_source
915 if !self.check_attr_crate_level(attr, meta, hir_id) =>
920 sym::inline | sym::no_inline
921 if !self.check_doc_inline(
932 // no_default_passes: deprecated
933 // passes: deprecated
934 // plugins: removed, but rustdoc warns about it itself
939 | sym::html_favicon_url
941 | sym::html_no_source
942 | sym::html_playground_url
945 | sym::issue_tracker_base_url
948 | sym::no_default_passes
953 | sym::fake_variadic => {}
956 if !self.check_test_attr(meta, hir_id) {
962 if !self.tcx.features().rustdoc_internals {
963 self.tcx.emit_spanned_lint(
964 INVALID_DOC_ATTRIBUTES,
967 errors::DocPrimitive,
973 let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
974 if i_meta.has_name(sym::spotlight) {
975 self.tcx.emit_spanned_lint(
976 INVALID_DOC_ATTRIBUTES,
979 errors::DocTestUnknownSpotlight {
984 } else if i_meta.has_name(sym::include) &&
985 let Some(value) = i_meta.value_str() {
986 let applicability = if list.len() == 1 {
987 Applicability::MachineApplicable
989 Applicability::MaybeIncorrect
991 // If there are multiple attributes, the suggestion would suggest
992 // deleting all of them, which is incorrect.
993 self.tcx.emit_spanned_lint(
994 INVALID_DOC_ATTRIBUTES,
997 errors::DocTestUnknownInclude {
999 value: value.to_string(),
1000 inner: (attr.style == AttrStyle::Inner)
1003 sugg: (attr.meta().unwrap().span, applicability),
1007 self.tcx.emit_spanned_lint(
1008 INVALID_DOC_ATTRIBUTES,
1011 errors::DocTestUnknownAny { path }
1018 self.tcx.emit_spanned_lint(
1019 INVALID_DOC_ATTRIBUTES,
1032 /// Warns against some misuses of `#[pass_by_value]`
1033 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1035 Target::Struct | Target::Enum | Target::TyAlias => true,
1037 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1043 fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1045 Target::Method(MethodKind::Inherent) => true,
1047 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1053 fn check_has_incoherent_inherent_impls(
1060 Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1066 .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1072 /// Warns against some misuses of `#[must_use]`
1073 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1074 let node = self.tcx.hir().get(hir_id);
1075 if let Some(kind) = node.fn_kind() && let rustc_hir::IsAsync::Async = kind.asyncness() {
1076 self.tcx.emit_spanned_lint(
1080 errors::MustUseAsync { span }
1092 // `impl Trait` in return position can trip
1093 // `unused_must_use` if `Trait` is marked as
1097 let article = match target {
1102 | Target::Expression
1104 | Target::AssocConst
1105 | Target::AssocTy => "an",
1109 self.tcx.emit_spanned_lint(
1113 errors::MustUseNoEffect { article, target },
1117 // For now, its always valid
1121 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1122 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1124 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1126 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1132 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1133 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1135 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1136 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1137 // `#[cold]` attribute with just a lint, because we previously
1138 // erroneously allowed it and some crates used it accidentally, to to be compatible
1139 // with crates depending on them, we can't throw an error here.
1140 Target::Field | Target::Arm | Target::MacroDef => {
1141 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1144 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1145 // this, so only emit a warning.
1146 self.tcx.emit_spanned_lint(
1150 errors::Cold { span },
1156 /// Checks if `#[link]` is applied to an item other than a foreign module.
1157 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1158 if target == Target::ForeignMod
1159 && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1160 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1161 && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1166 self.tcx.emit_spanned_lint(
1170 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1174 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1175 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1177 Target::ForeignFn | Target::ForeignStatic => {}
1178 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1179 // `#[link_name]` attribute with just a lint, because we previously
1180 // erroneously allowed it and some crates used it accidentally, to to be compatible
1181 // with crates depending on them, we can't throw an error here.
1182 Target::Field | Target::Arm | Target::MacroDef => {
1183 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1186 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1187 // used this, so only emit a warning.
1188 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1189 if let Some(s) = attr.value_str() {
1190 self.tcx.emit_spanned_lint(
1194 errors::LinkName { span, attr_span, value: s.as_str() },
1197 self.tcx.emit_spanned_lint(
1201 errors::LinkName { span, attr_span, value: "..." },
1208 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1209 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1211 Target::ExternCrate => true,
1212 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1213 // `#[no_link]` attribute with just a lint, because we previously
1214 // erroneously allowed it and some crates used it accidentally, to to be compatible
1215 // with crates depending on them, we can't throw an error here.
1216 Target::Field | Target::Arm | Target::MacroDef => {
1217 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1221 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1227 fn is_impl_item(&self, hir_id: HirId) -> bool {
1228 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1231 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1232 fn check_export_name(
1240 Target::Static | Target::Fn => true,
1241 Target::Method(..) if self.is_impl_item(hir_id) => true,
1242 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1243 // `#[export_name]` attribute with just a lint, because we previously
1244 // erroneously allowed it and some crates used it accidentally, to to be compatible
1245 // with crates depending on them, we can't throw an error here.
1246 Target::Field | Target::Arm | Target::MacroDef => {
1247 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1251 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1257 fn check_rustc_layout_scalar_valid_range(
1263 if target != Target::Struct {
1264 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1265 attr_span: attr.span,
1271 let Some(list) = attr.meta_item_list() else {
1275 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
1278 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1283 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1284 fn check_rustc_legacy_const_generics(
1289 item: Option<ItemLike<'_>>,
1291 let is_function = matches!(target, Target::Fn);
1293 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1294 attr_span: attr.span,
1300 let Some(list) = attr.meta_item_list() else {
1301 // The attribute form is validated on AST.
1305 let Some(ItemLike::Item(Item {
1306 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1309 bug!("should be a function item");
1312 for param in generics.params {
1314 hir::GenericParamKind::Const { .. } => {}
1316 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1317 attr_span: attr.span,
1318 param_span: param.span,
1325 if list.len() != generics.params.len() {
1326 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1327 attr_span: attr.span,
1328 generics_span: generics.span,
1333 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1334 let mut invalid_args = vec![];
1336 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1337 if *val >= arg_count {
1338 let span = meta.span();
1339 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1341 arg_count: arg_count as usize,
1346 invalid_args.push(meta.span());
1350 if !invalid_args.is_empty() {
1351 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1358 /// Helper function for checking that the provided attribute is only applied to a function or
1360 fn check_applied_to_fn_or_method(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1361 let is_function = matches!(target, Target::Fn | Target::Method(..));
1363 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1364 attr_span: attr.span,
1373 /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1375 fn check_rustc_lint_query_instability(
1381 self.check_applied_to_fn_or_method(attr, span, target)
1384 /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1386 fn check_rustc_lint_diagnostics(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1387 self.check_applied_to_fn_or_method(attr, span, target)
1390 /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1391 fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1393 Target::Struct => true,
1395 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1401 /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1402 fn check_rustc_lint_opt_deny_field_access(
1409 Target::Field => true,
1413 .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1419 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1420 /// option is passed to the compiler.
1421 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1422 if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1425 self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1430 /// Checks if `#[link_section]` is applied to a function or static.
1431 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1433 Target::Static | Target::Fn | Target::Method(..) => {}
1434 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1435 // `#[link_section]` attribute with just a lint, because we previously
1436 // erroneously allowed it and some crates used it accidentally, to to be compatible
1437 // with crates depending on them, we can't throw an error here.
1438 Target::Field | Target::Arm | Target::MacroDef => {
1439 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1442 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1443 // crates used this, so only emit a warning.
1444 self.tcx.emit_spanned_lint(
1448 errors::LinkSection { span },
1454 /// Checks if `#[no_mangle]` is applied to a function or static.
1455 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1457 Target::Static | Target::Fn => {}
1458 Target::Method(..) if self.is_impl_item(hir_id) => {}
1459 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1460 // `#[no_mangle]` attribute with just a lint, because we previously
1461 // erroneously allowed it and some crates used it accidentally, to to be compatible
1462 // with crates depending on them, we can't throw an error here.
1463 Target::Field | Target::Arm | Target::MacroDef => {
1464 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1466 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1467 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1468 // otherwise the error seems odd
1469 Target::ForeignFn | Target::ForeignStatic => {
1470 let foreign_item_kind = match target {
1471 Target::ForeignFn => "function",
1472 Target::ForeignStatic => "static",
1473 _ => unreachable!(),
1475 self.tcx.emit_spanned_lint(
1479 errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1483 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1484 // crates used this, so only emit a warning.
1485 self.tcx.emit_spanned_lint(
1489 errors::NoMangle { span },
1495 /// Checks if the `#[repr]` attributes on `item` are valid.
1498 attrs: &[Attribute],
1501 item: Option<ItemLike<'_>>,
1504 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1507 // #[repr(bar, align(8))]
1509 let hints: Vec<_> = attrs
1511 .filter(|attr| attr.has_name(sym::repr))
1512 .filter_map(|attr| attr.meta_item_list())
1516 let mut int_reprs = 0;
1517 let mut is_c = false;
1518 let mut is_simd = false;
1519 let mut is_transparent = false;
1521 for hint in &hints {
1522 if !hint.is_meta_item() {
1523 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1527 let (article, allowed_targets) = match hint.name_or_empty() {
1531 Target::Struct | Target::Union | Target::Enum => continue,
1532 _ => ("a", "struct, enum, or union"),
1536 if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1538 &self.tcx.sess.parse_sess,
1541 "`repr(align)` attributes on functions are unstable",
1547 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1548 _ => ("a", "struct, enum, function, or union"),
1552 if target != Target::Struct && target != Target::Union {
1553 ("a", "struct or union")
1560 if target != Target::Struct {
1566 sym::transparent => {
1567 is_transparent = true;
1569 Target::Struct | Target::Union | Target::Enum => continue,
1570 _ => ("a", "struct, enum, or union"),
1586 if target != Target::Enum {
1597 "unrecognized representation hint"
1610 &format!("attribute should be applied to {article} {allowed_targets}")
1612 .span_label(span, &format!("not {article} {allowed_targets}"))
1616 // Just point at all repr hints if there are any incompatibilities.
1617 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1618 let hint_spans = hints.iter().map(|hint| hint.span());
1620 // Error on repr(transparent, <anything else>).
1621 if is_transparent && hints.len() > 1 {
1622 let hint_spans: Vec<_> = hint_spans.clone().collect();
1627 "transparent {} cannot have other repr hints",
1632 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1634 || (is_simd && is_c)
1637 && item.map_or(false, |item| {
1638 if let ItemLike::Item(item) = item {
1639 return is_c_like_enum(item);
1644 self.tcx.emit_spanned_lint(
1645 CONFLICTING_REPR_HINTS,
1647 hint_spans.collect::<Vec<Span>>(),
1648 errors::ReprConflicting,
1653 fn check_used(&self, attrs: &[Attribute], target: Target) {
1654 let mut used_linker_span = None;
1655 let mut used_compiler_span = None;
1656 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1657 if target != Target::Static {
1658 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1660 let inner = attr.meta_item_list();
1661 match inner.as_deref() {
1662 Some([item]) if item.has_name(sym::linker) => {
1663 if used_linker_span.is_none() {
1664 used_linker_span = Some(attr.span);
1667 Some([item]) if item.has_name(sym::compiler) => {
1668 if used_compiler_span.is_none() {
1669 used_compiler_span = Some(attr.span);
1673 // This error case is handled in rustc_typeck::collect.
1676 // Default case (compiler) when arg isn't defined.
1677 if used_compiler_span.is_none() {
1678 used_compiler_span = Some(attr.span);
1683 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1686 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1690 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1691 /// (Allows proc_macro functions)
1692 fn check_allow_internal_unstable(
1698 attrs: &[Attribute],
1700 debug!("Checking target: {:?}", target);
1704 if self.tcx.sess.is_proc_macro_attr(attr) {
1705 debug!("Is proc macro attr");
1709 debug!("Is not proc macro attr");
1712 Target::MacroDef => true,
1713 // FIXME(#80564): We permit struct fields and match arms to have an
1714 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1715 // erroneously allowed it and some crates used it accidentally, to to be compatible
1716 // with crates depending on them, we can't throw an error here.
1717 Target::Field | Target::Arm => {
1718 self.inline_attr_str_error_without_macro_def(
1721 "allow_internal_unstable",
1728 .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1734 /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1735 fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1739 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1744 let Some(hints) = attr.meta_item_list() else {
1745 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1749 let hint = match hints.len() {
1752 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1757 let Some(meta_item) = hint.meta_item() else {
1758 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1762 let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1763 (sym::natvis_file, Some(value)) => value,
1764 (sym::gdb_script_file, Some(value)) => value,
1766 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1772 match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1780 match std::fs::File::open(&file) {
1787 &format!("couldn't read {}: {}", file.display(), err),
1795 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1796 /// (Allows proc_macro functions)
1797 fn check_rustc_allow_const_fn_unstable(
1805 Target::Fn | Target::Method(_)
1806 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id).to_def_id()) =>
1810 // FIXME(#80564): We permit struct fields and match arms to have an
1811 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1812 // erroneously allowed it and some crates used it accidentally, to to be compatible
1813 // with crates depending on them, we can't throw an error here.
1814 Target::Field | Target::Arm | Target::MacroDef => {
1815 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1821 .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
1827 fn check_rustc_std_internal_symbol(
1834 Target::Fn | Target::Static => true,
1838 .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
1844 /// `#[const_trait]` only applies to traits.
1845 fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1847 Target::Trait => true,
1849 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1855 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1857 Target::Expression => {
1858 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
1865 fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1867 Target::ForeignFn => true,
1869 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
1875 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
1877 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
1878 self.tcx.emit_spanned_lint(
1889 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1890 let name = attr.name_or_empty();
1892 Target::ExternCrate | Target::Mod => {}
1894 self.tcx.emit_spanned_lint(
1898 errors::MacroUse { name },
1904 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1905 if target != Target::MacroDef {
1906 self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
1910 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1911 if target != Target::Fn {
1912 self.tcx.emit_spanned_lint(
1916 errors::PluginRegistrar,
1921 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
1922 // Warn on useless empty attributes.
1923 let note = if matches!(
1924 attr.name_or_empty(),
1933 | sym::target_feature
1934 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
1936 errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
1938 attr.name_or_empty(),
1939 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
1940 ) && let Some(meta) = attr.meta_item_list()
1942 && let Some(item) = meta[0].meta_item()
1943 && let MetaItemKind::NameValue(_) = &item.kind
1944 && item.path == sym::reason
1946 errors::UnusedNote::NoLints { name: attr.name_or_empty() }
1947 } else if attr.name_or_empty() == sym::default_method_body_is_const {
1948 errors::UnusedNote::DefaultMethodBodyConst
1953 self.tcx.emit_spanned_lint(
1957 errors::Unused { attr_span: attr.span, note },
1962 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1963 type NestedFilter = nested_filter::OnlyBodies;
1965 fn nested_visit_map(&mut self) -> Self::Map {
1969 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1970 // Historically we've run more checks on non-exported than exported macros,
1971 // so this lets us continue to run them while maintaining backwards compatibility.
1972 // In the long run, the checks should be harmonized.
1973 if let ItemKind::Macro(ref macro_def, _) = item.kind {
1974 let def_id = item.def_id.to_def_id();
1975 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
1976 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1980 let target = Target::from_item(item);
1981 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1982 intravisit::walk_item(self, item)
1985 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1986 let target = Target::from_generic_param(generic_param);
1987 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1988 intravisit::walk_generic_param(self, generic_param)
1991 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1992 let target = Target::from_trait_item(trait_item);
1993 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1994 intravisit::walk_trait_item(self, trait_item)
1997 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1998 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1999 intravisit::walk_field_def(self, struct_field);
2002 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2003 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2004 intravisit::walk_arm(self, arm);
2007 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2008 let target = Target::from_foreign_item(f_item);
2009 self.check_attributes(
2013 Some(ItemLike::ForeignItem(f_item)),
2015 intravisit::walk_foreign_item(self, f_item)
2018 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2019 let target = target_from_impl_item(self.tcx, impl_item);
2020 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2021 intravisit::walk_impl_item(self, impl_item)
2024 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2025 // When checking statements ignore expressions, they will be checked later.
2026 if let hir::StmtKind::Local(ref l) = stmt.kind {
2027 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2029 intravisit::walk_stmt(self, stmt)
2032 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2033 let target = match expr.kind {
2034 hir::ExprKind::Closure { .. } => Target::Closure,
2035 _ => Target::Expression,
2038 self.check_attributes(expr.hir_id, expr.span, target, None);
2039 intravisit::walk_expr(self, expr)
2044 variant: &'tcx hir::Variant<'tcx>,
2045 generics: &'tcx hir::Generics<'tcx>,
2048 self.check_attributes(variant.id, variant.span, Target::Variant, None);
2049 intravisit::walk_variant(self, variant, generics, item_id)
2052 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2053 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2055 intravisit::walk_param(self, param);
2059 fn is_c_like_enum(item: &Item<'_>) -> bool {
2060 if let ItemKind::Enum(ref def, _) = item.kind {
2061 for variant in def.variants {
2062 match variant.data {
2063 hir::VariantData::Unit(..) => { /* continue */ }
2073 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2075 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2076 // Check for builtin attributes at the crate level
2077 // which were unsuccessfully resolved due to cannot determine
2078 // resolution for the attribute macro error.
2079 const ATTRS_TO_CHECK: &[Symbol] = &[
2083 sym::automatically_derived,
2089 sym::global_allocator,
2094 // This function should only be called with crate attributes
2095 // which are inner attributes always but lets check to make sure
2096 if attr.style == AttrStyle::Inner {
2097 for attr_to_check in ATTRS_TO_CHECK {
2098 if attr.has_name(*attr_to_check) {
2099 let mut err = tcx.sess.struct_span_err(
2102 "`{}` attribute cannot be used at crate level",
2103 attr_to_check.to_ident_string()
2106 // Only emit an error with a suggestion if we can create a
2107 // string out of the attribute span
2108 if let Ok(src) = tcx.sess.source_map().span_to_snippet(attr.span) {
2109 let replacement = src.replace("#!", "#");
2110 err.span_suggestion_verbose(
2112 "perhaps you meant to use an outer attribute",
2114 rustc_errors::Applicability::MachineApplicable,
2124 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2125 let attrs = tcx.hir().attrs(item.hir_id());
2128 if attr.has_name(sym::inline) {
2129 tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2134 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2135 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
2136 tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2137 if module_def_id.is_top_level_module() {
2138 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2139 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2143 pub(crate) fn provide(providers: &mut Providers) {
2144 *providers = Providers { check_mod_attrs, ..*providers };
2147 fn check_duplicates(
2151 duplicates: AttributeDuplicates,
2152 seen: &mut FxHashMap<Symbol, Span>,
2154 use AttributeDuplicates::*;
2155 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2160 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2161 match seen.entry(attr.name_or_empty()) {
2162 Entry::Occupied(mut entry) => {
2163 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2164 let to_remove = entry.insert(attr.span);
2165 (to_remove, attr.span)
2167 (attr.span, *entry.get())
2169 tcx.emit_spanned_lint(
2173 errors::UnusedDuplicate {
2178 FutureWarnFollowing | FutureWarnPreceding
2184 Entry::Vacant(entry) => {
2185 entry.insert(attr.span);
2189 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2190 Entry::Occupied(mut entry) => {
2191 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2192 let to_remove = entry.insert(attr.span);
2193 (to_remove, attr.span)
2195 (attr.span, *entry.get())
2197 tcx.sess.emit_err(errors::UnusedMultiple {
2200 name: attr.name_or_empty(),
2203 Entry::Vacant(entry) => {
2204 entry.insert(attr.span);