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