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::Unroll(..) => (),
414 AttributeKind::UnstableFeatureBound(..) => (),
415 AttributeKind::UnstableRemoved(..) => (),
416 AttributeKind::Used { .. } => (),
417 AttributeKind::WindowsSubsystem(..) => (),
418 }
420 }
421
422 fn check_rustc_must_implement_one_of(
423 &self,
424 attr_span: Span,
425 list: &ThinVec<Ident>,
426 hir_id: HirId,
427 target: Target,
428 ) {
429 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
432 return;
433 }
434
435 let def_id = hir_id.owner.def_id;
436
437 let items = self.tcx.associated_items(def_id);
438 for ident in list {
441 let item = items
442 .filter_by_name_unhygienic(ident.name)
443 .find(|item| item.ident(self.tcx) == *ident);
444
445 match item {
446 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
447 if !item.defaultness(self.tcx).has_value() {
448 self.tcx.dcx().emit_err(
449 diagnostics::FunctionNotHaveDefaultImplementation {
450 span: self.tcx.def_span(item.def_id),
451 note_span: attr_span,
452 },
453 );
454 }
455 }
456 Some(item) => {
457 self.dcx().emit_err(diagnostics::MustImplementNotFunction {
458 span: self.tcx.def_span(item.def_id),
459 span_note: diagnostics::MustImplementNotFunctionSpanNote {
460 span: attr_span,
461 },
462 note: diagnostics::MustImplementNotFunctionNote {},
463 });
464 }
465 None => {
466 self.dcx().emit_err(diagnostics::FunctionNotFoundInTrait { span: ident.span });
467 }
468 }
469 }
470 let mut set: UnordMap<Symbol, Span> = Default::default();
473
474 for ident in &*list {
475 if let Some(dup) = set.insert(ident.name, ident.span) {
476 self.tcx.dcx().emit_err(diagnostics::FunctionNamesDuplicated {
477 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],
478 });
479 }
480 }
481 }
482
483 fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
484 for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
485 match target {
486 Target::Fn | Target::Static => {}
487 _ => {
488 self.dcx().emit_err(diagnostics::EiiImplTarget { span: *span });
489 }
490 }
491
492 if let EiiImplResolution::Macro(eii_macro) = resolution
493 && {
{
'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)
494 && !impl_marked_unsafe
495 {
496 self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe {
497 span: *span,
498 name: self.tcx.item_name(*eii_macro),
499 suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion {
500 left: inner_span.shrink_to_lo(),
501 right: inner_span.shrink_to_hi(),
502 },
503 });
504 }
505 }
506 }
507
508 fn check_diagnostic_on_unimplemented(&self, hir_id: HirId, directive: Option<&Directive>) {
510 if let Some(directive) = directive {
511 if let Node::Item(Item {
512 kind: ItemKind::Trait { ident: trait_name, generics, .. },
513 ..
514 }) = self.tcx.hir_node(hir_id)
515 {
516 directive.visit_params(&mut |argument_name, span| {
517 let has_generic = generics.params.iter().any(|p| {
518 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
519 && let ParamName::Plain(name) = p.name
520 && name.name == argument_name
521 {
522 true
523 } else {
524 false
525 }
526 });
527 if !has_generic {
528 self.tcx.emit_node_span_lint(
529 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
530 hir_id,
531 span,
532 diagnostics::UnknownFormatParameterForOnUnimplementedAttr {
533 argument_name,
534 trait_name: *trait_name,
535 help: !directive.is_rustc_attr,
536 },
537 )
538 }
539 })
540 }
541 }
542 }
543
544 fn check_diagnostic_on_const(
546 &self,
547 attr_span: Span,
548 hir_id: HirId,
549 target: Target,
550 item: Option<ItemLike<'_>>,
551 ) {
552 if target == (Target::Impl { of_trait: true }) {
555 match item.unwrap() {
556 ItemLike::Item(it) => match it.expect_impl().constness {
557 Constness::Const { .. } => {
558 let item_span = self.tcx.hir_span(hir_id);
559 self.tcx.emit_node_span_lint(
560 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
561 hir_id,
562 attr_span,
563 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
564 );
565 return;
566 }
567 Constness::NotConst => return,
568 },
569 ItemLike::ForeignItem => {}
570 }
571 }
572 }
576
577 fn check_diagnostic_on_move(&self, hir_id: HirId, directive: Option<&Directive>) {
579 if let Some(directive) = directive {
580 if let Node::Item(Item {
581 kind:
582 ItemKind::Struct(_, generics, _)
583 | ItemKind::Enum(_, generics, _)
584 | ItemKind::Union(_, generics, _),
585 ..
586 }) = self.tcx.hir_node(hir_id)
587 {
588 directive.visit_params(&mut |argument_name, span| {
589 let has_generic = generics.params.iter().any(|p| {
590 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
591 && let ParamName::Plain(name) = p.name
592 && name.name == argument_name
593 {
594 true
595 } else {
596 false
597 }
598 });
599 if !has_generic {
600 self.tcx.emit_node_span_lint(
601 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
602 hir_id,
603 span,
604 diagnostics::OnMoveMalformedFormatLiterals { name: argument_name },
605 )
606 }
607 });
608 }
609 }
610 }
611
612 fn check_diagnostic_on_type_error(&self, hir_id: HirId, directive: Option<&Directive>) {
613 if let Some(directive) = directive {
614 if let Node::Item(Item {
615 kind:
616 ItemKind::Struct(_, generics, _)
617 | ItemKind::Enum(_, generics, _)
618 | ItemKind::Union(_, generics, _),
619 ..
620 }) = self.tcx.hir_node(hir_id)
621 {
622 let generic_count = generics
623 .params
624 .iter()
625 .filter(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. }))
626 .count();
627
628 if generic_count != 1 {
630 self.tcx.emit_node_span_lint(
631 MALFORMED_DIAGNOSTIC_ATTRIBUTES,
632 hir_id,
633 generics.span,
634 diagnostics::OnTypeErrorNotExactlyOneGeneric { count: generic_count },
635 );
636 }
637
638 directive.visit_params(&mut |argument_name, span| {
639 let has_generic = generics.params.iter().any(|p| {
640 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
641 && let ParamName::Plain(name) = p.name
642 && name.name == argument_name
643 {
644 true
645 } else {
646 false
647 }
648 });
649
650 let is_allowed = argument_name == sym::Expected || argument_name == sym::Found;
651 if !(has_generic | is_allowed) {
652 self.tcx.emit_node_span_lint(
653 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
654 hir_id,
655 span,
656 diagnostics::OnTypeErrorMalformedFormatLiterals { name: argument_name },
657 )
658 }
659 });
660 }
661 }
662 }
663
664 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
666 match target {
667 Target::Fn
668 | Target::Closure
669 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
670 if let Some(did) = hir_id.as_owner()
672 && self.tcx.def_kind(did).has_codegen_attrs()
673 && kind != &InlineAttr::Never
674 {
675 let attrs = self.tcx.codegen_fn_attrs(did);
676 if attrs.contains_extern_indicator() {
678 self.tcx.emit_node_span_lint(
679 UNUSED_ATTRIBUTES,
680 hir_id,
681 attr_span,
682 diagnostics::InlineIgnoredForExported,
683 );
684 }
685 }
686 }
687 _ => {}
688 }
689 }
690
691 fn check_naked(&self, hir_id: HirId, target: Target) {
693 match target {
694 Target::Fn
695 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
696 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
697 let abi = fn_sig.header.abi;
698 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
699 feature_err(
700 &self.tcx.sess,
701 sym::naked_functions_rustic_abi,
702 fn_sig.span,
703 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
abi.as_str()))
})format!(
704 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
705 abi.as_str()
706 ),
707 )
708 .emit();
709 }
710 }
711 _ => {}
712 }
713 }
714
715 fn check_dump_object_lifetime_defaults(&self, hir_id: HirId) {
717 let tcx = self.tcx;
718 let Some(owner_id) = hir_id.as_owner() else { return };
719 for param in &tcx.generics_of(owner_id.def_id).own_params {
720 let ty::GenericParamDefKind::Type { .. } = param.kind else { continue };
721 let default = tcx.object_lifetime_default(param.def_id);
722 let repr = match default {
723 ObjectLifetimeDefault::Empty => "Empty".to_owned(),
724 ObjectLifetimeDefault::Static => "'static".to_owned(),
725 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
726 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
727 };
728 tcx.dcx().span_err(tcx.def_span(param.def_id), repr);
729 }
730 }
731
732 fn check_track_caller(
734 &self,
735 hir_id: HirId,
736 attr_span: Span,
737 attrs: &[Attribute],
738 target: Target,
739 ) {
740 match target {
741 Target::Fn => {
742 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)
745 && item.is_weak()
746 {
747 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
748
749 self.dcx().emit_err(diagnostics::LangItemWithTrackCaller {
750 attr_span,
751 name: item.name(),
752 sig_span: sig.span,
753 });
754 }
755
756 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) {
757 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
758 for i in impls {
759 let name = match i.resolution {
760 EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
761 EiiImplResolution::Known(decl) => decl.name.name,
762 EiiImplResolution::Error(_eg) => continue,
763 };
764 self.dcx().emit_err(diagnostics::EiiWithTrackCaller {
765 attr_span,
766 name,
767 sig_span: sig.span,
768 });
769 }
770 }
771 }
772 _ => {}
773 }
774 }
775
776 fn check_non_exhaustive(
778 &self,
779 attr_span: Span,
780 span: Span,
781 target: Target,
782 item: Option<ItemLike<'_>>,
783 ) {
784 match target {
785 Target::Struct => {
786 if let Some(ItemLike::Item(hir::Item {
787 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
788 ..
789 })) = item
790 && !fields.is_empty()
791 && fields.iter().any(|f| f.default.is_some())
792 {
793 self.dcx().emit_err(diagnostics::NonExhaustiveWithDefaultFieldValues {
794 attr_span,
795 defn_span: span,
796 });
797 }
798 }
799 _ => {}
800 }
801 }
802
803 fn check_target_feature(
805 &self,
806 hir_id: HirId,
807 attr_span: Span,
808 target: Target,
809 attrs: &[Attribute],
810 ) {
811 match target {
812 Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
813 | Target::Fn => {
814 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)
816 && !self.tcx.sess.target.is_like_wasm
819 && !self.tcx.sess.opts.actually_rustdoc
820 {
821 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
822
823 self.dcx().emit_err(diagnostics::LangItemWithTargetFeature {
824 attr_span,
825 name: lang_item.name(),
826 sig_span: sig.span,
827 });
828 }
829 }
830 _ => {}
831 }
832 }
833
834 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
835 if let Some(location) = match target {
836 Target::AssocTy => {
837 if let DefKind::Impl { .. } =
838 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
839 {
840 Some("type alias in implementation block")
841 } else {
842 None
843 }
844 }
845 Target::AssocConst => {
846 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
847 let containing_item = self.tcx.hir_expect_item(parent_def_id);
848 let err = "associated constant in trait implementation block";
850 match containing_item.kind {
851 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
852 _ => None,
853 }
854 }
855 Target::Param => return,
857 Target::Expression
858 | Target::Statement
859 | Target::Arm
860 | Target::ForeignMod
861 | Target::Closure
862 | Target::Impl { .. }
863 | Target::WherePredicate => Some(target.name()),
864 Target::ExternCrate
865 | Target::Use
866 | Target::Static
867 | Target::Const
868 | Target::Fn
869 | Target::Mod
870 | Target::GlobalAsm
871 | Target::TyAlias
872 | Target::Enum
873 | Target::Variant
874 | Target::Struct
875 | Target::Field
876 | Target::Union
877 | Target::Trait
878 | Target::TraitAlias
879 | Target::Method(..)
880 | Target::ForeignFn
881 | Target::ForeignStatic
882 | Target::ForeignTy
883 | Target::GenericParam { .. }
884 | Target::MacroDef
885 | Target::PatField
886 | Target::ExprField
887 | Target::Crate
888 | Target::MacroCall
889 | Target::Delegation { .. }
890 | Target::Loop
891 | Target::ForLoop
892 | Target::While => 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 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1126 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
} => true,
_ => false,
}matches!(
1127 param.kind,
1128 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1129 )
1130 && #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1131 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1132 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1133 && let hir::ItemKind::Impl(impl_) = item.kind
1134 && let Some(of_trait) = impl_.of_trait
1135 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1136 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1137 {
1138 return;
1139 }
1140
1141 self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
1142 }
1143
1144 fn check_link(&self, hir_id: HirId, attr_span: Span, target: Target) {
1146 if target != Target::ForeignMod {
1147 return; }
1149
1150 if let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1151 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1152 && !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::Rust => true,
_ => false,
}matches!(abi, ExternAbi::Rust)
1153 {
1154 return;
1155 }
1156
1157 self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr_span, diagnostics::Link);
1158 }
1159
1160 fn check_rustc_legacy_const_generics(
1162 &self,
1163 item: Option<ItemLike<'_>>,
1164 attr_span: Span,
1165 index_list: &ThinVec<(usize, Span)>,
1166 ) {
1167 let Some(ItemLike::Item(Item {
1168 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1169 ..
1170 })) = item
1171 else {
1172 return;
1174 };
1175
1176 for param in generics.params {
1177 match param.kind {
1178 hir::GenericParamKind::Const { .. } => {}
1179 _ => {
1180 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsOnly {
1181 attr_span,
1182 param_span: param.span,
1183 });
1184 return;
1185 }
1186 }
1187 }
1188
1189 if index_list.len() != generics.params.len() {
1190 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndex {
1191 attr_span,
1192 generics_span: generics.span,
1193 });
1194 return;
1195 }
1196
1197 let arg_count = decl.inputs.len() + generics.params.len();
1198 for (index, span) in index_list {
1199 if *index >= arg_count {
1200 self.dcx().emit_err(diagnostics::RustcLegacyConstGenericsIndexExceed {
1201 span: *span,
1202 arg_count,
1203 });
1204 }
1205 }
1206 }
1207
1208 fn check_repr(
1210 &self,
1211 attrs: &[Attribute],
1212 span: Span,
1213 target: Target,
1214 item: Option<ItemLike<'_>>,
1215 hir_id: HirId,
1216 ) {
1217 let (reprs, _first_attr_span) =
1223 {
'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)))
1224 .unwrap_or((&[], None));
1225
1226 let mut int_reprs = 0;
1227 let mut is_explicit_rust = false;
1228 let mut is_c = false;
1229 let mut is_simd = false;
1230 let mut is_transparent = false;
1231
1232 for (repr, _repr_span) in reprs {
1233 match repr {
1234 ReprAttr::ReprRust => {
1235 is_explicit_rust = true;
1236 }
1237 ReprAttr::ReprC => {
1238 is_c = true;
1239 }
1240 ReprAttr::ReprAlign(..) => {}
1241 ReprAttr::ReprPacked(_) => {}
1242 ReprAttr::ReprSimd => {
1243 is_simd = true;
1244 }
1245 ReprAttr::ReprTransparent => {
1246 is_transparent = true;
1247 }
1248 ReprAttr::ReprInt(_) => {
1249 int_reprs += 1;
1250 }
1251 };
1252 }
1253
1254 let hint_spans = reprs.iter().map(|(_, span)| *span);
1257
1258 if is_transparent && reprs.len() > 1 {
1260 let hint_spans = hint_spans.clone().collect();
1261 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1262 hint_spans,
1263 target: target.to_string(),
1264 });
1265 }
1266 if is_transparent
1269 && let Some(&pass_indirectly_span) =
1270 {
'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)
1271 {
1272 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1273 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],
1274 target: target.to_string(),
1275 });
1276 }
1277 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1278 let hint_spans = hint_spans.clone().collect();
1279 self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
1280 }
1281 if (int_reprs > 1)
1283 || (is_simd && is_c)
1284 || (int_reprs == 1
1285 && is_c
1286 && item.is_some_and(|item| {
1287 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1288 }))
1289 {
1290 self.tcx.emit_node_span_lint(
1291 CONFLICTING_REPR_HINTS,
1292 hir_id,
1293 hint_spans.collect::<Vec<Span>>(),
1294 diagnostics::ReprConflictingLint,
1295 );
1296 }
1297 }
1298
1299 fn check_macro_only_attr(
1304 &self,
1305 attr_span: Span,
1306 span: Span,
1307 target: Target,
1308 attrs: &[Attribute],
1309 ) {
1310 match target {
1311 Target::Fn => {
1312 for attr in attrs {
1313 if attr.is_proc_macro_attr() {
1314 return;
1316 }
1317 }
1318 self.tcx.dcx().emit_err(diagnostics::MacroOnlyAttribute { attr_span, span });
1319 }
1320 _ => {}
1321 }
1322 }
1323
1324 fn check_rustc_allow_const_fn_unstable(
1327 &self,
1328 hir_id: HirId,
1329 attr_span: Span,
1330 span: Span,
1331 target: Target,
1332 ) {
1333 match target {
1334 Target::Fn | Target::Method(_) => {
1335 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1336 self.tcx
1337 .dcx()
1338 .emit_err(diagnostics::RustcAllowConstFnUnstable { attr_span, span });
1339 }
1340 }
1341 _ => {}
1342 }
1343 }
1344
1345 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1346 match target {
1347 Target::AssocConst | Target::Method(..) | Target::AssocTy
1348 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1349 == DefKind::Impl { of_trait: true } =>
1350 {
1351 self.tcx.emit_node_span_lint(
1352 UNUSED_ATTRIBUTES,
1353 hir_id,
1354 attr_span,
1355 diagnostics::DeprecatedAnnotationHasNoEffect { span: attr_span },
1356 );
1357 }
1358 _ => {}
1359 }
1360 }
1361
1362 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1363 if target != Target::MacroDef {
1364 return;
1365 }
1366
1367 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1369 let is_decl_macro = !macro_definition.macro_rules;
1370
1371 if is_decl_macro {
1372 self.tcx.emit_node_span_lint(
1373 UNUSED_ATTRIBUTES,
1374 hir_id,
1375 attr_span,
1376 diagnostics::MacroExport::OnDeclMacro,
1377 );
1378 }
1379 }
1380
1381 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1382 let note =
1385 if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1386 && attr.meta_item_list().is_some_and(|list| list.is_empty())
1387 {
1388 diagnostics::UnusedNote::EmptyList { name: attr.name().unwrap() }
1389 } else if attr.has_any_name(&[
1390 sym::allow,
1391 sym::warn,
1392 sym::deny,
1393 sym::forbid,
1394 sym::expect,
1395 ]) && let Some(meta) = attr.meta_item_list()
1396 && let [meta] = meta.as_slice()
1397 && let Some(item) = meta.meta_item()
1398 && let MetaItemKind::NameValue(_) = &item.kind
1399 && item.path == sym::reason
1400 {
1401 diagnostics::UnusedNote::NoLints { name: attr.name().unwrap() }
1402 } else if attr.has_any_name(&[
1403 sym::allow,
1404 sym::warn,
1405 sym::deny,
1406 sym::forbid,
1407 sym::expect,
1408 ]) && let Some(meta) = attr.meta_item_list()
1409 && meta.iter().any(|meta| {
1410 meta.meta_item().map_or(false, |item| {
1411 item.path == sym::linker_messages || item.path == sym::linker_info
1412 })
1413 })
1414 {
1415 if hir_id != CRATE_HIR_ID {
1416 match style {
1417 Some(ast::AttrStyle::Outer) => {
1418 let attr_span = attr.span();
1419 let bang_position = self
1420 .tcx
1421 .sess
1422 .source_map()
1423 .span_until_char(attr_span, '[')
1424 .shrink_to_hi();
1425
1426 self.tcx.emit_node_span_lint(
1427 UNUSED_ATTRIBUTES,
1428 hir_id,
1429 attr_span,
1430 diagnostics::OuterCrateLevelAttr {
1431 suggestion: diagnostics::OuterCrateLevelAttrSuggestion {
1432 bang_position,
1433 },
1434 },
1435 )
1436 }
1437 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1438 UNUSED_ATTRIBUTES,
1439 hir_id,
1440 attr.span(),
1441 diagnostics::InnerCrateLevelAttr,
1442 ),
1443 };
1444 return;
1445 } else {
1446 let never_needs_link = self
1447 .tcx
1448 .crate_types()
1449 .iter()
1450 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1451 if never_needs_link {
1452 diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly
1453 } else {
1454 return;
1455 }
1456 }
1457 } else if hir_id == CRATE_HIR_ID
1458 && attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1459 && let Some(meta) = attr.meta_item_list()
1460 && meta.iter().any(|meta| {
1461 meta.meta_item().is_some_and(|item| item.path == sym::dead_code_pub_in_binary)
1462 })
1463 && !self.tcx.crate_types().contains(&CrateType::Executable)
1464 {
1465 diagnostics::UnusedNote::NoEffectDeadCodePubInBinary
1466 } else if attr.has_name(sym::default_method_body_is_const) {
1467 diagnostics::UnusedNote::DefaultMethodBodyConst
1468 } else {
1469 return;
1470 };
1471
1472 self.tcx.emit_node_span_lint(
1473 UNUSED_ATTRIBUTES,
1474 hir_id,
1475 attr.span(),
1476 diagnostics::Unused { attr_span: attr.span(), note },
1477 );
1478 }
1479
1480 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1484 if target != Target::Fn {
1485 return;
1486 }
1487
1488 let tcx = self.tcx;
1489 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1490 return;
1491 };
1492 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1493 return;
1494 };
1495
1496 let def_id = hir_id.expect_owner().def_id;
1497 let param_env = ty::ParamEnv::empty();
1498
1499 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1500 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1501
1502 let span = tcx.def_span(def_id);
1503 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1504 let sig = tcx.liberate_late_bound_regions(
1505 def_id.to_def_id(),
1506 tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1507 );
1508
1509 let mut cause = ObligationCause::misc(span, def_id);
1510 let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1511
1512 let errors = ocx.try_evaluate_obligations();
1514 if !errors.is_empty() {
1515 return;
1516 }
1517
1518 let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1519 std::iter::repeat_n(
1520 token_stream,
1521 match kind {
1522 ProcMacroKind::Attribute => 2,
1523 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1524 },
1525 ),
1526 token_stream,
1527 );
1528
1529 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1530 let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1531
1532 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1533 if let Some(hir_sig) = hir_sig {
1534 match terr {
1535 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1536 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1537 diag.span(ty.span);
1538 cause.span = ty.span;
1539 } else if idx == hir_sig.decl.inputs.len() {
1540 let span = hir_sig.decl.output.span();
1541 diag.span(span);
1542 cause.span = span;
1543 }
1544 }
1545 TypeError::ArgCount => {
1546 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1547 diag.span(ty.span);
1548 cause.span = ty.span;
1549 }
1550 }
1551 TypeError::SafetyMismatch(_) => {
1552 }
1554 TypeError::AbiMismatch(_) => {
1555 }
1557 TypeError::VariadicMismatch(_) => {
1558 }
1560 _ => {}
1561 }
1562 }
1563
1564 infcx.err_ctxt().note_type_err(
1565 &mut diag,
1566 &cause,
1567 None,
1568 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1569 expected: ty::Binder::dummy(expected_sig),
1570 found: ty::Binder::dummy(sig),
1571 }))),
1572 terr,
1573 false,
1574 None,
1575 );
1576 diag.emit();
1577 self.abort.set(true);
1578 }
1579
1580 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1581 if !errors.is_empty() {
1582 infcx.err_ctxt().report_fulfillment_errors(errors);
1583 self.abort.set(true);
1584 }
1585 }
1586
1587 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1588 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))
1589 .unwrap_or(false)
1590 {
1591 self.dcx().emit_err(diagnostics::RustcPubTransparent { span, attr_span });
1592 }
1593 }
1594
1595 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1596 if let (Target::Closure, None) = (
1597 target,
1598 {
'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),
1599 ) {
1600 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!(
1601 self.tcx.hir_expect_expr(hir_id).kind,
1602 hir::ExprKind::Closure(hir::Closure {
1603 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1604 ..
1605 })
1606 );
1607 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1608 let parent_span = self.tcx.def_span(parent_did);
1609
1610 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!(
1611 self.tcx, parent_did,
1612 Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1613 ) && is_coro
1614 {
1615 self.dcx()
1616 .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1617 }
1618 }
1619 }
1620
1621 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1622 if let Some(export_name_span) =
1623 {
'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)
1624 && let Some(no_mangle_span) =
1625 {
'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)
1626 {
1627 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1628 "#[unsafe(no_mangle)]"
1629 } else {
1630 "#[no_mangle]"
1631 };
1632 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1633 "#[unsafe(export_name)]"
1634 } else {
1635 "#[export_name]"
1636 };
1637
1638 self.tcx.emit_node_span_lint(
1639 lint::builtin::UNUSED_ATTRIBUTES,
1640 hir_id,
1641 no_mangle_span,
1642 diagnostics::MixedExportNameAndNoMangle {
1643 no_mangle_span,
1644 export_name_span,
1645 no_mangle_attr,
1646 export_name_attr,
1647 },
1648 );
1649 }
1650 }
1651
1652 fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1653 if let Some(optimize_span) =
1654 {
'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)
1655 && let Some((inline_attr, inline_span)) =
1656 {
'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))
1657 && inline_attr != &InlineAttr::Never
1658 {
1659 self.dcx()
1660 .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1661 }
1662 }
1663
1664 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1665 let node_span = self.tcx.hir_span(hir_id);
1666
1667 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1668 return; }
1670
1671 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(..)) {
1672 self.dcx().emit_err(diagnostics::LoopMatchAttr { attr_span, node_span });
1673 };
1674 }
1675
1676 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1677 let node_span = self.tcx.hir_span(hir_id);
1678
1679 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1680 return; }
1682
1683 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(..)) {
1684 self.dcx().emit_err(diagnostics::ConstContinueAttr { attr_span, node_span });
1685 };
1686 }
1687}
1688
1689impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1690 type NestedFilter = nested_filter::OnlyBodies;
1691
1692 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1693 self.tcx
1694 }
1695
1696 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1697 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1701 let def_id = item.owner_id.to_def_id();
1702 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 { .. }) {
1703 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1704 }
1705 }
1706
1707 let target = Target::from_item(item);
1708 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1709 intravisit::walk_item(self, item)
1710 }
1711
1712 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1713 self.check_attributes(
1714 where_predicate.hir_id,
1715 where_predicate.span,
1716 Target::WherePredicate,
1717 None,
1718 );
1719 intravisit::walk_where_predicate(self, where_predicate)
1720 }
1721
1722 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1723 let target = Target::from_generic_param(generic_param);
1724 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1725 intravisit::walk_generic_param(self, generic_param)
1726 }
1727
1728 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1729 let target = Target::from_trait_item(trait_item);
1730 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1731 intravisit::walk_trait_item(self, trait_item)
1732 }
1733
1734 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1735 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1736 intravisit::walk_field_def(self, struct_field);
1737 }
1738
1739 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1740 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1741 intravisit::walk_arm(self, arm);
1742 }
1743
1744 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1745 let target = Target::from_foreign_item(f_item);
1746 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1747 intravisit::walk_foreign_item(self, f_item)
1748 }
1749
1750 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1751 let target = target_from_impl_item(self.tcx, impl_item);
1752 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1753 intravisit::walk_impl_item(self, impl_item)
1754 }
1755
1756 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1757 if let hir::StmtKind::Let(l) = stmt.kind {
1759 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1760 }
1761 intravisit::walk_stmt(self, stmt)
1762 }
1763
1764 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1765 let target = match expr.kind {
1766 hir::ExprKind::Closure { .. } => Target::Closure,
1767 _ => Target::Expression,
1768 };
1769
1770 self.check_attributes(expr.hir_id, expr.span, target, None);
1771 intravisit::walk_expr(self, expr)
1772 }
1773
1774 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
1775 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
1776 intravisit::walk_expr_field(self, field)
1777 }
1778
1779 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
1780 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
1781 intravisit::walk_variant(self, variant)
1782 }
1783
1784 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1785 self.check_attributes(param.hir_id, param.span, Target::Param, None);
1786
1787 intravisit::walk_param(self, param);
1788 }
1789
1790 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
1791 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
1792 intravisit::walk_pat_field(self, field);
1793 }
1794}
1795
1796fn is_c_like_enum(item: &Item<'_>) -> bool {
1797 if let ItemKind::Enum(_, _, ref def) = item.kind {
1798 for variant in def.variants {
1799 match variant.data {
1800 hir::VariantData::Unit(..) => { }
1801 _ => return false,
1802 }
1803 }
1804 true
1805 } else {
1806 false
1807 }
1808}
1809
1810fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
1811 let attrs = tcx.hir_attrs(item.hir_id());
1812
1813 if let Some(attr_span) =
1814 {
'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)
1815 {
1816 tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
1817 }
1818}
1819
1820fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1821 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
1822 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
1823 if module_def_id.to_local_def_id().is_top_level_module() {
1824 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
1825 }
1826 if check_attr_visitor.abort.get() {
1827 tcx.dcx().abort_if_errors()
1828 }
1829}
1830
1831pub(crate) fn provide(providers: &mut Providers) {
1832 *providers = Providers { check_mod_attrs, ..*providers };
1833}
1834
1835fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
1836 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
1837 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
1838 fn_ptr_ty.decl.inputs.len() == 1
1839 } else {
1840 false
1841 }
1842 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
1843 && let Some(&[hir::GenericArg::Type(ty)]) =
1844 path.segments.last().map(|last| last.args().args)
1845 {
1846 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
1847 } else {
1848 false
1849 })
1850}