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