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