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, 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::RustcTestEntrypointMarker => (),
394 AttributeKind::RustcTestMarker(..) => (),
395 AttributeKind::RustcThenThisWouldNeed(..) => (),
396 AttributeKind::RustcTrivialFieldReads => (),
397 AttributeKind::Sanitize { .. } => {}
398 AttributeKind::ShouldPanic { .. } => (),
399 AttributeKind::Splat(..) => (),
400 AttributeKind::Stability { .. } => (),
401 AttributeKind::TargetFeature { .. } => {}
402 AttributeKind::TestRunner(..) => (),
403 AttributeKind::ThreadLocal => (),
404 AttributeKind::TrackCaller(_) => (),
405 AttributeKind::TypeLengthLimit { .. } => (),
406 AttributeKind::Unroll(..) => (),
407 AttributeKind::UnstableFeatureBound(..) => (),
408 AttributeKind::UnstableRemoved(..) => (),
409 AttributeKind::Used { .. } => (),
410 AttributeKind::WindowsSubsystem(..) => (),
411 }
413 }
414
415 fn check_path(&self, span: Span, hir_id: HirId) {
416 let Node::Item(item) = self.tcx.hir_node(hir_id) else {
417 return;
418 };
419
420 let ItemKind::Mod(_, module) = &item.kind else {
421 return;
422 };
423
424 if item.span == module.spans.inner_span || !item.span.contains(module.spans.inner_span) {
425 return;
426 }
427
428 if self.has_nested_module_path_dependency(module) {
431 return;
432 }
433
434 self.tcx.emit_node_span_lint(
435 UNUSED_ATTRIBUTES,
436 hir_id,
437 span,
438 diagnostics::Unused {
439 attr_span: span,
440 note: diagnostics::UnusedNote::PathOnInlineModule,
441 },
442 );
443 }
444
445 fn has_nested_module_path_dependency(&self, module: &Mod<'tcx>) -> bool {
446 module.item_ids.iter().any(|item_id| {
447 let child = self.tcx.hir_item(*item_id);
448
449 let ItemKind::Mod(_, child_module) = &child.kind else {
450 return false;
451 };
452
453 let is_out_of_line = child.span == child_module.spans.inner_span
454 || !child.span.contains(child_module.spans.inner_span);
455
456 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(..));
457
458 is_out_of_line || has_path_attr || self.has_nested_module_path_dependency(child_module)
459 })
460 }
461
462 fn check_rustc_must_implement_one_of(
463 &self,
464 attr_span: Span,
465 list: &ThinVec<Ident>,
466 hir_id: HirId,
467 target: Target,
468 ) {
469 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
472 return;
473 }
474
475 let def_id = hir_id.owner.def_id;
476
477 let items = self.tcx.associated_items(def_id);
478 for ident in list {
481 let item = items
482 .filter_by_name_unhygienic(ident.name)
483 .find(|item| item.ident(self.tcx) == *ident);
484
485 match item {
486 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
487 if !item.defaultness(self.tcx).has_value() {
488 self.tcx.dcx().emit_err(
489 diagnostics::FunctionNotHaveDefaultImplementation {
490 span: self.tcx.def_span(item.def_id),
491 note_span: attr_span,
492 },
493 );
494 }
495 }
496 Some(item) => {
497 self.dcx().emit_err(diagnostics::MustImplementNotFunction {
498 span: self.tcx.def_span(item.def_id),
499 span_note: diagnostics::MustImplementNotFunctionSpanNote {
500 span: attr_span,
501 },
502 note: diagnostics::MustImplementNotFunctionNote {},
503 });
504 }
505 None => {
506 self.dcx().emit_err(diagnostics::FunctionNotFoundInTrait { span: ident.span });
507 }
508 }
509 }
510 }
511
512 fn check_eii_impl(&self, eii_impl: &EiiImpl) {
515 let EiiImpl { span, inner_span, resolution, impl_unsafe_span, is_default: _ } = eii_impl;
516 let impl_unsafe = match resolution {
517 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!(
518 self.tcx,
519 *eii_macro,
520 EiiDeclaration(EiiDecl { impl_unsafe, .. }) => *impl_unsafe
521 ),
522 EiiImplResolution::Known(foreign_item_did) => self
523 .tcx
524 .externally_implementable_items(foreign_item_did.krate)
525 .get(foreign_item_did)
526 .map(|(decl, _)| decl.impl_unsafe),
527 EiiImplResolution::Error(_) => None,
528 };
529 let Some(needs_unsafe) = impl_unsafe else {
530 return;
531 };
532
533 let name = match resolution {
534 EiiImplResolution::Macro(eii_macro) => self.tcx.item_name(*eii_macro),
535 EiiImplResolution::Known(def_id) => self.tcx.item_name(*def_id),
536 EiiImplResolution::Error(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
537 };
538
539 match (needs_unsafe, *impl_unsafe_span) {
540 (true, None) => {
541 self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe {
542 span: *span,
543 name,
544 suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion {
545 left: inner_span.shrink_to_lo(),
546 right: inner_span.shrink_to_hi(),
547 },
548 });
549 }
550 (false, Some(unsafe_span)) => {
551 self.dcx().emit_err(diagnostics::EiiImplCannotBeUnsafe {
552 impl_span: *span,
553 unsafe_span,
554 name,
555 });
556 }
557 _ => {}
558 }
559 }
560
561 fn check_diagnostic_on_unimplemented(&self, hir_id: HirId, directive: Option<&Directive>) {
563 if let Some(directive) = directive {
564 if let Node::Item(Item {
565 kind: ItemKind::Trait { ident: trait_name, generics, .. },
566 ..
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::UnknownFormatParameterForOnUnimplementedAttr {
586 argument_name,
587 trait_name: *trait_name,
588 help: !directive.is_rustc_attr,
589 },
590 )
591 }
592 })
593 }
594 }
595 }
596
597 fn check_diagnostic_on_const(
599 &self,
600 attr_path_span: Span,
601 hir_id: HirId,
602 target: Target,
603 item: Option<&'tcx Item<'tcx>>,
604 directive: Option<&Directive>,
605 ) {
606 if target == (Target::Impl { of_trait: true }) {
609 if let Some(directive) = directive
610 && let Node::Item(Item { kind: ItemKind::Impl(hir::Impl { generics, .. }), .. }) =
611 self.tcx.hir_node(hir_id)
612 {
613 directive.visit_params(&mut |argument_name, span| {
614 let has_generic = generics.params.iter().any(|p| {
615 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
616 && let ParamName::Plain(name) = p.name
617 && name.name == argument_name
618 {
619 true
620 } else {
621 false
622 }
623 });
624 if !has_generic {
625 self.tcx.emit_node_span_lint(
626 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
627 hir_id,
628 span,
629 diagnostics::OnConstMalformedFormatLiterals { name: argument_name },
630 )
631 }
632 });
633 }
634 match item.unwrap().expect_impl().constness {
635 Constness::Const { .. } => {
636 let item_span = self.tcx.hir_span(hir_id);
637 self.tcx.emit_node_span_lint(
638 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
639 hir_id,
640 attr_path_span,
641 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
642 );
643 return;
644 }
645 Constness::NotConst => return,
646 }
647 }
648 }
649
650 fn check_diagnostic_on_move(&self, hir_id: HirId, directive: Option<&Directive>) {
652 if let Some(directive) = directive {
653 if let Node::Item(Item {
654 kind:
655 ItemKind::Struct(_, generics, _)
656 | ItemKind::Enum(_, generics, _)
657 | ItemKind::Union(_, generics, _),
658 ..
659 }) = self.tcx.hir_node(hir_id)
660 {
661 directive.visit_params(&mut |argument_name, span| {
662 let has_generic = generics.params.iter().any(|p| {
663 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
664 && let ParamName::Plain(name) = p.name
665 && name.name == argument_name
666 {
667 true
668 } else {
669 false
670 }
671 });
672 if !has_generic {
673 self.tcx.emit_node_span_lint(
674 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
675 hir_id,
676 span,
677 diagnostics::OnMoveMalformedFormatLiterals { name: argument_name },
678 )
679 }
680 });
681 }
682 }
683 }
684
685 fn check_diagnostic_on_type_error(&self, hir_id: HirId, directive: Option<&Directive>) {
686 if let Some(directive) = directive {
687 if let Node::Item(Item {
688 kind:
689 ItemKind::Struct(_, generics, _)
690 | ItemKind::Enum(_, generics, _)
691 | ItemKind::Union(_, generics, _),
692 ..
693 }) = self.tcx.hir_node(hir_id)
694 {
695 let generic_count = generics
696 .params
697 .iter()
698 .filter(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. }))
699 .count();
700
701 if generic_count != 1 {
703 self.tcx.emit_node_span_lint(
704 MALFORMED_DIAGNOSTIC_ATTRIBUTES,
705 hir_id,
706 generics.span,
707 diagnostics::OnTypeErrorNotExactlyOneGeneric { count: generic_count },
708 );
709 }
710
711 directive.visit_params(&mut |argument_name, span| {
712 let has_generic = generics.params.iter().any(|p| {
713 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
714 && let ParamName::Plain(name) = p.name
715 && name.name == argument_name
716 {
717 true
718 } else {
719 false
720 }
721 });
722
723 let is_allowed = argument_name == sym::Expected || argument_name == sym::Found;
724 if !(has_generic | is_allowed) {
725 self.tcx.emit_node_span_lint(
726 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
727 hir_id,
728 span,
729 diagnostics::OnTypeErrorMalformedFormatLiterals { name: argument_name },
730 )
731 }
732 });
733 }
734 }
735 }
736
737 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
739 match target {
740 Target::Fn
741 | Target::Closure
742 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
743 if let Some(did) = hir_id.as_owner()
745 && self.tcx.def_kind(did).has_codegen_attrs()
746 && kind != &InlineAttr::Never
747 {
748 let attrs = self.tcx.codegen_fn_attrs(did);
749 if attrs.contains_extern_indicator() {
751 self.tcx.emit_node_span_lint(
752 UNUSED_ATTRIBUTES,
753 hir_id,
754 attr_span,
755 diagnostics::InlineIgnoredForExported,
756 );
757 }
758 }
759 }
760 _ => {}
761 }
762 }
763
764 fn check_naked(&self, hir_id: HirId, target: Target) {
766 match target {
767 Target::Fn
768 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
769 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
770 let abi = fn_sig.header.abi;
771 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
772 feature_err(
773 &self.tcx.sess,
774 sym::naked_functions_rustic_abi,
775 fn_sig.span,
776 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
abi.as_str()))
})format!(
777 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
778 abi.as_str()
779 ),
780 )
781 .emit();
782 }
783 }
784 _ => {}
785 }
786 }
787
788 fn check_dump_object_lifetime_defaults(&self, hir_id: HirId) {
790 let tcx = self.tcx;
791 let Some(owner_id) = hir_id.as_owner() else { return };
792 for param in &tcx.generics_of(owner_id.def_id).own_params {
793 let ty::GenericParamDefKind::Type { .. } = param.kind else { continue };
794 let default = tcx.object_lifetime_default(param.def_id);
795 let repr = match default {
796 ObjectLifetimeDefault::Empty => "Empty".to_owned(),
797 ObjectLifetimeDefault::Static => "'static".to_owned(),
798 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
799 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
800 };
801 tcx.dcx().span_err(tcx.def_span(param.def_id), repr);
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, 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_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)))
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_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)
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_rustc_allow_const_fn_unstable(
1293 &self,
1294 hir_id: HirId,
1295 attr_span: Span,
1296 span: Span,
1297 target: Target,
1298 ) {
1299 match target {
1300 Target::Fn | Target::Method(_) => {
1301 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1302 self.tcx
1303 .dcx()
1304 .emit_err(diagnostics::RustcAllowConstFnUnstable { attr_span, span });
1305 }
1306 }
1307 _ => {}
1308 }
1309 }
1310
1311 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1312 match target {
1313 Target::AssocConst | Target::Method(..) | Target::AssocTy
1314 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1315 == DefKind::Impl { of_trait: true } =>
1316 {
1317 self.tcx.emit_node_span_lint(
1318 UNUSED_ATTRIBUTES,
1319 hir_id,
1320 attr_span,
1321 diagnostics::DeprecatedAnnotationHasNoEffect { span: attr_span },
1322 );
1323 }
1324 _ => {}
1325 }
1326 }
1327
1328 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1329 if target != Target::MacroDef {
1330 return;
1331 }
1332
1333 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1335 let is_decl_macro = !macro_definition.macro_rules;
1336
1337 if is_decl_macro {
1338 self.tcx.emit_node_span_lint(
1339 UNUSED_ATTRIBUTES,
1340 hir_id,
1341 attr_span,
1342 diagnostics::MacroExport::OnDeclMacro,
1343 );
1344 }
1345 }
1346
1347 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1348 let note =
1351 if attr.has_any_name(&[sym::allow, sym::expect, sym::warn, sym::deny, sym::forbid])
1352 && attr.meta_item_list().is_some_and(|list| list.is_empty())
1353 {
1354 diagnostics::UnusedNote::EmptyList { name: attr.name().unwrap() }
1355 } else if attr.has_any_name(&[
1356 sym::allow,
1357 sym::warn,
1358 sym::deny,
1359 sym::forbid,
1360 sym::expect,
1361 ]) && let Some(meta) = attr.meta_item_list()
1362 && let [meta] = meta.as_slice()
1363 && let Some(item) = meta.meta_item()
1364 && let MetaItemKind::NameValue(_) = &item.kind
1365 && item.path == sym::reason
1366 {
1367 diagnostics::UnusedNote::NoLints { name: attr.name().unwrap() }
1368 } else if attr.has_any_name(&[
1369 sym::allow,
1370 sym::warn,
1371 sym::deny,
1372 sym::forbid,
1373 sym::expect,
1374 ]) && let Some(meta) = attr.meta_item_list()
1375 && meta.iter().any(|meta| {
1376 meta.meta_item().map_or(false, |item| {
1377 item.path == sym::linker_messages || item.path == sym::linker_info
1378 })
1379 })
1380 {
1381 if hir_id != CRATE_HIR_ID {
1382 match style {
1383 Some(ast::AttrStyle::Outer) => {
1384 let attr_span = attr.span();
1385 let bang_position = self
1386 .tcx
1387 .sess
1388 .source_map()
1389 .span_until_char(attr_span, '[')
1390 .shrink_to_hi();
1391
1392 self.tcx.emit_node_span_lint(
1393 UNUSED_ATTRIBUTES,
1394 hir_id,
1395 attr_span,
1396 diagnostics::OuterCrateLevelAttr {
1397 suggestion: diagnostics::OuterCrateLevelAttrSuggestion {
1398 bang_position,
1399 },
1400 },
1401 )
1402 }
1403 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1404 UNUSED_ATTRIBUTES,
1405 hir_id,
1406 attr.span(),
1407 diagnostics::InnerCrateLevelAttr,
1408 ),
1409 };
1410 return;
1411 } else {
1412 let never_needs_link = self
1413 .tcx
1414 .crate_types()
1415 .iter()
1416 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1417 if never_needs_link {
1418 diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly
1419 } else {
1420 return;
1421 }
1422 }
1423 } else if hir_id == CRATE_HIR_ID
1424 && attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1425 && let Some(meta) = attr.meta_item_list()
1426 && meta.iter().any(|meta| {
1427 meta.meta_item().is_some_and(|item| item.path == sym::dead_code_pub_in_binary)
1428 })
1429 && !self.tcx.crate_types().contains(&CrateType::Executable)
1430 {
1431 diagnostics::UnusedNote::NoEffectDeadCodePubInBinary
1432 } else if attr.has_name(sym::default_method_body_is_const) {
1433 diagnostics::UnusedNote::DefaultMethodBodyConst
1434 } else {
1435 return;
1436 };
1437
1438 self.tcx.emit_node_span_lint(
1439 UNUSED_ATTRIBUTES,
1440 hir_id,
1441 attr.span(),
1442 diagnostics::Unused { attr_span: attr.span(), note },
1443 );
1444 }
1445
1446 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1450 if target != Target::Fn {
1451 return;
1452 }
1453
1454 let tcx = self.tcx;
1455 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1456 return;
1457 };
1458 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1459 return;
1460 };
1461
1462 let def_id = hir_id.expect_owner().def_id;
1463 let param_env = ty::ParamEnv::empty();
1464
1465 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1466 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1467
1468 let span = tcx.def_span(def_id);
1469 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1470 let sig = tcx.liberate_late_bound_regions(
1471 def_id.to_def_id(),
1472 tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1473 );
1474
1475 let mut cause = ObligationCause::misc(span, def_id);
1476 let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1477
1478 let errors = ocx.try_evaluate_obligations();
1480 if !errors.no_errors() {
1481 return;
1482 }
1483
1484 let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1485 std::iter::repeat_n(
1486 token_stream,
1487 match kind {
1488 ProcMacroKind::Attribute => 2,
1489 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1490 },
1491 ),
1492 token_stream,
1493 );
1494
1495 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1496 let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1497
1498 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1499 if let Some(hir_sig) = hir_sig {
1500 match terr {
1501 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1502 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1503 diag.span(ty.span);
1504 cause.span = ty.span;
1505 } else if idx == hir_sig.decl.inputs.len() {
1506 let span = hir_sig.decl.output.span();
1507 diag.span(span);
1508 cause.span = span;
1509 }
1510 }
1511 TypeError::ArgCount => {
1512 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1513 diag.span(ty.span);
1514 cause.span = ty.span;
1515 }
1516 }
1517 TypeError::SafetyMismatch(_) => {
1518 }
1520 TypeError::AbiMismatch(_) => {
1521 }
1523 TypeError::VariadicMismatch(_) => {
1524 }
1526 _ => {}
1527 }
1528 }
1529
1530 infcx.err_ctxt().note_type_err(
1531 &mut diag,
1532 &cause,
1533 None,
1534 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1535 expected: ty::Binder::dummy(expected_sig),
1536 found: ty::Binder::dummy(sig),
1537 }))),
1538 terr,
1539 false,
1540 None,
1541 );
1542 diag.emit();
1543 self.abort.set(true);
1544 }
1545
1546 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1547 if let TraitErrors::HasErrors(errors) = errors {
1548 infcx.err_ctxt().report_fulfillment_errors(errors);
1549 self.abort.set(true);
1550 }
1551 }
1552
1553 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1554 if let (Target::Closure, None) = (
1555 target,
1556 {
'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),
1557 ) {
1558 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!(
1559 self.tcx.hir_expect_expr(hir_id).kind,
1560 hir::ExprKind::Closure(hir::Closure {
1561 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1562 ..
1563 })
1564 );
1565 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1566 let parent_span = self.tcx.def_span(parent_did);
1567
1568 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!(
1569 self.tcx, parent_did,
1570 Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1571 ) && is_coro
1572 {
1573 self.dcx()
1574 .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1575 }
1576 }
1577 }
1578
1579 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1580 if let Some(export_name_span) =
1581 {
'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)
1582 && let Some(no_mangle_span) =
1583 {
'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)
1584 {
1585 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1586 "#[unsafe(no_mangle)]"
1587 } else {
1588 "#[no_mangle]"
1589 };
1590 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1591 "#[unsafe(export_name)]"
1592 } else {
1593 "#[export_name]"
1594 };
1595
1596 self.tcx.emit_node_span_lint(
1597 lint::builtin::UNUSED_ATTRIBUTES,
1598 hir_id,
1599 no_mangle_span,
1600 diagnostics::MixedExportNameAndNoMangle {
1601 no_mangle_span,
1602 export_name_span,
1603 no_mangle_attr,
1604 export_name_attr,
1605 },
1606 );
1607 }
1608 }
1609
1610 fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1611 if let Some(optimize_span) =
1612 {
'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)
1613 && let Some((inline_attr, inline_span)) =
1614 {
'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))
1615 && inline_attr != &InlineAttr::Never
1616 {
1617 self.dcx()
1618 .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1619 }
1620 }
1621
1622 fn check_linkage(
1623 &self,
1624 span: Span,
1625 hir_id: HirId,
1626 target: Target,
1627 item: Option<&'tcx Item<'tcx>>,
1628 ) {
1629 match target {
1632 Target::ForeignStatic
1633 if self.tcx.is_mutable_static(hir_id.expect_owner().def_id.into()) =>
1634 {
1635 self.tcx.dcx().emit_err(diagnostics::StaticMutLinkage { span });
1636 }
1637 Target::Fn
1638 if let Item { kind: ItemKind::Fn { sig, .. }, .. } = item.unwrap()
1639 && #[allow(non_exhaustive_omitted_patterns)] match sig.header.constness {
Constness::Const { .. } => true,
_ => false,
}matches!(sig.header.constness, Constness::Const { .. }) =>
1640 {
1641 self.tcx.dcx().emit_err(diagnostics::ConstFnLinkage { span });
1642 }
1643 _ => {}
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_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 { .. }) {
1662 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1663 }
1664 }
1665
1666 let target = Target::from(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);
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);
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(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_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)
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}