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, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_errors::{fluent, Applicability, IntoDiagnosticArg, 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;
15 use rustc_hir::intravisit::{self, Visitor};
17 self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID,
19 use rustc_hir::{MethodKind, Target, Unsafety};
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
22 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
23 use rustc_middle::ty::query::Providers;
24 use rustc_middle::ty::{ParamEnv, TyCtxt};
25 use rustc_session::lint::builtin::{
26 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
28 use rustc_session::parse::feature_err;
29 use rustc_span::symbol::{kw, sym, Symbol};
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::spec::abi::Abi;
33 use std::collections::hash_map::Entry;
35 pub(crate) fn target_from_impl_item<'tcx>(
37 impl_item: &hir::ImplItem<'_>,
39 match impl_item.kind {
40 hir::ImplItemKind::Const(..) => Target::AssocConst,
41 hir::ImplItemKind::Fn(..) => {
42 let parent_def_id = tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
43 let containing_item = tcx.hir().expect_item(parent_def_id);
44 let containing_impl_is_for_trait = match &containing_item.kind {
45 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
46 _ => bug!("parent of an ImplItem must be an Impl"),
48 if containing_impl_is_for_trait {
49 Target::Method(MethodKind::Trait { body: true })
51 Target::Method(MethodKind::Inherent)
54 hir::ImplItemKind::Type(..) => Target::AssocTy,
58 #[derive(Clone, Copy)]
60 Item(&'tcx Item<'tcx>),
64 #[derive(Copy, Clone)]
65 pub(crate) enum ProcMacroKind {
71 impl IntoDiagnosticArg for ProcMacroKind {
72 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
74 ProcMacroKind::Attribute => "attribute proc macro",
75 ProcMacroKind::Derive => "derive proc macro",
76 ProcMacroKind::FunctionLike => "function-like proc macro",
78 .into_diagnostic_arg()
82 struct CheckAttrVisitor<'tcx> {
85 // Whether or not this visitor should abort after finding errors
89 impl CheckAttrVisitor<'_> {
90 /// Checks any attribute.
96 item: Option<ItemLike<'_>>,
98 let mut doc_aliases = FxHashMap::default();
99 let mut is_valid = true;
100 let mut specified_inline = None;
101 let mut seen = FxHashMap::default();
102 let attrs = self.tcx.hir().attrs(hir_id);
104 let attr_is_valid = match attr.name_or_empty() {
105 sym::do_not_recommend => self.check_do_not_recommend(attr.span, target),
106 sym::inline => self.check_inline(hir_id, attr, span, target),
107 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
108 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
109 sym::marker => self.check_marker(hir_id, attr, span, target),
110 sym::rustc_must_implement_one_of => {
111 self.check_rustc_must_implement_one_of(attr, span, target)
113 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
114 sym::thread_local => self.check_thread_local(attr, span, target),
115 sym::track_caller => {
116 self.check_track_caller(hir_id, attr.span, attrs, span, target)
118 sym::doc => self.check_doc_attrs(
122 &mut specified_inline,
125 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
126 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
127 sym::rustc_layout_scalar_valid_range_start
128 | sym::rustc_layout_scalar_valid_range_end => {
129 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
131 sym::allow_internal_unstable => {
132 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
134 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
135 sym::rustc_allow_const_fn_unstable => {
136 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
138 sym::rustc_std_internal_symbol => {
139 self.check_rustc_std_internal_symbol(&attr, span, target)
141 sym::naked => self.check_naked(hir_id, attr, span, target),
142 sym::rustc_legacy_const_generics => {
143 self.check_rustc_legacy_const_generics(hir_id, &attr, span, target, item)
145 sym::rustc_lint_query_instability => {
146 self.check_rustc_lint_query_instability(hir_id, &attr, span, target)
148 sym::rustc_lint_diagnostics => {
149 self.check_rustc_lint_diagnostics(hir_id, &attr, span, target)
151 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
152 sym::rustc_lint_opt_deny_field_access => {
153 self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
157 | sym::rustc_if_this_changed
158 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
159 sym::cmse_nonsecure_entry => {
160 self.check_cmse_nonsecure_entry(hir_id, attr, span, target)
162 sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target),
163 sym::const_trait => self.check_const_trait(attr, span, target),
164 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
165 sym::must_use => self.check_must_use(hir_id, &attr, target),
166 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
167 sym::rustc_allow_incoherent_impl => {
168 self.check_allow_incoherent_impl(&attr, span, target)
170 sym::rustc_has_incoherent_inherent_impls => {
171 self.check_has_incoherent_inherent_impls(&attr, span, target)
173 sym::ffi_pure => self.check_ffi_pure(attr.span, attrs, target),
174 sym::ffi_const => self.check_ffi_const(attr.span, target),
175 sym::ffi_returns_twice => self.check_ffi_returns_twice(attr.span, target),
176 sym::rustc_const_unstable
177 | sym::rustc_const_stable
180 | sym::rustc_allowed_through_unstable_modules
181 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
182 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
185 is_valid &= attr_is_valid;
188 match attr.name_or_empty() {
189 sym::cold => self.check_cold(hir_id, attr, span, target),
190 sym::link => self.check_link(hir_id, attr, span, target),
191 sym::link_name => self.check_link_name(hir_id, attr, span, target),
192 sym::link_section => self.check_link_section(hir_id, attr, span, target),
193 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
194 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
195 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
196 sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod),
197 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
198 sym::macro_export => self.check_macro_export(hir_id, attr, target),
199 sym::ignore | sym::should_panic => {
200 self.check_generic_attr(hir_id, attr, target, Target::Fn)
202 sym::automatically_derived => {
203 self.check_generic_attr(hir_id, attr, target, Target::Impl)
205 sym::no_implicit_prelude => {
206 self.check_generic_attr(hir_id, attr, target, Target::Mod)
208 sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id),
210 self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
212 sym::proc_macro_attribute => {
213 self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
215 sym::proc_macro_derive => {
216 self.check_generic_attr(hir_id, attr, target, Target::Fn);
217 self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
222 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
224 if hir_id != CRATE_HIR_ID {
225 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
226 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
229 ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
233 errors::OuterCrateLevelAttr,
235 ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
239 errors::InnerCrateLevelAttr,
245 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
246 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
249 self.check_unused_attribute(hir_id, attr)
256 self.check_repr(attrs, span, target, item, hir_id);
257 self.check_used(attrs, target);
260 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
261 self.tcx.emit_spanned_lint(
265 errors::IgnoredAttrWithMacro { sym },
269 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
270 self.tcx.emit_spanned_lint(
274 errors::IgnoredAttr { sym },
278 /// Checks if `#[do_not_recommend]` is applied on a trait impl.
279 fn check_do_not_recommend(&self, attr_span: Span, target: Target) -> bool {
280 if let Target::Impl = target {
283 self.tcx.sess.emit_err(errors::IncorrectDoNotRecommendLocation { span: attr_span });
288 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
289 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
293 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
294 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
295 self.tcx.emit_spanned_lint(
299 errors::IgnoredInlineAttrFnProto,
303 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
304 // just a lint, because we previously erroneously allowed it and some crates used it
305 // accidentally, to be compatible with crates depending on them, we can't throw an
307 Target::AssocConst => {
308 self.tcx.emit_spanned_lint(
312 errors::IgnoredInlineAttrConstants,
316 // FIXME(#80564): Same for fields, arms, and macro defs
317 Target::Field | Target::Arm | Target::MacroDef => {
318 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
322 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
323 attr_span: attr.span,
331 /// Checks if a `#[no_coverage]` is applied directly to a function
332 fn check_no_coverage(
340 // no_coverage on function is fine
343 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
345 // function prototypes can't be covered
346 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
347 self.tcx.emit_spanned_lint(
351 errors::IgnoredNoCoverageFnProto,
356 Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
357 self.tcx.emit_spanned_lint(
361 errors::IgnoredNoCoveragePropagate,
366 Target::Expression | Target::Statement | Target::Arm => {
367 self.tcx.emit_spanned_lint(
371 errors::IgnoredNoCoverageFnDefn,
377 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
378 attr_span: attr.span,
386 fn check_generic_attr(
391 allowed_target: Target,
393 if target != allowed_target {
394 self.tcx.emit_spanned_lint(
398 errors::OnlyHasEffectOn {
399 attr_name: attr.name_or_empty(),
400 target_name: allowed_target.name().replace(' ', "_"),
406 /// Checks if `#[naked]` is applied to a function definition.
407 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
410 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
411 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
412 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
413 // erroneously allowed it and some crates used it accidentally, to be compatible
414 // with crates depending on them, we can't throw an error here.
415 Target::Field | Target::Arm | Target::MacroDef => {
416 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
420 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
421 attr_span: attr.span,
423 on_crate: hir_id == CRATE_HIR_ID,
430 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
431 fn check_cmse_nonsecure_entry(
440 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
442 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
443 attr_span: attr.span,
445 on_crate: hir_id == CRATE_HIR_ID,
452 /// Debugging aid for `object_lifetime_default` query.
453 fn check_object_lifetime_default(&self, hir_id: HirId) {
455 if let Some(owner_id) = hir_id.as_owner()
456 && let Some(generics) = tcx.hir().get_generics(owner_id.def_id)
458 for p in generics.params {
459 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
460 let default = tcx.object_lifetime_default(p.def_id);
461 let repr = match default {
462 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
463 ObjectLifetimeDefault::Static => "'static".to_owned(),
464 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
465 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
467 tcx.sess.emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
472 /// Checks if `#[collapse_debuginfo]` is applied to a macro.
473 fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) -> bool {
475 Target::MacroDef => true,
479 .emit_err(errors::CollapseDebuginfo { attr_span: attr.span, defn_span: span });
485 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
486 fn check_track_caller(
495 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
496 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
499 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
500 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
501 // `#[track_caller]` attribute with just a lint, because we previously
502 // erroneously allowed it and some crates used it accidentally, to be compatible
503 // with crates depending on them, we can't throw an error here.
504 Target::Field | Target::Arm | Target::MacroDef => {
506 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
511 self.tcx.sess.emit_err(errors::TrackedCallerWrongLocation {
514 on_crate: hir_id == CRATE_HIR_ID,
521 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
522 fn check_non_exhaustive(
530 Target::Struct | Target::Enum | Target::Variant => true,
531 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
532 // `#[non_exhaustive]` attribute with just a lint, because we previously
533 // erroneously allowed it and some crates used it accidentally, to be compatible
534 // with crates depending on them, we can't throw an error here.
535 Target::Field | Target::Arm | Target::MacroDef => {
536 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
540 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
541 attr_span: attr.span,
549 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
550 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
552 Target::Trait => true,
553 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
554 // `#[marker]` attribute with just a lint, because we previously
555 // erroneously allowed it and some crates used it accidentally, to be compatible
556 // with crates depending on them, we can't throw an error here.
557 Target::Field | Target::Arm | Target::MacroDef => {
558 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
562 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
563 attr_span: attr.span,
571 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
572 fn check_rustc_must_implement_one_of(
579 Target::Trait => true,
581 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
582 attr_span: attr.span,
590 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
591 fn check_target_feature(
600 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
601 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
602 // crates used this, so only emit a warning.
603 Target::Statement => {
604 self.tcx.emit_spanned_lint(
608 errors::TargetFeatureOnStatement,
612 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
613 // `#[target_feature]` attribute with just a lint, because we previously
614 // erroneously allowed it and some crates used it accidentally, to be compatible
615 // with crates depending on them, we can't throw an error here.
616 Target::Field | Target::Arm | Target::MacroDef => {
617 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
621 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
622 attr_span: attr.span,
624 on_crate: hir_id == CRATE_HIR_ID,
631 /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
632 fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
634 Target::ForeignStatic | Target::Static => true,
636 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
637 attr_span: attr.span,
645 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
646 self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
649 fn check_doc_alias_value(
651 meta: &NestedMetaItem,
656 aliases: &mut FxHashMap<String, Span>,
659 let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
661 &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
662 if doc_alias == kw::Empty {
663 tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
667 let doc_alias_str = doc_alias.as_str();
668 if let Some(c) = doc_alias_str
670 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
672 tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
675 if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
676 tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
680 let span = meta.span();
681 if let Some(location) = match target {
683 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
684 let containing_item = self.tcx.hir().expect_item(parent_def_id);
685 if Target::from_item(containing_item) == Target::Impl {
686 Some("type alias in implementation block")
691 Target::AssocConst => {
692 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
693 let containing_item = self.tcx.hir().expect_item(parent_def_id);
694 // We can't link to trait impl's consts.
695 let err = "associated constant in trait implementation block";
696 match containing_item.kind {
697 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
701 // we check the validity of params elsewhere
702 Target::Param => return false,
708 | Target::Impl => Some(target.name()),
718 | Target::ImplTraitPlaceholder
728 | Target::ForeignStatic
730 | Target::GenericParam(..)
733 | Target::ExprField => None,
735 tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
738 let item_name = self.tcx.hir().name(hir_id);
739 if item_name == doc_alias {
740 tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
743 if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
744 self.tcx.emit_spanned_lint(
748 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
756 meta: &NestedMetaItem,
759 aliases: &mut FxHashMap<String, Span>,
761 if let Some(values) = meta.meta_item_list() {
765 Some(l) => match l.kind {
766 LitKind::Str(s, _) => {
767 if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
774 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
779 self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
785 } else if let Some(doc_alias) = meta.value_str() {
786 self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
788 self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
793 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
794 let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
795 if doc_keyword == kw::Empty {
796 self.doc_attr_str_error(meta, "keyword");
799 match self.tcx.hir().find(hir_id).and_then(|node| match node {
800 hir::Node::Item(item) => Some(&item.kind),
803 Some(ItemKind::Mod(ref module)) => {
804 if !module.item_ids.is_empty() {
805 self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
810 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
814 if !rustc_lexer::is_ident(doc_keyword.as_str()) {
815 self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
816 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
824 fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
825 match self.tcx.hir().find(hir_id).and_then(|node| match node {
826 hir::Node::Item(item) => Some(&item.kind),
829 Some(ItemKind::Impl(ref i)) => {
830 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
831 || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
832 bare_fn_ty.decl.inputs.len() == 1
837 self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
842 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
849 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
851 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
852 /// if there are conflicting attributes for one item.
854 /// `specified_inline` is used to keep track of whether we have
855 /// already seen an inlining attribute for this item.
856 /// If so, `specified_inline` holds the value and the span of
857 /// the first `inline`/`no_inline` attribute.
861 meta: &NestedMetaItem,
864 specified_inline: &mut Option<(bool, Span)>,
867 Target::Use | Target::ExternCrate => {
868 let do_inline = meta.name_or_empty() == sym::inline;
869 if let Some((prev_inline, prev_span)) = *specified_inline {
870 if do_inline != prev_inline {
871 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
872 spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first);
873 spans.push_span_label(
875 fluent::passes_doc_inline_conflict_second,
877 self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
882 *specified_inline = Some((do_inline, meta.span()));
887 self.tcx.emit_spanned_lint(
888 INVALID_DOC_ATTRIBUTES,
891 errors::DocInlineOnlyUse {
892 attr_span: meta.span(),
893 item_span: (attr.style == AttrStyle::Outer)
894 .then(|| self.tcx.hir().span(hir_id)),
902 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
903 fn check_attr_not_crate_level(
905 meta: &NestedMetaItem,
909 if CRATE_HIR_ID == hir_id {
910 self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
916 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
917 fn check_attr_crate_level(
920 meta: &NestedMetaItem,
923 if hir_id != CRATE_HIR_ID {
924 self.tcx.struct_span_lint_hir(
925 INVALID_DOC_ATTRIBUTES,
928 fluent::passes_attr_crate_level,
930 if attr.style == AttrStyle::Outer
931 && self.tcx.hir().get_parent_item(hir_id) == CRATE_OWNER_ID
933 if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
935 err.span_suggestion_verbose(
939 Applicability::MaybeIncorrect,
942 err.span_help(attr.span, fluent::help);
945 err.note(fluent::note);
954 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
956 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
957 let mut is_valid = true;
958 if let Some(metas) = meta.meta_item_list() {
959 for i_meta in metas {
960 match i_meta.name_or_empty() {
961 sym::attr | sym::no_crate_inject => {}
963 self.tcx.emit_spanned_lint(
964 INVALID_DOC_ATTRIBUTES,
967 errors::DocTestUnknown {
968 path: rustc_ast_pretty::pprust::path_to_string(
969 &i_meta.meta_item().unwrap().path,
978 self.tcx.emit_spanned_lint(
979 INVALID_DOC_ATTRIBUTES,
982 errors::DocTestTakesList,
989 /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes.
990 /// Returns `true` if valid.
991 fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
992 if meta.meta_item_list().is_some() {
995 self.tcx.emit_spanned_lint(
996 INVALID_DOC_ATTRIBUTES,
999 errors::DocCfgHideTakesList,
1005 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
1007 /// `specified_inline` should be initialized to `None` and kept for the scope
1008 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1010 /// [`check_doc_inline`]: Self::check_doc_inline
1016 specified_inline: &mut Option<(bool, Span)>,
1017 aliases: &mut FxHashMap<String, Span>,
1019 let mut is_valid = true;
1021 if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
1023 if let Some(i_meta) = meta.meta_item() {
1024 match i_meta.name_or_empty() {
1026 if !self.check_attr_not_crate_level(meta, hir_id, "alias")
1027 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
1033 if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
1034 || !self.check_doc_keyword(meta, hir_id) =>
1040 if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
1041 || !self.check_doc_fake_variadic(meta, hir_id) =>
1046 sym::html_favicon_url
1047 | sym::html_logo_url
1048 | sym::html_playground_url
1049 | sym::issue_tracker_base_url
1050 | sym::html_root_url
1051 | sym::html_no_source
1053 if !self.check_attr_crate_level(attr, meta, hir_id) =>
1059 if !self.check_attr_crate_level(attr, meta, hir_id)
1060 || !self.check_doc_cfg_hide(meta, hir_id) =>
1065 sym::inline | sym::no_inline
1066 if !self.check_doc_inline(
1077 // no_default_passes: deprecated
1078 // passes: deprecated
1079 // plugins: removed, but rustdoc warns about it itself
1084 | sym::html_favicon_url
1085 | sym::html_logo_url
1086 | sym::html_no_source
1087 | sym::html_playground_url
1088 | sym::html_root_url
1090 | sym::issue_tracker_base_url
1093 | sym::no_default_passes
1095 | sym::notable_trait
1098 | sym::fake_variadic => {}
1101 if !self.check_test_attr(meta, hir_id) {
1107 if !self.tcx.features().rustdoc_internals {
1108 self.tcx.emit_spanned_lint(
1109 INVALID_DOC_ATTRIBUTES,
1112 errors::DocPrimitive,
1118 let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1119 if i_meta.has_name(sym::spotlight) {
1120 self.tcx.emit_spanned_lint(
1121 INVALID_DOC_ATTRIBUTES,
1124 errors::DocTestUnknownSpotlight {
1129 } else if i_meta.has_name(sym::include) &&
1130 let Some(value) = i_meta.value_str() {
1131 let applicability = if list.len() == 1 {
1132 Applicability::MachineApplicable
1134 Applicability::MaybeIncorrect
1136 // If there are multiple attributes, the suggestion would suggest
1137 // deleting all of them, which is incorrect.
1138 self.tcx.emit_spanned_lint(
1139 INVALID_DOC_ATTRIBUTES,
1142 errors::DocTestUnknownInclude {
1144 value: value.to_string(),
1145 inner: match attr.style { AttrStyle::Inner=> "!" , AttrStyle::Outer => "" },
1146 sugg: (attr.meta().unwrap().span, applicability),
1150 self.tcx.emit_spanned_lint(
1151 INVALID_DOC_ATTRIBUTES,
1154 errors::DocTestUnknownAny { path }
1161 self.tcx.emit_spanned_lint(
1162 INVALID_DOC_ATTRIBUTES,
1175 /// Warns against some misuses of `#[pass_by_value]`
1176 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1178 Target::Struct | Target::Enum | Target::TyAlias => true,
1180 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1186 fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1188 Target::Method(MethodKind::Inherent) => true,
1190 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1196 fn check_has_incoherent_inherent_impls(
1203 Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1209 .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1215 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute], target: Target) -> bool {
1216 if target != Target::ForeignFn {
1217 self.tcx.sess.emit_err(errors::FfiPureInvalidTarget { attr_span });
1220 if attrs.iter().any(|a| a.has_name(sym::ffi_const)) {
1221 // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1222 self.tcx.sess.emit_err(errors::BothFfiConstAndPure { attr_span });
1229 fn check_ffi_const(&self, attr_span: Span, target: Target) -> bool {
1230 if target == Target::ForeignFn {
1233 self.tcx.sess.emit_err(errors::FfiConstInvalidTarget { attr_span });
1238 fn check_ffi_returns_twice(&self, attr_span: Span, target: Target) -> bool {
1239 if target == Target::ForeignFn {
1242 self.tcx.sess.emit_err(errors::FfiReturnsTwiceInvalidTarget { attr_span });
1247 /// Warns against some misuses of `#[must_use]`
1248 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool {
1257 // `impl Trait` in return position can trip
1258 // `unused_must_use` if `Trait` is marked as
1262 let article = match target {
1267 | Target::Expression
1269 | Target::AssocConst
1270 | Target::AssocTy => "an",
1274 self.tcx.emit_spanned_lint(
1278 errors::MustUseNoEffect { article, target },
1282 // For now, its always valid
1286 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1287 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1289 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1291 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1297 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1298 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1300 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1301 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1302 // `#[cold]` attribute with just a lint, because we previously
1303 // erroneously allowed it and some crates used it accidentally, to be compatible
1304 // with crates depending on them, we can't throw an error here.
1305 Target::Field | Target::Arm | Target::MacroDef => {
1306 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1309 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1310 // this, so only emit a warning.
1311 self.tcx.emit_spanned_lint(
1315 errors::Cold { span, on_crate: hir_id == CRATE_HIR_ID },
1321 /// Checks if `#[link]` is applied to an item other than a foreign module.
1322 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1323 if target == Target::ForeignMod
1324 && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1325 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1326 && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1331 self.tcx.emit_spanned_lint(
1335 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1339 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1340 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1342 Target::ForeignFn | Target::ForeignStatic => {}
1343 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1344 // `#[link_name]` attribute with just a lint, because we previously
1345 // erroneously allowed it and some crates used it accidentally, to be compatible
1346 // with crates depending on them, we can't throw an error here.
1347 Target::Field | Target::Arm | Target::MacroDef => {
1348 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1351 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1352 // used this, so only emit a warning.
1353 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1354 if let Some(s) = attr.value_str() {
1355 self.tcx.emit_spanned_lint(
1359 errors::LinkName { span, attr_span, value: s.as_str() },
1362 self.tcx.emit_spanned_lint(
1366 errors::LinkName { span, attr_span, value: "..." },
1373 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1374 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1376 Target::ExternCrate => true,
1377 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1378 // `#[no_link]` attribute with just a lint, because we previously
1379 // erroneously allowed it and some crates used it accidentally, to be compatible
1380 // with crates depending on them, we can't throw an error here.
1381 Target::Field | Target::Arm | Target::MacroDef => {
1382 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1386 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1392 fn is_impl_item(&self, hir_id: HirId) -> bool {
1393 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1396 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1397 fn check_export_name(
1405 Target::Static | Target::Fn => true,
1406 Target::Method(..) if self.is_impl_item(hir_id) => true,
1407 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1408 // `#[export_name]` attribute with just a lint, because we previously
1409 // erroneously allowed it and some crates used it accidentally, to be compatible
1410 // with crates depending on them, we can't throw an error here.
1411 Target::Field | Target::Arm | Target::MacroDef => {
1412 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1416 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1422 fn check_rustc_layout_scalar_valid_range(
1428 if target != Target::Struct {
1429 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1430 attr_span: attr.span,
1436 let Some(list) = attr.meta_item_list() else {
1440 if matches!(&list[..], &[NestedMetaItem::Lit(MetaItemLit { kind: LitKind::Int(..), .. })]) {
1443 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1448 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1449 fn check_rustc_legacy_const_generics(
1455 item: Option<ItemLike<'_>>,
1457 let is_function = matches!(target, Target::Fn);
1459 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1460 attr_span: attr.span,
1462 on_crate: hir_id == CRATE_HIR_ID,
1467 let Some(list) = attr.meta_item_list() else {
1468 // The attribute form is validated on AST.
1472 let Some(ItemLike::Item(Item {
1473 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1476 bug!("should be a function item");
1479 for param in generics.params {
1481 hir::GenericParamKind::Const { .. } => {}
1483 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1484 attr_span: attr.span,
1485 param_span: param.span,
1492 if list.len() != generics.params.len() {
1493 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1494 attr_span: attr.span,
1495 generics_span: generics.span,
1500 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1501 let mut invalid_args = vec![];
1503 if let Some(LitKind::Int(val, _)) = meta.lit().map(|lit| &lit.kind) {
1504 if *val >= arg_count {
1505 let span = meta.span();
1506 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1508 arg_count: arg_count as usize,
1513 invalid_args.push(meta.span());
1517 if !invalid_args.is_empty() {
1518 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1525 /// Helper function for checking that the provided attribute is only applied to a function or
1527 fn check_applied_to_fn_or_method(
1534 let is_function = matches!(target, Target::Fn | Target::Method(..));
1536 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1537 attr_span: attr.span,
1539 on_crate: hir_id == CRATE_HIR_ID,
1547 /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1549 fn check_rustc_lint_query_instability(
1556 self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1559 /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1561 fn check_rustc_lint_diagnostics(
1568 self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1571 /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1572 fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1574 Target::Struct => true,
1576 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1582 /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1583 fn check_rustc_lint_opt_deny_field_access(
1590 Target::Field => true,
1594 .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1600 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1601 /// option is passed to the compiler.
1602 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1603 if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1606 self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1611 /// Checks if `#[link_section]` is applied to a function or static.
1612 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1614 Target::Static | Target::Fn | Target::Method(..) => {}
1615 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1616 // `#[link_section]` attribute with just a lint, because we previously
1617 // erroneously allowed it and some crates used it accidentally, to be compatible
1618 // with crates depending on them, we can't throw an error here.
1619 Target::Field | Target::Arm | Target::MacroDef => {
1620 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1623 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1624 // crates used this, so only emit a warning.
1625 self.tcx.emit_spanned_lint(
1629 errors::LinkSection { span },
1635 /// Checks if `#[no_mangle]` is applied to a function or static.
1636 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1638 Target::Static | Target::Fn => {}
1639 Target::Method(..) if self.is_impl_item(hir_id) => {}
1640 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1641 // `#[no_mangle]` attribute with just a lint, because we previously
1642 // erroneously allowed it and some crates used it accidentally, to be compatible
1643 // with crates depending on them, we can't throw an error here.
1644 Target::Field | Target::Arm | Target::MacroDef => {
1645 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1647 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1648 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1649 // otherwise the error seems odd
1650 Target::ForeignFn | Target::ForeignStatic => {
1651 let foreign_item_kind = match target {
1652 Target::ForeignFn => "function",
1653 Target::ForeignStatic => "static",
1654 _ => unreachable!(),
1656 self.tcx.emit_spanned_lint(
1660 errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1664 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1665 // crates used this, so only emit a warning.
1666 self.tcx.emit_spanned_lint(
1670 errors::NoMangle { span },
1676 /// Checks if the `#[repr]` attributes on `item` are valid.
1679 attrs: &[Attribute],
1682 item: Option<ItemLike<'_>>,
1685 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1688 // #[repr(bar, align(8))]
1690 let hints: Vec<_> = attrs
1692 .filter(|attr| attr.has_name(sym::repr))
1693 .filter_map(|attr| attr.meta_item_list())
1697 let mut int_reprs = 0;
1698 let mut is_c = false;
1699 let mut is_simd = false;
1700 let mut is_transparent = false;
1702 for hint in &hints {
1703 if !hint.is_meta_item() {
1704 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1708 match hint.name_or_empty() {
1712 Target::Struct | Target::Union | Target::Enum => continue,
1714 self.tcx.sess.emit_err(errors::AttrApplication::StructEnumUnion {
1715 hint_span: hint.span(),
1722 if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1724 &self.tcx.sess.parse_sess,
1727 "`repr(align)` attributes on functions are unstable",
1733 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1735 self.tcx.sess.emit_err(
1736 errors::AttrApplication::StructEnumFunctionUnion {
1737 hint_span: hint.span(),
1745 if target != Target::Struct && target != Target::Union {
1746 self.tcx.sess.emit_err(errors::AttrApplication::StructUnion {
1747 hint_span: hint.span(),
1756 if target != Target::Struct {
1757 self.tcx.sess.emit_err(errors::AttrApplication::Struct {
1758 hint_span: hint.span(),
1765 sym::transparent => {
1766 is_transparent = true;
1768 Target::Struct | Target::Union | Target::Enum => continue,
1770 self.tcx.sess.emit_err(errors::AttrApplication::StructEnumUnion {
1771 hint_span: hint.span(),
1790 if target != Target::Enum {
1791 self.tcx.sess.emit_err(errors::AttrApplication::Enum {
1792 hint_span: hint.span(),
1800 self.tcx.sess.emit_err(errors::UnrecognizedReprHint { span: hint.span() });
1806 // Just point at all repr hints if there are any incompatibilities.
1807 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1808 let hint_spans = hints.iter().map(|hint| hint.span());
1810 // Error on repr(transparent, <anything else>).
1811 if is_transparent && hints.len() > 1 {
1812 let hint_spans: Vec<_> = hint_spans.clone().collect();
1813 self.tcx.sess.emit_err(errors::TransparentIncompatible {
1815 target: target.to_string(),
1818 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1820 || (is_simd && is_c)
1823 && item.map_or(false, |item| {
1824 if let ItemLike::Item(item) = item {
1825 return is_c_like_enum(item);
1830 self.tcx.emit_spanned_lint(
1831 CONFLICTING_REPR_HINTS,
1833 hint_spans.collect::<Vec<Span>>(),
1834 errors::ReprConflicting,
1839 fn check_used(&self, attrs: &[Attribute], target: Target) {
1840 let mut used_linker_span = None;
1841 let mut used_compiler_span = None;
1842 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1843 if target != Target::Static {
1844 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1846 let inner = attr.meta_item_list();
1847 match inner.as_deref() {
1848 Some([item]) if item.has_name(sym::linker) => {
1849 if used_linker_span.is_none() {
1850 used_linker_span = Some(attr.span);
1853 Some([item]) if item.has_name(sym::compiler) => {
1854 if used_compiler_span.is_none() {
1855 used_compiler_span = Some(attr.span);
1859 // This error case is handled in rustc_hir_analysis::collect.
1862 // Default case (compiler) when arg isn't defined.
1863 if used_compiler_span.is_none() {
1864 used_compiler_span = Some(attr.span);
1869 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1872 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1876 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1877 /// (Allows proc_macro functions)
1878 fn check_allow_internal_unstable(
1884 attrs: &[Attribute],
1886 debug!("Checking target: {:?}", target);
1890 if self.tcx.sess.is_proc_macro_attr(attr) {
1891 debug!("Is proc macro attr");
1895 debug!("Is not proc macro attr");
1898 Target::MacroDef => true,
1899 // FIXME(#80564): We permit struct fields and match arms to have an
1900 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1901 // erroneously allowed it and some crates used it accidentally, to be compatible
1902 // with crates depending on them, we can't throw an error here.
1903 Target::Field | Target::Arm => {
1904 self.inline_attr_str_error_without_macro_def(
1907 "allow_internal_unstable",
1914 .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1920 /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1921 fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1925 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1930 let Some(hints) = attr.meta_item_list() else {
1931 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1935 let hint = match hints.len() {
1938 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1943 let Some(meta_item) = hint.meta_item() else {
1944 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1948 let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1949 (sym::natvis_file, Some(value)) => value,
1950 (sym::gdb_script_file, Some(value)) => value,
1952 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1958 match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1966 match std::fs::File::open(&file) {
1969 self.tcx.sess.emit_err(errors::DebugVisualizerUnreadable {
1970 span: meta_item.span,
1979 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1980 /// (Allows proc_macro functions)
1981 fn check_rustc_allow_const_fn_unstable(
1989 Target::Fn | Target::Method(_)
1990 if self.tcx.is_const_fn_raw(hir_id.expect_owner().to_def_id()) =>
1994 // FIXME(#80564): We permit struct fields and match arms to have an
1995 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1996 // erroneously allowed it and some crates used it accidentally, to be compatible
1997 // with crates depending on them, we can't throw an error here.
1998 Target::Field | Target::Arm | Target::MacroDef => {
1999 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
2005 .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
2011 fn check_rustc_std_internal_symbol(
2018 Target::Fn | Target::Static => true,
2022 .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
2028 /// `#[const_trait]` only applies to traits.
2029 fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
2031 Target::Trait => true,
2033 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
2039 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
2041 Target::Expression => {
2042 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
2049 fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
2051 Target::ForeignFn | Target::ForeignStatic => true,
2053 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
2059 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
2061 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
2062 self.tcx.emit_spanned_lint(
2073 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2074 let name = attr.name_or_empty();
2076 Target::ExternCrate | Target::Mod => {}
2078 self.tcx.emit_spanned_lint(
2082 errors::MacroUse { name },
2088 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2089 if target != Target::MacroDef {
2090 self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
2094 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2095 if target != Target::Fn {
2096 self.tcx.emit_spanned_lint(
2100 errors::PluginRegistrar,
2105 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
2106 // Warn on useless empty attributes.
2107 let note = if matches!(
2108 attr.name_or_empty(),
2117 | sym::target_feature
2118 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
2120 errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
2122 attr.name_or_empty(),
2123 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
2124 ) && let Some(meta) = attr.meta_item_list()
2126 && let Some(item) = meta[0].meta_item()
2127 && let MetaItemKind::NameValue(_) = &item.kind
2128 && item.path == sym::reason
2130 errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2131 } else if attr.name_or_empty() == sym::default_method_body_is_const {
2132 errors::UnusedNote::DefaultMethodBodyConst
2137 self.tcx.emit_spanned_lint(
2141 errors::Unused { attr_span: attr.span, note },
2145 /// A best effort attempt to create an error for a mismatching proc macro signature.
2147 /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
2148 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
2149 let expected_input_count = match kind {
2150 ProcMacroKind::Attribute => 2,
2151 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
2154 let expected_signature = match kind {
2155 ProcMacroKind::Attribute => "fn(TokenStream, TokenStream) -> TokenStream",
2156 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => "fn(TokenStream) -> TokenStream",
2160 if target == Target::Fn {
2161 let Some(tokenstream) = tcx.get_diagnostic_item(sym::TokenStream) else {return};
2162 let tokenstream = tcx.type_of(tokenstream);
2164 let id = hir_id.expect_owner();
2165 let hir_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap();
2168 tcx.liberate_late_bound_regions(id.to_def_id(), tcx.fn_sig(id).subst_identity());
2169 let sig = tcx.normalize_erasing_regions(ParamEnv::empty(), sig);
2171 // We don't currently require that the function signature is equal to
2172 // `fn(TokenStream) -> TokenStream`, but instead monomorphizes to
2173 // `fn(TokenStream) -> TokenStream` after some substitution of generic arguments.
2175 // Properly checking this means pulling in additional `rustc` crates, so we don't.
2176 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer };
2178 if sig.abi != Abi::Rust {
2179 tcx.sess.emit_err(errors::ProcMacroInvalidAbi {
2181 abi: sig.abi.name(),
2183 self.abort.set(true);
2186 if sig.unsafety == Unsafety::Unsafe {
2187 tcx.sess.emit_err(errors::ProcMacroUnsafe { span: hir_sig.span });
2188 self.abort.set(true);
2191 let output = sig.output();
2193 // Typecheck the output
2194 if !drcx.types_may_unify(output, tokenstream) {
2195 tcx.sess.emit_err(errors::ProcMacroTypeError {
2196 span: hir_sig.decl.output.span(),
2201 self.abort.set(true);
2204 if sig.inputs().len() < expected_input_count {
2205 tcx.sess.emit_err(errors::ProcMacroMissingArguments {
2206 expected_input_count,
2211 self.abort.set(true);
2214 // Check that the inputs are correct, if there are enough.
2215 if sig.inputs().len() >= expected_input_count {
2217 sig.inputs().iter().zip(hir_sig.decl.inputs).take(expected_input_count)
2219 if !drcx.types_may_unify(*arg, tokenstream) {
2220 tcx.sess.emit_err(errors::ProcMacroTypeError {
2226 self.abort.set(true);
2231 // Check that there are not too many arguments
2232 let body_id = tcx.hir().body_owned_by(id.def_id);
2233 let excess = tcx.hir().body(body_id).params.get(expected_input_count..);
2234 if let Some(excess @ [begin @ end] | excess @ [begin, .., end]) = excess {
2235 tcx.sess.emit_err(errors::ProcMacroDiffArguments {
2236 span: begin.span.to(end.span),
2237 count: excess.len(),
2241 self.abort.set(true);
2247 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2248 type NestedFilter = nested_filter::OnlyBodies;
2250 fn nested_visit_map(&mut self) -> Self::Map {
2254 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2255 // Historically we've run more checks on non-exported than exported macros,
2256 // so this lets us continue to run them while maintaining backwards compatibility.
2257 // In the long run, the checks should be harmonized.
2258 if let ItemKind::Macro(ref macro_def, _) = item.kind {
2259 let def_id = item.owner_id.to_def_id();
2260 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
2261 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2265 let target = Target::from_item(item);
2266 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2267 intravisit::walk_item(self, item)
2270 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2271 let target = Target::from_generic_param(generic_param);
2272 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2273 intravisit::walk_generic_param(self, generic_param)
2276 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2277 let target = Target::from_trait_item(trait_item);
2278 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2279 intravisit::walk_trait_item(self, trait_item)
2282 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2283 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2284 intravisit::walk_field_def(self, struct_field);
2287 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2288 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2289 intravisit::walk_arm(self, arm);
2292 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2293 let target = Target::from_foreign_item(f_item);
2294 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2295 intravisit::walk_foreign_item(self, f_item)
2298 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2299 let target = target_from_impl_item(self.tcx, impl_item);
2300 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2301 intravisit::walk_impl_item(self, impl_item)
2304 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2305 // When checking statements ignore expressions, they will be checked later.
2306 if let hir::StmtKind::Local(ref l) = stmt.kind {
2307 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2309 intravisit::walk_stmt(self, stmt)
2312 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2313 let target = match expr.kind {
2314 hir::ExprKind::Closure { .. } => Target::Closure,
2315 _ => Target::Expression,
2318 self.check_attributes(expr.hir_id, expr.span, target, None);
2319 intravisit::walk_expr(self, expr)
2322 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2323 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2324 intravisit::walk_expr_field(self, field)
2327 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2328 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2329 intravisit::walk_variant(self, variant)
2332 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2333 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2335 intravisit::walk_param(self, param);
2338 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2339 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2340 intravisit::walk_pat_field(self, field);
2344 fn is_c_like_enum(item: &Item<'_>) -> bool {
2345 if let ItemKind::Enum(ref def, _) = item.kind {
2346 for variant in def.variants {
2347 match variant.data {
2348 hir::VariantData::Unit(..) => { /* continue */ }
2358 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2360 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2361 // Check for builtin attributes at the crate level
2362 // which were unsuccessfully resolved due to cannot determine
2363 // resolution for the attribute macro error.
2364 const ATTRS_TO_CHECK: &[Symbol] = &[
2368 sym::automatically_derived,
2375 sym::global_allocator,
2380 // This function should only be called with crate attributes
2381 // which are inner attributes always but lets check to make sure
2382 if attr.style == AttrStyle::Inner {
2383 for attr_to_check in ATTRS_TO_CHECK {
2384 if attr.has_name(*attr_to_check) {
2385 tcx.sess.emit_err(errors::InvalidAttrAtCrateLevel {
2387 snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(),
2388 name: *attr_to_check,
2396 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2397 let attrs = tcx.hir().attrs(item.hir_id());
2400 if attr.has_name(sym::inline) {
2401 tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2406 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2407 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2408 tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2409 if module_def_id.is_top_level_module() {
2410 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2411 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2413 if check_attr_visitor.abort.get() {
2414 tcx.sess.abort_if_errors()
2418 pub(crate) fn provide(providers: &mut Providers) {
2419 *providers = Providers { check_mod_attrs, ..*providers };
2422 fn check_duplicates(
2426 duplicates: AttributeDuplicates,
2427 seen: &mut FxHashMap<Symbol, Span>,
2429 use AttributeDuplicates::*;
2430 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2435 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2436 match seen.entry(attr.name_or_empty()) {
2437 Entry::Occupied(mut entry) => {
2438 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2439 let to_remove = entry.insert(attr.span);
2440 (to_remove, attr.span)
2442 (attr.span, *entry.get())
2444 tcx.emit_spanned_lint(
2448 errors::UnusedDuplicate {
2453 FutureWarnFollowing | FutureWarnPreceding
2459 Entry::Vacant(entry) => {
2460 entry.insert(attr.span);
2464 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2465 Entry::Occupied(mut entry) => {
2466 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2467 let to_remove = entry.insert(attr.span);
2468 (to_remove, attr.span)
2470 (attr.span, *entry.get())
2472 tcx.sess.emit_err(errors::UnusedMultiple {
2475 name: attr.name_or_empty(),
2478 Entry::Vacant(entry) => {
2479 entry.insert(attr.span);