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