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