]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/check_attr.rs
Auto merge of #107360 - bjorn3:fix_thin_archive_reading, r=wesleywiser
[rust.git] / compiler / rustc_passes / src / check_attr.rs
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
5 //! item.
6
7 use crate::errors::{
8     self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr,
9     OnlyHasEffectOn, ProcMacroDiffArguments, ProcMacroInvalidAbi, ProcMacroMissingArguments,
10     ProcMacroTypeError, ProcMacroUnsafe, TransparentIncompatible, UnrecognizedReprHint,
11 };
12 use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem};
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_errors::{fluent, Applicability, IntoDiagnosticArg, MultiSpan};
15 use rustc_expand::base::resolve_path;
16 use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
17 use rustc_hir as hir;
18 use rustc_hir::def_id::LocalDefId;
19 use rustc_hir::intravisit::{self, Visitor};
20 use rustc_hir::{
21     self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID,
22 };
23 use rustc_hir::{MethodKind, Target, Unsafety};
24 use rustc_middle::hir::nested_filter;
25 use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
26 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
27 use rustc_middle::ty::query::Providers;
28 use rustc_middle::ty::{ParamEnv, TyCtxt};
29 use rustc_session::lint::builtin::{
30     CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
31 };
32 use rustc_session::parse::feature_err;
33 use rustc_span::symbol::{kw, sym, Symbol};
34 use rustc_span::{Span, DUMMY_SP};
35 use rustc_target::spec::abi::Abi;
36 use std::cell::Cell;
37 use std::collections::hash_map::Entry;
38
39 pub(crate) fn target_from_impl_item<'tcx>(
40     tcx: TyCtxt<'tcx>,
41     impl_item: &hir::ImplItem<'_>,
42 ) -> Target {
43     match impl_item.kind {
44         hir::ImplItemKind::Const(..) => Target::AssocConst,
45         hir::ImplItemKind::Fn(..) => {
46             let parent_def_id = tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
47             let containing_item = tcx.hir().expect_item(parent_def_id);
48             let containing_impl_is_for_trait = match &containing_item.kind {
49                 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
50                 _ => bug!("parent of an ImplItem must be an Impl"),
51             };
52             if containing_impl_is_for_trait {
53                 Target::Method(MethodKind::Trait { body: true })
54             } else {
55                 Target::Method(MethodKind::Inherent)
56             }
57         }
58         hir::ImplItemKind::Type(..) => Target::AssocTy,
59     }
60 }
61
62 #[derive(Clone, Copy)]
63 enum ItemLike<'tcx> {
64     Item(&'tcx Item<'tcx>),
65     ForeignItem,
66 }
67
68 #[derive(Copy, Clone)]
69 pub(crate) enum ProcMacroKind {
70     FunctionLike,
71     Derive,
72     Attribute,
73 }
74
75 impl IntoDiagnosticArg for ProcMacroKind {
76     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
77         match self {
78             ProcMacroKind::Attribute => "attribute proc macro",
79             ProcMacroKind::Derive => "derive proc macro",
80             ProcMacroKind::FunctionLike => "function-like proc macro",
81         }
82         .into_diagnostic_arg()
83     }
84 }
85
86 struct CheckAttrVisitor<'tcx> {
87     tcx: TyCtxt<'tcx>,
88
89     // Whether or not this visitor should abort after finding errors
90     abort: Cell<bool>,
91 }
92
93 impl CheckAttrVisitor<'_> {
94     /// Checks any attribute.
95     fn check_attributes(
96         &self,
97         hir_id: HirId,
98         span: Span,
99         target: Target,
100         item: Option<ItemLike<'_>>,
101     ) {
102         let mut doc_aliases = FxHashMap::default();
103         let mut is_valid = true;
104         let mut specified_inline = None;
105         let mut seen = FxHashMap::default();
106         let attrs = self.tcx.hir().attrs(hir_id);
107         for attr in attrs {
108             let attr_is_valid = match attr.name_or_empty() {
109                 sym::do_not_recommend => self.check_do_not_recommend(attr.span, target),
110                 sym::inline => self.check_inline(hir_id, attr, span, target),
111                 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
112                 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
113                 sym::marker => self.check_marker(hir_id, attr, span, target),
114                 sym::rustc_must_implement_one_of => {
115                     self.check_rustc_must_implement_one_of(attr, span, target)
116                 }
117                 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
118                 sym::thread_local => self.check_thread_local(attr, span, target),
119                 sym::track_caller => {
120                     self.check_track_caller(hir_id, attr.span, attrs, span, target)
121                 }
122                 sym::doc => self.check_doc_attrs(
123                     attr,
124                     hir_id,
125                     target,
126                     &mut specified_inline,
127                     &mut doc_aliases,
128                 ),
129                 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
130                 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
131                 sym::rustc_layout_scalar_valid_range_start
132                 | sym::rustc_layout_scalar_valid_range_end => {
133                     self.check_rustc_layout_scalar_valid_range(&attr, span, target)
134                 }
135                 sym::allow_internal_unstable => {
136                     self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
137                 }
138                 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
139                 sym::rustc_allow_const_fn_unstable => {
140                     self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
141                 }
142                 sym::rustc_std_internal_symbol => {
143                     self.check_rustc_std_internal_symbol(&attr, span, target)
144                 }
145                 sym::naked => self.check_naked(hir_id, attr, span, target),
146                 sym::rustc_legacy_const_generics => {
147                     self.check_rustc_legacy_const_generics(hir_id, &attr, span, target, item)
148                 }
149                 sym::rustc_lint_query_instability => {
150                     self.check_rustc_lint_query_instability(hir_id, &attr, span, target)
151                 }
152                 sym::rustc_lint_diagnostics => {
153                     self.check_rustc_lint_diagnostics(hir_id, &attr, span, target)
154                 }
155                 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
156                 sym::rustc_lint_opt_deny_field_access => {
157                     self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
158                 }
159                 sym::rustc_clean
160                 | sym::rustc_dirty
161                 | sym::rustc_if_this_changed
162                 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
163                 sym::cmse_nonsecure_entry => {
164                     self.check_cmse_nonsecure_entry(hir_id, attr, span, target)
165                 }
166                 sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target),
167                 sym::const_trait => self.check_const_trait(attr, span, target),
168                 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
169                 sym::must_use => self.check_must_use(hir_id, &attr, target),
170                 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
171                 sym::rustc_allow_incoherent_impl => {
172                     self.check_allow_incoherent_impl(&attr, span, target)
173                 }
174                 sym::rustc_has_incoherent_inherent_impls => {
175                     self.check_has_incoherent_inherent_impls(&attr, span, target)
176                 }
177                 sym::rustc_const_unstable
178                 | sym::rustc_const_stable
179                 | sym::unstable
180                 | sym::stable
181                 | sym::rustc_allowed_through_unstable_modules
182                 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
183                 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
184                 _ => true,
185             };
186             is_valid &= attr_is_valid;
187
188             // lint-only checks
189             match attr.name_or_empty() {
190                 sym::cold => self.check_cold(hir_id, attr, span, target),
191                 sym::link => self.check_link(hir_id, attr, span, target),
192                 sym::link_name => self.check_link_name(hir_id, attr, span, target),
193                 sym::link_section => self.check_link_section(hir_id, attr, span, target),
194                 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
195                 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
196                 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
197                 sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod),
198                 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
199                 sym::macro_export => self.check_macro_export(hir_id, attr, target),
200                 sym::ignore | sym::should_panic => {
201                     self.check_generic_attr(hir_id, attr, target, Target::Fn)
202                 }
203                 sym::automatically_derived => {
204                     self.check_generic_attr(hir_id, attr, target, Target::Impl)
205                 }
206                 sym::no_implicit_prelude => {
207                     self.check_generic_attr(hir_id, attr, target, Target::Mod)
208                 }
209                 sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id),
210                 sym::proc_macro => {
211                     self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
212                 }
213                 sym::proc_macro_attribute => {
214                     self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
215                 }
216                 sym::proc_macro_derive => {
217                     self.check_generic_attr(hir_id, attr, target, Target::Fn);
218                     self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
219                 }
220                 _ => {}
221             }
222
223             let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
224
225             if hir_id != CRATE_HIR_ID {
226                 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
227                     attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
228                 {
229                     match attr.style {
230                         ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
231                             UNUSED_ATTRIBUTES,
232                             hir_id,
233                             attr.span,
234                             errors::OuterCrateLevelAttr,
235                         ),
236                         ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
237                             UNUSED_ATTRIBUTES,
238                             hir_id,
239                             attr.span,
240                             errors::InnerCrateLevelAttr,
241                         ),
242                     }
243                 }
244             }
245
246             if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
247                 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
248             }
249
250             self.check_unused_attribute(hir_id, attr)
251         }
252
253         if !is_valid {
254             return;
255         }
256
257         self.check_repr(attrs, span, target, item, hir_id);
258         self.check_used(attrs, target);
259     }
260
261     fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
262         self.tcx.emit_spanned_lint(
263             UNUSED_ATTRIBUTES,
264             hir_id,
265             attr.span,
266             errors::IgnoredAttrWithMacro { sym },
267         );
268     }
269
270     fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
271         self.tcx.emit_spanned_lint(
272             UNUSED_ATTRIBUTES,
273             hir_id,
274             attr.span,
275             errors::IgnoredAttr { sym },
276         );
277     }
278
279     /// Checks if `#[do_not_recommend]` is applied on a trait impl.
280     fn check_do_not_recommend(&self, attr_span: Span, target: Target) -> bool {
281         if let Target::Impl = target {
282             true
283         } else {
284             self.tcx.sess.emit_err(errors::IncorrectDoNotRecommendLocation { span: attr_span });
285             false
286         }
287     }
288
289     /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
290     fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
291         match target {
292             Target::Fn
293             | Target::Closure
294             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
295             Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
296                 self.tcx.emit_spanned_lint(
297                     UNUSED_ATTRIBUTES,
298                     hir_id,
299                     attr.span,
300                     errors::IgnoredInlineAttrFnProto,
301                 );
302                 true
303             }
304             // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
305             // just a lint, because we previously erroneously allowed it and some crates used it
306             // accidentally, to be compatible with crates depending on them, we can't throw an
307             // error here.
308             Target::AssocConst => {
309                 self.tcx.emit_spanned_lint(
310                     UNUSED_ATTRIBUTES,
311                     hir_id,
312                     attr.span,
313                     errors::IgnoredInlineAttrConstants,
314                 );
315                 true
316             }
317             // FIXME(#80564): Same for fields, arms, and macro defs
318             Target::Field | Target::Arm | Target::MacroDef => {
319                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
320                 true
321             }
322             _ => {
323                 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
324                     attr_span: attr.span,
325                     defn_span: span,
326                 });
327                 false
328             }
329         }
330     }
331
332     /// Checks if a `#[no_coverage]` is applied directly to a function
333     fn check_no_coverage(
334         &self,
335         hir_id: HirId,
336         attr: &Attribute,
337         span: Span,
338         target: Target,
339     ) -> bool {
340         match target {
341             // no_coverage on function is fine
342             Target::Fn
343             | Target::Closure
344             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
345
346             // function prototypes can't be covered
347             Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
348                 self.tcx.emit_spanned_lint(
349                     UNUSED_ATTRIBUTES,
350                     hir_id,
351                     attr.span,
352                     errors::IgnoredNoCoverageFnProto,
353                 );
354                 true
355             }
356
357             Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
358                 self.tcx.emit_spanned_lint(
359                     UNUSED_ATTRIBUTES,
360                     hir_id,
361                     attr.span,
362                     errors::IgnoredNoCoveragePropagate,
363                 );
364                 true
365             }
366
367             Target::Expression | Target::Statement | Target::Arm => {
368                 self.tcx.emit_spanned_lint(
369                     UNUSED_ATTRIBUTES,
370                     hir_id,
371                     attr.span,
372                     errors::IgnoredNoCoverageFnDefn,
373                 );
374                 true
375             }
376
377             _ => {
378                 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
379                     attr_span: attr.span,
380                     defn_span: span,
381                 });
382                 false
383             }
384         }
385     }
386
387     fn check_generic_attr(
388         &self,
389         hir_id: HirId,
390         attr: &Attribute,
391         target: Target,
392         allowed_target: Target,
393     ) {
394         if target != allowed_target {
395             self.tcx.emit_spanned_lint(
396                 UNUSED_ATTRIBUTES,
397                 hir_id,
398                 attr.span,
399                 OnlyHasEffectOn {
400                     attr_name: attr.name_or_empty(),
401                     target_name: allowed_target.name().replace(' ', "_"),
402                 },
403             );
404         }
405     }
406
407     /// Checks if `#[naked]` is applied to a function definition.
408     fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
409         match target {
410             Target::Fn
411             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
412             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
413             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
414             // erroneously allowed it and some crates used it accidentally, to be compatible
415             // with crates depending on them, we can't throw an error here.
416             Target::Field | Target::Arm | Target::MacroDef => {
417                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
418                 true
419             }
420             _ => {
421                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
422                     attr_span: attr.span,
423                     defn_span: span,
424                     on_crate: hir_id == CRATE_HIR_ID,
425                 });
426                 false
427             }
428         }
429     }
430
431     /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
432     fn check_cmse_nonsecure_entry(
433         &self,
434         hir_id: HirId,
435         attr: &Attribute,
436         span: Span,
437         target: Target,
438     ) -> bool {
439         match target {
440             Target::Fn
441             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
442             _ => {
443                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
444                     attr_span: attr.span,
445                     defn_span: span,
446                     on_crate: hir_id == CRATE_HIR_ID,
447                 });
448                 false
449             }
450         }
451     }
452
453     /// Debugging aid for `object_lifetime_default` query.
454     fn check_object_lifetime_default(&self, hir_id: HirId) {
455         let tcx = self.tcx;
456         if let Some(generics) = tcx.hir().get_generics(tcx.hir().local_def_id(hir_id)) {
457             for p in generics.params {
458                 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
459                 let default = tcx.object_lifetime_default(p.def_id);
460                 let repr = match default {
461                     ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
462                     ObjectLifetimeDefault::Static => "'static".to_owned(),
463                     ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
464                     ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
465                 };
466                 tcx.sess.emit_err(ObjectLifetimeErr { span: p.span, repr });
467             }
468         }
469     }
470
471     /// Checks if `#[collapse_debuginfo]` is applied to a macro.
472     fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) -> bool {
473         match target {
474             Target::MacroDef => true,
475             _ => {
476                 self.tcx
477                     .sess
478                     .emit_err(errors::CollapseDebuginfo { attr_span: attr.span, defn_span: span });
479                 false
480             }
481         }
482     }
483
484     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
485     fn check_track_caller(
486         &self,
487         hir_id: HirId,
488         attr_span: Span,
489         attrs: &[Attribute],
490         span: Span,
491         target: Target,
492     ) -> bool {
493         match target {
494             _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
495                 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
496                 false
497             }
498             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
499             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
500             // `#[track_caller]` attribute with just a lint, because we previously
501             // erroneously allowed it and some crates used it accidentally, to be compatible
502             // with crates depending on them, we can't throw an error here.
503             Target::Field | Target::Arm | Target::MacroDef => {
504                 for attr in attrs {
505                     self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
506                 }
507                 true
508             }
509             _ => {
510                 self.tcx.sess.emit_err(errors::TrackedCallerWrongLocation {
511                     attr_span,
512                     defn_span: span,
513                     on_crate: hir_id == CRATE_HIR_ID,
514                 });
515                 false
516             }
517         }
518     }
519
520     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
521     fn check_non_exhaustive(
522         &self,
523         hir_id: HirId,
524         attr: &Attribute,
525         span: Span,
526         target: Target,
527     ) -> bool {
528         match target {
529             Target::Struct | Target::Enum | Target::Variant => true,
530             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
531             // `#[non_exhaustive]` attribute with just a lint, because we previously
532             // erroneously allowed it and some crates used it accidentally, to be compatible
533             // with crates depending on them, we can't throw an error here.
534             Target::Field | Target::Arm | Target::MacroDef => {
535                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
536                 true
537             }
538             _ => {
539                 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
540                     attr_span: attr.span,
541                     defn_span: span,
542                 });
543                 false
544             }
545         }
546     }
547
548     /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
549     fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
550         match target {
551             Target::Trait => true,
552             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
553             // `#[marker]` attribute with just a lint, because we previously
554             // erroneously allowed it and some crates used it accidentally, to be compatible
555             // with crates depending on them, we can't throw an error here.
556             Target::Field | Target::Arm | Target::MacroDef => {
557                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
558                 true
559             }
560             _ => {
561                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
562                     attr_span: attr.span,
563                     defn_span: span,
564                 });
565                 false
566             }
567         }
568     }
569
570     /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
571     fn check_rustc_must_implement_one_of(
572         &self,
573         attr: &Attribute,
574         span: Span,
575         target: Target,
576     ) -> bool {
577         match target {
578             Target::Trait => true,
579             _ => {
580                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
581                     attr_span: attr.span,
582                     defn_span: span,
583                 });
584                 false
585             }
586         }
587     }
588
589     /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
590     fn check_target_feature(
591         &self,
592         hir_id: HirId,
593         attr: &Attribute,
594         span: Span,
595         target: Target,
596     ) -> bool {
597         match target {
598             Target::Fn
599             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
600             // FIXME: #[target_feature] was previously erroneously allowed on statements and some
601             // crates used this, so only emit a warning.
602             Target::Statement => {
603                 self.tcx.emit_spanned_lint(
604                     UNUSED_ATTRIBUTES,
605                     hir_id,
606                     attr.span,
607                     errors::TargetFeatureOnStatement,
608                 );
609                 true
610             }
611             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
612             // `#[target_feature]` attribute with just a lint, because we previously
613             // erroneously allowed it and some crates used it accidentally, to be compatible
614             // with crates depending on them, we can't throw an error here.
615             Target::Field | Target::Arm | Target::MacroDef => {
616                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
617                 true
618             }
619             _ => {
620                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
621                     attr_span: attr.span,
622                     defn_span: span,
623                     on_crate: hir_id == CRATE_HIR_ID,
624                 });
625                 false
626             }
627         }
628     }
629
630     /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
631     fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
632         match target {
633             Target::ForeignStatic | Target::Static => true,
634             _ => {
635                 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
636                     attr_span: attr.span,
637                     defn_span: span,
638                 });
639                 false
640             }
641         }
642     }
643
644     fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
645         self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
646     }
647
648     fn check_doc_alias_value(
649         &self,
650         meta: &NestedMetaItem,
651         doc_alias: Symbol,
652         hir_id: HirId,
653         target: Target,
654         is_list: bool,
655         aliases: &mut FxHashMap<String, Span>,
656     ) -> bool {
657         let tcx = self.tcx;
658         let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
659         let attr_str =
660             &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
661         if doc_alias == kw::Empty {
662             tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
663             return false;
664         }
665
666         let doc_alias_str = doc_alias.as_str();
667         if let Some(c) = doc_alias_str
668             .chars()
669             .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
670         {
671             tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
672             return false;
673         }
674         if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
675             tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
676             return false;
677         }
678
679         let span = meta.span();
680         if let Some(location) = match target {
681             Target::AssocTy => {
682                 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
683                 let containing_item = self.tcx.hir().expect_item(parent_def_id);
684                 if Target::from_item(containing_item) == Target::Impl {
685                     Some("type alias in implementation block")
686                 } else {
687                     None
688                 }
689             }
690             Target::AssocConst => {
691                 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
692                 let containing_item = self.tcx.hir().expect_item(parent_def_id);
693                 // We can't link to trait impl's consts.
694                 let err = "associated constant in trait implementation block";
695                 match containing_item.kind {
696                     ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
697                     _ => None,
698                 }
699             }
700             // we check the validity of params elsewhere
701             Target::Param => return false,
702             Target::Expression
703             | Target::Statement
704             | Target::Arm
705             | Target::ForeignMod
706             | Target::Closure
707             | Target::Impl => Some(target.name()),
708             Target::ExternCrate
709             | Target::Use
710             | Target::Static
711             | Target::Const
712             | Target::Fn
713             | Target::Mod
714             | Target::GlobalAsm
715             | Target::TyAlias
716             | Target::OpaqueTy
717             | Target::ImplTraitPlaceholder
718             | Target::Enum
719             | Target::Variant
720             | Target::Struct
721             | Target::Field
722             | Target::Union
723             | Target::Trait
724             | Target::TraitAlias
725             | Target::Method(..)
726             | Target::ForeignFn
727             | Target::ForeignStatic
728             | Target::ForeignTy
729             | Target::GenericParam(..)
730             | Target::MacroDef
731             | Target::PatField
732             | Target::ExprField => None,
733         } {
734             tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
735             return false;
736         }
737         let item_name = self.tcx.hir().name(hir_id);
738         if item_name == doc_alias {
739             tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
740             return false;
741         }
742         if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
743             self.tcx.emit_spanned_lint(
744                 UNUSED_ATTRIBUTES,
745                 hir_id,
746                 span,
747                 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
748             );
749         }
750         true
751     }
752
753     fn check_doc_alias(
754         &self,
755         meta: &NestedMetaItem,
756         hir_id: HirId,
757         target: Target,
758         aliases: &mut FxHashMap<String, Span>,
759     ) -> bool {
760         if let Some(values) = meta.meta_item_list() {
761             let mut errors = 0;
762             for v in values {
763                 match v.lit() {
764                     Some(l) => match l.kind {
765                         LitKind::Str(s, _) => {
766                             if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
767                                 errors += 1;
768                             }
769                         }
770                         _ => {
771                             self.tcx
772                                 .sess
773                                 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
774                             errors += 1;
775                         }
776                     },
777                     None => {
778                         self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
779                         errors += 1;
780                     }
781                 }
782             }
783             errors == 0
784         } else if let Some(doc_alias) = meta.value_str() {
785             self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
786         } else {
787             self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
788             false
789         }
790     }
791
792     fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
793         let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
794         if doc_keyword == kw::Empty {
795             self.doc_attr_str_error(meta, "keyword");
796             return false;
797         }
798         match self.tcx.hir().find(hir_id).and_then(|node| match node {
799             hir::Node::Item(item) => Some(&item.kind),
800             _ => None,
801         }) {
802             Some(ItemKind::Mod(ref module)) => {
803                 if !module.item_ids.is_empty() {
804                     self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
805                     return false;
806                 }
807             }
808             _ => {
809                 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
810                 return false;
811             }
812         }
813         if !rustc_lexer::is_ident(doc_keyword.as_str()) {
814             self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
815                 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
816                 doc_keyword,
817             });
818             return false;
819         }
820         true
821     }
822
823     fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
824         match self.tcx.hir().find(hir_id).and_then(|node| match node {
825             hir::Node::Item(item) => Some(&item.kind),
826             _ => None,
827         }) {
828             Some(ItemKind::Impl(ref i)) => {
829                 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
830                     || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
831                         bare_fn_ty.decl.inputs.len() == 1
832                     } else {
833                         false
834                     };
835                 if !is_valid {
836                     self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
837                     return false;
838                 }
839             }
840             _ => {
841                 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
842                 return false;
843             }
844         }
845         true
846     }
847
848     /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
849     ///
850     /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
851     /// if there are conflicting attributes for one item.
852     ///
853     /// `specified_inline` is used to keep track of whether we have
854     /// already seen an inlining attribute for this item.
855     /// If so, `specified_inline` holds the value and the span of
856     /// the first `inline`/`no_inline` attribute.
857     fn check_doc_inline(
858         &self,
859         attr: &Attribute,
860         meta: &NestedMetaItem,
861         hir_id: HirId,
862         target: Target,
863         specified_inline: &mut Option<(bool, Span)>,
864     ) -> bool {
865         if target == Target::Use || target == Target::ExternCrate {
866             let do_inline = meta.name_or_empty() == sym::inline;
867             if let Some((prev_inline, prev_span)) = *specified_inline {
868                 if do_inline != prev_inline {
869                     let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
870                     spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first);
871                     spans.push_span_label(meta.span(), fluent::passes_doc_inline_conflict_second);
872                     self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
873                     return false;
874                 }
875                 true
876             } else {
877                 *specified_inline = Some((do_inline, meta.span()));
878                 true
879             }
880         } else {
881             self.tcx.emit_spanned_lint(
882                 INVALID_DOC_ATTRIBUTES,
883                 hir_id,
884                 meta.span(),
885                 errors::DocInlineOnlyUse {
886                     attr_span: meta.span(),
887                     item_span: (attr.style == AttrStyle::Outer)
888                         .then(|| self.tcx.hir().span(hir_id)),
889                 },
890             );
891             false
892         }
893     }
894
895     /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
896     fn check_attr_not_crate_level(
897         &self,
898         meta: &NestedMetaItem,
899         hir_id: HirId,
900         attr_name: &str,
901     ) -> bool {
902         if CRATE_HIR_ID == hir_id {
903             self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
904             return false;
905         }
906         true
907     }
908
909     /// Checks that an attribute is used at the crate level. Returns `true` if valid.
910     fn check_attr_crate_level(
911         &self,
912         attr: &Attribute,
913         meta: &NestedMetaItem,
914         hir_id: HirId,
915     ) -> bool {
916         if hir_id != CRATE_HIR_ID {
917             self.tcx.struct_span_lint_hir(
918                 INVALID_DOC_ATTRIBUTES,
919                 hir_id,
920                 meta.span(),
921                 fluent::passes_attr_crate_level,
922                 |err| {
923                     if attr.style == AttrStyle::Outer
924                         && self.tcx.hir().get_parent_item(hir_id) == CRATE_OWNER_ID
925                     {
926                         if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
927                             src.insert(1, '!');
928                             err.span_suggestion_verbose(
929                                 attr.span,
930                                 fluent::suggestion,
931                                 src,
932                                 Applicability::MaybeIncorrect,
933                             );
934                         } else {
935                             err.span_help(attr.span, fluent::help);
936                         }
937                     }
938                     err.note(fluent::note);
939                     err
940                 },
941             );
942             return false;
943         }
944         true
945     }
946
947     /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
948     /// valid.
949     fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
950         let mut is_valid = true;
951         if let Some(metas) = meta.meta_item_list() {
952             for i_meta in metas {
953                 match i_meta.name_or_empty() {
954                     sym::attr | sym::no_crate_inject => {}
955                     _ => {
956                         self.tcx.emit_spanned_lint(
957                             INVALID_DOC_ATTRIBUTES,
958                             hir_id,
959                             i_meta.span(),
960                             errors::DocTestUnknown {
961                                 path: rustc_ast_pretty::pprust::path_to_string(
962                                     &i_meta.meta_item().unwrap().path,
963                                 ),
964                             },
965                         );
966                         is_valid = false;
967                     }
968                 }
969             }
970         } else {
971             self.tcx.emit_spanned_lint(
972                 INVALID_DOC_ATTRIBUTES,
973                 hir_id,
974                 meta.span(),
975                 errors::DocTestTakesList,
976             );
977             is_valid = false;
978         }
979         is_valid
980     }
981
982     /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes.
983     /// Returns `true` if valid.
984     fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
985         if meta.meta_item_list().is_some() {
986             true
987         } else {
988             self.tcx.emit_spanned_lint(
989                 INVALID_DOC_ATTRIBUTES,
990                 hir_id,
991                 meta.span(),
992                 errors::DocCfgHideTakesList,
993             );
994             false
995         }
996     }
997
998     /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
999     ///
1000     /// `specified_inline` should be initialized to `None` and kept for the scope
1001     /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1002     ///
1003     /// [`check_doc_inline`]: Self::check_doc_inline
1004     fn check_doc_attrs(
1005         &self,
1006         attr: &Attribute,
1007         hir_id: HirId,
1008         target: Target,
1009         specified_inline: &mut Option<(bool, Span)>,
1010         aliases: &mut FxHashMap<String, Span>,
1011     ) -> bool {
1012         let mut is_valid = true;
1013
1014         if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
1015             for meta in list {
1016                 if let Some(i_meta) = meta.meta_item() {
1017                     match i_meta.name_or_empty() {
1018                         sym::alias
1019                             if !self.check_attr_not_crate_level(meta, hir_id, "alias")
1020                                 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
1021                         {
1022                             is_valid = false
1023                         }
1024
1025                         sym::keyword
1026                             if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
1027                                 || !self.check_doc_keyword(meta, hir_id) =>
1028                         {
1029                             is_valid = false
1030                         }
1031
1032                         sym::fake_variadic
1033                             if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
1034                                 || !self.check_doc_fake_variadic(meta, hir_id) =>
1035                         {
1036                             is_valid = false
1037                         }
1038
1039                         sym::html_favicon_url
1040                         | sym::html_logo_url
1041                         | sym::html_playground_url
1042                         | sym::issue_tracker_base_url
1043                         | sym::html_root_url
1044                         | sym::html_no_source
1045                         | sym::test
1046                             if !self.check_attr_crate_level(attr, meta, hir_id) =>
1047                         {
1048                             is_valid = false;
1049                         }
1050
1051                         sym::cfg_hide
1052                             if !self.check_attr_crate_level(attr, meta, hir_id)
1053                                 || !self.check_doc_cfg_hide(meta, hir_id) =>
1054                         {
1055                             is_valid = false;
1056                         }
1057
1058                         sym::inline | sym::no_inline
1059                             if !self.check_doc_inline(
1060                                 attr,
1061                                 meta,
1062                                 hir_id,
1063                                 target,
1064                                 specified_inline,
1065                             ) =>
1066                         {
1067                             is_valid = false;
1068                         }
1069
1070                         // no_default_passes: deprecated
1071                         // passes: deprecated
1072                         // plugins: removed, but rustdoc warns about it itself
1073                         sym::alias
1074                         | sym::cfg
1075                         | sym::cfg_hide
1076                         | sym::hidden
1077                         | sym::html_favicon_url
1078                         | sym::html_logo_url
1079                         | sym::html_no_source
1080                         | sym::html_playground_url
1081                         | sym::html_root_url
1082                         | sym::inline
1083                         | sym::issue_tracker_base_url
1084                         | sym::keyword
1085                         | sym::masked
1086                         | sym::no_default_passes
1087                         | sym::no_inline
1088                         | sym::notable_trait
1089                         | sym::passes
1090                         | sym::plugins
1091                         | sym::fake_variadic => {}
1092
1093                         sym::test => {
1094                             if !self.check_test_attr(meta, hir_id) {
1095                                 is_valid = false;
1096                             }
1097                         }
1098
1099                         sym::primitive => {
1100                             if !self.tcx.features().rustdoc_internals {
1101                                 self.tcx.emit_spanned_lint(
1102                                     INVALID_DOC_ATTRIBUTES,
1103                                     hir_id,
1104                                     i_meta.span,
1105                                     errors::DocPrimitive,
1106                                 );
1107                             }
1108                         }
1109
1110                         _ => {
1111                             let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1112                             if i_meta.has_name(sym::spotlight) {
1113                                 self.tcx.emit_spanned_lint(
1114                                     INVALID_DOC_ATTRIBUTES,
1115                                     hir_id,
1116                                     i_meta.span,
1117                                     errors::DocTestUnknownSpotlight {
1118                                         path,
1119                                         span: i_meta.span
1120                                     }
1121                                 );
1122                             } else if i_meta.has_name(sym::include) &&
1123                                     let Some(value) = i_meta.value_str() {
1124                                 let applicability = if list.len() == 1 {
1125                                     Applicability::MachineApplicable
1126                                 } else {
1127                                     Applicability::MaybeIncorrect
1128                                 };
1129                                 // If there are multiple attributes, the suggestion would suggest
1130                                 // deleting all of them, which is incorrect.
1131                                 self.tcx.emit_spanned_lint(
1132                                     INVALID_DOC_ATTRIBUTES,
1133                                     hir_id,
1134                                     i_meta.span,
1135                                     errors::DocTestUnknownInclude {
1136                                         path,
1137                                         value: value.to_string(),
1138                                         inner: if attr.style == AttrStyle::Inner { "!" } else { "" },
1139                                         sugg: (attr.meta().unwrap().span, applicability),
1140                                     }
1141                                 );
1142                             } else {
1143                                 self.tcx.emit_spanned_lint(
1144                                     INVALID_DOC_ATTRIBUTES,
1145                                     hir_id,
1146                                     i_meta.span,
1147                                     errors::DocTestUnknownAny { path }
1148                                 );
1149                             }
1150                             is_valid = false;
1151                         }
1152                     }
1153                 } else {
1154                     self.tcx.emit_spanned_lint(
1155                         INVALID_DOC_ATTRIBUTES,
1156                         hir_id,
1157                         meta.span(),
1158                         errors::DocInvalid,
1159                     );
1160                     is_valid = false;
1161                 }
1162             }
1163         }
1164
1165         is_valid
1166     }
1167
1168     /// Warns against some misuses of `#[pass_by_value]`
1169     fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1170         match target {
1171             Target::Struct | Target::Enum | Target::TyAlias => true,
1172             _ => {
1173                 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1174                 false
1175             }
1176         }
1177     }
1178
1179     fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1180         match target {
1181             Target::Method(MethodKind::Inherent) => true,
1182             _ => {
1183                 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1184                 false
1185             }
1186         }
1187     }
1188
1189     fn check_has_incoherent_inherent_impls(
1190         &self,
1191         attr: &Attribute,
1192         span: Span,
1193         target: Target,
1194     ) -> bool {
1195         match target {
1196             Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1197                 true
1198             }
1199             _ => {
1200                 self.tcx
1201                     .sess
1202                     .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1203                 false
1204             }
1205         }
1206     }
1207
1208     /// Warns against some misuses of `#[must_use]`
1209     fn check_must_use(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool {
1210         if !matches!(
1211             target,
1212             Target::Fn
1213                 | Target::Enum
1214                 | Target::Struct
1215                 | Target::Union
1216                 | Target::Method(_)
1217                 | Target::ForeignFn
1218                 // `impl Trait` in return position can trip
1219                 // `unused_must_use` if `Trait` is marked as
1220                 // `#[must_use]`
1221                 | Target::Trait
1222         ) {
1223             let article = match target {
1224                 Target::ExternCrate
1225                 | Target::OpaqueTy
1226                 | Target::Enum
1227                 | Target::Impl
1228                 | Target::Expression
1229                 | Target::Arm
1230                 | Target::AssocConst
1231                 | Target::AssocTy => "an",
1232                 _ => "a",
1233             };
1234
1235             self.tcx.emit_spanned_lint(
1236                 UNUSED_ATTRIBUTES,
1237                 hir_id,
1238                 attr.span,
1239                 errors::MustUseNoEffect { article, target },
1240             );
1241         }
1242
1243         // For now, its always valid
1244         true
1245     }
1246
1247     /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1248     fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1249         match target {
1250             Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1251             _ => {
1252                 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1253                 false
1254             }
1255         }
1256     }
1257
1258     /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1259     fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1260         match target {
1261             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1262             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1263             // `#[cold]` attribute with just a lint, because we previously
1264             // erroneously allowed it and some crates used it accidentally, to be compatible
1265             // with crates depending on them, we can't throw an error here.
1266             Target::Field | Target::Arm | Target::MacroDef => {
1267                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1268             }
1269             _ => {
1270                 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1271                 // this, so only emit a warning.
1272                 self.tcx.emit_spanned_lint(
1273                     UNUSED_ATTRIBUTES,
1274                     hir_id,
1275                     attr.span,
1276                     errors::Cold { span, on_crate: hir_id == CRATE_HIR_ID },
1277                 );
1278             }
1279         }
1280     }
1281
1282     /// Checks if `#[link]` is applied to an item other than a foreign module.
1283     fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1284         if target == Target::ForeignMod
1285             && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1286             && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1287             && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1288         {
1289             return;
1290         }
1291
1292         self.tcx.emit_spanned_lint(
1293             UNUSED_ATTRIBUTES,
1294             hir_id,
1295             attr.span,
1296             errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1297         );
1298     }
1299
1300     /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1301     fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1302         match target {
1303             Target::ForeignFn | Target::ForeignStatic => {}
1304             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1305             // `#[link_name]` attribute with just a lint, because we previously
1306             // erroneously allowed it and some crates used it accidentally, to be compatible
1307             // with crates depending on them, we can't throw an error here.
1308             Target::Field | Target::Arm | Target::MacroDef => {
1309                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1310             }
1311             _ => {
1312                 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1313                 // used this, so only emit a warning.
1314                 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1315                 if let Some(s) = attr.value_str() {
1316                     self.tcx.emit_spanned_lint(
1317                         UNUSED_ATTRIBUTES,
1318                         hir_id,
1319                         attr.span,
1320                         errors::LinkName { span, attr_span, value: s.as_str() },
1321                     );
1322                 } else {
1323                     self.tcx.emit_spanned_lint(
1324                         UNUSED_ATTRIBUTES,
1325                         hir_id,
1326                         attr.span,
1327                         errors::LinkName { span, attr_span, value: "..." },
1328                     );
1329                 };
1330             }
1331         }
1332     }
1333
1334     /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1335     fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1336         match target {
1337             Target::ExternCrate => true,
1338             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1339             // `#[no_link]` attribute with just a lint, because we previously
1340             // erroneously allowed it and some crates used it accidentally, to be compatible
1341             // with crates depending on them, we can't throw an error here.
1342             Target::Field | Target::Arm | Target::MacroDef => {
1343                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1344                 true
1345             }
1346             _ => {
1347                 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1348                 false
1349             }
1350         }
1351     }
1352
1353     fn is_impl_item(&self, hir_id: HirId) -> bool {
1354         matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1355     }
1356
1357     /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1358     fn check_export_name(
1359         &self,
1360         hir_id: HirId,
1361         attr: &Attribute,
1362         span: Span,
1363         target: Target,
1364     ) -> bool {
1365         match target {
1366             Target::Static | Target::Fn => true,
1367             Target::Method(..) if self.is_impl_item(hir_id) => true,
1368             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1369             // `#[export_name]` attribute with just a lint, because we previously
1370             // erroneously allowed it and some crates used it accidentally, to be compatible
1371             // with crates depending on them, we can't throw an error here.
1372             Target::Field | Target::Arm | Target::MacroDef => {
1373                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1374                 true
1375             }
1376             _ => {
1377                 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1378                 false
1379             }
1380         }
1381     }
1382
1383     fn check_rustc_layout_scalar_valid_range(
1384         &self,
1385         attr: &Attribute,
1386         span: Span,
1387         target: Target,
1388     ) -> bool {
1389         if target != Target::Struct {
1390             self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1391                 attr_span: attr.span,
1392                 span,
1393             });
1394             return false;
1395         }
1396
1397         let Some(list) = attr.meta_item_list() else {
1398             return false;
1399         };
1400
1401         if matches!(&list[..], &[NestedMetaItem::Lit(MetaItemLit { kind: LitKind::Int(..), .. })]) {
1402             true
1403         } else {
1404             self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1405             false
1406         }
1407     }
1408
1409     /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1410     fn check_rustc_legacy_const_generics(
1411         &self,
1412         hir_id: HirId,
1413         attr: &Attribute,
1414         span: Span,
1415         target: Target,
1416         item: Option<ItemLike<'_>>,
1417     ) -> bool {
1418         let is_function = matches!(target, Target::Fn);
1419         if !is_function {
1420             self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1421                 attr_span: attr.span,
1422                 defn_span: span,
1423                 on_crate: hir_id == CRATE_HIR_ID,
1424             });
1425             return false;
1426         }
1427
1428         let Some(list) = attr.meta_item_list() else {
1429             // The attribute form is validated on AST.
1430             return false;
1431         };
1432
1433         let Some(ItemLike::Item(Item {
1434             kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1435             ..
1436         }))  = item else {
1437             bug!("should be a function item");
1438         };
1439
1440         for param in generics.params {
1441             match param.kind {
1442                 hir::GenericParamKind::Const { .. } => {}
1443                 _ => {
1444                     self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1445                         attr_span: attr.span,
1446                         param_span: param.span,
1447                     });
1448                     return false;
1449                 }
1450             }
1451         }
1452
1453         if list.len() != generics.params.len() {
1454             self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1455                 attr_span: attr.span,
1456                 generics_span: generics.span,
1457             });
1458             return false;
1459         }
1460
1461         let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1462         let mut invalid_args = vec![];
1463         for meta in list {
1464             if let Some(LitKind::Int(val, _)) = meta.lit().map(|lit| &lit.kind) {
1465                 if *val >= arg_count {
1466                     let span = meta.span();
1467                     self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1468                         span,
1469                         arg_count: arg_count as usize,
1470                     });
1471                     return false;
1472                 }
1473             } else {
1474                 invalid_args.push(meta.span());
1475             }
1476         }
1477
1478         if !invalid_args.is_empty() {
1479             self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1480             false
1481         } else {
1482             true
1483         }
1484     }
1485
1486     /// Helper function for checking that the provided attribute is only applied to a function or
1487     /// method.
1488     fn check_applied_to_fn_or_method(
1489         &self,
1490         hir_id: HirId,
1491         attr: &Attribute,
1492         span: Span,
1493         target: Target,
1494     ) -> bool {
1495         let is_function = matches!(target, Target::Fn | Target::Method(..));
1496         if !is_function {
1497             self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1498                 attr_span: attr.span,
1499                 defn_span: span,
1500                 on_crate: hir_id == CRATE_HIR_ID,
1501             });
1502             false
1503         } else {
1504             true
1505         }
1506     }
1507
1508     /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1509     /// or method.
1510     fn check_rustc_lint_query_instability(
1511         &self,
1512         hir_id: HirId,
1513         attr: &Attribute,
1514         span: Span,
1515         target: Target,
1516     ) -> bool {
1517         self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1518     }
1519
1520     /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1521     /// method.
1522     fn check_rustc_lint_diagnostics(
1523         &self,
1524         hir_id: HirId,
1525         attr: &Attribute,
1526         span: Span,
1527         target: Target,
1528     ) -> bool {
1529         self.check_applied_to_fn_or_method(hir_id, attr, span, target)
1530     }
1531
1532     /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1533     fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1534         match target {
1535             Target::Struct => true,
1536             _ => {
1537                 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1538                 false
1539             }
1540         }
1541     }
1542
1543     /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1544     fn check_rustc_lint_opt_deny_field_access(
1545         &self,
1546         attr: &Attribute,
1547         span: Span,
1548         target: Target,
1549     ) -> bool {
1550         match target {
1551             Target::Field => true,
1552             _ => {
1553                 self.tcx
1554                     .sess
1555                     .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1556                 false
1557             }
1558         }
1559     }
1560
1561     /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1562     /// option is passed to the compiler.
1563     fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1564         if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1565             true
1566         } else {
1567             self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1568             false
1569         }
1570     }
1571
1572     /// Checks if `#[link_section]` is applied to a function or static.
1573     fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1574         match target {
1575             Target::Static | Target::Fn | Target::Method(..) => {}
1576             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1577             // `#[link_section]` attribute with just a lint, because we previously
1578             // erroneously allowed it and some crates used it accidentally, to be compatible
1579             // with crates depending on them, we can't throw an error here.
1580             Target::Field | Target::Arm | Target::MacroDef => {
1581                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1582             }
1583             _ => {
1584                 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1585                 // crates used this, so only emit a warning.
1586                 self.tcx.emit_spanned_lint(
1587                     UNUSED_ATTRIBUTES,
1588                     hir_id,
1589                     attr.span,
1590                     errors::LinkSection { span },
1591                 );
1592             }
1593         }
1594     }
1595
1596     /// Checks if `#[no_mangle]` is applied to a function or static.
1597     fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1598         match target {
1599             Target::Static | Target::Fn => {}
1600             Target::Method(..) if self.is_impl_item(hir_id) => {}
1601             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1602             // `#[no_mangle]` attribute with just a lint, because we previously
1603             // erroneously allowed it and some crates used it accidentally, to be compatible
1604             // with crates depending on them, we can't throw an error here.
1605             Target::Field | Target::Arm | Target::MacroDef => {
1606                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1607             }
1608             // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1609             // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1610             // otherwise the error seems odd
1611             Target::ForeignFn | Target::ForeignStatic => {
1612                 let foreign_item_kind = match target {
1613                     Target::ForeignFn => "function",
1614                     Target::ForeignStatic => "static",
1615                     _ => unreachable!(),
1616                 };
1617                 self.tcx.emit_spanned_lint(
1618                     UNUSED_ATTRIBUTES,
1619                     hir_id,
1620                     attr.span,
1621                     errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1622                 );
1623             }
1624             _ => {
1625                 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1626                 // crates used this, so only emit a warning.
1627                 self.tcx.emit_spanned_lint(
1628                     UNUSED_ATTRIBUTES,
1629                     hir_id,
1630                     attr.span,
1631                     errors::NoMangle { span },
1632                 );
1633             }
1634         }
1635     }
1636
1637     /// Checks if the `#[repr]` attributes on `item` are valid.
1638     fn check_repr(
1639         &self,
1640         attrs: &[Attribute],
1641         span: Span,
1642         target: Target,
1643         item: Option<ItemLike<'_>>,
1644         hir_id: HirId,
1645     ) {
1646         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1647         // ```
1648         // #[repr(foo)]
1649         // #[repr(bar, align(8))]
1650         // ```
1651         let hints: Vec<_> = attrs
1652             .iter()
1653             .filter(|attr| attr.has_name(sym::repr))
1654             .filter_map(|attr| attr.meta_item_list())
1655             .flatten()
1656             .collect();
1657
1658         let mut int_reprs = 0;
1659         let mut is_c = false;
1660         let mut is_simd = false;
1661         let mut is_transparent = false;
1662
1663         for hint in &hints {
1664             if !hint.is_meta_item() {
1665                 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1666                 continue;
1667             }
1668
1669             match hint.name_or_empty() {
1670                 sym::C => {
1671                     is_c = true;
1672                     match target {
1673                         Target::Struct | Target::Union | Target::Enum => continue,
1674                         _ => {
1675                             self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1676                                 hint_span: hint.span(),
1677                                 span,
1678                             });
1679                         }
1680                     }
1681                 }
1682                 sym::align => {
1683                     if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1684                         feature_err(
1685                             &self.tcx.sess.parse_sess,
1686                             sym::fn_align,
1687                             hint.span(),
1688                             "`repr(align)` attributes on functions are unstable",
1689                         )
1690                         .emit();
1691                     }
1692
1693                     match target {
1694                         Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1695                         _ => {
1696                             self.tcx.sess.emit_err(AttrApplication::StructEnumFunctionUnion {
1697                                 hint_span: hint.span(),
1698                                 span,
1699                             });
1700                         }
1701                     }
1702                 }
1703                 sym::packed => {
1704                     if target != Target::Struct && target != Target::Union {
1705                         self.tcx.sess.emit_err(AttrApplication::StructUnion {
1706                             hint_span: hint.span(),
1707                             span,
1708                         });
1709                     } else {
1710                         continue;
1711                     }
1712                 }
1713                 sym::simd => {
1714                     is_simd = true;
1715                     if target != Target::Struct {
1716                         self.tcx
1717                             .sess
1718                             .emit_err(AttrApplication::Struct { hint_span: hint.span(), span });
1719                     } else {
1720                         continue;
1721                     }
1722                 }
1723                 sym::transparent => {
1724                     is_transparent = true;
1725                     match target {
1726                         Target::Struct | Target::Union | Target::Enum => continue,
1727                         _ => {
1728                             self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1729                                 hint_span: hint.span(),
1730                                 span,
1731                             });
1732                         }
1733                     }
1734                 }
1735                 sym::i8
1736                 | sym::u8
1737                 | sym::i16
1738                 | sym::u16
1739                 | sym::i32
1740                 | sym::u32
1741                 | sym::i64
1742                 | sym::u64
1743                 | sym::i128
1744                 | sym::u128
1745                 | sym::isize
1746                 | sym::usize => {
1747                     int_reprs += 1;
1748                     if target != Target::Enum {
1749                         self.tcx
1750                             .sess
1751                             .emit_err(AttrApplication::Enum { hint_span: hint.span(), span });
1752                     } else {
1753                         continue;
1754                     }
1755                 }
1756                 _ => {
1757                     self.tcx.sess.emit_err(UnrecognizedReprHint { span: hint.span() });
1758                     continue;
1759                 }
1760             };
1761         }
1762
1763         // Just point at all repr hints if there are any incompatibilities.
1764         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1765         let hint_spans = hints.iter().map(|hint| hint.span());
1766
1767         // Error on repr(transparent, <anything else>).
1768         if is_transparent && hints.len() > 1 {
1769             let hint_spans: Vec<_> = hint_spans.clone().collect();
1770             self.tcx
1771                 .sess
1772                 .emit_err(TransparentIncompatible { hint_spans, target: target.to_string() });
1773         }
1774         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1775         if (int_reprs > 1)
1776             || (is_simd && is_c)
1777             || (int_reprs == 1
1778                 && is_c
1779                 && item.map_or(false, |item| {
1780                     if let ItemLike::Item(item) = item {
1781                         return is_c_like_enum(item);
1782                     }
1783                     return false;
1784                 }))
1785         {
1786             self.tcx.emit_spanned_lint(
1787                 CONFLICTING_REPR_HINTS,
1788                 hir_id,
1789                 hint_spans.collect::<Vec<Span>>(),
1790                 errors::ReprConflicting,
1791             );
1792         }
1793     }
1794
1795     fn check_used(&self, attrs: &[Attribute], target: Target) {
1796         let mut used_linker_span = None;
1797         let mut used_compiler_span = None;
1798         for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1799             if target != Target::Static {
1800                 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1801             }
1802             let inner = attr.meta_item_list();
1803             match inner.as_deref() {
1804                 Some([item]) if item.has_name(sym::linker) => {
1805                     if used_linker_span.is_none() {
1806                         used_linker_span = Some(attr.span);
1807                     }
1808                 }
1809                 Some([item]) if item.has_name(sym::compiler) => {
1810                     if used_compiler_span.is_none() {
1811                         used_compiler_span = Some(attr.span);
1812                     }
1813                 }
1814                 Some(_) => {
1815                     // This error case is handled in rustc_hir_analysis::collect.
1816                 }
1817                 None => {
1818                     // Default case (compiler) when arg isn't defined.
1819                     if used_compiler_span.is_none() {
1820                         used_compiler_span = Some(attr.span);
1821                     }
1822                 }
1823             }
1824         }
1825         if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1826             self.tcx
1827                 .sess
1828                 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1829         }
1830     }
1831
1832     /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1833     /// (Allows proc_macro functions)
1834     fn check_allow_internal_unstable(
1835         &self,
1836         hir_id: HirId,
1837         attr: &Attribute,
1838         span: Span,
1839         target: Target,
1840         attrs: &[Attribute],
1841     ) -> bool {
1842         debug!("Checking target: {:?}", target);
1843         match target {
1844             Target::Fn => {
1845                 for attr in attrs {
1846                     if self.tcx.sess.is_proc_macro_attr(attr) {
1847                         debug!("Is proc macro attr");
1848                         return true;
1849                     }
1850                 }
1851                 debug!("Is not proc macro attr");
1852                 false
1853             }
1854             Target::MacroDef => true,
1855             // FIXME(#80564): We permit struct fields and match arms to have an
1856             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1857             // erroneously allowed it and some crates used it accidentally, to be compatible
1858             // with crates depending on them, we can't throw an error here.
1859             Target::Field | Target::Arm => {
1860                 self.inline_attr_str_error_without_macro_def(
1861                     hir_id,
1862                     attr,
1863                     "allow_internal_unstable",
1864                 );
1865                 true
1866             }
1867             _ => {
1868                 self.tcx
1869                     .sess
1870                     .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1871                 false
1872             }
1873         }
1874     }
1875
1876     /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1877     fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1878         match target {
1879             Target::Mod => {}
1880             _ => {
1881                 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1882                 return false;
1883             }
1884         }
1885
1886         let Some(hints) = attr.meta_item_list() else {
1887             self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1888             return false;
1889         };
1890
1891         let hint = match hints.len() {
1892             1 => &hints[0],
1893             _ => {
1894                 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1895                 return false;
1896             }
1897         };
1898
1899         let Some(meta_item) = hint.meta_item() else {
1900             self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1901             return false;
1902         };
1903
1904         let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1905             (sym::natvis_file, Some(value)) => value,
1906             (sym::gdb_script_file, Some(value)) => value,
1907             (_, _) => {
1908                 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1909                 return false;
1910             }
1911         };
1912
1913         let file =
1914             match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1915                 Ok(file) => file,
1916                 Err(mut err) => {
1917                     err.emit();
1918                     return false;
1919                 }
1920             };
1921
1922         match std::fs::File::open(&file) {
1923             Ok(_) => true,
1924             Err(error) => {
1925                 self.tcx.sess.emit_err(DebugVisualizerUnreadable {
1926                     span: meta_item.span,
1927                     file: &file,
1928                     error,
1929                 });
1930                 false
1931             }
1932         }
1933     }
1934
1935     /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1936     /// (Allows proc_macro functions)
1937     fn check_rustc_allow_const_fn_unstable(
1938         &self,
1939         hir_id: HirId,
1940         attr: &Attribute,
1941         span: Span,
1942         target: Target,
1943     ) -> bool {
1944         match target {
1945             Target::Fn | Target::Method(_)
1946                 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id).to_def_id()) =>
1947             {
1948                 true
1949             }
1950             // FIXME(#80564): We permit struct fields and match arms to have an
1951             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1952             // erroneously allowed it and some crates used it accidentally, to be compatible
1953             // with crates depending on them, we can't throw an error here.
1954             Target::Field | Target::Arm | Target::MacroDef => {
1955                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1956                 true
1957             }
1958             _ => {
1959                 self.tcx
1960                     .sess
1961                     .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
1962                 false
1963             }
1964         }
1965     }
1966
1967     fn check_rustc_std_internal_symbol(
1968         &self,
1969         attr: &Attribute,
1970         span: Span,
1971         target: Target,
1972     ) -> bool {
1973         match target {
1974             Target::Fn | Target::Static => true,
1975             _ => {
1976                 self.tcx
1977                     .sess
1978                     .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
1979                 false
1980             }
1981         }
1982     }
1983
1984     /// `#[const_trait]` only applies to traits.
1985     fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1986         match target {
1987             Target::Trait => true,
1988             _ => {
1989                 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1990                 false
1991             }
1992         }
1993     }
1994
1995     fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1996         match target {
1997             Target::Expression => {
1998                 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
1999                 false
2000             }
2001             _ => true,
2002         }
2003     }
2004
2005     fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
2006         match target {
2007             Target::ForeignFn | Target::ForeignStatic => true,
2008             _ => {
2009                 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
2010                 false
2011             }
2012         }
2013     }
2014
2015     fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
2016         match target {
2017             Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
2018                 self.tcx.emit_spanned_lint(
2019                     UNUSED_ATTRIBUTES,
2020                     hir_id,
2021                     attr.span,
2022                     errors::Deprecated,
2023                 );
2024             }
2025             _ => {}
2026         }
2027     }
2028
2029     fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2030         let name = attr.name_or_empty();
2031         match target {
2032             Target::ExternCrate | Target::Mod => {}
2033             _ => {
2034                 self.tcx.emit_spanned_lint(
2035                     UNUSED_ATTRIBUTES,
2036                     hir_id,
2037                     attr.span,
2038                     errors::MacroUse { name },
2039                 );
2040             }
2041         }
2042     }
2043
2044     fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2045         if target != Target::MacroDef {
2046             self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
2047         }
2048     }
2049
2050     fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2051         if target != Target::Fn {
2052             self.tcx.emit_spanned_lint(
2053                 UNUSED_ATTRIBUTES,
2054                 hir_id,
2055                 attr.span,
2056                 errors::PluginRegistrar,
2057             );
2058         }
2059     }
2060
2061     fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
2062         // Warn on useless empty attributes.
2063         let note = if matches!(
2064             attr.name_or_empty(),
2065             sym::macro_use
2066                 | sym::allow
2067                 | sym::expect
2068                 | sym::warn
2069                 | sym::deny
2070                 | sym::forbid
2071                 | sym::feature
2072                 | sym::repr
2073                 | sym::target_feature
2074         ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
2075         {
2076             errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
2077         } else if matches!(
2078                 attr.name_or_empty(),
2079                 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
2080             ) && let Some(meta) = attr.meta_item_list()
2081             && meta.len() == 1
2082             && let Some(item) = meta[0].meta_item()
2083             && let MetaItemKind::NameValue(_) = &item.kind
2084             && item.path == sym::reason
2085         {
2086             errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2087         } else if attr.name_or_empty() == sym::default_method_body_is_const {
2088             errors::UnusedNote::DefaultMethodBodyConst
2089         } else {
2090             return;
2091         };
2092
2093         self.tcx.emit_spanned_lint(
2094             UNUSED_ATTRIBUTES,
2095             hir_id,
2096             attr.span,
2097             errors::Unused { attr_span: attr.span, note },
2098         );
2099     }
2100
2101     /// A best effort attempt to create an error for a mismatching proc macro signature.
2102     ///
2103     /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
2104     fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
2105         let expected_input_count = match kind {
2106             ProcMacroKind::Attribute => 2,
2107             ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
2108         };
2109
2110         let expected_signature = match kind {
2111             ProcMacroKind::Attribute => "fn(TokenStream, TokenStream) -> TokenStream",
2112             ProcMacroKind::Derive | ProcMacroKind::FunctionLike => "fn(TokenStream) -> TokenStream",
2113         };
2114
2115         let tcx = self.tcx;
2116         if target == Target::Fn {
2117             let Some(tokenstream) = tcx.get_diagnostic_item(sym::TokenStream) else {return};
2118             let tokenstream = tcx.type_of(tokenstream);
2119
2120             let id = hir_id.expect_owner();
2121             let hir_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap();
2122
2123             let sig =
2124                 tcx.liberate_late_bound_regions(id.to_def_id(), tcx.fn_sig(id).subst_identity());
2125             let sig = tcx.normalize_erasing_regions(ParamEnv::empty(), sig);
2126
2127             // We don't currently require that the function signature is equal to
2128             // `fn(TokenStream) -> TokenStream`, but instead monomorphizes to
2129             // `fn(TokenStream) -> TokenStream` after some substitution of generic arguments.
2130             //
2131             // Properly checking this means pulling in additional `rustc` crates, so we don't.
2132             let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer };
2133
2134             if sig.abi != Abi::Rust {
2135                 tcx.sess.emit_err(ProcMacroInvalidAbi { span: hir_sig.span, abi: sig.abi.name() });
2136                 self.abort.set(true);
2137             }
2138
2139             if sig.unsafety == Unsafety::Unsafe {
2140                 tcx.sess.emit_err(ProcMacroUnsafe { span: hir_sig.span });
2141                 self.abort.set(true);
2142             }
2143
2144             let output = sig.output();
2145
2146             // Typecheck the output
2147             if !drcx.types_may_unify(output, tokenstream) {
2148                 tcx.sess.emit_err(ProcMacroTypeError {
2149                     span: hir_sig.decl.output.span(),
2150                     found: output,
2151                     kind,
2152                     expected_signature,
2153                 });
2154                 self.abort.set(true);
2155             }
2156
2157             if sig.inputs().len() < expected_input_count {
2158                 tcx.sess.emit_err(ProcMacroMissingArguments {
2159                     expected_input_count,
2160                     span: hir_sig.span,
2161                     kind,
2162                     expected_signature,
2163                 });
2164                 self.abort.set(true);
2165             }
2166
2167             // Check that the inputs are correct, if there are enough.
2168             if sig.inputs().len() >= expected_input_count {
2169                 for (arg, input) in
2170                     sig.inputs().iter().zip(hir_sig.decl.inputs).take(expected_input_count)
2171                 {
2172                     if !drcx.types_may_unify(*arg, tokenstream) {
2173                         tcx.sess.emit_err(ProcMacroTypeError {
2174                             span: input.span,
2175                             found: *arg,
2176                             kind,
2177                             expected_signature,
2178                         });
2179                         self.abort.set(true);
2180                     }
2181                 }
2182             }
2183
2184             // Check that there are not too many arguments
2185             let body_id = tcx.hir().body_owned_by(id.def_id);
2186             let excess = tcx.hir().body(body_id).params.get(expected_input_count..);
2187             if let Some(excess @ [begin @ end] | excess @ [begin, .., end]) = excess {
2188                 tcx.sess.emit_err(ProcMacroDiffArguments {
2189                     span: begin.span.to(end.span),
2190                     count: excess.len(),
2191                     kind,
2192                     expected_signature,
2193                 });
2194                 self.abort.set(true);
2195             }
2196         }
2197     }
2198 }
2199
2200 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2201     type NestedFilter = nested_filter::OnlyBodies;
2202
2203     fn nested_visit_map(&mut self) -> Self::Map {
2204         self.tcx.hir()
2205     }
2206
2207     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2208         // Historically we've run more checks on non-exported than exported macros,
2209         // so this lets us continue to run them while maintaining backwards compatibility.
2210         // In the long run, the checks should be harmonized.
2211         if let ItemKind::Macro(ref macro_def, _) = item.kind {
2212             let def_id = item.owner_id.to_def_id();
2213             if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
2214                 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2215             }
2216         }
2217
2218         let target = Target::from_item(item);
2219         self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2220         intravisit::walk_item(self, item)
2221     }
2222
2223     fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2224         let target = Target::from_generic_param(generic_param);
2225         self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2226         intravisit::walk_generic_param(self, generic_param)
2227     }
2228
2229     fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2230         let target = Target::from_trait_item(trait_item);
2231         self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2232         intravisit::walk_trait_item(self, trait_item)
2233     }
2234
2235     fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2236         self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2237         intravisit::walk_field_def(self, struct_field);
2238     }
2239
2240     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2241         self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2242         intravisit::walk_arm(self, arm);
2243     }
2244
2245     fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2246         let target = Target::from_foreign_item(f_item);
2247         self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2248         intravisit::walk_foreign_item(self, f_item)
2249     }
2250
2251     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2252         let target = target_from_impl_item(self.tcx, impl_item);
2253         self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2254         intravisit::walk_impl_item(self, impl_item)
2255     }
2256
2257     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2258         // When checking statements ignore expressions, they will be checked later.
2259         if let hir::StmtKind::Local(ref l) = stmt.kind {
2260             self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2261         }
2262         intravisit::walk_stmt(self, stmt)
2263     }
2264
2265     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2266         let target = match expr.kind {
2267             hir::ExprKind::Closure { .. } => Target::Closure,
2268             _ => Target::Expression,
2269         };
2270
2271         self.check_attributes(expr.hir_id, expr.span, target, None);
2272         intravisit::walk_expr(self, expr)
2273     }
2274
2275     fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2276         self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2277         intravisit::walk_expr_field(self, field)
2278     }
2279
2280     fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2281         self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2282         intravisit::walk_variant(self, variant)
2283     }
2284
2285     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2286         self.check_attributes(param.hir_id, param.span, Target::Param, None);
2287
2288         intravisit::walk_param(self, param);
2289     }
2290
2291     fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2292         self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2293         intravisit::walk_pat_field(self, field);
2294     }
2295 }
2296
2297 fn is_c_like_enum(item: &Item<'_>) -> bool {
2298     if let ItemKind::Enum(ref def, _) = item.kind {
2299         for variant in def.variants {
2300             match variant.data {
2301                 hir::VariantData::Unit(..) => { /* continue */ }
2302                 _ => return false,
2303             }
2304         }
2305         true
2306     } else {
2307         false
2308     }
2309 }
2310
2311 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2312 // from this check.
2313 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2314     // Check for builtin attributes at the crate level
2315     // which were unsuccessfully resolved due to cannot determine
2316     // resolution for the attribute macro error.
2317     const ATTRS_TO_CHECK: &[Symbol] = &[
2318         sym::macro_export,
2319         sym::repr,
2320         sym::path,
2321         sym::automatically_derived,
2322         sym::start,
2323         sym::rustc_main,
2324         sym::unix_sigpipe,
2325         sym::derive,
2326         sym::test,
2327         sym::test_case,
2328         sym::global_allocator,
2329         sym::bench,
2330     ];
2331
2332     for attr in attrs {
2333         // This function should only be called with crate attributes
2334         // which are inner attributes always but lets check to make sure
2335         if attr.style == AttrStyle::Inner {
2336             for attr_to_check in ATTRS_TO_CHECK {
2337                 if attr.has_name(*attr_to_check) {
2338                     tcx.sess.emit_err(InvalidAttrAtCrateLevel {
2339                         span: attr.span,
2340                         snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(),
2341                         name: *attr_to_check,
2342                     });
2343                 }
2344             }
2345         }
2346     }
2347 }
2348
2349 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2350     let attrs = tcx.hir().attrs(item.hir_id());
2351
2352     for attr in attrs {
2353         if attr.has_name(sym::inline) {
2354             tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2355         }
2356     }
2357 }
2358
2359 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2360     let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2361     tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2362     if module_def_id.is_top_level_module() {
2363         check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2364         check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2365     }
2366     if check_attr_visitor.abort.get() {
2367         tcx.sess.abort_if_errors()
2368     }
2369 }
2370
2371 pub(crate) fn provide(providers: &mut Providers) {
2372     *providers = Providers { check_mod_attrs, ..*providers };
2373 }
2374
2375 fn check_duplicates(
2376     tcx: TyCtxt<'_>,
2377     attr: &Attribute,
2378     hir_id: HirId,
2379     duplicates: AttributeDuplicates,
2380     seen: &mut FxHashMap<Symbol, Span>,
2381 ) {
2382     use AttributeDuplicates::*;
2383     if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2384         return;
2385     }
2386     match duplicates {
2387         DuplicatesOk => {}
2388         WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2389             match seen.entry(attr.name_or_empty()) {
2390                 Entry::Occupied(mut entry) => {
2391                     let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2392                         let to_remove = entry.insert(attr.span);
2393                         (to_remove, attr.span)
2394                     } else {
2395                         (attr.span, *entry.get())
2396                     };
2397                     tcx.emit_spanned_lint(
2398                         UNUSED_ATTRIBUTES,
2399                         hir_id,
2400                         this,
2401                         errors::UnusedDuplicate {
2402                             this,
2403                             other,
2404                             warning: matches!(
2405                                 duplicates,
2406                                 FutureWarnFollowing | FutureWarnPreceding
2407                             )
2408                             .then_some(()),
2409                         },
2410                     );
2411                 }
2412                 Entry::Vacant(entry) => {
2413                     entry.insert(attr.span);
2414                 }
2415             }
2416         }
2417         ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2418             Entry::Occupied(mut entry) => {
2419                 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2420                     let to_remove = entry.insert(attr.span);
2421                     (to_remove, attr.span)
2422                 } else {
2423                     (attr.span, *entry.get())
2424                 };
2425                 tcx.sess.emit_err(errors::UnusedMultiple {
2426                     this,
2427                     other,
2428                     name: attr.name_or_empty(),
2429                 });
2430             }
2431             Entry::Vacant(entry) => {
2432                 entry.insert(attr.span);
2433             }
2434         },
2435     }
2436 }