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