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, G> rustc_errors::Diagnostic<'_sess, G> for
            DiagnosticOnConstOnlyForNonConstTraitImpls {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    DiagnosticOnConstOnlyForNonConstTraitImpls {
                        item_span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `diagnostic::on_const` attribute can only be applied to non-const trait implementations")));
                        ;
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait implementation")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
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                _ => 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                _ => 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                _ => 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) -> ProcMacroKind { *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                                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::GenericParam { .. }
848            | Target::MacroDef
849            | Target::PatField
850            | Target::ExprField
851            | Target::Crate
852            | Target::MacroCall
853            | Target::Delegation { .. }
854            | Target::Loop
855            | Target::ForLoop
856            | Target::While
857            | Target::Break => None,
858        } {
859            self.tcx.dcx().emit_err(diagnostics::DocAliasBadLocation { span, location });
860            return;
861        }
862        if self.tcx.hir_opt_name(hir_id) == Some(alias) {
863            self.tcx.dcx().emit_err(diagnostics::DocAliasNotAnAlias { span, attr_str: alias });
864            return;
865        }
866    }
867
868    fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
869        let item_kind = match self.tcx.hir_node(hir_id) {
870            hir::Node::Item(item) => Some(&item.kind),
871            _ => None,
872        };
873        match item_kind {
874            Some(ItemKind::Impl(i)) => {
875                let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
876                    || if let Some(&[hir::GenericArg::Type(ty)]) = i
877                        .of_trait
878                        .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
879                        .map(|last_segment| last_segment.args().args)
880                    {
881                        #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
882                    } else {
883                        false
884                    };
885                if !is_valid {
886                    self.dcx().emit_err(diagnostics::DocFakeVariadicNotValid { span });
887                }
888            }
889            _ => {
890                self.dcx().emit_err(diagnostics::DocKeywordOnlyImpl { span });
891            }
892        }
893    }
894
895    fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
896        let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
897            self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
898            return;
899        };
900        match item.kind {
901            ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
902                if generics.params.len() != 0 => {}
903            ItemKind::Trait { generics, items, .. }
904                if generics.params.len() != 0
905                    || items.iter().any(|item| {
906                        #[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)
907                    }) => {}
908            ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
909            _ => {
910                self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
911            }
912        }
913    }
914
915    /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes.
916    ///
917    /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
918    /// if there are conflicting attributes for one item.
919    ///
920    /// `specified_inline` is used to keep track of whether we have
921    /// already seen an inlining attribute for this item.
922    /// If so, `specified_inline` holds the value and the span of
923    /// the first `inline`/`no_inline` attribute.
924    fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
925        let span = match inline {
926            [] => return,
927            [(_, span)] => *span,
928            [(inline, span), rest @ ..] => {
929                for (inline2, span2) in rest {
930                    if inline2 != inline {
931                        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]);
932                        spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))msg!("this attribute..."));
933                        spans.push_span_label(
934                            *span2,
935                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))msg!("{\".\"}..conflicts with this attribute"),
936                        );
937                        self.dcx().emit_err(diagnostics::DocInlineConflict { spans });
938                        return;
939                    }
940                }
941                *span
942            }
943        };
944
945        match target {
946            Target::Use | Target::ExternCrate => {}
947            _ => {
948                self.tcx.emit_node_span_lint(
949                    INVALID_DOC_ATTRIBUTES,
950                    hir_id,
951                    span,
952                    diagnostics::DocInlineOnlyUse {
953                        attr_span: span,
954                        item_span: self.tcx.hir_span(hir_id),
955                    },
956                );
957            }
958        }
959    }
960
961    fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
962        if target != Target::ExternCrate {
963            self.tcx.emit_node_span_lint(
964                INVALID_DOC_ATTRIBUTES,
965                hir_id,
966                span,
967                diagnostics::DocMaskedOnlyExternCrate {
968                    attr_span: span,
969                    item_span: self.tcx.hir_span(hir_id),
970                },
971            );
972            return;
973        }
974
975        if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
976            self.tcx.emit_node_span_lint(
977                INVALID_DOC_ATTRIBUTES,
978                hir_id,
979                span,
980                diagnostics::DocMaskedNotExternCrateSelf {
981                    attr_span: span,
982                    item_span: self.tcx.hir_span(hir_id),
983                },
984            );
985        }
986    }
987
988    fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
989        let item_kind = match self.tcx.hir_node(hir_id) {
990            hir::Node::Item(item) => Some(&item.kind),
991            _ => None,
992        };
993        if let Some(ItemKind::Const(ident, _gen, _ty, _rhs)) = item_kind
994            && ident.name == kw::Underscore
995        {
996        } else {
997            self.dcx().emit_err(diagnostics::DocKeywordAttributeNotAnonConst { span, attr_name });
998        }
999    }
1000
1001    /// Runs various checks on `#[doc]` attributes.
1002    ///
1003    /// `specified_inline` should be initialized to `None` and kept for the scope
1004    /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1005    ///
1006    /// [`check_doc_inline`]: Self::check_doc_inline
1007    fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1008        let DocAttribute {
1009            first_span: _,
1010            aliases,
1011            // valid pretty much anywhere, not checked here?
1012            // FIXME: should we?
1013            hidden: _,
1014            inline,
1015            // FIXME: currently unchecked
1016            cfg: _,
1017            // already checked in attr_parsing
1018            auto_cfg: _,
1019            // already checked in attr_parsing
1020            auto_cfg_change: _,
1021            fake_variadic,
1022            keyword,
1023            masked,
1024            // FIXME: currently unchecked
1025            notable_trait: _,
1026            search_unbox,
1027            // already checked in attr_parsing
1028            html_favicon_url: _,
1029            // already checked in attr_parsing
1030            html_logo_url: _,
1031            // already checked in attr_parsing
1032            html_playground_url: _,
1033            // already checked in attr_parsing
1034            html_root_url: _,
1035            // already checked in attr_parsing
1036            html_no_source: _,
1037            // already checked in attr_parsing
1038            issue_tracker_base_url: _,
1039            // already checked in attr_parsing
1040            rust_logo: _,
1041            // allowed anywhere
1042            test_attrs: _,
1043            // already checked in attr_parsing
1044            no_crate_inject: _,
1045            attribute,
1046        } = attr;
1047
1048        for (alias, span) in aliases {
1049            self.check_doc_alias_value(*span, hir_id, target, *alias);
1050        }
1051
1052        if let Some((_, span)) = keyword {
1053            self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1054        }
1055        if let Some((_, span)) = attribute {
1056            self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1057        }
1058
1059        if let Some(span) = fake_variadic {
1060            self.check_doc_fake_variadic(*span, hir_id);
1061        }
1062
1063        if let Some(span) = search_unbox {
1064            self.check_doc_search_unbox(*span, hir_id);
1065        }
1066
1067        self.check_doc_inline(hir_id, target, inline);
1068
1069        if let Some(span) = masked {
1070            self.check_doc_masked(*span, hir_id, target);
1071        }
1072    }
1073
1074    /// Checks if `#[may_dangle]` is applied to a lifetime or type generic parameter in `Drop` impl.
1075    fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1076        let hir::Node::GenericParam(
1077            param @ GenericParam {
1078                kind: hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. },
1079                ..
1080            },
1081        ) = self.tcx.hir_node(hir_id)
1082        else {
1083            self.dcx().delayed_bug("Checked in attr parser");
1084            return;
1085        };
1086
1087        if #[allow(non_exhaustive_omitted_patterns)] match param.source {
    hir::GenericParamSource::Generics => true,
    _ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1088            && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1089            && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1090            && let hir::ItemKind::Impl(impl_) = item.kind
1091            && let Some(of_trait) = impl_.of_trait
1092            && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1093            && self.tcx.is_lang_item(def_id, LangItem::Drop)
1094        {
1095            return;
1096        }
1097
1098        self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
1099    }
1100
1101    /// Checks if `#[link]` is applied to an item other than a foreign module.
1102    fn check_link(&self, hir_id: HirId, attr_span: Span, target: Target) {
1103        if target != Target::ForeignMod {
1104            return; // Checked by attribute parser
1105        }
1106
1107        if let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1108            && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1109            && !#[allow(non_exhaustive_omitted_patterns)] match abi {
    ExternAbi::Rust => true,
    _ => false,
}matches!(abi, ExternAbi::Rust)
1110        {
1111            return;
1112        }
1113
1114        self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr_span, diagnostics::Link);
1115    }
1116
1117    /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1118    fn check_rustc_legacy_const_generics(
1119        &self,
1120        item: Option<&'tcx Item<'tcx>>,
1121        attr_span: Span,
1122        index_list: &ThinVec<(usize, Span)>,
1123    ) {
1124        let Some(Item { kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. }, .. }) = item
1125        else {
1126            // No error here, since it's already given by the parser
1127            return;
1128        };
1129
1130        for param in generics.params {
1131            match param.kind {
1132                hir::GenericParamKind::Const { .. } => {}
1133                _ => {
1134                    self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsOnly {
1135                        attr_span,
1136                        param_span: param.span,
1137                    });
1138                    return;
1139                }
1140            }
1141        }
1142
1143        if index_list.len() != generics.params.len() {
1144            self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndex {
1145                attr_span,
1146                generics_span: generics.span,
1147            });
1148            return;
1149        }
1150
1151        let arg_count = decl.inputs.len() + generics.params.len();
1152        for (index, span) in index_list {
1153            if *index >= arg_count {
1154                self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndexExceed {
1155                    span: *span,
1156                    arg_count,
1157                });
1158            }
1159        }
1160    }
1161
1162    /// Checks if the `#[repr]` attributes on `item` are valid.
1163    fn check_repr(
1164        &self,
1165        attrs: &[Attribute],
1166        span: Span,
1167        target: Target,
1168        item: Option<&'tcx Item<'tcx>>,
1169        hir_id: HirId,
1170    ) {
1171        // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1172        // ```
1173        // #[repr(foo)]
1174        // #[repr(bar, align(8))]
1175        // ```
1176        let (reprs, _first_attr_span) =
1177            {
    '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)))
1178                .unwrap_or((&[], None));
1179
1180        let mut int_reprs = 0;
1181        let mut is_explicit_rust = false;
1182        let mut is_c = false;
1183        let mut is_simd = false;
1184        let mut is_transparent = false;
1185
1186        for (repr, _repr_span) in reprs {
1187            match repr {
1188                ReprAttr::ReprRust => {
1189                    is_explicit_rust = true;
1190                }
1191                ReprAttr::ReprC => {
1192                    is_c = true;
1193                }
1194                ReprAttr::ReprAlign(..) => (),
1195                ReprAttr::ReprPacked(..) => (),
1196                ReprAttr::ReprSimd => {
1197                    is_simd = true;
1198                }
1199                ReprAttr::ReprTransparent => {
1200                    is_transparent = true;
1201                }
1202                ReprAttr::ReprInt(..) => {
1203                    int_reprs += 1;
1204                }
1205            };
1206        }
1207
1208        if !reprs.is_empty() {
1209            let sorted_reprs = {
1210                let mut to_sort = reprs.to_owned();
1211                to_sort.sort_unstable();
1212                to_sort
1213            };
1214
1215            // To collect all duplicates, get subslices where all of the elements of the subslice
1216            // are equal, then filter out all those whose length is not 1. We could return warnings
1217            // for each of them, but that's annoyingly excessive. So we instead collect all spans in
1218            // one big Vec.
1219            let spans: Vec<Span> = sorted_reprs
1220                .chunk_by(|(a, _), (b, _)| a == b)
1221                .map(ToOwned::to_owned)
1222                .filter(|slice| slice.len() != 1)
1223                .flatten()
1224                .map(|(_, span)| span)
1225                .collect();
1226
1227            if !spans.is_empty() {
1228                self.tcx.emit_node_span_lint(
1229                    REPEATED_REPRS,
1230                    hir_id,
1231                    spans,
1232                    diagnostics::RepeatedRepr,
1233                );
1234            }
1235        }
1236
1237        // Just point at all repr hints if there are any incompatibilities.
1238        // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1239        let hint_spans = reprs.iter().map(|(_, span)| *span);
1240
1241        // Error on repr(transparent, <anything else>).
1242        if is_transparent && reprs.len() > 1 {
1243            let hint_spans = hint_spans.clone().collect();
1244            self.dcx().emit_err(diagnostics::TransparentIncompatible {
1245                hint_spans,
1246                target: target.to_string(),
1247            });
1248        }
1249        // Error on `#[repr(transparent)]` in combination with
1250        // `#[rustc_pass_indirectly_in_non_rustic_abis]`
1251        if is_transparent
1252            && let Some(&pass_indirectly_span) =
1253                {
    '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)
1254        {
1255            self.dcx().emit_err(diagnostics::TransparentIncompatible {
1256                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],
1257                target: target.to_string(),
1258            });
1259        }
1260        if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1261            let hint_spans = hint_spans.clone().collect();
1262            self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
1263        }
1264        // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1265        if (int_reprs > 1)
1266            || (is_simd && is_c)
1267            || (int_reprs == 1 && is_c && item.is_some_and(is_c_like_enum))
1268        {
1269            self.tcx.emit_node_span_lint(
1270                CONFLICTING_REPR_HINTS,
1271                hir_id,
1272                hint_spans.collect::<Vec<Span>>(),
1273                diagnostics::ReprConflictingLint,
1274            );
1275        }
1276    }
1277
1278    /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1279    /// (Allows proc_macro functions)
1280    fn check_rustc_allow_const_fn_unstable(
1281        &self,
1282        hir_id: HirId,
1283        attr_span: Span,
1284        span: Span,
1285        target: Target,
1286    ) {
1287        match target {
1288            Target::Fn | Target::Method(_) => {
1289                if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1290                    self.tcx
1291                        .dcx()
1292                        .emit_err(diagnostics::RustcAllowConstFnUnstable { attr_span, span });
1293                }
1294            }
1295            _ => {}
1296        }
1297    }
1298
1299    fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1300        if target != Target::MacroDef {
1301            return;
1302        }
1303
1304        // special case when `#[macro_export]` is applied to a macro 2.0
1305        let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1306        let is_decl_macro = !macro_definition.macro_rules;
1307
1308        if is_decl_macro {
1309            self.tcx.emit_node_span_lint(
1310                UNUSED_ATTRIBUTES,
1311                hir_id,
1312                attr_span,
1313                diagnostics::MacroExport::OnDeclMacro,
1314            );
1315        }
1316    }
1317
1318    fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
1319        // Warn on useless empty attributes.
1320        // FIXME(jdonszelmann): this lint should be moved to attribute parsing, see `AcceptContext::warn_empty_attribute`
1321        let note =
1322            if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1323                && attr.meta_item_list().is_some_and(|list| list.is_empty())
1324            {
1325                diagnostics::UnusedNote::EmptyList { name: attr.name().unwrap() }
1326            } else if attr.has_any_name(&[
1327                sym::allow,
1328                sym::warn,
1329                sym::deny,
1330                sym::forbid,
1331                sym::expect,
1332            ]) && let Some(meta) = attr.meta_item_list()
1333                && let [meta] = meta.as_slice()
1334                && let Some(item) = meta.meta_item()
1335                && let MetaItemKind::NameValue(_) = &item.kind
1336                && item.path == sym::reason
1337            {
1338                diagnostics::UnusedNote::NoLints { name: attr.name().unwrap() }
1339            } else if attr.has_any_name(&[
1340                sym::allow,
1341                sym::warn,
1342                sym::deny,
1343                sym::forbid,
1344                sym::expect,
1345            ]) && let Some(meta) = attr.meta_item_list()
1346                && meta.iter().any(|meta| {
1347                    meta.meta_item().map_or(false, |item| {
1348                        item.path == sym::linker_messages || item.path == sym::linker_info
1349                    })
1350                })
1351            {
1352                if hir_id != CRATE_HIR_ID {
1353                    return;
1354                } else {
1355                    let never_needs_link = self
1356                        .tcx
1357                        .crate_types()
1358                        .iter()
1359                        .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
    CrateType::Rlib | CrateType::StaticLib => true,
    _ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1360                    if never_needs_link {
1361                        diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly
1362                    } else {
1363                        return;
1364                    }
1365                }
1366            } else if hir_id == CRATE_HIR_ID
1367                && attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1368                && let Some(meta) = attr.meta_item_list()
1369                && meta.iter().any(|meta| {
1370                    meta.meta_item().is_some_and(|item| item.path == sym::dead_code_pub_in_binary)
1371                })
1372                && !self.tcx.crate_types().contains(&CrateType::Executable)
1373            {
1374                diagnostics::UnusedNote::NoEffectDeadCodePubInBinary
1375            } else {
1376                return;
1377            };
1378
1379        self.tcx.emit_node_span_lint(
1380            UNUSED_ATTRIBUTES,
1381            hir_id,
1382            attr.span(),
1383            diagnostics::Unused { attr_span: attr.span(), note },
1384        );
1385    }
1386
1387    /// A best effort attempt to create an error for a mismatching proc macro signature.
1388    ///
1389    /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
1390    fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1391        if target != Target::Fn {
1392            return;
1393        }
1394
1395        let tcx = self.tcx;
1396        let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1397            return;
1398        };
1399        let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1400            return;
1401        };
1402
1403        let def_id = hir_id.expect_owner().def_id;
1404        let param_env = ty::ParamEnv::empty();
1405
1406        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1407        let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1408
1409        let span = tcx.def_span(def_id);
1410        let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1411        let sig = tcx.liberate_late_bound_regions(
1412            def_id.to_def_id(),
1413            tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1414        );
1415
1416        let mut cause = ObligationCause::misc(span, def_id);
1417        let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1418
1419        // proc macro is not WF.
1420        let errors = ocx.try_evaluate_obligations();
1421        if !errors.no_errors() {
1422            return;
1423        }
1424
1425        let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1426            std::iter::repeat_n(
1427                token_stream,
1428                match kind {
1429                    ProcMacroKind::Attribute => 2,
1430                    ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1431                },
1432            ),
1433            token_stream,
1434        );
1435
1436        if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1437            let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1438
1439            let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1440            if let Some(hir_sig) = hir_sig {
1441                match terr {
1442                    TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1443                        if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1444                            diag.span(ty.span);
1445                            cause.span = ty.span;
1446                        } else if idx == hir_sig.decl.inputs.len() {
1447                            let span = hir_sig.decl.output.span();
1448                            diag.span(span);
1449                            cause.span = span;
1450                        }
1451                    }
1452                    TypeError::ArgCount => {
1453                        if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1454                            diag.span(ty.span);
1455                            cause.span = ty.span;
1456                        }
1457                    }
1458                    TypeError::SafetyMismatch(_) => {
1459                        // FIXME: Would be nice if we had a span here..
1460                    }
1461                    TypeError::AbiMismatch(_) => {
1462                        // FIXME: Would be nice if we had a span here..
1463                    }
1464                    TypeError::VariadicMismatch(_) => {
1465                        // FIXME: Would be nice if we had a span here..
1466                    }
1467                    _ => {}
1468                }
1469            }
1470
1471            infcx.err_ctxt().note_type_err(
1472                &mut diag,
1473                &cause,
1474                None,
1475                Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1476                    expected: ty::Binder::dummy(expected_sig),
1477                    found: ty::Binder::dummy(sig),
1478                }))),
1479                terr,
1480                false,
1481                None,
1482            );
1483            diag.emit();
1484            self.abort.set(true);
1485        }
1486
1487        let errors = ocx.evaluate_obligations_error_on_ambiguity();
1488        if let TraitErrors::HasErrors(errors) = errors {
1489            infcx.err_ctxt().report_fulfillment_errors(errors);
1490            self.abort.set(true);
1491        }
1492    }
1493
1494    fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1495        if let (Target::Closure, None) = (
1496            target,
1497            {
    '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),
1498        ) {
1499            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!(
1500                self.tcx.hir_expect_expr(hir_id).kind,
1501                hir::ExprKind::Closure(hir::Closure {
1502                    kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1503                    ..
1504                })
1505            );
1506            let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1507            let parent_span = self.tcx.def_span(parent_did);
1508
1509            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!(
1510                self.tcx, parent_did,
1511                Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1512            ) && is_coro
1513            {
1514                self.dcx()
1515                    .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1516            }
1517        }
1518    }
1519
1520    fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1521        if let Some(export_name_span) =
1522            {
    '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)
1523            && let Some(no_mangle_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(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)
1525        {
1526            let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1527                "#[unsafe(no_mangle)]"
1528            } else {
1529                "#[no_mangle]"
1530            };
1531            let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1532                "#[unsafe(export_name)]"
1533            } else {
1534                "#[export_name]"
1535            };
1536
1537            self.tcx.emit_node_span_lint(
1538                UNUSED_ATTRIBUTES,
1539                hir_id,
1540                no_mangle_span,
1541                diagnostics::MixedExportNameAndNoMangle {
1542                    no_mangle_span,
1543                    export_name_span,
1544                    no_mangle_attr,
1545                    export_name_attr,
1546                },
1547            );
1548        }
1549    }
1550
1551    fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1552        if let Some(optimize_span) =
1553            {
    '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)
1554            && let Some((inline_attr, inline_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(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))
1556            && inline_attr != &InlineAttr::Never
1557        {
1558            self.dcx()
1559                .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1560        }
1561    }
1562
1563    fn check_linkage(
1564        &self,
1565        span: Span,
1566        hir_id: HirId,
1567        target: Target,
1568        item: Option<&'tcx Item<'tcx>>,
1569    ) {
1570        // FIXME(eii) Once eii is no longer so experimental, suggest doing
1571        // linkage stuff with externally implementable items instead
1572        match target {
1573            Target::ForeignStatic
1574                if self.tcx.is_mutable_static(hir_id.expect_owner().def_id.into()) =>
1575            {
1576                self.tcx.dcx().emit_err(diagnostics::StaticMutLinkage { span });
1577            }
1578            Target::Fn
1579                if let Item { kind: ItemKind::Fn { sig, .. }, .. } = item.unwrap()
1580                    && #[allow(non_exhaustive_omitted_patterns)] match sig.header.constness {
    Constness::Const { .. } => true,
    _ => false,
}matches!(sig.header.constness, Constness::Const { .. }) =>
1581            {
1582                self.tcx.dcx().emit_err(diagnostics::ConstFnLinkage { span });
1583            }
1584            _ => {}
1585        }
1586    }
1587}
1588
1589impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1590    type NestedFilter = nested_filter::OnlyBodies;
1591
1592    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1593        self.tcx
1594    }
1595
1596    fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1597        // Historically we've run more checks on non-exported than exported macros,
1598        // so this lets us continue to run them while maintaining backwards compatibility.
1599        // In the long run, the checks should be harmonized.
1600        if let ItemKind::Macro(_, macro_def, _) = item.kind {
1601            let def_id = item.owner_id.to_def_id();
1602            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 { .. }) {
1603                check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1604            }
1605        }
1606
1607        let target = Target::from(item);
1608        self.check_attributes(item.hir_id(), item.span, target, Some(item));
1609        intravisit::walk_item(self, item)
1610    }
1611
1612    fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1613        self.check_attributes(
1614            where_predicate.hir_id,
1615            where_predicate.span,
1616            Target::WherePredicate,
1617            None,
1618        );
1619        intravisit::walk_where_predicate(self, where_predicate)
1620    }
1621
1622    fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1623        let target = Target::from(generic_param);
1624        self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1625        intravisit::walk_generic_param(self, generic_param)
1626    }
1627
1628    fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1629        let target = Target::from(trait_item);
1630        self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1631        intravisit::walk_trait_item(self, trait_item)
1632    }
1633
1634    fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1635        self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1636        intravisit::walk_field_def(self, struct_field);
1637    }
1638
1639    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1640        self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1641        intravisit::walk_arm(self, arm);
1642    }
1643
1644    fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1645        let target = Target::from(f_item);
1646        self.check_attributes(f_item.hir_id(), f_item.span, target, None);
1647        intravisit::walk_foreign_item(self, f_item)
1648    }
1649
1650    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1651        let target = target_from_impl_item(self.tcx, impl_item);
1652        self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1653        intravisit::walk_impl_item(self, impl_item)
1654    }
1655
1656    fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1657        // When checking statements ignore expressions, they will be checked later.
1658        if let hir::StmtKind::Let(l) = stmt.kind {
1659            self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1660        }
1661        intravisit::walk_stmt(self, stmt)
1662    }
1663
1664    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1665        let target = match expr.kind {
1666            hir::ExprKind::Closure { .. } => Target::Closure,
1667            _ => Target::Expression,
1668        };
1669
1670        self.check_attributes(expr.hir_id, expr.span, target, None);
1671        intravisit::walk_expr(self, expr)
1672    }
1673
1674    fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
1675        self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
1676        intravisit::walk_expr_field(self, field)
1677    }
1678
1679    fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
1680        self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
1681        intravisit::walk_variant(self, variant)
1682    }
1683
1684    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1685        self.check_attributes(param.hir_id, param.span, Target::Param, None);
1686
1687        intravisit::walk_param(self, param);
1688    }
1689
1690    fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
1691        self.check_attributes(field.hir_id, field.span, Target::PatField, None);
1692        intravisit::walk_pat_field(self, field);
1693    }
1694}
1695
1696fn is_c_like_enum(item: &Item<'_>) -> bool {
1697    if let ItemKind::Enum(_, _, ref def) = item.kind {
1698        for variant in def.variants {
1699            match variant.data {
1700                hir::VariantData::Unit(..) => { /* continue */ }
1701                _ => return false,
1702            }
1703        }
1704        true
1705    } else {
1706        false
1707    }
1708}
1709
1710fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
1711    let attrs = tcx.hir_attrs(item.hir_id());
1712
1713    if let Some(attr_span) =
1714        {
    '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)
1715    {
1716        tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
1717    }
1718}
1719
1720fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModId) {
1721    let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
1722    tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
1723    if module_def_id.to_local_def_id().is_top_level_module() {
1724        check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
1725    }
1726    if check_attr_visitor.abort.get() {
1727        tcx.dcx().abort_if_errors()
1728    }
1729}
1730
1731pub(crate) fn provide(providers: &mut Providers) {
1732    *providers = Providers { check_mod_attrs, ..*providers };
1733}
1734
1735fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
1736    #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
    hir::TyKind::Tup([_]) => true,
    _ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
1737        || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
1738            fn_ptr_ty.decl.inputs.len() == 1
1739        } else {
1740            false
1741        }
1742        || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
1743            && let Some(&[hir::GenericArg::Type(ty)]) =
1744                path.segments.last().map(|last| last.args().args)
1745        {
1746            doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
1747        } else {
1748            false
1749        })
1750}