Skip to main content

rustc_passes/
check_attr.rs

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