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