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 self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr,
9 OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint,
11 use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_errors::{fluent, Applicability, MultiSpan};
14 use rustc_expand::base::resolve_path;
15 use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
17 use rustc_hir::def_id::LocalDefId;
18 use rustc_hir::intravisit::{self, Visitor};
20 self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID,
22 use rustc_hir::{MethodKind, Target};
23 use rustc_middle::hir::nested_filter;
24 use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
25 use rustc_middle::ty::query::Providers;
26 use rustc_middle::ty::TyCtxt;
27 use rustc_session::lint::builtin::{
28 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
30 use rustc_session::parse::feature_err;
31 use rustc_span::symbol::{kw, sym, Symbol};
32 use rustc_span::{Span, DUMMY_SP};
33 use rustc_target::spec::abi::Abi;
34 use std::collections::hash_map::Entry;
36 pub(crate) fn target_from_impl_item<'tcx>(
38 impl_item: &hir::ImplItem<'_>,
40 match impl_item.kind {
41 hir::ImplItemKind::Const(..) => Target::AssocConst,
42 hir::ImplItemKind::Fn(..) => {
43 let parent_def_id = tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
44 let containing_item = tcx.hir().expect_item(parent_def_id);
45 let containing_impl_is_for_trait = match &containing_item.kind {
46 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
47 _ => bug!("parent of an ImplItem must be an Impl"),
49 if containing_impl_is_for_trait {
50 Target::Method(MethodKind::Trait { body: true })
52 Target::Method(MethodKind::Inherent)
55 hir::ImplItemKind::Type(..) => Target::AssocTy,
59 #[derive(Clone, Copy)]
61 Item(&'tcx Item<'tcx>),
65 struct CheckAttrVisitor<'tcx> {
69 impl CheckAttrVisitor<'_> {
70 /// Checks any attribute.
76 item: Option<ItemLike<'_>>,
78 let mut doc_aliases = FxHashMap::default();
79 let mut is_valid = true;
80 let mut specified_inline = None;
81 let mut seen = FxHashMap::default();
82 let attrs = self.tcx.hir().attrs(hir_id);
84 let attr_is_valid = match attr.name_or_empty() {
85 sym::inline => self.check_inline(hir_id, attr, span, target),
86 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
87 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
88 sym::marker => self.check_marker(hir_id, attr, span, target),
89 sym::rustc_must_implement_one_of => {
90 self.check_rustc_must_implement_one_of(attr, span, target)
92 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
93 sym::thread_local => self.check_thread_local(attr, span, target),
94 sym::track_caller => {
95 self.check_track_caller(hir_id, attr.span, attrs, span, target)
97 sym::doc => self.check_doc_attrs(
101 &mut specified_inline,
104 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
105 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
106 sym::rustc_layout_scalar_valid_range_start
107 | sym::rustc_layout_scalar_valid_range_end => {
108 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
110 sym::allow_internal_unstable => {
111 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
113 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
114 sym::rustc_allow_const_fn_unstable => {
115 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
117 sym::rustc_std_internal_symbol => {
118 self.check_rustc_std_internal_symbol(&attr, span, target)
120 sym::naked => self.check_naked(hir_id, attr, span, target),
121 sym::rustc_legacy_const_generics => {
122 self.check_rustc_legacy_const_generics(hir_id, &attr, span, target, item)
124 sym::rustc_lint_query_instability => {
125 self.check_rustc_lint_query_instability(hir_id, &attr, span, target)
127 sym::rustc_lint_diagnostics => {
128 self.check_rustc_lint_diagnostics(hir_id, &attr, span, target)
130 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
131 sym::rustc_lint_opt_deny_field_access => {
132 self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
136 | sym::rustc_if_this_changed
137 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
138 sym::cmse_nonsecure_entry => {
139 self.check_cmse_nonsecure_entry(hir_id, attr, span, target)
141 sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target),
142 sym::const_trait => self.check_const_trait(attr, span, target),
143 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
144 sym::must_use => self.check_must_use(hir_id, &attr, target),
145 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
146 sym::rustc_allow_incoherent_impl => {
147 self.check_allow_incoherent_impl(&attr, span, target)
149 sym::rustc_has_incoherent_inherent_impls => {
150 self.check_has_incoherent_inherent_impls(&attr, span, target)
152 sym::rustc_const_unstable
153 | sym::rustc_const_stable
156 | sym::rustc_allowed_through_unstable_modules
157 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
158 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
161 is_valid &= attr_is_valid;
164 match attr.name_or_empty() {
165 sym::cold => self.check_cold(hir_id, attr, span, target),
166 sym::link => self.check_link(hir_id, attr, span, target),
167 sym::link_name => self.check_link_name(hir_id, attr, span, target),
168 sym::link_section => self.check_link_section(hir_id, attr, span, target),
169 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
170 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
171 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
172 sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod),
173 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
174 sym::macro_export => self.check_macro_export(hir_id, attr, target),
175 sym::ignore | sym::should_panic | sym::proc_macro_derive => {
176 self.check_generic_attr(hir_id, attr, target, Target::Fn)
178 sym::automatically_derived => {
179 self.check_generic_attr(hir_id, attr, target, Target::Impl)
181 sym::no_implicit_prelude => {
182 self.check_generic_attr(hir_id, attr, target, Target::Mod)
184 sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id),
188 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
190 if hir_id != CRATE_HIR_ID {
191 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
192 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
195 ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
199 errors::OuterCrateLevelAttr,
201 ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
205 errors::InnerCrateLevelAttr,
211 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
212 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
215 self.check_unused_attribute(hir_id, attr)
222 self.check_repr(attrs, span, target, item, hir_id);
223 self.check_used(attrs, target);
226 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
227 self.tcx.emit_spanned_lint(
231 errors::IgnoredAttrWithMacro { sym },
235 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
236 self.tcx.emit_spanned_lint(
240 errors::IgnoredAttr { sym },
244 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
245 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
249 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
250 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
251 self.tcx.emit_spanned_lint(
255 errors::IgnoredInlineAttrFnProto,
259 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
260 // just a lint, because we previously erroneously allowed it and some crates used it
261 // accidentally, to be compatible with crates depending on them, we can't throw an
263 Target::AssocConst => {
264 self.tcx.emit_spanned_lint(
268 errors::IgnoredInlineAttrConstants,
272 // FIXME(#80564): Same for fields, arms, and macro defs
273 Target::Field | Target::Arm | Target::MacroDef => {
274 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
278 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
279 attr_span: attr.span,
287 /// Checks if a `#[no_coverage]` is applied directly to a function
288 fn check_no_coverage(
296 // no_coverage on function is fine
299 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
301 // function prototypes can't be covered
302 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
303 self.tcx.emit_spanned_lint(
307 errors::IgnoredNoCoverageFnProto,
312 Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
313 self.tcx.emit_spanned_lint(
317 errors::IgnoredNoCoveragePropagate,
322 Target::Expression | Target::Statement | Target::Arm => {
323 self.tcx.emit_spanned_lint(
327 errors::IgnoredNoCoverageFnDefn,
333 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
334 attr_span: attr.span,
342 fn check_generic_attr(
347 allowed_target: Target,
349 if target != allowed_target {
350 self.tcx.emit_spanned_lint(
355 attr_name: attr.name_or_empty(),
356 target_name: allowed_target.name().replace(' ', "_"),
362 /// Checks if `#[naked]` is applied to a function definition.
363 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
366 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
367 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
368 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
369 // erroneously allowed it and some crates used it accidentally, to be compatible
370 // with crates depending on them, we can't throw an error here.
371 Target::Field | Target::Arm | Target::MacroDef => {
372 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
376 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
377 attr_span: attr.span,
379 on_crate: hir_id == CRATE_HIR_ID,
386 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
387 fn check_cmse_nonsecure_entry(
396 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
398 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
399 attr_span: attr.span,
401 on_crate: hir_id == CRATE_HIR_ID,
408 /// Debugging aid for `object_lifetime_default` query.
409 fn check_object_lifetime_default(&self, hir_id: HirId) {
411 if let Some(generics) = tcx.hir().get_generics(tcx.hir().local_def_id(hir_id)) {
412 for p in generics.params {
413 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
414 let default = tcx.object_lifetime_default(p.def_id);
415 let repr = match default {
416 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
417 ObjectLifetimeDefault::Static => "'static".to_owned(),
418 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
419 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
421 tcx.sess.emit_err(ObjectLifetimeErr { span: p.span, repr });
426 /// Checks if `#[collapse_debuginfo]` is applied to a macro.
427 fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) -> bool {
429 Target::MacroDef => true,
433 .emit_err(errors::CollapseDebuginfo { attr_span: attr.span, defn_span: span });
439 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
440 fn check_track_caller(
449 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
450 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
453 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
454 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
455 // `#[track_caller]` attribute with just a lint, because we previously
456 // erroneously allowed it and some crates used it accidentally, to be compatible
457 // with crates depending on them, we can't throw an error here.
458 Target::Field | Target::Arm | Target::MacroDef => {
460 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
465 self.tcx.sess.emit_err(errors::TrackedCallerWrongLocation {
468 on_crate: hir_id == CRATE_HIR_ID,
475 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
476 fn check_non_exhaustive(
484 Target::Struct | Target::Enum | Target::Variant => true,
485 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
486 // `#[non_exhaustive]` attribute with just a lint, because we previously
487 // erroneously allowed it and some crates used it accidentally, to be compatible
488 // with crates depending on them, we can't throw an error here.
489 Target::Field | Target::Arm | Target::MacroDef => {
490 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
494 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
495 attr_span: attr.span,
503 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
504 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
506 Target::Trait => true,
507 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
508 // `#[marker]` attribute with just a lint, because we previously
509 // erroneously allowed it and some crates used it accidentally, to be compatible
510 // with crates depending on them, we can't throw an error here.
511 Target::Field | Target::Arm | Target::MacroDef => {
512 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
516 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
517 attr_span: attr.span,
525 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
526 fn check_rustc_must_implement_one_of(
533 Target::Trait => true,
535 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
536 attr_span: attr.span,
544 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
545 fn check_target_feature(
554 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
555 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
556 // crates used this, so only emit a warning.
557 Target::Statement => {
558 self.tcx.emit_spanned_lint(
562 errors::TargetFeatureOnStatement,
566 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
567 // `#[target_feature]` attribute with just a lint, because we previously
568 // erroneously allowed it and some crates used it accidentally, to be compatible
569 // with crates depending on them, we can't throw an error here.
570 Target::Field | Target::Arm | Target::MacroDef => {
571 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
575 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
576 attr_span: attr.span,
578 on_crate: hir_id == CRATE_HIR_ID,
585 /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
586 fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
588 Target::ForeignStatic | Target::Static => true,
590 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
591 attr_span: attr.span,
599 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
600 self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
603 fn check_doc_alias_value(
605 meta: &NestedMetaItem,
610 aliases: &mut FxHashMap<String, Span>,
613 let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
615 &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
616 if doc_alias == kw::Empty {
617 tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
621 let doc_alias_str = doc_alias.as_str();
622 if let Some(c) = doc_alias_str
624 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
626 tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
629 if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
630 tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
634 let span = meta.span();
635 if let Some(location) = match target {
637 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
638 let containing_item = self.tcx.hir().expect_item(parent_def_id);
639 if Target::from_item(containing_item) == Target::Impl {
640 Some("type alias in implementation block")
645 Target::AssocConst => {
646 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
647 let containing_item = self.tcx.hir().expect_item(parent_def_id);
648 // We can't link to trait impl's consts.
649 let err = "associated constant in trait implementation block";
650 match containing_item.kind {
651 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
655 // we check the validity of params elsewhere
656 Target::Param => return false,
662 | Target::Impl => Some(target.name()),
672 | Target::ImplTraitPlaceholder
682 | Target::ForeignStatic
684 | Target::GenericParam(..)
687 | Target::ExprField => None,
689 tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
692 let item_name = self.tcx.hir().name(hir_id);
693 if item_name == doc_alias {
694 tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
697 if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
698 self.tcx.emit_spanned_lint(
702 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
710 meta: &NestedMetaItem,
713 aliases: &mut FxHashMap<String, Span>,
715 if let Some(values) = meta.meta_item_list() {
719 Some(l) => match l.kind {
720 LitKind::Str(s, _) => {
721 if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
728 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
733 self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
739 } else if let Some(doc_alias) = meta.value_str() {
740 self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
742 self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
747 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
748 let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
749 if doc_keyword == kw::Empty {
750 self.doc_attr_str_error(meta, "keyword");
753 match self.tcx.hir().find(hir_id).and_then(|node| match node {
754 hir::Node::Item(item) => Some(&item.kind),
757 Some(ItemKind::Mod(ref module)) => {
758 if !module.item_ids.is_empty() {
759 self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
764 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
768 if !rustc_lexer::is_ident(doc_keyword.as_str()) {
769 self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
770 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
778 fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
779 match self.tcx.hir().find(hir_id).and_then(|node| match node {
780 hir::Node::Item(item) => Some(&item.kind),
783 Some(ItemKind::Impl(ref i)) => {
784 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
785 || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
786 bare_fn_ty.decl.inputs.len() == 1
791 self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
796 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
803 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
805 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
806 /// if there are conflicting attributes for one item.
808 /// `specified_inline` is used to keep track of whether we have
809 /// already seen an inlining attribute for this item.
810 /// If so, `specified_inline` holds the value and the span of
811 /// the first `inline`/`no_inline` attribute.
815 meta: &NestedMetaItem,
818 specified_inline: &mut Option<(bool, Span)>,
820 if target == Target::Use || target == Target::ExternCrate {
821 let do_inline = meta.name_or_empty() == sym::inline;
822 if let Some((prev_inline, prev_span)) = *specified_inline {
823 if do_inline != prev_inline {
824 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
825 spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first);
826 spans.push_span_label(meta.span(), fluent::passes_doc_inline_conflict_second);
827 self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
832 *specified_inline = Some((do_inline, meta.span()));
836 self.tcx.emit_spanned_lint(
837 INVALID_DOC_ATTRIBUTES,
840 errors::DocInlineOnlyUse {
841 attr_span: meta.span(),
842 item_span: (attr.style == AttrStyle::Outer)
843 .then(|| self.tcx.hir().span(hir_id)),
850 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
851 fn check_attr_not_crate_level(
853 meta: &NestedMetaItem,
857 if CRATE_HIR_ID == hir_id {
858 self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
864 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
865 fn check_attr_crate_level(
868 meta: &NestedMetaItem,
871 if hir_id != CRATE_HIR_ID {
872 self.tcx.struct_span_lint_hir(
873 INVALID_DOC_ATTRIBUTES,
876 fluent::passes_attr_crate_level,
878 if attr.style == AttrStyle::Outer
879 && self.tcx.hir().get_parent_item(hir_id) == CRATE_OWNER_ID
881 if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
883 err.span_suggestion_verbose(
887 Applicability::MaybeIncorrect,
890 err.span_help(attr.span, fluent::help);
893 err.note(fluent::note);
902 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
904 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
905 let mut is_valid = true;
906 if let Some(metas) = meta.meta_item_list() {
907 for i_meta in metas {
908 match i_meta.name_or_empty() {
909 sym::attr | sym::no_crate_inject => {}
911 self.tcx.emit_spanned_lint(
912 INVALID_DOC_ATTRIBUTES,
915 errors::DocTestUnknown {
916 path: rustc_ast_pretty::pprust::path_to_string(
917 &i_meta.meta_item().unwrap().path,
926 self.tcx.emit_spanned_lint(
927 INVALID_DOC_ATTRIBUTES,
930 errors::DocTestTakesList,
937 /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes.
938 /// Returns `true` if valid.
939 fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
940 if meta.meta_item_list().is_some() {
943 self.tcx.emit_spanned_lint(
944 INVALID_DOC_ATTRIBUTES,
947 errors::DocCfgHideTakesList,
953 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
955 /// `specified_inline` should be initialized to `None` and kept for the scope
956 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
958 /// [`check_doc_inline`]: Self::check_doc_inline
964 specified_inline: &mut Option<(bool, Span)>,
965 aliases: &mut FxHashMap<String, Span>,
967 let mut is_valid = true;
969 if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
971 if let Some(i_meta) = meta.meta_item() {
972 match i_meta.name_or_empty() {
974 if !self.check_attr_not_crate_level(meta, hir_id, "alias")
975 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
981 if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
982 || !self.check_doc_keyword(meta, hir_id) =>
988 if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
989 || !self.check_doc_fake_variadic(meta, hir_id) =>
994 sym::html_favicon_url
996 | sym::html_playground_url
997 | sym::issue_tracker_base_url
999 | sym::html_no_source
1001 if !self.check_attr_crate_level(attr, meta, hir_id) =>
1007 if !self.check_attr_crate_level(attr, meta, hir_id)
1008 || !self.check_doc_cfg_hide(meta, hir_id) =>
1013 sym::inline | sym::no_inline
1014 if !self.check_doc_inline(
1025 // no_default_passes: deprecated
1026 // passes: deprecated
1027 // plugins: removed, but rustdoc warns about it itself
1032 | sym::html_favicon_url
1033 | sym::html_logo_url
1034 | sym::html_no_source
1035 | sym::html_playground_url
1036 | sym::html_root_url
1038 | sym::issue_tracker_base_url
1041 | sym::no_default_passes
1043 | sym::notable_trait
1046 | sym::fake_variadic => {}
1049 if !self.check_test_attr(meta, hir_id) {
1055 if !self.tcx.features().rustdoc_internals {
1056 self.tcx.emit_spanned_lint(
1057 INVALID_DOC_ATTRIBUTES,
1060 errors::DocPrimitive,
1066 let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1067 if i_meta.has_name(sym::spotlight) {
1068 self.tcx.emit_spanned_lint(
1069 INVALID_DOC_ATTRIBUTES,
1072 errors::DocTestUnknownSpotlight {
1077 } else if i_meta.has_name(sym::include) &&
1078 let Some(value) = i_meta.value_str() {
1079 let applicability = if list.len() == 1 {
1080 Applicability::MachineApplicable
1082 Applicability::MaybeIncorrect
1084 // If there are multiple attributes, the suggestion would suggest
1085 // deleting all of them, which is incorrect.
1086 self.tcx.emit_spanned_lint(
1087 INVALID_DOC_ATTRIBUTES,
1090 errors::DocTestUnknownInclude {
1092 value: value.to_string(),
1093 inner: (attr.style == AttrStyle::Inner)
1096 sugg: (attr.meta().unwrap().span, applicability),
1100 self.tcx.emit_spanned_lint(
1101 INVALID_DOC_ATTRIBUTES,
1104 errors::DocTestUnknownAny { path }
1111 self.tcx.emit_spanned_lint(
1112 INVALID_DOC_ATTRIBUTES,
1125 /// Warns against some misuses of `#[pass_by_value]`
1126 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1128 Target::Struct | Target::Enum | Target::TyAlias => true,
1130 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1136 fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1138 Target::Method(MethodKind::Inherent) => true,
1140 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1146 fn check_has_incoherent_inherent_impls(
1153 Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1159 .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1165 /// Warns against some misuses of `#[must_use]`
1166 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool {
1175 // `impl Trait` in return position can trip
1176 // `unused_must_use` if `Trait` is marked as
1180 let article = match target {
1185 | Target::Expression
1187 | Target::AssocConst
1188 | Target::AssocTy => "an",
1192 self.tcx.emit_spanned_lint(
1196 errors::MustUseNoEffect { article, target },
1200 // For now, its always valid
1204 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1205 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1207 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1209 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1215 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1216 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1218 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1219 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1220 // `#[cold]` attribute with just a lint, because we previously
1221 // erroneously allowed it and some crates used it accidentally, to be compatible
1222 // with crates depending on them, we can't throw an error here.
1223 Target::Field | Target::Arm | Target::MacroDef => {
1224 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1227 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1228 // this, so only emit a warning.
1229 self.tcx.emit_spanned_lint(
1233 errors::Cold { span, on_crate: hir_id == CRATE_HIR_ID },
1239 /// Checks if `#[link]` is applied to an item other than a foreign module.
1240 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1241 if target == Target::ForeignMod
1242 && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1243 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1244 && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1249 self.tcx.emit_spanned_lint(
1253 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1257 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1258 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1260 Target::ForeignFn | Target::ForeignStatic => {}
1261 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1262 // `#[link_name]` attribute with just a lint, because we previously
1263 // erroneously allowed it and some crates used it accidentally, to be compatible
1264 // with crates depending on them, we can't throw an error here.
1265 Target::Field | Target::Arm | Target::MacroDef => {
1266 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1269 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1270 // used this, so only emit a warning.
1271 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1272 if let Some(s) = attr.value_str() {
1273 self.tcx.emit_spanned_lint(
1277 errors::LinkName { span, attr_span, value: s.as_str() },
1280 self.tcx.emit_spanned_lint(
1284 errors::LinkName { span, attr_span, value: "..." },
1291 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1292 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1294 Target::ExternCrate => true,
1295 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1296 // `#[no_link]` attribute with just a lint, because we previously
1297 // erroneously allowed it and some crates used it accidentally, to be compatible
1298 // with crates depending on them, we can't throw an error here.
1299 Target::Field | Target::Arm | Target::MacroDef => {
1300 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1304 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1310 fn is_impl_item(&self, hir_id: HirId) -> bool {
1311 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1314 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1315 fn check_export_name(
1323 Target::Static | Target::Fn => true,
1324 Target::Method(..) if self.is_impl_item(hir_id) => true,
1325 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1326 // `#[export_name]` attribute with just a lint, because we previously
1327 // erroneously allowed it and some crates used it accidentally, to be compatible
1328 // with crates depending on them, we can't throw an error here.
1329 Target::Field | Target::Arm | Target::MacroDef => {
1330 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1334 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1340 fn check_rustc_layout_scalar_valid_range(
1346 if target != Target::Struct {
1347 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1348 attr_span: attr.span,
1354 let Some(list) = attr.meta_item_list() else {
1360 &[NestedMetaItem::Literal(MetaItemLit { kind: LitKind::Int(..), .. })]
1364 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1369 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1370 fn check_rustc_legacy_const_generics(
1376 item: Option<ItemLike<'_>>,
1378 let is_function = matches!(target, Target::Fn);
1380 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1381 attr_span: attr.span,
1383 on_crate: hir_id == CRATE_HIR_ID,
1388 let Some(list) = attr.meta_item_list() else {
1389 // The attribute form is validated on AST.
1393 let Some(ItemLike::Item(Item {
1394 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1397 bug!("should be a function item");
1400 for param in generics.params {
1402 hir::GenericParamKind::Const { .. } => {}
1404 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1405 attr_span: attr.span,
1406 param_span: param.span,
1413 if list.len() != generics.params.len() {
1414 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1415 attr_span: attr.span,
1416 generics_span: generics.span,
1421 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1422 let mut invalid_args = vec![];
1424 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1425 if *val >= arg_count {
1426 let span = meta.span();
1427 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1429 arg_count: arg_count as usize,
1434 invalid_args.push(meta.span());
1438 if !invalid_args.is_empty() {
1439 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1446 /// Helper function for checking that the provided attribute is only applied to a function or
1448 fn check_applied_to_fn_or_method(
1455 let is_function = matches!(target, Target::Fn | Target::Method(..));
1457 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1458 attr_span: attr.span,
1460 on_crate: hir_id == CRATE_HIR_ID,
1468 /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1470 fn check_rustc_lint_query_instability(
1477 self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1480 /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1482 fn check_rustc_lint_diagnostics(
1489 self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1492 /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1493 fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1495 Target::Struct => true,
1497 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1503 /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1504 fn check_rustc_lint_opt_deny_field_access(
1511 Target::Field => true,
1515 .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1521 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1522 /// option is passed to the compiler.
1523 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1524 if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1527 self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1532 /// Checks if `#[link_section]` is applied to a function or static.
1533 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1535 Target::Static | Target::Fn | Target::Method(..) => {}
1536 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1537 // `#[link_section]` attribute with just a lint, because we previously
1538 // erroneously allowed it and some crates used it accidentally, to be compatible
1539 // with crates depending on them, we can't throw an error here.
1540 Target::Field | Target::Arm | Target::MacroDef => {
1541 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1544 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1545 // crates used this, so only emit a warning.
1546 self.tcx.emit_spanned_lint(
1550 errors::LinkSection { span },
1556 /// Checks if `#[no_mangle]` is applied to a function or static.
1557 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1559 Target::Static | Target::Fn => {}
1560 Target::Method(..) if self.is_impl_item(hir_id) => {}
1561 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1562 // `#[no_mangle]` attribute with just a lint, because we previously
1563 // erroneously allowed it and some crates used it accidentally, to be compatible
1564 // with crates depending on them, we can't throw an error here.
1565 Target::Field | Target::Arm | Target::MacroDef => {
1566 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1568 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1569 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1570 // otherwise the error seems odd
1571 Target::ForeignFn | Target::ForeignStatic => {
1572 let foreign_item_kind = match target {
1573 Target::ForeignFn => "function",
1574 Target::ForeignStatic => "static",
1575 _ => unreachable!(),
1577 self.tcx.emit_spanned_lint(
1581 errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1585 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1586 // crates used this, so only emit a warning.
1587 self.tcx.emit_spanned_lint(
1591 errors::NoMangle { span },
1597 /// Checks if the `#[repr]` attributes on `item` are valid.
1600 attrs: &[Attribute],
1603 item: Option<ItemLike<'_>>,
1606 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1609 // #[repr(bar, align(8))]
1611 let hints: Vec<_> = attrs
1613 .filter(|attr| attr.has_name(sym::repr))
1614 .filter_map(|attr| attr.meta_item_list())
1618 let mut int_reprs = 0;
1619 let mut is_c = false;
1620 let mut is_simd = false;
1621 let mut is_transparent = false;
1623 for hint in &hints {
1624 if !hint.is_meta_item() {
1625 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1629 match hint.name_or_empty() {
1633 Target::Struct | Target::Union | Target::Enum => continue,
1635 self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1636 hint_span: hint.span(),
1643 if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1645 &self.tcx.sess.parse_sess,
1648 "`repr(align)` attributes on functions are unstable",
1654 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1656 self.tcx.sess.emit_err(AttrApplication::StructEnumFunctionUnion {
1657 hint_span: hint.span(),
1664 if target != Target::Struct && target != Target::Union {
1665 self.tcx.sess.emit_err(AttrApplication::StructUnion {
1666 hint_span: hint.span(),
1675 if target != Target::Struct {
1678 .emit_err(AttrApplication::Struct { hint_span: hint.span(), span });
1683 sym::transparent => {
1684 is_transparent = true;
1686 Target::Struct | Target::Union | Target::Enum => continue,
1688 self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1689 hint_span: hint.span(),
1708 if target != Target::Enum {
1711 .emit_err(AttrApplication::Enum { hint_span: hint.span(), span });
1717 self.tcx.sess.emit_err(UnrecognizedReprHint { span: hint.span() });
1723 // Just point at all repr hints if there are any incompatibilities.
1724 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1725 let hint_spans = hints.iter().map(|hint| hint.span());
1727 // Error on repr(transparent, <anything else>).
1728 if is_transparent && hints.len() > 1 {
1729 let hint_spans: Vec<_> = hint_spans.clone().collect();
1732 .emit_err(TransparentIncompatible { hint_spans, target: target.to_string() });
1734 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1736 || (is_simd && is_c)
1739 && item.map_or(false, |item| {
1740 if let ItemLike::Item(item) = item {
1741 return is_c_like_enum(item);
1746 self.tcx.emit_spanned_lint(
1747 CONFLICTING_REPR_HINTS,
1749 hint_spans.collect::<Vec<Span>>(),
1750 errors::ReprConflicting,
1755 fn check_used(&self, attrs: &[Attribute], target: Target) {
1756 let mut used_linker_span = None;
1757 let mut used_compiler_span = None;
1758 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1759 if target != Target::Static {
1760 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1762 let inner = attr.meta_item_list();
1763 match inner.as_deref() {
1764 Some([item]) if item.has_name(sym::linker) => {
1765 if used_linker_span.is_none() {
1766 used_linker_span = Some(attr.span);
1769 Some([item]) if item.has_name(sym::compiler) => {
1770 if used_compiler_span.is_none() {
1771 used_compiler_span = Some(attr.span);
1775 // This error case is handled in rustc_hir_analysis::collect.
1778 // Default case (compiler) when arg isn't defined.
1779 if used_compiler_span.is_none() {
1780 used_compiler_span = Some(attr.span);
1785 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1788 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1792 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1793 /// (Allows proc_macro functions)
1794 fn check_allow_internal_unstable(
1800 attrs: &[Attribute],
1802 debug!("Checking target: {:?}", target);
1806 if self.tcx.sess.is_proc_macro_attr(attr) {
1807 debug!("Is proc macro attr");
1811 debug!("Is not proc macro attr");
1814 Target::MacroDef => true,
1815 // FIXME(#80564): We permit struct fields and match arms to have an
1816 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1817 // erroneously allowed it and some crates used it accidentally, to be compatible
1818 // with crates depending on them, we can't throw an error here.
1819 Target::Field | Target::Arm => {
1820 self.inline_attr_str_error_without_macro_def(
1823 "allow_internal_unstable",
1830 .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1836 /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1837 fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1841 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1846 let Some(hints) = attr.meta_item_list() else {
1847 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1851 let hint = match hints.len() {
1854 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1859 let Some(meta_item) = hint.meta_item() else {
1860 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1864 let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1865 (sym::natvis_file, Some(value)) => value,
1866 (sym::gdb_script_file, Some(value)) => value,
1868 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1874 match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1882 match std::fs::File::open(&file) {
1885 self.tcx.sess.emit_err(DebugVisualizerUnreadable {
1886 span: meta_item.span,
1895 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1896 /// (Allows proc_macro functions)
1897 fn check_rustc_allow_const_fn_unstable(
1905 Target::Fn | Target::Method(_)
1906 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id).to_def_id()) =>
1910 // FIXME(#80564): We permit struct fields and match arms to have an
1911 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1912 // erroneously allowed it and some crates used it accidentally, to be compatible
1913 // with crates depending on them, we can't throw an error here.
1914 Target::Field | Target::Arm | Target::MacroDef => {
1915 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1921 .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
1927 fn check_rustc_std_internal_symbol(
1934 Target::Fn | Target::Static => true,
1938 .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
1944 /// `#[const_trait]` only applies to traits.
1945 fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1947 Target::Trait => true,
1949 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1955 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1957 Target::Expression => {
1958 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
1965 fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1967 Target::ForeignFn | Target::ForeignStatic => true,
1969 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
1975 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
1977 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
1978 self.tcx.emit_spanned_lint(
1989 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1990 let name = attr.name_or_empty();
1992 Target::ExternCrate | Target::Mod => {}
1994 self.tcx.emit_spanned_lint(
1998 errors::MacroUse { name },
2004 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2005 if target != Target::MacroDef {
2006 self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
2010 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2011 if target != Target::Fn {
2012 self.tcx.emit_spanned_lint(
2016 errors::PluginRegistrar,
2021 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
2022 // Warn on useless empty attributes.
2023 let note = if matches!(
2024 attr.name_or_empty(),
2033 | sym::target_feature
2034 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
2036 errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
2038 attr.name_or_empty(),
2039 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
2040 ) && let Some(meta) = attr.meta_item_list()
2042 && let Some(item) = meta[0].meta_item()
2043 && let MetaItemKind::NameValue(_) = &item.kind
2044 && item.path == sym::reason
2046 errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2047 } else if attr.name_or_empty() == sym::default_method_body_is_const {
2048 errors::UnusedNote::DefaultMethodBodyConst
2053 self.tcx.emit_spanned_lint(
2057 errors::Unused { attr_span: attr.span, note },
2062 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2063 type NestedFilter = nested_filter::OnlyBodies;
2065 fn nested_visit_map(&mut self) -> Self::Map {
2069 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2070 // Historically we've run more checks on non-exported than exported macros,
2071 // so this lets us continue to run them while maintaining backwards compatibility.
2072 // In the long run, the checks should be harmonized.
2073 if let ItemKind::Macro(ref macro_def, _) = item.kind {
2074 let def_id = item.owner_id.to_def_id();
2075 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
2076 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2080 let target = Target::from_item(item);
2081 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2082 intravisit::walk_item(self, item)
2085 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2086 let target = Target::from_generic_param(generic_param);
2087 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2088 intravisit::walk_generic_param(self, generic_param)
2091 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2092 let target = Target::from_trait_item(trait_item);
2093 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2094 intravisit::walk_trait_item(self, trait_item)
2097 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2098 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2099 intravisit::walk_field_def(self, struct_field);
2102 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2103 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2104 intravisit::walk_arm(self, arm);
2107 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2108 let target = Target::from_foreign_item(f_item);
2109 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2110 intravisit::walk_foreign_item(self, f_item)
2113 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2114 let target = target_from_impl_item(self.tcx, impl_item);
2115 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2116 intravisit::walk_impl_item(self, impl_item)
2119 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2120 // When checking statements ignore expressions, they will be checked later.
2121 if let hir::StmtKind::Local(ref l) = stmt.kind {
2122 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2124 intravisit::walk_stmt(self, stmt)
2127 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2128 let target = match expr.kind {
2129 hir::ExprKind::Closure { .. } => Target::Closure,
2130 _ => Target::Expression,
2133 self.check_attributes(expr.hir_id, expr.span, target, None);
2134 intravisit::walk_expr(self, expr)
2137 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2138 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2139 intravisit::walk_expr_field(self, field)
2142 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2143 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2144 intravisit::walk_variant(self, variant)
2147 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2148 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2150 intravisit::walk_param(self, param);
2153 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2154 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2155 intravisit::walk_pat_field(self, field);
2159 fn is_c_like_enum(item: &Item<'_>) -> bool {
2160 if let ItemKind::Enum(ref def, _) = item.kind {
2161 for variant in def.variants {
2162 match variant.data {
2163 hir::VariantData::Unit(..) => { /* continue */ }
2173 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2175 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2176 // Check for builtin attributes at the crate level
2177 // which were unsuccessfully resolved due to cannot determine
2178 // resolution for the attribute macro error.
2179 const ATTRS_TO_CHECK: &[Symbol] = &[
2183 sym::automatically_derived,
2190 sym::global_allocator,
2195 // This function should only be called with crate attributes
2196 // which are inner attributes always but lets check to make sure
2197 if attr.style == AttrStyle::Inner {
2198 for attr_to_check in ATTRS_TO_CHECK {
2199 if attr.has_name(*attr_to_check) {
2200 tcx.sess.emit_err(InvalidAttrAtCrateLevel {
2202 snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(),
2203 name: *attr_to_check,
2211 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2212 let attrs = tcx.hir().attrs(item.hir_id());
2215 if attr.has_name(sym::inline) {
2216 tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2221 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2222 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
2223 tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2224 if module_def_id.is_top_level_module() {
2225 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2226 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2230 pub(crate) fn provide(providers: &mut Providers) {
2231 *providers = Providers { check_mod_attrs, ..*providers };
2234 fn check_duplicates(
2238 duplicates: AttributeDuplicates,
2239 seen: &mut FxHashMap<Symbol, Span>,
2241 use AttributeDuplicates::*;
2242 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2247 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2248 match seen.entry(attr.name_or_empty()) {
2249 Entry::Occupied(mut entry) => {
2250 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2251 let to_remove = entry.insert(attr.span);
2252 (to_remove, attr.span)
2254 (attr.span, *entry.get())
2256 tcx.emit_spanned_lint(
2260 errors::UnusedDuplicate {
2265 FutureWarnFollowing | FutureWarnPreceding
2271 Entry::Vacant(entry) => {
2272 entry.insert(attr.span);
2276 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2277 Entry::Occupied(mut entry) => {
2278 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2279 let to_remove = entry.insert(attr.span);
2280 (to_remove, attr.span)
2282 (attr.span, *entry.get())
2284 tcx.sess.emit_err(errors::UnusedMultiple {
2287 name: attr.name_or_empty(),
2290 Entry::Vacant(entry) => {
2291 entry.insert(attr.span);