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