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