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