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::middle::resolve_lifetime::ObjectLifetimeDefault;
20 use rustc_middle::ty::query::Providers;
21 use rustc_middle::ty::TyCtxt;
22 use rustc_session::lint::builtin::{
23 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
25 use rustc_session::parse::feature_err;
26 use rustc_span::symbol::{kw, sym, Symbol};
27 use rustc_span::{Span, DUMMY_SP};
28 use rustc_target::spec::abi::Abi;
29 use std::collections::hash_map::Entry;
31 pub(crate) fn target_from_impl_item<'tcx>(
33 impl_item: &hir::ImplItem<'_>,
35 match impl_item.kind {
36 hir::ImplItemKind::Const(..) => Target::AssocConst,
37 hir::ImplItemKind::Fn(..) => {
38 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id());
39 let containing_item = tcx.hir().expect_item(parent_hir_id);
40 let containing_impl_is_for_trait = match &containing_item.kind {
41 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
42 _ => bug!("parent of an ImplItem must be an Impl"),
44 if containing_impl_is_for_trait {
45 Target::Method(MethodKind::Trait { body: true })
47 Target::Method(MethodKind::Inherent)
50 hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
54 #[derive(Clone, Copy)]
56 Item(&'tcx Item<'tcx>),
60 struct CheckAttrVisitor<'tcx> {
64 impl CheckAttrVisitor<'_> {
65 /// Checks any attribute.
71 item: Option<ItemLike<'_>>,
73 let mut doc_aliases = FxHashMap::default();
74 let mut is_valid = true;
75 let mut specified_inline = None;
76 let mut seen = FxHashMap::default();
77 let attrs = self.tcx.hir().attrs(hir_id);
79 let attr_is_valid = match attr.name_or_empty() {
80 sym::inline => self.check_inline(hir_id, attr, span, target),
81 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
82 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
83 sym::marker => self.check_marker(hir_id, attr, span, target),
84 sym::rustc_must_implement_one_of => {
85 self.check_rustc_must_implement_one_of(attr, span, target)
87 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
88 sym::thread_local => self.check_thread_local(attr, span, target),
89 sym::track_caller => {
90 self.check_track_caller(hir_id, attr.span, attrs, span, target)
92 sym::doc => self.check_doc_attrs(
96 &mut specified_inline,
99 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
100 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
101 sym::rustc_layout_scalar_valid_range_start
102 | sym::rustc_layout_scalar_valid_range_end => {
103 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
105 sym::allow_internal_unstable => {
106 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
108 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
109 sym::rustc_allow_const_fn_unstable => {
110 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
112 sym::rustc_std_internal_symbol => {
113 self.check_rustc_std_internal_symbol(&attr, span, target)
115 sym::naked => self.check_naked(hir_id, attr, span, target),
116 sym::rustc_legacy_const_generics => {
117 self.check_rustc_legacy_const_generics(&attr, span, target, item)
119 sym::rustc_lint_query_instability => {
120 self.check_rustc_lint_query_instability(&attr, span, target)
122 sym::rustc_lint_diagnostics => {
123 self.check_rustc_lint_diagnostics(&attr, span, target)
125 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
126 sym::rustc_lint_opt_deny_field_access => {
127 self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
131 | sym::rustc_if_this_changed
132 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
133 sym::cmse_nonsecure_entry => self.check_cmse_nonsecure_entry(attr, span, target),
134 sym::const_trait => self.check_const_trait(attr, span, target),
135 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
136 sym::must_use => self.check_must_use(hir_id, &attr, span, target),
137 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
138 sym::rustc_allow_incoherent_impl => {
139 self.check_allow_incoherent_impl(&attr, span, target)
141 sym::rustc_has_incoherent_inherent_impls => {
142 self.check_has_incoherent_inherent_impls(&attr, span, target)
144 sym::rustc_const_unstable
145 | sym::rustc_const_stable
148 | sym::rustc_allowed_through_unstable_modules
149 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
150 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
153 is_valid &= attr_is_valid;
156 match attr.name_or_empty() {
157 sym::cold => self.check_cold(hir_id, attr, span, target),
158 sym::link => self.check_link(hir_id, attr, span, target),
159 sym::link_name => self.check_link_name(hir_id, attr, span, target),
160 sym::link_section => self.check_link_section(hir_id, attr, span, target),
161 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
162 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
163 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
164 sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]),
165 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
166 sym::macro_export => self.check_macro_export(hir_id, attr, target),
167 sym::ignore | sym::should_panic | sym::proc_macro_derive => {
168 self.check_generic_attr(hir_id, attr, target, &[Target::Fn])
170 sym::automatically_derived => {
171 self.check_generic_attr(hir_id, attr, target, &[Target::Impl])
173 sym::no_implicit_prelude => {
174 self.check_generic_attr(hir_id, attr, target, &[Target::Mod])
176 sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id),
180 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
182 if hir_id != CRATE_HIR_ID {
183 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
184 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
187 ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
191 errors::OuterCrateLevelAttr,
193 ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
197 errors::InnerCrateLevelAttr,
203 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
204 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
207 self.check_unused_attribute(hir_id, attr)
214 // FIXME(@lcnr): this doesn't belong here.
221 | Target::ForeignStatic
223 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
226 self.check_repr(attrs, span, target, item, hir_id);
227 self.check_used(attrs, target);
230 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
231 self.tcx.emit_spanned_lint(
235 errors::IgnoredAttrWithMacro { sym },
239 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
240 self.tcx.emit_spanned_lint(
244 errors::IgnoredAttr { sym },
248 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
249 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
253 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
254 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
255 self.tcx.emit_spanned_lint(
259 errors::IgnoredInlineAttrFnProto,
263 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
264 // just a lint, because we previously erroneously allowed it and some crates used it
265 // accidentally, to to be compatible with crates depending on them, we can't throw an
267 Target::AssocConst => {
268 self.tcx.emit_spanned_lint(
272 errors::IgnoredInlineAttrConstants,
276 // FIXME(#80564): Same for fields, arms, and macro defs
277 Target::Field | Target::Arm | Target::MacroDef => {
278 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
282 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
283 attr_span: attr.span,
291 /// Checks if a `#[no_coverage]` is applied directly to a function
292 fn check_no_coverage(
300 // no_coverage on function is fine
303 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
305 // function prototypes can't be covered
306 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
307 self.tcx.emit_spanned_lint(
311 errors::IgnoredNoCoverageFnProto,
316 Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
317 self.tcx.emit_spanned_lint(
321 errors::IgnoredNoCoveragePropagate,
326 Target::Expression | Target::Statement | Target::Arm => {
327 self.tcx.emit_spanned_lint(
331 errors::IgnoredNoCoverageFnDefn,
337 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
338 attr_span: attr.span,
346 fn check_generic_attr(
351 allowed_targets: &[Target],
353 if !allowed_targets.iter().any(|t| t == &target) {
354 let name = attr.name_or_empty();
355 let mut i = allowed_targets.iter();
357 let b = i.next().map_or_else(String::new, |t| t.to_string() + "s");
358 let supported_names = i.enumerate().fold(b, |mut b, (i, allowed_target)| {
359 if allowed_targets.len() > 2 && i == allowed_targets.len() - 2 {
360 b.push_str(", and ");
361 } else if allowed_targets.len() == 2 && i == allowed_targets.len() - 2 {
367 b.push_str(&(allowed_target.to_string() + "s"));
370 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
371 lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names))
377 /// Checks if `#[naked]` is applied to a function definition.
378 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
381 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
382 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
383 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
384 // erroneously allowed it and some crates used it accidentally, to to be compatible
385 // with crates depending on them, we can't throw an error here.
386 Target::Field | Target::Arm | Target::MacroDef => {
387 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
391 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
392 attr_span: attr.span,
400 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
401 fn check_cmse_nonsecure_entry(&self, attr: &Attribute, span: Span, target: Target) -> bool {
404 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
406 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
407 attr_span: attr.span,
415 /// Debugging aid for `object_lifetime_default` query.
416 fn check_object_lifetime_default(&self, hir_id: HirId) {
418 if let Some(generics) = tcx.hir().get_generics(tcx.hir().local_def_id(hir_id)) {
419 for p in generics.params {
420 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
421 let param_id = tcx.hir().local_def_id(p.hir_id);
422 let default = tcx.object_lifetime_default(param_id);
423 let repr = match default {
424 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
425 ObjectLifetimeDefault::Static => "'static".to_owned(),
426 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
427 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
429 tcx.sess.span_err(p.span, &repr);
434 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
435 fn check_track_caller(
444 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
445 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
448 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
449 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
450 // `#[track_caller]` attribute with just a lint, because we previously
451 // erroneously allowed it and some crates used it accidentally, to to be compatible
452 // with crates depending on them, we can't throw an error here.
453 Target::Field | Target::Arm | Target::MacroDef => {
455 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
462 .emit_err(errors::TrackedCallerWrongLocation { attr_span, defn_span: span });
468 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
469 fn check_non_exhaustive(
477 Target::Struct | Target::Enum | Target::Variant => true,
478 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
479 // `#[non_exhaustive]` attribute with just a lint, because we previously
480 // erroneously allowed it and some crates used it accidentally, to to be compatible
481 // with crates depending on them, we can't throw an error here.
482 Target::Field | Target::Arm | Target::MacroDef => {
483 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
487 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
488 attr_span: attr.span,
496 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
497 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
499 Target::Trait => true,
500 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
501 // `#[marker]` attribute with just a lint, because we previously
502 // erroneously allowed it and some crates used it accidentally, to to be compatible
503 // with crates depending on them, we can't throw an error here.
504 Target::Field | Target::Arm | Target::MacroDef => {
505 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
509 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
510 attr_span: attr.span,
518 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
519 fn check_rustc_must_implement_one_of(
526 Target::Trait => true,
528 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
529 attr_span: attr.span,
537 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
538 fn check_target_feature(
547 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
548 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
549 // crates used this, so only emit a warning.
550 Target::Statement => {
551 self.tcx.emit_spanned_lint(
555 errors::TargetFeatureOnStatement,
559 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
560 // `#[target_feature]` attribute with just a lint, because we previously
561 // erroneously allowed it and some crates used it accidentally, to to be compatible
562 // with crates depending on them, we can't throw an error here.
563 Target::Field | Target::Arm | Target::MacroDef => {
564 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
568 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
569 attr_span: attr.span,
577 /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
578 fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
580 Target::ForeignStatic | Target::Static => true,
582 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
583 attr_span: attr.span,
591 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
592 self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
595 fn check_doc_alias_value(
597 meta: &NestedMetaItem,
602 aliases: &mut FxHashMap<String, Span>,
605 let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
607 &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
608 if doc_alias == kw::Empty {
609 tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
613 let doc_alias_str = doc_alias.as_str();
614 if let Some(c) = doc_alias_str
616 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
618 tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
621 if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
622 tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
626 let span = meta.span();
627 if let Some(location) = match target {
629 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
630 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
631 if Target::from_item(containing_item) == Target::Impl {
632 Some("type alias in implementation block")
637 Target::AssocConst => {
638 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
639 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
640 // We can't link to trait impl's consts.
641 let err = "associated constant in trait implementation block";
642 match containing_item.kind {
643 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
647 // we check the validity of params elsewhere
648 Target::Param => return false,
654 | Target::Impl => Some(target.name()),
673 | Target::ForeignStatic
675 | Target::GenericParam(..)
678 | Target::ExprField => None,
680 tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
683 let item_name = self.tcx.hir().name(hir_id);
684 if item_name == doc_alias {
685 tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
688 if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
689 self.tcx.emit_spanned_lint(
693 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
701 meta: &NestedMetaItem,
704 aliases: &mut FxHashMap<String, Span>,
706 if let Some(values) = meta.meta_item_list() {
710 Some(l) => match l.kind {
711 LitKind::Str(s, _) => {
712 if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
719 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
724 self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
730 } else if let Some(doc_alias) = meta.value_str() {
731 self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
733 self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
738 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
739 let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
740 if doc_keyword == kw::Empty {
741 self.doc_attr_str_error(meta, "keyword");
744 match self.tcx.hir().find(hir_id).and_then(|node| match node {
745 hir::Node::Item(item) => Some(&item.kind),
748 Some(ItemKind::Mod(ref module)) => {
749 if !module.item_ids.is_empty() {
750 self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
755 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
759 if !rustc_lexer::is_ident(doc_keyword.as_str()) {
760 self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
761 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
769 fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
770 match self.tcx.hir().find(hir_id).and_then(|node| match node {
771 hir::Node::Item(item) => Some(&item.kind),
774 Some(ItemKind::Impl(ref i)) => {
775 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
776 || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
777 bare_fn_ty.decl.inputs.len() == 1
782 self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
787 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
794 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
796 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
797 /// if there are conflicting attributes for one item.
799 /// `specified_inline` is used to keep track of whether we have
800 /// already seen an inlining attribute for this item.
801 /// If so, `specified_inline` holds the value and the span of
802 /// the first `inline`/`no_inline` attribute.
806 meta: &NestedMetaItem,
809 specified_inline: &mut Option<(bool, Span)>,
811 if target == Target::Use || target == Target::ExternCrate {
812 let do_inline = meta.name_or_empty() == sym::inline;
813 if let Some((prev_inline, prev_span)) = *specified_inline {
814 if do_inline != prev_inline {
815 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
816 spans.push_span_label(prev_span, fluent::passes::doc_inline_conflict_first);
817 spans.push_span_label(meta.span(), fluent::passes::doc_inline_conflict_second);
818 self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
823 *specified_inline = Some((do_inline, meta.span()));
827 self.tcx.emit_spanned_lint(
828 INVALID_DOC_ATTRIBUTES,
831 errors::DocInlineOnlyUse {
832 attr_span: meta.span(),
833 item_span: (attr.style == AttrStyle::Outer)
834 .then(|| self.tcx.hir().span(hir_id)),
841 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
842 fn check_attr_not_crate_level(
844 meta: &NestedMetaItem,
848 if CRATE_HIR_ID == hir_id {
849 self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
855 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
856 fn check_attr_crate_level(
859 meta: &NestedMetaItem,
862 if hir_id != CRATE_HIR_ID {
863 self.tcx.struct_span_lint_hir(INVALID_DOC_ATTRIBUTES, hir_id, meta.span(), |lint| {
864 let mut err = lint.build(fluent::passes::attr_crate_level);
865 if attr.style == AttrStyle::Outer
866 && self.tcx.hir().get_parent_item(hir_id) == CRATE_DEF_ID
868 if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
870 err.span_suggestion_verbose(
872 fluent::passes::suggestion,
874 Applicability::MaybeIncorrect,
877 err.span_help(attr.span, fluent::passes::help);
880 err.note(fluent::passes::note).emit();
887 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
889 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
890 let mut is_valid = true;
891 if let Some(metas) = meta.meta_item_list() {
892 for i_meta in metas {
893 match i_meta.name_or_empty() {
894 sym::attr | sym::no_crate_inject => {}
896 self.tcx.emit_spanned_lint(
897 INVALID_DOC_ATTRIBUTES,
900 errors::DocTestUnknown {
901 path: rustc_ast_pretty::pprust::path_to_string(
902 &i_meta.meta_item().unwrap().path,
911 self.tcx.emit_spanned_lint(
912 INVALID_DOC_ATTRIBUTES,
915 errors::DocTestTakesList,
922 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
924 /// `specified_inline` should be initialized to `None` and kept for the scope
925 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
927 /// [`check_doc_inline`]: Self::check_doc_inline
933 specified_inline: &mut Option<(bool, Span)>,
934 aliases: &mut FxHashMap<String, Span>,
936 let mut is_valid = true;
938 if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
940 if let Some(i_meta) = meta.meta_item() {
941 match i_meta.name_or_empty() {
943 if !self.check_attr_not_crate_level(meta, hir_id, "alias")
944 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
950 if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
951 || !self.check_doc_keyword(meta, hir_id) =>
957 if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
958 || !self.check_doc_fake_variadic(meta, hir_id) =>
963 sym::html_favicon_url
965 | sym::html_playground_url
966 | sym::issue_tracker_base_url
968 | sym::html_no_source
970 if !self.check_attr_crate_level(attr, meta, hir_id) =>
975 sym::inline | sym::no_inline
976 if !self.check_doc_inline(
987 // no_default_passes: deprecated
988 // passes: deprecated
989 // plugins: removed, but rustdoc warns about it itself
994 | sym::html_favicon_url
996 | sym::html_no_source
997 | sym::html_playground_url
1000 | sym::issue_tracker_base_url
1003 | sym::no_default_passes
1005 | sym::notable_trait
1008 | sym::fake_variadic => {}
1011 if !self.check_test_attr(meta, hir_id) {
1017 if !self.tcx.features().rustdoc_internals {
1018 self.tcx.emit_spanned_lint(
1019 INVALID_DOC_ATTRIBUTES,
1022 errors::DocPrimitive,
1028 let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1029 if i_meta.has_name(sym::spotlight) {
1030 self.tcx.emit_spanned_lint(
1031 INVALID_DOC_ATTRIBUTES,
1034 errors::DocTestUnknownSpotlight {
1039 } else if i_meta.has_name(sym::include) &&
1040 let Some(value) = i_meta.value_str() {
1041 let applicability = if list.len() == 1 {
1042 Applicability::MachineApplicable
1044 Applicability::MaybeIncorrect
1046 // If there are multiple attributes, the suggestion would suggest
1047 // deleting all of them, which is incorrect.
1048 self.tcx.emit_spanned_lint(
1049 INVALID_DOC_ATTRIBUTES,
1052 errors::DocTestUnknownInclude {
1054 value: value.to_string(),
1055 inner: (attr.style == AttrStyle::Inner)
1058 sugg: (attr.meta().unwrap().span, applicability),
1062 self.tcx.emit_spanned_lint(
1063 INVALID_DOC_ATTRIBUTES,
1066 errors::DocTestUnknownAny { path }
1073 self.tcx.emit_spanned_lint(
1074 INVALID_DOC_ATTRIBUTES,
1087 /// Warns against some misuses of `#[pass_by_value]`
1088 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1090 Target::Struct | Target::Enum | Target::TyAlias => true,
1092 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1098 fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1100 Target::Method(MethodKind::Inherent) => true,
1102 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1108 fn check_has_incoherent_inherent_impls(
1115 Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1121 .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1127 /// Warns against some misuses of `#[must_use]`
1128 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1129 let node = self.tcx.hir().get(hir_id);
1130 if let Some(kind) = node.fn_kind() && let rustc_hir::IsAsync::Async = kind.asyncness() {
1131 self.tcx.emit_spanned_lint(
1135 errors::MustUseAsync { span }
1147 // `impl Trait` in return position can trip
1148 // `unused_must_use` if `Trait` is marked as
1152 let article = match target {
1157 | Target::Expression
1159 | Target::AssocConst
1160 | Target::AssocTy => "an",
1164 self.tcx.emit_spanned_lint(
1168 errors::MustUseNoEffect { article, target },
1172 // For now, its always valid
1176 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1177 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1179 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1181 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1187 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1188 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1190 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1191 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1192 // `#[cold]` attribute with just a lint, because we previously
1193 // erroneously allowed it and some crates used it accidentally, to to be compatible
1194 // with crates depending on them, we can't throw an error here.
1195 Target::Field | Target::Arm | Target::MacroDef => {
1196 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1199 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1200 // this, so only emit a warning.
1201 self.tcx.emit_spanned_lint(
1205 errors::Cold { span },
1211 /// Checks if `#[link]` is applied to an item other than a foreign module.
1212 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1213 if target == Target::ForeignMod
1214 && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1215 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1216 && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1221 self.tcx.emit_spanned_lint(
1225 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1229 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1230 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1232 Target::ForeignFn | Target::ForeignStatic => {}
1233 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1234 // `#[link_name]` attribute with just a lint, because we previously
1235 // erroneously allowed it and some crates used it accidentally, to to be compatible
1236 // with crates depending on them, we can't throw an error here.
1237 Target::Field | Target::Arm | Target::MacroDef => {
1238 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1241 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1242 // used this, so only emit a warning.
1243 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1244 if let Some(s) = attr.value_str() {
1245 self.tcx.emit_spanned_lint(
1249 errors::LinkName { span, attr_span, value: s.as_str() },
1252 self.tcx.emit_spanned_lint(
1256 errors::LinkName { span, attr_span, value: "..." },
1263 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1264 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1266 Target::ExternCrate => true,
1267 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1268 // `#[no_link]` attribute with just a lint, because we previously
1269 // erroneously allowed it and some crates used it accidentally, to to be compatible
1270 // with crates depending on them, we can't throw an error here.
1271 Target::Field | Target::Arm | Target::MacroDef => {
1272 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1276 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1282 fn is_impl_item(&self, hir_id: HirId) -> bool {
1283 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1286 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1287 fn check_export_name(
1295 Target::Static | Target::Fn => true,
1296 Target::Method(..) if self.is_impl_item(hir_id) => true,
1297 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1298 // `#[export_name]` attribute with just a lint, because we previously
1299 // erroneously allowed it and some crates used it accidentally, to to be compatible
1300 // with crates depending on them, we can't throw an error here.
1301 Target::Field | Target::Arm | Target::MacroDef => {
1302 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1306 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1312 fn check_rustc_layout_scalar_valid_range(
1318 if target != Target::Struct {
1319 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1320 attr_span: attr.span,
1326 let Some(list) = attr.meta_item_list() else {
1330 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
1333 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1338 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1339 fn check_rustc_legacy_const_generics(
1344 item: Option<ItemLike<'_>>,
1346 let is_function = matches!(target, Target::Fn);
1348 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1349 attr_span: attr.span,
1355 let Some(list) = attr.meta_item_list() else {
1356 // The attribute form is validated on AST.
1360 let Some(ItemLike::Item(Item {
1361 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1364 bug!("should be a function item");
1367 for param in generics.params {
1369 hir::GenericParamKind::Const { .. } => {}
1371 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1372 attr_span: attr.span,
1373 param_span: param.span,
1380 if list.len() != generics.params.len() {
1381 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1382 attr_span: attr.span,
1383 generics_span: generics.span,
1388 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1389 let mut invalid_args = vec![];
1391 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1392 if *val >= arg_count {
1393 let span = meta.span();
1394 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1396 arg_count: arg_count as usize,
1401 invalid_args.push(meta.span());
1405 if !invalid_args.is_empty() {
1406 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1413 /// Helper function for checking that the provided attribute is only applied to a function or
1415 fn check_applied_to_fn_or_method(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1416 let is_function = matches!(target, Target::Fn | Target::Method(..));
1418 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1419 attr_span: attr.span,
1428 /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1430 fn check_rustc_lint_query_instability(
1436 self.check_applied_to_fn_or_method(attr, span, target)
1439 /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1441 fn check_rustc_lint_diagnostics(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1442 self.check_applied_to_fn_or_method(attr, span, target)
1445 /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1446 fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1448 Target::Struct => true,
1450 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1456 /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1457 fn check_rustc_lint_opt_deny_field_access(
1464 Target::Field => true,
1468 .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1474 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1475 /// option is passed to the compiler.
1476 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1477 if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1480 self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1485 /// Checks if `#[link_section]` is applied to a function or static.
1486 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1488 Target::Static | Target::Fn | Target::Method(..) => {}
1489 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1490 // `#[link_section]` attribute with just a lint, because we previously
1491 // erroneously allowed it and some crates used it accidentally, to to be compatible
1492 // with crates depending on them, we can't throw an error here.
1493 Target::Field | Target::Arm | Target::MacroDef => {
1494 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1497 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1498 // crates used this, so only emit a warning.
1499 self.tcx.emit_spanned_lint(
1503 errors::LinkSection { span },
1509 /// Checks if `#[no_mangle]` is applied to a function or static.
1510 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1512 Target::Static | Target::Fn => {}
1513 Target::Method(..) if self.is_impl_item(hir_id) => {}
1514 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1515 // `#[no_mangle]` attribute with just a lint, because we previously
1516 // erroneously allowed it and some crates used it accidentally, to to be compatible
1517 // with crates depending on them, we can't throw an error here.
1518 Target::Field | Target::Arm | Target::MacroDef => {
1519 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1521 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1522 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1523 // otherwise the error seems odd
1524 Target::ForeignFn | Target::ForeignStatic => {
1525 let foreign_item_kind = match target {
1526 Target::ForeignFn => "function",
1527 Target::ForeignStatic => "static",
1528 _ => unreachable!(),
1530 self.tcx.emit_spanned_lint(
1534 errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1538 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1539 // crates used this, so only emit a warning.
1540 self.tcx.emit_spanned_lint(
1544 errors::NoMangle { span },
1550 /// Checks if the `#[repr]` attributes on `item` are valid.
1553 attrs: &[Attribute],
1556 item: Option<ItemLike<'_>>,
1559 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1562 // #[repr(bar, align(8))]
1564 let hints: Vec<_> = attrs
1566 .filter(|attr| attr.has_name(sym::repr))
1567 .filter_map(|attr| attr.meta_item_list())
1571 let mut int_reprs = 0;
1572 let mut is_c = false;
1573 let mut is_simd = false;
1574 let mut is_transparent = false;
1576 for hint in &hints {
1577 if !hint.is_meta_item() {
1578 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1582 let (article, allowed_targets) = match hint.name_or_empty() {
1586 Target::Struct | Target::Union | Target::Enum => continue,
1587 _ => ("a", "struct, enum, or union"),
1591 if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1593 &self.tcx.sess.parse_sess,
1596 "`repr(align)` attributes on functions are unstable",
1602 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1603 _ => ("a", "struct, enum, function, or union"),
1607 if target != Target::Struct && target != Target::Union {
1608 ("a", "struct or union")
1615 if target != Target::Struct {
1621 sym::transparent => {
1622 is_transparent = true;
1624 Target::Struct | Target::Union | Target::Enum => continue,
1625 _ => ("a", "struct, enum, or union"),
1641 if target != Target::Enum {
1652 "unrecognized representation hint"
1665 &format!("attribute should be applied to {article} {allowed_targets}")
1667 .span_label(span, &format!("not {article} {allowed_targets}"))
1671 // Just point at all repr hints if there are any incompatibilities.
1672 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1673 let hint_spans = hints.iter().map(|hint| hint.span());
1675 // Error on repr(transparent, <anything else>).
1676 if is_transparent && hints.len() > 1 {
1677 let hint_spans: Vec<_> = hint_spans.clone().collect();
1682 "transparent {} cannot have other repr hints",
1687 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1689 || (is_simd && is_c)
1692 && item.map_or(false, |item| {
1693 if let ItemLike::Item(item) = item {
1694 return is_c_like_enum(item);
1699 self.tcx.emit_spanned_lint(
1700 CONFLICTING_REPR_HINTS,
1702 hint_spans.collect::<Vec<Span>>(),
1703 errors::ReprConflicting,
1708 fn check_used(&self, attrs: &[Attribute], target: Target) {
1709 let mut used_linker_span = None;
1710 let mut used_compiler_span = None;
1711 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1712 if target != Target::Static {
1713 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1715 let inner = attr.meta_item_list();
1716 match inner.as_deref() {
1717 Some([item]) if item.has_name(sym::linker) => {
1718 if used_linker_span.is_none() {
1719 used_linker_span = Some(attr.span);
1722 Some([item]) if item.has_name(sym::compiler) => {
1723 if used_compiler_span.is_none() {
1724 used_compiler_span = Some(attr.span);
1728 // This error case is handled in rustc_typeck::collect.
1731 // Default case (compiler) when arg isn't defined.
1732 if used_compiler_span.is_none() {
1733 used_compiler_span = Some(attr.span);
1738 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1741 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1745 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1746 /// (Allows proc_macro functions)
1747 fn check_allow_internal_unstable(
1753 attrs: &[Attribute],
1755 debug!("Checking target: {:?}", target);
1759 if self.tcx.sess.is_proc_macro_attr(attr) {
1760 debug!("Is proc macro attr");
1764 debug!("Is not proc macro attr");
1767 Target::MacroDef => true,
1768 // FIXME(#80564): We permit struct fields and match arms to have an
1769 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1770 // erroneously allowed it and some crates used it accidentally, to to be compatible
1771 // with crates depending on them, we can't throw an error here.
1772 Target::Field | Target::Arm => {
1773 self.inline_attr_str_error_without_macro_def(
1776 "allow_internal_unstable",
1783 .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1789 /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1790 fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1794 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1799 let Some(hints) = attr.meta_item_list() else {
1800 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1804 let hint = match hints.len() {
1807 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1812 let Some(meta_item) = hint.meta_item() else {
1813 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1817 let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1818 (sym::natvis_file, Some(value)) => value,
1819 (sym::gdb_script_file, Some(value)) => value,
1821 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1827 match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1835 match std::fs::File::open(&file) {
1842 &format!("couldn't read {}: {}", file.display(), err),
1850 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1851 /// (Allows proc_macro functions)
1852 fn check_rustc_allow_const_fn_unstable(
1860 Target::Fn | Target::Method(_)
1861 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id).to_def_id()) =>
1865 // FIXME(#80564): We permit struct fields and match arms to have an
1866 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1867 // erroneously allowed it and some crates used it accidentally, to to be compatible
1868 // with crates depending on them, we can't throw an error here.
1869 Target::Field | Target::Arm | Target::MacroDef => {
1870 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1876 .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
1882 fn check_rustc_std_internal_symbol(
1889 Target::Fn | Target::Static => true,
1893 .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
1899 /// `#[const_trait]` only applies to traits.
1900 fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1902 Target::Trait => true,
1904 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1910 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1912 Target::Expression => {
1913 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
1920 fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1922 Target::ForeignFn | Target::ForeignStatic => true,
1924 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
1930 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
1932 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
1933 self.tcx.emit_spanned_lint(
1944 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1945 let name = attr.name_or_empty();
1947 Target::ExternCrate | Target::Mod => {}
1949 self.tcx.emit_spanned_lint(
1953 errors::MacroUse { name },
1959 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1960 if target != Target::MacroDef {
1961 self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
1965 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1966 if target != Target::Fn {
1967 self.tcx.emit_spanned_lint(
1971 errors::PluginRegistrar,
1976 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
1977 // Warn on useless empty attributes.
1978 let note = if matches!(
1979 attr.name_or_empty(),
1988 | sym::target_feature
1989 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
1991 errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
1993 attr.name_or_empty(),
1994 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
1995 ) && let Some(meta) = attr.meta_item_list()
1997 && let Some(item) = meta[0].meta_item()
1998 && let MetaItemKind::NameValue(_) = &item.kind
1999 && item.path == sym::reason
2001 errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2002 } else if attr.name_or_empty() == sym::default_method_body_is_const {
2003 errors::UnusedNote::DefaultMethodBodyConst
2008 self.tcx.emit_spanned_lint(
2012 errors::Unused { attr_span: attr.span, note },
2017 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2018 type NestedFilter = nested_filter::OnlyBodies;
2020 fn nested_visit_map(&mut self) -> Self::Map {
2024 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2025 // Historically we've run more checks on non-exported than exported macros,
2026 // so this lets us continue to run them while maintaining backwards compatibility.
2027 // In the long run, the checks should be harmonized.
2028 if let ItemKind::Macro(ref macro_def, _) = item.kind {
2029 let def_id = item.def_id.to_def_id();
2030 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
2031 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2035 let target = Target::from_item(item);
2036 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2037 intravisit::walk_item(self, item)
2040 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2041 let target = Target::from_generic_param(generic_param);
2042 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2043 intravisit::walk_generic_param(self, generic_param)
2046 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2047 let target = Target::from_trait_item(trait_item);
2048 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2049 intravisit::walk_trait_item(self, trait_item)
2052 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2053 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2054 intravisit::walk_field_def(self, struct_field);
2057 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2058 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2059 intravisit::walk_arm(self, arm);
2062 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2063 let target = Target::from_foreign_item(f_item);
2064 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2065 intravisit::walk_foreign_item(self, f_item)
2068 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2069 let target = target_from_impl_item(self.tcx, impl_item);
2070 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2071 intravisit::walk_impl_item(self, impl_item)
2074 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2075 // When checking statements ignore expressions, they will be checked later.
2076 if let hir::StmtKind::Local(ref l) = stmt.kind {
2077 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2079 intravisit::walk_stmt(self, stmt)
2082 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2083 let target = match expr.kind {
2084 hir::ExprKind::Closure { .. } => Target::Closure,
2085 _ => Target::Expression,
2088 self.check_attributes(expr.hir_id, expr.span, target, None);
2089 intravisit::walk_expr(self, expr)
2092 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2093 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2094 intravisit::walk_expr_field(self, field)
2097 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2098 self.check_attributes(variant.id, variant.span, Target::Variant, None);
2099 intravisit::walk_variant(self, variant)
2102 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2103 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2105 intravisit::walk_param(self, param);
2108 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2109 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2110 intravisit::walk_pat_field(self, field);
2114 fn is_c_like_enum(item: &Item<'_>) -> bool {
2115 if let ItemKind::Enum(ref def, _) = item.kind {
2116 for variant in def.variants {
2117 match variant.data {
2118 hir::VariantData::Unit(..) => { /* continue */ }
2128 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2130 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2131 // Check for builtin attributes at the crate level
2132 // which were unsuccessfully resolved due to cannot determine
2133 // resolution for the attribute macro error.
2134 const ATTRS_TO_CHECK: &[Symbol] = &[
2138 sym::automatically_derived,
2145 sym::global_allocator,
2150 // This function should only be called with crate attributes
2151 // which are inner attributes always but lets check to make sure
2152 if attr.style == AttrStyle::Inner {
2153 for attr_to_check in ATTRS_TO_CHECK {
2154 if attr.has_name(*attr_to_check) {
2155 let mut err = tcx.sess.struct_span_err(
2158 "`{}` attribute cannot be used at crate level",
2159 attr_to_check.to_ident_string()
2162 // Only emit an error with a suggestion if we can create a
2163 // string out of the attribute span
2164 if let Ok(src) = tcx.sess.source_map().span_to_snippet(attr.span) {
2165 let replacement = src.replace("#!", "#");
2166 err.span_suggestion_verbose(
2168 "perhaps you meant to use an outer attribute",
2170 rustc_errors::Applicability::MachineApplicable,
2180 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2181 let attrs = tcx.hir().attrs(item.hir_id());
2184 if attr.has_name(sym::inline) {
2185 tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2190 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2191 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
2192 tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2193 if module_def_id.is_top_level_module() {
2194 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2195 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2199 pub(crate) fn provide(providers: &mut Providers) {
2200 *providers = Providers { check_mod_attrs, ..*providers };
2203 fn check_duplicates(
2207 duplicates: AttributeDuplicates,
2208 seen: &mut FxHashMap<Symbol, Span>,
2210 use AttributeDuplicates::*;
2211 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2216 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2217 match seen.entry(attr.name_or_empty()) {
2218 Entry::Occupied(mut entry) => {
2219 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2220 let to_remove = entry.insert(attr.span);
2221 (to_remove, attr.span)
2223 (attr.span, *entry.get())
2225 tcx.emit_spanned_lint(
2229 errors::UnusedDuplicate {
2234 FutureWarnFollowing | FutureWarnPreceding
2240 Entry::Vacant(entry) => {
2241 entry.insert(attr.span);
2245 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2246 Entry::Occupied(mut entry) => {
2247 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2248 let to_remove = entry.insert(attr.span);
2249 (to_remove, attr.span)
2251 (attr.span, *entry.get())
2253 tcx.sess.emit_err(errors::UnusedMultiple {
2256 name: attr.name_or_empty(),
2259 Entry::Vacant(entry) => {
2260 entry.insert(attr.span);