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::slice;
10
11use rustc_abi::ExternAbi;
12use rustc_ast::{AttrStyle, MetaItemKind, ast};
13use rustc_attr_parsing::AttributeParser;
14use rustc_data_structures::thin_vec::ThinVec;
15use rustc_data_structures::unord::UnordMap;
16use rustc_errors::{DiagCtxtHandle, IntoDiagArg, MultiSpan, msg};
17use rustc_feature::BUILTIN_ATTRIBUTE_MAP;
18use rustc_hir::attrs::diagnostic::Directive;
19use rustc_hir::attrs::{
20    AttributeKind, DocAttribute, DocInline, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
21    OptimizeAttr, ReprAttr,
22};
23use rustc_hir::def::DefKind;
24use rustc_hir::def_id::LocalModDefId;
25use rustc_hir::intravisit::{self, Visitor};
26use rustc_hir::{
27    self as hir, Attribute, CRATE_HIR_ID, Constness, FnSig, ForeignItem, GenericParam,
28    GenericParamKind, HirId, Item, ItemKind, MethodKind, Node, ParamName, Target, TraitItem,
29    find_attr,
30};
31use rustc_macros::Diagnostic;
32use rustc_middle::hir::nested_filter;
33use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
34use rustc_middle::query::Providers;
35use rustc_middle::traits::ObligationCause;
36use rustc_middle::ty::error::{ExpectedFound, TypeError};
37use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized};
38use rustc_middle::{bug, span_bug};
39use rustc_session::config::CrateType;
40use rustc_session::diagnostics::feature_err;
41use rustc_session::lint;
42use rustc_session::lint::builtin::{
43    CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES,
44    MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES,
45};
46use rustc_span::edition::Edition;
47use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
48use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
49use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
50use rustc_trait_selection::traits::ObligationCtxt;
51
52use crate::diagnostics;
53
54#[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 implementations")));
                        ;
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait implementation")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
55#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait implementations")]
56struct DiagnosticOnConstOnlyForNonConstTraitImpls {
57    #[label("this is a const trait implementation")]
58    item_span: Span,
59}
60
61fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
62    match impl_item.kind {
63        hir::ImplItemKind::Const(..) => Target::AssocConst,
64        hir::ImplItemKind::Fn(..) => {
65            let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
66            let containing_item = tcx.hir_expect_item(parent_def_id);
67            let containing_impl_is_for_trait = match &containing_item.kind {
68                hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
69                _ => ::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"),
70            };
71            if containing_impl_is_for_trait {
72                Target::Method(MethodKind::Trait { body: true })
73            } else {
74                Target::Method(MethodKind::Inherent)
75            }
76        }
77        hir::ImplItemKind::Type(..) => Target::AssocTy,
78    }
79}
80
81#[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)]
82enum ItemLike<'tcx> {
83    Item(&'tcx Item<'tcx>),
84    ForeignItem,
85}
86
87#[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)]
88pub(crate) enum ProcMacroKind {
89    FunctionLike,
90    Derive,
91    Attribute,
92}
93
94impl IntoDiagArg for ProcMacroKind {
95    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
96        match self {
97            ProcMacroKind::Attribute => "attribute proc macro",
98            ProcMacroKind::Derive => "derive proc macro",
99            ProcMacroKind::FunctionLike => "function-like proc macro",
100        }
101        .into_diag_arg(&mut None)
102    }
103}
104
105struct CheckAttrVisitor<'tcx> {
106    tcx: TyCtxt<'tcx>,
107
108    // Whether or not this visitor should abort after finding errors
109    abort: Cell<bool>,
110}
111
112impl<'tcx> CheckAttrVisitor<'tcx> {
113    fn dcx(&self) -> DiagCtxtHandle<'tcx> {
114        self.tcx.dcx()
115    }
116
117    /// Checks any attribute.
118    fn check_attributes(
119        &self,
120        hir_id: HirId,
121        span: Span,
122        target: Target,
123        item: Option<ItemLike<'_>>,
124    ) {
125        let attrs = self.tcx.hir_attrs(hir_id);
126        for attr in attrs {
127            match attr {
128                Attribute::Parsed(attr_kind) => {
129                    self.check_one_parsed_attribute(hir_id, span, target, item, attrs, attr_kind);
130                    self.check_unused_attribute(hir_id, attr, None);
131                }
132                Attribute::Unparsed(attr_item) => {
133                    match attr.path().as_slice() {
134                        // ok
135                        [sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid, ..] => {}
136
137                        [name, rest @ ..] => {
138                            if let Some(_) = BUILTIN_ATTRIBUTE_MAP.get(name) {
139                                if rest.len() > 0
140                                    && AttributeParser::is_parsed_attribute(slice::from_ref(name))
141                                {
142                                    // Check if we tried to use a builtin attribute as an attribute
143                                    // namespace, like `#[must_use::skip]`. This check is here to
144                                    // solve <https://github.com/rust-lang/rust/issues/137590>.
145                                    // An error is already produced for this case elsewhere.
146                                    return;
147                                }
148
149                                ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
    format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
        name))span_bug!(
150                                    attr.span(),
151                                    "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
152                                )
153                            }
154                        }
155
156                        [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
157                    }
158
159                    self.check_unused_attribute(hir_id, attr, Some(attr_item.style));
160                }
161            }
162        }
163
164        self.check_repr(attrs, span, target, item, hir_id);
165        self.check_rustc_force_inline(hir_id, attrs, target);
166        self.check_mix_no_mangle_export(hir_id, attrs);
167        self.check_optimize_and_inline(attrs);
168    }
169
170    /// Called by [`Self::check_attributes()`] to check a single attribute which is
171    /// [`Attribute::Parsed`].
172    ///
173    /// This is a separate function to help with comprehensibility and rustfmt-ability.
174    fn check_one_parsed_attribute(
175        &self,
176        hir_id: HirId,
177        span: Span,
178        target: Target,
179        item: Option<ItemLike<'_>>,
180        attrs: &[Attribute],
181        attr: &AttributeKind,
182    ) {
183        match attr {
184            AttributeKind::ProcMacro => {
185                self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
186            }
187            AttributeKind::ProcMacroAttribute => {
188                self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
189            }
190            AttributeKind::ProcMacroDerive { .. } => {
191                self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
192            }
193            AttributeKind::Inline(InlineAttr::Force { .. }, ..) => {} // handled separately below
194            AttributeKind::Inline(kind, attr_span) => {
195                self.check_inline(hir_id, *attr_span, kind, target)
196            }
197            AttributeKind::AllowInternalUnsafe(attr_span)
198            | AttributeKind::AllowInternalUnstable(.., attr_span) => {
199                self.check_macro_only_attr(*attr_span, span, target, attrs)
200            }
201            AttributeKind::RustcAllowConstFnUnstable(_, first_span) => {
202                self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
203            }
204            AttributeKind::Deprecated { span: attr_span, .. } => {
205                self.check_deprecated(hir_id, *attr_span, target)
206            }
207            AttributeKind::RustcDumpObjectLifetimeDefaults => {
208                self.check_dump_object_lifetime_defaults(hir_id);
209            }
210            &AttributeKind::RustcPubTransparent(attr_span) => {
211                self.check_rustc_pub_transparent(attr_span, span, attrs)
212            }
213            AttributeKind::Naked(..) => self.check_naked(hir_id, target),
214            AttributeKind::TrackCaller(attr_span) => {
215                self.check_track_caller(hir_id, *attr_span, attrs, target)
216            }
217            AttributeKind::NonExhaustive(attr_span) => {
218                self.check_non_exhaustive(*attr_span, span, target, item)
219            }
220            AttributeKind::MayDangle(attr_span) => self.check_may_dangle(hir_id, *attr_span),
221            AttributeKind::Link(_, attr_span) => self.check_link(hir_id, *attr_span, target),
222            AttributeKind::MacroExport { span, .. } => {
223                self.check_macro_export(hir_id, *span, target)
224            }
225            AttributeKind::RustcLegacyConstGenerics { attr_span, fn_indexes } => {
226                self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
227            }
228            AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target),
229            AttributeKind::EiiImpls(impls) => self.check_eii_impl(impls, target),
230            AttributeKind::RustcMustImplementOneOf { attr_span, fn_names } => {
231                self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id, target)
232            }
233            AttributeKind::OnUnimplemented { directive } => {
234                self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())
235            }
236            AttributeKind::OnConst { span, directive } => {
237                self.check_diagnostic_on_const(*span, hir_id, target, item, directive.as_deref())
238            }
239            AttributeKind::OnMove { directive } => {
240                self.check_diagnostic_on_move(hir_id, directive.as_deref())
241            }
242            AttributeKind::OnTypeError { directive, .. } => {
243                self.check_diagnostic_on_type_error(hir_id, directive.as_deref())
244            }
245
246            // All of the following attributes have no specific checks.
247            // tidy-alphabetical-start
248            AttributeKind::AutomaticallyDerived => (),
249            AttributeKind::CfgAttrTrace => (),
250            AttributeKind::CfgTrace(..) => (),
251            AttributeKind::CfiEncoding { .. } => (),
252            AttributeKind::Cold => (),
253            AttributeKind::CollapseDebugInfo(..) => (),
254            AttributeKind::CompilerBuiltins => (),
255            AttributeKind::ConstContinue(..) => {}
256            AttributeKind::Coroutine => (),
257            AttributeKind::Coverage(..) => (),
258            AttributeKind::CrateName { .. } => (),
259            AttributeKind::CrateType(..) => (),
260            AttributeKind::CustomMir(..) => (),
261            AttributeKind::DebuggerVisualizer(..) => (),
262            AttributeKind::DefaultLibAllocator => (),
263            AttributeKind::DoNotRecommend => (),
264            // `#[doc]` is actually a lot more than just doc comments, so is checked below
265            AttributeKind::DocComment { .. } => (),
266            AttributeKind::EiiDeclaration { .. } => (),
267            AttributeKind::ExportName { .. } => (),
268            AttributeKind::ExportStable => (),
269            AttributeKind::Feature(..) => (),
270            AttributeKind::FfiConst => (),
271            AttributeKind::FfiPure(..) => (),
272            AttributeKind::Fundamental => (),
273            AttributeKind::Ignore { .. } => (),
274            AttributeKind::InstructionSet(..) => (),
275            AttributeKind::InstrumentFn(..) => (),
276            AttributeKind::Lang(..) => (),
277            AttributeKind::LinkName { .. } => (),
278            AttributeKind::LinkOrdinal { .. } => (),
279            AttributeKind::LinkSection { .. } => (),
280            AttributeKind::Linkage(..) => (),
281            AttributeKind::LoopMatch(..) => {}
282            AttributeKind::MacroEscape => (),
283            AttributeKind::MacroUse { .. } => (),
284            AttributeKind::Marker => (),
285            AttributeKind::MoveSizeLimit { .. } => (),
286            AttributeKind::MustNotSupend { .. } => (),
287            AttributeKind::MustUse { .. } => (),
288            AttributeKind::NeedsAllocator => (),
289            AttributeKind::NeedsPanicRuntime => (),
290            AttributeKind::NoBuiltins => (),
291            AttributeKind::NoCore { .. } => (),
292            AttributeKind::NoImplicitPrelude => (),
293            AttributeKind::NoLink => (),
294            AttributeKind::NoMain => (),
295            AttributeKind::NoMangle(..) => (),
296            AttributeKind::NoStd { .. } => (),
297            AttributeKind::OnUnknown { .. } => (),
298            AttributeKind::OnUnmatchedArgs { .. } => (),
299            AttributeKind::Optimize(..) => (),
300            AttributeKind::PanicRuntime => (),
301            AttributeKind::PatchableFunctionEntry { .. } => (),
302            AttributeKind::Path(..) => (),
303            AttributeKind::PatternComplexityLimit { .. } => (),
304            AttributeKind::PinV2(..) => (),
305            AttributeKind::PreludeImport => (),
306            AttributeKind::ProfilerRuntime => (),
307            AttributeKind::RecursionLimit { .. } => (),
308            AttributeKind::ReexportTestHarnessMain(..) => (),
309            AttributeKind::RegisterTool(..) => (),
310            // handled below this loop and elsewhere
311            AttributeKind::Repr { .. } => (),
312            AttributeKind::RustcAbi { .. } => (),
313            AttributeKind::RustcAlign { .. } => {}
314            AttributeKind::RustcAllocator => (),
315            AttributeKind::RustcAllocatorZeroed => (),
316            AttributeKind::RustcAllocatorZeroedVariant { .. } => (),
317            AttributeKind::RustcAllowIncoherentImpl(..) => (),
318            AttributeKind::RustcAsPtr => (),
319            AttributeKind::RustcAutodiff(..) => (),
320            AttributeKind::RustcBodyStability { .. } => (),
321            AttributeKind::RustcBuiltinMacro { .. } => (),
322            AttributeKind::RustcCaptureAnalysis => (),
323            AttributeKind::RustcCguTestAttr(..) => (),
324            AttributeKind::RustcClean(..) => (),
325            AttributeKind::RustcCoherenceIsCore => (),
326            AttributeKind::RustcCoinductive => (),
327            AttributeKind::RustcComptime(_) => (),
328            AttributeKind::RustcConfusables { .. } => (),
329            AttributeKind::RustcConstStability { .. } => (),
330            AttributeKind::RustcConstStableIndirect => (),
331            AttributeKind::RustcConversionSuggestion => (),
332            AttributeKind::RustcDeallocator => (),
333            AttributeKind::RustcDelayedBugFromInsideQuery => (),
334            AttributeKind::RustcDenyExplicitImpl => (),
335            AttributeKind::RustcDeprecatedSafe2024 { .. } => (),
336            AttributeKind::RustcDiagnosticItem(..) => (),
337            AttributeKind::RustcDoNotConstCheck => (),
338            AttributeKind::RustcDocPrimitive(..) => (),
339            AttributeKind::RustcDummy => (),
340            AttributeKind::RustcDumpDefParents => (),
341            AttributeKind::RustcDumpDefPath(..) => (),
342            AttributeKind::RustcDumpGenerics => (),
343            AttributeKind::RustcDumpHiddenTypeOfOpaques => (),
344            AttributeKind::RustcDumpInferredOutlives => (),
345            AttributeKind::RustcDumpItemBounds => (),
346            AttributeKind::RustcDumpLayout(..) => (),
347            AttributeKind::RustcDumpPredicates => (),
348            AttributeKind::RustcDumpSymbolName(..) => (),
349            AttributeKind::RustcDumpUserArgs => (),
350            AttributeKind::RustcDumpVariances => (),
351            AttributeKind::RustcDumpVariancesOfOpaques => (),
352            AttributeKind::RustcDumpVtable(..) => (),
353            AttributeKind::RustcDynIncompatibleTrait(..) => (),
354            AttributeKind::RustcEffectiveVisibility => (),
355            AttributeKind::RustcEiiForeignItem => (),
356            AttributeKind::RustcEvaluateWhereClauses => (),
357            AttributeKind::RustcHasIncoherentInherentImpls => (),
358            AttributeKind::RustcIfThisChanged(..) => (),
359            AttributeKind::RustcInheritOverflowChecks => (),
360            AttributeKind::RustcInsignificantDtor => (),
361            AttributeKind::RustcIntrinsic => (),
362            AttributeKind::RustcIntrinsicConstStableIndirect => (),
363            AttributeKind::RustcLintOptDenyFieldAccess { .. } => (),
364            AttributeKind::RustcLintOptTy => (),
365            AttributeKind::RustcLintQueryInstability => (),
366            AttributeKind::RustcLintUntrackedQueryInformation => (),
367            AttributeKind::RustcMacroTransparency(_) => (),
368            AttributeKind::RustcMain => (),
369            AttributeKind::RustcMir(_) => (),
370            AttributeKind::RustcMustMatchExhaustively(..) => (),
371            AttributeKind::RustcNeverReturnsNullPtr => (),
372            AttributeKind::RustcNeverTypeOptions { .. } => (),
373            AttributeKind::RustcNoImplicitAutorefs => (),
374            AttributeKind::RustcNoImplicitBounds => (),
375            AttributeKind::RustcNoMirInline => (),
376            AttributeKind::RustcNoWritable => (),
377            AttributeKind::RustcNonConstTraitMethod => (),
378            AttributeKind::RustcNonnullOptimizationGuaranteed => (),
379            AttributeKind::RustcNounwind => (),
380            AttributeKind::RustcObjcClass { .. } => (),
381            AttributeKind::RustcObjcSelector { .. } => (),
382            AttributeKind::RustcOffloadKernel => (),
383            AttributeKind::RustcParenSugar => (),
384            AttributeKind::RustcPassByValue => (),
385            AttributeKind::RustcPassIndirectlyInNonRusticAbis(..) => (),
386            AttributeKind::RustcPreserveUbChecks => (),
387            AttributeKind::RustcProcMacroDecls => (),
388            AttributeKind::RustcReallocator => (),
389            AttributeKind::RustcRegions => (),
390            AttributeKind::RustcReservationImpl(..) => (),
391            AttributeKind::RustcScalableVector { .. } => (),
392            AttributeKind::RustcShouldNotBeCalledOnConstItems => (),
393            AttributeKind::RustcSimdMonomorphizeLaneLimit(..) => (),
394            AttributeKind::RustcSkipDuringMethodDispatch { .. } => (),
395            AttributeKind::RustcSpecializationTrait => (),
396            AttributeKind::RustcStdInternalSymbol => (),
397            AttributeKind::RustcStrictCoherence(..) => (),
398            AttributeKind::RustcTestEntrypointMarker => (),
399            AttributeKind::RustcTestMarker(..) => (),
400            AttributeKind::RustcThenThisWouldNeed(..) => (),
401            AttributeKind::RustcTrivialFieldReads => (),
402            AttributeKind::RustcUnsafeSpecializationMarker => (),
403            AttributeKind::Sanitize { .. } => {}
404            AttributeKind::ShouldPanic { .. } => (),
405            AttributeKind::Splat(..) => (),
406            AttributeKind::Stability { .. } => (),
407            AttributeKind::TargetFeature { .. } => {}
408            AttributeKind::TestRunner(..) => (),
409            AttributeKind::ThreadLocal => (),
410            AttributeKind::TypeLengthLimit { .. } => (),
411            AttributeKind::Unroll(..) => (),
412            AttributeKind::UnstableFeatureBound(..) => (),
413            AttributeKind::UnstableRemoved(..) => (),
414            AttributeKind::Used { .. } => (),
415            AttributeKind::WindowsSubsystem(..) => (),
416            // tidy-alphabetical-end
417        }
418    }
419
420    fn check_rustc_must_implement_one_of(
421        &self,
422        attr_span: Span,
423        list: &ThinVec<Ident>,
424        hir_id: HirId,
425        target: Target,
426    ) {
427        // Ignoring invalid targets because TyCtxt::associated_items emits bug if the target isn't valid
428        // the parser has already produced an error for the target being invalid
429        if !#[allow(non_exhaustive_omitted_patterns)] match target {
    Target::Trait => true,
    _ => false,
}matches!(target, Target::Trait) {
430            return;
431        }
432
433        let def_id = hir_id.owner.def_id;
434
435        let items = self.tcx.associated_items(def_id);
436        // Check that all arguments of `#[rustc_must_implement_one_of]` reference
437        // functions in the trait with default implementations
438        for ident in list {
439            let item = items
440                .filter_by_name_unhygienic(ident.name)
441                .find(|item| item.ident(self.tcx) == *ident);
442
443            match item {
444                Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ty::AssocKind::Fn { .. } => true,
    _ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
445                    if !item.defaultness(self.tcx).has_value() {
446                        self.tcx.dcx().emit_err(
447                            diagnostics::FunctionNotHaveDefaultImplementation {
448                                span: self.tcx.def_span(item.def_id),
449                                note_span: attr_span,
450                            },
451                        );
452                    }
453                }
454                Some(item) => {
455                    self.dcx().emit_err(diagnostics::MustImplementNotFunction {
456                        span: self.tcx.def_span(item.def_id),
457                        span_note: diagnostics::MustImplementNotFunctionSpanNote {
458                            span: attr_span,
459                        },
460                        note: diagnostics::MustImplementNotFunctionNote {},
461                    });
462                }
463                None => {
464                    self.dcx().emit_err(diagnostics::FunctionNotFoundInTrait { span: ident.span });
465                }
466            }
467        }
468        // Check for duplicates
469
470        let mut set: UnordMap<Symbol, Span> = Default::default();
471
472        for ident in &*list {
473            if let Some(dup) = set.insert(ident.name, ident.span) {
474                self.tcx.dcx().emit_err(diagnostics::FunctionNamesDuplicated {
475                    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],
476                });
477            }
478        }
479    }
480
481    fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
482        for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
483            match target {
484                Target::Fn | Target::Static => {}
485                _ => {
486                    self.dcx().emit_err(diagnostics::EiiImplTarget { span: *span });
487                }
488            }
489
490            if let EiiImplResolution::Macro(eii_macro) = resolution
491                && {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(*eii_macro,
                        &self.tcx) {
                    #[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)
492                && !impl_marked_unsafe
493            {
494                self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe {
495                    span: *span,
496                    name: self.tcx.item_name(*eii_macro),
497                    suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion {
498                        left: inner_span.shrink_to_lo(),
499                        right: inner_span.shrink_to_hi(),
500                    },
501                });
502            }
503        }
504    }
505
506    /// Checks use of generic formatting parameters in `#[diagnostic::on_unimplemented]`
507    fn check_diagnostic_on_unimplemented(&self, hir_id: HirId, directive: Option<&Directive>) {
508        if let Some(directive) = directive {
509            if let Node::Item(Item {
510                kind: ItemKind::Trait { ident: trait_name, generics, .. },
511                ..
512            }) = self.tcx.hir_node(hir_id)
513            {
514                directive.visit_params(&mut |argument_name, span| {
515                    let has_generic = generics.params.iter().any(|p| {
516                        if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
517                            && let ParamName::Plain(name) = p.name
518                            && name.name == argument_name
519                        {
520                            true
521                        } else {
522                            false
523                        }
524                    });
525                    if !has_generic {
526                        self.tcx.emit_node_span_lint(
527                            MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
528                            hir_id,
529                            span,
530                            diagnostics::UnknownFormatParameterForOnUnimplementedAttr {
531                                argument_name,
532                                trait_name: *trait_name,
533                                help: !directive.is_rustc_attr,
534                            },
535                        )
536                    }
537                })
538            }
539        }
540    }
541
542    /// Checks if `#[diagnostic::on_const]` is applied to a on-const trait impl
543    fn check_diagnostic_on_const(
544        &self,
545        attr_span: Span,
546        hir_id: HirId,
547        target: Target,
548        item: Option<ItemLike<'_>>,
549        directive: Option<&Directive>,
550    ) {
551        // We only check the non-constness here. A diagnostic for use
552        // on not-trait impl items is issued during attribute parsing.
553        if target == (Target::Impl { of_trait: true }) {
554            if let Some(directive) = directive
555                && let Node::Item(Item { kind: ItemKind::Impl(hir::Impl { generics, .. }), .. }) =
556                    self.tcx.hir_node(hir_id)
557            {
558                directive.visit_params(&mut |argument_name, span| {
559                    let has_generic = generics.params.iter().any(|p| {
560                        if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
561                            && let ParamName::Plain(name) = p.name
562                            && name.name == argument_name
563                        {
564                            true
565                        } else {
566                            false
567                        }
568                    });
569                    if !has_generic {
570                        self.tcx.emit_node_span_lint(
571                            MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
572                            hir_id,
573                            span,
574                            diagnostics::OnConstMalformedFormatLiterals { name: argument_name },
575                        )
576                    }
577                });
578            }
579            match item.unwrap() {
580                ItemLike::Item(it) => match it.expect_impl().constness {
581                    Constness::Const { .. } => {
582                        let item_span = self.tcx.hir_span(hir_id);
583                        self.tcx.emit_node_span_lint(
584                            MISPLACED_DIAGNOSTIC_ATTRIBUTES,
585                            hir_id,
586                            attr_span,
587                            DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
588                        );
589                        return;
590                    }
591                    Constness::NotConst => return,
592                },
593                ItemLike::ForeignItem => {}
594            }
595        }
596    }
597
598    /// Checks use of generic formatting parameters in `#[diagnostic::on_move]`
599    fn check_diagnostic_on_move(&self, hir_id: HirId, directive: Option<&Directive>) {
600        if let Some(directive) = directive {
601            if let Node::Item(Item {
602                kind:
603                    ItemKind::Struct(_, generics, _)
604                    | ItemKind::Enum(_, generics, _)
605                    | ItemKind::Union(_, generics, _),
606                ..
607            }) = self.tcx.hir_node(hir_id)
608            {
609                directive.visit_params(&mut |argument_name, span| {
610                    let has_generic = generics.params.iter().any(|p| {
611                        if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
612                            && let ParamName::Plain(name) = p.name
613                            && name.name == argument_name
614                        {
615                            true
616                        } else {
617                            false
618                        }
619                    });
620                    if !has_generic {
621                        self.tcx.emit_node_span_lint(
622                            MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
623                            hir_id,
624                            span,
625                            diagnostics::OnMoveMalformedFormatLiterals { name: argument_name },
626                        )
627                    }
628                });
629            }
630        }
631    }
632
633    fn check_diagnostic_on_type_error(&self, hir_id: HirId, directive: Option<&Directive>) {
634        if let Some(directive) = directive {
635            if let Node::Item(Item {
636                kind:
637                    ItemKind::Struct(_, generics, _)
638                    | ItemKind::Enum(_, generics, _)
639                    | ItemKind::Union(_, generics, _),
640                ..
641            }) = self.tcx.hir_node(hir_id)
642            {
643                let generic_count = generics
644                    .params
645                    .iter()
646                    .filter(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. }))
647                    .count();
648
649                // Enforce: at most one generic
650                if generic_count != 1 {
651                    self.tcx.emit_node_span_lint(
652                        MALFORMED_DIAGNOSTIC_ATTRIBUTES,
653                        hir_id,
654                        generics.span,
655                        diagnostics::OnTypeErrorNotExactlyOneGeneric { count: generic_count },
656                    );
657                }
658
659                directive.visit_params(&mut |argument_name, span| {
660                    let has_generic = generics.params.iter().any(|p| {
661                        if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
    GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
662                            && let ParamName::Plain(name) = p.name
663                            && name.name == argument_name
664                        {
665                            true
666                        } else {
667                            false
668                        }
669                    });
670
671                    let is_allowed = argument_name == sym::Expected || argument_name == sym::Found;
672                    if !(has_generic | is_allowed) {
673                        self.tcx.emit_node_span_lint(
674                            MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
675                            hir_id,
676                            span,
677                            diagnostics::OnTypeErrorMalformedFormatLiterals { name: argument_name },
678                        )
679                    }
680                });
681            }
682        }
683    }
684
685    /// Checks if an `#[inline]` is applied to a function or a closure.
686    fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
687        match target {
688            Target::Fn
689            | Target::Closure
690            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
691                // `#[inline]` is ignored if the symbol must be codegened upstream because it's exported.
692                if let Some(did) = hir_id.as_owner()
693                    && self.tcx.def_kind(did).has_codegen_attrs()
694                    && kind != &InlineAttr::Never
695                {
696                    let attrs = self.tcx.codegen_fn_attrs(did);
697                    // Not checking naked as `#[inline]` is forbidden for naked functions anyways.
698                    if attrs.contains_extern_indicator() {
699                        self.tcx.emit_node_span_lint(
700                            UNUSED_ATTRIBUTES,
701                            hir_id,
702                            attr_span,
703                            diagnostics::InlineIgnoredForExported,
704                        );
705                    }
706                }
707            }
708            _ => {}
709        }
710    }
711
712    /// Checks if `#[naked]` is applied to a function definition.
713    fn check_naked(&self, hir_id: HirId, target: Target) {
714        match target {
715            Target::Fn
716            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
717                let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
718                let abi = fn_sig.header.abi;
719                if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
720                    feature_err(
721                        &self.tcx.sess,
722                        sym::naked_functions_rustic_abi,
723                        fn_sig.span,
724                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
                abi.as_str()))
    })format!(
725                            "`#[naked]` is currently unstable on `extern \"{}\"` functions",
726                            abi.as_str()
727                        ),
728                    )
729                    .emit();
730                }
731            }
732            _ => {}
733        }
734    }
735
736    /// Debugging aid for the `object_lifetime_default` query.
737    fn check_dump_object_lifetime_defaults(&self, hir_id: HirId) {
738        let tcx = self.tcx;
739        let Some(owner_id) = hir_id.as_owner() else { return };
740        for param in &tcx.generics_of(owner_id.def_id).own_params {
741            let ty::GenericParamDefKind::Type { .. } = param.kind else { continue };
742            let default = tcx.object_lifetime_default(param.def_id);
743            let repr = match default {
744                ObjectLifetimeDefault::Empty => "Empty".to_owned(),
745                ObjectLifetimeDefault::Static => "'static".to_owned(),
746                ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
747                ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
748            };
749            tcx.dcx().span_err(tcx.def_span(param.def_id), repr);
750        }
751    }
752
753    /// Checks if a `#[track_caller]` is applied to a function.
754    fn check_track_caller(
755        &self,
756        hir_id: HirId,
757        attr_span: Span,
758        attrs: &[Attribute],
759        target: Target,
760    ) {
761        match target {
762            Target::Fn => {
763                // `#[track_caller]` is not valid on weak lang items because they are called via
764                // `extern` declarations and `#[track_caller]` would alter their ABI.
765                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)
766                    && item.is_weak()
767                {
768                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
769
770                    self.dcx().emit_err(diagnostics::LangItemWithTrackCaller {
771                        attr_span,
772                        name: item.name(),
773                        sig_span: sig.span,
774                    });
775                }
776
777                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) {
778                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
779                    for i in impls {
780                        let name = match i.resolution {
781                            EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
782                            EiiImplResolution::Known(decl) => decl.name.name,
783                            EiiImplResolution::Error(_eg) => continue,
784                        };
785                        self.dcx().emit_err(diagnostics::EiiWithTrackCaller {
786                            attr_span,
787                            name,
788                            sig_span: sig.span,
789                        });
790                    }
791                }
792            }
793            _ => {}
794        }
795    }
796
797    /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid.
798    fn check_non_exhaustive(
799        &self,
800        attr_span: Span,
801        span: Span,
802        target: Target,
803        item: Option<ItemLike<'_>>,
804    ) {
805        match target {
806            Target::Struct => {
807                if let Some(ItemLike::Item(hir::Item {
808                    kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
809                    ..
810                })) = item
811                    && !fields.is_empty()
812                    && fields.iter().any(|f| f.default.is_some())
813                {
814                    self.dcx().emit_err(diagnostics::NonExhaustiveWithDefaultFieldValues {
815                        attr_span,
816                        defn_span: span,
817                    });
818                }
819            }
820            _ => {}
821        }
822    }
823
824    fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
825        if let Some(location) = match target {
826            Target::AssocTy => {
827                if let DefKind::Impl { .. } =
828                    self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
829                {
830                    Some("type alias in implementation block")
831                } else {
832                    None
833                }
834            }
835            Target::AssocConst => {
836                let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
837                let containing_item = self.tcx.hir_expect_item(parent_def_id);
838                // We can't link to trait impl's consts.
839                let err = "associated constant in trait implementation block";
840                match containing_item.kind {
841                    ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
842                    _ => None,
843                }
844            }
845            // we check the validity of params elsewhere
846            Target::Param => return,
847            Target::Expression
848            | Target::Statement
849            | Target::Arm
850            | Target::ForeignMod
851            | Target::Closure
852            | Target::Impl { .. }
853            | Target::WherePredicate => Some(target.name()),
854            Target::ExternCrate
855            | Target::Use
856            | Target::Static
857            | Target::Const
858            | Target::Fn
859            | Target::Mod
860            | Target::GlobalAsm
861            | Target::TyAlias
862            | Target::Enum
863            | Target::Variant
864            | Target::Struct
865            | Target::Field
866            | Target::Union
867            | Target::Trait
868            | Target::TraitAlias
869            | Target::Method(..)
870            | Target::ForeignFn
871            | Target::ForeignStatic
872            | Target::ForeignTy
873            | Target::GenericParam { .. }
874            | Target::MacroDef
875            | Target::PatField
876            | Target::ExprField
877            | Target::Crate
878            | Target::MacroCall
879            | Target::Delegation { .. }
880            | Target::Loop
881            | Target::ForLoop
882            | Target::While
883            | Target::Break => None,
884        } {
885            self.tcx.dcx().emit_err(diagnostics::DocAliasBadLocation { span, location });
886            return;
887        }
888        if self.tcx.hir_opt_name(hir_id) == Some(alias) {
889            self.tcx.dcx().emit_err(diagnostics::DocAliasNotAnAlias { span, attr_str: alias });
890            return;
891        }
892    }
893
894    fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
895        let item_kind = match self.tcx.hir_node(hir_id) {
896            hir::Node::Item(item) => Some(&item.kind),
897            _ => None,
898        };
899        match item_kind {
900            Some(ItemKind::Impl(i)) => {
901                let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
902                    || if let Some(&[hir::GenericArg::Type(ty)]) = i
903                        .of_trait
904                        .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
905                        .map(|last_segment| last_segment.args().args)
906                    {
907                        #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
908                    } else {
909                        false
910                    };
911                if !is_valid {
912                    self.dcx().emit_err(diagnostics::DocFakeVariadicNotValid { span });
913                }
914            }
915            _ => {
916                self.dcx().emit_err(diagnostics::DocKeywordOnlyImpl { span });
917            }
918        }
919    }
920
921    fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
922        let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
923            self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
924            return;
925        };
926        match item.kind {
927            ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
928                if generics.params.len() != 0 => {}
929            ItemKind::Trait { generics, items, .. }
930                if generics.params.len() != 0
931                    || items.iter().any(|item| {
932                        #[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)
933                    }) => {}
934            ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
935            _ => {
936                self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
937            }
938        }
939    }
940
941    /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes.
942    ///
943    /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
944    /// if there are conflicting attributes for one item.
945    ///
946    /// `specified_inline` is used to keep track of whether we have
947    /// already seen an inlining attribute for this item.
948    /// If so, `specified_inline` holds the value and the span of
949    /// the first `inline`/`no_inline` attribute.
950    fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
951        let span = match inline {
952            [] => return,
953            [(_, span)] => *span,
954            [(inline, span), rest @ ..] => {
955                for (inline2, span2) in rest {
956                    if inline2 != inline {
957                        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]);
958                        spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))msg!("this attribute..."));
959                        spans.push_span_label(
960                            *span2,
961                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))msg!("{\".\"}..conflicts with this attribute"),
962                        );
963                        self.dcx().emit_err(diagnostics::DocInlineConflict { spans });
964                        return;
965                    }
966                }
967                *span
968            }
969        };
970
971        match target {
972            Target::Use | Target::ExternCrate => {}
973            _ => {
974                self.tcx.emit_node_span_lint(
975                    INVALID_DOC_ATTRIBUTES,
976                    hir_id,
977                    span,
978                    diagnostics::DocInlineOnlyUse {
979                        attr_span: span,
980                        item_span: self.tcx.hir_span(hir_id),
981                    },
982                );
983            }
984        }
985    }
986
987    fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
988        if target != Target::ExternCrate {
989            self.tcx.emit_node_span_lint(
990                INVALID_DOC_ATTRIBUTES,
991                hir_id,
992                span,
993                diagnostics::DocMaskedOnlyExternCrate {
994                    attr_span: span,
995                    item_span: self.tcx.hir_span(hir_id),
996                },
997            );
998            return;
999        }
1000
1001        if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1002            self.tcx.emit_node_span_lint(
1003                INVALID_DOC_ATTRIBUTES,
1004                hir_id,
1005                span,
1006                diagnostics::DocMaskedNotExternCrateSelf {
1007                    attr_span: span,
1008                    item_span: self.tcx.hir_span(hir_id),
1009                },
1010            );
1011        }
1012    }
1013
1014    fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1015        let item_kind = match self.tcx.hir_node(hir_id) {
1016            hir::Node::Item(item) => Some(&item.kind),
1017            _ => None,
1018        };
1019        match item_kind {
1020            Some(ItemKind::Mod(_, module)) => {
1021                if !module.item_ids.is_empty() {
1022                    self.dcx()
1023                        .emit_err(diagnostics::DocKeywordAttributeEmptyMod { span, attr_name });
1024                    return;
1025                }
1026            }
1027            _ => {
1028                self.dcx().emit_err(diagnostics::DocKeywordAttributeNotMod { span, attr_name });
1029                return;
1030            }
1031        }
1032    }
1033
1034    /// Runs various checks on `#[doc]` attributes.
1035    ///
1036    /// `specified_inline` should be initialized to `None` and kept for the scope
1037    /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1038    ///
1039    /// [`check_doc_inline`]: Self::check_doc_inline
1040    fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1041        let DocAttribute {
1042            first_span: _,
1043            aliases,
1044            // valid pretty much anywhere, not checked here?
1045            // FIXME: should we?
1046            hidden: _,
1047            inline,
1048            // FIXME: currently unchecked
1049            cfg: _,
1050            // already checked in attr_parsing
1051            auto_cfg: _,
1052            // already checked in attr_parsing
1053            auto_cfg_change: _,
1054            fake_variadic,
1055            keyword,
1056            masked,
1057            // FIXME: currently unchecked
1058            notable_trait: _,
1059            search_unbox,
1060            // already checked in attr_parsing
1061            html_favicon_url: _,
1062            // already checked in attr_parsing
1063            html_logo_url: _,
1064            // already checked in attr_parsing
1065            html_playground_url: _,
1066            // already checked in attr_parsing
1067            html_root_url: _,
1068            // already checked in attr_parsing
1069            html_no_source: _,
1070            // already checked in attr_parsing
1071            issue_tracker_base_url: _,
1072            // already checked in attr_parsing
1073            rust_logo: _,
1074            // allowed anywhere
1075            test_attrs: _,
1076            // already checked in attr_parsing
1077            no_crate_inject: _,
1078            attribute,
1079        } = attr;
1080
1081        for (alias, span) in aliases {
1082            self.check_doc_alias_value(*span, hir_id, target, *alias);
1083        }
1084
1085        if let Some((_, span)) = keyword {
1086            self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1087        }
1088        if let Some((_, span)) = attribute {
1089            self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1090        }
1091
1092        if let Some(span) = fake_variadic {
1093            self.check_doc_fake_variadic(*span, hir_id);
1094        }
1095
1096        if let Some(span) = search_unbox {
1097            self.check_doc_search_unbox(*span, hir_id);
1098        }
1099
1100        self.check_doc_inline(hir_id, target, inline);
1101
1102        if let Some(span) = masked {
1103            self.check_doc_masked(*span, hir_id, target);
1104        }
1105    }
1106
1107    /// Checks if `#[may_dangle]` is applied to a lifetime or type generic parameter in `Drop` impl.
1108    fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1109        let hir::Node::GenericParam(
1110            param @ GenericParam {
1111                kind: hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. },
1112                ..
1113            },
1114        ) = self.tcx.hir_node(hir_id)
1115        else {
1116            self.dcx().delayed_bug("Checked in attr parser");
1117            return;
1118        };
1119
1120        if #[allow(non_exhaustive_omitted_patterns)] match param.source {
    hir::GenericParamSource::Generics => true,
    _ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1121            && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1122            && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1123            && let hir::ItemKind::Impl(impl_) = item.kind
1124            && let Some(of_trait) = impl_.of_trait
1125            && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1126            && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1127        {
1128            return;
1129        }
1130
1131        self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
1132    }
1133
1134    /// Checks if `#[link]` is applied to an item other than a foreign module.
1135    fn check_link(&self, hir_id: HirId, attr_span: Span, target: Target) {
1136        if target != Target::ForeignMod {
1137            return; // Checked by attribute parser
1138        }
1139
1140        if let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1141            && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1142            && !#[allow(non_exhaustive_omitted_patterns)] match abi {
    ExternAbi::Rust => true,
    _ => false,
}matches!(abi, ExternAbi::Rust)
1143        {
1144            return;
1145        }
1146
1147        self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr_span, diagnostics::Link);
1148    }
1149
1150    /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1151    fn check_rustc_legacy_const_generics(
1152        &self,
1153        item: Option<ItemLike<'_>>,
1154        attr_span: Span,
1155        index_list: &ThinVec<(usize, Span)>,
1156    ) {
1157        let Some(ItemLike::Item(Item {
1158            kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1159            ..
1160        })) = item
1161        else {
1162            // No error here, since it's already given by the parser
1163            return;
1164        };
1165
1166        for param in generics.params {
1167            match param.kind {
1168                hir::GenericParamKind::Const { .. } => {}
1169                _ => {
1170                    self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsOnly {
1171                        attr_span,
1172                        param_span: param.span,
1173                    });
1174                    return;
1175                }
1176            }
1177        }
1178
1179        if index_list.len() != generics.params.len() {
1180            self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndex {
1181                attr_span,
1182                generics_span: generics.span,
1183            });
1184            return;
1185        }
1186
1187        let arg_count = decl.inputs.len() + generics.params.len();
1188        for (index, span) in index_list {
1189            if *index >= arg_count {
1190                self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndexExceed {
1191                    span: *span,
1192                    arg_count,
1193                });
1194            }
1195        }
1196    }
1197
1198    /// Checks if the `#[repr]` attributes on `item` are valid.
1199    fn check_repr(
1200        &self,
1201        attrs: &[Attribute],
1202        span: Span,
1203        target: Target,
1204        item: Option<ItemLike<'_>>,
1205        hir_id: HirId,
1206    ) {
1207        // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1208        // ```
1209        // #[repr(foo)]
1210        // #[repr(bar, align(8))]
1211        // ```
1212        let (reprs, _first_attr_span) =
1213            {
    '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)))
1214                .unwrap_or((&[], None));
1215
1216        let mut int_reprs = 0;
1217        let mut is_explicit_rust = false;
1218        let mut is_c = false;
1219        let mut is_simd = false;
1220        let mut is_transparent = false;
1221
1222        for (repr, _repr_span) in reprs {
1223            match repr {
1224                ReprAttr::ReprRust => {
1225                    is_explicit_rust = true;
1226                }
1227                ReprAttr::ReprC => {
1228                    is_c = true;
1229                }
1230                ReprAttr::ReprAlign(..) => {}
1231                ReprAttr::ReprPacked(_) => {}
1232                ReprAttr::ReprSimd => {
1233                    is_simd = true;
1234                }
1235                ReprAttr::ReprTransparent => {
1236                    is_transparent = true;
1237                }
1238                ReprAttr::ReprInt(_) => {
1239                    int_reprs += 1;
1240                }
1241            };
1242        }
1243
1244        // Just point at all repr hints if there are any incompatibilities.
1245        // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1246        let hint_spans = reprs.iter().map(|(_, span)| *span);
1247
1248        // Error on repr(transparent, <anything else>).
1249        if is_transparent && reprs.len() > 1 {
1250            let hint_spans = hint_spans.clone().collect();
1251            self.dcx().emit_err(diagnostics::TransparentIncompatible {
1252                hint_spans,
1253                target: target.to_string(),
1254            });
1255        }
1256        // Error on `#[repr(transparent)]` in combination with
1257        // `#[rustc_pass_indirectly_in_non_rustic_abis]`
1258        if is_transparent
1259            && let Some(&pass_indirectly_span) =
1260                {
    '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)
1261        {
1262            self.dcx().emit_err(diagnostics::TransparentIncompatible {
1263                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],
1264                target: target.to_string(),
1265            });
1266        }
1267        if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1268            let hint_spans = hint_spans.clone().collect();
1269            self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
1270        }
1271        // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1272        if (int_reprs > 1)
1273            || (is_simd && is_c)
1274            || (int_reprs == 1
1275                && is_c
1276                && item.is_some_and(|item| {
1277                    if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1278                }))
1279        {
1280            self.tcx.emit_node_span_lint(
1281                CONFLICTING_REPR_HINTS,
1282                hir_id,
1283                hint_spans.collect::<Vec<Span>>(),
1284                diagnostics::ReprConflictingLint,
1285            );
1286        }
1287    }
1288
1289    /// Outputs an error for attributes that can only be applied to macros, such as
1290    /// `#[allow_internal_unsafe]` and `#[allow_internal_unstable]`.
1291    /// (Allows proc_macro functions)
1292    // FIXME(jdonszelmann): if possible, move to attr parsing
1293    fn check_macro_only_attr(
1294        &self,
1295        attr_span: Span,
1296        span: Span,
1297        target: Target,
1298        attrs: &[Attribute],
1299    ) {
1300        match target {
1301            Target::Fn => {
1302                for attr in attrs {
1303                    if attr.is_proc_macro_attr() {
1304                        // return on proc macros
1305                        return;
1306                    }
1307                }
1308                self.tcx.dcx().emit_err(diagnostics::MacroOnlyAttribute { attr_span, span });
1309            }
1310            _ => {}
1311        }
1312    }
1313
1314    /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1315    /// (Allows proc_macro functions)
1316    fn check_rustc_allow_const_fn_unstable(
1317        &self,
1318        hir_id: HirId,
1319        attr_span: Span,
1320        span: Span,
1321        target: Target,
1322    ) {
1323        match target {
1324            Target::Fn | Target::Method(_) => {
1325                if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1326                    self.tcx
1327                        .dcx()
1328                        .emit_err(diagnostics::RustcAllowConstFnUnstable { attr_span, span });
1329                }
1330            }
1331            _ => {}
1332        }
1333    }
1334
1335    fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1336        match target {
1337            Target::AssocConst | Target::Method(..) | Target::AssocTy
1338                if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1339                    == DefKind::Impl { of_trait: true } =>
1340            {
1341                self.tcx.emit_node_span_lint(
1342                    UNUSED_ATTRIBUTES,
1343                    hir_id,
1344                    attr_span,
1345                    diagnostics::DeprecatedAnnotationHasNoEffect { span: attr_span },
1346                );
1347            }
1348            _ => {}
1349        }
1350    }
1351
1352    fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1353        if target != Target::MacroDef {
1354            return;
1355        }
1356
1357        // special case when `#[macro_export]` is applied to a macro 2.0
1358        let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1359        let is_decl_macro = !macro_definition.macro_rules;
1360
1361        if is_decl_macro {
1362            self.tcx.emit_node_span_lint(
1363                UNUSED_ATTRIBUTES,
1364                hir_id,
1365                attr_span,
1366                diagnostics::MacroExport::OnDeclMacro,
1367            );
1368        }
1369    }
1370
1371    fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1372        // Warn on useless empty attributes.
1373        // FIXME(jdonszelmann): this lint should be moved to attribute parsing, see `AcceptContext::warn_empty_attribute`
1374        let note =
1375            if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1376                && attr.meta_item_list().is_some_and(|list| list.is_empty())
1377            {
1378                diagnostics::UnusedNote::EmptyList { name: attr.name().unwrap() }
1379            } else if attr.has_any_name(&[
1380                sym::allow,
1381                sym::warn,
1382                sym::deny,
1383                sym::forbid,
1384                sym::expect,
1385            ]) && let Some(meta) = attr.meta_item_list()
1386                && let [meta] = meta.as_slice()
1387                && let Some(item) = meta.meta_item()
1388                && let MetaItemKind::NameValue(_) = &item.kind
1389                && item.path == sym::reason
1390            {
1391                diagnostics::UnusedNote::NoLints { name: attr.name().unwrap() }
1392            } else if attr.has_any_name(&[
1393                sym::allow,
1394                sym::warn,
1395                sym::deny,
1396                sym::forbid,
1397                sym::expect,
1398            ]) && let Some(meta) = attr.meta_item_list()
1399                && meta.iter().any(|meta| {
1400                    meta.meta_item().map_or(false, |item| {
1401                        item.path == sym::linker_messages || item.path == sym::linker_info
1402                    })
1403                })
1404            {
1405                if hir_id != CRATE_HIR_ID {
1406                    match style {
1407                        Some(ast::AttrStyle::Outer) => {
1408                            let attr_span = attr.span();
1409                            let bang_position = self
1410                                .tcx
1411                                .sess
1412                                .source_map()
1413                                .span_until_char(attr_span, '[')
1414                                .shrink_to_hi();
1415
1416                            self.tcx.emit_node_span_lint(
1417                                UNUSED_ATTRIBUTES,
1418                                hir_id,
1419                                attr_span,
1420                                diagnostics::OuterCrateLevelAttr {
1421                                    suggestion: diagnostics::OuterCrateLevelAttrSuggestion {
1422                                        bang_position,
1423                                    },
1424                                },
1425                            )
1426                        }
1427                        Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1428                            UNUSED_ATTRIBUTES,
1429                            hir_id,
1430                            attr.span(),
1431                            diagnostics::InnerCrateLevelAttr,
1432                        ),
1433                    };
1434                    return;
1435                } else {
1436                    let never_needs_link = self
1437                        .tcx
1438                        .crate_types()
1439                        .iter()
1440                        .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
    CrateType::Rlib | CrateType::StaticLib => true,
    _ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1441                    if never_needs_link {
1442                        diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly
1443                    } else {
1444                        return;
1445                    }
1446                }
1447            } else if hir_id == CRATE_HIR_ID
1448                && attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1449                && let Some(meta) = attr.meta_item_list()
1450                && meta.iter().any(|meta| {
1451                    meta.meta_item().is_some_and(|item| item.path == sym::dead_code_pub_in_binary)
1452                })
1453                && !self.tcx.crate_types().contains(&CrateType::Executable)
1454            {
1455                diagnostics::UnusedNote::NoEffectDeadCodePubInBinary
1456            } else if attr.has_name(sym::default_method_body_is_const) {
1457                diagnostics::UnusedNote::DefaultMethodBodyConst
1458            } else {
1459                return;
1460            };
1461
1462        self.tcx.emit_node_span_lint(
1463            UNUSED_ATTRIBUTES,
1464            hir_id,
1465            attr.span(),
1466            diagnostics::Unused { attr_span: attr.span(), note },
1467        );
1468    }
1469
1470    /// A best effort attempt to create an error for a mismatching proc macro signature.
1471    ///
1472    /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
1473    fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1474        if target != Target::Fn {
1475            return;
1476        }
1477
1478        let tcx = self.tcx;
1479        let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1480            return;
1481        };
1482        let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1483            return;
1484        };
1485
1486        let def_id = hir_id.expect_owner().def_id;
1487        let param_env = ty::ParamEnv::empty();
1488
1489        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1490        let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1491
1492        let span = tcx.def_span(def_id);
1493        let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1494        let sig = tcx.liberate_late_bound_regions(
1495            def_id.to_def_id(),
1496            tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1497        );
1498
1499        let mut cause = ObligationCause::misc(span, def_id);
1500        let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1501
1502        // proc macro is not WF.
1503        let errors = ocx.try_evaluate_obligations();
1504        if !errors.is_empty() {
1505            return;
1506        }
1507
1508        let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1509            std::iter::repeat_n(
1510                token_stream,
1511                match kind {
1512                    ProcMacroKind::Attribute => 2,
1513                    ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1514                },
1515            ),
1516            token_stream,
1517        );
1518
1519        if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1520            let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1521
1522            let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1523            if let Some(hir_sig) = hir_sig {
1524                match terr {
1525                    TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1526                        if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1527                            diag.span(ty.span);
1528                            cause.span = ty.span;
1529                        } else if idx == hir_sig.decl.inputs.len() {
1530                            let span = hir_sig.decl.output.span();
1531                            diag.span(span);
1532                            cause.span = span;
1533                        }
1534                    }
1535                    TypeError::ArgCount => {
1536                        if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1537                            diag.span(ty.span);
1538                            cause.span = ty.span;
1539                        }
1540                    }
1541                    TypeError::SafetyMismatch(_) => {
1542                        // FIXME: Would be nice if we had a span here..
1543                    }
1544                    TypeError::AbiMismatch(_) => {
1545                        // FIXME: Would be nice if we had a span here..
1546                    }
1547                    TypeError::VariadicMismatch(_) => {
1548                        // FIXME: Would be nice if we had a span here..
1549                    }
1550                    _ => {}
1551                }
1552            }
1553
1554            infcx.err_ctxt().note_type_err(
1555                &mut diag,
1556                &cause,
1557                None,
1558                Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1559                    expected: ty::Binder::dummy(expected_sig),
1560                    found: ty::Binder::dummy(sig),
1561                }))),
1562                terr,
1563                false,
1564                None,
1565            );
1566            diag.emit();
1567            self.abort.set(true);
1568        }
1569
1570        let errors = ocx.evaluate_obligations_error_on_ambiguity();
1571        if !errors.is_empty() {
1572            infcx.err_ctxt().report_fulfillment_errors(errors);
1573            self.abort.set(true);
1574        }
1575    }
1576
1577    fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1578        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))
1579            .unwrap_or(false)
1580        {
1581            self.dcx().emit_err(diagnostics::RustcPubTransparent { span, attr_span });
1582        }
1583    }
1584
1585    fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1586        if let (Target::Closure, None) = (
1587            target,
1588            {
    '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),
1589        ) {
1590            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!(
1591                self.tcx.hir_expect_expr(hir_id).kind,
1592                hir::ExprKind::Closure(hir::Closure {
1593                    kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1594                    ..
1595                })
1596            );
1597            let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1598            let parent_span = self.tcx.def_span(parent_did);
1599
1600            if let Some(attr_span) = {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(parent_did, &self.tcx)
                {
                #[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!(
1601                self.tcx, parent_did,
1602                Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1603            ) && is_coro
1604            {
1605                self.dcx()
1606                    .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1607            }
1608        }
1609    }
1610
1611    fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1612        if let Some(export_name_span) =
1613            {
    '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)
1614            && let Some(no_mangle_span) =
1615                {
    '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)
1616        {
1617            let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1618                "#[unsafe(no_mangle)]"
1619            } else {
1620                "#[no_mangle]"
1621            };
1622            let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1623                "#[unsafe(export_name)]"
1624            } else {
1625                "#[export_name]"
1626            };
1627
1628            self.tcx.emit_node_span_lint(
1629                lint::builtin::UNUSED_ATTRIBUTES,
1630                hir_id,
1631                no_mangle_span,
1632                diagnostics::MixedExportNameAndNoMangle {
1633                    no_mangle_span,
1634                    export_name_span,
1635                    no_mangle_attr,
1636                    export_name_attr,
1637                },
1638            );
1639        }
1640    }
1641
1642    fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1643        if let Some(optimize_span) =
1644            {
    '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(Optimize(OptimizeAttr::DoNotOptimize,
                    span)) => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Optimize(OptimizeAttr::DoNotOptimize, span) => *span)
1645            && let Some((inline_attr, inline_span)) =
1646                {
    '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(inline_attr, span)) => {
                    break 'done Some((inline_attr, *span));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Inline(inline_attr, span) => (inline_attr, *span))
1647            && inline_attr != &InlineAttr::Never
1648        {
1649            self.dcx()
1650                .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1651        }
1652    }
1653}
1654
1655impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1656    type NestedFilter = nested_filter::OnlyBodies;
1657
1658    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1659        self.tcx
1660    }
1661
1662    fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1663        // Historically we've run more checks on non-exported than exported macros,
1664        // so this lets us continue to run them while maintaining backwards compatibility.
1665        // In the long run, the checks should be harmonized.
1666        if let ItemKind::Macro(_, macro_def, _) = item.kind {
1667            let def_id = item.owner_id.to_def_id();
1668            if macro_def.macro_rules && !{
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
                    #[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 { .. }) {
1669                check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1670            }
1671        }
1672
1673        let target = Target::from_item(item);
1674        self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1675        intravisit::walk_item(self, item)
1676    }
1677
1678    fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1679        self.check_attributes(
1680            where_predicate.hir_id,
1681            where_predicate.span,
1682            Target::WherePredicate,
1683            None,
1684        );
1685        intravisit::walk_where_predicate(self, where_predicate)
1686    }
1687
1688    fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1689        let target = Target::from_generic_param(generic_param);
1690        self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1691        intravisit::walk_generic_param(self, generic_param)
1692    }
1693
1694    fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1695        let target = Target::from_trait_item(trait_item);
1696        self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1697        intravisit::walk_trait_item(self, trait_item)
1698    }
1699
1700    fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1701        self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1702        intravisit::walk_field_def(self, struct_field);
1703    }
1704
1705    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1706        self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1707        intravisit::walk_arm(self, arm);
1708    }
1709
1710    fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1711        let target = Target::from_foreign_item(f_item);
1712        self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1713        intravisit::walk_foreign_item(self, f_item)
1714    }
1715
1716    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1717        let target = target_from_impl_item(self.tcx, impl_item);
1718        self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1719        intravisit::walk_impl_item(self, impl_item)
1720    }
1721
1722    fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1723        // When checking statements ignore expressions, they will be checked later.
1724        if let hir::StmtKind::Let(l) = stmt.kind {
1725            self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1726        }
1727        intravisit::walk_stmt(self, stmt)
1728    }
1729
1730    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1731        let target = match expr.kind {
1732            hir::ExprKind::Closure { .. } => Target::Closure,
1733            _ => Target::Expression,
1734        };
1735
1736        self.check_attributes(expr.hir_id, expr.span, target, None);
1737        intravisit::walk_expr(self, expr)
1738    }
1739
1740    fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
1741        self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
1742        intravisit::walk_expr_field(self, field)
1743    }
1744
1745    fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
1746        self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
1747        intravisit::walk_variant(self, variant)
1748    }
1749
1750    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1751        self.check_attributes(param.hir_id, param.span, Target::Param, None);
1752
1753        intravisit::walk_param(self, param);
1754    }
1755
1756    fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
1757        self.check_attributes(field.hir_id, field.span, Target::PatField, None);
1758        intravisit::walk_pat_field(self, field);
1759    }
1760}
1761
1762fn is_c_like_enum(item: &Item<'_>) -> bool {
1763    if let ItemKind::Enum(_, _, ref def) = item.kind {
1764        for variant in def.variants {
1765            match variant.data {
1766                hir::VariantData::Unit(..) => { /* continue */ }
1767                _ => return false,
1768            }
1769        }
1770        true
1771    } else {
1772        false
1773    }
1774}
1775
1776fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
1777    let attrs = tcx.hir_attrs(item.hir_id());
1778
1779    if let Some(attr_span) =
1780        {
    '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)
1781    {
1782        tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
1783    }
1784}
1785
1786fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1787    let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
1788    tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
1789    if module_def_id.to_local_def_id().is_top_level_module() {
1790        check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
1791    }
1792    if check_attr_visitor.abort.get() {
1793        tcx.dcx().abort_if_errors()
1794    }
1795}
1796
1797pub(crate) fn provide(providers: &mut Providers) {
1798    *providers = Providers { check_mod_attrs, ..*providers };
1799}
1800
1801fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
1802    #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
1803        || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
1804            fn_ptr_ty.decl.inputs.len() == 1
1805        } else {
1806            false
1807        }
1808        || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
1809            && let Some(&[hir::GenericArg::Type(ty)]) =
1810                path.segments.last().map(|last| last.args().args)
1811        {
1812            doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
1813        } else {
1814            false
1815        })
1816}