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