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