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