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