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