Skip to main content

rustc_passes/
check_attr.rs

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