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, msg};
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, MISPLACED_DIAGNOSTIC_ATTRIBUTES,
47 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;
58
59#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnUnimplementedOnlyForTraits {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnUnimplementedOnlyForTraits => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")));
;
diag
}
};
}
}
};LintDiagnostic)]
60#[diag("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")]
61struct DiagnosticOnUnimplementedOnlyForTraits;
62
63#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnConstOnlyForTraitImpls {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnConstOnlyForTraitImpls { item_span: __binding_0
} => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to trait impls")));
;
diag.span_label(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("not a trait impl")));
diag
}
};
}
}
};LintDiagnostic)]
64#[diag("`#[diagnostic::on_const]` can only be applied to trait impls")]
65struct DiagnosticOnConstOnlyForTraitImpls {
66 #[label("not a trait impl")]
67 item_span: Span,
68}
69
70#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnConstOnlyForNonConstTraitImpls {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnConstOnlyForNonConstTraitImpls {
item_span: __binding_0 } => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to non-const trait impls")));
;
diag.span_label(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait impl")));
diag
}
};
}
}
};LintDiagnostic)]
71#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait impls")]
72struct DiagnosticOnConstOnlyForNonConstTraitImpls {
73 #[label("this is a const trait impl")]
74 item_span: Span,
75}
76
77fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
78 match impl_item.kind {
79 hir::ImplItemKind::Const(..) => Target::AssocConst,
80 hir::ImplItemKind::Fn(..) => {
81 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
82 let containing_item = tcx.hir_expect_item(parent_def_id);
83 let containing_impl_is_for_trait = match &containing_item.kind {
84 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
85 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("parent of an ImplItem must be an Impl"))bug!("parent of an ImplItem must be an Impl"),
86 };
87 if containing_impl_is_for_trait {
88 Target::Method(MethodKind::Trait { body: true })
89 } else {
90 Target::Method(MethodKind::Inherent)
91 }
92 }
93 hir::ImplItemKind::Type(..) => Target::AssocTy,
94 }
95}
96
97#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ItemLike<'tcx> {
#[inline]
fn clone(&self) -> ItemLike<'tcx> {
let _: ::core::clone::AssertParamIsClone<&'tcx Item<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ItemLike<'tcx> { }Copy)]
98enum ItemLike<'tcx> {
99 Item(&'tcx Item<'tcx>),
100 ForeignItem,
101}
102
103#[derive(#[automatically_derived]
impl ::core::marker::Copy for ProcMacroKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ProcMacroKind {
#[inline]
fn clone(&self) -> ProcMacroKind { *self }
}Clone)]
104pub(crate) enum ProcMacroKind {
105 FunctionLike,
106 Derive,
107 Attribute,
108}
109
110impl IntoDiagArg for ProcMacroKind {
111 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
112 match self {
113 ProcMacroKind::Attribute => "attribute proc macro",
114 ProcMacroKind::Derive => "derive proc macro",
115 ProcMacroKind::FunctionLike => "function-like proc macro",
116 }
117 .into_diag_arg(&mut None)
118 }
119}
120
121struct CheckAttrVisitor<'tcx> {
122 tcx: TyCtxt<'tcx>,
123
124 abort: Cell<bool>,
126}
127
128impl<'tcx> CheckAttrVisitor<'tcx> {
129 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
130 self.tcx.dcx()
131 }
132
133 fn check_attributes(
135 &self,
136 hir_id: HirId,
137 span: Span,
138 target: Target,
139 item: Option<ItemLike<'_>>,
140 ) {
141 let mut seen = FxHashMap::default();
142 let attrs = self.tcx.hir_attrs(hir_id);
143 for attr in attrs {
144 let mut style = None;
145 match attr {
146 Attribute::Parsed(AttributeKind::ProcMacro(_)) => {
147 self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
148 }
149 Attribute::Parsed(AttributeKind::ProcMacroAttribute(_)) => {
150 self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
151 }
152 Attribute::Parsed(AttributeKind::ProcMacroDerive { .. }) => {
153 self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
154 }
155 Attribute::Parsed(
156 AttributeKind::Stability {
157 span: attr_span,
158 stability: Stability { level, feature },
159 }
160 | AttributeKind::RustcConstStability {
161 span: attr_span,
162 stability: PartialConstStability { level, feature, .. },
163 },
164 ) => self.check_stability(*attr_span, span, level, *feature),
165 Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force { .. }, ..)) => {} Attribute::Parsed(AttributeKind::Inline(kind, attr_span)) => {
167 self.check_inline(hir_id, *attr_span, kind, target)
168 }
169 Attribute::Parsed(AttributeKind::LoopMatch(attr_span)) => {
170 self.check_loop_match(hir_id, *attr_span, target)
171 }
172 Attribute::Parsed(AttributeKind::ConstContinue(attr_span)) => {
173 self.check_const_continue(hir_id, *attr_span, target)
174 }
175 Attribute::Parsed(AttributeKind::AllowInternalUnsafe(attr_span) | AttributeKind::AllowInternalUnstable(.., attr_span)) => {
176 self.check_macro_only_attr(*attr_span, span, target, attrs)
177 }
178 Attribute::Parsed(AttributeKind::RustcAllowConstFnUnstable(_, first_span)) => {
179 self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
180 }
181 Attribute::Parsed(AttributeKind::Deprecation {span: attr_span, .. }) => {
182 self.check_deprecated(hir_id, *attr_span, target)
183 }
184 Attribute::Parsed(AttributeKind::TargetFeature{ attr_span, ..}) => {
185 self.check_target_feature(hir_id, *attr_span, target, attrs)
186 }
187 Attribute::Parsed(AttributeKind::RustcObjectLifetimeDefault) => {
188 self.check_object_lifetime_default(hir_id);
189 }
190 &Attribute::Parsed(AttributeKind::RustcPubTransparent(attr_span)) => {
191 self.check_rustc_pub_transparent(attr_span, span, attrs)
192 }
193 Attribute::Parsed(AttributeKind::Align { align, span: attr_span }) => {
194 self.check_align(*align, *attr_span)
195 }
196 Attribute::Parsed(AttributeKind::Naked(..)) => {
197 self.check_naked(hir_id, target)
198 }
199 Attribute::Parsed(AttributeKind::TrackCaller(attr_span)) => {
200 self.check_track_caller(hir_id, *attr_span, attrs, target)
201 }
202 Attribute::Parsed(AttributeKind::NonExhaustive(attr_span)) => {
203 self.check_non_exhaustive(*attr_span, span, target, item)
204 }
205 &Attribute::Parsed(AttributeKind::FfiPure(attr_span)) => {
206 self.check_ffi_pure(attr_span, attrs)
207 }
208 Attribute::Parsed(AttributeKind::MayDangle(attr_span)) => {
209 self.check_may_dangle(hir_id, *attr_span)
210 }
211 &Attribute::Parsed(AttributeKind::CustomMir(dialect, phase, attr_span)) => {
212 self.check_custom_mir(dialect, phase, attr_span)
213 }
214 &Attribute::Parsed(AttributeKind::Sanitize { on_set, off_set, rtsan: _, span: attr_span}) => {
215 self.check_sanitize(attr_span, on_set | off_set, span, target);
216 },
217 Attribute::Parsed(AttributeKind::Link(_, attr_span)) => {
218 self.check_link(hir_id, *attr_span, span, target)
219 },
220 Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
221 self.check_macro_export(hir_id, *span, target)
222 },
223 Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics{attr_span, fn_indexes}) => {
224 self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
225 },
226 Attribute::Parsed(AttributeKind::Doc(attr)) => self.check_doc_attrs(attr, hir_id, target),
227 Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
228 self.check_eii_impl(impls, target)
229 },
230 Attribute::Parsed(AttributeKind::RustcMustImplementOneOf { attr_span, fn_names }) => {
231 self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id,target)
232 },
233 Attribute::Parsed(AttributeKind::DoNotRecommend{attr_span}) => {self.check_do_not_recommend(*attr_span, hir_id, target, item)},
234 Attribute::Parsed(
235 AttributeKind::RustcAllowIncoherentImpl(..)
237 | AttributeKind::AutomaticallyDerived(..)
238 | AttributeKind::CfgAttrTrace
239 | AttributeKind::CfgTrace(..)
240 | AttributeKind::CfiEncoding { .. }
241 | AttributeKind::Cold(..)
242 | AttributeKind::CollapseDebugInfo(..)
243 | AttributeKind::CompilerBuiltins
244 | AttributeKind::Coroutine(..)
245 | AttributeKind::Coverage (..)
246 | AttributeKind::CrateName { .. }
247 | AttributeKind::CrateType(..)
248 | AttributeKind::DebuggerVisualizer(..)
249 | AttributeKind::DocComment {..}
251 | AttributeKind::EiiDeclaration { .. }
252 | AttributeKind::EiiForeignItem
253 | AttributeKind::ExportName { .. }
254 | AttributeKind::ExportStable
255 | AttributeKind::FfiConst(..)
256 | AttributeKind::Fundamental
257 | AttributeKind::Ignore { .. }
258 | AttributeKind::InstructionSet(..)
259 | AttributeKind::Lang(..)
260 | AttributeKind::LinkName { .. }
261 | AttributeKind::LinkOrdinal { .. }
262 | AttributeKind::LinkSection { .. }
263 | AttributeKind::Linkage(..)
264 | AttributeKind::MacroEscape( .. )
265 | AttributeKind::MacroUse { .. }
266 | AttributeKind::Marker(..)
267 | AttributeKind::MoveSizeLimit { .. }
268 | AttributeKind::MustNotSupend { .. }
269 | AttributeKind::MustUse { .. }
270 | AttributeKind::NeedsAllocator
271 | AttributeKind::NeedsPanicRuntime
272 | AttributeKind::NoBuiltins
273 | AttributeKind::NoCore { .. }
274 | AttributeKind::NoImplicitPrelude(..)
275 | AttributeKind::NoLink
276 | AttributeKind::NoMain
277 | AttributeKind::NoMangle(..)
278 | AttributeKind::NoStd { .. }
279 | AttributeKind::Optimize(..)
280 | AttributeKind::PanicRuntime
281 | AttributeKind::PatchableFunctionEntry { .. }
282 | AttributeKind::Path(..)
283 | AttributeKind::PatternComplexityLimit { .. }
284 | AttributeKind::PinV2(..)
285 | AttributeKind::Pointee(..)
286 | AttributeKind::PreludeImport
287 | AttributeKind::ProfilerRuntime
288 | AttributeKind::RecursionLimit { .. }
289 | AttributeKind::ReexportTestHarnessMain(..)
290 | AttributeKind::Repr { .. }
292 | AttributeKind::RustcAbi { .. }
293 | AttributeKind::RustcAllocator
294 | AttributeKind::RustcAllocatorZeroed
295 | AttributeKind::RustcAllocatorZeroedVariant { .. }
296 | AttributeKind::RustcAsPtr(..)
297 | AttributeKind::RustcBodyStability { .. }
298 | AttributeKind::RustcBuiltinMacro { .. }
299 | AttributeKind::RustcCaptureAnalysis
300 | AttributeKind::RustcCguTestAttr(..)
301 | AttributeKind::RustcClean(..)
302 | AttributeKind::RustcCoherenceIsCore(..)
303 | AttributeKind::RustcCoinductive(..)
304 | AttributeKind::RustcConfusables { .. }
305 | AttributeKind::RustcConstStabilityIndirect
306 | AttributeKind::RustcConversionSuggestion
307 | AttributeKind::RustcDeallocator
308 | AttributeKind::RustcDefPath(..)
309 | AttributeKind::RustcDelayedBugFromInsideQuery
310 | AttributeKind::RustcDenyExplicitImpl(..)
311 | AttributeKind::RustcDeprecatedSafe2024 {..}
312 | AttributeKind::RustcDiagnosticItem(..)
313 | AttributeKind::RustcDoNotConstCheck
314 | AttributeKind::RustcDummy
315 | AttributeKind::RustcDumpDefParents
316 | AttributeKind::RustcDumpItemBounds
317 | AttributeKind::RustcDumpPredicates
318 | AttributeKind::RustcDumpUserArgs
319 | AttributeKind::RustcDumpVtable(..)
320 | AttributeKind::RustcDynIncompatibleTrait(..)
321 | AttributeKind::RustcEffectiveVisibility
322 | AttributeKind::RustcEvaluateWhereClauses
323 | AttributeKind::RustcHasIncoherentInherentImpls
324 | AttributeKind::RustcHiddenTypeOfOpaques
325 | AttributeKind::RustcIfThisChanged(..)
326 | AttributeKind::RustcInsignificantDtor
327 | AttributeKind::RustcIntrinsic
328 | AttributeKind::RustcIntrinsicConstStableIndirect
329 | AttributeKind::RustcLayout(..)
330 | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
331 | AttributeKind::RustcLayoutScalarValidRangeStart(..)
332 | AttributeKind::RustcLintOptDenyFieldAccess { .. }
333 | AttributeKind::RustcLintOptTy
334 | AttributeKind::RustcLintQueryInstability
335 | AttributeKind::RustcLintUntrackedQueryInformation
336 | AttributeKind::RustcMacroTransparency(_)
337 | AttributeKind::RustcMain
338 | AttributeKind::RustcMir(_)
339 | AttributeKind::RustcNeverReturnsNullPointer
340 | AttributeKind::RustcNeverTypeOptions {..}
341 | AttributeKind::RustcNoImplicitAutorefs
342 | AttributeKind::RustcNoImplicitBounds
343 | AttributeKind::RustcNoMirInline
344 | AttributeKind::RustcNonConstTraitMethod
345 | AttributeKind::RustcNonnullOptimizationGuaranteed
346 | AttributeKind::RustcNounwind
347 | AttributeKind::RustcObjcClass { .. }
348 | AttributeKind::RustcObjcSelector { .. }
349 | AttributeKind::RustcOffloadKernel
350 | AttributeKind::RustcOutlives
351 | AttributeKind::RustcParenSugar(..)
352 | AttributeKind::RustcPassByValue (..)
353 | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)
354 | AttributeKind::RustcPreserveUbChecks
355 | AttributeKind::RustcProcMacroDecls
356 | AttributeKind::RustcReallocator
357 | AttributeKind::RustcRegions
358 | AttributeKind::RustcReservationImpl(..)
359 | AttributeKind::RustcScalableVector { .. }
360 | AttributeKind::RustcShouldNotBeCalledOnConstItems(..)
361 | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
362 | AttributeKind::RustcSkipDuringMethodDispatch { .. }
363 | AttributeKind::RustcSpecializationTrait(..)
364 | AttributeKind::RustcStdInternalSymbol (..)
365 | AttributeKind::RustcStrictCoherence(..)
366 | AttributeKind::RustcSymbolName(..)
367 | AttributeKind::RustcTestMarker(..)
368 | AttributeKind::RustcThenThisWouldNeed(..)
369 | AttributeKind::RustcTrivialFieldReads
370 | AttributeKind::RustcUnsafeSpecializationMarker(..)
371 | AttributeKind::RustcVariance
372 | AttributeKind::RustcVarianceOfOpaques
373 | AttributeKind::ShouldPanic { .. }
374 | AttributeKind::TestRunner(..)
375 | AttributeKind::ThreadLocal
376 | AttributeKind::TypeLengthLimit { .. }
377 | AttributeKind::UnstableFeatureBound(..)
378 | AttributeKind::Used { .. }
379 | AttributeKind::WindowsSubsystem(..)
380 ) => { }
382 Attribute::Unparsed(attr_item) => {
383 style = Some(attr_item.style);
384 match attr.path().as_slice() {
385 [sym::diagnostic, sym::on_unimplemented, ..] => {
386 self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
387 }
388 [sym::diagnostic, sym::on_const, ..] => {
389 self.check_diagnostic_on_const(attr.span(), hir_id, target, item)
390 }
391 [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => {
392 self.check_autodiff(hir_id, attr, span, target)
393 }
394 [
395 sym::allow
397 | sym::expect
398 | sym::warn
399 | sym::deny
400 | sym::forbid
401 | sym::default_lib_allocator
403 | sym::rustc_inherit_overflow_checks
404 | sym::rustc_on_unimplemented
405 | sym::rustc_doc_primitive
406 | sym::rustc_layout
407 | sym::rustc_autodiff
408 | sym::rustc_capture_analysis
409 | sym::rustc_mir
410 | sym::feature
412 | sym::register_tool, ..
413 ] => {}
414 [name, rest@..] => {
415 match BUILTIN_ATTRIBUTE_MAP.get(name) {
416 Some(_) => {
417 if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
418 continue
422 }
423
424 ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
name))span_bug!(
425 attr.span(),
426 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
427 )
428 }
429 None => (),
430 }
431 }
432 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
433 }
434 }
435 }
436
437 if hir_id != CRATE_HIR_ID {
438 match attr {
439 Attribute::Parsed(_) => { }
440 Attribute::Unparsed(attr) => {
441 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
444 attr.path
445 .segments
446 .first()
447 .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
448 {
449 match attr.style {
450 ast::AttrStyle::Outer => {
451 let attr_span = attr.span;
452 let bang_position = self
453 .tcx
454 .sess
455 .source_map()
456 .span_until_char(attr_span, '[')
457 .shrink_to_hi();
458
459 self.tcx.emit_node_span_lint(
460 UNUSED_ATTRIBUTES,
461 hir_id,
462 attr.span,
463 errors::OuterCrateLevelAttr {
464 suggestion: errors::OuterCrateLevelAttrSuggestion {
465 bang_position,
466 },
467 },
468 )
469 }
470 ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
471 UNUSED_ATTRIBUTES,
472 hir_id,
473 attr.span,
474 errors::InnerCrateLevelAttr,
475 ),
476 }
477 }
478 }
479 }
480 }
481
482 if let Attribute::Unparsed(unparsed_attr) = attr
483 && let Some(BuiltinAttribute { duplicates, .. }) =
484 attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
485 {
486 check_duplicates(
487 self.tcx,
488 unparsed_attr.span,
489 attr,
490 hir_id,
491 *duplicates,
492 &mut seen,
493 );
494 }
495
496 self.check_unused_attribute(hir_id, attr, style)
497 }
498
499 self.check_repr(attrs, span, target, item, hir_id);
500 self.check_rustc_force_inline(hir_id, attrs, target);
501 self.check_mix_no_mangle_export(hir_id, attrs);
502 }
503
504 fn check_rustc_must_implement_one_of(
505 &self,
506 attr_span: Span,
507 list: &ThinVec<Ident>,
508 hir_id: HirId,
509 target: Target,
510 ) {
511 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
514 return;
515 }
516
517 let def_id = hir_id.owner.def_id;
518
519 let items = self.tcx.associated_items(def_id);
520 for ident in list {
523 let item = items
524 .filter_by_name_unhygienic(ident.name)
525 .find(|item| item.ident(self.tcx) == *ident);
526
527 match item {
528 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
529 if !item.defaultness(self.tcx).has_value() {
530 self.tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation {
531 span: self.tcx.def_span(item.def_id),
532 note_span: attr_span,
533 });
534 }
535 }
536 Some(item) => {
537 self.dcx().emit_err(errors::MustImplementNotFunction {
538 span: self.tcx.def_span(item.def_id),
539 span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span },
540 note: errors::MustImplementNotFunctionNote {},
541 });
542 }
543 None => {
544 self.dcx().emit_err(errors::FunctionNotFoundInTrait { span: ident.span });
545 }
546 }
547 }
548 let mut set: UnordMap<Symbol, Span> = Default::default();
551
552 for ident in &*list {
553 if let Some(dup) = set.insert(ident.name, ident.span) {
554 self.tcx
555 .dcx()
556 .emit_err(errors::FunctionNamesDuplicated { spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[dup, ident.span]))vec![dup, ident.span] });
557 }
558 }
559 }
560
561 fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
562 for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
563 match target {
564 Target::Fn => {}
565 _ => {
566 self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
567 }
568 }
569
570 if let EiiImplResolution::Macro(eii_macro) = resolution
571 && {
{
'done:
{
for i in self.tcx.get_all_attrs(*eii_macro) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::EiiDeclaration(EiiDecl {
impl_unsafe, .. })) if *impl_unsafe => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
572 && !impl_marked_unsafe
573 {
574 self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
575 span: *span,
576 name: self.tcx.item_name(*eii_macro),
577 suggestion: errors::EiiImplRequiresUnsafeSuggestion {
578 left: inner_span.shrink_to_lo(),
579 right: inner_span.shrink_to_hi(),
580 },
581 });
582 }
583 }
584 }
585
586 fn check_do_not_recommend(
588 &self,
589 attr_span: Span,
590 hir_id: HirId,
591 target: Target,
592 item: Option<ItemLike<'_>>,
593 ) {
594 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Impl { .. } => true,
_ => false,
}matches!(target, Target::Impl { .. })
595 || #[allow(non_exhaustive_omitted_patterns)] match item {
Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl), .. }))
if _impl.of_trait.is_none() => true,
_ => false,
}matches!(
596 item,
597 Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl),.. }))
598 if _impl.of_trait.is_none()
599 )
600 {
601 self.tcx.emit_node_span_lint(
602 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
603 hir_id,
604 attr_span,
605 errors::IncorrectDoNotRecommendLocation,
606 );
607 }
608 }
609
610 fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) {
612 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
613 self.tcx.emit_node_span_lint(
614 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
615 hir_id,
616 attr_span,
617 DiagnosticOnUnimplementedOnlyForTraits,
618 );
619 }
620 }
621
622 fn check_diagnostic_on_const(
624 &self,
625 attr_span: Span,
626 hir_id: HirId,
627 target: Target,
628 item: Option<ItemLike<'_>>,
629 ) {
630 if target == (Target::Impl { of_trait: true }) {
631 match item.unwrap() {
632 ItemLike::Item(it) => match it.expect_impl().constness {
633 Constness::Const => {
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 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
640 );
641 return;
642 }
643 Constness::NotConst => return,
644 },
645 ItemLike::ForeignItem => {}
646 }
647 }
648 let item_span = self.tcx.hir_span(hir_id);
649 self.tcx.emit_node_span_lint(
650 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
651 hir_id,
652 attr_span,
653 DiagnosticOnConstOnlyForTraitImpls { item_span },
654 );
655 }
656
657 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
659 match target {
660 Target::Fn
661 | Target::Closure
662 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
663 if let Some(did) = hir_id.as_owner()
665 && self.tcx.def_kind(did).has_codegen_attrs()
666 && kind != &InlineAttr::Never
667 {
668 let attrs = self.tcx.codegen_fn_attrs(did);
669 if attrs.contains_extern_indicator() {
671 self.tcx.emit_node_span_lint(
672 UNUSED_ATTRIBUTES,
673 hir_id,
674 attr_span,
675 errors::InlineIgnoredForExported {},
676 );
677 }
678 }
679 }
680 _ => {}
681 }
682 }
683
684 fn check_sanitize(
687 &self,
688 attr_span: Span,
689 set: SanitizerSet,
690 target_span: Span,
691 target: Target,
692 ) {
693 let mut not_fn_impl_mod = None;
694 let mut no_body = None;
695
696 match target {
697 Target::Fn
698 | Target::Closure
699 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
700 | Target::Impl { .. }
701 | Target::Mod => return,
702 Target::Static
703 if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
706 == SanitizerSet::empty() =>
707 {
708 return;
709 }
710
711 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
714 no_body = Some(target_span);
715 }
716
717 _ => {
718 not_fn_impl_mod = Some(target_span);
719 }
720 }
721
722 self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
723 attr_span,
724 not_fn_impl_mod,
725 no_body,
726 help: (),
727 });
728 }
729
730 fn check_naked(&self, hir_id: HirId, target: Target) {
732 match target {
733 Target::Fn
734 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
735 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
736 let abi = fn_sig.header.abi;
737 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
738 feature_err(
739 &self.tcx.sess,
740 sym::naked_functions_rustic_abi,
741 fn_sig.span,
742 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
abi.as_str()))
})format!(
743 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
744 abi.as_str()
745 ),
746 )
747 .emit();
748 }
749 }
750 _ => {}
751 }
752 }
753
754 fn check_object_lifetime_default(&self, hir_id: HirId) {
756 let tcx = self.tcx;
757 if let Some(owner_id) = hir_id.as_owner()
758 && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
759 {
760 for p in generics.params {
761 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
762 let default = tcx.object_lifetime_default(p.def_id);
763 let repr = match default {
764 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
765 ObjectLifetimeDefault::Static => "'static".to_owned(),
766 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
767 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
768 };
769 tcx.dcx().emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
770 }
771 }
772 }
773
774 fn check_track_caller(
776 &self,
777 hir_id: HirId,
778 attr_span: Span,
779 attrs: &[Attribute],
780 target: Target,
781 ) {
782 match target {
783 Target::Fn => {
784 if let Some(item) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Lang(item, _)) =>
{
break 'done Some(item);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Lang(item, _) => item)
787 && item.is_weak()
788 {
789 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
790
791 self.dcx().emit_err(errors::LangItemWithTrackCaller {
792 attr_span,
793 name: item.name(),
794 sig_span: sig.span,
795 });
796 }
797
798 if let Some(impls) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::EiiImpls(impls))
=> {
break 'done Some(impls);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
799 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
800 for i in impls {
801 let name = match i.resolution {
802 EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
803 EiiImplResolution::Known(decl) => decl.name.name,
804 EiiImplResolution::Error(_eg) => continue,
805 };
806 self.dcx().emit_err(errors::EiiWithTrackCaller {
807 attr_span,
808 name,
809 sig_span: sig.span,
810 });
811 }
812 }
813 }
814 _ => {}
815 }
816 }
817
818 fn check_non_exhaustive(
820 &self,
821 attr_span: Span,
822 span: Span,
823 target: Target,
824 item: Option<ItemLike<'_>>,
825 ) {
826 match target {
827 Target::Struct => {
828 if let Some(ItemLike::Item(hir::Item {
829 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
830 ..
831 })) = item
832 && !fields.is_empty()
833 && fields.iter().any(|f| f.default.is_some())
834 {
835 self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
836 attr_span,
837 defn_span: span,
838 });
839 }
840 }
841 _ => {}
842 }
843 }
844
845 fn check_target_feature(
847 &self,
848 hir_id: HirId,
849 attr_span: Span,
850 target: Target,
851 attrs: &[Attribute],
852 ) {
853 match target {
854 Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
855 | Target::Fn => {
856 if let Some(lang_item) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Lang(lang, _)) =>
{
break 'done Some(lang);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Lang(lang, _) => lang)
858 && !self.tcx.sess.target.is_like_wasm
861 && !self.tcx.sess.opts.actually_rustdoc
862 {
863 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
864
865 self.dcx().emit_err(errors::LangItemWithTargetFeature {
866 attr_span,
867 name: lang_item.name(),
868 sig_span: sig.span,
869 });
870 }
871 }
872 _ => {}
873 }
874 }
875
876 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
877 if let Some(location) = match target {
878 Target::AssocTy => {
879 if let DefKind::Impl { .. } =
880 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
881 {
882 Some("type alias in implementation block")
883 } else {
884 None
885 }
886 }
887 Target::AssocConst => {
888 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
889 let containing_item = self.tcx.hir_expect_item(parent_def_id);
890 let err = "associated constant in trait implementation block";
892 match containing_item.kind {
893 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
894 _ => None,
895 }
896 }
897 Target::Param => return,
899 Target::Expression
900 | Target::Statement
901 | Target::Arm
902 | Target::ForeignMod
903 | Target::Closure
904 | Target::Impl { .. }
905 | Target::WherePredicate => Some(target.name()),
906 Target::ExternCrate
907 | Target::Use
908 | Target::Static
909 | Target::Const
910 | Target::Fn
911 | Target::Mod
912 | Target::GlobalAsm
913 | Target::TyAlias
914 | Target::Enum
915 | Target::Variant
916 | Target::Struct
917 | Target::Field
918 | Target::Union
919 | Target::Trait
920 | Target::TraitAlias
921 | Target::Method(..)
922 | Target::ForeignFn
923 | Target::ForeignStatic
924 | Target::ForeignTy
925 | Target::GenericParam { .. }
926 | Target::MacroDef
927 | Target::PatField
928 | Target::ExprField
929 | Target::Crate
930 | Target::MacroCall
931 | Target::Delegation { .. } => None,
932 } {
933 self.tcx.dcx().emit_err(errors::DocAliasBadLocation { span, location });
934 return;
935 }
936 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
937 self.tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str: alias });
938 return;
939 }
940 }
941
942 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
943 let item_kind = match self.tcx.hir_node(hir_id) {
944 hir::Node::Item(item) => Some(&item.kind),
945 _ => None,
946 };
947 match item_kind {
948 Some(ItemKind::Impl(i)) => {
949 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
950 || if let Some(&[hir::GenericArg::Type(ty)]) = i
951 .of_trait
952 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
953 .map(|last_segment| last_segment.args().args)
954 {
955 #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
956 } else {
957 false
958 };
959 if !is_valid {
960 self.dcx().emit_err(errors::DocFakeVariadicNotValid { span });
961 }
962 }
963 _ => {
964 self.dcx().emit_err(errors::DocKeywordOnlyImpl { span });
965 }
966 }
967 }
968
969 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
970 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
971 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
972 return;
973 };
974 match item.kind {
975 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
976 if generics.params.len() != 0 => {}
977 ItemKind::Trait(_, _, _, _, generics, _, items)
978 if generics.params.len() != 0
979 || items.iter().any(|item| {
980 #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(item.owner_id)
{
DefKind::AssocTy => true,
_ => false,
}matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy)
981 }) => {}
982 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
983 _ => {
984 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
985 }
986 }
987 }
988
989 fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
999 let span = match inline {
1000 [] => return,
1001 [(_, span)] => *span,
1002 [(inline, span), rest @ ..] => {
1003 for (inline2, span2) in rest {
1004 if inline2 != inline {
1005 let mut spans = MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[*span, *span2]))vec![*span, *span2]);
1006 spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))msg!("this attribute..."));
1007 spans.push_span_label(
1008 *span2,
1009 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))msg!("{\".\"}..conflicts with this attribute"),
1010 );
1011 self.dcx().emit_err(errors::DocInlineConflict { spans });
1012 return;
1013 }
1014 }
1015 *span
1016 }
1017 };
1018
1019 match target {
1020 Target::Use | Target::ExternCrate => {}
1021 _ => {
1022 self.tcx.emit_node_span_lint(
1023 INVALID_DOC_ATTRIBUTES,
1024 hir_id,
1025 span,
1026 errors::DocInlineOnlyUse {
1027 attr_span: span,
1028 item_span: self.tcx.hir_span(hir_id),
1029 },
1030 );
1031 }
1032 }
1033 }
1034
1035 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
1036 if target != Target::ExternCrate {
1037 self.tcx.emit_node_span_lint(
1038 INVALID_DOC_ATTRIBUTES,
1039 hir_id,
1040 span,
1041 errors::DocMaskedOnlyExternCrate {
1042 attr_span: span,
1043 item_span: self.tcx.hir_span(hir_id),
1044 },
1045 );
1046 return;
1047 }
1048
1049 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1050 self.tcx.emit_node_span_lint(
1051 INVALID_DOC_ATTRIBUTES,
1052 hir_id,
1053 span,
1054 errors::DocMaskedNotExternCrateSelf {
1055 attr_span: span,
1056 item_span: self.tcx.hir_span(hir_id),
1057 },
1058 );
1059 }
1060 }
1061
1062 fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1063 let item_kind = match self.tcx.hir_node(hir_id) {
1064 hir::Node::Item(item) => Some(&item.kind),
1065 _ => None,
1066 };
1067 match item_kind {
1068 Some(ItemKind::Mod(_, module)) => {
1069 if !module.item_ids.is_empty() {
1070 self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod { span, attr_name });
1071 return;
1072 }
1073 }
1074 _ => {
1075 self.dcx().emit_err(errors::DocKeywordAttributeNotMod { span, attr_name });
1076 return;
1077 }
1078 }
1079 }
1080
1081 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1088 let DocAttribute {
1089 aliases,
1090 hidden: _,
1093 inline,
1094 cfg: _,
1096 auto_cfg: _,
1098 auto_cfg_change: _,
1100 fake_variadic,
1101 keyword,
1102 masked,
1103 notable_trait: _,
1105 search_unbox,
1106 html_favicon_url: _,
1108 html_logo_url: _,
1110 html_playground_url: _,
1112 html_root_url: _,
1114 html_no_source: _,
1116 issue_tracker_base_url: _,
1118 rust_logo,
1119 test_attrs: _,
1121 no_crate_inject: _,
1123 attribute,
1124 } = attr;
1125
1126 for (alias, span) in aliases {
1127 self.check_doc_alias_value(*span, hir_id, target, *alias);
1128 }
1129
1130 if let Some((_, span)) = keyword {
1131 self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1132 }
1133 if let Some((_, span)) = attribute {
1134 self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1135 }
1136
1137 if let Some(span) = fake_variadic {
1138 self.check_doc_fake_variadic(*span, hir_id);
1139 }
1140
1141 if let Some(span) = search_unbox {
1142 self.check_doc_search_unbox(*span, hir_id);
1143 }
1144
1145 self.check_doc_inline(hir_id, target, inline);
1146
1147 if let Some(span) = rust_logo
1148 && !self.tcx.features().rustdoc_internals()
1149 {
1150 feature_err(
1151 &self.tcx.sess,
1152 sym::rustdoc_internals,
1153 *span,
1154 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `#[doc(rust_logo)]` attribute is used for Rust branding"))msg!("the `#[doc(rust_logo)]` attribute is used for Rust branding"),
1155 )
1156 .emit();
1157 }
1158
1159 if let Some(span) = masked {
1160 self.check_doc_masked(*span, hir_id, target);
1161 }
1162 }
1163
1164 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1165 if {
{
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::FfiConst(_)) =>
{
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, AttributeKind::FfiConst(_)) {
1166 self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1168 }
1169 }
1170
1171 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1173 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1174 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
} => true,
_ => false,
}matches!(
1175 param.kind,
1176 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1177 )
1178 && #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1179 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1180 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1181 && let hir::ItemKind::Impl(impl_) = item.kind
1182 && let Some(of_trait) = impl_.of_trait
1183 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1184 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1185 {
1186 return;
1187 }
1188
1189 self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1190 }
1191
1192 fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1194 if target == Target::ForeignMod
1195 && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1196 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1197 && !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::Rust => true,
_ => false,
}matches!(abi, ExternAbi::Rust)
1198 {
1199 return;
1200 }
1201
1202 self.tcx.emit_node_span_lint(
1203 UNUSED_ATTRIBUTES,
1204 hir_id,
1205 attr_span,
1206 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1207 );
1208 }
1209
1210 fn check_rustc_legacy_const_generics(
1212 &self,
1213 item: Option<ItemLike<'_>>,
1214 attr_span: Span,
1215 index_list: &ThinVec<(usize, Span)>,
1216 ) {
1217 let Some(ItemLike::Item(Item {
1218 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1219 ..
1220 })) = item
1221 else {
1222 return;
1224 };
1225
1226 for param in generics.params {
1227 match param.kind {
1228 hir::GenericParamKind::Const { .. } => {}
1229 _ => {
1230 self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1231 attr_span,
1232 param_span: param.span,
1233 });
1234 return;
1235 }
1236 }
1237 }
1238
1239 if index_list.len() != generics.params.len() {
1240 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1241 attr_span,
1242 generics_span: generics.span,
1243 });
1244 return;
1245 }
1246
1247 let arg_count = decl.inputs.len() + generics.params.len();
1248 for (index, span) in index_list {
1249 if *index >= arg_count {
1250 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1251 span: *span,
1252 arg_count,
1253 });
1254 }
1255 }
1256 }
1257
1258 fn check_repr(
1260 &self,
1261 attrs: &[Attribute],
1262 span: Span,
1263 target: Target,
1264 item: Option<ItemLike<'_>>,
1265 hir_id: HirId,
1266 ) {
1267 let (reprs, first_attr_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Repr {
reprs, first_span }) => {
break 'done Some((reprs.as_slice(), Some(*first_span)));
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))).unwrap_or((&[], None));
1273
1274 let mut int_reprs = 0;
1275 let mut is_explicit_rust = false;
1276 let mut is_c = false;
1277 let mut is_simd = false;
1278 let mut is_transparent = false;
1279
1280 for (repr, repr_span) in reprs {
1281 match repr {
1282 ReprAttr::ReprRust => {
1283 is_explicit_rust = true;
1284 match target {
1285 Target::Struct | Target::Union | Target::Enum => continue,
1286 _ => {
1287 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1288 hint_span: *repr_span,
1289 span,
1290 });
1291 }
1292 }
1293 }
1294 ReprAttr::ReprC => {
1295 is_c = true;
1296 match target {
1297 Target::Struct | Target::Union | Target::Enum => continue,
1298 _ => {
1299 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1300 hint_span: *repr_span,
1301 span,
1302 });
1303 }
1304 }
1305 }
1306 ReprAttr::ReprAlign(align) => {
1307 match target {
1308 Target::Struct | Target::Union | Target::Enum => {}
1309 Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1310 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1311 span: *repr_span,
1312 item: target.plural_name(),
1313 });
1314 }
1315 Target::Static if self.tcx.features().static_align() => {
1316 self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1317 span: *repr_span,
1318 item: target.plural_name(),
1319 });
1320 }
1321 _ => {
1322 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1323 hint_span: *repr_span,
1324 span,
1325 });
1326 }
1327 }
1328
1329 self.check_align(*align, *repr_span);
1330 }
1331 ReprAttr::ReprPacked(_) => {
1332 if target != Target::Struct && target != Target::Union {
1333 self.dcx().emit_err(errors::AttrApplication::StructUnion {
1334 hint_span: *repr_span,
1335 span,
1336 });
1337 } else {
1338 continue;
1339 }
1340 }
1341 ReprAttr::ReprSimd => {
1342 is_simd = true;
1343 if target != Target::Struct {
1344 self.dcx().emit_err(errors::AttrApplication::Struct {
1345 hint_span: *repr_span,
1346 span,
1347 });
1348 } else {
1349 continue;
1350 }
1351 }
1352 ReprAttr::ReprTransparent => {
1353 is_transparent = true;
1354 match target {
1355 Target::Struct | Target::Union | Target::Enum => continue,
1356 _ => {
1357 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1358 hint_span: *repr_span,
1359 span,
1360 });
1361 }
1362 }
1363 }
1364 ReprAttr::ReprInt(_) => {
1365 int_reprs += 1;
1366 if target != Target::Enum {
1367 self.dcx().emit_err(errors::AttrApplication::Enum {
1368 hint_span: *repr_span,
1369 span,
1370 });
1371 } else {
1372 continue;
1373 }
1374 }
1375 };
1376 }
1377
1378 if let Some(first_attr_span) = first_attr_span
1380 && reprs.is_empty()
1381 && item.is_some()
1382 {
1383 match target {
1384 Target::Struct | Target::Union | Target::Enum => {}
1385 Target::Fn | Target::Method(_) => {
1386 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1387 span: first_attr_span,
1388 item: target.plural_name(),
1389 });
1390 }
1391 _ => {
1392 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1393 hint_span: first_attr_span,
1394 span,
1395 });
1396 }
1397 }
1398 return;
1399 }
1400
1401 let hint_spans = reprs.iter().map(|(_, span)| *span);
1404
1405 if is_transparent && reprs.len() > 1 {
1407 let hint_spans = hint_spans.clone().collect();
1408 self.dcx().emit_err(errors::TransparentIncompatible {
1409 hint_spans,
1410 target: target.to_string(),
1411 });
1412 }
1413 if is_transparent
1416 && let Some(&pass_indirectly_span) =
1417 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcPassIndirectlyInNonRusticAbis(span))
=> {
break 'done Some(span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::RustcPassIndirectlyInNonRusticAbis(span) => span)
1418 {
1419 self.dcx().emit_err(errors::TransparentIncompatible {
1420 hint_spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span, pass_indirectly_span]))vec![span, pass_indirectly_span],
1421 target: target.to_string(),
1422 });
1423 }
1424 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1425 let hint_spans = hint_spans.clone().collect();
1426 self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1427 }
1428 if (int_reprs > 1)
1430 || (is_simd && is_c)
1431 || (int_reprs == 1
1432 && is_c
1433 && item.is_some_and(|item| {
1434 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1435 }))
1436 {
1437 self.tcx.emit_node_span_lint(
1438 CONFLICTING_REPR_HINTS,
1439 hir_id,
1440 hint_spans.collect::<Vec<Span>>(),
1441 errors::ReprConflictingLint,
1442 );
1443 }
1444 }
1445
1446 fn check_align(&self, align: Align, span: Span) {
1447 if align.bytes() > 2_u64.pow(29) {
1448 self.dcx().span_delayed_bug(
1450 span,
1451 "alignment greater than 2^29 should be errored on elsewhere",
1452 );
1453 } else {
1454 let max = Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64;
1459 if align.bytes() > max {
1460 self.dcx().emit_err(errors::InvalidReprAlignForTarget { span, size: max });
1461 }
1462 }
1463 }
1464
1465 fn check_macro_only_attr(
1470 &self,
1471 attr_span: Span,
1472 span: Span,
1473 target: Target,
1474 attrs: &[Attribute],
1475 ) {
1476 match target {
1477 Target::Fn => {
1478 for attr in attrs {
1479 if attr.is_proc_macro_attr() {
1480 return;
1482 }
1483 }
1484 self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1485 }
1486 _ => {}
1487 }
1488 }
1489
1490 fn check_rustc_allow_const_fn_unstable(
1493 &self,
1494 hir_id: HirId,
1495 attr_span: Span,
1496 span: Span,
1497 target: Target,
1498 ) {
1499 match target {
1500 Target::Fn | Target::Method(_) => {
1501 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1502 self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1503 }
1504 }
1505 _ => {}
1506 }
1507 }
1508
1509 fn check_stability(
1510 &self,
1511 attr_span: Span,
1512 item_span: Span,
1513 level: &StabilityLevel,
1514 feature: Symbol,
1515 ) {
1516 if level.is_unstable()
1519 && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1520 {
1521 self.tcx
1522 .dcx()
1523 .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1524 }
1525 }
1526
1527 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1528 match target {
1529 Target::AssocConst | Target::Method(..) | Target::AssocTy
1530 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1531 == DefKind::Impl { of_trait: true } =>
1532 {
1533 self.tcx.emit_node_span_lint(
1534 UNUSED_ATTRIBUTES,
1535 hir_id,
1536 attr_span,
1537 errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1538 );
1539 }
1540 _ => {}
1541 }
1542 }
1543
1544 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1545 if target != Target::MacroDef {
1546 return;
1547 }
1548
1549 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1551 let is_decl_macro = !macro_definition.macro_rules;
1552
1553 if is_decl_macro {
1554 self.tcx.emit_node_span_lint(
1555 UNUSED_ATTRIBUTES,
1556 hir_id,
1557 attr_span,
1558 errors::MacroExport::OnDeclMacro,
1559 );
1560 }
1561 }
1562
1563 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1564 let note = if attr.has_any_name(&[
1567 sym::allow,
1568 sym::expect,
1569 sym::warn,
1570 sym::deny,
1571 sym::forbid,
1572 sym::feature,
1573 ]) && attr.meta_item_list().is_some_and(|list| list.is_empty())
1574 {
1575 errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1576 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1577 && let Some(meta) = attr.meta_item_list()
1578 && let [meta] = meta.as_slice()
1579 && let Some(item) = meta.meta_item()
1580 && let MetaItemKind::NameValue(_) = &item.kind
1581 && item.path == sym::reason
1582 {
1583 errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1584 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1585 && let Some(meta) = attr.meta_item_list()
1586 && meta.iter().any(|meta| {
1587 meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
1588 })
1589 {
1590 if hir_id != CRATE_HIR_ID {
1591 match style {
1592 Some(ast::AttrStyle::Outer) => {
1593 let attr_span = attr.span();
1594 let bang_position = self
1595 .tcx
1596 .sess
1597 .source_map()
1598 .span_until_char(attr_span, '[')
1599 .shrink_to_hi();
1600
1601 self.tcx.emit_node_span_lint(
1602 UNUSED_ATTRIBUTES,
1603 hir_id,
1604 attr_span,
1605 errors::OuterCrateLevelAttr {
1606 suggestion: errors::OuterCrateLevelAttrSuggestion { bang_position },
1607 },
1608 )
1609 }
1610 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1611 UNUSED_ATTRIBUTES,
1612 hir_id,
1613 attr.span(),
1614 errors::InnerCrateLevelAttr,
1615 ),
1616 };
1617 return;
1618 } else {
1619 let never_needs_link = self
1620 .tcx
1621 .crate_types()
1622 .iter()
1623 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1624 if never_needs_link {
1625 errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1626 } else {
1627 return;
1628 }
1629 }
1630 } else if attr.has_name(sym::default_method_body_is_const) {
1631 errors::UnusedNote::DefaultMethodBodyConst
1632 } else {
1633 return;
1634 };
1635
1636 self.tcx.emit_node_span_lint(
1637 UNUSED_ATTRIBUTES,
1638 hir_id,
1639 attr.span(),
1640 errors::Unused { attr_span: attr.span(), note },
1641 );
1642 }
1643
1644 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1648 if target != Target::Fn {
1649 return;
1650 }
1651
1652 let tcx = self.tcx;
1653 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1654 return;
1655 };
1656 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1657 return;
1658 };
1659
1660 let def_id = hir_id.expect_owner().def_id;
1661 let param_env = ty::ParamEnv::empty();
1662
1663 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1664 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1665
1666 let span = tcx.def_span(def_id);
1667 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1668 let sig = tcx.liberate_late_bound_regions(
1669 def_id.to_def_id(),
1670 tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
1671 );
1672
1673 let mut cause = ObligationCause::misc(span, def_id);
1674 let sig = ocx.normalize(&cause, param_env, sig);
1675
1676 let errors = ocx.try_evaluate_obligations();
1678 if !errors.is_empty() {
1679 return;
1680 }
1681
1682 let expected_sig = tcx.mk_fn_sig(
1683 std::iter::repeat_n(
1684 token_stream,
1685 match kind {
1686 ProcMacroKind::Attribute => 2,
1687 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1688 },
1689 ),
1690 token_stream,
1691 false,
1692 Safety::Safe,
1693 ExternAbi::Rust,
1694 );
1695
1696 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1697 let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
1698
1699 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1700 if let Some(hir_sig) = hir_sig {
1701 match terr {
1702 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1703 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1704 diag.span(ty.span);
1705 cause.span = ty.span;
1706 } else if idx == hir_sig.decl.inputs.len() {
1707 let span = hir_sig.decl.output.span();
1708 diag.span(span);
1709 cause.span = span;
1710 }
1711 }
1712 TypeError::ArgCount => {
1713 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1714 diag.span(ty.span);
1715 cause.span = ty.span;
1716 }
1717 }
1718 TypeError::SafetyMismatch(_) => {
1719 }
1721 TypeError::AbiMismatch(_) => {
1722 }
1724 TypeError::VariadicMismatch(_) => {
1725 }
1727 _ => {}
1728 }
1729 }
1730
1731 infcx.err_ctxt().note_type_err(
1732 &mut diag,
1733 &cause,
1734 None,
1735 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1736 expected: ty::Binder::dummy(expected_sig),
1737 found: ty::Binder::dummy(sig),
1738 }))),
1739 terr,
1740 false,
1741 None,
1742 );
1743 diag.emit();
1744 self.abort.set(true);
1745 }
1746
1747 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1748 if !errors.is_empty() {
1749 infcx.err_ctxt().report_fulfillment_errors(errors);
1750 self.abort.set(true);
1751 }
1752 }
1753
1754 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1755 if !{
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Repr { reprs, ..
}) => {
break 'done
Some(reprs.iter().any(|(r, _)|
r == &ReprAttr::ReprTransparent));
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent))
1756 .unwrap_or(false)
1757 {
1758 self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
1759 }
1760 }
1761
1762 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1763 if let (Target::Closure, None) = (
1764 target,
1765 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
1766 ) {
1767 let is_coro = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
{
hir::ExprKind::Closure(hir::Closure {
kind: hir::ClosureKind::Coroutine(..) |
hir::ClosureKind::CoroutineClosure(..), .. }) => true,
_ => false,
}matches!(
1768 self.tcx.hir_expect_expr(hir_id).kind,
1769 hir::ExprKind::Closure(hir::Closure {
1770 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1771 ..
1772 })
1773 );
1774 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1775 let parent_span = self.tcx.def_span(parent_did);
1776
1777 if let Some(attr_span) = {
'done:
{
for i in self.tcx.get_all_attrs(parent_did) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
_ => {}
}
}
None
}
}find_attr!(
1778 self.tcx.get_all_attrs(parent_did),
1779 AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1780 ) && is_coro
1781 {
1782 self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
1783 }
1784 }
1785 }
1786
1787 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1788 if let Some(export_name_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::ExportName {
span: export_name_span, .. }) => {
break 'done Some(*export_name_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::ExportName { span: export_name_span, .. } => *export_name_span)
1789 && let Some(no_mangle_span) =
1790 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoMangle(no_mangle_span))
=> {
break 'done Some(*no_mangle_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span)
1791 {
1792 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1793 "#[unsafe(no_mangle)]"
1794 } else {
1795 "#[no_mangle]"
1796 };
1797 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1798 "#[unsafe(export_name)]"
1799 } else {
1800 "#[export_name]"
1801 };
1802
1803 self.tcx.emit_node_span_lint(
1804 lint::builtin::UNUSED_ATTRIBUTES,
1805 hir_id,
1806 no_mangle_span,
1807 errors::MixedExportNameAndNoMangle {
1808 no_mangle_span,
1809 export_name_span,
1810 no_mangle_attr,
1811 export_name_attr,
1812 },
1813 );
1814 }
1815 }
1816
1817 fn check_autodiff(&self, _hir_id: HirId, _attr: &Attribute, span: Span, target: Target) {
1819 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_passes/src/check_attr.rs:1819",
"rustc_passes::check_attr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/check_attr.rs"),
::tracing_core::__macro_support::Option::Some(1819u32),
::tracing_core::__macro_support::Option::Some("rustc_passes::check_attr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_autodiff")
as &dyn Value))])
});
} else { ; }
};debug!("check_autodiff");
1820 match target {
1821 Target::Fn => {}
1822 _ => {
1823 self.dcx().emit_err(errors::AutoDiffAttr { attr_span: span });
1824 self.abort.set(true);
1825 }
1826 }
1827 }
1828
1829 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1830 let node_span = self.tcx.hir_span(hir_id);
1831
1832 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1833 return; }
1835
1836 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
{
hir::ExprKind::Loop(..) => true,
_ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Loop(..)) {
1837 self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
1838 };
1839 }
1840
1841 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1842 let node_span = self.tcx.hir_span(hir_id);
1843
1844 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1845 return; }
1847
1848 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
{
hir::ExprKind::Break(..) => true,
_ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Break(..)) {
1849 self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
1850 };
1851 }
1852
1853 fn check_custom_mir(
1854 &self,
1855 dialect: Option<(MirDialect, Span)>,
1856 phase: Option<(MirPhase, Span)>,
1857 attr_span: Span,
1858 ) {
1859 let Some((dialect, dialect_span)) = dialect else {
1860 if let Some((_, phase_span)) = phase {
1861 self.dcx()
1862 .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
1863 }
1864 return;
1865 };
1866
1867 match dialect {
1868 MirDialect::Analysis => {
1869 if let Some((MirPhase::Optimized, phase_span)) = phase {
1870 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1871 dialect,
1872 phase: MirPhase::Optimized,
1873 attr_span,
1874 dialect_span,
1875 phase_span,
1876 });
1877 }
1878 }
1879
1880 MirDialect::Built => {
1881 if let Some((phase, phase_span)) = phase {
1882 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1883 dialect,
1884 phase,
1885 attr_span,
1886 dialect_span,
1887 phase_span,
1888 });
1889 }
1890 }
1891 MirDialect::Runtime => {}
1892 }
1893 }
1894}
1895
1896impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1897 type NestedFilter = nested_filter::OnlyBodies;
1898
1899 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1900 self.tcx
1901 }
1902
1903 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1904 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1908 let def_id = item.owner_id.to_def_id();
1909 if macro_def.macro_rules
1910 && !{
{
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::MacroExport { ..
}) => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. })
1911 {
1912 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1913 }
1914 }
1915
1916 let target = Target::from_item(item);
1917 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1918 intravisit::walk_item(self, item)
1919 }
1920
1921 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1922 let spans = self
1927 .tcx
1928 .hir_attrs(where_predicate.hir_id)
1929 .iter()
1930 .filter(|attr| {
1932 #[allow(non_exhaustive_omitted_patterns)] match attr {
Attribute::Parsed(AttributeKind::DocComment { .. } |
AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
_ => false,
}matches!(
1933 attr,
1934 Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
1935 | Attribute::Unparsed(_)
1936 )
1937 })
1938 .map(|attr| attr.span())
1939 .collect::<Vec<_>>();
1940 if !spans.is_empty() {
1941 self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
1942 }
1943 self.check_attributes(
1944 where_predicate.hir_id,
1945 where_predicate.span,
1946 Target::WherePredicate,
1947 None,
1948 );
1949 intravisit::walk_where_predicate(self, where_predicate)
1950 }
1951
1952 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1953 let target = Target::from_generic_param(generic_param);
1954 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1955 intravisit::walk_generic_param(self, generic_param)
1956 }
1957
1958 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1959 let target = Target::from_trait_item(trait_item);
1960 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1961 intravisit::walk_trait_item(self, trait_item)
1962 }
1963
1964 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1965 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1966 intravisit::walk_field_def(self, struct_field);
1967 }
1968
1969 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1970 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1971 intravisit::walk_arm(self, arm);
1972 }
1973
1974 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1975 let target = Target::from_foreign_item(f_item);
1976 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1977 intravisit::walk_foreign_item(self, f_item)
1978 }
1979
1980 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1981 let target = target_from_impl_item(self.tcx, impl_item);
1982 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1983 intravisit::walk_impl_item(self, impl_item)
1984 }
1985
1986 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1987 if let hir::StmtKind::Let(l) = stmt.kind {
1989 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1990 }
1991 intravisit::walk_stmt(self, stmt)
1992 }
1993
1994 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1995 let target = match expr.kind {
1996 hir::ExprKind::Closure { .. } => Target::Closure,
1997 _ => Target::Expression,
1998 };
1999
2000 self.check_attributes(expr.hir_id, expr.span, target, None);
2001 intravisit::walk_expr(self, expr)
2002 }
2003
2004 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2005 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2006 intravisit::walk_expr_field(self, field)
2007 }
2008
2009 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2010 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2011 intravisit::walk_variant(self, variant)
2012 }
2013
2014 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2015 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2016
2017 intravisit::walk_param(self, param);
2018 }
2019
2020 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2021 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2022 intravisit::walk_pat_field(self, field);
2023 }
2024}
2025
2026fn is_c_like_enum(item: &Item<'_>) -> bool {
2027 if let ItemKind::Enum(_, _, ref def) = item.kind {
2028 for variant in def.variants {
2029 match variant.data {
2030 hir::VariantData::Unit(..) => { }
2031 _ => return false,
2032 }
2033 }
2034 true
2035 } else {
2036 false
2037 }
2038}
2039
2040fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2043 const ATTRS_TO_CHECK: &[Symbol] =
2047 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2048
2049 for attr in attrs {
2050 let (span, name) = if let Some(a) =
2052 ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2053 {
2054 (attr.span(), *a)
2055 } else if let Attribute::Parsed(AttributeKind::Repr {
2056 reprs: _,
2057 first_span: first_attr_span,
2058 }) = attr
2059 {
2060 (*first_attr_span, sym::repr)
2061 } else {
2062 continue;
2063 };
2064
2065 let item = tcx
2066 .hir_free_items()
2067 .map(|id| tcx.hir_item(id))
2068 .find(|item| !item.span.is_dummy()) .map(|item| errors::ItemFollowingInnerAttr {
2070 span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2071 kind: tcx.def_descr(item.owner_id.to_def_id()),
2072 });
2073 let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2074 span,
2075 sugg_span: tcx
2076 .sess
2077 .source_map()
2078 .span_to_snippet(span)
2079 .ok()
2080 .filter(|src| src.starts_with("#!["))
2081 .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2082 name,
2083 item,
2084 });
2085
2086 if let Attribute::Unparsed(p) = attr {
2087 tcx.dcx().try_steal_replace_and_emit_err(
2088 p.path.span,
2089 StashKey::UndeterminedMacroResolution,
2090 err,
2091 );
2092 } else {
2093 err.emit();
2094 }
2095 }
2096}
2097
2098fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2099 let attrs = tcx.hir_attrs(item.hir_id());
2100
2101 if let Some(attr_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(i, span))
if
!#[allow(non_exhaustive_omitted_patterns)] match i {
InlineAttr::Force { .. } => true,
_ => false,
} => {
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
2102 {
2103 tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2104 }
2105}
2106
2107fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2108 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2109 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2110 if module_def_id.to_local_def_id().is_top_level_module() {
2111 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2112 check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2113 }
2114 if check_attr_visitor.abort.get() {
2115 tcx.dcx().abort_if_errors()
2116 }
2117}
2118
2119pub(crate) fn provide(providers: &mut Providers) {
2120 *providers = Providers { check_mod_attrs, ..*providers };
2121}
2122
2123fn check_duplicates(
2125 tcx: TyCtxt<'_>,
2126 attr_span: Span,
2127 attr: &Attribute,
2128 hir_id: HirId,
2129 duplicates: AttributeDuplicates,
2130 seen: &mut FxHashMap<Symbol, Span>,
2131) {
2132 use AttributeDuplicates::*;
2133 if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
WarnFollowingWordOnly => true,
_ => false,
}matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2134 return;
2135 }
2136 let attr_name = attr.name().unwrap();
2137 match duplicates {
2138 DuplicatesOk => {}
2139 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2140 match seen.entry(attr_name) {
2141 Entry::Occupied(mut entry) => {
2142 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnPreceding => true,
_ => false,
}matches!(duplicates, FutureWarnPreceding) {
2143 let to_remove = entry.insert(attr_span);
2144 (to_remove, attr_span)
2145 } else {
2146 (attr_span, *entry.get())
2147 };
2148 tcx.emit_node_span_lint(
2149 UNUSED_ATTRIBUTES,
2150 hir_id,
2151 this,
2152 errors::UnusedDuplicate {
2153 this,
2154 other,
2155 warning: #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnFollowing | FutureWarnPreceding => true,
_ => false,
}matches!(
2156 duplicates,
2157 FutureWarnFollowing | FutureWarnPreceding
2158 ),
2159 },
2160 );
2161 }
2162 Entry::Vacant(entry) => {
2163 entry.insert(attr_span);
2164 }
2165 }
2166 }
2167 ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2168 Entry::Occupied(mut entry) => {
2169 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
ErrorPreceding => true,
_ => false,
}matches!(duplicates, ErrorPreceding) {
2170 let to_remove = entry.insert(attr_span);
2171 (to_remove, attr_span)
2172 } else {
2173 (attr_span, *entry.get())
2174 };
2175 tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2176 }
2177 Entry::Vacant(entry) => {
2178 entry.insert(attr_span);
2179 }
2180 },
2181 }
2182}
2183
2184fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2185 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2186 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2187 fn_ptr_ty.decl.inputs.len() == 1
2188 } else {
2189 false
2190 }
2191 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2192 && let Some(&[hir::GenericArg::Type(ty)]) =
2193 path.segments.last().map(|last| last.args().args)
2194 {
2195 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2196 } else {
2197 false
2198 })
2199}