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