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