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