1use 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, EiiImplResolution, InlineAttr,
25 MirDialect, MirPhase, 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 abort: Cell<bool>,
119}
120
121impl<'tcx> CheckAttrVisitor<'tcx> {
122 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
123 self.tcx.dcx()
124 }
125
126 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 { .. }, ..)) => {} 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::EiiDeclaration { .. }
228 | AttributeKind::EiiForeignItem
229 | AttributeKind::BodyStability { .. }
230 | AttributeKind::ConstStabilityIndirect
231 | AttributeKind::MacroTransparency(_)
232 | AttributeKind::CollapseDebugInfo(..)
233 | AttributeKind::CfgTrace(..)
234 | AttributeKind::Pointee(..)
235 | AttributeKind::Dummy
236 | AttributeKind::RustcBuiltinMacro { .. }
237 | AttributeKind::Ignore { .. }
238 | AttributeKind::InstructionSet(..)
239 | AttributeKind::Path(..)
240 | AttributeKind::NoImplicitPrelude(..)
241 | AttributeKind::AutomaticallyDerived(..)
242 | AttributeKind::Marker(..)
243 | AttributeKind::SkipDuringMethodDispatch { .. }
244 | AttributeKind::Coinductive(..)
245 | AttributeKind::DenyExplicitImpl(..)
246 | AttributeKind::DoNotImplementViaObject(..)
247 | AttributeKind::SpecializationTrait(..)
248 | AttributeKind::UnsafeSpecializationMarker(..)
249 | AttributeKind::ParenSugar(..)
250 | AttributeKind::AllowIncoherentImpl(..)
251 | AttributeKind::Confusables { .. }
252 | AttributeKind::TypeConst{..}
253 | AttributeKind::DocComment {..}
255 | AttributeKind::Repr { .. }
257 | AttributeKind::Cold(..)
258 | AttributeKind::ExportName { .. }
259 | AttributeKind::Fundamental
260 | AttributeKind::Optimize(..)
261 | AttributeKind::LinkSection { .. }
262 | AttributeKind::MacroUse { .. }
263 | AttributeKind::MacroEscape( .. )
264 | AttributeKind::NoLink
265 | AttributeKind::RustcNoImplicitAutorefs
266 | AttributeKind::RustcLayoutScalarValidRangeStart(..)
267 | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
268 | AttributeKind::RustcLintDiagnostics
269 | AttributeKind::RustcLintOptDenyFieldAccess { .. }
270 | AttributeKind::RustcLintOptTy
271 | AttributeKind::RustcLintQueryInstability
272 | AttributeKind::RustcLintUntrackedQueryInformation
273 | AttributeKind::RustcNeverReturnsNullPointer
274 | AttributeKind::RustcScalableVector { .. }
275 | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
276 | AttributeKind::RustcShouldNotBeCalledOnConstItems(..)
277 | AttributeKind::ExportStable
278 | AttributeKind::FfiConst(..)
279 | AttributeKind::UnstableFeatureBound(..)
280 | AttributeKind::AsPtr(..)
281 | AttributeKind::LinkName { .. }
282 | AttributeKind::LinkOrdinal { .. }
283 | AttributeKind::NoMangle(..)
284 | AttributeKind::Used { .. }
285 | AttributeKind::PassByValue (..)
286 | AttributeKind::StdInternalSymbol (..)
287 | AttributeKind::Coverage (..)
288 | AttributeKind::ShouldPanic { .. }
289 | AttributeKind::Coroutine(..)
290 | AttributeKind::Linkage(..)
291 | AttributeKind::MustUse { .. }
292 | AttributeKind::CrateName { .. }
293 | AttributeKind::RecursionLimit { .. }
294 | AttributeKind::MoveSizeLimit { .. }
295 | AttributeKind::TypeLengthLimit { .. }
296 | AttributeKind::PatternComplexityLimit { .. }
297 | AttributeKind::NoCore { .. }
298 | AttributeKind::NoStd { .. }
299 | AttributeKind::ObjcClass { .. }
300 | AttributeKind::ObjcSelector { .. }
301 | AttributeKind::RustcCoherenceIsCore(..)
302 | AttributeKind::DebuggerVisualizer(..)
303 | AttributeKind::RustcMain
304 | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)
305 | AttributeKind::PinV2(..)
306 | AttributeKind::WindowsSubsystem(..)
307 | AttributeKind::CfgAttrTrace
308 | AttributeKind::ThreadLocal
309 | AttributeKind::CfiEncoding { .. }
310 | AttributeKind::RustcHasIncoherentInherentImpls
311 ) => { }
312 Attribute::Unparsed(attr_item) => {
313 style = Some(attr_item.style);
314 match attr.path().as_slice() {
315 [sym::diagnostic, sym::do_not_recommend, ..] => {
316 self.check_do_not_recommend(attr.span(), hir_id, target, attr, item)
317 }
318 [sym::diagnostic, sym::on_unimplemented, ..] => {
319 self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
320 }
321 [sym::diagnostic, sym::on_const, ..] => {
322 self.check_diagnostic_on_const(attr.span(), hir_id, target, item)
323 }
324 [sym::rustc_clean, ..]
325 | [sym::rustc_dirty, ..]
326 | [sym::rustc_if_this_changed, ..]
327 | [sym::rustc_then_this_would_need, ..] => self.check_rustc_dirty_clean(attr),
328 [sym::must_not_suspend, ..] => self.check_must_not_suspend(attr, span, target),
329 [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => {
330 self.check_autodiff(hir_id, attr, span, target)
331 }
332 [
333 sym::allow
335 | sym::expect
336 | sym::warn
337 | sym::deny
338 | sym::forbid
339 | sym::patchable_function_entry | sym::deprecated_safe | sym::prelude_import
344 | sym::panic_handler
345 | sym::lang
346 | sym::needs_allocator
347 | sym::default_lib_allocator
348 | sym::rustc_diagnostic_item
349 | sym::rustc_no_mir_inline
350 | sym::rustc_insignificant_dtor
351 | sym::rustc_nonnull_optimization_guaranteed
352 | sym::rustc_intrinsic
353 | sym::rustc_inherit_overflow_checks
354 | sym::rustc_intrinsic_const_stable_indirect
355 | sym::rustc_trivial_field_reads
356 | sym::rustc_on_unimplemented
357 | sym::rustc_do_not_const_check
358 | sym::rustc_reservation_impl
359 | sym::rustc_doc_primitive
360 | sym::rustc_allocator
361 | sym::rustc_deallocator
362 | sym::rustc_reallocator
363 | sym::rustc_conversion_suggestion
364 | sym::rustc_allocator_zeroed
365 | sym::rustc_allocator_zeroed_variant
366 | sym::rustc_deprecated_safe_2024
367 | sym::rustc_test_marker
368 | sym::rustc_abi
369 | sym::rustc_layout
370 | sym::rustc_proc_macro_decls
371 | sym::rustc_dump_def_parents
372 | sym::rustc_never_type_options
373 | sym::rustc_autodiff
374 | sym::rustc_capture_analysis
375 | sym::rustc_regions
376 | sym::rustc_strict_coherence
377 | sym::rustc_dump_predicates
378 | sym::rustc_variance
379 | sym::rustc_variance_of_opaques
380 | sym::rustc_hidden_type_of_opaques
381 | sym::rustc_mir
382 | sym::rustc_dump_user_args
383 | sym::rustc_effective_visibility
384 | sym::rustc_outlives
385 | sym::rustc_symbol_name
386 | sym::rustc_evaluate_where_clauses
387 | sym::rustc_dump_vtable
388 | sym::rustc_delayed_bug_from_inside_query
389 | sym::rustc_dump_item_bounds
390 | sym::rustc_def_path
391 | sym::rustc_partition_reused
392 | sym::rustc_partition_codegened
393 | sym::rustc_expected_cgu_reuse
394 | sym::rustc_nounwind,
395 ..
396 ] => {}
397 [name, rest@..] => {
398 match BUILTIN_ATTRIBUTE_MAP.get(name) {
399 Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) => {}
401 Some(_) => {
402 if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
403 continue
407 }
408
409 span_bug!(
410 attr.span(),
411 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
412 )
413 }
414 None => (),
415 }
416 }
417 [] => unreachable!(),
418 }
419 }
420 }
421
422 if hir_id != CRATE_HIR_ID {
423 match attr {
424 Attribute::Parsed(_) => { }
425 Attribute::Unparsed(attr) => {
426 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
429 attr.path
430 .segments
431 .first()
432 .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
433 {
434 match attr.style {
435 ast::AttrStyle::Outer => {
436 let attr_span = attr.span;
437 let bang_position = self
438 .tcx
439 .sess
440 .source_map()
441 .span_until_char(attr_span, '[')
442 .shrink_to_hi();
443
444 self.tcx.emit_node_span_lint(
445 UNUSED_ATTRIBUTES,
446 hir_id,
447 attr.span,
448 errors::OuterCrateLevelAttr {
449 suggestion: errors::OuterCrateLevelAttrSuggestion {
450 bang_position,
451 },
452 },
453 )
454 }
455 ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
456 UNUSED_ATTRIBUTES,
457 hir_id,
458 attr.span,
459 errors::InnerCrateLevelAttr,
460 ),
461 }
462 }
463 }
464 }
465 }
466
467 if let Attribute::Unparsed(unparsed_attr) = attr
468 && let Some(BuiltinAttribute { duplicates, .. }) =
469 attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
470 {
471 check_duplicates(
472 self.tcx,
473 unparsed_attr.span,
474 attr,
475 hir_id,
476 *duplicates,
477 &mut seen,
478 );
479 }
480
481 self.check_unused_attribute(hir_id, attr, style)
482 }
483
484 self.check_repr(attrs, span, target, item, hir_id);
485 self.check_rustc_force_inline(hir_id, attrs, target);
486 self.check_mix_no_mangle_export(hir_id, attrs);
487 }
488
489 fn check_rustc_must_implement_one_of(
490 &self,
491 attr_span: Span,
492 list: &ThinVec<Ident>,
493 hir_id: HirId,
494 target: Target,
495 ) {
496 if !matches!(target, Target::Trait) {
499 return;
500 }
501
502 let def_id = hir_id.owner.def_id;
503
504 let items = self.tcx.associated_items(def_id);
505 for ident in list {
508 let item = items
509 .filter_by_name_unhygienic(ident.name)
510 .find(|item| item.ident(self.tcx) == *ident);
511
512 match item {
513 Some(item) if matches!(item.kind, ty::AssocKind::Fn { .. }) => {
514 if !item.defaultness(self.tcx).has_value() {
515 self.tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation {
516 span: self.tcx.def_span(item.def_id),
517 note_span: attr_span,
518 });
519 }
520 }
521 Some(item) => {
522 self.dcx().emit_err(errors::MustImplementNotFunction {
523 span: self.tcx.def_span(item.def_id),
524 span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span },
525 note: errors::MustImplementNotFunctionNote {},
526 });
527 }
528 None => {
529 self.dcx().emit_err(errors::FunctionNotFoundInTrait { span: ident.span });
530 }
531 }
532 }
533 let mut set: UnordMap<Symbol, Span> = Default::default();
536
537 for ident in &*list {
538 if let Some(dup) = set.insert(ident.name, ident.span) {
539 self.tcx
540 .dcx()
541 .emit_err(errors::FunctionNamesDuplicated { spans: vec![dup, ident.span] });
542 }
543 }
544 }
545
546 fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
547 for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
548 match target {
549 Target::Fn => {}
550 _ => {
551 self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
552 }
553 }
554
555 if let EiiImplResolution::Macro(eii_macro) = resolution
556 && find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
557 && !impl_marked_unsafe
558 {
559 self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
560 span: *span,
561 name: self.tcx.item_name(*eii_macro),
562 suggestion: errors::EiiImplRequiresUnsafeSuggestion {
563 left: inner_span.shrink_to_lo(),
564 right: inner_span.shrink_to_hi(),
565 },
566 });
567 }
568 }
569 }
570
571 fn check_do_not_recommend(
574 &self,
575 attr_span: Span,
576 hir_id: HirId,
577 target: Target,
578 attr: &Attribute,
579 item: Option<ItemLike<'_>>,
580 ) {
581 if !matches!(target, Target::Impl { .. })
582 || matches!(
583 item,
584 Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl),.. }))
585 if _impl.of_trait.is_none()
586 )
587 {
588 self.tcx.emit_node_span_lint(
589 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
590 hir_id,
591 attr_span,
592 errors::IncorrectDoNotRecommendLocation,
593 );
594 }
595 if !attr.is_word() {
596 self.tcx.emit_node_span_lint(
597 MALFORMED_DIAGNOSTIC_ATTRIBUTES,
598 hir_id,
599 attr_span,
600 errors::DoNotRecommendDoesNotExpectArgs,
601 );
602 }
603 }
604
605 fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) {
607 if !matches!(target, Target::Trait) {
608 self.tcx.emit_node_span_lint(
609 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
610 hir_id,
611 attr_span,
612 DiagnosticOnUnimplementedOnlyForTraits,
613 );
614 }
615 }
616
617 fn check_diagnostic_on_const(
619 &self,
620 attr_span: Span,
621 hir_id: HirId,
622 target: Target,
623 item: Option<ItemLike<'_>>,
624 ) {
625 if target == (Target::Impl { of_trait: true }) {
626 match item.unwrap() {
627 ItemLike::Item(it) => match it.expect_impl().constness {
628 Constness::Const => {}
629 Constness::NotConst => return,
630 },
631 ItemLike::ForeignItem => {}
632 }
633 }
634 let item_span = self.tcx.hir_span(hir_id);
635 self.tcx.emit_node_span_lint(
636 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
637 hir_id,
638 attr_span,
639 DiagnosticOnConstOnlyForTraitImpls { item_span },
640 );
641 }
642
643 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
645 match target {
646 Target::Fn
647 | Target::Closure
648 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
649 if let Some(did) = hir_id.as_owner()
651 && self.tcx.def_kind(did).has_codegen_attrs()
652 && kind != &InlineAttr::Never
653 {
654 let attrs = self.tcx.codegen_fn_attrs(did);
655 if attrs.contains_extern_indicator() {
657 self.tcx.emit_node_span_lint(
658 UNUSED_ATTRIBUTES,
659 hir_id,
660 attr_span,
661 errors::InlineIgnoredForExported {},
662 );
663 }
664 }
665 }
666 _ => {}
667 }
668 }
669
670 fn check_sanitize(
673 &self,
674 attr_span: Span,
675 set: SanitizerSet,
676 target_span: Span,
677 target: Target,
678 ) {
679 let mut not_fn_impl_mod = None;
680 let mut no_body = None;
681
682 match target {
683 Target::Fn
684 | Target::Closure
685 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
686 | Target::Impl { .. }
687 | Target::Mod => return,
688 Target::Static
689 if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
692 == SanitizerSet::empty() =>
693 {
694 return;
695 }
696
697 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
700 no_body = Some(target_span);
701 }
702
703 _ => {
704 not_fn_impl_mod = Some(target_span);
705 }
706 }
707
708 self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
709 attr_span,
710 not_fn_impl_mod,
711 no_body,
712 help: (),
713 });
714 }
715
716 fn check_naked(&self, hir_id: HirId, target: Target) {
718 match target {
719 Target::Fn
720 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
721 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
722 let abi = fn_sig.header.abi;
723 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
724 feature_err(
725 &self.tcx.sess,
726 sym::naked_functions_rustic_abi,
727 fn_sig.span,
728 format!(
729 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
730 abi.as_str()
731 ),
732 )
733 .emit();
734 }
735 }
736 _ => {}
737 }
738 }
739
740 fn check_object_lifetime_default(&self, hir_id: HirId) {
742 let tcx = self.tcx;
743 if let Some(owner_id) = hir_id.as_owner()
744 && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
745 {
746 for p in generics.params {
747 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
748 let default = tcx.object_lifetime_default(p.def_id);
749 let repr = match default {
750 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
751 ObjectLifetimeDefault::Static => "'static".to_owned(),
752 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
753 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
754 };
755 tcx.dcx().emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
756 }
757 }
758 }
759
760 fn check_track_caller(
762 &self,
763 hir_id: HirId,
764 attr_span: Span,
765 attrs: &[Attribute],
766 target: Target,
767 ) {
768 match target {
769 Target::Fn => {
770 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
773 && let Some(item) = hir::LangItem::from_name(lang_item)
774 && item.is_weak()
775 {
776 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
777
778 self.dcx().emit_err(errors::LangItemWithTrackCaller {
779 attr_span,
780 name: lang_item,
781 sig_span: sig.span,
782 });
783 }
784
785 if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
786 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
787 for i in impls {
788 let name = match i.resolution {
789 EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
790 EiiImplResolution::Known(decl) => decl.name.name,
791 EiiImplResolution::Error(_eg) => continue,
792 };
793 self.dcx().emit_err(errors::EiiWithTrackCaller {
794 attr_span,
795 name,
796 sig_span: sig.span,
797 });
798 }
799 }
800 }
801 _ => {}
802 }
803 }
804
805 fn check_non_exhaustive(
807 &self,
808 attr_span: Span,
809 span: Span,
810 target: Target,
811 item: Option<ItemLike<'_>>,
812 ) {
813 match target {
814 Target::Struct => {
815 if let Some(ItemLike::Item(hir::Item {
816 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
817 ..
818 })) = item
819 && !fields.is_empty()
820 && fields.iter().any(|f| f.default.is_some())
821 {
822 self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
823 attr_span,
824 defn_span: span,
825 });
826 }
827 }
828 _ => {}
829 }
830 }
831
832 fn check_target_feature(
834 &self,
835 hir_id: HirId,
836 attr_span: Span,
837 target: Target,
838 attrs: &[Attribute],
839 ) {
840 match target {
841 Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
842 | Target::Fn => {
843 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
845 && !self.tcx.sess.target.is_like_wasm
848 && !self.tcx.sess.opts.actually_rustdoc
849 {
850 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
851
852 self.dcx().emit_err(errors::LangItemWithTargetFeature {
853 attr_span,
854 name: lang_item,
855 sig_span: sig.span,
856 });
857 }
858 }
859 _ => {}
860 }
861 }
862
863 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
864 if let Some(location) = match target {
865 Target::AssocTy => {
866 if let DefKind::Impl { .. } =
867 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
868 {
869 Some("type alias in implementation block")
870 } else {
871 None
872 }
873 }
874 Target::AssocConst => {
875 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
876 let containing_item = self.tcx.hir_expect_item(parent_def_id);
877 let err = "associated constant in trait implementation block";
879 match containing_item.kind {
880 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
881 _ => None,
882 }
883 }
884 Target::Param => return,
886 Target::Expression
887 | Target::Statement
888 | Target::Arm
889 | Target::ForeignMod
890 | Target::Closure
891 | Target::Impl { .. }
892 | Target::WherePredicate => Some(target.name()),
893 Target::ExternCrate
894 | Target::Use
895 | Target::Static
896 | Target::Const
897 | Target::Fn
898 | Target::Mod
899 | Target::GlobalAsm
900 | Target::TyAlias
901 | Target::Enum
902 | Target::Variant
903 | Target::Struct
904 | Target::Field
905 | Target::Union
906 | Target::Trait
907 | Target::TraitAlias
908 | Target::Method(..)
909 | Target::ForeignFn
910 | Target::ForeignStatic
911 | Target::ForeignTy
912 | Target::GenericParam { .. }
913 | Target::MacroDef
914 | Target::PatField
915 | Target::ExprField
916 | Target::Crate
917 | Target::MacroCall
918 | Target::Delegation { .. } => None,
919 } {
920 self.tcx.dcx().emit_err(errors::DocAliasBadLocation { span, location });
921 return;
922 }
923 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
924 self.tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str: alias });
925 return;
926 }
927 }
928
929 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
930 let item_kind = match self.tcx.hir_node(hir_id) {
931 hir::Node::Item(item) => Some(&item.kind),
932 _ => None,
933 };
934 match item_kind {
935 Some(ItemKind::Impl(i)) => {
936 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
937 || if let Some(&[hir::GenericArg::Type(ty)]) = i
938 .of_trait
939 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
940 .map(|last_segment| last_segment.args().args)
941 {
942 matches!(&ty.kind, hir::TyKind::Tup([_]))
943 } else {
944 false
945 };
946 if !is_valid {
947 self.dcx().emit_err(errors::DocFakeVariadicNotValid { span });
948 }
949 }
950 _ => {
951 self.dcx().emit_err(errors::DocKeywordOnlyImpl { span });
952 }
953 }
954 }
955
956 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
957 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
958 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
959 return;
960 };
961 match item.kind {
962 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
963 if generics.params.len() != 0 => {}
964 ItemKind::Trait(_, _, _, _, generics, _, items)
965 if generics.params.len() != 0
966 || items.iter().any(|item| {
967 matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy)
968 }) => {}
969 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
970 _ => {
971 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
972 }
973 }
974 }
975
976 fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
986 let span = match inline {
987 [] => return,
988 [(_, span)] => *span,
989 [(inline, span), rest @ ..] => {
990 for (inline2, span2) in rest {
991 if inline2 != inline {
992 let mut spans = MultiSpan::from_spans(vec![*span, *span2]);
993 spans.push_span_label(*span, fluent::passes_doc_inline_conflict_first);
994 spans.push_span_label(*span2, fluent::passes_doc_inline_conflict_second);
995 self.dcx().emit_err(errors::DocInlineConflict { spans });
996 return;
997 }
998 }
999 *span
1000 }
1001 };
1002
1003 match target {
1004 Target::Use | Target::ExternCrate => {}
1005 _ => {
1006 self.tcx.emit_node_span_lint(
1007 INVALID_DOC_ATTRIBUTES,
1008 hir_id,
1009 span,
1010 errors::DocInlineOnlyUse {
1011 attr_span: span,
1012 item_span: self.tcx.hir_span(hir_id),
1013 },
1014 );
1015 }
1016 }
1017 }
1018
1019 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
1020 if target != Target::ExternCrate {
1021 self.tcx.emit_node_span_lint(
1022 INVALID_DOC_ATTRIBUTES,
1023 hir_id,
1024 span,
1025 errors::DocMaskedOnlyExternCrate {
1026 attr_span: span,
1027 item_span: self.tcx.hir_span(hir_id),
1028 },
1029 );
1030 return;
1031 }
1032
1033 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1034 self.tcx.emit_node_span_lint(
1035 INVALID_DOC_ATTRIBUTES,
1036 hir_id,
1037 span,
1038 errors::DocMaskedNotExternCrateSelf {
1039 attr_span: span,
1040 item_span: self.tcx.hir_span(hir_id),
1041 },
1042 );
1043 }
1044 }
1045
1046 fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1047 let item_kind = match self.tcx.hir_node(hir_id) {
1048 hir::Node::Item(item) => Some(&item.kind),
1049 _ => None,
1050 };
1051 match item_kind {
1052 Some(ItemKind::Mod(_, module)) => {
1053 if !module.item_ids.is_empty() {
1054 self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod { span, attr_name });
1055 return;
1056 }
1057 }
1058 _ => {
1059 self.dcx().emit_err(errors::DocKeywordAttributeNotMod { span, attr_name });
1060 return;
1061 }
1062 }
1063 }
1064
1065 fn check_attr_not_crate_level(&self, span: Span, hir_id: HirId, attr_name: &str) -> bool {
1067 if CRATE_HIR_ID == hir_id {
1068 self.dcx().emit_err(errors::DocAttrNotCrateLevel { span, attr_name });
1069 return false;
1070 }
1071 true
1072 }
1073
1074 fn check_attr_crate_level(&self, span: Span, hir_id: HirId) -> bool {
1076 if hir_id != CRATE_HIR_ID {
1077 self.tcx.emit_node_span_lint(
1078 INVALID_DOC_ATTRIBUTES,
1079 hir_id,
1080 span,
1081 errors::AttrCrateLevelOnly {},
1082 );
1083 return false;
1084 }
1085 true
1086 }
1087
1088 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1095 let DocAttribute {
1096 aliases,
1097 hidden: _,
1100 inline,
1101 cfg: _,
1103 auto_cfg: _,
1105 auto_cfg_change: _,
1107 fake_variadic,
1108 keyword,
1109 masked,
1110 notable_trait: _,
1112 search_unbox,
1113 html_favicon_url,
1114 html_logo_url,
1115 html_playground_url,
1116 html_root_url,
1117 html_no_source,
1118 issue_tracker_base_url,
1119 rust_logo,
1120 test_attrs: _,
1122 no_crate_inject,
1123 attribute,
1124 } = attr;
1125
1126 for (alias, span) in aliases {
1127 if self.check_attr_not_crate_level(*span, hir_id, "alias") {
1128 self.check_doc_alias_value(*span, hir_id, target, *alias);
1129 }
1130 }
1131
1132 if let Some((_, span)) = keyword
1133 && self.check_attr_not_crate_level(*span, hir_id, "keyword")
1134 {
1135 self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1136 }
1137 if let Some((_, span)) = attribute
1138 && self.check_attr_not_crate_level(*span, hir_id, "attribute")
1139 {
1140 self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1141 }
1142
1143 if let Some(span) = fake_variadic
1144 && self.check_attr_not_crate_level(*span, hir_id, "fake_variadic")
1145 {
1146 self.check_doc_fake_variadic(*span, hir_id);
1147 }
1148
1149 if let Some(span) = search_unbox
1150 && self.check_attr_not_crate_level(*span, hir_id, "search_unbox")
1151 {
1152 self.check_doc_search_unbox(*span, hir_id);
1153 }
1154
1155 for i in [
1156 html_favicon_url,
1157 html_logo_url,
1158 html_playground_url,
1159 issue_tracker_base_url,
1160 html_root_url,
1161 ] {
1162 if let Some((_, span)) = i {
1163 self.check_attr_crate_level(*span, hir_id);
1164 }
1165 }
1166
1167 for i in [html_no_source, no_crate_inject] {
1168 if let Some(span) = i {
1169 self.check_attr_crate_level(*span, hir_id);
1170 }
1171 }
1172
1173 self.check_doc_inline(hir_id, target, inline);
1174
1175 if let Some(span) = rust_logo
1176 && self.check_attr_crate_level(*span, hir_id)
1177 && !self.tcx.features().rustdoc_internals()
1178 {
1179 feature_err(
1180 &self.tcx.sess,
1181 sym::rustdoc_internals,
1182 *span,
1183 fluent::passes_doc_rust_logo,
1184 )
1185 .emit();
1186 }
1187
1188 if let Some(span) = masked {
1189 self.check_doc_masked(*span, hir_id, target);
1190 }
1191 }
1192
1193 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1194 if find_attr!(attrs, AttributeKind::FfiConst(_)) {
1195 self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1197 }
1198 }
1199
1200 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) {
1202 match target {
1203 Target::Struct | Target::Enum | Target::Union | Target::Trait => {}
1204 _ => {
1205 self.dcx().emit_err(errors::MustNotSuspend { attr_span: attr.span(), span });
1206 }
1207 }
1208 }
1209
1210 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1212 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1213 && matches!(
1214 param.kind,
1215 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1216 )
1217 && matches!(param.source, hir::GenericParamSource::Generics)
1218 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1219 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1220 && let hir::ItemKind::Impl(impl_) = item.kind
1221 && let Some(of_trait) = impl_.of_trait
1222 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1223 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1224 {
1225 return;
1226 }
1227
1228 self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1229 }
1230
1231 fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1233 if target == Target::ForeignMod
1234 && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1235 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1236 && !matches!(abi, ExternAbi::Rust)
1237 {
1238 return;
1239 }
1240
1241 self.tcx.emit_node_span_lint(
1242 UNUSED_ATTRIBUTES,
1243 hir_id,
1244 attr_span,
1245 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1246 );
1247 }
1248
1249 fn check_rustc_legacy_const_generics(
1251 &self,
1252 item: Option<ItemLike<'_>>,
1253 attr_span: Span,
1254 index_list: &ThinVec<(usize, Span)>,
1255 ) {
1256 let Some(ItemLike::Item(Item {
1257 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1258 ..
1259 })) = item
1260 else {
1261 return;
1263 };
1264
1265 for param in generics.params {
1266 match param.kind {
1267 hir::GenericParamKind::Const { .. } => {}
1268 _ => {
1269 self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1270 attr_span,
1271 param_span: param.span,
1272 });
1273 return;
1274 }
1275 }
1276 }
1277
1278 if index_list.len() != generics.params.len() {
1279 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1280 attr_span,
1281 generics_span: generics.span,
1282 });
1283 return;
1284 }
1285
1286 let arg_count = decl.inputs.len() + generics.params.len();
1287 for (index, span) in index_list {
1288 if *index >= arg_count {
1289 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1290 span: *span,
1291 arg_count,
1292 });
1293 }
1294 }
1295 }
1296
1297 fn check_rustc_dirty_clean(&self, attr: &Attribute) {
1300 if !self.tcx.sess.opts.unstable_opts.query_dep_graph {
1301 self.dcx().emit_err(errors::RustcDirtyClean { span: attr.span() });
1302 }
1303 }
1304
1305 fn check_repr(
1307 &self,
1308 attrs: &[Attribute],
1309 span: Span,
1310 target: Target,
1311 item: Option<ItemLike<'_>>,
1312 hir_id: HirId,
1313 ) {
1314 let (reprs, first_attr_span) = find_attr!(attrs, AttributeKind::Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))).unwrap_or((&[], None));
1320
1321 let mut int_reprs = 0;
1322 let mut is_explicit_rust = false;
1323 let mut is_c = false;
1324 let mut is_simd = false;
1325 let mut is_transparent = false;
1326
1327 for (repr, repr_span) in reprs {
1328 match repr {
1329 ReprAttr::ReprRust => {
1330 is_explicit_rust = true;
1331 match target {
1332 Target::Struct | Target::Union | Target::Enum => continue,
1333 _ => {
1334 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1335 hint_span: *repr_span,
1336 span,
1337 });
1338 }
1339 }
1340 }
1341 ReprAttr::ReprC => {
1342 is_c = true;
1343 match target {
1344 Target::Struct | Target::Union | Target::Enum => continue,
1345 _ => {
1346 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1347 hint_span: *repr_span,
1348 span,
1349 });
1350 }
1351 }
1352 }
1353 ReprAttr::ReprAlign(align) => {
1354 match target {
1355 Target::Struct | Target::Union | Target::Enum => {}
1356 Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1357 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1358 span: *repr_span,
1359 item: target.plural_name(),
1360 });
1361 }
1362 Target::Static if self.tcx.features().static_align() => {
1363 self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1364 span: *repr_span,
1365 item: target.plural_name(),
1366 });
1367 }
1368 _ => {
1369 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1370 hint_span: *repr_span,
1371 span,
1372 });
1373 }
1374 }
1375
1376 self.check_align(*align, *repr_span);
1377 }
1378 ReprAttr::ReprPacked(_) => {
1379 if target != Target::Struct && target != Target::Union {
1380 self.dcx().emit_err(errors::AttrApplication::StructUnion {
1381 hint_span: *repr_span,
1382 span,
1383 });
1384 } else {
1385 continue;
1386 }
1387 }
1388 ReprAttr::ReprSimd => {
1389 is_simd = true;
1390 if target != Target::Struct {
1391 self.dcx().emit_err(errors::AttrApplication::Struct {
1392 hint_span: *repr_span,
1393 span,
1394 });
1395 } else {
1396 continue;
1397 }
1398 }
1399 ReprAttr::ReprTransparent => {
1400 is_transparent = true;
1401 match target {
1402 Target::Struct | Target::Union | Target::Enum => continue,
1403 _ => {
1404 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1405 hint_span: *repr_span,
1406 span,
1407 });
1408 }
1409 }
1410 }
1411 ReprAttr::ReprInt(_) => {
1412 int_reprs += 1;
1413 if target != Target::Enum {
1414 self.dcx().emit_err(errors::AttrApplication::Enum {
1415 hint_span: *repr_span,
1416 span,
1417 });
1418 } else {
1419 continue;
1420 }
1421 }
1422 };
1423 }
1424
1425 if let Some(first_attr_span) = first_attr_span
1427 && reprs.is_empty()
1428 && item.is_some()
1429 {
1430 match target {
1431 Target::Struct | Target::Union | Target::Enum => {}
1432 Target::Fn | Target::Method(_) => {
1433 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1434 span: first_attr_span,
1435 item: target.plural_name(),
1436 });
1437 }
1438 _ => {
1439 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1440 hint_span: first_attr_span,
1441 span,
1442 });
1443 }
1444 }
1445 return;
1446 }
1447
1448 let hint_spans = reprs.iter().map(|(_, span)| *span);
1451
1452 if is_transparent && reprs.len() > 1 {
1454 let hint_spans = hint_spans.clone().collect();
1455 self.dcx().emit_err(errors::TransparentIncompatible {
1456 hint_spans,
1457 target: target.to_string(),
1458 });
1459 }
1460 if is_transparent
1463 && let Some(&pass_indirectly_span) =
1464 find_attr!(attrs, AttributeKind::RustcPassIndirectlyInNonRusticAbis(span) => span)
1465 {
1466 self.dcx().emit_err(errors::TransparentIncompatible {
1467 hint_spans: vec![span, pass_indirectly_span],
1468 target: target.to_string(),
1469 });
1470 }
1471 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1472 let hint_spans = hint_spans.clone().collect();
1473 self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1474 }
1475 if (int_reprs > 1)
1477 || (is_simd && is_c)
1478 || (int_reprs == 1
1479 && is_c
1480 && item.is_some_and(|item| {
1481 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1482 }))
1483 {
1484 self.tcx.emit_node_span_lint(
1485 CONFLICTING_REPR_HINTS,
1486 hir_id,
1487 hint_spans.collect::<Vec<Span>>(),
1488 errors::ReprConflictingLint,
1489 );
1490 }
1491 }
1492
1493 fn check_align(&self, align: Align, span: Span) {
1494 if align.bytes() > 2_u64.pow(29) {
1495 self.dcx().span_delayed_bug(
1497 span,
1498 "alignment greater than 2^29 should be errored on elsewhere",
1499 );
1500 } else {
1501 let max = Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64;
1506 if align.bytes() > max {
1507 self.dcx().emit_err(errors::InvalidReprAlignForTarget { span, size: max });
1508 }
1509 }
1510 }
1511
1512 fn check_macro_only_attr(
1517 &self,
1518 attr_span: Span,
1519 span: Span,
1520 target: Target,
1521 attrs: &[Attribute],
1522 ) {
1523 match target {
1524 Target::Fn => {
1525 for attr in attrs {
1526 if attr.is_proc_macro_attr() {
1527 return;
1529 }
1530 }
1531 self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1532 }
1533 _ => {}
1534 }
1535 }
1536
1537 fn check_rustc_allow_const_fn_unstable(
1540 &self,
1541 hir_id: HirId,
1542 attr_span: Span,
1543 span: Span,
1544 target: Target,
1545 ) {
1546 match target {
1547 Target::Fn | Target::Method(_) => {
1548 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1549 self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1550 }
1551 }
1552 _ => {}
1553 }
1554 }
1555
1556 fn check_stability(
1557 &self,
1558 attr_span: Span,
1559 item_span: Span,
1560 level: &StabilityLevel,
1561 feature: Symbol,
1562 ) {
1563 if level.is_unstable()
1566 && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1567 {
1568 self.tcx
1569 .dcx()
1570 .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1571 }
1572 }
1573
1574 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1575 match target {
1576 Target::AssocConst | Target::Method(..) | Target::AssocTy
1577 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1578 == DefKind::Impl { of_trait: true } =>
1579 {
1580 self.tcx.emit_node_span_lint(
1581 UNUSED_ATTRIBUTES,
1582 hir_id,
1583 attr_span,
1584 errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1585 );
1586 }
1587 _ => {}
1588 }
1589 }
1590
1591 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1592 if target != Target::MacroDef {
1593 return;
1594 }
1595
1596 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1598 let is_decl_macro = !macro_definition.macro_rules;
1599
1600 if is_decl_macro {
1601 self.tcx.emit_node_span_lint(
1602 UNUSED_ATTRIBUTES,
1603 hir_id,
1604 attr_span,
1605 errors::MacroExport::OnDeclMacro,
1606 );
1607 }
1608 }
1609
1610 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1611 let note = if attr.has_any_name(&[
1614 sym::allow,
1615 sym::expect,
1616 sym::warn,
1617 sym::deny,
1618 sym::forbid,
1619 sym::feature,
1620 ]) && attr.meta_item_list().is_some_and(|list| list.is_empty())
1621 {
1622 errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1623 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1624 && let Some(meta) = attr.meta_item_list()
1625 && let [meta] = meta.as_slice()
1626 && let Some(item) = meta.meta_item()
1627 && let MetaItemKind::NameValue(_) = &item.kind
1628 && item.path == sym::reason
1629 {
1630 errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1631 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1632 && let Some(meta) = attr.meta_item_list()
1633 && meta.iter().any(|meta| {
1634 meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
1635 })
1636 {
1637 if hir_id != CRATE_HIR_ID {
1638 match style {
1639 Some(ast::AttrStyle::Outer) => {
1640 let attr_span = attr.span();
1641 let bang_position = self
1642 .tcx
1643 .sess
1644 .source_map()
1645 .span_until_char(attr_span, '[')
1646 .shrink_to_hi();
1647
1648 self.tcx.emit_node_span_lint(
1649 UNUSED_ATTRIBUTES,
1650 hir_id,
1651 attr_span,
1652 errors::OuterCrateLevelAttr {
1653 suggestion: errors::OuterCrateLevelAttrSuggestion { bang_position },
1654 },
1655 )
1656 }
1657 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1658 UNUSED_ATTRIBUTES,
1659 hir_id,
1660 attr.span(),
1661 errors::InnerCrateLevelAttr,
1662 ),
1663 };
1664 return;
1665 } else {
1666 let never_needs_link = self
1667 .tcx
1668 .crate_types()
1669 .iter()
1670 .all(|kind| matches!(kind, CrateType::Rlib | CrateType::Staticlib));
1671 if never_needs_link {
1672 errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1673 } else {
1674 return;
1675 }
1676 }
1677 } else if attr.has_name(sym::default_method_body_is_const) {
1678 errors::UnusedNote::DefaultMethodBodyConst
1679 } else {
1680 return;
1681 };
1682
1683 self.tcx.emit_node_span_lint(
1684 UNUSED_ATTRIBUTES,
1685 hir_id,
1686 attr.span(),
1687 errors::Unused { attr_span: attr.span(), note },
1688 );
1689 }
1690
1691 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1695 if target != Target::Fn {
1696 return;
1697 }
1698
1699 let tcx = self.tcx;
1700 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1701 return;
1702 };
1703 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1704 return;
1705 };
1706
1707 let def_id = hir_id.expect_owner().def_id;
1708 let param_env = ty::ParamEnv::empty();
1709
1710 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1711 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1712
1713 let span = tcx.def_span(def_id);
1714 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1715 let sig = tcx.liberate_late_bound_regions(
1716 def_id.to_def_id(),
1717 tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
1718 );
1719
1720 let mut cause = ObligationCause::misc(span, def_id);
1721 let sig = ocx.normalize(&cause, param_env, sig);
1722
1723 let errors = ocx.try_evaluate_obligations();
1725 if !errors.is_empty() {
1726 return;
1727 }
1728
1729 let expected_sig = tcx.mk_fn_sig(
1730 std::iter::repeat_n(
1731 token_stream,
1732 match kind {
1733 ProcMacroKind::Attribute => 2,
1734 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1735 },
1736 ),
1737 token_stream,
1738 false,
1739 Safety::Safe,
1740 ExternAbi::Rust,
1741 );
1742
1743 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1744 let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
1745
1746 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1747 if let Some(hir_sig) = hir_sig {
1748 #[allow(rustc::diagnostic_outside_of_impl)] match terr {
1750 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1751 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1752 diag.span(ty.span);
1753 cause.span = ty.span;
1754 } else if idx == hir_sig.decl.inputs.len() {
1755 let span = hir_sig.decl.output.span();
1756 diag.span(span);
1757 cause.span = span;
1758 }
1759 }
1760 TypeError::ArgCount => {
1761 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1762 diag.span(ty.span);
1763 cause.span = ty.span;
1764 }
1765 }
1766 TypeError::SafetyMismatch(_) => {
1767 }
1769 TypeError::AbiMismatch(_) => {
1770 }
1772 TypeError::VariadicMismatch(_) => {
1773 }
1775 _ => {}
1776 }
1777 }
1778
1779 infcx.err_ctxt().note_type_err(
1780 &mut diag,
1781 &cause,
1782 None,
1783 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1784 expected: ty::Binder::dummy(expected_sig),
1785 found: ty::Binder::dummy(sig),
1786 }))),
1787 terr,
1788 false,
1789 None,
1790 );
1791 diag.emit();
1792 self.abort.set(true);
1793 }
1794
1795 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1796 if !errors.is_empty() {
1797 infcx.err_ctxt().report_fulfillment_errors(errors);
1798 self.abort.set(true);
1799 }
1800 }
1801
1802 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1803 if !find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent))
1804 .unwrap_or(false)
1805 {
1806 self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
1807 }
1808 }
1809
1810 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1811 if let (Target::Closure, None) = (
1812 target,
1813 find_attr!(attrs, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
1814 ) {
1815 let is_coro = matches!(
1816 self.tcx.hir_expect_expr(hir_id).kind,
1817 hir::ExprKind::Closure(hir::Closure {
1818 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1819 ..
1820 })
1821 );
1822 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1823 let parent_span = self.tcx.def_span(parent_did);
1824
1825 if let Some(attr_span) = find_attr!(
1826 self.tcx.get_all_attrs(parent_did),
1827 AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1828 ) && is_coro
1829 {
1830 self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
1831 }
1832 }
1833 }
1834
1835 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1836 if let Some(export_name_span) = find_attr!(attrs, AttributeKind::ExportName { span: export_name_span, .. } => *export_name_span)
1837 && let Some(no_mangle_span) =
1838 find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span)
1839 {
1840 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1841 "#[unsafe(no_mangle)]"
1842 } else {
1843 "#[no_mangle]"
1844 };
1845 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1846 "#[unsafe(export_name)]"
1847 } else {
1848 "#[export_name]"
1849 };
1850
1851 self.tcx.emit_node_span_lint(
1852 lint::builtin::UNUSED_ATTRIBUTES,
1853 hir_id,
1854 no_mangle_span,
1855 errors::MixedExportNameAndNoMangle {
1856 no_mangle_span,
1857 export_name_span,
1858 no_mangle_attr,
1859 export_name_attr,
1860 },
1861 );
1862 }
1863 }
1864
1865 fn check_autodiff(&self, _hir_id: HirId, _attr: &Attribute, span: Span, target: Target) {
1867 debug!("check_autodiff");
1868 match target {
1869 Target::Fn => {}
1870 _ => {
1871 self.dcx().emit_err(errors::AutoDiffAttr { attr_span: span });
1872 self.abort.set(true);
1873 }
1874 }
1875 }
1876
1877 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1878 let node_span = self.tcx.hir_span(hir_id);
1879
1880 if !matches!(target, Target::Expression) {
1881 return; }
1883
1884 if !matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Loop(..)) {
1885 self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
1886 };
1887 }
1888
1889 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1890 let node_span = self.tcx.hir_span(hir_id);
1891
1892 if !matches!(target, Target::Expression) {
1893 return; }
1895
1896 if !matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Break(..)) {
1897 self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
1898 };
1899 }
1900
1901 fn check_custom_mir(
1902 &self,
1903 dialect: Option<(MirDialect, Span)>,
1904 phase: Option<(MirPhase, Span)>,
1905 attr_span: Span,
1906 ) {
1907 let Some((dialect, dialect_span)) = dialect else {
1908 if let Some((_, phase_span)) = phase {
1909 self.dcx()
1910 .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
1911 }
1912 return;
1913 };
1914
1915 match dialect {
1916 MirDialect::Analysis => {
1917 if let Some((MirPhase::Optimized, phase_span)) = phase {
1918 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1919 dialect,
1920 phase: MirPhase::Optimized,
1921 attr_span,
1922 dialect_span,
1923 phase_span,
1924 });
1925 }
1926 }
1927
1928 MirDialect::Built => {
1929 if let Some((phase, phase_span)) = phase {
1930 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1931 dialect,
1932 phase,
1933 attr_span,
1934 dialect_span,
1935 phase_span,
1936 });
1937 }
1938 }
1939 MirDialect::Runtime => {}
1940 }
1941 }
1942}
1943
1944impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1945 type NestedFilter = nested_filter::OnlyBodies;
1946
1947 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1948 self.tcx
1949 }
1950
1951 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1952 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1956 let def_id = item.owner_id.to_def_id();
1957 if macro_def.macro_rules
1958 && !find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. })
1959 {
1960 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1961 }
1962 }
1963
1964 let target = Target::from_item(item);
1965 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1966 intravisit::walk_item(self, item)
1967 }
1968
1969 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1970 let spans = self
1975 .tcx
1976 .hir_attrs(where_predicate.hir_id)
1977 .iter()
1978 .filter(|attr| {
1980 matches!(
1981 attr,
1982 Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
1983 | Attribute::Unparsed(_)
1984 )
1985 })
1986 .map(|attr| attr.span())
1987 .collect::<Vec<_>>();
1988 if !spans.is_empty() {
1989 self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
1990 }
1991 self.check_attributes(
1992 where_predicate.hir_id,
1993 where_predicate.span,
1994 Target::WherePredicate,
1995 None,
1996 );
1997 intravisit::walk_where_predicate(self, where_predicate)
1998 }
1999
2000 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2001 let target = Target::from_generic_param(generic_param);
2002 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2003 intravisit::walk_generic_param(self, generic_param)
2004 }
2005
2006 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2007 let target = Target::from_trait_item(trait_item);
2008 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2009 intravisit::walk_trait_item(self, trait_item)
2010 }
2011
2012 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2013 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2014 intravisit::walk_field_def(self, struct_field);
2015 }
2016
2017 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2018 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2019 intravisit::walk_arm(self, arm);
2020 }
2021
2022 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2023 let target = Target::from_foreign_item(f_item);
2024 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2025 intravisit::walk_foreign_item(self, f_item)
2026 }
2027
2028 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2029 let target = target_from_impl_item(self.tcx, impl_item);
2030 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2031 intravisit::walk_impl_item(self, impl_item)
2032 }
2033
2034 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2035 if let hir::StmtKind::Let(l) = stmt.kind {
2037 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2038 }
2039 intravisit::walk_stmt(self, stmt)
2040 }
2041
2042 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2043 let target = match expr.kind {
2044 hir::ExprKind::Closure { .. } => Target::Closure,
2045 _ => Target::Expression,
2046 };
2047
2048 self.check_attributes(expr.hir_id, expr.span, target, None);
2049 intravisit::walk_expr(self, expr)
2050 }
2051
2052 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2053 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2054 intravisit::walk_expr_field(self, field)
2055 }
2056
2057 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2058 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2059 intravisit::walk_variant(self, variant)
2060 }
2061
2062 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2063 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2064
2065 intravisit::walk_param(self, param);
2066 }
2067
2068 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2069 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2070 intravisit::walk_pat_field(self, field);
2071 }
2072}
2073
2074fn is_c_like_enum(item: &Item<'_>) -> bool {
2075 if let ItemKind::Enum(_, _, ref def) = item.kind {
2076 for variant in def.variants {
2077 match variant.data {
2078 hir::VariantData::Unit(..) => { }
2079 _ => return false,
2080 }
2081 }
2082 true
2083 } else {
2084 false
2085 }
2086}
2087
2088fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2091 const ATTRS_TO_CHECK: &[Symbol] =
2095 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2096
2097 for attr in attrs {
2098 let (span, name) = if let Some(a) =
2100 ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2101 {
2102 (attr.span(), *a)
2103 } else if let Attribute::Parsed(AttributeKind::Repr {
2104 reprs: _,
2105 first_span: first_attr_span,
2106 }) = attr
2107 {
2108 (*first_attr_span, sym::repr)
2109 } else {
2110 continue;
2111 };
2112
2113 let item = tcx
2114 .hir_free_items()
2115 .map(|id| tcx.hir_item(id))
2116 .find(|item| !item.span.is_dummy()) .map(|item| errors::ItemFollowingInnerAttr {
2118 span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2119 kind: tcx.def_descr(item.owner_id.to_def_id()),
2120 });
2121 let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2122 span,
2123 sugg_span: tcx
2124 .sess
2125 .source_map()
2126 .span_to_snippet(span)
2127 .ok()
2128 .filter(|src| src.starts_with("#!["))
2129 .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2130 name,
2131 item,
2132 });
2133
2134 if let Attribute::Unparsed(p) = attr {
2135 tcx.dcx().try_steal_replace_and_emit_err(
2136 p.path.span,
2137 StashKey::UndeterminedMacroResolution,
2138 err,
2139 );
2140 } else {
2141 err.emit();
2142 }
2143 }
2144}
2145
2146fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2147 let attrs = tcx.hir_attrs(item.hir_id());
2148
2149 if let Some(attr_span) = find_attr!(attrs, AttributeKind::Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
2150 {
2151 tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2152 }
2153}
2154
2155fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2156 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2157 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2158 if module_def_id.to_local_def_id().is_top_level_module() {
2159 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2160 check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2161 }
2162 if check_attr_visitor.abort.get() {
2163 tcx.dcx().abort_if_errors()
2164 }
2165}
2166
2167pub(crate) fn provide(providers: &mut Providers) {
2168 *providers = Providers { check_mod_attrs, ..*providers };
2169}
2170
2171fn check_duplicates(
2173 tcx: TyCtxt<'_>,
2174 attr_span: Span,
2175 attr: &Attribute,
2176 hir_id: HirId,
2177 duplicates: AttributeDuplicates,
2178 seen: &mut FxHashMap<Symbol, Span>,
2179) {
2180 use AttributeDuplicates::*;
2181 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2182 return;
2183 }
2184 let attr_name = attr.name().unwrap();
2185 match duplicates {
2186 DuplicatesOk => {}
2187 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2188 match seen.entry(attr_name) {
2189 Entry::Occupied(mut entry) => {
2190 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2191 let to_remove = entry.insert(attr_span);
2192 (to_remove, attr_span)
2193 } else {
2194 (attr_span, *entry.get())
2195 };
2196 tcx.emit_node_span_lint(
2197 UNUSED_ATTRIBUTES,
2198 hir_id,
2199 this,
2200 errors::UnusedDuplicate {
2201 this,
2202 other,
2203 warning: matches!(
2204 duplicates,
2205 FutureWarnFollowing | FutureWarnPreceding
2206 ),
2207 },
2208 );
2209 }
2210 Entry::Vacant(entry) => {
2211 entry.insert(attr_span);
2212 }
2213 }
2214 }
2215 ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2216 Entry::Occupied(mut entry) => {
2217 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2218 let to_remove = entry.insert(attr_span);
2219 (to_remove, attr_span)
2220 } else {
2221 (attr_span, *entry.get())
2222 };
2223 tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2224 }
2225 Entry::Vacant(entry) => {
2226 entry.insert(attr_span);
2227 }
2228 },
2229 }
2230}
2231
2232fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2233 matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2234 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2235 fn_ptr_ty.decl.inputs.len() == 1
2236 } else {
2237 false
2238 }
2239 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2240 && let Some(&[hir::GenericArg::Type(ty)]) =
2241 path.segments.last().map(|last| last.args().args)
2242 {
2243 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2244 } else {
2245 false
2246 })
2247}