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