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