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