Skip to main content

rustc_passes/
check_attr.rs

1// FIXME(jdonszelmann): should become rustc_attr_validation
2//! This module implements some validity checks for attributes.
3//! In particular it verifies that `#[inline]` and `#[repr]` attributes are
4//! attached to items that actually support them and if there are
5//! conflicts between multiple such attributes attached to the same
6//! item.
7
8use std::cell::Cell;
9use std::collections::hash_map::Entry;
10use std::slice;
11
12use rustc_abi::ExternAbi;
13use rustc_ast::{AttrStyle, MetaItemKind, ast};
14use rustc_attr_parsing::{AttributeParser, Late};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::thin_vec::ThinVec;
17use rustc_data_structures::unord::UnordMap;
18use rustc_errors::{DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey, msg};
19use rustc_feature::{
20    ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP,
21    BuiltinAttribute,
22};
23use rustc_hir::attrs::diagnostic::Directive;
24use rustc_hir::attrs::{
25    AttributeKind, DocAttribute, DocInline, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
26    MirDialect, MirPhase, ReprAttr, SanitizerSet,
27};
28use rustc_hir::def::DefKind;
29use rustc_hir::def_id::LocalModDefId;
30use rustc_hir::intravisit::{self, Visitor};
31use rustc_hir::{
32    self as hir, Attribute, CRATE_HIR_ID, Constness, FnSig, ForeignItem, GenericParamKind, HirId,
33    Item, ItemKind, MethodKind, Node, ParamName, PartialConstStability, Safety, Stability,
34    StabilityLevel, Target, TraitItem, find_attr,
35};
36use rustc_macros::Diagnostic;
37use rustc_middle::hir::nested_filter;
38use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
39use rustc_middle::query::Providers;
40use rustc_middle::traits::ObligationCause;
41use rustc_middle::ty::error::{ExpectedFound, TypeError};
42use rustc_middle::ty::{self, TyCtxt, TypingMode};
43use rustc_middle::{bug, span_bug};
44use rustc_session::config::CrateType;
45use rustc_session::lint;
46use rustc_session::lint::builtin::{
47    CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
48    MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES,
49};
50use rustc_session::parse::feature_err;
51use rustc_span::edition::Edition;
52use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, sym};
53use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
54use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
55use rustc_trait_selection::traits::ObligationCtxt;
56
57use crate::errors;
58
59#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            DiagnosticOnUnimplementedOnlyForTraits where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    DiagnosticOnUnimplementedOnlyForTraits => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
60#[diag("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")]
61struct DiagnosticOnUnimplementedOnlyForTraits;
62
63#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            DiagnosticOnConstOnlyForTraitImpls where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    DiagnosticOnConstOnlyForTraitImpls { item_span: __binding_0
                        } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to trait impls")));
                        ;
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("not a trait impl")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
64#[diag("`#[diagnostic::on_const]` can only be applied to trait impls")]
65struct DiagnosticOnConstOnlyForTraitImpls {
66    #[label("not a trait impl")]
67    item_span: Span,
68}
69
70#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            DiagnosticOnConstOnlyForNonConstTraitImpls where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    DiagnosticOnConstOnlyForNonConstTraitImpls {
                        item_span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to non-const trait impls")));
                        ;
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait impl")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
71#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait impls")]
72struct DiagnosticOnConstOnlyForNonConstTraitImpls {
73    #[label("this is a const trait impl")]
74    item_span: Span,
75}
76
77fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
78    match impl_item.kind {
79        hir::ImplItemKind::Const(..) => Target::AssocConst,
80        hir::ImplItemKind::Fn(..) => {
81            let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
82            let containing_item = tcx.hir_expect_item(parent_def_id);
83            let containing_impl_is_for_trait = match &containing_item.kind {
84                hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
85                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("parent of an ImplItem must be an Impl"))bug!("parent of an ImplItem must be an Impl"),
86            };
87            if containing_impl_is_for_trait {
88                Target::Method(MethodKind::Trait { body: true })
89            } else {
90                Target::Method(MethodKind::Inherent)
91            }
92        }
93        hir::ImplItemKind::Type(..) => Target::AssocTy,
94    }
95}
96
97#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ItemLike<'tcx> {
    #[inline]
    fn clone(&self) -> ItemLike<'tcx> {
        let _: ::core::clone::AssertParamIsClone<&'tcx Item<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ItemLike<'tcx> { }Copy)]
98enum ItemLike<'tcx> {
99    Item(&'tcx Item<'tcx>),
100    ForeignItem,
101}
102
103#[derive(#[automatically_derived]
impl ::core::marker::Copy for ProcMacroKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProcMacroKind {
    #[inline]
    fn clone(&self) -> ProcMacroKind { *self }
}Clone)]
104pub(crate) enum ProcMacroKind {
105    FunctionLike,
106    Derive,
107    Attribute,
108}
109
110impl IntoDiagArg for ProcMacroKind {
111    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
112        match self {
113            ProcMacroKind::Attribute => "attribute proc macro",
114            ProcMacroKind::Derive => "derive proc macro",
115            ProcMacroKind::FunctionLike => "function-like proc macro",
116        }
117        .into_diag_arg(&mut None)
118    }
119}
120
121struct CheckAttrVisitor<'tcx> {
122    tcx: TyCtxt<'tcx>,
123
124    // Whether or not this visitor should abort after finding errors
125    abort: Cell<bool>,
126}
127
128impl<'tcx> CheckAttrVisitor<'tcx> {
129    fn dcx(&self) -> DiagCtxtHandle<'tcx> {
130        self.tcx.dcx()
131    }
132
133    /// Checks any attribute.
134    fn check_attributes(
135        &self,
136        hir_id: HirId,
137        span: Span,
138        target: Target,
139        item: Option<ItemLike<'_>>,
140    ) {
141        let mut seen = FxHashMap::default();
142        let attrs = self.tcx.hir_attrs(hir_id);
143        for attr in attrs {
144            let mut style = None;
145            match attr {
146                Attribute::Parsed(AttributeKind::ProcMacro(_)) => {
147                    self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
148                }
149                Attribute::Parsed(AttributeKind::ProcMacroAttribute(_)) => {
150                    self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
151                }
152                Attribute::Parsed(AttributeKind::ProcMacroDerive { .. }) => {
153                    self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
154                }
155                Attribute::Parsed(
156                    AttributeKind::Stability {
157                        span: attr_span,
158                        stability: Stability { level, feature },
159                    }
160                    | AttributeKind::RustcConstStability {
161                        span: attr_span,
162                        stability: PartialConstStability { level, feature, .. },
163                    },
164                ) => self.check_stability(*attr_span, span, level, *feature),
165                Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force { .. }, ..)) => {} // handled separately below
166                Attribute::Parsed(AttributeKind::Inline(kind, attr_span)) => {
167                    self.check_inline(hir_id, *attr_span, kind, target)
168                }
169                Attribute::Parsed(AttributeKind::LoopMatch(attr_span)) => {
170                    self.check_loop_match(hir_id, *attr_span, target)
171                }
172                Attribute::Parsed(AttributeKind::ConstContinue(attr_span)) => {
173                    self.check_const_continue(hir_id, *attr_span, target)
174                }
175                Attribute::Parsed(AttributeKind::AllowInternalUnsafe(attr_span) | AttributeKind::AllowInternalUnstable(.., attr_span)) => {
176                    self.check_macro_only_attr(*attr_span, span, target, attrs)
177                }
178                Attribute::Parsed(AttributeKind::RustcAllowConstFnUnstable(_, first_span)) => {
179                    self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
180                }
181                Attribute::Parsed(AttributeKind::Deprecated { span: attr_span, .. }) => {
182                    self.check_deprecated(hir_id, *attr_span, target)
183                }
184                Attribute::Parsed(AttributeKind::TargetFeature{ attr_span, ..}) => {
185                    self.check_target_feature(hir_id, *attr_span, target, attrs)
186                }
187                Attribute::Parsed(AttributeKind::RustcDumpObjectLifetimeDefaults) => {
188                    self.check_dump_object_lifetime_defaults(hir_id);
189                }
190                &Attribute::Parsed(AttributeKind::RustcPubTransparent(attr_span)) => {
191                    self.check_rustc_pub_transparent(attr_span, span, attrs)
192                }
193                Attribute::Parsed(AttributeKind::RustcAlign {..}) => {
194
195                }
196                Attribute::Parsed(AttributeKind::Naked(..)) => {
197                    self.check_naked(hir_id, target)
198                }
199                Attribute::Parsed(AttributeKind::TrackCaller(attr_span)) => {
200                    self.check_track_caller(hir_id, *attr_span, attrs, target)
201                }
202                Attribute::Parsed(AttributeKind::NonExhaustive(attr_span)) => {
203                    self.check_non_exhaustive(*attr_span, span, target, item)
204                }
205                &Attribute::Parsed(AttributeKind::FfiPure(attr_span)) => {
206                    self.check_ffi_pure(attr_span, attrs)
207                }
208                Attribute::Parsed(AttributeKind::MayDangle(attr_span)) => {
209                    self.check_may_dangle(hir_id, *attr_span)
210                }
211                &Attribute::Parsed(AttributeKind::CustomMir(dialect, phase, attr_span)) => {
212                    self.check_custom_mir(dialect, phase, attr_span)
213                }
214                &Attribute::Parsed(AttributeKind::Sanitize { on_set, off_set, rtsan: _, span: attr_span}) => {
215                    self.check_sanitize(attr_span, on_set | off_set, span, target);
216                },
217                Attribute::Parsed(AttributeKind::Link(_, attr_span)) => {
218                    self.check_link(hir_id, *attr_span, span, target)
219                },
220                Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
221                    self.check_macro_export(hir_id, *span, target)
222                },
223                Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics{attr_span, fn_indexes}) => {
224                    self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
225                },
226                Attribute::Parsed(AttributeKind::Doc(attr)) => self.check_doc_attrs(attr, hir_id, target),
227                Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
228                     self.check_eii_impl(impls, target)
229                },
230                Attribute::Parsed(AttributeKind::RustcMustImplementOneOf { attr_span, fn_names }) => {
231                    self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id,target)
232                },
233                Attribute::Parsed(AttributeKind::DoNotRecommend{attr_span}) => {self.check_do_not_recommend(*attr_span, hir_id, target, item)},
234                Attribute::Parsed(AttributeKind::OnUnimplemented{span, directive}) => {self.check_diagnostic_on_unimplemented(*span, hir_id, target,directive.as_deref())},
235                Attribute::Parsed(AttributeKind::OnConst{span, ..}) => {self.check_diagnostic_on_const(*span, hir_id, target, item)}
236                Attribute::Parsed(
237                    // tidy-alphabetical-start
238                    AttributeKind::RustcAllowIncoherentImpl(..)
239                    | AttributeKind::AutomaticallyDerived(..)
240                    | AttributeKind::CfgAttrTrace
241                    | AttributeKind::CfgTrace(..)
242                    | AttributeKind::CfiEncoding { .. }
243                    | AttributeKind::Cold(..)
244                    | AttributeKind::CollapseDebugInfo(..)
245                    | AttributeKind::CompilerBuiltins
246                    | AttributeKind::Coroutine(..)
247                    | AttributeKind::Coverage (..)
248                    | AttributeKind::CrateName { .. }
249                    | AttributeKind::CrateType(..)
250                    | AttributeKind::DebuggerVisualizer(..)
251                    | AttributeKind::DefaultLibAllocator
252                    // `#[doc]` is actually a lot more than just doc comments, so is checked below
253                    | AttributeKind::DocComment {..}
254                    | AttributeKind::EiiDeclaration { .. }
255                    | AttributeKind::ExportName { .. }
256                    | AttributeKind::ExportStable
257                    | AttributeKind::Feature(..)
258                    | AttributeKind::FfiConst(..)
259                    | AttributeKind::Fundamental
260                    | AttributeKind::Ignore { .. }
261                    | AttributeKind::InstructionSet(..)
262                    | AttributeKind::Lang(..)
263                    | AttributeKind::LinkName { .. }
264                    | AttributeKind::LinkOrdinal { .. }
265                    | AttributeKind::LinkSection { .. }
266                    | AttributeKind::Linkage(..)
267                    | AttributeKind::MacroEscape( .. )
268                    | AttributeKind::MacroUse { .. }
269                    | AttributeKind::Marker(..)
270                    | AttributeKind::MoveSizeLimit { .. }
271                    | AttributeKind::MustNotSupend { .. }
272                    | AttributeKind::MustUse { .. }
273                    | AttributeKind::NeedsAllocator
274                    | AttributeKind::NeedsPanicRuntime
275                    | AttributeKind::NoBuiltins
276                    | AttributeKind::NoCore { .. }
277                    | AttributeKind::NoImplicitPrelude(..)
278                    | AttributeKind::NoLink
279                    | AttributeKind::NoMain
280                    | AttributeKind::NoMangle(..)
281                    | AttributeKind::NoStd { .. }
282                    | AttributeKind::Optimize(..)
283                    | AttributeKind::PanicRuntime
284                    | AttributeKind::PatchableFunctionEntry { .. }
285                    | AttributeKind::Path(..)
286                    | AttributeKind::PatternComplexityLimit { .. }
287                    | AttributeKind::PinV2(..)
288                    | AttributeKind::Pointee(..)
289                    | AttributeKind::PreludeImport
290                    | AttributeKind::ProfilerRuntime
291                    | AttributeKind::RecursionLimit { .. }
292                    | AttributeKind::ReexportTestHarnessMain(..)
293                    | AttributeKind::RegisterTool(..)
294                    // handled below this loop and elsewhere
295                    | AttributeKind::Repr { .. }
296                    | AttributeKind::RustcAbi { .. }
297                    | AttributeKind::RustcAllocator
298                    | AttributeKind::RustcAllocatorZeroed
299                    | AttributeKind::RustcAllocatorZeroedVariant { .. }
300                    | AttributeKind::RustcAsPtr(..)
301                    | AttributeKind::RustcAutodiff(..)
302                    | AttributeKind::RustcBodyStability { .. }
303                    | AttributeKind::RustcBuiltinMacro { .. }
304                    | AttributeKind::RustcCaptureAnalysis
305                    | AttributeKind::RustcCguTestAttr(..)
306                    | AttributeKind::RustcClean(..)
307                    | AttributeKind::RustcCoherenceIsCore(..)
308                    | AttributeKind::RustcCoinductive(..)
309                    | AttributeKind::RustcConfusables { .. }
310                    | AttributeKind::RustcConstStableIndirect
311                    | AttributeKind::RustcConversionSuggestion
312                    | AttributeKind::RustcDeallocator
313                    | AttributeKind::RustcDefPath(..)
314                    | AttributeKind::RustcDelayedBugFromInsideQuery
315                    | AttributeKind::RustcDenyExplicitImpl(..)
316                    | AttributeKind::RustcDeprecatedSafe2024 {..}
317                    | AttributeKind::RustcDiagnosticItem(..)
318                    | AttributeKind::RustcDoNotConstCheck
319                    | AttributeKind::RustcDocPrimitive(..)
320                    | AttributeKind::RustcDummy
321                    | AttributeKind::RustcDumpDefParents
322                    | AttributeKind::RustcDumpInferredOutlives
323                    | AttributeKind::RustcDumpItemBounds
324                    | AttributeKind::RustcDumpPredicates
325                    | AttributeKind::RustcDumpUserArgs
326                    | AttributeKind::RustcDumpVariances
327                    | AttributeKind::RustcDumpVariancesOfOpaques
328                    | AttributeKind::RustcDumpVtable(..)
329                    | AttributeKind::RustcDynIncompatibleTrait(..)
330                    | AttributeKind::RustcEffectiveVisibility
331                    | AttributeKind::RustcEiiForeignItem
332                    | AttributeKind::RustcEvaluateWhereClauses
333                    | AttributeKind::RustcHasIncoherentInherentImpls
334                    | AttributeKind::RustcHiddenTypeOfOpaques
335                    | AttributeKind::RustcIfThisChanged(..)
336                    | AttributeKind::RustcInheritOverflowChecks
337                    | AttributeKind::RustcInsignificantDtor
338                    | AttributeKind::RustcIntrinsic
339                    | AttributeKind::RustcIntrinsicConstStableIndirect
340                    | AttributeKind::RustcLayout(..)
341                    | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
342                    | AttributeKind::RustcLayoutScalarValidRangeStart(..)
343                    | AttributeKind::RustcLintOptDenyFieldAccess { .. }
344                    | AttributeKind::RustcLintOptTy
345                    | AttributeKind::RustcLintQueryInstability
346                    | AttributeKind::RustcLintUntrackedQueryInformation
347                    | AttributeKind::RustcMacroTransparency(_)
348                    | AttributeKind::RustcMain
349                    | AttributeKind::RustcMir(_)
350                    | AttributeKind::RustcNeverReturnsNullPtr
351                    | AttributeKind::RustcNeverTypeOptions {..}
352                    | AttributeKind::RustcNoImplicitAutorefs
353                    | AttributeKind::RustcNoImplicitBounds
354                    | AttributeKind::RustcNoMirInline
355                    | AttributeKind::RustcNonConstTraitMethod
356                    | AttributeKind::RustcNonnullOptimizationGuaranteed
357                    | AttributeKind::RustcNounwind
358                    | AttributeKind::RustcObjcClass { .. }
359                    | AttributeKind::RustcObjcSelector { .. }
360                    | AttributeKind::RustcOffloadKernel
361                    | AttributeKind::RustcParenSugar(..)
362                    | AttributeKind::RustcPassByValue (..)
363                    | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)
364                    | AttributeKind::RustcPreserveUbChecks
365                    | AttributeKind::RustcProcMacroDecls
366                    | AttributeKind::RustcReallocator
367                    | AttributeKind::RustcRegions
368                    | AttributeKind::RustcReservationImpl(..)
369                    | AttributeKind::RustcScalableVector { .. }
370                    | AttributeKind::RustcShouldNotBeCalledOnConstItems(..)
371                    | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
372                    | AttributeKind::RustcSkipDuringMethodDispatch { .. }
373                    | AttributeKind::RustcSpecializationTrait(..)
374                    | AttributeKind::RustcStdInternalSymbol (..)
375                    | AttributeKind::RustcStrictCoherence(..)
376                    | AttributeKind::RustcSymbolName(..)
377                    | AttributeKind::RustcTestMarker(..)
378                    | AttributeKind::RustcThenThisWouldNeed(..)
379                    | AttributeKind::RustcTrivialFieldReads
380                    | AttributeKind::RustcUnsafeSpecializationMarker(..)
381                    | AttributeKind::ShouldPanic { .. }
382                    | AttributeKind::TestRunner(..)
383                    | AttributeKind::ThreadLocal
384                    | AttributeKind::TypeLengthLimit { .. }
385                    | AttributeKind::UnstableFeatureBound(..)
386                    | AttributeKind::Used { .. }
387                    | AttributeKind::WindowsSubsystem(..)
388                    // tidy-alphabetical-end
389                ) => { /* do nothing  */ }
390                Attribute::Unparsed(attr_item) => {
391                    style = Some(attr_item.style);
392                    match attr.path().as_slice() {
393                        [
394                            // ok
395                            sym::allow
396                            | sym::expect
397                            | sym::warn
398                            | sym::deny
399                            | sym::forbid,
400                            ..
401                        ] => {}
402                        [name, rest@..] => {
403                            match BUILTIN_ATTRIBUTE_MAP.get(name) {
404                                Some(_) => {
405                                    if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
406                                        // Check if we tried to use a builtin attribute as an attribute namespace, like `#[must_use::skip]`.
407                                        // This check is here to solve https://github.com/rust-lang/rust/issues/137590
408                                        // An error is already produced for this case elsewhere
409                                        continue
410                                    }
411
412                                    ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
    format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
        name))span_bug!(
413                                        attr.span(),
414                                        "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
415                                    )
416                                }
417                                None => (),
418                            }
419                        }
420                        [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
421                    }
422                }
423            }
424
425            if hir_id != CRATE_HIR_ID {
426                match attr {
427                    Attribute::Parsed(_) => { /* Already validated. */ }
428                    Attribute::Unparsed(attr) => {
429                        // FIXME(jdonszelmann): remove once all crate-level attrs are parsed and caught by
430                        // the above
431                        if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
432                            attr.path
433                                .segments
434                                .first()
435                                .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
436                        {
437                            match attr.style {
438                                ast::AttrStyle::Outer => {
439                                    let attr_span = attr.span;
440                                    let bang_position = self
441                                        .tcx
442                                        .sess
443                                        .source_map()
444                                        .span_until_char(attr_span, '[')
445                                        .shrink_to_hi();
446
447                                    self.tcx.emit_node_span_lint(
448                                        UNUSED_ATTRIBUTES,
449                                        hir_id,
450                                        attr.span,
451                                        errors::OuterCrateLevelAttr {
452                                            suggestion: errors::OuterCrateLevelAttrSuggestion {
453                                                bang_position,
454                                            },
455                                        },
456                                    )
457                                }
458                                ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
459                                    UNUSED_ATTRIBUTES,
460                                    hir_id,
461                                    attr.span,
462                                    errors::InnerCrateLevelAttr,
463                                ),
464                            }
465                        }
466                    }
467                }
468            }
469
470            if let Attribute::Unparsed(unparsed_attr) = attr
471                && let Some(BuiltinAttribute { duplicates, .. }) =
472                    attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
473            {
474                check_duplicates(
475                    self.tcx,
476                    unparsed_attr.span,
477                    attr,
478                    hir_id,
479                    *duplicates,
480                    &mut seen,
481                );
482            }
483
484            self.check_unused_attribute(hir_id, attr, style)
485        }
486
487        self.check_repr(attrs, span, target, item, hir_id);
488        self.check_rustc_force_inline(hir_id, attrs, target);
489        self.check_mix_no_mangle_export(hir_id, attrs);
490    }
491
492    fn check_rustc_must_implement_one_of(
493        &self,
494        attr_span: Span,
495        list: &ThinVec<Ident>,
496        hir_id: HirId,
497        target: Target,
498    ) {
499        // Ignoring invalid targets because TyCtxt::associated_items emits bug if the target isn't valid
500        // the parser has already produced an error for the target being invalid
501        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Trait => true,
    _ => false,
}matches!(target, Target::Trait) {
502            return;
503        }
504
505        let def_id = hir_id.owner.def_id;
506
507        let items = self.tcx.associated_items(def_id);
508        // Check that all arguments of `#[rustc_must_implement_one_of]` reference
509        // functions in the trait with default implementations
510        for ident in list {
511            let item = items
512                .filter_by_name_unhygienic(ident.name)
513                .find(|item| item.ident(self.tcx) == *ident);
514
515            match item {
516                Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ty::AssocKind::Fn { .. } => true,
    _ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
517                    if !item.defaultness(self.tcx).has_value() {
518                        self.tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation {
519                            span: self.tcx.def_span(item.def_id),
520                            note_span: attr_span,
521                        });
522                    }
523                }
524                Some(item) => {
525                    self.dcx().emit_err(errors::MustImplementNotFunction {
526                        span: self.tcx.def_span(item.def_id),
527                        span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span },
528                        note: errors::MustImplementNotFunctionNote {},
529                    });
530                }
531                None => {
532                    self.dcx().emit_err(errors::FunctionNotFoundInTrait { span: ident.span });
533                }
534            }
535        }
536        // Check for duplicates
537
538        let mut set: UnordMap<Symbol, Span> = Default::default();
539
540        for ident in &*list {
541            if let Some(dup) = set.insert(ident.name, ident.span) {
542                self.tcx
543                    .dcx()
544                    .emit_err(errors::FunctionNamesDuplicated { spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [dup, ident.span]))vec![dup, ident.span] });
545            }
546        }
547    }
548
549    fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
550        for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
551            match target {
552                Target::Fn => {}
553                _ => {
554                    self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
555                }
556            }
557
558            if let EiiImplResolution::Macro(eii_macro) = resolution
559                && {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(*eii_macro) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
                                impl_unsafe, .. })) if *impl_unsafe => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.tcx, *eii_macro, EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
560                && !impl_marked_unsafe
561            {
562                self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
563                    span: *span,
564                    name: self.tcx.item_name(*eii_macro),
565                    suggestion: errors::EiiImplRequiresUnsafeSuggestion {
566                        left: inner_span.shrink_to_lo(),
567                        right: inner_span.shrink_to_hi(),
568                    },
569                });
570            }
571        }
572    }
573
574    /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl
575    fn check_do_not_recommend(
576        &self,
577        attr_span: Span,
578        hir_id: HirId,
579        target: Target,
580        item: Option<ItemLike<'_>>,
581    ) {
582        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Impl { .. } => true,
    _ => false,
}matches!(target, Target::Impl { .. })
583            || #[allow(non_exhaustive_omitted_patterns)] match item {
    Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl), .. }))
        if _impl.of_trait.is_none() => true,
    _ => false,
}matches!(
584                item,
585                Some(ItemLike::Item(hir::Item {  kind: hir::ItemKind::Impl(_impl),.. }))
586                    if _impl.of_trait.is_none()
587            )
588        {
589            self.tcx.emit_node_span_lint(
590                MISPLACED_DIAGNOSTIC_ATTRIBUTES,
591                hir_id,
592                attr_span,
593                errors::IncorrectDoNotRecommendLocation,
594            );
595        }
596    }
597
598    /// Checks if `#[diagnostic::on_unimplemented]` is applied to a trait definition
599    fn check_diagnostic_on_unimplemented(
600        &self,
601        attr_span: Span,
602        hir_id: HirId,
603        target: Target,
604        directive: Option<&Directive>,
605    ) {
606        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Trait => true,
    _ => false,
}matches!(target, Target::Trait) {
607            self.tcx.emit_node_span_lint(
608                MISPLACED_DIAGNOSTIC_ATTRIBUTES,
609                hir_id,
610                attr_span,
611                DiagnosticOnUnimplementedOnlyForTraits,
612            );
613        }
614
615        if let Some(directive) = directive {
616            if let Node::Item(Item {
617                kind: ItemKind::Trait(_, _, _, trait_name, generics, _, _),
618                ..
619            }) = self.tcx.hir_node(hir_id)
620            {
621                directive.visit_params(&mut |argument_name, span| {
622                    let has_generic = generics.params.iter().any(|p| {
623                        if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
624                            && let ParamName::Plain(name) = p.name
625                            && name.name == argument_name
626                        {
627                            true
628                        } else {
629                            false
630                        }
631                    });
632                    if !has_generic {
633                        self.tcx.emit_node_span_lint(
634                            MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
635                            hir_id,
636                            span,
637                            errors::UnknownFormatParameterForOnUnimplementedAttr {
638                                argument_name,
639                                trait_name: *trait_name,
640                                help: !directive.is_rustc_attr,
641                            },
642                        )
643                    }
644                })
645            }
646        }
647    }
648
649    /// Checks if `#[diagnostic::on_const]` is applied to a trait impl
650    fn check_diagnostic_on_const(
651        &self,
652        attr_span: Span,
653        hir_id: HirId,
654        target: Target,
655        item: Option<ItemLike<'_>>,
656    ) {
657        if target == (Target::Impl { of_trait: true }) {
658            match item.unwrap() {
659                ItemLike::Item(it) => match it.expect_impl().constness {
660                    Constness::Const => {
661                        let item_span = self.tcx.hir_span(hir_id);
662                        self.tcx.emit_node_span_lint(
663                            MISPLACED_DIAGNOSTIC_ATTRIBUTES,
664                            hir_id,
665                            attr_span,
666                            DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
667                        );
668                        return;
669                    }
670                    Constness::NotConst => return,
671                },
672                ItemLike::ForeignItem => {}
673            }
674        }
675        let item_span = self.tcx.hir_span(hir_id);
676        self.tcx.emit_node_span_lint(
677            MISPLACED_DIAGNOSTIC_ATTRIBUTES,
678            hir_id,
679            attr_span,
680            DiagnosticOnConstOnlyForTraitImpls { item_span },
681        );
682
683        // We don't check the validity of generic args here...whose generics would that be, anyway?
684        // The traits' or the impls'?
685    }
686
687    /// Checks if an `#[inline]` is applied to a function or a closure.
688    fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
689        match target {
690            Target::Fn
691            | Target::Closure
692            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
693                // `#[inline]` is ignored if the symbol must be codegened upstream because it's exported.
694                if let Some(did) = hir_id.as_owner()
695                    && self.tcx.def_kind(did).has_codegen_attrs()
696                    && kind != &InlineAttr::Never
697                {
698                    let attrs = self.tcx.codegen_fn_attrs(did);
699                    // Not checking naked as `#[inline]` is forbidden for naked functions anyways.
700                    if attrs.contains_extern_indicator() {
701                        self.tcx.emit_node_span_lint(
702                            UNUSED_ATTRIBUTES,
703                            hir_id,
704                            attr_span,
705                            errors::InlineIgnoredForExported,
706                        );
707                    }
708                }
709            }
710            _ => {}
711        }
712    }
713
714    /// Checks that the `#[sanitize(..)]` attribute is applied to a
715    /// function/closure/method, or to an impl block or module.
716    fn check_sanitize(
717        &self,
718        attr_span: Span,
719        set: SanitizerSet,
720        target_span: Span,
721        target: Target,
722    ) {
723        let mut not_fn_impl_mod = None;
724        let mut no_body = None;
725
726        match target {
727            Target::Fn
728            | Target::Closure
729            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
730            | Target::Impl { .. }
731            | Target::Mod => return,
732            Target::Static
733                // if we mask out the address bits, i.e. *only* address was set,
734                // we allow it
735                if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
736                    == SanitizerSet::empty() =>
737            {
738                return;
739            }
740
741            // These are "functions", but they aren't allowed because they don't
742            // have a body, so the usual explanation would be confusing.
743            Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
744                no_body = Some(target_span);
745            }
746
747            _ => {
748                not_fn_impl_mod = Some(target_span);
749            }
750        }
751
752        self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
753            attr_span,
754            not_fn_impl_mod,
755            no_body,
756            help: (),
757        });
758    }
759
760    /// Checks if `#[naked]` is applied to a function definition.
761    fn check_naked(&self, hir_id: HirId, target: Target) {
762        match target {
763            Target::Fn
764            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
765                let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
766                let abi = fn_sig.header.abi;
767                if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
768                    feature_err(
769                        &self.tcx.sess,
770                        sym::naked_functions_rustic_abi,
771                        fn_sig.span,
772                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
                abi.as_str()))
    })format!(
773                            "`#[naked]` is currently unstable on `extern \"{}\"` functions",
774                            abi.as_str()
775                        ),
776                    )
777                    .emit();
778                }
779            }
780            _ => {}
781        }
782    }
783
784    /// Debugging aid for the `object_lifetime_default` query.
785    fn check_dump_object_lifetime_defaults(&self, hir_id: HirId) {
786        let tcx = self.tcx;
787        if let Some(owner_id) = hir_id.as_owner()
788            && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
789        {
790            for p in generics.params {
791                let hir::GenericParamKind::Type { .. } = p.kind else { continue };
792                let default = tcx.object_lifetime_default(p.def_id);
793                let repr = match default {
794                    ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
795                    ObjectLifetimeDefault::Static => "'static".to_owned(),
796                    ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
797                    ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
798                };
799                tcx.dcx().span_err(p.span, repr);
800            }
801        }
802    }
803
804    /// Checks if a `#[track_caller]` is applied to a function.
805    fn check_track_caller(
806        &self,
807        hir_id: HirId,
808        attr_span: Span,
809        attrs: &[Attribute],
810        target: Target,
811    ) {
812        match target {
813            Target::Fn => {
814                // `#[track_caller]` is not valid on weak lang items because they are called via
815                // `extern` declarations and `#[track_caller]` would alter their ABI.
816                if let Some(item) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Lang(item, _)) => {
                    break 'done Some(item);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Lang(item, _) => item)
817                    && item.is_weak()
818                {
819                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
820
821                    self.dcx().emit_err(errors::LangItemWithTrackCaller {
822                        attr_span,
823                        name: item.name(),
824                        sig_span: sig.span,
825                    });
826                }
827
828                if let Some(impls) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
                    break 'done Some(impls);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, EiiImpls(impls) => impls) {
829                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
830                    for i in impls {
831                        let name = match i.resolution {
832                            EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
833                            EiiImplResolution::Known(decl) => decl.name.name,
834                            EiiImplResolution::Error(_eg) => continue,
835                        };
836                        self.dcx().emit_err(errors::EiiWithTrackCaller {
837                            attr_span,
838                            name,
839                            sig_span: sig.span,
840                        });
841                    }
842                }
843            }
844            _ => {}
845        }
846    }
847
848    /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid.
849    fn check_non_exhaustive(
850        &self,
851        attr_span: Span,
852        span: Span,
853        target: Target,
854        item: Option<ItemLike<'_>>,
855    ) {
856        match target {
857            Target::Struct => {
858                if let Some(ItemLike::Item(hir::Item {
859                    kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
860                    ..
861                })) = item
862                    && !fields.is_empty()
863                    && fields.iter().any(|f| f.default.is_some())
864                {
865                    self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
866                        attr_span,
867                        defn_span: span,
868                    });
869                }
870            }
871            _ => {}
872        }
873    }
874
875    /// Checks if the `#[target_feature]` attribute on `item` is valid.
876    fn check_target_feature(
877        &self,
878        hir_id: HirId,
879        attr_span: Span,
880        target: Target,
881        attrs: &[Attribute],
882    ) {
883        match target {
884            Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
885            | Target::Fn => {
886                // `#[target_feature]` is not allowed in lang items.
887                if let Some(lang_item) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Lang(lang, _)) => {
                    break 'done Some(lang);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Lang(lang, _) => lang)
888                    // Calling functions with `#[target_feature]` is
889                    // not unsafe on WASM, see #84988
890                    && !self.tcx.sess.target.is_like_wasm
891                    && !self.tcx.sess.opts.actually_rustdoc
892                {
893                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
894
895                    self.dcx().emit_err(errors::LangItemWithTargetFeature {
896                        attr_span,
897                        name: lang_item.name(),
898                        sig_span: sig.span,
899                    });
900                }
901            }
902            _ => {}
903        }
904    }
905
906    fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
907        if let Some(location) = match target {
908            Target::AssocTy => {
909                if let DefKind::Impl { .. } =
910                    self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
911                {
912                    Some("type alias in implementation block")
913                } else {
914                    None
915                }
916            }
917            Target::AssocConst => {
918                let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
919                let containing_item = self.tcx.hir_expect_item(parent_def_id);
920                // We can't link to trait impl's consts.
921                let err = "associated constant in trait implementation block";
922                match containing_item.kind {
923                    ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
924                    _ => None,
925                }
926            }
927            // we check the validity of params elsewhere
928            Target::Param => return,
929            Target::Expression
930            | Target::Statement
931            | Target::Arm
932            | Target::ForeignMod
933            | Target::Closure
934            | Target::Impl { .. }
935            | Target::WherePredicate => Some(target.name()),
936            Target::ExternCrate
937            | Target::Use
938            | Target::Static
939            | Target::Const
940            | Target::Fn
941            | Target::Mod
942            | Target::GlobalAsm
943            | Target::TyAlias
944            | Target::Enum
945            | Target::Variant
946            | Target::Struct
947            | Target::Field
948            | Target::Union
949            | Target::Trait
950            | Target::TraitAlias
951            | Target::Method(..)
952            | Target::ForeignFn
953            | Target::ForeignStatic
954            | Target::ForeignTy
955            | Target::GenericParam { .. }
956            | Target::MacroDef
957            | Target::PatField
958            | Target::ExprField
959            | Target::Crate
960            | Target::MacroCall
961            | Target::Delegation { .. } => None,
962        } {
963            self.tcx.dcx().emit_err(errors::DocAliasBadLocation { span, location });
964            return;
965        }
966        if self.tcx.hir_opt_name(hir_id) == Some(alias) {
967            self.tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str: alias });
968            return;
969        }
970    }
971
972    fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
973        let item_kind = match self.tcx.hir_node(hir_id) {
974            hir::Node::Item(item) => Some(&item.kind),
975            _ => None,
976        };
977        match item_kind {
978            Some(ItemKind::Impl(i)) => {
979                let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
980                    || if let Some(&[hir::GenericArg::Type(ty)]) = i
981                        .of_trait
982                        .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
983                        .map(|last_segment| last_segment.args().args)
984                    {
985                        #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
986                    } else {
987                        false
988                    };
989                if !is_valid {
990                    self.dcx().emit_err(errors::DocFakeVariadicNotValid { span });
991                }
992            }
993            _ => {
994                self.dcx().emit_err(errors::DocKeywordOnlyImpl { span });
995            }
996        }
997    }
998
999    fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
1000        let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
1001            self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
1002            return;
1003        };
1004        match item.kind {
1005            ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
1006                if generics.params.len() != 0 => {}
1007            ItemKind::Trait(_, _, _, _, generics, _, items)
1008                if generics.params.len() != 0
1009                    || items.iter().any(|item| {
1010                        #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(item.owner_id)
    {
    DefKind::AssocTy => true,
    _ => false,
}matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy)
1011                    }) => {}
1012            ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
1013            _ => {
1014                self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
1015            }
1016        }
1017    }
1018
1019    /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes.
1020    ///
1021    /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
1022    /// if there are conflicting attributes for one item.
1023    ///
1024    /// `specified_inline` is used to keep track of whether we have
1025    /// already seen an inlining attribute for this item.
1026    /// If so, `specified_inline` holds the value and the span of
1027    /// the first `inline`/`no_inline` attribute.
1028    fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
1029        let span = match inline {
1030            [] => return,
1031            [(_, span)] => *span,
1032            [(inline, span), rest @ ..] => {
1033                for (inline2, span2) in rest {
1034                    if inline2 != inline {
1035                        let mut spans = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [*span, *span2]))vec![*span, *span2]);
1036                        spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))msg!("this attribute..."));
1037                        spans.push_span_label(
1038                            *span2,
1039                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))msg!("{\".\"}..conflicts with this attribute"),
1040                        );
1041                        self.dcx().emit_err(errors::DocInlineConflict { spans });
1042                        return;
1043                    }
1044                }
1045                *span
1046            }
1047        };
1048
1049        match target {
1050            Target::Use | Target::ExternCrate => {}
1051            _ => {
1052                self.tcx.emit_node_span_lint(
1053                    INVALID_DOC_ATTRIBUTES,
1054                    hir_id,
1055                    span,
1056                    errors::DocInlineOnlyUse {
1057                        attr_span: span,
1058                        item_span: self.tcx.hir_span(hir_id),
1059                    },
1060                );
1061            }
1062        }
1063    }
1064
1065    fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
1066        if target != Target::ExternCrate {
1067            self.tcx.emit_node_span_lint(
1068                INVALID_DOC_ATTRIBUTES,
1069                hir_id,
1070                span,
1071                errors::DocMaskedOnlyExternCrate {
1072                    attr_span: span,
1073                    item_span: self.tcx.hir_span(hir_id),
1074                },
1075            );
1076            return;
1077        }
1078
1079        if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1080            self.tcx.emit_node_span_lint(
1081                INVALID_DOC_ATTRIBUTES,
1082                hir_id,
1083                span,
1084                errors::DocMaskedNotExternCrateSelf {
1085                    attr_span: span,
1086                    item_span: self.tcx.hir_span(hir_id),
1087                },
1088            );
1089        }
1090    }
1091
1092    fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1093        let item_kind = match self.tcx.hir_node(hir_id) {
1094            hir::Node::Item(item) => Some(&item.kind),
1095            _ => None,
1096        };
1097        match item_kind {
1098            Some(ItemKind::Mod(_, module)) => {
1099                if !module.item_ids.is_empty() {
1100                    self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod { span, attr_name });
1101                    return;
1102                }
1103            }
1104            _ => {
1105                self.dcx().emit_err(errors::DocKeywordAttributeNotMod { span, attr_name });
1106                return;
1107            }
1108        }
1109    }
1110
1111    /// Runs various checks on `#[doc]` attributes.
1112    ///
1113    /// `specified_inline` should be initialized to `None` and kept for the scope
1114    /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1115    ///
1116    /// [`check_doc_inline`]: Self::check_doc_inline
1117    fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1118        let DocAttribute {
1119            aliases,
1120            // valid pretty much anywhere, not checked here?
1121            // FIXME: should we?
1122            hidden: _,
1123            inline,
1124            // FIXME: currently unchecked
1125            cfg: _,
1126            // already checked in attr_parsing
1127            auto_cfg: _,
1128            // already checked in attr_parsing
1129            auto_cfg_change: _,
1130            fake_variadic,
1131            keyword,
1132            masked,
1133            // FIXME: currently unchecked
1134            notable_trait: _,
1135            search_unbox,
1136            // already checked in attr_parsing
1137            html_favicon_url: _,
1138            // already checked in attr_parsing
1139            html_logo_url: _,
1140            // already checked in attr_parsing
1141            html_playground_url: _,
1142            // already checked in attr_parsing
1143            html_root_url: _,
1144            // already checked in attr_parsing
1145            html_no_source: _,
1146            // already checked in attr_parsing
1147            issue_tracker_base_url: _,
1148            rust_logo,
1149            // allowed anywhere
1150            test_attrs: _,
1151            // already checked in attr_parsing
1152            no_crate_inject: _,
1153            attribute,
1154        } = attr;
1155
1156        for (alias, span) in aliases {
1157            self.check_doc_alias_value(*span, hir_id, target, *alias);
1158        }
1159
1160        if let Some((_, span)) = keyword {
1161            self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1162        }
1163        if let Some((_, span)) = attribute {
1164            self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1165        }
1166
1167        if let Some(span) = fake_variadic {
1168            self.check_doc_fake_variadic(*span, hir_id);
1169        }
1170
1171        if let Some(span) = search_unbox {
1172            self.check_doc_search_unbox(*span, hir_id);
1173        }
1174
1175        self.check_doc_inline(hir_id, target, inline);
1176
1177        if let Some(span) = rust_logo
1178            && !self.tcx.features().rustdoc_internals()
1179        {
1180            feature_err(
1181                &self.tcx.sess,
1182                sym::rustdoc_internals,
1183                *span,
1184                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `#[doc(rust_logo)]` attribute is used for Rust branding"))msg!("the `#[doc(rust_logo)]` attribute is used for Rust branding"),
1185            )
1186            .emit();
1187        }
1188
1189        if let Some(span) = masked {
1190            self.check_doc_masked(*span, hir_id, target);
1191        }
1192    }
1193
1194    fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1195        if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(FfiConst(_)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, FfiConst(_)) {
1196            // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1197            self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1198        }
1199    }
1200
1201    /// Checks if `#[may_dangle]` is applied to a lifetime or type generic parameter in `Drop` impl.
1202    fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1203        if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1204            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
        } => true,
    _ => false,
}matches!(
1205                param.kind,
1206                hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1207            )
1208            && #[allow(non_exhaustive_omitted_patterns)] match param.source {
    hir::GenericParamSource::Generics => true,
    _ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1209            && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1210            && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1211            && let hir::ItemKind::Impl(impl_) = item.kind
1212            && let Some(of_trait) = impl_.of_trait
1213            && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1214            && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1215        {
1216            return;
1217        }
1218
1219        self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1220    }
1221
1222    /// Checks if `#[link]` is applied to an item other than a foreign module.
1223    fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1224        if target == Target::ForeignMod
1225            && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1226            && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1227            && !#[allow(non_exhaustive_omitted_patterns)] match abi {
    ExternAbi::Rust => true,
    _ => false,
}matches!(abi, ExternAbi::Rust)
1228        {
1229            return;
1230        }
1231
1232        self.tcx.emit_node_span_lint(
1233            UNUSED_ATTRIBUTES,
1234            hir_id,
1235            attr_span,
1236            errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1237        );
1238    }
1239
1240    /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1241    fn check_rustc_legacy_const_generics(
1242        &self,
1243        item: Option<ItemLike<'_>>,
1244        attr_span: Span,
1245        index_list: &ThinVec<(usize, Span)>,
1246    ) {
1247        let Some(ItemLike::Item(Item {
1248            kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1249            ..
1250        })) = item
1251        else {
1252            // No error here, since it's already given by the parser
1253            return;
1254        };
1255
1256        for param in generics.params {
1257            match param.kind {
1258                hir::GenericParamKind::Const { .. } => {}
1259                _ => {
1260                    self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1261                        attr_span,
1262                        param_span: param.span,
1263                    });
1264                    return;
1265                }
1266            }
1267        }
1268
1269        if index_list.len() != generics.params.len() {
1270            self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1271                attr_span,
1272                generics_span: generics.span,
1273            });
1274            return;
1275        }
1276
1277        let arg_count = decl.inputs.len() + generics.params.len();
1278        for (index, span) in index_list {
1279            if *index >= arg_count {
1280                self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1281                    span: *span,
1282                    arg_count,
1283                });
1284            }
1285        }
1286    }
1287
1288    /// Checks if the `#[repr]` attributes on `item` are valid.
1289    fn check_repr(
1290        &self,
1291        attrs: &[Attribute],
1292        span: Span,
1293        target: Target,
1294        item: Option<ItemLike<'_>>,
1295        hir_id: HirId,
1296    ) {
1297        // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1298        // ```
1299        // #[repr(foo)]
1300        // #[repr(bar, align(8))]
1301        // ```
1302        let (reprs, first_attr_span) =
1303            {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Repr { reprs, first_span }) => {
                    break 'done Some((reprs.as_slice(), Some(*first_span)));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span)))
1304                .unwrap_or((&[], None));
1305
1306        let mut int_reprs = 0;
1307        let mut is_explicit_rust = false;
1308        let mut is_c = false;
1309        let mut is_simd = false;
1310        let mut is_transparent = false;
1311
1312        for (repr, repr_span) in reprs {
1313            match repr {
1314                ReprAttr::ReprRust => {
1315                    is_explicit_rust = true;
1316                    match target {
1317                        Target::Struct | Target::Union | Target::Enum => continue,
1318                        _ => {
1319                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1320                                hint_span: *repr_span,
1321                                span,
1322                            });
1323                        }
1324                    }
1325                }
1326                ReprAttr::ReprC => {
1327                    is_c = true;
1328                    match target {
1329                        Target::Struct | Target::Union | Target::Enum => continue,
1330                        _ => {
1331                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1332                                hint_span: *repr_span,
1333                                span,
1334                            });
1335                        }
1336                    }
1337                }
1338                ReprAttr::ReprAlign(..) => match target {
1339                    Target::Struct | Target::Union | Target::Enum => {}
1340                    Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1341                        self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1342                            span: *repr_span,
1343                            item: target.plural_name(),
1344                        });
1345                    }
1346                    Target::Static if self.tcx.features().static_align() => {
1347                        self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1348                            span: *repr_span,
1349                            item: target.plural_name(),
1350                        });
1351                    }
1352                    _ => {
1353                        self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1354                            hint_span: *repr_span,
1355                            span,
1356                        });
1357                    }
1358                },
1359                ReprAttr::ReprPacked(_) => {
1360                    if target != Target::Struct && target != Target::Union {
1361                        self.dcx().emit_err(errors::AttrApplication::StructUnion {
1362                            hint_span: *repr_span,
1363                            span,
1364                        });
1365                    } else {
1366                        continue;
1367                    }
1368                }
1369                ReprAttr::ReprSimd => {
1370                    is_simd = true;
1371                    if target != Target::Struct {
1372                        self.dcx().emit_err(errors::AttrApplication::Struct {
1373                            hint_span: *repr_span,
1374                            span,
1375                        });
1376                    } else {
1377                        continue;
1378                    }
1379                }
1380                ReprAttr::ReprTransparent => {
1381                    is_transparent = true;
1382                    match target {
1383                        Target::Struct | Target::Union | Target::Enum => continue,
1384                        _ => {
1385                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1386                                hint_span: *repr_span,
1387                                span,
1388                            });
1389                        }
1390                    }
1391                }
1392                ReprAttr::ReprInt(_) => {
1393                    int_reprs += 1;
1394                    if target != Target::Enum {
1395                        self.dcx().emit_err(errors::AttrApplication::Enum {
1396                            hint_span: *repr_span,
1397                            span,
1398                        });
1399                    } else {
1400                        continue;
1401                    }
1402                }
1403            };
1404        }
1405
1406        // catch `repr()` with no arguments, applied to an item (i.e. not `#![repr()]`)
1407        if let Some(first_attr_span) = first_attr_span
1408            && reprs.is_empty()
1409            && item.is_some()
1410        {
1411            match target {
1412                Target::Struct | Target::Union | Target::Enum => {}
1413                Target::Fn | Target::Method(_) => {
1414                    self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1415                        span: first_attr_span,
1416                        item: target.plural_name(),
1417                    });
1418                }
1419                _ => {
1420                    self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1421                        hint_span: first_attr_span,
1422                        span,
1423                    });
1424                }
1425            }
1426            return;
1427        }
1428
1429        // Just point at all repr hints if there are any incompatibilities.
1430        // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1431        let hint_spans = reprs.iter().map(|(_, span)| *span);
1432
1433        // Error on repr(transparent, <anything else>).
1434        if is_transparent && reprs.len() > 1 {
1435            let hint_spans = hint_spans.clone().collect();
1436            self.dcx().emit_err(errors::TransparentIncompatible {
1437                hint_spans,
1438                target: target.to_string(),
1439            });
1440        }
1441        // Error on `#[repr(transparent)]` in combination with
1442        // `#[rustc_pass_indirectly_in_non_rustic_abis]`
1443        if is_transparent
1444            && let Some(&pass_indirectly_span) =
1445                {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcPassIndirectlyInNonRusticAbis(span))
                    => {
                    break 'done Some(span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcPassIndirectlyInNonRusticAbis(span) => span)
1446        {
1447            self.dcx().emit_err(errors::TransparentIncompatible {
1448                hint_spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span, pass_indirectly_span]))vec![span, pass_indirectly_span],
1449                target: target.to_string(),
1450            });
1451        }
1452        if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1453            let hint_spans = hint_spans.clone().collect();
1454            self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1455        }
1456        // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1457        if (int_reprs > 1)
1458            || (is_simd && is_c)
1459            || (int_reprs == 1
1460                && is_c
1461                && item.is_some_and(|item| {
1462                    if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1463                }))
1464        {
1465            self.tcx.emit_node_span_lint(
1466                CONFLICTING_REPR_HINTS,
1467                hir_id,
1468                hint_spans.collect::<Vec<Span>>(),
1469                errors::ReprConflictingLint,
1470            );
1471        }
1472    }
1473
1474    /// Outputs an error for attributes that can only be applied to macros, such as
1475    /// `#[allow_internal_unsafe]` and `#[allow_internal_unstable]`.
1476    /// (Allows proc_macro functions)
1477    // FIXME(jdonszelmann): if possible, move to attr parsing
1478    fn check_macro_only_attr(
1479        &self,
1480        attr_span: Span,
1481        span: Span,
1482        target: Target,
1483        attrs: &[Attribute],
1484    ) {
1485        match target {
1486            Target::Fn => {
1487                for attr in attrs {
1488                    if attr.is_proc_macro_attr() {
1489                        // return on proc macros
1490                        return;
1491                    }
1492                }
1493                self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1494            }
1495            _ => {}
1496        }
1497    }
1498
1499    /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1500    /// (Allows proc_macro functions)
1501    fn check_rustc_allow_const_fn_unstable(
1502        &self,
1503        hir_id: HirId,
1504        attr_span: Span,
1505        span: Span,
1506        target: Target,
1507    ) {
1508        match target {
1509            Target::Fn | Target::Method(_) => {
1510                if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1511                    self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1512                }
1513            }
1514            _ => {}
1515        }
1516    }
1517
1518    fn check_stability(
1519        &self,
1520        attr_span: Span,
1521        item_span: Span,
1522        level: &StabilityLevel,
1523        feature: Symbol,
1524    ) {
1525        // Stable *language* features shouldn't be used as unstable library features.
1526        // (Not doing this for stable library features is checked by tidy.)
1527        if level.is_unstable()
1528            && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1529        {
1530            self.tcx
1531                .dcx()
1532                .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1533        }
1534    }
1535
1536    fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1537        match target {
1538            Target::AssocConst | Target::Method(..) | Target::AssocTy
1539                if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1540                    == DefKind::Impl { of_trait: true } =>
1541            {
1542                self.tcx.emit_node_span_lint(
1543                    UNUSED_ATTRIBUTES,
1544                    hir_id,
1545                    attr_span,
1546                    errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1547                );
1548            }
1549            _ => {}
1550        }
1551    }
1552
1553    fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1554        if target != Target::MacroDef {
1555            return;
1556        }
1557
1558        // special case when `#[macro_export]` is applied to a macro 2.0
1559        let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1560        let is_decl_macro = !macro_definition.macro_rules;
1561
1562        if is_decl_macro {
1563            self.tcx.emit_node_span_lint(
1564                UNUSED_ATTRIBUTES,
1565                hir_id,
1566                attr_span,
1567                errors::MacroExport::OnDeclMacro,
1568            );
1569        }
1570    }
1571
1572    fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1573        // Warn on useless empty attributes.
1574        // FIXME(jdonszelmann): this lint should be moved to attribute parsing, see `AcceptContext::warn_empty_attribute`
1575        let note =
1576            if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1577                && attr.meta_item_list().is_some_and(|list| list.is_empty())
1578            {
1579                errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1580            } else if attr.has_any_name(&[
1581                sym::allow,
1582                sym::warn,
1583                sym::deny,
1584                sym::forbid,
1585                sym::expect,
1586            ]) && let Some(meta) = attr.meta_item_list()
1587                && let [meta] = meta.as_slice()
1588                && let Some(item) = meta.meta_item()
1589                && let MetaItemKind::NameValue(_) = &item.kind
1590                && item.path == sym::reason
1591            {
1592                errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1593            } else if attr.has_any_name(&[
1594                sym::allow,
1595                sym::warn,
1596                sym::deny,
1597                sym::forbid,
1598                sym::expect,
1599            ]) && let Some(meta) = attr.meta_item_list()
1600                && meta.iter().any(|meta| {
1601                    meta.meta_item().map_or(false, |item| {
1602                        item.path == sym::linker_messages || item.path == sym::linker_info
1603                    })
1604                })
1605            {
1606                if hir_id != CRATE_HIR_ID {
1607                    match style {
1608                        Some(ast::AttrStyle::Outer) => {
1609                            let attr_span = attr.span();
1610                            let bang_position = self
1611                                .tcx
1612                                .sess
1613                                .source_map()
1614                                .span_until_char(attr_span, '[')
1615                                .shrink_to_hi();
1616
1617                            self.tcx.emit_node_span_lint(
1618                                UNUSED_ATTRIBUTES,
1619                                hir_id,
1620                                attr_span,
1621                                errors::OuterCrateLevelAttr {
1622                                    suggestion: errors::OuterCrateLevelAttrSuggestion {
1623                                        bang_position,
1624                                    },
1625                                },
1626                            )
1627                        }
1628                        Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1629                            UNUSED_ATTRIBUTES,
1630                            hir_id,
1631                            attr.span(),
1632                            errors::InnerCrateLevelAttr,
1633                        ),
1634                    };
1635                    return;
1636                } else {
1637                    let never_needs_link = self
1638                        .tcx
1639                        .crate_types()
1640                        .iter()
1641                        .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
    CrateType::Rlib | CrateType::StaticLib => true,
    _ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1642                    if never_needs_link {
1643                        errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1644                    } else {
1645                        return;
1646                    }
1647                }
1648            } else if attr.has_name(sym::default_method_body_is_const) {
1649                errors::UnusedNote::DefaultMethodBodyConst
1650            } else {
1651                return;
1652            };
1653
1654        self.tcx.emit_node_span_lint(
1655            UNUSED_ATTRIBUTES,
1656            hir_id,
1657            attr.span(),
1658            errors::Unused { attr_span: attr.span(), note },
1659        );
1660    }
1661
1662    /// A best effort attempt to create an error for a mismatching proc macro signature.
1663    ///
1664    /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
1665    fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1666        if target != Target::Fn {
1667            return;
1668        }
1669
1670        let tcx = self.tcx;
1671        let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1672            return;
1673        };
1674        let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1675            return;
1676        };
1677
1678        let def_id = hir_id.expect_owner().def_id;
1679        let param_env = ty::ParamEnv::empty();
1680
1681        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1682        let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1683
1684        let span = tcx.def_span(def_id);
1685        let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1686        let sig = tcx.liberate_late_bound_regions(
1687            def_id.to_def_id(),
1688            tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
1689        );
1690
1691        let mut cause = ObligationCause::misc(span, def_id);
1692        let sig = ocx.normalize(&cause, param_env, sig);
1693
1694        // proc macro is not WF.
1695        let errors = ocx.try_evaluate_obligations();
1696        if !errors.is_empty() {
1697            return;
1698        }
1699
1700        let expected_sig = tcx.mk_fn_sig(
1701            std::iter::repeat_n(
1702                token_stream,
1703                match kind {
1704                    ProcMacroKind::Attribute => 2,
1705                    ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1706                },
1707            ),
1708            token_stream,
1709            false,
1710            Safety::Safe,
1711            ExternAbi::Rust,
1712        );
1713
1714        if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1715            let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
1716
1717            let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1718            if let Some(hir_sig) = hir_sig {
1719                match terr {
1720                    TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1721                        if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1722                            diag.span(ty.span);
1723                            cause.span = ty.span;
1724                        } else if idx == hir_sig.decl.inputs.len() {
1725                            let span = hir_sig.decl.output.span();
1726                            diag.span(span);
1727                            cause.span = span;
1728                        }
1729                    }
1730                    TypeError::ArgCount => {
1731                        if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1732                            diag.span(ty.span);
1733                            cause.span = ty.span;
1734                        }
1735                    }
1736                    TypeError::SafetyMismatch(_) => {
1737                        // FIXME: Would be nice if we had a span here..
1738                    }
1739                    TypeError::AbiMismatch(_) => {
1740                        // FIXME: Would be nice if we had a span here..
1741                    }
1742                    TypeError::VariadicMismatch(_) => {
1743                        // FIXME: Would be nice if we had a span here..
1744                    }
1745                    _ => {}
1746                }
1747            }
1748
1749            infcx.err_ctxt().note_type_err(
1750                &mut diag,
1751                &cause,
1752                None,
1753                Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1754                    expected: ty::Binder::dummy(expected_sig),
1755                    found: ty::Binder::dummy(sig),
1756                }))),
1757                terr,
1758                false,
1759                None,
1760            );
1761            diag.emit();
1762            self.abort.set(true);
1763        }
1764
1765        let errors = ocx.evaluate_obligations_error_on_ambiguity();
1766        if !errors.is_empty() {
1767            infcx.err_ctxt().report_fulfillment_errors(errors);
1768            self.abort.set(true);
1769        }
1770    }
1771
1772    fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1773        if !{
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Repr { reprs, .. }) => {
                    break 'done
                        Some(reprs.iter().any(|(r, _)|
                                    r == &ReprAttr::ReprTransparent));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent))
1774            .unwrap_or(false)
1775        {
1776            self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
1777        }
1778    }
1779
1780    fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1781        if let (Target::Closure, None) = (
1782            target,
1783            {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Inline(InlineAttr::Force {
                    attr_span, .. }, _)) => {
                    break 'done Some(*attr_span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
1784        ) {
1785            let is_coro = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
    {
    hir::ExprKind::Closure(hir::Closure {
        kind: hir::ClosureKind::Coroutine(..) |
            hir::ClosureKind::CoroutineClosure(..), .. }) => true,
    _ => false,
}matches!(
1786                self.tcx.hir_expect_expr(hir_id).kind,
1787                hir::ExprKind::Closure(hir::Closure {
1788                    kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1789                    ..
1790                })
1791            );
1792            let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1793            let parent_span = self.tcx.def_span(parent_did);
1794
1795            if let Some(attr_span) = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in self.tcx.get_all_attrs(parent_did) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Inline(InlineAttr::Force {
                            attr_span, .. }, _)) => {
                            break 'done Some(*attr_span);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(
1796                self.tcx, parent_did,
1797                Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1798            ) && is_coro
1799            {
1800                self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
1801            }
1802        }
1803    }
1804
1805    fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1806        if let Some(export_name_span) =
1807            {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(ExportName {
                    span: export_name_span, .. }) => {
                    break 'done Some(*export_name_span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, ExportName { span: export_name_span, .. } => *export_name_span)
1808            && let Some(no_mangle_span) =
1809                {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(NoMangle(no_mangle_span)) => {
                    break 'done Some(*no_mangle_span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, NoMangle(no_mangle_span) => *no_mangle_span)
1810        {
1811            let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1812                "#[unsafe(no_mangle)]"
1813            } else {
1814                "#[no_mangle]"
1815            };
1816            let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1817                "#[unsafe(export_name)]"
1818            } else {
1819                "#[export_name]"
1820            };
1821
1822            self.tcx.emit_node_span_lint(
1823                lint::builtin::UNUSED_ATTRIBUTES,
1824                hir_id,
1825                no_mangle_span,
1826                errors::MixedExportNameAndNoMangle {
1827                    no_mangle_span,
1828                    export_name_span,
1829                    no_mangle_attr,
1830                    export_name_attr,
1831                },
1832            );
1833        }
1834    }
1835
1836    fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1837        let node_span = self.tcx.hir_span(hir_id);
1838
1839        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Expression => true,
    _ => false,
}matches!(target, Target::Expression) {
1840            return; // Handled in target checking during attr parse
1841        }
1842
1843        if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
    {
    hir::ExprKind::Loop(..) => true,
    _ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Loop(..)) {
1844            self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
1845        };
1846    }
1847
1848    fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1849        let node_span = self.tcx.hir_span(hir_id);
1850
1851        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Expression => true,
    _ => false,
}matches!(target, Target::Expression) {
1852            return; // Handled in target checking during attr parse
1853        }
1854
1855        if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
    {
    hir::ExprKind::Break(..) => true,
    _ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Break(..)) {
1856            self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
1857        };
1858    }
1859
1860    fn check_custom_mir(
1861        &self,
1862        dialect: Option<(MirDialect, Span)>,
1863        phase: Option<(MirPhase, Span)>,
1864        attr_span: Span,
1865    ) {
1866        let Some((dialect, dialect_span)) = dialect else {
1867            if let Some((_, phase_span)) = phase {
1868                self.dcx()
1869                    .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
1870            }
1871            return;
1872        };
1873
1874        match dialect {
1875            MirDialect::Analysis => {
1876                if let Some((MirPhase::Optimized, phase_span)) = phase {
1877                    self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1878                        dialect,
1879                        phase: MirPhase::Optimized,
1880                        attr_span,
1881                        dialect_span,
1882                        phase_span,
1883                    });
1884                }
1885            }
1886
1887            MirDialect::Built => {
1888                if let Some((phase, phase_span)) = phase {
1889                    self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1890                        dialect,
1891                        phase,
1892                        attr_span,
1893                        dialect_span,
1894                        phase_span,
1895                    });
1896                }
1897            }
1898            MirDialect::Runtime => {}
1899        }
1900    }
1901}
1902
1903impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1904    type NestedFilter = nested_filter::OnlyBodies;
1905
1906    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1907        self.tcx
1908    }
1909
1910    fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1911        // Historically we've run more checks on non-exported than exported macros,
1912        // so this lets us continue to run them while maintaining backwards compatibility.
1913        // In the long run, the checks should be harmonized.
1914        if let ItemKind::Macro(_, macro_def, _) = item.kind {
1915            let def_id = item.owner_id.to_def_id();
1916            if macro_def.macro_rules && !{

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(MacroExport { .. }) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.tcx, def_id, MacroExport { .. }) {
1917                check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1918            }
1919        }
1920
1921        let target = Target::from_item(item);
1922        self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1923        intravisit::walk_item(self, item)
1924    }
1925
1926    fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1927        // FIXME(where_clause_attrs): Currently, as the following check shows,
1928        // only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
1929        // if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
1930        // in where clauses. After that, only `self.check_attributes` should be enough.
1931        let spans = self
1932            .tcx
1933            .hir_attrs(where_predicate.hir_id)
1934            .iter()
1935            // FIXME: We shouldn't need to special-case `doc`!
1936            .filter(|attr| {
1937                #[allow(non_exhaustive_omitted_patterns)] match attr {
    Attribute::Parsed(AttributeKind::DocComment { .. } |
        AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
    _ => false,
}matches!(
1938                    attr,
1939                    Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
1940                        | Attribute::Unparsed(_)
1941                )
1942            })
1943            .map(|attr| attr.span())
1944            .collect::<Vec<_>>();
1945        if !spans.is_empty() {
1946            self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
1947        }
1948        self.check_attributes(
1949            where_predicate.hir_id,
1950            where_predicate.span,
1951            Target::WherePredicate,
1952            None,
1953        );
1954        intravisit::walk_where_predicate(self, where_predicate)
1955    }
1956
1957    fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1958        let target = Target::from_generic_param(generic_param);
1959        self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1960        intravisit::walk_generic_param(self, generic_param)
1961    }
1962
1963    fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1964        let target = Target::from_trait_item(trait_item);
1965        self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1966        intravisit::walk_trait_item(self, trait_item)
1967    }
1968
1969    fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1970        self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1971        intravisit::walk_field_def(self, struct_field);
1972    }
1973
1974    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1975        self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1976        intravisit::walk_arm(self, arm);
1977    }
1978
1979    fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1980        let target = Target::from_foreign_item(f_item);
1981        self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1982        intravisit::walk_foreign_item(self, f_item)
1983    }
1984
1985    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1986        let target = target_from_impl_item(self.tcx, impl_item);
1987        self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1988        intravisit::walk_impl_item(self, impl_item)
1989    }
1990
1991    fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1992        // When checking statements ignore expressions, they will be checked later.
1993        if let hir::StmtKind::Let(l) = stmt.kind {
1994            self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1995        }
1996        intravisit::walk_stmt(self, stmt)
1997    }
1998
1999    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2000        let target = match expr.kind {
2001            hir::ExprKind::Closure { .. } => Target::Closure,
2002            _ => Target::Expression,
2003        };
2004
2005        self.check_attributes(expr.hir_id, expr.span, target, None);
2006        intravisit::walk_expr(self, expr)
2007    }
2008
2009    fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2010        self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2011        intravisit::walk_expr_field(self, field)
2012    }
2013
2014    fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2015        self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2016        intravisit::walk_variant(self, variant)
2017    }
2018
2019    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2020        self.check_attributes(param.hir_id, param.span, Target::Param, None);
2021
2022        intravisit::walk_param(self, param);
2023    }
2024
2025    fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2026        self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2027        intravisit::walk_pat_field(self, field);
2028    }
2029}
2030
2031fn is_c_like_enum(item: &Item<'_>) -> bool {
2032    if let ItemKind::Enum(_, _, ref def) = item.kind {
2033        for variant in def.variants {
2034            match variant.data {
2035                hir::VariantData::Unit(..) => { /* continue */ }
2036                _ => return false,
2037            }
2038        }
2039        true
2040    } else {
2041        false
2042    }
2043}
2044
2045// FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2046// from this check.
2047fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2048    // Check for builtin attributes at the crate level
2049    // which were unsuccessfully resolved due to cannot determine
2050    // resolution for the attribute macro error.
2051    const ATTRS_TO_CHECK: &[Symbol] =
2052        &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2053
2054    for attr in attrs {
2055        // FIXME(jdonszelmann): all attrs should be combined here cleaning this up some day.
2056        let (span, name) = if let Some(a) =
2057            ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2058        {
2059            (attr.span(), *a)
2060        } else if let Attribute::Parsed(AttributeKind::Repr {
2061            reprs: _,
2062            first_span: first_attr_span,
2063        }) = attr
2064        {
2065            (*first_attr_span, sym::repr)
2066        } else {
2067            continue;
2068        };
2069
2070        let item = tcx
2071            .hir_free_items()
2072            .map(|id| tcx.hir_item(id))
2073            .find(|item| !item.span.is_dummy()) // Skip prelude `use`s
2074            .map(|item| errors::ItemFollowingInnerAttr {
2075                span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2076                kind: tcx.def_descr(item.owner_id.to_def_id()),
2077            });
2078        let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2079            span,
2080            sugg_span: tcx
2081                .sess
2082                .source_map()
2083                .span_to_snippet(span)
2084                .ok()
2085                .filter(|src| src.starts_with("#!["))
2086                .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2087            name,
2088            item,
2089        });
2090
2091        if let Attribute::Unparsed(p) = attr {
2092            tcx.dcx().try_steal_replace_and_emit_err(
2093                p.path.span,
2094                StashKey::UndeterminedMacroResolution,
2095                err,
2096            );
2097        } else {
2098            err.emit();
2099        }
2100    }
2101}
2102
2103fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2104    let attrs = tcx.hir_attrs(item.hir_id());
2105
2106    if let Some(attr_span) =
2107        {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Inline(i, span)) if
                    !#[allow(non_exhaustive_omitted_patterns)] match i {
                            InlineAttr::Force { .. } => true,
                            _ => false,
                        } => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
2108    {
2109        tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2110    }
2111}
2112
2113fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2114    let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2115    tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2116    if module_def_id.to_local_def_id().is_top_level_module() {
2117        check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2118        check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2119    }
2120    if check_attr_visitor.abort.get() {
2121        tcx.dcx().abort_if_errors()
2122    }
2123}
2124
2125pub(crate) fn provide(providers: &mut Providers) {
2126    *providers = Providers { check_mod_attrs, ..*providers };
2127}
2128
2129// FIXME(jdonszelmann): remove, check during parsing
2130fn check_duplicates(
2131    tcx: TyCtxt<'_>,
2132    attr_span: Span,
2133    attr: &Attribute,
2134    hir_id: HirId,
2135    duplicates: AttributeDuplicates,
2136    seen: &mut FxHashMap<Symbol, Span>,
2137) {
2138    use AttributeDuplicates::*;
2139    if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
    WarnFollowingWordOnly => true,
    _ => false,
}matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2140        return;
2141    }
2142    let attr_name = attr.name().unwrap();
2143    match duplicates {
2144        DuplicatesOk => {}
2145        WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2146            match seen.entry(attr_name) {
2147                Entry::Occupied(mut entry) => {
2148                    let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
    FutureWarnPreceding => true,
    _ => false,
}matches!(duplicates, FutureWarnPreceding) {
2149                        let to_remove = entry.insert(attr_span);
2150                        (to_remove, attr_span)
2151                    } else {
2152                        (attr_span, *entry.get())
2153                    };
2154                    tcx.emit_node_span_lint(
2155                        UNUSED_ATTRIBUTES,
2156                        hir_id,
2157                        this,
2158                        errors::UnusedDuplicate {
2159                            this,
2160                            other,
2161                            warning: #[allow(non_exhaustive_omitted_patterns)] match duplicates {
    FutureWarnFollowing | FutureWarnPreceding => true,
    _ => false,
}matches!(
2162                                duplicates,
2163                                FutureWarnFollowing | FutureWarnPreceding
2164                            ),
2165                        },
2166                    );
2167                }
2168                Entry::Vacant(entry) => {
2169                    entry.insert(attr_span);
2170                }
2171            }
2172        }
2173        ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2174            Entry::Occupied(mut entry) => {
2175                let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
    ErrorPreceding => true,
    _ => false,
}matches!(duplicates, ErrorPreceding) {
2176                    let to_remove = entry.insert(attr_span);
2177                    (to_remove, attr_span)
2178                } else {
2179                    (attr_span, *entry.get())
2180                };
2181                tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2182            }
2183            Entry::Vacant(entry) => {
2184                entry.insert(attr_span);
2185            }
2186        },
2187    }
2188}
2189
2190fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2191    #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2192        || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2193            fn_ptr_ty.decl.inputs.len() == 1
2194        } else {
2195            false
2196        }
2197        || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2198            && let Some(&[hir::GenericArg::Type(ty)]) =
2199                path.segments.last().map(|last| last.args().args)
2200        {
2201            doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2202        } else {
2203            false
2204        })
2205}