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