1use std::cell::Cell;
9use std::collections::hash_map::Entry;
10use std::slice;
11
12use rustc_abi::{Align, ExternAbi, Size};
13use rustc_ast::{AttrStyle, MetaItemKind, ast};
14use rustc_attr_parsing::{AttributeParser, Late};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::thin_vec::ThinVec;
17use rustc_data_structures::unord::UnordMap;
18use rustc_errors::{DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey, inline_fluent};
19use rustc_feature::{
20 ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP,
21 BuiltinAttribute,
22};
23use rustc_hir::attrs::{
24 AttributeKind, DocAttribute, DocInline, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
25 MirDialect, MirPhase, ReprAttr, SanitizerSet,
26};
27use rustc_hir::def::DefKind;
28use rustc_hir::def_id::LocalModDefId;
29use rustc_hir::intravisit::{self, Visitor};
30use rustc_hir::{
31 self as hir, Attribute, CRATE_HIR_ID, Constness, FnSig, ForeignItem, HirId, Item, ItemKind,
32 MethodKind, PartialConstStability, Safety, Stability, StabilityLevel, Target, TraitItem,
33 find_attr,
34};
35use rustc_macros::LintDiagnostic;
36use rustc_middle::hir::nested_filter;
37use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
38use rustc_middle::query::Providers;
39use rustc_middle::traits::ObligationCause;
40use rustc_middle::ty::error::{ExpectedFound, TypeError};
41use rustc_middle::ty::{self, TyCtxt, TypingMode};
42use rustc_middle::{bug, span_bug};
43use rustc_session::config::CrateType;
44use rustc_session::lint;
45use rustc_session::lint::builtin::{
46 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES,
47 UNUSED_ATTRIBUTES,
48};
49use rustc_session::parse::feature_err;
50use rustc_span::edition::Edition;
51use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, sym};
52use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
53use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
54use rustc_trait_selection::traits::ObligationCtxt;
55use tracing::debug;
56
57use crate::errors;
58
59#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnUnimplementedOnlyForTraits {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnUnimplementedOnlyForTraits => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")));
;
diag
}
};
}
}
};LintDiagnostic)]
60#[diag("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")]
61struct DiagnosticOnUnimplementedOnlyForTraits;
62
63#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnConstOnlyForTraitImpls {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnConstOnlyForTraitImpls { item_span: __binding_0
} => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to trait impls")));
;
diag.span_label(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("not a trait impl")));
diag
}
};
}
}
};LintDiagnostic)]
64#[diag("`#[diagnostic::on_const]` can only be applied to trait impls")]
65struct DiagnosticOnConstOnlyForTraitImpls {
66 #[label("not a trait impl")]
67 item_span: Span,
68}
69
70#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
DiagnosticOnConstOnlyForNonConstTraitImpls {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
DiagnosticOnConstOnlyForNonConstTraitImpls {
item_span: __binding_0 } => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`#[diagnostic::on_const]` can only be applied to non-const trait impls")));
;
diag.span_label(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait impl")));
diag
}
};
}
}
};LintDiagnostic)]
71#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait impls")]
72struct DiagnosticOnConstOnlyForNonConstTraitImpls {
73 #[label("this is a const trait impl")]
74 item_span: Span,
75}
76
77fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
78 match impl_item.kind {
79 hir::ImplItemKind::Const(..) => Target::AssocConst,
80 hir::ImplItemKind::Fn(..) => {
81 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
82 let containing_item = tcx.hir_expect_item(parent_def_id);
83 let containing_impl_is_for_trait = match &containing_item.kind {
84 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
85 _ => ::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"),
86 };
87 if containing_impl_is_for_trait {
88 Target::Method(MethodKind::Trait { body: true })
89 } else {
90 Target::Method(MethodKind::Inherent)
91 }
92 }
93 hir::ImplItemKind::Type(..) => Target::AssocTy,
94 }
95}
96
97#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ItemLike<'tcx> {
#[inline]
fn clone(&self) -> ItemLike<'tcx> {
let _: ::core::clone::AssertParamIsClone<&'tcx Item<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ItemLike<'tcx> { }Copy)]
98enum ItemLike<'tcx> {
99 Item(&'tcx Item<'tcx>),
100 ForeignItem,
101}
102
103#[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)]
104pub(crate) enum ProcMacroKind {
105 FunctionLike,
106 Derive,
107 Attribute,
108}
109
110impl IntoDiagArg for ProcMacroKind {
111 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
112 match self {
113 ProcMacroKind::Attribute => "attribute proc macro",
114 ProcMacroKind::Derive => "derive proc macro",
115 ProcMacroKind::FunctionLike => "function-like proc macro",
116 }
117 .into_diag_arg(&mut None)
118 }
119}
120
121struct CheckAttrVisitor<'tcx> {
122 tcx: TyCtxt<'tcx>,
123
124 abort: Cell<bool>,
126}
127
128impl<'tcx> CheckAttrVisitor<'tcx> {
129 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
130 self.tcx.dcx()
131 }
132
133 fn check_attributes(
135 &self,
136 hir_id: HirId,
137 span: Span,
138 target: Target,
139 item: Option<ItemLike<'_>>,
140 ) {
141 let mut seen = FxHashMap::default();
142 let attrs = self.tcx.hir_attrs(hir_id);
143 for attr in attrs {
144 let mut style = None;
145 match attr {
146 Attribute::Parsed(AttributeKind::ProcMacro(_)) => {
147 self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
148 }
149 Attribute::Parsed(AttributeKind::ProcMacroAttribute(_)) => {
150 self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
151 }
152 Attribute::Parsed(AttributeKind::ProcMacroDerive { .. }) => {
153 self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
154 }
155 Attribute::Parsed(
156 AttributeKind::Stability {
157 span: attr_span,
158 stability: Stability { level, feature },
159 }
160 | AttributeKind::RustcConstStability {
161 span: attr_span,
162 stability: PartialConstStability { level, feature, .. },
163 },
164 ) => self.check_stability(*attr_span, span, level, *feature),
165 Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force { .. }, ..)) => {} Attribute::Parsed(AttributeKind::Inline(kind, attr_span)) => {
167 self.check_inline(hir_id, *attr_span, kind, target)
168 }
169 Attribute::Parsed(AttributeKind::LoopMatch(attr_span)) => {
170 self.check_loop_match(hir_id, *attr_span, target)
171 }
172 Attribute::Parsed(AttributeKind::ConstContinue(attr_span)) => {
173 self.check_const_continue(hir_id, *attr_span, target)
174 }
175 Attribute::Parsed(AttributeKind::AllowInternalUnsafe(attr_span) | AttributeKind::AllowInternalUnstable(.., attr_span)) => {
176 self.check_macro_only_attr(*attr_span, span, target, attrs)
177 }
178 Attribute::Parsed(AttributeKind::RustcAllowConstFnUnstable(_, first_span)) => {
179 self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target)
180 }
181 Attribute::Parsed(AttributeKind::Deprecation {span: attr_span, .. }) => {
182 self.check_deprecated(hir_id, *attr_span, target)
183 }
184 Attribute::Parsed(AttributeKind::TargetFeature{ attr_span, ..}) => {
185 self.check_target_feature(hir_id, *attr_span, target, attrs)
186 }
187 Attribute::Parsed(AttributeKind::RustcObjectLifetimeDefault) => {
188 self.check_object_lifetime_default(hir_id);
189 }
190 &Attribute::Parsed(AttributeKind::RustcPubTransparent(attr_span)) => {
191 self.check_rustc_pub_transparent(attr_span, span, attrs)
192 }
193 Attribute::Parsed(AttributeKind::Align { align, span: attr_span }) => {
194 self.check_align(*align, *attr_span)
195 }
196 Attribute::Parsed(AttributeKind::Naked(..)) => {
197 self.check_naked(hir_id, target)
198 }
199 Attribute::Parsed(AttributeKind::TrackCaller(attr_span)) => {
200 self.check_track_caller(hir_id, *attr_span, attrs, target)
201 }
202 Attribute::Parsed(AttributeKind::NonExhaustive(attr_span)) => {
203 self.check_non_exhaustive(*attr_span, span, target, item)
204 }
205 &Attribute::Parsed(AttributeKind::FfiPure(attr_span)) => {
206 self.check_ffi_pure(attr_span, attrs)
207 }
208 Attribute::Parsed(AttributeKind::MayDangle(attr_span)) => {
209 self.check_may_dangle(hir_id, *attr_span)
210 }
211 &Attribute::Parsed(AttributeKind::CustomMir(dialect, phase, attr_span)) => {
212 self.check_custom_mir(dialect, phase, attr_span)
213 }
214 &Attribute::Parsed(AttributeKind::Sanitize { on_set, off_set, rtsan: _, span: attr_span}) => {
215 self.check_sanitize(attr_span, on_set | off_set, span, target);
216 },
217 Attribute::Parsed(AttributeKind::Link(_, attr_span)) => {
218 self.check_link(hir_id, *attr_span, span, target)
219 },
220 Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
221 self.check_macro_export(hir_id, *span, target)
222 },
223 Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics{attr_span, fn_indexes}) => {
224 self.check_rustc_legacy_const_generics(item, *attr_span, fn_indexes)
225 },
226 Attribute::Parsed(AttributeKind::Doc(attr)) => self.check_doc_attrs(attr, hir_id, target),
227 Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
228 self.check_eii_impl(impls, target)
229 },
230 Attribute::Parsed(AttributeKind::RustcMustImplementOneOf { attr_span, fn_names }) => {
231 self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id,target)
232 },
233 Attribute::Parsed(AttributeKind::DoNotRecommend{attr_span}) => {self.check_do_not_recommend(*attr_span, hir_id, target, item)},
234 Attribute::Parsed(
235 AttributeKind::RustcAllowIncoherentImpl(..)
237 | AttributeKind::AutomaticallyDerived(..)
238 | AttributeKind::CfgAttrTrace
239 | AttributeKind::CfgTrace(..)
240 | AttributeKind::CfiEncoding { .. }
241 | AttributeKind::Cold(..)
242 | AttributeKind::CollapseDebugInfo(..)
243 | AttributeKind::CompilerBuiltins
244 | AttributeKind::Coroutine(..)
245 | AttributeKind::Coverage (..)
246 | AttributeKind::CrateName { .. }
247 | AttributeKind::CrateType(..)
248 | AttributeKind::DebuggerVisualizer(..)
249 | AttributeKind::DocComment {..}
251 | AttributeKind::EiiDeclaration { .. }
252 | AttributeKind::EiiForeignItem
253 | AttributeKind::ExportName { .. }
254 | AttributeKind::ExportStable
255 | AttributeKind::FfiConst(..)
256 | AttributeKind::Fundamental
257 | AttributeKind::Ignore { .. }
258 | AttributeKind::InstructionSet(..)
259 | AttributeKind::LinkName { .. }
260 | AttributeKind::LinkOrdinal { .. }
261 | AttributeKind::LinkSection { .. }
262 | AttributeKind::Linkage(..)
263 | AttributeKind::MacroEscape( .. )
264 | AttributeKind::MacroUse { .. }
265 | AttributeKind::Marker(..)
266 | AttributeKind::MoveSizeLimit { .. }
267 | AttributeKind::MustNotSupend { .. }
268 | AttributeKind::MustUse { .. }
269 | AttributeKind::NeedsAllocator
270 | AttributeKind::NeedsPanicRuntime
271 | AttributeKind::NoBuiltins
272 | AttributeKind::NoCore { .. }
273 | AttributeKind::NoImplicitPrelude(..)
274 | AttributeKind::NoLink
275 | AttributeKind::NoMain
276 | AttributeKind::NoMangle(..)
277 | AttributeKind::NoStd { .. }
278 | AttributeKind::Optimize(..)
279 | AttributeKind::PanicRuntime
280 | AttributeKind::PatchableFunctionEntry { .. }
281 | AttributeKind::Path(..)
282 | AttributeKind::PatternComplexityLimit { .. }
283 | AttributeKind::PinV2(..)
284 | AttributeKind::Pointee(..)
285 | AttributeKind::ProfilerRuntime
286 | AttributeKind::RecursionLimit { .. }
287 | AttributeKind::ReexportTestHarnessMain(..)
288 | AttributeKind::Repr { .. }
290 | AttributeKind::RustcAbi { .. }
291 | AttributeKind::RustcAllocator
292 | AttributeKind::RustcAllocatorZeroed
293 | AttributeKind::RustcAllocatorZeroedVariant { .. }
294 | AttributeKind::RustcAsPtr(..)
295 | AttributeKind::RustcBodyStability { .. }
296 | AttributeKind::RustcBuiltinMacro { .. }
297 | AttributeKind::RustcCaptureAnalysis
298 | AttributeKind::RustcCguTestAttr(..)
299 | AttributeKind::RustcClean(..)
300 | AttributeKind::RustcCoherenceIsCore(..)
301 | AttributeKind::RustcCoinductive(..)
302 | AttributeKind::RustcConfusables { .. }
303 | AttributeKind::RustcConstStabilityIndirect
304 | AttributeKind::RustcConversionSuggestion
305 | AttributeKind::RustcDeallocator
306 | AttributeKind::RustcDefPath(..)
307 | AttributeKind::RustcDelayedBugFromInsideQuery
308 | AttributeKind::RustcDenyExplicitImpl(..)
309 | AttributeKind::RustcDeprecatedSafe2024 {..}
310 | AttributeKind::RustcDummy
311 | AttributeKind::RustcDumpDefParents
312 | AttributeKind::RustcDumpItemBounds
313 | AttributeKind::RustcDumpPredicates
314 | AttributeKind::RustcDumpUserArgs
315 | AttributeKind::RustcDumpVtable(..)
316 | AttributeKind::RustcDynIncompatibleTrait(..)
317 | AttributeKind::RustcEffectiveVisibility
318 | AttributeKind::RustcEvaluateWhereClauses
319 | AttributeKind::RustcHasIncoherentInherentImpls
320 | AttributeKind::RustcHiddenTypeOfOpaques
321 | AttributeKind::RustcIfThisChanged(..)
322 | AttributeKind::RustcInsignificantDtor
323 | AttributeKind::RustcIntrinsic
324 | AttributeKind::RustcIntrinsicConstStableIndirect
325 | AttributeKind::RustcLayout(..)
326 | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
327 | AttributeKind::RustcLayoutScalarValidRangeStart(..)
328 | AttributeKind::RustcLintOptDenyFieldAccess { .. }
329 | AttributeKind::RustcLintOptTy
330 | AttributeKind::RustcLintQueryInstability
331 | AttributeKind::RustcLintUntrackedQueryInformation
332 | AttributeKind::RustcMacroTransparency(_)
333 | AttributeKind::RustcMain
334 | AttributeKind::RustcMir(_)
335 | AttributeKind::RustcNeverReturnsNullPointer
336 | AttributeKind::RustcNeverTypeOptions {..}
337 | AttributeKind::RustcNoImplicitAutorefs
338 | AttributeKind::RustcNoImplicitBounds
339 | AttributeKind::RustcNoMirInline
340 | AttributeKind::RustcNonConstTraitMethod
341 | AttributeKind::RustcNounwind
342 | AttributeKind::RustcObjcClass { .. }
343 | AttributeKind::RustcObjcSelector { .. }
344 | AttributeKind::RustcOffloadKernel
345 | AttributeKind::RustcOutlives
346 | AttributeKind::RustcParenSugar(..)
347 | AttributeKind::RustcPassByValue (..)
348 | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)
349 | AttributeKind::RustcPreserveUbChecks
350 | AttributeKind::RustcReallocator
351 | AttributeKind::RustcRegions
352 | AttributeKind::RustcReservationImpl(..)
353 | AttributeKind::RustcScalableVector { .. }
354 | AttributeKind::RustcShouldNotBeCalledOnConstItems(..)
355 | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
356 | AttributeKind::RustcSkipDuringMethodDispatch { .. }
357 | AttributeKind::RustcSpecializationTrait(..)
358 | AttributeKind::RustcStdInternalSymbol (..)
359 | AttributeKind::RustcStrictCoherence(..)
360 | AttributeKind::RustcSymbolName(..)
361 | AttributeKind::RustcThenThisWouldNeed(..)
362 | AttributeKind::RustcTrivialFieldReads
363 | AttributeKind::RustcUnsafeSpecializationMarker(..)
364 | AttributeKind::RustcVariance
365 | AttributeKind::RustcVarianceOfOpaques
366 | AttributeKind::ShouldPanic { .. }
367 | AttributeKind::ThreadLocal
368 | AttributeKind::TypeLengthLimit { .. }
369 | AttributeKind::UnstableFeatureBound(..)
370 | AttributeKind::Used { .. }
371 | AttributeKind::WindowsSubsystem(..)
372 ) => { }
374 Attribute::Unparsed(attr_item) => {
375 style = Some(attr_item.style);
376 match attr.path().as_slice() {
377 [sym::diagnostic, sym::on_unimplemented, ..] => {
378 self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
379 }
380 [sym::diagnostic, sym::on_const, ..] => {
381 self.check_diagnostic_on_const(attr.span(), hir_id, target, item)
382 }
383 [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => {
384 self.check_autodiff(hir_id, attr, span, target)
385 }
386 [
387 sym::allow
389 | sym::expect
390 | sym::warn
391 | sym::deny
392 | sym::forbid
393 | sym::deprecated_safe | sym::prelude_import
397 | sym::panic_handler
398 | sym::lang
399 | sym::default_lib_allocator
400 | sym::rustc_diagnostic_item
401 | sym::rustc_nonnull_optimization_guaranteed
402 | sym::rustc_inherit_overflow_checks
403 | sym::rustc_on_unimplemented
404 | sym::rustc_do_not_const_check
405 | sym::rustc_doc_primitive
406 | sym::rustc_test_marker
407 | sym::rustc_layout
408 | sym::rustc_proc_macro_decls
409 | sym::rustc_autodiff
410 | sym::rustc_capture_analysis
411 | sym::rustc_mir
412 | sym::feature
414 | sym::register_tool
415 | sym::test_runner,
416 ..
417 ] => {}
418 [name, rest@..] => {
419 match BUILTIN_ATTRIBUTE_MAP.get(name) {
420 Some(_) => {
421 if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
422 continue
426 }
427
428 ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
name))span_bug!(
429 attr.span(),
430 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
431 )
432 }
433 None => (),
434 }
435 }
436 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
437 }
438 }
439 }
440
441 if hir_id != CRATE_HIR_ID {
442 match attr {
443 Attribute::Parsed(_) => { }
444 Attribute::Unparsed(attr) => {
445 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
448 attr.path
449 .segments
450 .first()
451 .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
452 {
453 match attr.style {
454 ast::AttrStyle::Outer => {
455 let attr_span = attr.span;
456 let bang_position = self
457 .tcx
458 .sess
459 .source_map()
460 .span_until_char(attr_span, '[')
461 .shrink_to_hi();
462
463 self.tcx.emit_node_span_lint(
464 UNUSED_ATTRIBUTES,
465 hir_id,
466 attr.span,
467 errors::OuterCrateLevelAttr {
468 suggestion: errors::OuterCrateLevelAttrSuggestion {
469 bang_position,
470 },
471 },
472 )
473 }
474 ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
475 UNUSED_ATTRIBUTES,
476 hir_id,
477 attr.span,
478 errors::InnerCrateLevelAttr,
479 ),
480 }
481 }
482 }
483 }
484 }
485
486 if let Attribute::Unparsed(unparsed_attr) = attr
487 && let Some(BuiltinAttribute { duplicates, .. }) =
488 attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
489 {
490 check_duplicates(
491 self.tcx,
492 unparsed_attr.span,
493 attr,
494 hir_id,
495 *duplicates,
496 &mut seen,
497 );
498 }
499
500 self.check_unused_attribute(hir_id, attr, style)
501 }
502
503 self.check_repr(attrs, span, target, item, hir_id);
504 self.check_rustc_force_inline(hir_id, attrs, target);
505 self.check_mix_no_mangle_export(hir_id, attrs);
506 }
507
508 fn check_rustc_must_implement_one_of(
509 &self,
510 attr_span: Span,
511 list: &ThinVec<Ident>,
512 hir_id: HirId,
513 target: Target,
514 ) {
515 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
518 return;
519 }
520
521 let def_id = hir_id.owner.def_id;
522
523 let items = self.tcx.associated_items(def_id);
524 for ident in list {
527 let item = items
528 .filter_by_name_unhygienic(ident.name)
529 .find(|item| item.ident(self.tcx) == *ident);
530
531 match item {
532 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
533 if !item.defaultness(self.tcx).has_value() {
534 self.tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation {
535 span: self.tcx.def_span(item.def_id),
536 note_span: attr_span,
537 });
538 }
539 }
540 Some(item) => {
541 self.dcx().emit_err(errors::MustImplementNotFunction {
542 span: self.tcx.def_span(item.def_id),
543 span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span },
544 note: errors::MustImplementNotFunctionNote {},
545 });
546 }
547 None => {
548 self.dcx().emit_err(errors::FunctionNotFoundInTrait { span: ident.span });
549 }
550 }
551 }
552 let mut set: UnordMap<Symbol, Span> = Default::default();
555
556 for ident in &*list {
557 if let Some(dup) = set.insert(ident.name, ident.span) {
558 self.tcx
559 .dcx()
560 .emit_err(errors::FunctionNamesDuplicated { spans: <[_]>::into_vec(::alloc::boxed::box_new([dup, ident.span]))vec![dup, ident.span] });
561 }
562 }
563 }
564
565 fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
566 for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
567 match target {
568 Target::Fn => {}
569 _ => {
570 self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
571 }
572 }
573
574 if let EiiImplResolution::Macro(eii_macro) = resolution
575 && {
{
'done:
{
for i in self.tcx.get_all_attrs(*eii_macro) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::EiiDeclaration(EiiDecl {
impl_unsafe, .. })) if *impl_unsafe => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiDeclaration(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
576 && !impl_marked_unsafe
577 {
578 self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
579 span: *span,
580 name: self.tcx.item_name(*eii_macro),
581 suggestion: errors::EiiImplRequiresUnsafeSuggestion {
582 left: inner_span.shrink_to_lo(),
583 right: inner_span.shrink_to_hi(),
584 },
585 });
586 }
587 }
588 }
589
590 fn check_do_not_recommend(
592 &self,
593 attr_span: Span,
594 hir_id: HirId,
595 target: Target,
596 item: Option<ItemLike<'_>>,
597 ) {
598 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Impl { .. } => true,
_ => false,
}matches!(target, Target::Impl { .. })
599 || #[allow(non_exhaustive_omitted_patterns)] match item {
Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl), .. }))
if _impl.of_trait.is_none() => true,
_ => false,
}matches!(
600 item,
601 Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl),.. }))
602 if _impl.of_trait.is_none()
603 )
604 {
605 self.tcx.emit_node_span_lint(
606 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
607 hir_id,
608 attr_span,
609 errors::IncorrectDoNotRecommendLocation,
610 );
611 }
612 }
613
614 fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) {
616 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
617 self.tcx.emit_node_span_lint(
618 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
619 hir_id,
620 attr_span,
621 DiagnosticOnUnimplementedOnlyForTraits,
622 );
623 }
624 }
625
626 fn check_diagnostic_on_const(
628 &self,
629 attr_span: Span,
630 hir_id: HirId,
631 target: Target,
632 item: Option<ItemLike<'_>>,
633 ) {
634 if target == (Target::Impl { of_trait: true }) {
635 match item.unwrap() {
636 ItemLike::Item(it) => match it.expect_impl().constness {
637 Constness::Const => {
638 let item_span = self.tcx.hir_span(hir_id);
639 self.tcx.emit_node_span_lint(
640 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
641 hir_id,
642 attr_span,
643 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
644 );
645 return;
646 }
647 Constness::NotConst => return,
648 },
649 ItemLike::ForeignItem => {}
650 }
651 }
652 let item_span = self.tcx.hir_span(hir_id);
653 self.tcx.emit_node_span_lint(
654 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
655 hir_id,
656 attr_span,
657 DiagnosticOnConstOnlyForTraitImpls { item_span },
658 );
659 }
660
661 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
663 match target {
664 Target::Fn
665 | Target::Closure
666 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
667 if let Some(did) = hir_id.as_owner()
669 && self.tcx.def_kind(did).has_codegen_attrs()
670 && kind != &InlineAttr::Never
671 {
672 let attrs = self.tcx.codegen_fn_attrs(did);
673 if attrs.contains_extern_indicator() {
675 self.tcx.emit_node_span_lint(
676 UNUSED_ATTRIBUTES,
677 hir_id,
678 attr_span,
679 errors::InlineIgnoredForExported {},
680 );
681 }
682 }
683 }
684 _ => {}
685 }
686 }
687
688 fn check_sanitize(
691 &self,
692 attr_span: Span,
693 set: SanitizerSet,
694 target_span: Span,
695 target: Target,
696 ) {
697 let mut not_fn_impl_mod = None;
698 let mut no_body = None;
699
700 match target {
701 Target::Fn
702 | Target::Closure
703 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
704 | Target::Impl { .. }
705 | Target::Mod => return,
706 Target::Static
707 if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
710 == SanitizerSet::empty() =>
711 {
712 return;
713 }
714
715 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
718 no_body = Some(target_span);
719 }
720
721 _ => {
722 not_fn_impl_mod = Some(target_span);
723 }
724 }
725
726 self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
727 attr_span,
728 not_fn_impl_mod,
729 no_body,
730 help: (),
731 });
732 }
733
734 fn check_naked(&self, hir_id: HirId, target: Target) {
736 match target {
737 Target::Fn
738 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
739 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
740 let abi = fn_sig.header.abi;
741 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
742 feature_err(
743 &self.tcx.sess,
744 sym::naked_functions_rustic_abi,
745 fn_sig.span,
746 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
abi.as_str()))
})format!(
747 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
748 abi.as_str()
749 ),
750 )
751 .emit();
752 }
753 }
754 _ => {}
755 }
756 }
757
758 fn check_object_lifetime_default(&self, hir_id: HirId) {
760 let tcx = self.tcx;
761 if let Some(owner_id) = hir_id.as_owner()
762 && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
763 {
764 for p in generics.params {
765 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
766 let default = tcx.object_lifetime_default(p.def_id);
767 let repr = match default {
768 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
769 ObjectLifetimeDefault::Static => "'static".to_owned(),
770 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
771 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
772 };
773 tcx.dcx().emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
774 }
775 }
776 }
777
778 fn check_track_caller(
780 &self,
781 hir_id: HirId,
782 attr_span: Span,
783 attrs: &[Attribute],
784 target: Target,
785 ) {
786 match target {
787 Target::Fn => {
788 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
791 && let Some(item) = hir::LangItem::from_name(lang_item)
792 && item.is_weak()
793 {
794 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
795
796 self.dcx().emit_err(errors::LangItemWithTrackCaller {
797 attr_span,
798 name: lang_item,
799 sig_span: sig.span,
800 });
801 }
802
803 if let Some(impls) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::EiiImpls(impls))
=> {
break 'done Some(impls);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
804 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
805 for i in impls {
806 let name = match i.resolution {
807 EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
808 EiiImplResolution::Known(decl) => decl.name.name,
809 EiiImplResolution::Error(_eg) => continue,
810 };
811 self.dcx().emit_err(errors::EiiWithTrackCaller {
812 attr_span,
813 name,
814 sig_span: sig.span,
815 });
816 }
817 }
818 }
819 _ => {}
820 }
821 }
822
823 fn check_non_exhaustive(
825 &self,
826 attr_span: Span,
827 span: Span,
828 target: Target,
829 item: Option<ItemLike<'_>>,
830 ) {
831 match target {
832 Target::Struct => {
833 if let Some(ItemLike::Item(hir::Item {
834 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
835 ..
836 })) = item
837 && !fields.is_empty()
838 && fields.iter().any(|f| f.default.is_some())
839 {
840 self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
841 attr_span,
842 defn_span: span,
843 });
844 }
845 }
846 _ => {}
847 }
848 }
849
850 fn check_target_feature(
852 &self,
853 hir_id: HirId,
854 attr_span: Span,
855 target: Target,
856 attrs: &[Attribute],
857 ) {
858 match target {
859 Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
860 | Target::Fn => {
861 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
863 && !self.tcx.sess.target.is_like_wasm
866 && !self.tcx.sess.opts.actually_rustdoc
867 {
868 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
869
870 self.dcx().emit_err(errors::LangItemWithTargetFeature {
871 attr_span,
872 name: lang_item,
873 sig_span: sig.span,
874 });
875 }
876 }
877 _ => {}
878 }
879 }
880
881 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
882 if let Some(location) = match target {
883 Target::AssocTy => {
884 if let DefKind::Impl { .. } =
885 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
886 {
887 Some("type alias in implementation block")
888 } else {
889 None
890 }
891 }
892 Target::AssocConst => {
893 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
894 let containing_item = self.tcx.hir_expect_item(parent_def_id);
895 let err = "associated constant in trait implementation block";
897 match containing_item.kind {
898 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
899 _ => None,
900 }
901 }
902 Target::Param => return,
904 Target::Expression
905 | Target::Statement
906 | Target::Arm
907 | Target::ForeignMod
908 | Target::Closure
909 | Target::Impl { .. }
910 | Target::WherePredicate => Some(target.name()),
911 Target::ExternCrate
912 | Target::Use
913 | Target::Static
914 | Target::Const
915 | Target::Fn
916 | Target::Mod
917 | Target::GlobalAsm
918 | Target::TyAlias
919 | Target::Enum
920 | Target::Variant
921 | Target::Struct
922 | Target::Field
923 | Target::Union
924 | Target::Trait
925 | Target::TraitAlias
926 | Target::Method(..)
927 | Target::ForeignFn
928 | Target::ForeignStatic
929 | Target::ForeignTy
930 | Target::GenericParam { .. }
931 | Target::MacroDef
932 | Target::PatField
933 | Target::ExprField
934 | Target::Crate
935 | Target::MacroCall
936 | Target::Delegation { .. } => None,
937 } {
938 self.tcx.dcx().emit_err(errors::DocAliasBadLocation { span, location });
939 return;
940 }
941 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
942 self.tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str: alias });
943 return;
944 }
945 }
946
947 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
948 let item_kind = match self.tcx.hir_node(hir_id) {
949 hir::Node::Item(item) => Some(&item.kind),
950 _ => None,
951 };
952 match item_kind {
953 Some(ItemKind::Impl(i)) => {
954 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
955 || if let Some(&[hir::GenericArg::Type(ty)]) = i
956 .of_trait
957 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
958 .map(|last_segment| last_segment.args().args)
959 {
960 #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
961 } else {
962 false
963 };
964 if !is_valid {
965 self.dcx().emit_err(errors::DocFakeVariadicNotValid { span });
966 }
967 }
968 _ => {
969 self.dcx().emit_err(errors::DocKeywordOnlyImpl { span });
970 }
971 }
972 }
973
974 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
975 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
976 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
977 return;
978 };
979 match item.kind {
980 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
981 if generics.params.len() != 0 => {}
982 ItemKind::Trait(_, _, _, _, generics, _, items)
983 if generics.params.len() != 0
984 || items.iter().any(|item| {
985 #[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)
986 }) => {}
987 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
988 _ => {
989 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
990 }
991 }
992 }
993
994 fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
1004 let span = match inline {
1005 [] => return,
1006 [(_, span)] => *span,
1007 [(inline, span), rest @ ..] => {
1008 for (inline2, span2) in rest {
1009 if inline2 != inline {
1010 let mut spans = MultiSpan::from_spans(<[_]>::into_vec(::alloc::boxed::box_new([*span, *span2]))vec![*span, *span2]);
1011 spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))inline_fluent!("this attribute..."));
1012 spans.push_span_label(
1013 *span2,
1014 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))inline_fluent!("{\".\"}..conflicts with this attribute"),
1015 );
1016 self.dcx().emit_err(errors::DocInlineConflict { spans });
1017 return;
1018 }
1019 }
1020 *span
1021 }
1022 };
1023
1024 match target {
1025 Target::Use | Target::ExternCrate => {}
1026 _ => {
1027 self.tcx.emit_node_span_lint(
1028 INVALID_DOC_ATTRIBUTES,
1029 hir_id,
1030 span,
1031 errors::DocInlineOnlyUse {
1032 attr_span: span,
1033 item_span: self.tcx.hir_span(hir_id),
1034 },
1035 );
1036 }
1037 }
1038 }
1039
1040 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
1041 if target != Target::ExternCrate {
1042 self.tcx.emit_node_span_lint(
1043 INVALID_DOC_ATTRIBUTES,
1044 hir_id,
1045 span,
1046 errors::DocMaskedOnlyExternCrate {
1047 attr_span: span,
1048 item_span: self.tcx.hir_span(hir_id),
1049 },
1050 );
1051 return;
1052 }
1053
1054 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1055 self.tcx.emit_node_span_lint(
1056 INVALID_DOC_ATTRIBUTES,
1057 hir_id,
1058 span,
1059 errors::DocMaskedNotExternCrateSelf {
1060 attr_span: span,
1061 item_span: self.tcx.hir_span(hir_id),
1062 },
1063 );
1064 }
1065 }
1066
1067 fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1068 let item_kind = match self.tcx.hir_node(hir_id) {
1069 hir::Node::Item(item) => Some(&item.kind),
1070 _ => None,
1071 };
1072 match item_kind {
1073 Some(ItemKind::Mod(_, module)) => {
1074 if !module.item_ids.is_empty() {
1075 self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod { span, attr_name });
1076 return;
1077 }
1078 }
1079 _ => {
1080 self.dcx().emit_err(errors::DocKeywordAttributeNotMod { span, attr_name });
1081 return;
1082 }
1083 }
1084 }
1085
1086 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1093 let DocAttribute {
1094 aliases,
1095 hidden: _,
1098 inline,
1099 cfg: _,
1101 auto_cfg: _,
1103 auto_cfg_change: _,
1105 fake_variadic,
1106 keyword,
1107 masked,
1108 notable_trait: _,
1110 search_unbox,
1111 html_favicon_url: _,
1113 html_logo_url: _,
1115 html_playground_url: _,
1117 html_root_url: _,
1119 html_no_source: _,
1121 issue_tracker_base_url: _,
1123 rust_logo,
1124 test_attrs: _,
1126 no_crate_inject: _,
1128 attribute,
1129 } = attr;
1130
1131 for (alias, span) in aliases {
1132 self.check_doc_alias_value(*span, hir_id, target, *alias);
1133 }
1134
1135 if let Some((_, span)) = keyword {
1136 self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1137 }
1138 if let Some((_, span)) = attribute {
1139 self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1140 }
1141
1142 if let Some(span) = fake_variadic {
1143 self.check_doc_fake_variadic(*span, hir_id);
1144 }
1145
1146 if let Some(span) = search_unbox {
1147 self.check_doc_search_unbox(*span, hir_id);
1148 }
1149
1150 self.check_doc_inline(hir_id, target, inline);
1151
1152 if let Some(span) = rust_logo
1153 && !self.tcx.features().rustdoc_internals()
1154 {
1155 feature_err(
1156 &self.tcx.sess,
1157 sym::rustdoc_internals,
1158 *span,
1159 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `#[doc(rust_logo)]` attribute is used for Rust branding"))inline_fluent!("the `#[doc(rust_logo)]` attribute is used for Rust branding"),
1160 )
1161 .emit();
1162 }
1163
1164 if let Some(span) = masked {
1165 self.check_doc_masked(*span, hir_id, target);
1166 }
1167 }
1168
1169 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1170 if {
{
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::FfiConst(_)) =>
{
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, AttributeKind::FfiConst(_)) {
1171 self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1173 }
1174 }
1175
1176 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1178 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1179 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
} => true,
_ => false,
}matches!(
1180 param.kind,
1181 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1182 )
1183 && #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1184 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1185 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1186 && let hir::ItemKind::Impl(impl_) = item.kind
1187 && let Some(of_trait) = impl_.of_trait
1188 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1189 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1190 {
1191 return;
1192 }
1193
1194 self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1195 }
1196
1197 fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1199 if target == Target::ForeignMod
1200 && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1201 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1202 && !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::Rust => true,
_ => false,
}matches!(abi, ExternAbi::Rust)
1203 {
1204 return;
1205 }
1206
1207 self.tcx.emit_node_span_lint(
1208 UNUSED_ATTRIBUTES,
1209 hir_id,
1210 attr_span,
1211 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1212 );
1213 }
1214
1215 fn check_rustc_legacy_const_generics(
1217 &self,
1218 item: Option<ItemLike<'_>>,
1219 attr_span: Span,
1220 index_list: &ThinVec<(usize, Span)>,
1221 ) {
1222 let Some(ItemLike::Item(Item {
1223 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1224 ..
1225 })) = item
1226 else {
1227 return;
1229 };
1230
1231 for param in generics.params {
1232 match param.kind {
1233 hir::GenericParamKind::Const { .. } => {}
1234 _ => {
1235 self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1236 attr_span,
1237 param_span: param.span,
1238 });
1239 return;
1240 }
1241 }
1242 }
1243
1244 if index_list.len() != generics.params.len() {
1245 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1246 attr_span,
1247 generics_span: generics.span,
1248 });
1249 return;
1250 }
1251
1252 let arg_count = decl.inputs.len() + generics.params.len();
1253 for (index, span) in index_list {
1254 if *index >= arg_count {
1255 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1256 span: *span,
1257 arg_count,
1258 });
1259 }
1260 }
1261 }
1262
1263 fn check_repr(
1265 &self,
1266 attrs: &[Attribute],
1267 span: Span,
1268 target: Target,
1269 item: Option<ItemLike<'_>>,
1270 hir_id: HirId,
1271 ) {
1272 let (reprs, first_attr_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Repr {
reprs, first_span }) => {
break 'done Some((reprs.as_slice(), Some(*first_span)));
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span))).unwrap_or((&[], None));
1278
1279 let mut int_reprs = 0;
1280 let mut is_explicit_rust = false;
1281 let mut is_c = false;
1282 let mut is_simd = false;
1283 let mut is_transparent = false;
1284
1285 for (repr, repr_span) in reprs {
1286 match repr {
1287 ReprAttr::ReprRust => {
1288 is_explicit_rust = true;
1289 match target {
1290 Target::Struct | Target::Union | Target::Enum => continue,
1291 _ => {
1292 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1293 hint_span: *repr_span,
1294 span,
1295 });
1296 }
1297 }
1298 }
1299 ReprAttr::ReprC => {
1300 is_c = true;
1301 match target {
1302 Target::Struct | Target::Union | Target::Enum => continue,
1303 _ => {
1304 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1305 hint_span: *repr_span,
1306 span,
1307 });
1308 }
1309 }
1310 }
1311 ReprAttr::ReprAlign(align) => {
1312 match target {
1313 Target::Struct | Target::Union | Target::Enum => {}
1314 Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1315 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1316 span: *repr_span,
1317 item: target.plural_name(),
1318 });
1319 }
1320 Target::Static if self.tcx.features().static_align() => {
1321 self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1322 span: *repr_span,
1323 item: target.plural_name(),
1324 });
1325 }
1326 _ => {
1327 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1328 hint_span: *repr_span,
1329 span,
1330 });
1331 }
1332 }
1333
1334 self.check_align(*align, *repr_span);
1335 }
1336 ReprAttr::ReprPacked(_) => {
1337 if target != Target::Struct && target != Target::Union {
1338 self.dcx().emit_err(errors::AttrApplication::StructUnion {
1339 hint_span: *repr_span,
1340 span,
1341 });
1342 } else {
1343 continue;
1344 }
1345 }
1346 ReprAttr::ReprSimd => {
1347 is_simd = true;
1348 if target != Target::Struct {
1349 self.dcx().emit_err(errors::AttrApplication::Struct {
1350 hint_span: *repr_span,
1351 span,
1352 });
1353 } else {
1354 continue;
1355 }
1356 }
1357 ReprAttr::ReprTransparent => {
1358 is_transparent = true;
1359 match target {
1360 Target::Struct | Target::Union | Target::Enum => continue,
1361 _ => {
1362 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1363 hint_span: *repr_span,
1364 span,
1365 });
1366 }
1367 }
1368 }
1369 ReprAttr::ReprInt(_) => {
1370 int_reprs += 1;
1371 if target != Target::Enum {
1372 self.dcx().emit_err(errors::AttrApplication::Enum {
1373 hint_span: *repr_span,
1374 span,
1375 });
1376 } else {
1377 continue;
1378 }
1379 }
1380 };
1381 }
1382
1383 if let Some(first_attr_span) = first_attr_span
1385 && reprs.is_empty()
1386 && item.is_some()
1387 {
1388 match target {
1389 Target::Struct | Target::Union | Target::Enum => {}
1390 Target::Fn | Target::Method(_) => {
1391 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1392 span: first_attr_span,
1393 item: target.plural_name(),
1394 });
1395 }
1396 _ => {
1397 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1398 hint_span: first_attr_span,
1399 span,
1400 });
1401 }
1402 }
1403 return;
1404 }
1405
1406 let hint_spans = reprs.iter().map(|(_, span)| *span);
1409
1410 if is_transparent && reprs.len() > 1 {
1412 let hint_spans = hint_spans.clone().collect();
1413 self.dcx().emit_err(errors::TransparentIncompatible {
1414 hint_spans,
1415 target: target.to_string(),
1416 });
1417 }
1418 if is_transparent
1421 && let Some(&pass_indirectly_span) =
1422 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcPassIndirectlyInNonRusticAbis(span))
=> {
break 'done Some(span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::RustcPassIndirectlyInNonRusticAbis(span) => span)
1423 {
1424 self.dcx().emit_err(errors::TransparentIncompatible {
1425 hint_spans: <[_]>::into_vec(::alloc::boxed::box_new([span, pass_indirectly_span]))vec![span, pass_indirectly_span],
1426 target: target.to_string(),
1427 });
1428 }
1429 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1430 let hint_spans = hint_spans.clone().collect();
1431 self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1432 }
1433 if (int_reprs > 1)
1435 || (is_simd && is_c)
1436 || (int_reprs == 1
1437 && is_c
1438 && item.is_some_and(|item| {
1439 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1440 }))
1441 {
1442 self.tcx.emit_node_span_lint(
1443 CONFLICTING_REPR_HINTS,
1444 hir_id,
1445 hint_spans.collect::<Vec<Span>>(),
1446 errors::ReprConflictingLint,
1447 );
1448 }
1449 }
1450
1451 fn check_align(&self, align: Align, span: Span) {
1452 if align.bytes() > 2_u64.pow(29) {
1453 self.dcx().span_delayed_bug(
1455 span,
1456 "alignment greater than 2^29 should be errored on elsewhere",
1457 );
1458 } else {
1459 let max = Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64;
1464 if align.bytes() > max {
1465 self.dcx().emit_err(errors::InvalidReprAlignForTarget { span, size: max });
1466 }
1467 }
1468 }
1469
1470 fn check_macro_only_attr(
1475 &self,
1476 attr_span: Span,
1477 span: Span,
1478 target: Target,
1479 attrs: &[Attribute],
1480 ) {
1481 match target {
1482 Target::Fn => {
1483 for attr in attrs {
1484 if attr.is_proc_macro_attr() {
1485 return;
1487 }
1488 }
1489 self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1490 }
1491 _ => {}
1492 }
1493 }
1494
1495 fn check_rustc_allow_const_fn_unstable(
1498 &self,
1499 hir_id: HirId,
1500 attr_span: Span,
1501 span: Span,
1502 target: Target,
1503 ) {
1504 match target {
1505 Target::Fn | Target::Method(_) => {
1506 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1507 self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1508 }
1509 }
1510 _ => {}
1511 }
1512 }
1513
1514 fn check_stability(
1515 &self,
1516 attr_span: Span,
1517 item_span: Span,
1518 level: &StabilityLevel,
1519 feature: Symbol,
1520 ) {
1521 if level.is_unstable()
1524 && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1525 {
1526 self.tcx
1527 .dcx()
1528 .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1529 }
1530 }
1531
1532 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1533 match target {
1534 Target::AssocConst | Target::Method(..) | Target::AssocTy
1535 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1536 == DefKind::Impl { of_trait: true } =>
1537 {
1538 self.tcx.emit_node_span_lint(
1539 UNUSED_ATTRIBUTES,
1540 hir_id,
1541 attr_span,
1542 errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1543 );
1544 }
1545 _ => {}
1546 }
1547 }
1548
1549 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1550 if target != Target::MacroDef {
1551 return;
1552 }
1553
1554 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1556 let is_decl_macro = !macro_definition.macro_rules;
1557
1558 if is_decl_macro {
1559 self.tcx.emit_node_span_lint(
1560 UNUSED_ATTRIBUTES,
1561 hir_id,
1562 attr_span,
1563 errors::MacroExport::OnDeclMacro,
1564 );
1565 }
1566 }
1567
1568 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1569 let note = if attr.has_any_name(&[
1572 sym::allow,
1573 sym::expect,
1574 sym::warn,
1575 sym::deny,
1576 sym::forbid,
1577 sym::feature,
1578 ]) && attr.meta_item_list().is_some_and(|list| list.is_empty())
1579 {
1580 errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1581 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1582 && let Some(meta) = attr.meta_item_list()
1583 && let [meta] = meta.as_slice()
1584 && let Some(item) = meta.meta_item()
1585 && let MetaItemKind::NameValue(_) = &item.kind
1586 && item.path == sym::reason
1587 {
1588 errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1589 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1590 && let Some(meta) = attr.meta_item_list()
1591 && meta.iter().any(|meta| {
1592 meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
1593 })
1594 {
1595 if hir_id != CRATE_HIR_ID {
1596 match style {
1597 Some(ast::AttrStyle::Outer) => {
1598 let attr_span = attr.span();
1599 let bang_position = self
1600 .tcx
1601 .sess
1602 .source_map()
1603 .span_until_char(attr_span, '[')
1604 .shrink_to_hi();
1605
1606 self.tcx.emit_node_span_lint(
1607 UNUSED_ATTRIBUTES,
1608 hir_id,
1609 attr_span,
1610 errors::OuterCrateLevelAttr {
1611 suggestion: errors::OuterCrateLevelAttrSuggestion { bang_position },
1612 },
1613 )
1614 }
1615 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1616 UNUSED_ATTRIBUTES,
1617 hir_id,
1618 attr.span(),
1619 errors::InnerCrateLevelAttr,
1620 ),
1621 };
1622 return;
1623 } else {
1624 let never_needs_link = self
1625 .tcx
1626 .crate_types()
1627 .iter()
1628 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1629 if never_needs_link {
1630 errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1631 } else {
1632 return;
1633 }
1634 }
1635 } else if attr.has_name(sym::default_method_body_is_const) {
1636 errors::UnusedNote::DefaultMethodBodyConst
1637 } else {
1638 return;
1639 };
1640
1641 self.tcx.emit_node_span_lint(
1642 UNUSED_ATTRIBUTES,
1643 hir_id,
1644 attr.span(),
1645 errors::Unused { attr_span: attr.span(), note },
1646 );
1647 }
1648
1649 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1653 if target != Target::Fn {
1654 return;
1655 }
1656
1657 let tcx = self.tcx;
1658 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1659 return;
1660 };
1661 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1662 return;
1663 };
1664
1665 let def_id = hir_id.expect_owner().def_id;
1666 let param_env = ty::ParamEnv::empty();
1667
1668 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1669 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1670
1671 let span = tcx.def_span(def_id);
1672 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1673 let sig = tcx.liberate_late_bound_regions(
1674 def_id.to_def_id(),
1675 tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
1676 );
1677
1678 let mut cause = ObligationCause::misc(span, def_id);
1679 let sig = ocx.normalize(&cause, param_env, sig);
1680
1681 let errors = ocx.try_evaluate_obligations();
1683 if !errors.is_empty() {
1684 return;
1685 }
1686
1687 let expected_sig = tcx.mk_fn_sig(
1688 std::iter::repeat_n(
1689 token_stream,
1690 match kind {
1691 ProcMacroKind::Attribute => 2,
1692 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1693 },
1694 ),
1695 token_stream,
1696 false,
1697 Safety::Safe,
1698 ExternAbi::Rust,
1699 );
1700
1701 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1702 let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
1703
1704 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1705 if let Some(hir_sig) = hir_sig {
1706 match terr {
1707 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1708 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1709 diag.span(ty.span);
1710 cause.span = ty.span;
1711 } else if idx == hir_sig.decl.inputs.len() {
1712 let span = hir_sig.decl.output.span();
1713 diag.span(span);
1714 cause.span = span;
1715 }
1716 }
1717 TypeError::ArgCount => {
1718 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1719 diag.span(ty.span);
1720 cause.span = ty.span;
1721 }
1722 }
1723 TypeError::SafetyMismatch(_) => {
1724 }
1726 TypeError::AbiMismatch(_) => {
1727 }
1729 TypeError::VariadicMismatch(_) => {
1730 }
1732 _ => {}
1733 }
1734 }
1735
1736 infcx.err_ctxt().note_type_err(
1737 &mut diag,
1738 &cause,
1739 None,
1740 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1741 expected: ty::Binder::dummy(expected_sig),
1742 found: ty::Binder::dummy(sig),
1743 }))),
1744 terr,
1745 false,
1746 None,
1747 );
1748 diag.emit();
1749 self.abort.set(true);
1750 }
1751
1752 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1753 if !errors.is_empty() {
1754 infcx.err_ctxt().report_fulfillment_errors(errors);
1755 self.abort.set(true);
1756 }
1757 }
1758
1759 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1760 if !{
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Repr { reprs, ..
}) => {
break 'done
Some(reprs.iter().any(|(r, _)|
r == &ReprAttr::ReprTransparent));
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Repr { reprs, .. } => reprs.iter().any(|(r, _)| r == &ReprAttr::ReprTransparent))
1761 .unwrap_or(false)
1762 {
1763 self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
1764 }
1765 }
1766
1767 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1768 if let (Target::Closure, None) = (
1769 target,
1770 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
1771 ) {
1772 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!(
1773 self.tcx.hir_expect_expr(hir_id).kind,
1774 hir::ExprKind::Closure(hir::Closure {
1775 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1776 ..
1777 })
1778 );
1779 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1780 let parent_span = self.tcx.def_span(parent_did);
1781
1782 if let Some(attr_span) = {
'done:
{
for i in self.tcx.get_all_attrs(parent_did) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
_ => {}
}
}
None
}
}find_attr!(
1783 self.tcx.get_all_attrs(parent_did),
1784 AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1785 ) && is_coro
1786 {
1787 self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
1788 }
1789 }
1790 }
1791
1792 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1793 if let Some(export_name_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::ExportName {
span: export_name_span, .. }) => {
break 'done Some(*export_name_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::ExportName { span: export_name_span, .. } => *export_name_span)
1794 && let Some(no_mangle_span) =
1795 {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoMangle(no_mangle_span))
=> {
break 'done Some(*no_mangle_span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::NoMangle(no_mangle_span) => *no_mangle_span)
1796 {
1797 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1798 "#[unsafe(no_mangle)]"
1799 } else {
1800 "#[no_mangle]"
1801 };
1802 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1803 "#[unsafe(export_name)]"
1804 } else {
1805 "#[export_name]"
1806 };
1807
1808 self.tcx.emit_node_span_lint(
1809 lint::builtin::UNUSED_ATTRIBUTES,
1810 hir_id,
1811 no_mangle_span,
1812 errors::MixedExportNameAndNoMangle {
1813 no_mangle_span,
1814 export_name_span,
1815 no_mangle_attr,
1816 export_name_attr,
1817 },
1818 );
1819 }
1820 }
1821
1822 fn check_autodiff(&self, _hir_id: HirId, _attr: &Attribute, span: Span, target: Target) {
1824 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_passes/src/check_attr.rs:1824",
"rustc_passes::check_attr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/check_attr.rs"),
::tracing_core::__macro_support::Option::Some(1824u32),
::tracing_core::__macro_support::Option::Some("rustc_passes::check_attr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_autodiff")
as &dyn Value))])
});
} else { ; }
};debug!("check_autodiff");
1825 match target {
1826 Target::Fn => {}
1827 _ => {
1828 self.dcx().emit_err(errors::AutoDiffAttr { attr_span: span });
1829 self.abort.set(true);
1830 }
1831 }
1832 }
1833
1834 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1835 let node_span = self.tcx.hir_span(hir_id);
1836
1837 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1838 return; }
1840
1841 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
{
hir::ExprKind::Loop(..) => true,
_ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Loop(..)) {
1842 self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
1843 };
1844 }
1845
1846 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1847 let node_span = self.tcx.hir_span(hir_id);
1848
1849 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1850 return; }
1852
1853 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.hir_expect_expr(hir_id).kind
{
hir::ExprKind::Break(..) => true,
_ => false,
}matches!(self.tcx.hir_expect_expr(hir_id).kind, hir::ExprKind::Break(..)) {
1854 self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
1855 };
1856 }
1857
1858 fn check_custom_mir(
1859 &self,
1860 dialect: Option<(MirDialect, Span)>,
1861 phase: Option<(MirPhase, Span)>,
1862 attr_span: Span,
1863 ) {
1864 let Some((dialect, dialect_span)) = dialect else {
1865 if let Some((_, phase_span)) = phase {
1866 self.dcx()
1867 .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
1868 }
1869 return;
1870 };
1871
1872 match dialect {
1873 MirDialect::Analysis => {
1874 if let Some((MirPhase::Optimized, phase_span)) = phase {
1875 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1876 dialect,
1877 phase: MirPhase::Optimized,
1878 attr_span,
1879 dialect_span,
1880 phase_span,
1881 });
1882 }
1883 }
1884
1885 MirDialect::Built => {
1886 if let Some((phase, phase_span)) = phase {
1887 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1888 dialect,
1889 phase,
1890 attr_span,
1891 dialect_span,
1892 phase_span,
1893 });
1894 }
1895 }
1896 MirDialect::Runtime => {}
1897 }
1898 }
1899}
1900
1901impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1902 type NestedFilter = nested_filter::OnlyBodies;
1903
1904 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1905 self.tcx
1906 }
1907
1908 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1909 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1913 let def_id = item.owner_id.to_def_id();
1914 if macro_def.macro_rules
1915 && !{
{
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::MacroExport { ..
}) => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.tcx.get_all_attrs(def_id), AttributeKind::MacroExport { .. })
1916 {
1917 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1918 }
1919 }
1920
1921 let target = Target::from_item(item);
1922 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1923 intravisit::walk_item(self, item)
1924 }
1925
1926 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1927 let spans = self
1932 .tcx
1933 .hir_attrs(where_predicate.hir_id)
1934 .iter()
1935 .filter(|attr| {
1937 #[allow(non_exhaustive_omitted_patterns)] match attr {
Attribute::Parsed(AttributeKind::DocComment { .. } |
AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
_ => false,
}matches!(
1938 attr,
1939 Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
1940 | Attribute::Unparsed(_)
1941 )
1942 })
1943 .map(|attr| attr.span())
1944 .collect::<Vec<_>>();
1945 if !spans.is_empty() {
1946 self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
1947 }
1948 self.check_attributes(
1949 where_predicate.hir_id,
1950 where_predicate.span,
1951 Target::WherePredicate,
1952 None,
1953 );
1954 intravisit::walk_where_predicate(self, where_predicate)
1955 }
1956
1957 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1958 let target = Target::from_generic_param(generic_param);
1959 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1960 intravisit::walk_generic_param(self, generic_param)
1961 }
1962
1963 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1964 let target = Target::from_trait_item(trait_item);
1965 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1966 intravisit::walk_trait_item(self, trait_item)
1967 }
1968
1969 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1970 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1971 intravisit::walk_field_def(self, struct_field);
1972 }
1973
1974 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1975 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1976 intravisit::walk_arm(self, arm);
1977 }
1978
1979 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1980 let target = Target::from_foreign_item(f_item);
1981 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1982 intravisit::walk_foreign_item(self, f_item)
1983 }
1984
1985 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1986 let target = target_from_impl_item(self.tcx, impl_item);
1987 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1988 intravisit::walk_impl_item(self, impl_item)
1989 }
1990
1991 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1992 if let hir::StmtKind::Let(l) = stmt.kind {
1994 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1995 }
1996 intravisit::walk_stmt(self, stmt)
1997 }
1998
1999 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2000 let target = match expr.kind {
2001 hir::ExprKind::Closure { .. } => Target::Closure,
2002 _ => Target::Expression,
2003 };
2004
2005 self.check_attributes(expr.hir_id, expr.span, target, None);
2006 intravisit::walk_expr(self, expr)
2007 }
2008
2009 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2010 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2011 intravisit::walk_expr_field(self, field)
2012 }
2013
2014 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2015 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2016 intravisit::walk_variant(self, variant)
2017 }
2018
2019 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2020 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2021
2022 intravisit::walk_param(self, param);
2023 }
2024
2025 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2026 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2027 intravisit::walk_pat_field(self, field);
2028 }
2029}
2030
2031fn is_c_like_enum(item: &Item<'_>) -> bool {
2032 if let ItemKind::Enum(_, _, ref def) = item.kind {
2033 for variant in def.variants {
2034 match variant.data {
2035 hir::VariantData::Unit(..) => { }
2036 _ => return false,
2037 }
2038 }
2039 true
2040 } else {
2041 false
2042 }
2043}
2044
2045fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2048 const ATTRS_TO_CHECK: &[Symbol] =
2052 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2053
2054 for attr in attrs {
2055 let (span, name) = if let Some(a) =
2057 ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2058 {
2059 (attr.span(), *a)
2060 } else if let Attribute::Parsed(AttributeKind::Repr {
2061 reprs: _,
2062 first_span: first_attr_span,
2063 }) = attr
2064 {
2065 (*first_attr_span, sym::repr)
2066 } else {
2067 continue;
2068 };
2069
2070 let item = tcx
2071 .hir_free_items()
2072 .map(|id| tcx.hir_item(id))
2073 .find(|item| !item.span.is_dummy()) .map(|item| errors::ItemFollowingInnerAttr {
2075 span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2076 kind: tcx.def_descr(item.owner_id.to_def_id()),
2077 });
2078 let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2079 span,
2080 sugg_span: tcx
2081 .sess
2082 .source_map()
2083 .span_to_snippet(span)
2084 .ok()
2085 .filter(|src| src.starts_with("#!["))
2086 .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2087 name,
2088 item,
2089 });
2090
2091 if let Attribute::Unparsed(p) = attr {
2092 tcx.dcx().try_steal_replace_and_emit_err(
2093 p.path.span,
2094 StashKey::UndeterminedMacroResolution,
2095 err,
2096 );
2097 } else {
2098 err.emit();
2099 }
2100 }
2101}
2102
2103fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2104 let attrs = tcx.hir_attrs(item.hir_id());
2105
2106 if let Some(attr_span) = {
'done:
{
for i in attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Inline(i, span))
if
!#[allow(non_exhaustive_omitted_patterns)] match i {
InlineAttr::Force { .. } => true,
_ => false,
} => {
break 'done Some(*span);
}
_ => {}
}
}
None
}
}find_attr!(attrs, AttributeKind::Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
2107 {
2108 tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2109 }
2110}
2111
2112fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2113 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2114 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2115 if module_def_id.to_local_def_id().is_top_level_module() {
2116 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2117 check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2118 }
2119 if check_attr_visitor.abort.get() {
2120 tcx.dcx().abort_if_errors()
2121 }
2122}
2123
2124pub(crate) fn provide(providers: &mut Providers) {
2125 *providers = Providers { check_mod_attrs, ..*providers };
2126}
2127
2128fn check_duplicates(
2130 tcx: TyCtxt<'_>,
2131 attr_span: Span,
2132 attr: &Attribute,
2133 hir_id: HirId,
2134 duplicates: AttributeDuplicates,
2135 seen: &mut FxHashMap<Symbol, Span>,
2136) {
2137 use AttributeDuplicates::*;
2138 if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
WarnFollowingWordOnly => true,
_ => false,
}matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2139 return;
2140 }
2141 let attr_name = attr.name().unwrap();
2142 match duplicates {
2143 DuplicatesOk => {}
2144 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2145 match seen.entry(attr_name) {
2146 Entry::Occupied(mut entry) => {
2147 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnPreceding => true,
_ => false,
}matches!(duplicates, FutureWarnPreceding) {
2148 let to_remove = entry.insert(attr_span);
2149 (to_remove, attr_span)
2150 } else {
2151 (attr_span, *entry.get())
2152 };
2153 tcx.emit_node_span_lint(
2154 UNUSED_ATTRIBUTES,
2155 hir_id,
2156 this,
2157 errors::UnusedDuplicate {
2158 this,
2159 other,
2160 warning: #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnFollowing | FutureWarnPreceding => true,
_ => false,
}matches!(
2161 duplicates,
2162 FutureWarnFollowing | FutureWarnPreceding
2163 ),
2164 },
2165 );
2166 }
2167 Entry::Vacant(entry) => {
2168 entry.insert(attr_span);
2169 }
2170 }
2171 }
2172 ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2173 Entry::Occupied(mut entry) => {
2174 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
ErrorPreceding => true,
_ => false,
}matches!(duplicates, ErrorPreceding) {
2175 let to_remove = entry.insert(attr_span);
2176 (to_remove, attr_span)
2177 } else {
2178 (attr_span, *entry.get())
2179 };
2180 tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2181 }
2182 Entry::Vacant(entry) => {
2183 entry.insert(attr_span);
2184 }
2185 },
2186 }
2187}
2188
2189fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2190 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2191 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2192 fn_ptr_ty.decl.inputs.len() == 1
2193 } else {
2194 false
2195 }
2196 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2197 && let Some(&[hir::GenericArg::Type(ty)]) =
2198 path.segments.last().map(|last| last.args().args)
2199 {
2200 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2201 } else {
2202 false
2203 })
2204}