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