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::collections::hash_map::Entry;
10use std::slice;
11
12use rustc_abi::{Align, ExternAbi, Size};
13use rustc_ast::{AttrStyle, LitKind, MetaItem, MetaItemInner, MetaItemKind, ast};
14use rustc_attr_parsing::{AttributeParser, Late};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_errors::{Applicability, DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey};
17use rustc_feature::{
18    ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP,
19    BuiltinAttribute,
20};
21use rustc_hir::attrs::{AttributeKind, InlineAttr, MirDialect, MirPhase, ReprAttr, SanitizerSet};
22use rustc_hir::def::DefKind;
23use rustc_hir::def_id::LocalModDefId;
24use rustc_hir::intravisit::{self, Visitor};
25use rustc_hir::{
26    self as hir, Attribute, CRATE_HIR_ID, CRATE_OWNER_ID, FnSig, ForeignItem, HirId, Item,
27    ItemKind, MethodKind, PartialConstStability, Safety, Stability, StabilityLevel, Target,
28    TraitItem, find_attr,
29};
30use rustc_macros::LintDiagnostic;
31use rustc_middle::hir::nested_filter;
32use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
33use rustc_middle::query::Providers;
34use rustc_middle::traits::ObligationCause;
35use rustc_middle::ty::error::{ExpectedFound, TypeError};
36use rustc_middle::ty::{self, TyCtxt, TypingMode};
37use rustc_middle::{bug, span_bug};
38use rustc_session::config::CrateType;
39use rustc_session::lint;
40use rustc_session::lint::builtin::{
41    CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES,
42    MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES,
43};
44use rustc_session::parse::feature_err;
45use rustc_span::edition::Edition;
46use rustc_span::{BytePos, DUMMY_SP, Span, Symbol, edition, sym};
47use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
48use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
49use rustc_trait_selection::traits::ObligationCtxt;
50use tracing::debug;
51
52use crate::{errors, fluent_generated as fluent};
53
54#[derive(LintDiagnostic)]
55#[diag(passes_diagnostic_diagnostic_on_unimplemented_only_for_traits)]
56struct DiagnosticOnUnimplementedOnlyForTraits;
57
58fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
59    match impl_item.kind {
60        hir::ImplItemKind::Const(..) => Target::AssocConst,
61        hir::ImplItemKind::Fn(..) => {
62            let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
63            let containing_item = tcx.hir_expect_item(parent_def_id);
64            let containing_impl_is_for_trait = match &containing_item.kind {
65                hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
66                _ => bug!("parent of an ImplItem must be an Impl"),
67            };
68            if containing_impl_is_for_trait {
69                Target::Method(MethodKind::Trait { body: true })
70            } else {
71                Target::Method(MethodKind::Inherent)
72            }
73        }
74        hir::ImplItemKind::Type(..) => Target::AssocTy,
75    }
76}
77
78#[derive(Clone, Copy)]
79enum ItemLike<'tcx> {
80    Item(&'tcx Item<'tcx>),
81    ForeignItem,
82}
83
84#[derive(Copy, Clone)]
85pub(crate) enum ProcMacroKind {
86    FunctionLike,
87    Derive,
88    Attribute,
89}
90
91impl IntoDiagArg for ProcMacroKind {
92    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
93        match self {
94            ProcMacroKind::Attribute => "attribute proc macro",
95            ProcMacroKind::Derive => "derive proc macro",
96            ProcMacroKind::FunctionLike => "function-like proc macro",
97        }
98        .into_diag_arg(&mut None)
99    }
100}
101
102#[derive(Clone, Copy)]
103enum DocFakeItemKind {
104    Attribute,
105    Keyword,
106}
107
108impl DocFakeItemKind {
109    fn name(self) -> &'static str {
110        match self {
111            Self::Attribute => "attribute",
112            Self::Keyword => "keyword",
113        }
114    }
115}
116
117struct CheckAttrVisitor<'tcx> {
118    tcx: TyCtxt<'tcx>,
119
120    // Whether or not this visitor should abort after finding errors
121    abort: Cell<bool>,
122}
123
124impl<'tcx> CheckAttrVisitor<'tcx> {
125    fn dcx(&self) -> DiagCtxtHandle<'tcx> {
126        self.tcx.dcx()
127    }
128
129    /// Checks any attribute.
130    fn check_attributes(
131        &self,
132        hir_id: HirId,
133        span: Span,
134        target: Target,
135        item: Option<ItemLike<'_>>,
136    ) {
137        let mut doc_aliases = FxHashMap::default();
138        let mut specified_inline = None;
139        let mut seen = FxHashMap::default();
140        let attrs = self.tcx.hir_attrs(hir_id);
141        for attr in attrs {
142            let mut style = None;
143            match attr {
144                Attribute::Parsed(AttributeKind::ProcMacro(_)) => {
145                    self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
146                }
147                Attribute::Parsed(AttributeKind::ProcMacroAttribute(_)) => {
148                    self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
149                }
150                Attribute::Parsed(AttributeKind::ProcMacroDerive { .. }) => {
151                    self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
152                }
153                &Attribute::Parsed(AttributeKind::TypeConst(attr_span)) => {
154                    self.check_type_const(hir_id, attr_span, target)
155                }
156                Attribute::Parsed(
157                    AttributeKind::Stability {
158                        span: attr_span,
159                        stability: Stability { level, feature },
160                    }
161                    | AttributeKind::ConstStability {
162                        span: attr_span,
163                        stability: PartialConstStability { level, feature, .. },
164                    },
165                ) => self.check_stability(*attr_span, span, level, *feature),
166                Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force { .. }, ..)) => {} // handled separately below
167                Attribute::Parsed(AttributeKind::Inline(kind, attr_span)) => {
168                    self.check_inline(hir_id, *attr_span, kind, target)
169                }
170                Attribute::Parsed(AttributeKind::LoopMatch(attr_span)) => {
171                    self.check_loop_match(hir_id, *attr_span, target)
172                }
173                Attribute::Parsed(AttributeKind::ConstContinue(attr_span)) => {
174                    self.check_const_continue(hir_id, *attr_span, target)
175                }
176                Attribute::Parsed(AttributeKind::AllowInternalUnsafe(attr_span) | AttributeKind::AllowInternalUnstable(.., attr_span)) => {
177                    self.check_macro_only_attr(*attr_span, span, target, attrs)
178                }
179                Attribute::Parsed(AttributeKind::AllowConstFnUnstable(_, first_span)) => {
180                    self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
181                }
182                Attribute::Parsed(AttributeKind::Deprecation {span: attr_span, .. }) => {
183                    self.check_deprecated(hir_id, *attr_span, target)
184                }
185                Attribute::Parsed(AttributeKind::TargetFeature{ attr_span, ..}) => {
186                    self.check_target_feature(hir_id, *attr_span, target, attrs)
187                }
188                Attribute::Parsed(AttributeKind::RustcObjectLifetimeDefault) => {
189                    self.check_object_lifetime_default(hir_id);
190                }
191                &Attribute::Parsed(AttributeKind::PubTransparent(attr_span)) => {
192                    self.check_rustc_pub_transparent(attr_span, span, attrs)
193                }
194                Attribute::Parsed(AttributeKind::Align { align, span: attr_span }) => {
195                    self.check_align(*align, *attr_span)
196                }
197                Attribute::Parsed(AttributeKind::Naked(..)) => {
198                    self.check_naked(hir_id, target)
199                }
200                Attribute::Parsed(AttributeKind::TrackCaller(attr_span)) => {
201                    self.check_track_caller(hir_id, *attr_span, attrs, target)
202                }
203                Attribute::Parsed(AttributeKind::NonExhaustive(attr_span)) => {
204                    self.check_non_exhaustive(*attr_span, span, target, item)
205                }
206                &Attribute::Parsed(AttributeKind::FfiPure(attr_span)) => {
207                    self.check_ffi_pure(attr_span, attrs)
208                }
209                Attribute::Parsed(AttributeKind::MayDangle(attr_span)) => {
210                    self.check_may_dangle(hir_id, *attr_span)
211                }
212                &Attribute::Parsed(AttributeKind::CustomMir(dialect, phase, attr_span)) => {
213                    self.check_custom_mir(dialect, phase, attr_span)
214                }
215                &Attribute::Parsed(AttributeKind::Sanitize { on_set, off_set, span: attr_span}) => {
216                    self.check_sanitize(attr_span, on_set | off_set, span, target);
217                },
218                Attribute::Parsed(AttributeKind::Link(_, attr_span)) => {
219                    self.check_link(hir_id, *attr_span, span, target)
220                },
221                Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
222                    self.check_macro_export(hir_id, *span, target)
223                },
224                Attribute::Parsed(
225                    AttributeKind::BodyStability { .. }
226                    | AttributeKind::ConstStabilityIndirect
227                    | AttributeKind::MacroTransparency(_)
228                    | AttributeKind::Pointee(..)
229                    | AttributeKind::Dummy
230                    | AttributeKind::RustcBuiltinMacro { .. }
231                    | AttributeKind::Ignore { .. }
232                    | AttributeKind::Path(..)
233                    | AttributeKind::NoImplicitPrelude(..)
234                    | AttributeKind::AutomaticallyDerived(..)
235                    | AttributeKind::Marker(..)
236                    | AttributeKind::SkipDuringMethodDispatch { .. }
237                    | AttributeKind::Coinductive(..)
238                    | AttributeKind::ConstTrait(..)
239                    | AttributeKind::DenyExplicitImpl(..)
240                    | AttributeKind::DoNotImplementViaObject(..)
241                    | AttributeKind::SpecializationTrait(..)
242                    | AttributeKind::UnsafeSpecializationMarker(..)
243                    | AttributeKind::ParenSugar(..)
244                    | AttributeKind::AllowIncoherentImpl(..)
245                    | AttributeKind::Confusables { .. }
246                    // `#[doc]` is actually a lot more than just doc comments, so is checked below
247                    | AttributeKind::DocComment {..}
248                    // handled below this loop and elsewhere
249                    | AttributeKind::Repr { .. }
250                    | AttributeKind::Cold(..)
251                    | AttributeKind::ExportName { .. }
252                    | AttributeKind::Fundamental
253                    | AttributeKind::Optimize(..)
254                    | AttributeKind::LinkSection { .. }
255                    | AttributeKind::MacroUse { .. }
256                    | AttributeKind::MacroEscape( .. )
257                    | AttributeKind::RustcLayoutScalarValidRangeStart(..)
258                    | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
259                    | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
260                    | AttributeKind::ExportStable
261                    | AttributeKind::FfiConst(..)
262                    | AttributeKind::UnstableFeatureBound(..)
263                    | AttributeKind::AsPtr(..)
264                    | AttributeKind::LinkName { .. }
265                    | AttributeKind::LinkOrdinal { .. }
266                    | AttributeKind::NoMangle(..)
267                    | AttributeKind::Used { .. }
268                    | AttributeKind::PassByValue (..)
269                    | AttributeKind::StdInternalSymbol (..)
270                    | AttributeKind::Coverage (..)
271                    | AttributeKind::ShouldPanic { .. }
272                    | AttributeKind::Coroutine(..)
273                    | AttributeKind::Linkage(..)
274                    | AttributeKind::MustUse { .. }
275                    | AttributeKind::CrateName { .. }
276                    | AttributeKind::RecursionLimit { .. }
277                    | AttributeKind::MoveSizeLimit { .. }
278                    | AttributeKind::TypeLengthLimit { .. }
279                    | AttributeKind::PatternComplexityLimit { .. }
280                    | AttributeKind::NoCore { .. }
281                    | AttributeKind::NoStd { .. }
282                    | AttributeKind::ObjcClass { .. }
283                    | AttributeKind::ObjcSelector { .. }
284                    | AttributeKind::RustcCoherenceIsCore(..)
285                    | AttributeKind::DebuggerVisualizer(..)
286                    | AttributeKind::RustcMain,
287                ) => { /* do nothing  */ }
288                Attribute::Unparsed(attr_item) => {
289                    style = Some(attr_item.style);
290                    match attr.path().as_slice() {
291                        [sym::diagnostic, sym::do_not_recommend, ..] => {
292                            self.check_do_not_recommend(attr.span(), hir_id, target, attr, item)
293                        }
294                        [sym::diagnostic, sym::on_unimplemented, ..] => {
295                            self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
296                        }
297                        [sym::thread_local, ..] => self.check_thread_local(attr, span, target),
298                        [sym::doc, ..] => self.check_doc_attrs(
299                            attr,
300                            attr.span(),
301                            attr_item.style,
302                            hir_id,
303                            target,
304                            &mut specified_inline,
305                            &mut doc_aliases,
306                        ),
307                        [sym::no_link, ..] => self.check_no_link(hir_id, attr, span, target),
308                        [sym::rustc_no_implicit_autorefs, ..] => {
309                            self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
310                        }
311                        [sym::rustc_never_returns_null_ptr, ..] => {
312                            self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
313                        }
314                        [sym::rustc_legacy_const_generics, ..] => {
315                            self.check_rustc_legacy_const_generics(hir_id, attr, span, target, item)
316                        }
317                        [sym::rustc_lint_query_instability, ..] => {
318                            self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
319                        }
320                        [sym::rustc_lint_untracked_query_information, ..] => {
321                            self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
322                        }
323                        [sym::rustc_lint_diagnostics, ..] => {
324                            self.check_applied_to_fn_or_method(hir_id, attr.span(), span, target)
325                        }
326                        [sym::rustc_lint_opt_ty, ..] => self.check_rustc_lint_opt_ty(attr, span, target),
327                        [sym::rustc_lint_opt_deny_field_access, ..] => {
328                            self.check_rustc_lint_opt_deny_field_access(attr, span, target)
329                        }
330                        [sym::rustc_clean, ..]
331                        | [sym::rustc_dirty, ..]
332                        | [sym::rustc_if_this_changed, ..]
333                        | [sym::rustc_then_this_would_need, ..] => self.check_rustc_dirty_clean(attr),
334                        [sym::rustc_must_implement_one_of, ..] => self.check_must_be_applied_to_trait(attr.span(), span, target),
335                        [sym::collapse_debuginfo, ..] => self.check_collapse_debuginfo(attr, span, target),
336                        [sym::must_not_suspend, ..] => self.check_must_not_suspend(attr, span, target),
337                        [sym::rustc_has_incoherent_inherent_impls, ..] => {
338                            self.check_has_incoherent_inherent_impls(attr, span, target)
339                        }
340                        [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => {
341                            self.check_autodiff(hir_id, attr, span, target)
342                        }
343                        [
344                            // ok
345                            sym::allow
346                            | sym::expect
347                            | sym::warn
348                            | sym::deny
349                            | sym::forbid
350                            | sym::cfg
351                            | sym::cfg_attr
352                            | sym::cfg_trace
353                            | sym::cfg_attr_trace
354                            // need to be fixed
355                            | sym::cfi_encoding // FIXME(cfi_encoding)
356                            | sym::instruction_set // broken on stable!!!
357                            | sym::windows_subsystem // broken on stable!!!
358                            | sym::patchable_function_entry // FIXME(patchable_function_entry)
359                            | sym::deprecated_safe // FIXME(deprecated_safe)
360                            // internal
361                            | sym::prelude_import
362                            | sym::panic_handler
363                            | sym::lang
364                            | sym::needs_allocator
365                            | sym::default_lib_allocator,
366                            ..
367                        ] => {}
368                        [name, rest@..] => {
369                            match BUILTIN_ATTRIBUTE_MAP.get(name) {
370                                // checked below
371                                Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) => {}
372                                Some(_) => {
373                                    if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
374                                        // Check if we tried to use a builtin attribute as an attribute namespace, like `#[must_use::skip]`.
375                                        // This check is here to solve https://github.com/rust-lang/rust/issues/137590
376                                        // An error is already produced for this case elsewhere
377                                        continue
378                                    }
379
380                                    // FIXME: differentiate between unstable and internal attributes just
381                                    // like we do with features instead of just accepting `rustc_`
382                                    // attributes by name. That should allow trimming the above list, too.
383                                    if !name.as_str().starts_with("rustc_") {
384                                        span_bug!(
385                                            attr.span(),
386                                            "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
387                                        )
388                                    }
389                                }
390                                None => (),
391                            }
392                        }
393                        [] => unreachable!(),
394                    }
395                }
396            }
397
398            if hir_id != CRATE_HIR_ID {
399                match attr {
400                    Attribute::Parsed(_) => { /* Already validated. */ }
401                    Attribute::Unparsed(attr) => {
402                        // FIXME(jdonszelmann): remove once all crate-level attrs are parsed and caught by
403                        // the above
404                        if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
405                            attr.path
406                                .segments
407                                .first()
408                                .and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
409                        {
410                            match attr.style {
411                                ast::AttrStyle::Outer => {
412                                    let attr_span = attr.span;
413                                    let bang_position = self
414                                        .tcx
415                                        .sess
416                                        .source_map()
417                                        .span_until_char(attr_span, '[')
418                                        .shrink_to_hi();
419
420                                    self.tcx.emit_node_span_lint(
421                                        UNUSED_ATTRIBUTES,
422                                        hir_id,
423                                        attr.span,
424                                        errors::OuterCrateLevelAttr {
425                                            suggestion: errors::OuterCrateLevelAttrSuggestion {
426                                                bang_position,
427                                            },
428                                        },
429                                    )
430                                }
431                                ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
432                                    UNUSED_ATTRIBUTES,
433                                    hir_id,
434                                    attr.span,
435                                    errors::InnerCrateLevelAttr,
436                                ),
437                            }
438                        }
439                    }
440                }
441            }
442
443            if let Attribute::Unparsed(unparsed_attr) = attr
444                && let Some(BuiltinAttribute { duplicates, .. }) =
445                    attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
446            {
447                check_duplicates(
448                    self.tcx,
449                    unparsed_attr.span,
450                    attr,
451                    hir_id,
452                    *duplicates,
453                    &mut seen,
454                );
455            }
456
457            self.check_unused_attribute(hir_id, attr, style)
458        }
459
460        self.check_repr(attrs, span, target, item, hir_id);
461        self.check_rustc_force_inline(hir_id, attrs, target);
462        self.check_mix_no_mangle_export(hir_id, attrs);
463    }
464
465    fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr_span: Span, sym: &str) {
466        self.tcx.emit_node_span_lint(
467            UNUSED_ATTRIBUTES,
468            hir_id,
469            attr_span,
470            errors::IgnoredAttrWithMacro { sym },
471        );
472    }
473
474    /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no
475    /// arguments.
476    fn check_do_not_recommend(
477        &self,
478        attr_span: Span,
479        hir_id: HirId,
480        target: Target,
481        attr: &Attribute,
482        item: Option<ItemLike<'_>>,
483    ) {
484        if !matches!(target, Target::Impl { .. })
485            || matches!(
486                item,
487                Some(ItemLike::Item(hir::Item {  kind: hir::ItemKind::Impl(_impl),.. }))
488                    if _impl.of_trait.is_none()
489            )
490        {
491            self.tcx.emit_node_span_lint(
492                MISPLACED_DIAGNOSTIC_ATTRIBUTES,
493                hir_id,
494                attr_span,
495                errors::IncorrectDoNotRecommendLocation,
496            );
497        }
498        if !attr.is_word() {
499            self.tcx.emit_node_span_lint(
500                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
501                hir_id,
502                attr_span,
503                errors::DoNotRecommendDoesNotExpectArgs,
504            );
505        }
506    }
507
508    /// Checks if `#[diagnostic::on_unimplemented]` is applied to a trait definition
509    fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) {
510        if !matches!(target, Target::Trait) {
511            self.tcx.emit_node_span_lint(
512                MISPLACED_DIAGNOSTIC_ATTRIBUTES,
513                hir_id,
514                attr_span,
515                DiagnosticOnUnimplementedOnlyForTraits,
516            );
517        }
518    }
519
520    /// Checks if an `#[inline]` is applied to a function or a closure.
521    fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
522        match target {
523            Target::Fn
524            | Target::Closure
525            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
526                // `#[inline]` is ignored if the symbol must be codegened upstream because it's exported.
527                if let Some(did) = hir_id.as_owner()
528                    && self.tcx.def_kind(did).has_codegen_attrs()
529                    && kind != &InlineAttr::Never
530                {
531                    let attrs = self.tcx.codegen_fn_attrs(did);
532                    // Not checking naked as `#[inline]` is forbidden for naked functions anyways.
533                    if attrs.contains_extern_indicator() {
534                        self.tcx.emit_node_span_lint(
535                            UNUSED_ATTRIBUTES,
536                            hir_id,
537                            attr_span,
538                            errors::InlineIgnoredForExported {},
539                        );
540                    }
541                }
542            }
543            _ => {}
544        }
545    }
546
547    /// Checks that the `#[sanitize(..)]` attribute is applied to a
548    /// function/closure/method, or to an impl block or module.
549    fn check_sanitize(
550        &self,
551        attr_span: Span,
552        set: SanitizerSet,
553        target_span: Span,
554        target: Target,
555    ) {
556        let mut not_fn_impl_mod = None;
557        let mut no_body = None;
558
559        match target {
560            Target::Fn
561            | Target::Closure
562            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
563            | Target::Impl { .. }
564            | Target::Mod => return,
565            Target::Static
566                // if we mask out the address bits, i.e. *only* address was set,
567                // we allow it
568                if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
569                    == SanitizerSet::empty() =>
570            {
571                return;
572            }
573
574            // These are "functions", but they aren't allowed because they don't
575            // have a body, so the usual explanation would be confusing.
576            Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
577                no_body = Some(target_span);
578            }
579
580            _ => {
581                not_fn_impl_mod = Some(target_span);
582            }
583        }
584
585        self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
586            attr_span,
587            not_fn_impl_mod,
588            no_body,
589            help: (),
590        });
591    }
592
593    /// Checks if `#[naked]` is applied to a function definition.
594    fn check_naked(&self, hir_id: HirId, target: Target) {
595        match target {
596            Target::Fn
597            | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
598                let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
599                let abi = fn_sig.header.abi;
600                if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
601                    feature_err(
602                        &self.tcx.sess,
603                        sym::naked_functions_rustic_abi,
604                        fn_sig.span,
605                        format!(
606                            "`#[naked]` is currently unstable on `extern \"{}\"` functions",
607                            abi.as_str()
608                        ),
609                    )
610                    .emit();
611                }
612            }
613            _ => {}
614        }
615    }
616
617    /// Debugging aid for `object_lifetime_default` query.
618    fn check_object_lifetime_default(&self, hir_id: HirId) {
619        let tcx = self.tcx;
620        if let Some(owner_id) = hir_id.as_owner()
621            && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
622        {
623            for p in generics.params {
624                let hir::GenericParamKind::Type { .. } = p.kind else { continue };
625                let default = tcx.object_lifetime_default(p.def_id);
626                let repr = match default {
627                    ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
628                    ObjectLifetimeDefault::Static => "'static".to_owned(),
629                    ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
630                    ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
631                };
632                tcx.dcx().emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
633            }
634        }
635    }
636    /// Checks if `#[collapse_debuginfo]` is applied to a macro.
637    fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) {
638        match target {
639            Target::MacroDef => {}
640            _ => {
641                self.tcx.dcx().emit_err(errors::CollapseDebuginfo {
642                    attr_span: attr.span(),
643                    defn_span: span,
644                });
645            }
646        }
647    }
648
649    /// Checks if a `#[track_caller]` is applied to a function.
650    fn check_track_caller(
651        &self,
652        hir_id: HirId,
653        attr_span: Span,
654        attrs: &[Attribute],
655        target: Target,
656    ) {
657        match target {
658            Target::Fn => {
659                // `#[track_caller]` is not valid on weak lang items because they are called via
660                // `extern` declarations and `#[track_caller]` would alter their ABI.
661                if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
662                    && let Some(item) = hir::LangItem::from_name(lang_item)
663                    && item.is_weak()
664                {
665                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
666
667                    self.dcx().emit_err(errors::LangItemWithTrackCaller {
668                        attr_span,
669                        name: lang_item,
670                        sig_span: sig.span,
671                    });
672                }
673            }
674            _ => {}
675        }
676    }
677
678    /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid.
679    fn check_non_exhaustive(
680        &self,
681        attr_span: Span,
682        span: Span,
683        target: Target,
684        item: Option<ItemLike<'_>>,
685    ) {
686        match target {
687            Target::Struct => {
688                if let Some(ItemLike::Item(hir::Item {
689                    kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
690                    ..
691                })) = item
692                    && !fields.is_empty()
693                    && fields.iter().any(|f| f.default.is_some())
694                {
695                    self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
696                        attr_span,
697                        defn_span: span,
698                    });
699                }
700            }
701            _ => {}
702        }
703    }
704
705    /// Checks if the `#[target_feature]` attribute on `item` is valid.
706    fn check_target_feature(
707        &self,
708        hir_id: HirId,
709        attr_span: Span,
710        target: Target,
711        attrs: &[Attribute],
712    ) {
713        match target {
714            Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
715            | Target::Fn => {
716                // `#[target_feature]` is not allowed in lang items.
717                if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
718                    // Calling functions with `#[target_feature]` is
719                    // not unsafe on WASM, see #84988
720                    && !self.tcx.sess.target.is_like_wasm
721                    && !self.tcx.sess.opts.actually_rustdoc
722                {
723                    let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
724
725                    self.dcx().emit_err(errors::LangItemWithTargetFeature {
726                        attr_span,
727                        name: lang_item,
728                        sig_span: sig.span,
729                    });
730                }
731            }
732            _ => {}
733        }
734    }
735
736    /// Checks if the `#[thread_local]` attribute on `item` is valid.
737    fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) {
738        match target {
739            Target::ForeignStatic | Target::Static => {}
740            _ => {
741                self.dcx().emit_err(errors::AttrShouldBeAppliedToStatic {
742                    attr_span: attr.span(),
743                    defn_span: span,
744                });
745            }
746        }
747    }
748
749    fn doc_attr_str_error(&self, meta: &MetaItemInner, attr_name: &str) {
750        self.dcx().emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
751    }
752
753    fn check_doc_alias_value(
754        &self,
755        meta: &MetaItemInner,
756        doc_alias: Symbol,
757        hir_id: HirId,
758        target: Target,
759        is_list: bool,
760        aliases: &mut FxHashMap<String, Span>,
761    ) {
762        let tcx = self.tcx;
763        let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
764        let attr_str =
765            &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
766        if doc_alias == sym::empty {
767            tcx.dcx().emit_err(errors::DocAliasEmpty { span, attr_str });
768            return;
769        }
770
771        let doc_alias_str = doc_alias.as_str();
772        if let Some(c) = doc_alias_str
773            .chars()
774            .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
775        {
776            tcx.dcx().emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
777            return;
778        }
779        if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
780            tcx.dcx().emit_err(errors::DocAliasStartEnd { span, attr_str });
781            return;
782        }
783
784        let span = meta.span();
785        if let Some(location) = match target {
786            Target::AssocTy => {
787                if let DefKind::Impl { .. } =
788                    self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
789                {
790                    Some("type alias in implementation block")
791                } else {
792                    None
793                }
794            }
795            Target::AssocConst => {
796                let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
797                let containing_item = self.tcx.hir_expect_item(parent_def_id);
798                // We can't link to trait impl's consts.
799                let err = "associated constant in trait implementation block";
800                match containing_item.kind {
801                    ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
802                    _ => None,
803                }
804            }
805            // we check the validity of params elsewhere
806            Target::Param => return,
807            Target::Expression
808            | Target::Statement
809            | Target::Arm
810            | Target::ForeignMod
811            | Target::Closure
812            | Target::Impl { .. }
813            | Target::WherePredicate => Some(target.name()),
814            Target::ExternCrate
815            | Target::Use
816            | Target::Static
817            | Target::Const
818            | Target::Fn
819            | Target::Mod
820            | Target::GlobalAsm
821            | Target::TyAlias
822            | Target::Enum
823            | Target::Variant
824            | Target::Struct
825            | Target::Field
826            | Target::Union
827            | Target::Trait
828            | Target::TraitAlias
829            | Target::Method(..)
830            | Target::ForeignFn
831            | Target::ForeignStatic
832            | Target::ForeignTy
833            | Target::GenericParam { .. }
834            | Target::MacroDef
835            | Target::PatField
836            | Target::ExprField
837            | Target::Crate
838            | Target::MacroCall
839            | Target::Delegation { .. } => None,
840        } {
841            tcx.dcx().emit_err(errors::DocAliasBadLocation { span, attr_str, location });
842            return;
843        }
844        if self.tcx.hir_opt_name(hir_id) == Some(doc_alias) {
845            tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str });
846            return;
847        }
848        if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
849            self.tcx.emit_node_span_lint(
850                UNUSED_ATTRIBUTES,
851                hir_id,
852                span,
853                errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
854            );
855        }
856    }
857
858    fn check_doc_alias(
859        &self,
860        meta: &MetaItemInner,
861        hir_id: HirId,
862        target: Target,
863        aliases: &mut FxHashMap<String, Span>,
864    ) {
865        if let Some(values) = meta.meta_item_list() {
866            for v in values {
867                match v.lit() {
868                    Some(l) => match l.kind {
869                        LitKind::Str(s, _) => {
870                            self.check_doc_alias_value(v, s, hir_id, target, true, aliases);
871                        }
872                        _ => {
873                            self.tcx
874                                .dcx()
875                                .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
876                        }
877                    },
878                    None => {
879                        self.tcx
880                            .dcx()
881                            .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
882                    }
883                }
884            }
885        } else if let Some(doc_alias) = meta.value_str() {
886            self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
887        } else {
888            self.dcx().emit_err(errors::DocAliasMalformed { span: meta.span() });
889        }
890    }
891
892    fn check_doc_keyword_and_attribute(
893        &self,
894        meta: &MetaItemInner,
895        hir_id: HirId,
896        attr_kind: DocFakeItemKind,
897    ) {
898        fn is_doc_keyword(s: Symbol) -> bool {
899            // FIXME: Once rustdoc can handle URL conflicts on case insensitive file systems, we
900            // can remove the `SelfTy` case here, remove `sym::SelfTy`, and update the
901            // `#[doc(keyword = "SelfTy")` attribute in `library/std/src/keyword_docs.rs`.
902            s.is_reserved(|| edition::LATEST_STABLE_EDITION) || s.is_weak() || s == sym::SelfTy
903        }
904
905        // FIXME: This should support attributes with namespace like `diagnostic::do_not_recommend`.
906        fn is_builtin_attr(s: Symbol) -> bool {
907            rustc_feature::BUILTIN_ATTRIBUTE_MAP.contains_key(&s)
908        }
909
910        let value = match meta.value_str() {
911            Some(value) if value != sym::empty => value,
912            _ => return self.doc_attr_str_error(meta, attr_kind.name()),
913        };
914
915        let item_kind = match self.tcx.hir_node(hir_id) {
916            hir::Node::Item(item) => Some(&item.kind),
917            _ => None,
918        };
919        match item_kind {
920            Some(ItemKind::Mod(_, module)) => {
921                if !module.item_ids.is_empty() {
922                    self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod {
923                        span: meta.span(),
924                        attr_name: attr_kind.name(),
925                    });
926                    return;
927                }
928            }
929            _ => {
930                self.dcx().emit_err(errors::DocKeywordAttributeNotMod {
931                    span: meta.span(),
932                    attr_name: attr_kind.name(),
933                });
934                return;
935            }
936        }
937        match attr_kind {
938            DocFakeItemKind::Keyword => {
939                if !is_doc_keyword(value) {
940                    self.dcx().emit_err(errors::DocKeywordNotKeyword {
941                        span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
942                        keyword: value,
943                    });
944                }
945            }
946            DocFakeItemKind::Attribute => {
947                if !is_builtin_attr(value) {
948                    self.dcx().emit_err(errors::DocAttributeNotAttribute {
949                        span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
950                        attribute: value,
951                    });
952                }
953            }
954        }
955    }
956
957    fn check_doc_fake_variadic(&self, meta: &MetaItemInner, hir_id: HirId) {
958        let item_kind = match self.tcx.hir_node(hir_id) {
959            hir::Node::Item(item) => Some(&item.kind),
960            _ => None,
961        };
962        match item_kind {
963            Some(ItemKind::Impl(i)) => {
964                let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
965                    || if let Some(&[hir::GenericArg::Type(ty)]) = i
966                        .of_trait
967                        .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
968                        .map(|last_segment| last_segment.args().args)
969                    {
970                        matches!(&ty.kind, hir::TyKind::Tup([_]))
971                    } else {
972                        false
973                    };
974                if !is_valid {
975                    self.dcx().emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
976                }
977            }
978            _ => {
979                self.dcx().emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
980            }
981        }
982    }
983
984    fn check_doc_search_unbox(&self, meta: &MetaItemInner, hir_id: HirId) {
985        let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
986            self.dcx().emit_err(errors::DocSearchUnboxInvalid { span: meta.span() });
987            return;
988        };
989        match item.kind {
990            ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
991                if generics.params.len() != 0 => {}
992            ItemKind::Trait(_, _, _, _, generics, _, items)
993                if generics.params.len() != 0
994                    || items.iter().any(|item| {
995                        matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy)
996                    }) => {}
997            ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
998            _ => {
999                self.dcx().emit_err(errors::DocSearchUnboxInvalid { span: meta.span() });
1000            }
1001        }
1002    }
1003
1004    /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes.
1005    ///
1006    /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
1007    /// if there are conflicting attributes for one item.
1008    ///
1009    /// `specified_inline` is used to keep track of whether we have
1010    /// already seen an inlining attribute for this item.
1011    /// If so, `specified_inline` holds the value and the span of
1012    /// the first `inline`/`no_inline` attribute.
1013    fn check_doc_inline(
1014        &self,
1015        style: AttrStyle,
1016        meta: &MetaItemInner,
1017        hir_id: HirId,
1018        target: Target,
1019        specified_inline: &mut Option<(bool, Span)>,
1020    ) {
1021        match target {
1022            Target::Use | Target::ExternCrate => {
1023                let do_inline = meta.has_name(sym::inline);
1024                if let Some((prev_inline, prev_span)) = *specified_inline {
1025                    if do_inline != prev_inline {
1026                        let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
1027                        spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first);
1028                        spans.push_span_label(
1029                            meta.span(),
1030                            fluent::passes_doc_inline_conflict_second,
1031                        );
1032                        self.dcx().emit_err(errors::DocKeywordConflict { spans });
1033                    }
1034                } else {
1035                    *specified_inline = Some((do_inline, meta.span()));
1036                }
1037            }
1038            _ => {
1039                self.tcx.emit_node_span_lint(
1040                    INVALID_DOC_ATTRIBUTES,
1041                    hir_id,
1042                    meta.span(),
1043                    errors::DocInlineOnlyUse {
1044                        attr_span: meta.span(),
1045                        item_span: (style == AttrStyle::Outer).then(|| self.tcx.hir_span(hir_id)),
1046                    },
1047                );
1048            }
1049        }
1050    }
1051
1052    fn check_doc_masked(
1053        &self,
1054        style: AttrStyle,
1055        meta: &MetaItemInner,
1056        hir_id: HirId,
1057        target: Target,
1058    ) {
1059        if target != Target::ExternCrate {
1060            self.tcx.emit_node_span_lint(
1061                INVALID_DOC_ATTRIBUTES,
1062                hir_id,
1063                meta.span(),
1064                errors::DocMaskedOnlyExternCrate {
1065                    attr_span: meta.span(),
1066                    item_span: (style == AttrStyle::Outer).then(|| self.tcx.hir_span(hir_id)),
1067                },
1068            );
1069            return;
1070        }
1071
1072        if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1073            self.tcx.emit_node_span_lint(
1074                INVALID_DOC_ATTRIBUTES,
1075                hir_id,
1076                meta.span(),
1077                errors::DocMaskedNotExternCrateSelf {
1078                    attr_span: meta.span(),
1079                    item_span: (style == AttrStyle::Outer).then(|| self.tcx.hir_span(hir_id)),
1080                },
1081            );
1082        }
1083    }
1084
1085    /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
1086    fn check_attr_not_crate_level(
1087        &self,
1088        meta: &MetaItemInner,
1089        hir_id: HirId,
1090        attr_name: &str,
1091    ) -> bool {
1092        if CRATE_HIR_ID == hir_id {
1093            self.dcx().emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
1094            return false;
1095        }
1096        true
1097    }
1098
1099    /// Checks that an attribute is used at the crate level. Returns `true` if valid.
1100    fn check_attr_crate_level(
1101        &self,
1102        attr_span: Span,
1103        style: AttrStyle,
1104        meta: &MetaItemInner,
1105        hir_id: HirId,
1106    ) -> bool {
1107        if hir_id != CRATE_HIR_ID {
1108            // insert a bang between `#` and `[...`
1109            let bang_span = attr_span.lo() + BytePos(1);
1110            let sugg = (style == AttrStyle::Outer
1111                && self.tcx.hir_get_parent_item(hir_id) == CRATE_OWNER_ID)
1112                .then_some(errors::AttrCrateLevelOnlySugg {
1113                    attr: attr_span.with_lo(bang_span).with_hi(bang_span),
1114                });
1115            self.tcx.emit_node_span_lint(
1116                INVALID_DOC_ATTRIBUTES,
1117                hir_id,
1118                meta.span(),
1119                errors::AttrCrateLevelOnly { sugg },
1120            );
1121            return false;
1122        }
1123        true
1124    }
1125
1126    /// Checks that `doc(test(...))` attribute contains only valid attributes and are at the right place.
1127    fn check_test_attr(
1128        &self,
1129        attr_span: Span,
1130        style: AttrStyle,
1131        meta: &MetaItemInner,
1132        hir_id: HirId,
1133    ) {
1134        if let Some(metas) = meta.meta_item_list() {
1135            for i_meta in metas {
1136                match (i_meta.name(), i_meta.meta_item()) {
1137                    (Some(sym::attr), _) => {
1138                        // Allowed everywhere like `#[doc]`
1139                    }
1140                    (Some(sym::no_crate_inject), _) => {
1141                        self.check_attr_crate_level(attr_span, style, meta, hir_id);
1142                    }
1143                    (_, Some(m)) => {
1144                        self.tcx.emit_node_span_lint(
1145                            INVALID_DOC_ATTRIBUTES,
1146                            hir_id,
1147                            i_meta.span(),
1148                            errors::DocTestUnknown {
1149                                path: rustc_ast_pretty::pprust::path_to_string(&m.path),
1150                            },
1151                        );
1152                    }
1153                    (_, None) => {
1154                        self.tcx.emit_node_span_lint(
1155                            INVALID_DOC_ATTRIBUTES,
1156                            hir_id,
1157                            i_meta.span(),
1158                            errors::DocTestLiteral,
1159                        );
1160                    }
1161                }
1162            }
1163        } else {
1164            self.tcx.emit_node_span_lint(
1165                INVALID_DOC_ATTRIBUTES,
1166                hir_id,
1167                meta.span(),
1168                errors::DocTestTakesList,
1169            );
1170        }
1171    }
1172
1173    /// Check that the `#![doc(auto_cfg)]` attribute has the expected input.
1174    fn check_doc_auto_cfg(&self, meta: &MetaItem, hir_id: HirId) {
1175        match &meta.kind {
1176            MetaItemKind::Word => {}
1177            MetaItemKind::NameValue(lit) => {
1178                if !matches!(lit.kind, LitKind::Bool(_)) {
1179                    self.tcx.emit_node_span_lint(
1180                        INVALID_DOC_ATTRIBUTES,
1181                        hir_id,
1182                        meta.span,
1183                        errors::DocAutoCfgWrongLiteral,
1184                    );
1185                }
1186            }
1187            MetaItemKind::List(list) => {
1188                for item in list {
1189                    let Some(attr_name @ (sym::hide | sym::show)) = item.name() else {
1190                        self.tcx.emit_node_span_lint(
1191                            INVALID_DOC_ATTRIBUTES,
1192                            hir_id,
1193                            meta.span,
1194                            errors::DocAutoCfgExpectsHideOrShow,
1195                        );
1196                        continue;
1197                    };
1198                    if let Some(list) = item.meta_item_list() {
1199                        for item in list {
1200                            let valid = item.meta_item().is_some_and(|meta| {
1201                                meta.path.segments.len() == 1
1202                                    && matches!(
1203                                        &meta.kind,
1204                                        MetaItemKind::Word | MetaItemKind::NameValue(_)
1205                                    )
1206                            });
1207                            if !valid {
1208                                self.tcx.emit_node_span_lint(
1209                                    INVALID_DOC_ATTRIBUTES,
1210                                    hir_id,
1211                                    item.span(),
1212                                    errors::DocAutoCfgHideShowUnexpectedItem { attr_name },
1213                                );
1214                            }
1215                        }
1216                    } else {
1217                        self.tcx.emit_node_span_lint(
1218                            INVALID_DOC_ATTRIBUTES,
1219                            hir_id,
1220                            meta.span,
1221                            errors::DocAutoCfgHideShowExpectsList { attr_name },
1222                        );
1223                    }
1224                }
1225            }
1226        }
1227    }
1228
1229    /// Runs various checks on `#[doc]` attributes.
1230    ///
1231    /// `specified_inline` should be initialized to `None` and kept for the scope
1232    /// of one item. Read the documentation of [`check_doc_inline`] for more information.
1233    ///
1234    /// [`check_doc_inline`]: Self::check_doc_inline
1235    fn check_doc_attrs(
1236        &self,
1237        attr: &Attribute,
1238        attr_span: Span,
1239        style: AttrStyle,
1240        hir_id: HirId,
1241        target: Target,
1242        specified_inline: &mut Option<(bool, Span)>,
1243        aliases: &mut FxHashMap<String, Span>,
1244    ) {
1245        if let Some(list) = attr.meta_item_list() {
1246            for meta in &list {
1247                if let Some(i_meta) = meta.meta_item() {
1248                    match i_meta.name() {
1249                        Some(sym::alias) => {
1250                            if self.check_attr_not_crate_level(meta, hir_id, "alias") {
1251                                self.check_doc_alias(meta, hir_id, target, aliases);
1252                            }
1253                        }
1254
1255                        Some(sym::keyword) => {
1256                            if self.check_attr_not_crate_level(meta, hir_id, "keyword") {
1257                                self.check_doc_keyword_and_attribute(
1258                                    meta,
1259                                    hir_id,
1260                                    DocFakeItemKind::Keyword,
1261                                );
1262                            }
1263                        }
1264
1265                        Some(sym::attribute) => {
1266                            if self.check_attr_not_crate_level(meta, hir_id, "attribute") {
1267                                self.check_doc_keyword_and_attribute(
1268                                    meta,
1269                                    hir_id,
1270                                    DocFakeItemKind::Attribute,
1271                                );
1272                            }
1273                        }
1274
1275                        Some(sym::fake_variadic) => {
1276                            if self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") {
1277                                self.check_doc_fake_variadic(meta, hir_id);
1278                            }
1279                        }
1280
1281                        Some(sym::search_unbox) => {
1282                            if self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") {
1283                                self.check_doc_search_unbox(meta, hir_id);
1284                            }
1285                        }
1286
1287                        Some(sym::test) => {
1288                            self.check_test_attr(attr_span, style, meta, hir_id);
1289                        }
1290
1291                        Some(
1292                            sym::html_favicon_url
1293                            | sym::html_logo_url
1294                            | sym::html_playground_url
1295                            | sym::issue_tracker_base_url
1296                            | sym::html_root_url
1297                            | sym::html_no_source,
1298                        ) => {
1299                            self.check_attr_crate_level(attr_span, style, meta, hir_id);
1300                        }
1301
1302                        Some(sym::auto_cfg) => {
1303                            self.check_doc_auto_cfg(i_meta, hir_id);
1304                        }
1305
1306                        Some(sym::inline | sym::no_inline) => {
1307                            self.check_doc_inline(style, meta, hir_id, target, specified_inline)
1308                        }
1309
1310                        Some(sym::masked) => self.check_doc_masked(style, meta, hir_id, target),
1311
1312                        Some(sym::cfg | sym::hidden | sym::notable_trait) => {}
1313
1314                        Some(sym::rust_logo) => {
1315                            if self.check_attr_crate_level(attr_span, style, meta, hir_id)
1316                                && !self.tcx.features().rustdoc_internals()
1317                            {
1318                                feature_err(
1319                                    &self.tcx.sess,
1320                                    sym::rustdoc_internals,
1321                                    meta.span(),
1322                                    fluent::passes_doc_rust_logo,
1323                                )
1324                                .emit();
1325                            }
1326                        }
1327
1328                        _ => {
1329                            let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1330                            if i_meta.has_name(sym::spotlight) {
1331                                self.tcx.emit_node_span_lint(
1332                                    INVALID_DOC_ATTRIBUTES,
1333                                    hir_id,
1334                                    i_meta.span,
1335                                    errors::DocTestUnknownSpotlight { path, span: i_meta.span },
1336                                );
1337                            } else if i_meta.has_name(sym::include)
1338                                && let Some(value) = i_meta.value_str()
1339                            {
1340                                let applicability = if list.len() == 1 {
1341                                    Applicability::MachineApplicable
1342                                } else {
1343                                    Applicability::MaybeIncorrect
1344                                };
1345                                // If there are multiple attributes, the suggestion would suggest
1346                                // deleting all of them, which is incorrect.
1347                                self.tcx.emit_node_span_lint(
1348                                    INVALID_DOC_ATTRIBUTES,
1349                                    hir_id,
1350                                    i_meta.span,
1351                                    errors::DocTestUnknownInclude {
1352                                        path,
1353                                        value: value.to_string(),
1354                                        inner: match style {
1355                                            AttrStyle::Inner => "!",
1356                                            AttrStyle::Outer => "",
1357                                        },
1358                                        sugg: (attr.span(), applicability),
1359                                    },
1360                                );
1361                            } else if i_meta.has_name(sym::passes)
1362                                || i_meta.has_name(sym::no_default_passes)
1363                            {
1364                                self.tcx.emit_node_span_lint(
1365                                    INVALID_DOC_ATTRIBUTES,
1366                                    hir_id,
1367                                    i_meta.span,
1368                                    errors::DocTestUnknownPasses { path, span: i_meta.span },
1369                                );
1370                            } else if i_meta.has_name(sym::plugins) {
1371                                self.tcx.emit_node_span_lint(
1372                                    INVALID_DOC_ATTRIBUTES,
1373                                    hir_id,
1374                                    i_meta.span,
1375                                    errors::DocTestUnknownPlugins { path, span: i_meta.span },
1376                                );
1377                            } else {
1378                                self.tcx.emit_node_span_lint(
1379                                    INVALID_DOC_ATTRIBUTES,
1380                                    hir_id,
1381                                    i_meta.span,
1382                                    errors::DocTestUnknownAny { path },
1383                                );
1384                            }
1385                        }
1386                    }
1387                } else {
1388                    self.tcx.emit_node_span_lint(
1389                        INVALID_DOC_ATTRIBUTES,
1390                        hir_id,
1391                        meta.span(),
1392                        errors::DocInvalid,
1393                    );
1394                }
1395            }
1396        }
1397    }
1398
1399    fn check_has_incoherent_inherent_impls(&self, attr: &Attribute, span: Span, target: Target) {
1400        match target {
1401            Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {}
1402            _ => {
1403                self.tcx
1404                    .dcx()
1405                    .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span(), span });
1406            }
1407        }
1408    }
1409
1410    fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1411        if find_attr!(attrs, AttributeKind::FfiConst(_)) {
1412            // `#[ffi_const]` functions cannot be `#[ffi_pure]`
1413            self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1414        }
1415    }
1416
1417    /// Checks if `#[must_not_suspend]` is applied to a struct, enum, union, or trait.
1418    fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) {
1419        match target {
1420            Target::Struct | Target::Enum | Target::Union | Target::Trait => {}
1421            _ => {
1422                self.dcx().emit_err(errors::MustNotSuspend { attr_span: attr.span(), span });
1423            }
1424        }
1425    }
1426
1427    /// Checks if `#[may_dangle]` is applied to a lifetime or type generic parameter in `Drop` impl.
1428    fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1429        if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1430            && matches!(
1431                param.kind,
1432                hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1433            )
1434            && matches!(param.source, hir::GenericParamSource::Generics)
1435            && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1436            && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1437            && let hir::ItemKind::Impl(impl_) = item.kind
1438            && let Some(of_trait) = impl_.of_trait
1439            && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1440            && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1441        {
1442            return;
1443        }
1444
1445        self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1446    }
1447
1448    /// Checks if `#[link]` is applied to an item other than a foreign module.
1449    fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1450        if target == Target::ForeignMod
1451            && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1452            && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1453            && !matches!(abi, ExternAbi::Rust)
1454        {
1455            return;
1456        }
1457
1458        self.tcx.emit_node_span_lint(
1459            UNUSED_ATTRIBUTES,
1460            hir_id,
1461            attr_span,
1462            errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1463        );
1464    }
1465
1466    /// Checks if `#[no_link]` is applied to an `extern crate`.
1467    fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1468        match target {
1469            Target::ExternCrate => {}
1470            // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1471            // `#[no_link]` attribute with just a lint, because we previously
1472            // erroneously allowed it and some crates used it accidentally, to be compatible
1473            // with crates depending on them, we can't throw an error here.
1474            Target::Field | Target::Arm | Target::MacroDef => {
1475                self.inline_attr_str_error_with_macro_def(hir_id, attr.span(), "no_link");
1476            }
1477            _ => {
1478                self.dcx().emit_err(errors::NoLink { attr_span: attr.span(), span });
1479            }
1480        }
1481    }
1482
1483    /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1484    fn check_rustc_legacy_const_generics(
1485        &self,
1486        hir_id: HirId,
1487        attr: &Attribute,
1488        span: Span,
1489        target: Target,
1490        item: Option<ItemLike<'_>>,
1491    ) {
1492        let is_function = matches!(target, Target::Fn);
1493        if !is_function {
1494            self.dcx().emit_err(errors::AttrShouldBeAppliedToFn {
1495                attr_span: attr.span(),
1496                defn_span: span,
1497                on_crate: hir_id == CRATE_HIR_ID,
1498            });
1499            return;
1500        }
1501
1502        let Some(list) = attr.meta_item_list() else {
1503            // The attribute form is validated on AST.
1504            return;
1505        };
1506
1507        let Some(ItemLike::Item(Item {
1508            kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1509            ..
1510        })) = item
1511        else {
1512            bug!("should be a function item");
1513        };
1514
1515        for param in generics.params {
1516            match param.kind {
1517                hir::GenericParamKind::Const { .. } => {}
1518                _ => {
1519                    self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1520                        attr_span: attr.span(),
1521                        param_span: param.span,
1522                    });
1523                    return;
1524                }
1525            }
1526        }
1527
1528        if list.len() != generics.params.len() {
1529            self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1530                attr_span: attr.span(),
1531                generics_span: generics.span,
1532            });
1533            return;
1534        }
1535
1536        let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1537        let mut invalid_args = vec![];
1538        for meta in list {
1539            if let Some(LitKind::Int(val, _)) = meta.lit().map(|lit| &lit.kind) {
1540                if *val >= arg_count {
1541                    let span = meta.span();
1542                    self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1543                        span,
1544                        arg_count: arg_count as usize,
1545                    });
1546                    return;
1547                }
1548            } else {
1549                invalid_args.push(meta.span());
1550            }
1551        }
1552
1553        if !invalid_args.is_empty() {
1554            self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1555        }
1556    }
1557
1558    /// Helper function for checking that the provided attribute is only applied to a function or
1559    /// method.
1560    fn check_applied_to_fn_or_method(
1561        &self,
1562        hir_id: HirId,
1563        attr_span: Span,
1564        defn_span: Span,
1565        target: Target,
1566    ) {
1567        let is_function = matches!(target, Target::Fn | Target::Method(..));
1568        if !is_function {
1569            self.dcx().emit_err(errors::AttrShouldBeAppliedToFn {
1570                attr_span,
1571                defn_span,
1572                on_crate: hir_id == CRATE_HIR_ID,
1573            });
1574        }
1575    }
1576
1577    /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1578    fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) {
1579        match target {
1580            Target::Struct => {}
1581            _ => {
1582                self.dcx().emit_err(errors::RustcLintOptTy { attr_span: attr.span(), span });
1583            }
1584        }
1585    }
1586
1587    /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1588    fn check_rustc_lint_opt_deny_field_access(&self, attr: &Attribute, span: Span, target: Target) {
1589        match target {
1590            Target::Field => {}
1591            _ => {
1592                self.tcx
1593                    .dcx()
1594                    .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span(), span });
1595            }
1596        }
1597    }
1598
1599    /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1600    /// option is passed to the compiler.
1601    fn check_rustc_dirty_clean(&self, attr: &Attribute) {
1602        if !self.tcx.sess.opts.unstable_opts.query_dep_graph {
1603            self.dcx().emit_err(errors::RustcDirtyClean { span: attr.span() });
1604        }
1605    }
1606
1607    /// Checks if the attribute is applied to a trait.
1608    fn check_must_be_applied_to_trait(&self, attr_span: Span, defn_span: Span, target: Target) {
1609        match target {
1610            Target::Trait => {}
1611            _ => {
1612                self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait { attr_span, defn_span });
1613            }
1614        }
1615    }
1616
1617    /// Checks if the `#[repr]` attributes on `item` are valid.
1618    fn check_repr(
1619        &self,
1620        attrs: &[Attribute],
1621        span: Span,
1622        target: Target,
1623        item: Option<ItemLike<'_>>,
1624        hir_id: HirId,
1625    ) {
1626        // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1627        // ```
1628        // #[repr(foo)]
1629        // #[repr(bar, align(8))]
1630        // ```
1631        let (reprs, first_attr_span) = find_attr!(attrs, AttributeKind::Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))).unwrap_or((&[], None));
1632
1633        let mut int_reprs = 0;
1634        let mut is_explicit_rust = false;
1635        let mut is_c = false;
1636        let mut is_simd = false;
1637        let mut is_transparent = false;
1638
1639        for (repr, repr_span) in reprs {
1640            match repr {
1641                ReprAttr::ReprRust => {
1642                    is_explicit_rust = true;
1643                    match target {
1644                        Target::Struct | Target::Union | Target::Enum => continue,
1645                        _ => {
1646                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1647                                hint_span: *repr_span,
1648                                span,
1649                            });
1650                        }
1651                    }
1652                }
1653                ReprAttr::ReprC => {
1654                    is_c = true;
1655                    match target {
1656                        Target::Struct | Target::Union | Target::Enum => continue,
1657                        _ => {
1658                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1659                                hint_span: *repr_span,
1660                                span,
1661                            });
1662                        }
1663                    }
1664                }
1665                ReprAttr::ReprAlign(align) => {
1666                    match target {
1667                        Target::Struct | Target::Union | Target::Enum => {}
1668                        Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1669                            self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1670                                span: *repr_span,
1671                                item: target.plural_name(),
1672                            });
1673                        }
1674                        Target::Static if self.tcx.features().static_align() => {
1675                            self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1676                                span: *repr_span,
1677                                item: target.plural_name(),
1678                            });
1679                        }
1680                        _ => {
1681                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1682                                hint_span: *repr_span,
1683                                span,
1684                            });
1685                        }
1686                    }
1687
1688                    self.check_align(*align, *repr_span);
1689                }
1690                ReprAttr::ReprPacked(_) => {
1691                    if target != Target::Struct && target != Target::Union {
1692                        self.dcx().emit_err(errors::AttrApplication::StructUnion {
1693                            hint_span: *repr_span,
1694                            span,
1695                        });
1696                    } else {
1697                        continue;
1698                    }
1699                }
1700                ReprAttr::ReprSimd => {
1701                    is_simd = true;
1702                    if target != Target::Struct {
1703                        self.dcx().emit_err(errors::AttrApplication::Struct {
1704                            hint_span: *repr_span,
1705                            span,
1706                        });
1707                    } else {
1708                        continue;
1709                    }
1710                }
1711                ReprAttr::ReprTransparent => {
1712                    is_transparent = true;
1713                    match target {
1714                        Target::Struct | Target::Union | Target::Enum => continue,
1715                        _ => {
1716                            self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1717                                hint_span: *repr_span,
1718                                span,
1719                            });
1720                        }
1721                    }
1722                }
1723                ReprAttr::ReprInt(_) => {
1724                    int_reprs += 1;
1725                    if target != Target::Enum {
1726                        self.dcx().emit_err(errors::AttrApplication::Enum {
1727                            hint_span: *repr_span,
1728                            span,
1729                        });
1730                    } else {
1731                        continue;
1732                    }
1733                }
1734            };
1735        }
1736
1737        // catch `repr()` with no arguments, applied to an item (i.e. not `#![repr()]`)
1738        if let Some(first_attr_span) = first_attr_span
1739            && reprs.is_empty()
1740            && item.is_some()
1741        {
1742            match target {
1743                Target::Struct | Target::Union | Target::Enum => {}
1744                Target::Fn | Target::Method(_) => {
1745                    self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1746                        span: first_attr_span,
1747                        item: target.plural_name(),
1748                    });
1749                }
1750                _ => {
1751                    self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1752                        hint_span: first_attr_span,
1753                        span,
1754                    });
1755                }
1756            }
1757            return;
1758        }
1759
1760        // Just point at all repr hints if there are any incompatibilities.
1761        // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1762        let hint_spans = reprs.iter().map(|(_, span)| *span);
1763
1764        // Error on repr(transparent, <anything else>).
1765        if is_transparent && reprs.len() > 1 {
1766            let hint_spans = hint_spans.clone().collect();
1767            self.dcx().emit_err(errors::TransparentIncompatible {
1768                hint_spans,
1769                target: target.to_string(),
1770            });
1771        }
1772        if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1773            let hint_spans = hint_spans.clone().collect();
1774            self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1775        }
1776        // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1777        if (int_reprs > 1)
1778            || (is_simd && is_c)
1779            || (int_reprs == 1
1780                && is_c
1781                && item.is_some_and(|item| {
1782                    if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1783                }))
1784        {
1785            self.tcx.emit_node_span_lint(
1786                CONFLICTING_REPR_HINTS,
1787                hir_id,
1788                hint_spans.collect::<Vec<Span>>(),
1789                errors::ReprConflictingLint,
1790            );
1791        }
1792    }
1793
1794    fn check_align(&self, align: Align, span: Span) {
1795        if align.bytes() > 2_u64.pow(29) {
1796            // for values greater than 2^29, a different error will be emitted, make sure that happens
1797            self.dcx().span_delayed_bug(
1798                span,
1799                "alignment greater than 2^29 should be errored on elsewhere",
1800            );
1801        } else {
1802            // only do this check when <= 2^29 to prevent duplicate errors:
1803            // alignment greater than 2^29 not supported
1804            // alignment is too large for the current target
1805
1806            let max = Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64;
1807            if align.bytes() > max {
1808                self.dcx().emit_err(errors::InvalidReprAlignForTarget { span, size: max });
1809            }
1810        }
1811    }
1812
1813    /// Outputs an error for attributes that can only be applied to macros, such as
1814    /// `#[allow_internal_unsafe]` and `#[allow_internal_unstable]`.
1815    /// (Allows proc_macro functions)
1816    // FIXME(jdonszelmann): if possible, move to attr parsing
1817    fn check_macro_only_attr(
1818        &self,
1819        attr_span: Span,
1820        span: Span,
1821        target: Target,
1822        attrs: &[Attribute],
1823    ) {
1824        match target {
1825            Target::Fn => {
1826                for attr in attrs {
1827                    if attr.is_proc_macro_attr() {
1828                        // return on proc macros
1829                        return;
1830                    }
1831                }
1832                self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1833            }
1834            _ => {}
1835        }
1836    }
1837
1838    /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1839    /// (Allows proc_macro functions)
1840    fn check_rustc_allow_const_fn_unstable(
1841        &self,
1842        hir_id: HirId,
1843        attr_span: Span,
1844        span: Span,
1845        target: Target,
1846    ) {
1847        match target {
1848            Target::Fn | Target::Method(_) => {
1849                if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1850                    self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1851                }
1852            }
1853            _ => {}
1854        }
1855    }
1856
1857    fn check_stability(
1858        &self,
1859        attr_span: Span,
1860        item_span: Span,
1861        level: &StabilityLevel,
1862        feature: Symbol,
1863    ) {
1864        // Stable *language* features shouldn't be used as unstable library features.
1865        // (Not doing this for stable library features is checked by tidy.)
1866        if level.is_unstable()
1867            && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1868        {
1869            self.tcx
1870                .dcx()
1871                .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1872        }
1873    }
1874
1875    fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1876        match target {
1877            Target::AssocConst | Target::Method(..) | Target::AssocTy
1878                if matches!(
1879                    self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id)),
1880                    DefKind::Impl { of_trait: true }
1881                ) =>
1882            {
1883                self.tcx.emit_node_span_lint(
1884                    UNUSED_ATTRIBUTES,
1885                    hir_id,
1886                    attr_span,
1887                    errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1888                );
1889            }
1890            _ => {}
1891        }
1892    }
1893
1894    fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1895        if target != Target::MacroDef {
1896            return;
1897        }
1898
1899        // special case when `#[macro_export]` is applied to a macro 2.0
1900        let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1901        let is_decl_macro = !macro_definition.macro_rules;
1902
1903        if is_decl_macro {
1904            self.tcx.emit_node_span_lint(
1905                UNUSED_ATTRIBUTES,
1906                hir_id,
1907                attr_span,
1908                errors::MacroExport::OnDeclMacro,
1909            );
1910        }
1911    }
1912
1913    fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1914        // Warn on useless empty attributes.
1915        // FIXME(jdonszelmann): this lint should be moved to attribute parsing, see `AcceptContext::warn_empty_attribute`
1916        let note = if attr.has_any_name(&[
1917            sym::allow,
1918            sym::expect,
1919            sym::warn,
1920            sym::deny,
1921            sym::forbid,
1922            sym::feature,
1923        ]) && attr.meta_item_list().is_some_and(|list| list.is_empty())
1924        {
1925            errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1926        } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1927            && let Some(meta) = attr.meta_item_list()
1928            && let [meta] = meta.as_slice()
1929            && let Some(item) = meta.meta_item()
1930            && let MetaItemKind::NameValue(_) = &item.kind
1931            && item.path == sym::reason
1932        {
1933            errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1934        } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1935            && let Some(meta) = attr.meta_item_list()
1936            && meta.iter().any(|meta| {
1937                meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
1938            })
1939        {
1940            if hir_id != CRATE_HIR_ID {
1941                match style {
1942                    Some(ast::AttrStyle::Outer) => {
1943                        let attr_span = attr.span();
1944                        let bang_position = self
1945                            .tcx
1946                            .sess
1947                            .source_map()
1948                            .span_until_char(attr_span, '[')
1949                            .shrink_to_hi();
1950
1951                        self.tcx.emit_node_span_lint(
1952                            UNUSED_ATTRIBUTES,
1953                            hir_id,
1954                            attr_span,
1955                            errors::OuterCrateLevelAttr {
1956                                suggestion: errors::OuterCrateLevelAttrSuggestion { bang_position },
1957                            },
1958                        )
1959                    }
1960                    Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1961                        UNUSED_ATTRIBUTES,
1962                        hir_id,
1963                        attr.span(),
1964                        errors::InnerCrateLevelAttr,
1965                    ),
1966                };
1967                return;
1968            } else {
1969                let never_needs_link = self
1970                    .tcx
1971                    .crate_types()
1972                    .iter()
1973                    .all(|kind| matches!(kind, CrateType::Rlib | CrateType::Staticlib));
1974                if never_needs_link {
1975                    errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1976                } else {
1977                    return;
1978                }
1979            }
1980        } else if attr.has_name(sym::default_method_body_is_const) {
1981            errors::UnusedNote::DefaultMethodBodyConst
1982        } else {
1983            return;
1984        };
1985
1986        self.tcx.emit_node_span_lint(
1987            UNUSED_ATTRIBUTES,
1988            hir_id,
1989            attr.span(),
1990            errors::Unused { attr_span: attr.span(), note },
1991        );
1992    }
1993
1994    /// A best effort attempt to create an error for a mismatching proc macro signature.
1995    ///
1996    /// If this best effort goes wrong, it will just emit a worse error later (see #102923)
1997    fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1998        if target != Target::Fn {
1999            return;
2000        }
2001
2002        let tcx = self.tcx;
2003        let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
2004            return;
2005        };
2006        let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
2007            return;
2008        };
2009
2010        let def_id = hir_id.expect_owner().def_id;
2011        let param_env = ty::ParamEnv::empty();
2012
2013        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2014        let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2015
2016        let span = tcx.def_span(def_id);
2017        let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
2018        let sig = tcx.liberate_late_bound_regions(
2019            def_id.to_def_id(),
2020            tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
2021        );
2022
2023        let mut cause = ObligationCause::misc(span, def_id);
2024        let sig = ocx.normalize(&cause, param_env, sig);
2025
2026        // proc macro is not WF.
2027        let errors = ocx.try_evaluate_obligations();
2028        if !errors.is_empty() {
2029            return;
2030        }
2031
2032        let expected_sig = tcx.mk_fn_sig(
2033            std::iter::repeat_n(
2034                token_stream,
2035                match kind {
2036                    ProcMacroKind::Attribute => 2,
2037                    ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
2038                },
2039            ),
2040            token_stream,
2041            false,
2042            Safety::Safe,
2043            ExternAbi::Rust,
2044        );
2045
2046        if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
2047            let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
2048
2049            let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
2050            if let Some(hir_sig) = hir_sig {
2051                #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
2052                match terr {
2053                    TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
2054                        if let Some(ty) = hir_sig.decl.inputs.get(idx) {
2055                            diag.span(ty.span);
2056                            cause.span = ty.span;
2057                        } else if idx == hir_sig.decl.inputs.len() {
2058                            let span = hir_sig.decl.output.span();
2059                            diag.span(span);
2060                            cause.span = span;
2061                        }
2062                    }
2063                    TypeError::ArgCount => {
2064                        if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
2065                            diag.span(ty.span);
2066                            cause.span = ty.span;
2067                        }
2068                    }
2069                    TypeError::SafetyMismatch(_) => {
2070                        // FIXME: Would be nice if we had a span here..
2071                    }
2072                    TypeError::AbiMismatch(_) => {
2073                        // FIXME: Would be nice if we had a span here..
2074                    }
2075                    TypeError::VariadicMismatch(_) => {
2076                        // FIXME: Would be nice if we had a span here..
2077                    }
2078                    _ => {}
2079                }
2080            }
2081
2082            infcx.err_ctxt().note_type_err(
2083                &mut diag,
2084                &cause,
2085                None,
2086                Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
2087                    expected: ty::Binder::dummy(expected_sig),
2088                    found: ty::Binder::dummy(sig),
2089                }))),
2090                terr,
2091                false,
2092                None,
2093            );
2094            diag.emit();
2095            self.abort.set(true);
2096        }
2097
2098        let errors = ocx.evaluate_obligations_error_on_ambiguity();
2099        if !errors.is_empty() {
2100            infcx.err_ctxt().report_fulfillment_errors(errors);
2101            self.abort.set(true);
2102        }
2103    }
2104
2105    fn check_type_const(&self, hir_id: HirId, attr_span: Span, target: Target) {
2106        let tcx = self.tcx;
2107        if target == Target::AssocConst
2108            && let parent = tcx.parent(hir_id.expect_owner().to_def_id())
2109            && self.tcx.def_kind(parent) == DefKind::Trait
2110        {
2111            return;
2112        } else {
2113            self.dcx()
2114                .struct_span_err(
2115                    attr_span,
2116                    "`#[type_const]` must only be applied to trait associated constants",
2117                )
2118                .emit();
2119        }
2120    }
2121
2122    fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
2123        if !find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent))
2124            .unwrap_or(false)
2125        {
2126            self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
2127        }
2128    }
2129
2130    fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
2131        if let (Target::Closure, None) = (
2132            target,
2133            find_attr!(attrs, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
2134        ) {
2135            let is_coro = matches!(
2136                self.tcx.hir_expect_expr(hir_id).kind,
2137                hir::ExprKind::Closure(hir::Closure {
2138                    kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
2139                    ..
2140                })
2141            );
2142            let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
2143            let parent_span = self.tcx.def_span(parent_did);
2144
2145            if let Some(attr_span) = find_attr!(
2146                self.tcx.get_all_attrs(parent_did),
2147                AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
2148            ) && is_coro
2149            {
2150                self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
2151            }
2152        }
2153    }
2154
2155    fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
2156        if let Some(export_name_span) = find_attr!(attrs, AttributeKind::ExportName { span: export_name_span, .. } => *export_name_span)
2157            && let Some(no_mangle_span) =
2158                find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span)
2159        {
2160            let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
2161                "#[unsafe(no_mangle)]"
2162            } else {
2163                "#[no_mangle]"
2164            };
2165            let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
2166                "#[unsafe(export_name)]"
2167            } else {
2168                "#[export_name]"
2169            };
2170
2171            self.tcx.emit_node_span_lint(
2172                lint::builtin::UNUSED_ATTRIBUTES,
2173                hir_id,
2174                no_mangle_span,
2175                errors::MixedExportNameAndNoMangle {
2176                    no_mangle_span,
2177                    export_name_span,
2178                    no_mangle_attr,
2179                    export_name_attr,
2180                },
2181            );
2182        }
2183    }
2184
2185    /// Checks if `#[autodiff]` is applied to an item other than a function item.
2186    fn check_autodiff(&self, _hir_id: HirId, _attr: &Attribute, span: Span, target: Target) {
2187        debug!("check_autodiff");
2188        match target {
2189            Target::Fn => {}
2190            _ => {
2191                self.dcx().emit_err(errors::AutoDiffAttr { attr_span: span });
2192                self.abort.set(true);
2193            }
2194        }
2195    }
2196
2197    fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
2198        let node_span = self.tcx.hir_span(hir_id);
2199
2200        if !matches!(target, Target::Expression) {
2201            return; // Handled in target checking during attr parse
2202        }
2203
2204        if !matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Loop(..)) {
2205            self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
2206        };
2207    }
2208
2209    fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
2210        let node_span = self.tcx.hir_span(hir_id);
2211
2212        if !matches!(target, Target::Expression) {
2213            return; // Handled in target checking during attr parse
2214        }
2215
2216        if !matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Break(..)) {
2217            self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
2218        };
2219    }
2220
2221    fn check_custom_mir(
2222        &self,
2223        dialect: Option<(MirDialect, Span)>,
2224        phase: Option<(MirPhase, Span)>,
2225        attr_span: Span,
2226    ) {
2227        let Some((dialect, dialect_span)) = dialect else {
2228            if let Some((_, phase_span)) = phase {
2229                self.dcx()
2230                    .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
2231            }
2232            return;
2233        };
2234
2235        match dialect {
2236            MirDialect::Analysis => {
2237                if let Some((MirPhase::Optimized, phase_span)) = phase {
2238                    self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
2239                        dialect,
2240                        phase: MirPhase::Optimized,
2241                        attr_span,
2242                        dialect_span,
2243                        phase_span,
2244                    });
2245                }
2246            }
2247
2248            MirDialect::Built => {
2249                if let Some((phase, phase_span)) = phase {
2250                    self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
2251                        dialect,
2252                        phase,
2253                        attr_span,
2254                        dialect_span,
2255                        phase_span,
2256                    });
2257                }
2258            }
2259            MirDialect::Runtime => {}
2260        }
2261    }
2262}
2263
2264impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2265    type NestedFilter = nested_filter::OnlyBodies;
2266
2267    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
2268        self.tcx
2269    }
2270
2271    fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2272        // Historically we've run more checks on non-exported than exported macros,
2273        // so this lets us continue to run them while maintaining backwards compatibility.
2274        // In the long run, the checks should be harmonized.
2275        if let ItemKind::Macro(_, macro_def, _) = item.kind {
2276            let def_id = item.owner_id.to_def_id();
2277            if macro_def.macro_rules
2278                && !find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. })
2279            {
2280                check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2281            }
2282        }
2283
2284        let target = Target::from_item(item);
2285        self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2286        intravisit::walk_item(self, item)
2287    }
2288
2289    fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
2290        // FIXME(where_clause_attrs): Currently, as the following check shows,
2291        // only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
2292        // if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
2293        // in where clauses. After that, only `self.check_attributes` should be enough.
2294        const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg_trace, sym::cfg_attr_trace];
2295        let spans = self
2296            .tcx
2297            .hir_attrs(where_predicate.hir_id)
2298            .iter()
2299            .filter(|attr| !ATTRS_ALLOWED.iter().any(|&sym| attr.has_name(sym)))
2300            .filter(|attr| !attr.is_parsed_attr())
2301            .map(|attr| attr.span())
2302            .collect::<Vec<_>>();
2303        if !spans.is_empty() {
2304            self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
2305        }
2306        self.check_attributes(
2307            where_predicate.hir_id,
2308            where_predicate.span,
2309            Target::WherePredicate,
2310            None,
2311        );
2312        intravisit::walk_where_predicate(self, where_predicate)
2313    }
2314
2315    fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2316        let target = Target::from_generic_param(generic_param);
2317        self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2318        intravisit::walk_generic_param(self, generic_param)
2319    }
2320
2321    fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2322        let target = Target::from_trait_item(trait_item);
2323        self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2324        intravisit::walk_trait_item(self, trait_item)
2325    }
2326
2327    fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2328        self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2329        intravisit::walk_field_def(self, struct_field);
2330    }
2331
2332    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2333        self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2334        intravisit::walk_arm(self, arm);
2335    }
2336
2337    fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2338        let target = Target::from_foreign_item(f_item);
2339        self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2340        intravisit::walk_foreign_item(self, f_item)
2341    }
2342
2343    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2344        let target = target_from_impl_item(self.tcx, impl_item);
2345        self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2346        intravisit::walk_impl_item(self, impl_item)
2347    }
2348
2349    fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2350        // When checking statements ignore expressions, they will be checked later.
2351        if let hir::StmtKind::Let(l) = stmt.kind {
2352            self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2353        }
2354        intravisit::walk_stmt(self, stmt)
2355    }
2356
2357    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2358        let target = match expr.kind {
2359            hir::ExprKind::Closure { .. } => Target::Closure,
2360            _ => Target::Expression,
2361        };
2362
2363        self.check_attributes(expr.hir_id, expr.span, target, None);
2364        intravisit::walk_expr(self, expr)
2365    }
2366
2367    fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2368        self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2369        intravisit::walk_expr_field(self, field)
2370    }
2371
2372    fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2373        self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2374        intravisit::walk_variant(self, variant)
2375    }
2376
2377    fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2378        self.check_attributes(param.hir_id, param.span, Target::Param, None);
2379
2380        intravisit::walk_param(self, param);
2381    }
2382
2383    fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2384        self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2385        intravisit::walk_pat_field(self, field);
2386    }
2387}
2388
2389fn is_c_like_enum(item: &Item<'_>) -> bool {
2390    if let ItemKind::Enum(_, _, ref def) = item.kind {
2391        for variant in def.variants {
2392            match variant.data {
2393                hir::VariantData::Unit(..) => { /* continue */ }
2394                _ => return false,
2395            }
2396        }
2397        true
2398    } else {
2399        false
2400    }
2401}
2402
2403// FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2404// from this check.
2405fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2406    // Check for builtin attributes at the crate level
2407    // which were unsuccessfully resolved due to cannot determine
2408    // resolution for the attribute macro error.
2409    const ATTRS_TO_CHECK: &[Symbol] =
2410        &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2411
2412    for attr in attrs {
2413        // FIXME(jdonszelmann): all attrs should be combined here cleaning this up some day.
2414        let (span, name) = if let Some(a) =
2415            ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2416        {
2417            (attr.span(), *a)
2418        } else if let Attribute::Parsed(AttributeKind::Repr {
2419            reprs: _,
2420            first_span: first_attr_span,
2421        }) = attr
2422        {
2423            (*first_attr_span, sym::repr)
2424        } else {
2425            continue;
2426        };
2427
2428        let item = tcx
2429            .hir_free_items()
2430            .map(|id| tcx.hir_item(id))
2431            .find(|item| !item.span.is_dummy()) // Skip prelude `use`s
2432            .map(|item| errors::ItemFollowingInnerAttr {
2433                span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2434                kind: tcx.def_descr(item.owner_id.to_def_id()),
2435            });
2436        let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2437            span,
2438            sugg_span: tcx
2439                .sess
2440                .source_map()
2441                .span_to_snippet(span)
2442                .ok()
2443                .filter(|src| src.starts_with("#!["))
2444                .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2445            name,
2446            item,
2447        });
2448
2449        if let Attribute::Unparsed(p) = attr {
2450            tcx.dcx().try_steal_replace_and_emit_err(
2451                p.path.span,
2452                StashKey::UndeterminedMacroResolution,
2453                err,
2454            );
2455        } else {
2456            err.emit();
2457        }
2458    }
2459}
2460
2461fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2462    let attrs = tcx.hir_attrs(item.hir_id());
2463
2464    if let Some(attr_span) = find_attr!(attrs, AttributeKind::Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
2465    {
2466        tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2467    }
2468}
2469
2470fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2471    let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2472    tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2473    if module_def_id.to_local_def_id().is_top_level_module() {
2474        check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2475        check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2476    }
2477    if check_attr_visitor.abort.get() {
2478        tcx.dcx().abort_if_errors()
2479    }
2480}
2481
2482pub(crate) fn provide(providers: &mut Providers) {
2483    *providers = Providers { check_mod_attrs, ..*providers };
2484}
2485
2486// FIXME(jdonszelmann): remove, check during parsing
2487fn check_duplicates(
2488    tcx: TyCtxt<'_>,
2489    attr_span: Span,
2490    attr: &Attribute,
2491    hir_id: HirId,
2492    duplicates: AttributeDuplicates,
2493    seen: &mut FxHashMap<Symbol, Span>,
2494) {
2495    use AttributeDuplicates::*;
2496    if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2497        return;
2498    }
2499    let attr_name = attr.name().unwrap();
2500    match duplicates {
2501        DuplicatesOk => {}
2502        WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2503            match seen.entry(attr_name) {
2504                Entry::Occupied(mut entry) => {
2505                    let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2506                        let to_remove = entry.insert(attr_span);
2507                        (to_remove, attr_span)
2508                    } else {
2509                        (attr_span, *entry.get())
2510                    };
2511                    tcx.emit_node_span_lint(
2512                        UNUSED_ATTRIBUTES,
2513                        hir_id,
2514                        this,
2515                        errors::UnusedDuplicate {
2516                            this,
2517                            other,
2518                            warning: matches!(
2519                                duplicates,
2520                                FutureWarnFollowing | FutureWarnPreceding
2521                            ),
2522                        },
2523                    );
2524                }
2525                Entry::Vacant(entry) => {
2526                    entry.insert(attr_span);
2527                }
2528            }
2529        }
2530        ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2531            Entry::Occupied(mut entry) => {
2532                let (this, other) = if matches!(duplicates, ErrorPreceding) {
2533                    let to_remove = entry.insert(attr_span);
2534                    (to_remove, attr_span)
2535                } else {
2536                    (attr_span, *entry.get())
2537                };
2538                tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2539            }
2540            Entry::Vacant(entry) => {
2541                entry.insert(attr_span);
2542            }
2543        },
2544    }
2545}
2546
2547fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2548    matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2549        || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2550            fn_ptr_ty.decl.inputs.len() == 1
2551        } else {
2552            false
2553        }
2554        || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2555            && let Some(&[hir::GenericArg::Type(ty)]) =
2556                path.segments.last().map(|last| last.args().args)
2557        {
2558            doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2559        } else {
2560            false
2561        })
2562}