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, 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::errors::feature_err;
40use rustc_session::lint;
41use rustc_session::lint::builtin::{
42 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES,
43 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES,
44};
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::diagnostics;
52
53#[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)]
54#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait implementations")]
55struct DiagnosticOnConstOnlyForNonConstTraitImpls {
56 #[label("this is a const trait implementation")]
57 item_span: Span,
58}
59
60fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
61 match impl_item.kind {
62 hir::ImplItemKind::Const(..) => Target::AssocConst,
63 hir::ImplItemKind::Fn(..) => {
64 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
65 let containing_item = tcx.hir_expect_item(parent_def_id);
66 let containing_impl_is_for_trait = match &containing_item.kind {
67 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
68 _ => ::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"),
69 };
70 if containing_impl_is_for_trait {
71 Target::Method(MethodKind::Trait { body: true })
72 } else {
73 Target::Method(MethodKind::Inherent)
74 }
75 }
76 hir::ImplItemKind::Type(..) => Target::AssocTy,
77 }
78}
79
80#[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)]
81enum ItemLike<'tcx> {
82 Item(&'tcx Item<'tcx>),
83 ForeignItem,
84}
85
86#[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)]
87pub(crate) enum ProcMacroKind {
88 FunctionLike,
89 Derive,
90 Attribute,
91}
92
93impl IntoDiagArg for ProcMacroKind {
94 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
95 match self {
96 ProcMacroKind::Attribute => "attribute proc macro",
97 ProcMacroKind::Derive => "derive proc macro",
98 ProcMacroKind::FunctionLike => "function-like proc macro",
99 }
100 .into_diag_arg(&mut None)
101 }
102}
103
104struct CheckAttrVisitor<'tcx> {
105 tcx: TyCtxt<'tcx>,
106
107 abort: Cell<bool>,
109}
110
111impl<'tcx> CheckAttrVisitor<'tcx> {
112 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
113 self.tcx.dcx()
114 }
115
116 fn check_attributes(
118 &self,
119 hir_id: HirId,
120 span: Span,
121 target: Target,
122 item: Option<ItemLike<'_>>,
123 ) {
124 let attrs = self.tcx.hir_attrs(hir_id);
125 for attr in attrs {
126 match attr {
127 Attribute::Parsed(attr_kind) => {
128 self.check_one_parsed_attribute(hir_id, span, target, item, attrs, attr_kind);
129 self.check_unused_attribute(hir_id, attr, None);
130 }
131 Attribute::Unparsed(attr_item) => {
132 match attr.path().as_slice() {
133 [sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid, ..] => {}
135
136 [name, rest @ ..] => {
137 if let Some(_) = BUILTIN_ATTRIBUTE_MAP.get(name) {
138 if rest.len() > 0
139 && AttributeParser::is_parsed_attribute(slice::from_ref(name))
140 {
141 return;
146 }
147
148 ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
name))span_bug!(
149 attr.span(),
150 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
151 )
152 }
153 }
154
155 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
156 }
157
158 self.check_unused_attribute(hir_id, attr, Some(attr_item.style));
159 }
160 }
161 }
162
163 self.check_repr(attrs, span, target, item, hir_id);
164 self.check_rustc_force_inline(hir_id, attrs, target);
165 self.check_mix_no_mangle_export(hir_id, attrs);
166 self.check_optimize_and_inline(attrs);
167 }
168
169 fn check_one_parsed_attribute(
174 &self,
175 hir_id: HirId,
176 span: Span,
177 target: Target,
178 item: Option<ItemLike<'_>>,
179 attrs: &[Attribute],
180 attr: &AttributeKind,
181 ) {
182 match attr {
183 AttributeKind::ProcMacro => {
184 self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
185 }
186 AttributeKind::ProcMacroAttribute => {
187 self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
188 }
189 AttributeKind::ProcMacroDerive { .. } => {
190 self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
191 }
192 AttributeKind::Inline(InlineAttr::Force { .. }, ..) => {} AttributeKind::Inline(kind, attr_span) => {
194 self.check_inline(hir_id, *attr_span, kind, target)
195 }
196 AttributeKind::LoopMatch(attr_span) => {
197 self.check_loop_match(hir_id, *attr_span, target)
198 }
199 AttributeKind::ConstContinue(attr_span) => {
200 self.check_const_continue(hir_id, *attr_span, target)
201 }
202 AttributeKind::AllowInternalUnsafe(attr_span)
203 | AttributeKind::AllowInternalUnstable(.., attr_span) => {
204 self.check_macro_only_attr(*attr_span, span, target, attrs)
205 }
206 AttributeKind::RustcAllowConstFnUnstable(_, first_span) => {
207 self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
208 }
209 AttributeKind::Deprecated { span: attr_span, .. } => {
210 self.check_deprecated(hir_id, *attr_span, target)
211 }
212 AttributeKind::TargetFeature { attr_span, .. } => {
213 self.check_target_feature(hir_id, *attr_span, target, attrs)
214 }
215 AttributeKind::RustcDumpObjectLifetimeDefaults => {
216 self.check_dump_object_lifetime_defaults(hir_id);
217 }
218 &AttributeKind::RustcPubTransparent(attr_span) => {
219 self.check_rustc_pub_transparent(attr_span, span, attrs)
220 }
221 AttributeKind::RustcAlign { .. } => {}
222 AttributeKind::Naked(..) => self.check_naked(hir_id, target),
223 AttributeKind::TrackCaller(attr_span) => {
224 self.check_track_caller(hir_id, *attr_span, attrs, target)
225 }
226 AttributeKind::NonExhaustive(attr_span) => {
227 self.check_non_exhaustive(*attr_span, span, target, item)
228 }
229 &AttributeKind::FfiPure(attr_span) => self.check_ffi_pure(attr_span, attrs),
230 AttributeKind::MayDangle(attr_span) => self.check_may_dangle(hir_id, *attr_span),
231 AttributeKind::Link(_, attr_span) => self.check_link(hir_id, *attr_span, target),
232 AttributeKind::MacroExport { span, .. } => {
233 self.check_macro_export(hir_id, *span, target)
234 }
235 AttributeKind::RustcLegacyConstGenerics { attr_span, fn_indexes } => {
236 self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
237 }
238 AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target),
239 AttributeKind::EiiImpls(impls) => self.check_eii_impl(impls, target),
240 AttributeKind::RustcMustImplementOneOf { attr_span, fn_names } => {
241 self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id, target)
242 }
243 AttributeKind::OnUnimplemented { directive } => {
244 self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())
245 }
246 AttributeKind::OnConst { span, .. } => {
247 self.check_diagnostic_on_const(*span, hir_id, target, item)
248 }
249 AttributeKind::OnMove { directive } => {
250 self.check_diagnostic_on_move(hir_id, directive.as_deref())
251 }
252 AttributeKind::OnTypeError { directive, .. } => {
253 self.check_diagnostic_on_type_error(hir_id, directive.as_deref())
254 }
255
256 AttributeKind::AutomaticallyDerived => (),
259 AttributeKind::CfgAttrTrace => (),
260 AttributeKind::CfgTrace(..) => (),
261 AttributeKind::CfiEncoding { .. } => (),
262 AttributeKind::Cold => (),
263 AttributeKind::CollapseDebugInfo(..) => (),
264 AttributeKind::CompilerBuiltins => (),
265 AttributeKind::Coroutine => (),
266 AttributeKind::Coverage(..) => (),
267 AttributeKind::CrateName { .. } => (),
268 AttributeKind::CrateType(..) => (),
269 AttributeKind::CustomMir(..) => (),
270 AttributeKind::DebuggerVisualizer(..) => (),
271 AttributeKind::DefaultLibAllocator => (),
272 AttributeKind::DoNotRecommend => (),
273 AttributeKind::DocComment { .. } => (),
275 AttributeKind::EiiDeclaration { .. } => (),
276 AttributeKind::ExportName { .. } => (),
277 AttributeKind::ExportStable => (),
278 AttributeKind::Feature(..) => (),
279 AttributeKind::FfiConst => (),
280 AttributeKind::Fundamental => (),
281 AttributeKind::Ignore { .. } => (),
282 AttributeKind::InstructionSet(..) => (),
283 AttributeKind::Lang(..) => (),
284 AttributeKind::LinkName { .. } => (),
285 AttributeKind::LinkOrdinal { .. } => (),
286 AttributeKind::LinkSection { .. } => (),
287 AttributeKind::Linkage(..) => (),
288 AttributeKind::MacroEscape => (),
289 AttributeKind::MacroUse { .. } => (),
290 AttributeKind::Marker => (),
291 AttributeKind::MoveSizeLimit { .. } => (),
292 AttributeKind::MustNotSupend { .. } => (),
293 AttributeKind::MustUse { .. } => (),
294 AttributeKind::NeedsAllocator => (),
295 AttributeKind::NeedsPanicRuntime => (),
296 AttributeKind::NoBuiltins => (),
297 AttributeKind::NoCore { .. } => (),
298 AttributeKind::NoImplicitPrelude => (),
299 AttributeKind::NoLink => (),
300 AttributeKind::NoMain => (),
301 AttributeKind::NoMangle(..) => (),
302 AttributeKind::NoStd { .. } => (),
303 AttributeKind::OnUnknown { .. } => (),
304 AttributeKind::OnUnmatchedArgs { .. } => (),
305 AttributeKind::Optimize(..) => (),
306 AttributeKind::PanicRuntime => (),
307 AttributeKind::PatchableFunctionEntry { .. } => (),
308 AttributeKind::Path(..) => (),
309 AttributeKind::PatternComplexityLimit { .. } => (),
310 AttributeKind::PinV2(..) => (),
311 AttributeKind::PreludeImport => (),
312 AttributeKind::ProfilerRuntime => (),
313 AttributeKind::RecursionLimit { .. } => (),
314 AttributeKind::ReexportTestHarnessMain(..) => (),
315 AttributeKind::RegisterTool(..) => (),
316 AttributeKind::Repr { .. } => (),
318 AttributeKind::RustcAbi { .. } => (),
319 AttributeKind::RustcAllocator => (),
320 AttributeKind::RustcAllocatorZeroed => (),
321 AttributeKind::RustcAllocatorZeroedVariant { .. } => (),
322 AttributeKind::RustcAllowIncoherentImpl(..) => (),
323 AttributeKind::RustcAsPtr => (),
324 AttributeKind::RustcAutodiff(..) => (),
325 AttributeKind::RustcBodyStability { .. } => (),
326 AttributeKind::RustcBuiltinMacro { .. } => (),
327 AttributeKind::RustcCaptureAnalysis => (),
328 AttributeKind::RustcCguTestAttr(..) => (),
329 AttributeKind::RustcClean(..) => (),
330 AttributeKind::RustcCoherenceIsCore => (),
331 AttributeKind::RustcCoinductive => (),
332 AttributeKind::RustcComptime(_) => (),
333 AttributeKind::RustcConfusables { .. } => (),
334 AttributeKind::RustcConstStability { .. } => (),
335 AttributeKind::RustcConstStableIndirect => (),
336 AttributeKind::RustcConversionSuggestion => (),
337 AttributeKind::RustcDeallocator => (),
338 AttributeKind::RustcDelayedBugFromInsideQuery => (),
339 AttributeKind::RustcDenyExplicitImpl => (),
340 AttributeKind::RustcDeprecatedSafe2024 { .. } => (),
341 AttributeKind::RustcDiagnosticItem(..) => (),
342 AttributeKind::RustcDoNotConstCheck => (),
343 AttributeKind::RustcDocPrimitive(..) => (),
344 AttributeKind::RustcDummy => (),
345 AttributeKind::RustcDumpDefParents => (),
346 AttributeKind::RustcDumpDefPath(..) => (),
347 AttributeKind::RustcDumpHiddenTypeOfOpaques => (),
348 AttributeKind::RustcDumpInferredOutlives => (),
349 AttributeKind::RustcDumpItemBounds => (),
350 AttributeKind::RustcDumpLayout(..) => (),
351 AttributeKind::RustcDumpPredicates => (),
352 AttributeKind::RustcDumpSymbolName(..) => (),
353 AttributeKind::RustcDumpUserArgs => (),
354 AttributeKind::RustcDumpVariances => (),
355 AttributeKind::RustcDumpVariancesOfOpaques => (),
356 AttributeKind::RustcDumpVtable(..) => (),
357 AttributeKind::RustcDynIncompatibleTrait(..) => (),
358 AttributeKind::RustcEffectiveVisibility => (),
359 AttributeKind::RustcEiiForeignItem => (),
360 AttributeKind::RustcEvaluateWhereClauses => (),
361 AttributeKind::RustcHasIncoherentInherentImpls => (),
362 AttributeKind::RustcIfThisChanged(..) => (),
363 AttributeKind::RustcInheritOverflowChecks => (),
364 AttributeKind::RustcInsignificantDtor => (),
365 AttributeKind::RustcIntrinsic => (),
366 AttributeKind::RustcIntrinsicConstStableIndirect => (),
367 AttributeKind::RustcLintOptDenyFieldAccess { .. } => (),
368 AttributeKind::RustcLintOptTy => (),
369 AttributeKind::RustcLintQueryInstability => (),
370 AttributeKind::RustcLintUntrackedQueryInformation => (),
371 AttributeKind::RustcMacroTransparency(_) => (),
372 AttributeKind::RustcMain => (),
373 AttributeKind::RustcMir(_) => (),
374 AttributeKind::RustcMustMatchExhaustively(..) => (),
375 AttributeKind::RustcNeverReturnsNullPtr => (),
376 AttributeKind::RustcNeverTypeOptions { .. } => (),
377 AttributeKind::RustcNoImplicitAutorefs => (),
378 AttributeKind::RustcNoImplicitBounds => (),
379 AttributeKind::RustcNoMirInline => (),
380 AttributeKind::RustcNoWritable => (),
381 AttributeKind::RustcNonConstTraitMethod => (),
382 AttributeKind::RustcNonnullOptimizationGuaranteed => (),
383 AttributeKind::RustcNounwind => (),
384 AttributeKind::RustcObjcClass { .. } => (),
385 AttributeKind::RustcObjcSelector { .. } => (),
386 AttributeKind::RustcOffloadKernel => (),
387 AttributeKind::RustcParenSugar => (),
388 AttributeKind::RustcPassByValue => (),
389 AttributeKind::RustcPassIndirectlyInNonRusticAbis(..) => (),
390 AttributeKind::RustcPreserveUbChecks => (),
391 AttributeKind::RustcProcMacroDecls => (),
392 AttributeKind::RustcReallocator => (),
393 AttributeKind::RustcRegions => (),
394 AttributeKind::RustcReservationImpl(..) => (),
395 AttributeKind::RustcScalableVector { .. } => (),
396 AttributeKind::RustcShouldNotBeCalledOnConstItems => (),
397 AttributeKind::RustcSimdMonomorphizeLaneLimit(..) => (),
398 AttributeKind::RustcSkipDuringMethodDispatch { .. } => (),
399 AttributeKind::RustcSpecializationTrait => (),
400 AttributeKind::RustcStdInternalSymbol => (),
401 AttributeKind::RustcStrictCoherence(..) => (),
402 AttributeKind::RustcTestMarker(..) => (),
403 AttributeKind::RustcThenThisWouldNeed(..) => (),
404 AttributeKind::RustcTrivialFieldReads => (),
405 AttributeKind::RustcUnsafeSpecializationMarker => (),
406 AttributeKind::Sanitize { .. } => {}
407 AttributeKind::ShouldPanic { .. } => (),
408 AttributeKind::Splat(..) => (),
409 AttributeKind::Stability { .. } => (),
410 AttributeKind::TestRunner(..) => (),
411 AttributeKind::ThreadLocal => (),
412 AttributeKind::TypeLengthLimit { .. } => (),
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 { .. } => None,
889 } {
890 self.tcx.dcx().emit_err(diagnostics::DocAliasBadLocation { span, location });
891 return;
892 }
893 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
894 self.tcx.dcx().emit_err(diagnostics::DocAliasNotAnAlias { span, attr_str: alias });
895 return;
896 }
897 }
898
899 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
900 let item_kind = match self.tcx.hir_node(hir_id) {
901 hir::Node::Item(item) => Some(&item.kind),
902 _ => None,
903 };
904 match item_kind {
905 Some(ItemKind::Impl(i)) => {
906 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
907 || if let Some(&[hir::GenericArg::Type(ty)]) = i
908 .of_trait
909 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
910 .map(|last_segment| last_segment.args().args)
911 {
912 #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
913 } else {
914 false
915 };
916 if !is_valid {
917 self.dcx().emit_err(diagnostics::DocFakeVariadicNotValid { span });
918 }
919 }
920 _ => {
921 self.dcx().emit_err(diagnostics::DocKeywordOnlyImpl { span });
922 }
923 }
924 }
925
926 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
927 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
928 self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
929 return;
930 };
931 match item.kind {
932 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
933 if generics.params.len() != 0 => {}
934 ItemKind::Trait { generics, items, .. }
935 if generics.params.len() != 0
936 || items.iter().any(|item| {
937 #[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)
938 }) => {}
939 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
940 _ => {
941 self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
942 }
943 }
944 }
945
946 fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
956 let span = match inline {
957 [] => return,
958 [(_, span)] => *span,
959 [(inline, span), rest @ ..] => {
960 for (inline2, span2) in rest {
961 if inline2 != inline {
962 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]);
963 spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))msg!("this attribute..."));
964 spans.push_span_label(
965 *span2,
966 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))msg!("{\".\"}..conflicts with this attribute"),
967 );
968 self.dcx().emit_err(diagnostics::DocInlineConflict { spans });
969 return;
970 }
971 }
972 *span
973 }
974 };
975
976 match target {
977 Target::Use | Target::ExternCrate => {}
978 _ => {
979 self.tcx.emit_node_span_lint(
980 INVALID_DOC_ATTRIBUTES,
981 hir_id,
982 span,
983 diagnostics::DocInlineOnlyUse {
984 attr_span: span,
985 item_span: self.tcx.hir_span(hir_id),
986 },
987 );
988 }
989 }
990 }
991
992 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
993 if target != Target::ExternCrate {
994 self.tcx.emit_node_span_lint(
995 INVALID_DOC_ATTRIBUTES,
996 hir_id,
997 span,
998 diagnostics::DocMaskedOnlyExternCrate {
999 attr_span: span,
1000 item_span: self.tcx.hir_span(hir_id),
1001 },
1002 );
1003 return;
1004 }
1005
1006 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1007 self.tcx.emit_node_span_lint(
1008 INVALID_DOC_ATTRIBUTES,
1009 hir_id,
1010 span,
1011 diagnostics::DocMaskedNotExternCrateSelf {
1012 attr_span: span,
1013 item_span: self.tcx.hir_span(hir_id),
1014 },
1015 );
1016 }
1017 }
1018
1019 fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1020 let item_kind = match self.tcx.hir_node(hir_id) {
1021 hir::Node::Item(item) => Some(&item.kind),
1022 _ => None,
1023 };
1024 match item_kind {
1025 Some(ItemKind::Mod(_, module)) => {
1026 if !module.item_ids.is_empty() {
1027 self.dcx()
1028 .emit_err(diagnostics::DocKeywordAttributeEmptyMod { span, attr_name });
1029 return;
1030 }
1031 }
1032 _ => {
1033 self.dcx().emit_err(diagnostics::DocKeywordAttributeNotMod { span, attr_name });
1034 return;
1035 }
1036 }
1037 }
1038
1039 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1046 let DocAttribute {
1047 first_span: _,
1048 aliases,
1049 hidden: _,
1052 inline,
1053 cfg: _,
1055 auto_cfg: _,
1057 auto_cfg_change: _,
1059 fake_variadic,
1060 keyword,
1061 masked,
1062 notable_trait: _,
1064 search_unbox,
1065 html_favicon_url: _,
1067 html_logo_url: _,
1069 html_playground_url: _,
1071 html_root_url: _,
1073 html_no_source: _,
1075 issue_tracker_base_url: _,
1077 rust_logo: _,
1079 test_attrs: _,
1081 no_crate_inject: _,
1083 attribute,
1084 } = attr;
1085
1086 for (alias, span) in aliases {
1087 self.check_doc_alias_value(*span, hir_id, target, *alias);
1088 }
1089
1090 if let Some((_, span)) = keyword {
1091 self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1092 }
1093 if let Some((_, span)) = attribute {
1094 self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1095 }
1096
1097 if let Some(span) = fake_variadic {
1098 self.check_doc_fake_variadic(*span, hir_id);
1099 }
1100
1101 if let Some(span) = search_unbox {
1102 self.check_doc_search_unbox(*span, hir_id);
1103 }
1104
1105 self.check_doc_inline(hir_id, target, inline);
1106
1107 if let Some(span) = masked {
1108 self.check_doc_masked(*span, hir_id, target);
1109 }
1110 }
1111
1112 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1113 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) {
1114 self.dcx().emit_err(diagnostics::BothFfiConstAndPure { attr_span });
1116 }
1117 }
1118
1119 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1121 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1122 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
} => true,
_ => false,
}matches!(
1123 param.kind,
1124 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1125 )
1126 && #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1127 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1128 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1129 && let hir::ItemKind::Impl(impl_) = item.kind
1130 && let Some(of_trait) = impl_.of_trait
1131 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1132 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1133 {
1134 return;
1135 }
1136
1137 self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
1138 }
1139
1140 fn check_link(&self, hir_id: HirId, attr_span: Span, target: Target) {
1142 if target != Target::ForeignMod {
1143 return; }
1145
1146 if let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1147 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1148 && !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::Rust => true,
_ => false,
}matches!(abi, ExternAbi::Rust)
1149 {
1150 return;
1151 }
1152
1153 self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr_span, diagnostics::Link);
1154 }
1155
1156 fn check_rustc_legacy_const_generics(
1158 &self,
1159 item: Option<ItemLike<'_>>,
1160 attr_span: Span,
1161 index_list: &ThinVec<(usize, Span)>,
1162 ) {
1163 let Some(ItemLike::Item(Item {
1164 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1165 ..
1166 })) = item
1167 else {
1168 return;
1170 };
1171
1172 for param in generics.params {
1173 match param.kind {
1174 hir::GenericParamKind::Const { .. } => {}
1175 _ => {
1176 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsOnly {
1177 attr_span,
1178 param_span: param.span,
1179 });
1180 return;
1181 }
1182 }
1183 }
1184
1185 if index_list.len() != generics.params.len() {
1186 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndex {
1187 attr_span,
1188 generics_span: generics.span,
1189 });
1190 return;
1191 }
1192
1193 let arg_count = decl.inputs.len() + generics.params.len();
1194 for (index, span) in index_list {
1195 if *index >= arg_count {
1196 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndexExceed {
1197 span: *span,
1198 arg_count,
1199 });
1200 }
1201 }
1202 }
1203
1204 fn check_repr(
1206 &self,
1207 attrs: &[Attribute],
1208 span: Span,
1209 target: Target,
1210 item: Option<ItemLike<'_>>,
1211 hir_id: HirId,
1212 ) {
1213 let (reprs, _first_attr_span) =
1219 {
'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)))
1220 .unwrap_or((&[], None));
1221
1222 let mut int_reprs = 0;
1223 let mut is_explicit_rust = false;
1224 let mut is_c = false;
1225 let mut is_simd = false;
1226 let mut is_transparent = false;
1227
1228 for (repr, _repr_span) in reprs {
1229 match repr {
1230 ReprAttr::ReprRust => {
1231 is_explicit_rust = true;
1232 }
1233 ReprAttr::ReprC => {
1234 is_c = true;
1235 }
1236 ReprAttr::ReprAlign(..) => {}
1237 ReprAttr::ReprPacked(_) => {}
1238 ReprAttr::ReprSimd => {
1239 is_simd = true;
1240 }
1241 ReprAttr::ReprTransparent => {
1242 is_transparent = true;
1243 }
1244 ReprAttr::ReprInt(_) => {
1245 int_reprs += 1;
1246 }
1247 };
1248 }
1249
1250 let hint_spans = reprs.iter().map(|(_, span)| *span);
1253
1254 if is_transparent && reprs.len() > 1 {
1256 let hint_spans = hint_spans.clone().collect();
1257 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1258 hint_spans,
1259 target: target.to_string(),
1260 });
1261 }
1262 if is_transparent
1265 && let Some(&pass_indirectly_span) =
1266 {
'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)
1267 {
1268 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1269 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],
1270 target: target.to_string(),
1271 });
1272 }
1273 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1274 let hint_spans = hint_spans.clone().collect();
1275 self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
1276 }
1277 if (int_reprs > 1)
1279 || (is_simd && is_c)
1280 || (int_reprs == 1
1281 && is_c
1282 && item.is_some_and(|item| {
1283 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1284 }))
1285 {
1286 self.tcx.emit_node_span_lint(
1287 CONFLICTING_REPR_HINTS,
1288 hir_id,
1289 hint_spans.collect::<Vec<Span>>(),
1290 diagnostics::ReprConflictingLint,
1291 );
1292 }
1293 }
1294
1295 fn check_macro_only_attr(
1300 &self,
1301 attr_span: Span,
1302 span: Span,
1303 target: Target,
1304 attrs: &[Attribute],
1305 ) {
1306 match target {
1307 Target::Fn => {
1308 for attr in attrs {
1309 if attr.is_proc_macro_attr() {
1310 return;
1312 }
1313 }
1314 self.tcx.dcx().emit_err(diagnostics::MacroOnlyAttribute { attr_span, span });
1315 }
1316 _ => {}
1317 }
1318 }
1319
1320 fn check_rustc_allow_const_fn_unstable(
1323 &self,
1324 hir_id: HirId,
1325 attr_span: Span,
1326 span: Span,
1327 target: Target,
1328 ) {
1329 match target {
1330 Target::Fn | Target::Method(_) => {
1331 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1332 self.tcx
1333 .dcx()
1334 .emit_err(diagnostics::RustcAllowConstFnUnstable { attr_span, span });
1335 }
1336 }
1337 _ => {}
1338 }
1339 }
1340
1341 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1342 match target {
1343 Target::AssocConst | Target::Method(..) | Target::AssocTy
1344 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1345 == DefKind::Impl { of_trait: true } =>
1346 {
1347 self.tcx.emit_node_span_lint(
1348 UNUSED_ATTRIBUTES,
1349 hir_id,
1350 attr_span,
1351 diagnostics::DeprecatedAnnotationHasNoEffect { span: attr_span },
1352 );
1353 }
1354 _ => {}
1355 }
1356 }
1357
1358 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1359 if target != Target::MacroDef {
1360 return;
1361 }
1362
1363 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1365 let is_decl_macro = !macro_definition.macro_rules;
1366
1367 if is_decl_macro {
1368 self.tcx.emit_node_span_lint(
1369 UNUSED_ATTRIBUTES,
1370 hir_id,
1371 attr_span,
1372 diagnostics::MacroExport::OnDeclMacro,
1373 );
1374 }
1375 }
1376
1377 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1378 let note =
1381 if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1382 && attr.meta_item_list().is_some_and(|list| list.is_empty())
1383 {
1384 diagnostics::UnusedNote::EmptyList { name: attr.name().unwrap() }
1385 } else if attr.has_any_name(&[
1386 sym::allow,
1387 sym::warn,
1388 sym::deny,
1389 sym::forbid,
1390 sym::expect,
1391 ]) && let Some(meta) = attr.meta_item_list()
1392 && let [meta] = meta.as_slice()
1393 && let Some(item) = meta.meta_item()
1394 && let MetaItemKind::NameValue(_) = &item.kind
1395 && item.path == sym::reason
1396 {
1397 diagnostics::UnusedNote::NoLints { name: attr.name().unwrap() }
1398 } else if attr.has_any_name(&[
1399 sym::allow,
1400 sym::warn,
1401 sym::deny,
1402 sym::forbid,
1403 sym::expect,
1404 ]) && let Some(meta) = attr.meta_item_list()
1405 && meta.iter().any(|meta| {
1406 meta.meta_item().map_or(false, |item| {
1407 item.path == sym::linker_messages || item.path == sym::linker_info
1408 })
1409 })
1410 {
1411 if hir_id != CRATE_HIR_ID {
1412 match style {
1413 Some(ast::AttrStyle::Outer) => {
1414 let attr_span = attr.span();
1415 let bang_position = self
1416 .tcx
1417 .sess
1418 .source_map()
1419 .span_until_char(attr_span, '[')
1420 .shrink_to_hi();
1421
1422 self.tcx.emit_node_span_lint(
1423 UNUSED_ATTRIBUTES,
1424 hir_id,
1425 attr_span,
1426 diagnostics::OuterCrateLevelAttr {
1427 suggestion: diagnostics::OuterCrateLevelAttrSuggestion {
1428 bang_position,
1429 },
1430 },
1431 )
1432 }
1433 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1434 UNUSED_ATTRIBUTES,
1435 hir_id,
1436 attr.span(),
1437 diagnostics::InnerCrateLevelAttr,
1438 ),
1439 };
1440 return;
1441 } else {
1442 let never_needs_link = self
1443 .tcx
1444 .crate_types()
1445 .iter()
1446 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1447 if never_needs_link {
1448 diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly
1449 } else {
1450 return;
1451 }
1452 }
1453 } else if hir_id == CRATE_HIR_ID
1454 && attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1455 && let Some(meta) = attr.meta_item_list()
1456 && meta.iter().any(|meta| {
1457 meta.meta_item().is_some_and(|item| item.path == sym::dead_code_pub_in_binary)
1458 })
1459 && !self.tcx.crate_types().contains(&CrateType::Executable)
1460 {
1461 diagnostics::UnusedNote::NoEffectDeadCodePubInBinary
1462 } else if attr.has_name(sym::default_method_body_is_const) {
1463 diagnostics::UnusedNote::DefaultMethodBodyConst
1464 } else {
1465 return;
1466 };
1467
1468 self.tcx.emit_node_span_lint(
1469 UNUSED_ATTRIBUTES,
1470 hir_id,
1471 attr.span(),
1472 diagnostics::Unused { attr_span: attr.span(), note },
1473 );
1474 }
1475
1476 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1480 if target != Target::Fn {
1481 return;
1482 }
1483
1484 let tcx = self.tcx;
1485 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1486 return;
1487 };
1488 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1489 return;
1490 };
1491
1492 let def_id = hir_id.expect_owner().def_id;
1493 let param_env = ty::ParamEnv::empty();
1494
1495 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1496 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1497
1498 let span = tcx.def_span(def_id);
1499 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1500 let sig = tcx.liberate_late_bound_regions(
1501 def_id.to_def_id(),
1502 tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1503 );
1504
1505 let mut cause = ObligationCause::misc(span, def_id);
1506 let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1507
1508 let errors = ocx.try_evaluate_obligations();
1510 if !errors.is_empty() {
1511 return;
1512 }
1513
1514 let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1515 std::iter::repeat_n(
1516 token_stream,
1517 match kind {
1518 ProcMacroKind::Attribute => 2,
1519 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1520 },
1521 ),
1522 token_stream,
1523 );
1524
1525 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1526 let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1527
1528 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1529 if let Some(hir_sig) = hir_sig {
1530 match terr {
1531 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1532 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1533 diag.span(ty.span);
1534 cause.span = ty.span;
1535 } else if idx == hir_sig.decl.inputs.len() {
1536 let span = hir_sig.decl.output.span();
1537 diag.span(span);
1538 cause.span = span;
1539 }
1540 }
1541 TypeError::ArgCount => {
1542 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1543 diag.span(ty.span);
1544 cause.span = ty.span;
1545 }
1546 }
1547 TypeError::SafetyMismatch(_) => {
1548 }
1550 TypeError::AbiMismatch(_) => {
1551 }
1553 TypeError::VariadicMismatch(_) => {
1554 }
1556 _ => {}
1557 }
1558 }
1559
1560 infcx.err_ctxt().note_type_err(
1561 &mut diag,
1562 &cause,
1563 None,
1564 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1565 expected: ty::Binder::dummy(expected_sig),
1566 found: ty::Binder::dummy(sig),
1567 }))),
1568 terr,
1569 false,
1570 None,
1571 );
1572 diag.emit();
1573 self.abort.set(true);
1574 }
1575
1576 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1577 if !errors.is_empty() {
1578 infcx.err_ctxt().report_fulfillment_errors(errors);
1579 self.abort.set(true);
1580 }
1581 }
1582
1583 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1584 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))
1585 .unwrap_or(false)
1586 {
1587 self.dcx().emit_err(diagnostics::RustcPubTransparent { span, attr_span });
1588 }
1589 }
1590
1591 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1592 if let (Target::Closure, None) = (
1593 target,
1594 {
'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),
1595 ) {
1596 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!(
1597 self.tcx.hir_expect_expr(hir_id).kind,
1598 hir::ExprKind::Closure(hir::Closure {
1599 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1600 ..
1601 })
1602 );
1603 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1604 let parent_span = self.tcx.def_span(parent_did);
1605
1606 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!(
1607 self.tcx, parent_did,
1608 Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1609 ) && is_coro
1610 {
1611 self.dcx()
1612 .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1613 }
1614 }
1615 }
1616
1617 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1618 if let Some(export_name_span) =
1619 {
'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)
1620 && let Some(no_mangle_span) =
1621 {
'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)
1622 {
1623 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1624 "#[unsafe(no_mangle)]"
1625 } else {
1626 "#[no_mangle]"
1627 };
1628 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1629 "#[unsafe(export_name)]"
1630 } else {
1631 "#[export_name]"
1632 };
1633
1634 self.tcx.emit_node_span_lint(
1635 lint::builtin::UNUSED_ATTRIBUTES,
1636 hir_id,
1637 no_mangle_span,
1638 diagnostics::MixedExportNameAndNoMangle {
1639 no_mangle_span,
1640 export_name_span,
1641 no_mangle_attr,
1642 export_name_attr,
1643 },
1644 );
1645 }
1646 }
1647
1648 fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1649 if let Some(optimize_span) =
1650 {
'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)
1651 && let Some((inline_attr, inline_span)) =
1652 {
'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))
1653 && inline_attr != &InlineAttr::Never
1654 {
1655 self.dcx()
1656 .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1657 }
1658 }
1659
1660 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1661 let node_span = self.tcx.hir_span(hir_id);
1662
1663 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1664 return; }
1666
1667 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(..)) {
1668 self.dcx().emit_err(diagnostics::LoopMatchAttr { attr_span, node_span });
1669 };
1670 }
1671
1672 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1673 let node_span = self.tcx.hir_span(hir_id);
1674
1675 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1676 return; }
1678
1679 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(..)) {
1680 self.dcx().emit_err(diagnostics::ConstContinueAttr { attr_span, node_span });
1681 };
1682 }
1683}
1684
1685impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1686 type NestedFilter = nested_filter::OnlyBodies;
1687
1688 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1689 self.tcx
1690 }
1691
1692 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1693 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1697 let def_id = item.owner_id.to_def_id();
1698 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 { .. }) {
1699 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1700 }
1701 }
1702
1703 let target = Target::from_item(item);
1704 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1705 intravisit::walk_item(self, item)
1706 }
1707
1708 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1709 self.check_attributes(
1710 where_predicate.hir_id,
1711 where_predicate.span,
1712 Target::WherePredicate,
1713 None,
1714 );
1715 intravisit::walk_where_predicate(self, where_predicate)
1716 }
1717
1718 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1719 let target = Target::from_generic_param(generic_param);
1720 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1721 intravisit::walk_generic_param(self, generic_param)
1722 }
1723
1724 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1725 let target = Target::from_trait_item(trait_item);
1726 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1727 intravisit::walk_trait_item(self, trait_item)
1728 }
1729
1730 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1731 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1732 intravisit::walk_field_def(self, struct_field);
1733 }
1734
1735 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1736 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1737 intravisit::walk_arm(self, arm);
1738 }
1739
1740 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1741 let target = Target::from_foreign_item(f_item);
1742 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1743 intravisit::walk_foreign_item(self, f_item)
1744 }
1745
1746 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1747 let target = target_from_impl_item(self.tcx, impl_item);
1748 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1749 intravisit::walk_impl_item(self, impl_item)
1750 }
1751
1752 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1753 if let hir::StmtKind::Let(l) = stmt.kind {
1755 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1756 }
1757 intravisit::walk_stmt(self, stmt)
1758 }
1759
1760 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1761 let target = match expr.kind {
1762 hir::ExprKind::Closure { .. } => Target::Closure,
1763 _ => Target::Expression,
1764 };
1765
1766 self.check_attributes(expr.hir_id, expr.span, target, None);
1767 intravisit::walk_expr(self, expr)
1768 }
1769
1770 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
1771 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
1772 intravisit::walk_expr_field(self, field)
1773 }
1774
1775 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
1776 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
1777 intravisit::walk_variant(self, variant)
1778 }
1779
1780 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1781 self.check_attributes(param.hir_id, param.span, Target::Param, None);
1782
1783 intravisit::walk_param(self, param);
1784 }
1785
1786 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
1787 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
1788 intravisit::walk_pat_field(self, field);
1789 }
1790}
1791
1792fn is_c_like_enum(item: &Item<'_>) -> bool {
1793 if let ItemKind::Enum(_, _, ref def) = item.kind {
1794 for variant in def.variants {
1795 match variant.data {
1796 hir::VariantData::Unit(..) => { }
1797 _ => return false,
1798 }
1799 }
1800 true
1801 } else {
1802 false
1803 }
1804}
1805
1806fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
1807 let attrs = tcx.hir_attrs(item.hir_id());
1808
1809 if let Some(attr_span) =
1810 {
'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)
1811 {
1812 tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
1813 }
1814}
1815
1816fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1817 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
1818 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
1819 if module_def_id.to_local_def_id().is_top_level_module() {
1820 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
1821 }
1822 if check_attr_visitor.abort.get() {
1823 tcx.dcx().abort_if_errors()
1824 }
1825}
1826
1827pub(crate) fn provide(providers: &mut Providers) {
1828 *providers = Providers { check_mod_attrs, ..*providers };
1829}
1830
1831fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
1832 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
1833 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
1834 fn_ptr_ty.decl.inputs.len() == 1
1835 } else {
1836 false
1837 }
1838 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
1839 && let Some(&[hir::GenericArg::Type(ty)]) =
1840 path.segments.last().map(|last| last.args().args)
1841 {
1842 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
1843 } else {
1844 false
1845 })
1846}