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