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