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