Skip to main content

rustc_passes/
check_attr.rs

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