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