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