Skip to main content

rustc_passes/
check_attr.rs

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