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::RustcClean(..)
298 | AttributeKind::RustcCoherenceIsCore(..)
299 | AttributeKind::RustcCoinductive(..)
300 | AttributeKind::RustcConfusables { .. }
301 | AttributeKind::RustcConstStabilityIndirect
302 | AttributeKind::RustcDeallocator
303 | AttributeKind::RustcDenyExplicitImpl(..)
304 | AttributeKind::RustcDummy
305 | AttributeKind::RustcDumpDefParents
306 | AttributeKind::RustcDumpItemBounds
307 | AttributeKind::RustcDumpPredicates
308 | AttributeKind::RustcDumpUserArgs
309 | AttributeKind::RustcDumpVtable(..)
310 | AttributeKind::RustcDynIncompatibleTrait(..)
311 | AttributeKind::RustcEffectiveVisibility
312 | AttributeKind::RustcHasIncoherentInherentImpls
313 | AttributeKind::RustcHiddenTypeOfOpaques
314 | AttributeKind::RustcIfThisChanged(..)
315 | AttributeKind::RustcLayout(..)
316 | AttributeKind::RustcLayoutScalarValidRangeEnd(..)
317 | AttributeKind::RustcLayoutScalarValidRangeStart(..)
318 | AttributeKind::RustcLintOptDenyFieldAccess { .. }
319 | AttributeKind::RustcLintOptTy
320 | AttributeKind::RustcLintQueryInstability
321 | AttributeKind::RustcLintUntrackedQueryInformation
322 | AttributeKind::RustcMacroTransparency(_)
323 | AttributeKind::RustcMain
324 | AttributeKind::RustcMir(_)
325 | AttributeKind::RustcNeverReturnsNullPointer
326 | AttributeKind::RustcNoImplicitAutorefs
327 | AttributeKind::RustcNonConstTraitMethod
328 | AttributeKind::RustcNounwind
329 | AttributeKind::RustcObjcClass { .. }
330 | AttributeKind::RustcObjcSelector { .. }
331 | AttributeKind::RustcOffloadKernel
332 | AttributeKind::RustcParenSugar(..)
333 | AttributeKind::RustcPassByValue (..)
334 | AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)
335 | AttributeKind::RustcPreserveUbChecks
336 | AttributeKind::RustcReallocator
337 | AttributeKind::RustcScalableVector { .. }
338 | AttributeKind::RustcShouldNotBeCalledOnConstItems(..)
339 | AttributeKind::RustcSimdMonomorphizeLaneLimit(..)
340 | AttributeKind::RustcSkipDuringMethodDispatch { .. }
341 | AttributeKind::RustcSpecializationTrait(..)
342 | AttributeKind::RustcStdInternalSymbol (..)
343 | AttributeKind::RustcThenThisWouldNeed(..)
344 | AttributeKind::RustcUnsafeSpecializationMarker(..)
345 | AttributeKind::RustcVariance
346 | AttributeKind::RustcVarianceOfOpaques
347 | AttributeKind::ShouldPanic { .. }
348 | AttributeKind::ThreadLocal
349 | AttributeKind::TypeConst{..}
350 | AttributeKind::TypeLengthLimit { .. }
351 | AttributeKind::UnstableFeatureBound(..)
352 | AttributeKind::Used { .. }
353 | AttributeKind::WindowsSubsystem(..)
354 ) => { }
356 Attribute::Unparsed(attr_item) => {
357 style = Some(attr_item.style);
358 match attr.path().as_slice() {
359 [sym::diagnostic, sym::on_unimplemented, ..] => {
360 self.check_diagnostic_on_unimplemented(attr.span(), hir_id, target)
361 }
362 [sym::diagnostic, sym::on_const, ..] => {
363 self.check_diagnostic_on_const(attr.span(), hir_id, target, item)
364 }
365 [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => {
366 self.check_autodiff(hir_id, attr, span, target)
367 }
368 [
369 sym::allow
371 | sym::expect
372 | sym::warn
373 | sym::deny
374 | sym::forbid
375 | sym::deprecated_safe | sym::prelude_import
379 | sym::panic_handler
380 | sym::lang
381 | sym::default_lib_allocator
382 | sym::rustc_diagnostic_item
383 | sym::rustc_no_mir_inline
384 | sym::rustc_insignificant_dtor
385 | sym::rustc_nonnull_optimization_guaranteed
386 | sym::rustc_intrinsic
387 | sym::rustc_inherit_overflow_checks
388 | sym::rustc_intrinsic_const_stable_indirect
389 | sym::rustc_trivial_field_reads
390 | sym::rustc_on_unimplemented
391 | sym::rustc_do_not_const_check
392 | sym::rustc_reservation_impl
393 | sym::rustc_doc_primitive
394 | sym::rustc_conversion_suggestion
395 | sym::rustc_deprecated_safe_2024
396 | sym::rustc_test_marker
397 | sym::rustc_layout
398 | sym::rustc_proc_macro_decls
399 | sym::rustc_never_type_options
400 | sym::rustc_autodiff
401 | sym::rustc_capture_analysis
402 | sym::rustc_regions
403 | sym::rustc_strict_coherence
404 | sym::rustc_mir
405 | sym::rustc_outlives
406 | sym::rustc_symbol_name
407 | sym::rustc_evaluate_where_clauses
408 | sym::rustc_delayed_bug_from_inside_query
409 | sym::rustc_def_path
410 | sym::rustc_partition_reused
411 | sym::rustc_partition_codegened
412 | sym::rustc_expected_cgu_reuse
413 | sym::feature
415 | sym::register_tool
416 | sym::rustc_no_implicit_bounds
417 | sym::test_runner,
418 ..
419 ] => {}
420 [name, rest@..] => {
421 match BUILTIN_ATTRIBUTE_MAP.get(name) {
422 Some(_) => {
423 if rest.len() > 0 && AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(name)) {
424 continue
428 }
429
430 ::rustc_middle::util::bug::span_bug_fmt(attr.span(),
format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
name))span_bug!(
431 attr.span(),
432 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
433 )
434 }
435 None => (),
436 }
437 }
438 [] => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
439 }
440 }
441 }
442
443 if hir_id != CRATE_HIR_ID {
444 match attr {
445 Attribute::Parsed(_) => { }
446 Attribute::Unparsed(attr) => {
447 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
450 attr.path
451 .segments
452 .first()
453 .and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
454 {
455 match attr.style {
456 ast::AttrStyle::Outer => {
457 let attr_span = attr.span;
458 let bang_position = self
459 .tcx
460 .sess
461 .source_map()
462 .span_until_char(attr_span, '[')
463 .shrink_to_hi();
464
465 self.tcx.emit_node_span_lint(
466 UNUSED_ATTRIBUTES,
467 hir_id,
468 attr.span,
469 errors::OuterCrateLevelAttr {
470 suggestion: errors::OuterCrateLevelAttrSuggestion {
471 bang_position,
472 },
473 },
474 )
475 }
476 ast::AttrStyle::Inner => self.tcx.emit_node_span_lint(
477 UNUSED_ATTRIBUTES,
478 hir_id,
479 attr.span,
480 errors::InnerCrateLevelAttr,
481 ),
482 }
483 }
484 }
485 }
486 }
487
488 if let Attribute::Unparsed(unparsed_attr) = attr
489 && let Some(BuiltinAttribute { duplicates, .. }) =
490 attr.name().and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name))
491 {
492 check_duplicates(
493 self.tcx,
494 unparsed_attr.span,
495 attr,
496 hir_id,
497 *duplicates,
498 &mut seen,
499 );
500 }
501
502 self.check_unused_attribute(hir_id, attr, style)
503 }
504
505 self.check_repr(attrs, span, target, item, hir_id);
506 self.check_rustc_force_inline(hir_id, attrs, target);
507 self.check_mix_no_mangle_export(hir_id, attrs);
508 }
509
510 fn check_rustc_must_implement_one_of(
511 &self,
512 attr_span: Span,
513 list: &ThinVec<Ident>,
514 hir_id: HirId,
515 target: Target,
516 ) {
517 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
520 return;
521 }
522
523 let def_id = hir_id.owner.def_id;
524
525 let items = self.tcx.associated_items(def_id);
526 for ident in list {
529 let item = items
530 .filter_by_name_unhygienic(ident.name)
531 .find(|item| item.ident(self.tcx) == *ident);
532
533 match item {
534 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
535 if !item.defaultness(self.tcx).has_value() {
536 self.tcx.dcx().emit_err(errors::FunctionNotHaveDefaultImplementation {
537 span: self.tcx.def_span(item.def_id),
538 note_span: attr_span,
539 });
540 }
541 }
542 Some(item) => {
543 self.dcx().emit_err(errors::MustImplementNotFunction {
544 span: self.tcx.def_span(item.def_id),
545 span_note: errors::MustImplementNotFunctionSpanNote { span: attr_span },
546 note: errors::MustImplementNotFunctionNote {},
547 });
548 }
549 None => {
550 self.dcx().emit_err(errors::FunctionNotFoundInTrait { span: ident.span });
551 }
552 }
553 }
554 let mut set: UnordMap<Symbol, Span> = Default::default();
557
558 for ident in &*list {
559 if let Some(dup) = set.insert(ident.name, ident.span) {
560 self.tcx
561 .dcx()
562 .emit_err(errors::FunctionNamesDuplicated { spans: <[_]>::into_vec(::alloc::boxed::box_new([dup, ident.span]))vec![dup, ident.span] });
563 }
564 }
565 }
566
567 fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
568 for EiiImpl { span, inner_span, resolution, impl_marked_unsafe, is_default: _ } in impls {
569 match target {
570 Target::Fn => {}
571 _ => {
572 self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
573 }
574 }
575
576 if let EiiImplResolution::Macro(eii_macro) = resolution
577 && {
{
'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)
578 && !impl_marked_unsafe
579 {
580 self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
581 span: *span,
582 name: self.tcx.item_name(*eii_macro),
583 suggestion: errors::EiiImplRequiresUnsafeSuggestion {
584 left: inner_span.shrink_to_lo(),
585 right: inner_span.shrink_to_hi(),
586 },
587 });
588 }
589 }
590 }
591
592 fn check_do_not_recommend(
594 &self,
595 attr_span: Span,
596 hir_id: HirId,
597 target: Target,
598 item: Option<ItemLike<'_>>,
599 ) {
600 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Impl { .. } => true,
_ => false,
}matches!(target, Target::Impl { .. })
601 || #[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!(
602 item,
603 Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl),.. }))
604 if _impl.of_trait.is_none()
605 )
606 {
607 self.tcx.emit_node_span_lint(
608 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
609 hir_id,
610 attr_span,
611 errors::IncorrectDoNotRecommendLocation,
612 );
613 }
614 }
615
616 fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) {
618 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
619 self.tcx.emit_node_span_lint(
620 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
621 hir_id,
622 attr_span,
623 DiagnosticOnUnimplementedOnlyForTraits,
624 );
625 }
626 }
627
628 fn check_diagnostic_on_const(
630 &self,
631 attr_span: Span,
632 hir_id: HirId,
633 target: Target,
634 item: Option<ItemLike<'_>>,
635 ) {
636 if target == (Target::Impl { of_trait: true }) {
637 match item.unwrap() {
638 ItemLike::Item(it) => match it.expect_impl().constness {
639 Constness::Const => {
640 let item_span = self.tcx.hir_span(hir_id);
641 self.tcx.emit_node_span_lint(
642 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
643 hir_id,
644 attr_span,
645 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
646 );
647 return;
648 }
649 Constness::NotConst => return,
650 },
651 ItemLike::ForeignItem => {}
652 }
653 }
654 let item_span = self.tcx.hir_span(hir_id);
655 self.tcx.emit_node_span_lint(
656 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
657 hir_id,
658 attr_span,
659 DiagnosticOnConstOnlyForTraitImpls { item_span },
660 );
661 }
662
663 fn check_inline(&self, hir_id: HirId, attr_span: Span, kind: &InlineAttr, target: Target) {
665 match target {
666 Target::Fn
667 | Target::Closure
668 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
669 if let Some(did) = hir_id.as_owner()
671 && self.tcx.def_kind(did).has_codegen_attrs()
672 && kind != &InlineAttr::Never
673 {
674 let attrs = self.tcx.codegen_fn_attrs(did);
675 if attrs.contains_extern_indicator() {
677 self.tcx.emit_node_span_lint(
678 UNUSED_ATTRIBUTES,
679 hir_id,
680 attr_span,
681 errors::InlineIgnoredForExported {},
682 );
683 }
684 }
685 }
686 _ => {}
687 }
688 }
689
690 fn check_sanitize(
693 &self,
694 attr_span: Span,
695 set: SanitizerSet,
696 target_span: Span,
697 target: Target,
698 ) {
699 let mut not_fn_impl_mod = None;
700 let mut no_body = None;
701
702 match target {
703 Target::Fn
704 | Target::Closure
705 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
706 | Target::Impl { .. }
707 | Target::Mod => return,
708 Target::Static
709 if set & !(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
712 == SanitizerSet::empty() =>
713 {
714 return;
715 }
716
717 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
720 no_body = Some(target_span);
721 }
722
723 _ => {
724 not_fn_impl_mod = Some(target_span);
725 }
726 }
727
728 self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
729 attr_span,
730 not_fn_impl_mod,
731 no_body,
732 help: (),
733 });
734 }
735
736 fn check_naked(&self, hir_id: HirId, target: Target) {
738 match target {
739 Target::Fn
740 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {
741 let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
742 let abi = fn_sig.header.abi;
743 if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() {
744 feature_err(
745 &self.tcx.sess,
746 sym::naked_functions_rustic_abi,
747 fn_sig.span,
748 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[naked]` is currently unstable on `extern \"{0}\"` functions",
abi.as_str()))
})format!(
749 "`#[naked]` is currently unstable on `extern \"{}\"` functions",
750 abi.as_str()
751 ),
752 )
753 .emit();
754 }
755 }
756 _ => {}
757 }
758 }
759
760 fn check_object_lifetime_default(&self, hir_id: HirId) {
762 let tcx = self.tcx;
763 if let Some(owner_id) = hir_id.as_owner()
764 && let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
765 {
766 for p in generics.params {
767 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
768 let default = tcx.object_lifetime_default(p.def_id);
769 let repr = match default {
770 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
771 ObjectLifetimeDefault::Static => "'static".to_owned(),
772 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
773 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
774 };
775 tcx.dcx().emit_err(errors::ObjectLifetimeErr { span: p.span, repr });
776 }
777 }
778 }
779
780 fn check_track_caller(
782 &self,
783 hir_id: HirId,
784 attr_span: Span,
785 attrs: &[Attribute],
786 target: Target,
787 ) {
788 match target {
789 Target::Fn => {
790 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
793 && let Some(item) = hir::LangItem::from_name(lang_item)
794 && item.is_weak()
795 {
796 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
797
798 self.dcx().emit_err(errors::LangItemWithTrackCaller {
799 attr_span,
800 name: lang_item,
801 sig_span: sig.span,
802 });
803 }
804
805 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) {
806 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
807 for i in impls {
808 let name = match i.resolution {
809 EiiImplResolution::Macro(def_id) => self.tcx.item_name(def_id),
810 EiiImplResolution::Known(decl) => decl.name.name,
811 EiiImplResolution::Error(_eg) => continue,
812 };
813 self.dcx().emit_err(errors::EiiWithTrackCaller {
814 attr_span,
815 name,
816 sig_span: sig.span,
817 });
818 }
819 }
820 }
821 _ => {}
822 }
823 }
824
825 fn check_non_exhaustive(
827 &self,
828 attr_span: Span,
829 span: Span,
830 target: Target,
831 item: Option<ItemLike<'_>>,
832 ) {
833 match target {
834 Target::Struct => {
835 if let Some(ItemLike::Item(hir::Item {
836 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Struct { fields, .. }),
837 ..
838 })) = item
839 && !fields.is_empty()
840 && fields.iter().any(|f| f.default.is_some())
841 {
842 self.dcx().emit_err(errors::NonExhaustiveWithDefaultFieldValues {
843 attr_span,
844 defn_span: span,
845 });
846 }
847 }
848 _ => {}
849 }
850 }
851
852 fn check_target_feature(
854 &self,
855 hir_id: HirId,
856 attr_span: Span,
857 target: Target,
858 attrs: &[Attribute],
859 ) {
860 match target {
861 Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
862 | Target::Fn => {
863 if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
865 && !self.tcx.sess.target.is_like_wasm
868 && !self.tcx.sess.opts.actually_rustdoc
869 {
870 let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
871
872 self.dcx().emit_err(errors::LangItemWithTargetFeature {
873 attr_span,
874 name: lang_item,
875 sig_span: sig.span,
876 });
877 }
878 }
879 _ => {}
880 }
881 }
882
883 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
884 if let Some(location) = match target {
885 Target::AssocTy => {
886 if let DefKind::Impl { .. } =
887 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
888 {
889 Some("type alias in implementation block")
890 } else {
891 None
892 }
893 }
894 Target::AssocConst => {
895 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
896 let containing_item = self.tcx.hir_expect_item(parent_def_id);
897 let err = "associated constant in trait implementation block";
899 match containing_item.kind {
900 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
901 _ => None,
902 }
903 }
904 Target::Param => return,
906 Target::Expression
907 | Target::Statement
908 | Target::Arm
909 | Target::ForeignMod
910 | Target::Closure
911 | Target::Impl { .. }
912 | Target::WherePredicate => Some(target.name()),
913 Target::ExternCrate
914 | Target::Use
915 | Target::Static
916 | Target::Const
917 | Target::Fn
918 | Target::Mod
919 | Target::GlobalAsm
920 | Target::TyAlias
921 | Target::Enum
922 | Target::Variant
923 | Target::Struct
924 | Target::Field
925 | Target::Union
926 | Target::Trait
927 | Target::TraitAlias
928 | Target::Method(..)
929 | Target::ForeignFn
930 | Target::ForeignStatic
931 | Target::ForeignTy
932 | Target::GenericParam { .. }
933 | Target::MacroDef
934 | Target::PatField
935 | Target::ExprField
936 | Target::Crate
937 | Target::MacroCall
938 | Target::Delegation { .. } => None,
939 } {
940 self.tcx.dcx().emit_err(errors::DocAliasBadLocation { span, location });
941 return;
942 }
943 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
944 self.tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str: alias });
945 return;
946 }
947 }
948
949 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
950 let item_kind = match self.tcx.hir_node(hir_id) {
951 hir::Node::Item(item) => Some(&item.kind),
952 _ => None,
953 };
954 match item_kind {
955 Some(ItemKind::Impl(i)) => {
956 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
957 || if let Some(&[hir::GenericArg::Type(ty)]) = i
958 .of_trait
959 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
960 .map(|last_segment| last_segment.args().args)
961 {
962 #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
963 } else {
964 false
965 };
966 if !is_valid {
967 self.dcx().emit_err(errors::DocFakeVariadicNotValid { span });
968 }
969 }
970 _ => {
971 self.dcx().emit_err(errors::DocKeywordOnlyImpl { span });
972 }
973 }
974 }
975
976 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
977 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
978 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
979 return;
980 };
981 match item.kind {
982 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
983 if generics.params.len() != 0 => {}
984 ItemKind::Trait(_, _, _, _, generics, _, items)
985 if generics.params.len() != 0
986 || items.iter().any(|item| {
987 #[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)
988 }) => {}
989 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
990 _ => {
991 self.dcx().emit_err(errors::DocSearchUnboxInvalid { span });
992 }
993 }
994 }
995
996 fn check_doc_inline(&self, hir_id: HirId, target: Target, inline: &[(DocInline, Span)]) {
1006 let span = match inline {
1007 [] => return,
1008 [(_, span)] => *span,
1009 [(inline, span), rest @ ..] => {
1010 for (inline2, span2) in rest {
1011 if inline2 != inline {
1012 let mut spans = MultiSpan::from_spans(<[_]>::into_vec(::alloc::boxed::box_new([*span, *span2]))vec![*span, *span2]);
1013 spans.push_span_label(*span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this attribute..."))inline_fluent!("this attribute..."));
1014 spans.push_span_label(
1015 *span2,
1016 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{\".\"}..conflicts with this attribute"))inline_fluent!("{\".\"}..conflicts with this attribute"),
1017 );
1018 self.dcx().emit_err(errors::DocInlineConflict { spans });
1019 return;
1020 }
1021 }
1022 *span
1023 }
1024 };
1025
1026 match target {
1027 Target::Use | Target::ExternCrate => {}
1028 _ => {
1029 self.tcx.emit_node_span_lint(
1030 INVALID_DOC_ATTRIBUTES,
1031 hir_id,
1032 span,
1033 errors::DocInlineOnlyUse {
1034 attr_span: span,
1035 item_span: self.tcx.hir_span(hir_id),
1036 },
1037 );
1038 }
1039 }
1040 }
1041
1042 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
1043 if target != Target::ExternCrate {
1044 self.tcx.emit_node_span_lint(
1045 INVALID_DOC_ATTRIBUTES,
1046 hir_id,
1047 span,
1048 errors::DocMaskedOnlyExternCrate {
1049 attr_span: span,
1050 item_span: self.tcx.hir_span(hir_id),
1051 },
1052 );
1053 return;
1054 }
1055
1056 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
1057 self.tcx.emit_node_span_lint(
1058 INVALID_DOC_ATTRIBUTES,
1059 hir_id,
1060 span,
1061 errors::DocMaskedNotExternCrateSelf {
1062 attr_span: span,
1063 item_span: self.tcx.hir_span(hir_id),
1064 },
1065 );
1066 }
1067 }
1068
1069 fn check_doc_keyword_and_attribute(&self, span: Span, hir_id: HirId, attr_name: &'static str) {
1070 let item_kind = match self.tcx.hir_node(hir_id) {
1071 hir::Node::Item(item) => Some(&item.kind),
1072 _ => None,
1073 };
1074 match item_kind {
1075 Some(ItemKind::Mod(_, module)) => {
1076 if !module.item_ids.is_empty() {
1077 self.dcx().emit_err(errors::DocKeywordAttributeEmptyMod { span, attr_name });
1078 return;
1079 }
1080 }
1081 _ => {
1082 self.dcx().emit_err(errors::DocKeywordAttributeNotMod { span, attr_name });
1083 return;
1084 }
1085 }
1086 }
1087
1088 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
1095 let DocAttribute {
1096 aliases,
1097 hidden: _,
1100 inline,
1101 cfg: _,
1103 auto_cfg: _,
1105 auto_cfg_change: _,
1107 fake_variadic,
1108 keyword,
1109 masked,
1110 notable_trait: _,
1112 search_unbox,
1113 html_favicon_url: _,
1115 html_logo_url: _,
1117 html_playground_url: _,
1119 html_root_url: _,
1121 html_no_source: _,
1123 issue_tracker_base_url: _,
1125 rust_logo,
1126 test_attrs: _,
1128 no_crate_inject: _,
1130 attribute,
1131 } = attr;
1132
1133 for (alias, span) in aliases {
1134 self.check_doc_alias_value(*span, hir_id, target, *alias);
1135 }
1136
1137 if let Some((_, span)) = keyword {
1138 self.check_doc_keyword_and_attribute(*span, hir_id, "keyword");
1139 }
1140 if let Some((_, span)) = attribute {
1141 self.check_doc_keyword_and_attribute(*span, hir_id, "attribute");
1142 }
1143
1144 if let Some(span) = fake_variadic {
1145 self.check_doc_fake_variadic(*span, hir_id);
1146 }
1147
1148 if let Some(span) = search_unbox {
1149 self.check_doc_search_unbox(*span, hir_id);
1150 }
1151
1152 self.check_doc_inline(hir_id, target, inline);
1153
1154 if let Some(span) = rust_logo
1155 && !self.tcx.features().rustdoc_internals()
1156 {
1157 feature_err(
1158 &self.tcx.sess,
1159 sym::rustdoc_internals,
1160 *span,
1161 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"),
1162 )
1163 .emit();
1164 }
1165
1166 if let Some(span) = masked {
1167 self.check_doc_masked(*span, hir_id, target);
1168 }
1169 }
1170
1171 fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute]) {
1172 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(_)) {
1173 self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span });
1175 }
1176 }
1177
1178 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
1180 if let hir::Node::GenericParam(param) = self.tcx.hir_node(hir_id)
1181 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { ..
} => true,
_ => false,
}matches!(
1182 param.kind,
1183 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. }
1184 )
1185 && #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
1186 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
1187 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
1188 && let hir::ItemKind::Impl(impl_) = item.kind
1189 && let Some(of_trait) = impl_.of_trait
1190 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
1191 && self.tcx.is_lang_item(def_id, hir::LangItem::Drop)
1192 {
1193 return;
1194 }
1195
1196 self.dcx().emit_err(errors::InvalidMayDangle { attr_span });
1197 }
1198
1199 fn check_link(&self, hir_id: HirId, attr_span: Span, span: Span, target: Target) {
1201 if target == Target::ForeignMod
1202 && let hir::Node::Item(item) = self.tcx.hir_node(hir_id)
1203 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1204 && !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::Rust => true,
_ => false,
}matches!(abi, ExternAbi::Rust)
1205 {
1206 return;
1207 }
1208
1209 self.tcx.emit_node_span_lint(
1210 UNUSED_ATTRIBUTES,
1211 hir_id,
1212 attr_span,
1213 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1214 );
1215 }
1216
1217 fn check_rustc_legacy_const_generics(
1219 &self,
1220 item: Option<ItemLike<'_>>,
1221 attr_span: Span,
1222 index_list: &ThinVec<(usize, Span)>,
1223 ) {
1224 let Some(ItemLike::Item(Item {
1225 kind: ItemKind::Fn { sig: FnSig { decl, .. }, generics, .. },
1226 ..
1227 })) = item
1228 else {
1229 return;
1231 };
1232
1233 for param in generics.params {
1234 match param.kind {
1235 hir::GenericParamKind::Const { .. } => {}
1236 _ => {
1237 self.dcx().emit_err(errors::RustcLegacyConstGenericsOnly {
1238 attr_span,
1239 param_span: param.span,
1240 });
1241 return;
1242 }
1243 }
1244 }
1245
1246 if index_list.len() != generics.params.len() {
1247 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndex {
1248 attr_span,
1249 generics_span: generics.span,
1250 });
1251 return;
1252 }
1253
1254 let arg_count = decl.inputs.len() + generics.params.len();
1255 for (index, span) in index_list {
1256 if *index >= arg_count {
1257 self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1258 span: *span,
1259 arg_count,
1260 });
1261 }
1262 }
1263 }
1264
1265 fn check_repr(
1267 &self,
1268 attrs: &[Attribute],
1269 span: Span,
1270 target: Target,
1271 item: Option<ItemLike<'_>>,
1272 hir_id: HirId,
1273 ) {
1274 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));
1280
1281 let mut int_reprs = 0;
1282 let mut is_explicit_rust = false;
1283 let mut is_c = false;
1284 let mut is_simd = false;
1285 let mut is_transparent = false;
1286
1287 for (repr, repr_span) in reprs {
1288 match repr {
1289 ReprAttr::ReprRust => {
1290 is_explicit_rust = true;
1291 match target {
1292 Target::Struct | Target::Union | Target::Enum => continue,
1293 _ => {
1294 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1295 hint_span: *repr_span,
1296 span,
1297 });
1298 }
1299 }
1300 }
1301 ReprAttr::ReprC => {
1302 is_c = true;
1303 match target {
1304 Target::Struct | Target::Union | Target::Enum => continue,
1305 _ => {
1306 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1307 hint_span: *repr_span,
1308 span,
1309 });
1310 }
1311 }
1312 }
1313 ReprAttr::ReprAlign(align) => {
1314 match target {
1315 Target::Struct | Target::Union | Target::Enum => {}
1316 Target::Fn | Target::Method(_) if self.tcx.features().fn_align() => {
1317 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1318 span: *repr_span,
1319 item: target.plural_name(),
1320 });
1321 }
1322 Target::Static if self.tcx.features().static_align() => {
1323 self.dcx().emit_err(errors::ReprAlignShouldBeAlignStatic {
1324 span: *repr_span,
1325 item: target.plural_name(),
1326 });
1327 }
1328 _ => {
1329 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1330 hint_span: *repr_span,
1331 span,
1332 });
1333 }
1334 }
1335
1336 self.check_align(*align, *repr_span);
1337 }
1338 ReprAttr::ReprPacked(_) => {
1339 if target != Target::Struct && target != Target::Union {
1340 self.dcx().emit_err(errors::AttrApplication::StructUnion {
1341 hint_span: *repr_span,
1342 span,
1343 });
1344 } else {
1345 continue;
1346 }
1347 }
1348 ReprAttr::ReprSimd => {
1349 is_simd = true;
1350 if target != Target::Struct {
1351 self.dcx().emit_err(errors::AttrApplication::Struct {
1352 hint_span: *repr_span,
1353 span,
1354 });
1355 } else {
1356 continue;
1357 }
1358 }
1359 ReprAttr::ReprTransparent => {
1360 is_transparent = true;
1361 match target {
1362 Target::Struct | Target::Union | Target::Enum => continue,
1363 _ => {
1364 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1365 hint_span: *repr_span,
1366 span,
1367 });
1368 }
1369 }
1370 }
1371 ReprAttr::ReprInt(_) => {
1372 int_reprs += 1;
1373 if target != Target::Enum {
1374 self.dcx().emit_err(errors::AttrApplication::Enum {
1375 hint_span: *repr_span,
1376 span,
1377 });
1378 } else {
1379 continue;
1380 }
1381 }
1382 };
1383 }
1384
1385 if let Some(first_attr_span) = first_attr_span
1387 && reprs.is_empty()
1388 && item.is_some()
1389 {
1390 match target {
1391 Target::Struct | Target::Union | Target::Enum => {}
1392 Target::Fn | Target::Method(_) => {
1393 self.dcx().emit_err(errors::ReprAlignShouldBeAlign {
1394 span: first_attr_span,
1395 item: target.plural_name(),
1396 });
1397 }
1398 _ => {
1399 self.dcx().emit_err(errors::AttrApplication::StructEnumUnion {
1400 hint_span: first_attr_span,
1401 span,
1402 });
1403 }
1404 }
1405 return;
1406 }
1407
1408 let hint_spans = reprs.iter().map(|(_, span)| *span);
1411
1412 if is_transparent && reprs.len() > 1 {
1414 let hint_spans = hint_spans.clone().collect();
1415 self.dcx().emit_err(errors::TransparentIncompatible {
1416 hint_spans,
1417 target: target.to_string(),
1418 });
1419 }
1420 if is_transparent
1423 && let Some(&pass_indirectly_span) =
1424 {
'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)
1425 {
1426 self.dcx().emit_err(errors::TransparentIncompatible {
1427 hint_spans: <[_]>::into_vec(::alloc::boxed::box_new([span, pass_indirectly_span]))vec![span, pass_indirectly_span],
1428 target: target.to_string(),
1429 });
1430 }
1431 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1432 let hint_spans = hint_spans.clone().collect();
1433 self.dcx().emit_err(errors::ReprConflicting { hint_spans });
1434 }
1435 if (int_reprs > 1)
1437 || (is_simd && is_c)
1438 || (int_reprs == 1
1439 && is_c
1440 && item.is_some_and(|item| {
1441 if let ItemLike::Item(item) = item { is_c_like_enum(item) } else { false }
1442 }))
1443 {
1444 self.tcx.emit_node_span_lint(
1445 CONFLICTING_REPR_HINTS,
1446 hir_id,
1447 hint_spans.collect::<Vec<Span>>(),
1448 errors::ReprConflictingLint,
1449 );
1450 }
1451 }
1452
1453 fn check_align(&self, align: Align, span: Span) {
1454 if align.bytes() > 2_u64.pow(29) {
1455 self.dcx().span_delayed_bug(
1457 span,
1458 "alignment greater than 2^29 should be errored on elsewhere",
1459 );
1460 } else {
1461 let max = Size::from_bits(self.tcx.sess.target.pointer_width).signed_int_max() as u64;
1466 if align.bytes() > max {
1467 self.dcx().emit_err(errors::InvalidReprAlignForTarget { span, size: max });
1468 }
1469 }
1470 }
1471
1472 fn check_macro_only_attr(
1477 &self,
1478 attr_span: Span,
1479 span: Span,
1480 target: Target,
1481 attrs: &[Attribute],
1482 ) {
1483 match target {
1484 Target::Fn => {
1485 for attr in attrs {
1486 if attr.is_proc_macro_attr() {
1487 return;
1489 }
1490 }
1491 self.tcx.dcx().emit_err(errors::MacroOnlyAttribute { attr_span, span });
1492 }
1493 _ => {}
1494 }
1495 }
1496
1497 fn check_rustc_allow_const_fn_unstable(
1500 &self,
1501 hir_id: HirId,
1502 attr_span: Span,
1503 span: Span,
1504 target: Target,
1505 ) {
1506 match target {
1507 Target::Fn | Target::Method(_) => {
1508 if !self.tcx.is_const_fn(hir_id.expect_owner().to_def_id()) {
1509 self.tcx.dcx().emit_err(errors::RustcAllowConstFnUnstable { attr_span, span });
1510 }
1511 }
1512 _ => {}
1513 }
1514 }
1515
1516 fn check_stability(
1517 &self,
1518 attr_span: Span,
1519 item_span: Span,
1520 level: &StabilityLevel,
1521 feature: Symbol,
1522 ) {
1523 if level.is_unstable()
1526 && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some()
1527 {
1528 self.tcx
1529 .dcx()
1530 .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span });
1531 }
1532 }
1533
1534 fn check_deprecated(&self, hir_id: HirId, attr_span: Span, target: Target) {
1535 match target {
1536 Target::AssocConst | Target::Method(..) | Target::AssocTy
1537 if self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
1538 == DefKind::Impl { of_trait: true } =>
1539 {
1540 self.tcx.emit_node_span_lint(
1541 UNUSED_ATTRIBUTES,
1542 hir_id,
1543 attr_span,
1544 errors::DeprecatedAnnotationHasNoEffect { span: attr_span },
1545 );
1546 }
1547 _ => {}
1548 }
1549 }
1550
1551 fn check_macro_export(&self, hir_id: HirId, attr_span: Span, target: Target) {
1552 if target != Target::MacroDef {
1553 return;
1554 }
1555
1556 let (_, macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();
1558 let is_decl_macro = !macro_definition.macro_rules;
1559
1560 if is_decl_macro {
1561 self.tcx.emit_node_span_lint(
1562 UNUSED_ATTRIBUTES,
1563 hir_id,
1564 attr_span,
1565 errors::MacroExport::OnDeclMacro,
1566 );
1567 }
1568 }
1569
1570 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute, style: Option<AttrStyle>) {
1571 let note = if attr.has_any_name(&[
1574 sym::allow,
1575 sym::expect,
1576 sym::warn,
1577 sym::deny,
1578 sym::forbid,
1579 sym::feature,
1580 ]) && attr.meta_item_list().is_some_and(|list| list.is_empty())
1581 {
1582 errors::UnusedNote::EmptyList { name: attr.name().unwrap() }
1583 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1584 && let Some(meta) = attr.meta_item_list()
1585 && let [meta] = meta.as_slice()
1586 && let Some(item) = meta.meta_item()
1587 && let MetaItemKind::NameValue(_) = &item.kind
1588 && item.path == sym::reason
1589 {
1590 errors::UnusedNote::NoLints { name: attr.name().unwrap() }
1591 } else if attr.has_any_name(&[sym::allow, sym::warn, sym::deny, sym::forbid, sym::expect])
1592 && let Some(meta) = attr.meta_item_list()
1593 && meta.iter().any(|meta| {
1594 meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
1595 })
1596 {
1597 if hir_id != CRATE_HIR_ID {
1598 match style {
1599 Some(ast::AttrStyle::Outer) => {
1600 let attr_span = attr.span();
1601 let bang_position = self
1602 .tcx
1603 .sess
1604 .source_map()
1605 .span_until_char(attr_span, '[')
1606 .shrink_to_hi();
1607
1608 self.tcx.emit_node_span_lint(
1609 UNUSED_ATTRIBUTES,
1610 hir_id,
1611 attr_span,
1612 errors::OuterCrateLevelAttr {
1613 suggestion: errors::OuterCrateLevelAttrSuggestion { bang_position },
1614 },
1615 )
1616 }
1617 Some(ast::AttrStyle::Inner) | None => self.tcx.emit_node_span_lint(
1618 UNUSED_ATTRIBUTES,
1619 hir_id,
1620 attr.span(),
1621 errors::InnerCrateLevelAttr,
1622 ),
1623 };
1624 return;
1625 } else {
1626 let never_needs_link = self
1627 .tcx
1628 .crate_types()
1629 .iter()
1630 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib));
1631 if never_needs_link {
1632 errors::UnusedNote::LinkerMessagesBinaryCrateOnly
1633 } else {
1634 return;
1635 }
1636 }
1637 } else if attr.has_name(sym::default_method_body_is_const) {
1638 errors::UnusedNote::DefaultMethodBodyConst
1639 } else {
1640 return;
1641 };
1642
1643 self.tcx.emit_node_span_lint(
1644 UNUSED_ATTRIBUTES,
1645 hir_id,
1646 attr.span(),
1647 errors::Unused { attr_span: attr.span(), note },
1648 );
1649 }
1650
1651 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1655 if target != Target::Fn {
1656 return;
1657 }
1658
1659 let tcx = self.tcx;
1660 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1661 return;
1662 };
1663 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1664 return;
1665 };
1666
1667 let def_id = hir_id.expect_owner().def_id;
1668 let param_env = ty::ParamEnv::empty();
1669
1670 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1671 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1672
1673 let span = tcx.def_span(def_id);
1674 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1675 let sig = tcx.liberate_late_bound_regions(
1676 def_id.to_def_id(),
1677 tcx.fn_sig(def_id).instantiate(tcx, fresh_args),
1678 );
1679
1680 let mut cause = ObligationCause::misc(span, def_id);
1681 let sig = ocx.normalize(&cause, param_env, sig);
1682
1683 let errors = ocx.try_evaluate_obligations();
1685 if !errors.is_empty() {
1686 return;
1687 }
1688
1689 let expected_sig = tcx.mk_fn_sig(
1690 std::iter::repeat_n(
1691 token_stream,
1692 match kind {
1693 ProcMacroKind::Attribute => 2,
1694 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1695 },
1696 ),
1697 token_stream,
1698 false,
1699 Safety::Safe,
1700 ExternAbi::Rust,
1701 );
1702
1703 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1704 let mut diag = tcx.dcx().create_err(errors::ProcMacroBadSig { span, kind });
1705
1706 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1707 if let Some(hir_sig) = hir_sig {
1708 match terr {
1709 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1710 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1711 diag.span(ty.span);
1712 cause.span = ty.span;
1713 } else if idx == hir_sig.decl.inputs.len() {
1714 let span = hir_sig.decl.output.span();
1715 diag.span(span);
1716 cause.span = span;
1717 }
1718 }
1719 TypeError::ArgCount => {
1720 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1721 diag.span(ty.span);
1722 cause.span = ty.span;
1723 }
1724 }
1725 TypeError::SafetyMismatch(_) => {
1726 }
1728 TypeError::AbiMismatch(_) => {
1729 }
1731 TypeError::VariadicMismatch(_) => {
1732 }
1734 _ => {}
1735 }
1736 }
1737
1738 infcx.err_ctxt().note_type_err(
1739 &mut diag,
1740 &cause,
1741 None,
1742 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1743 expected: ty::Binder::dummy(expected_sig),
1744 found: ty::Binder::dummy(sig),
1745 }))),
1746 terr,
1747 false,
1748 None,
1749 );
1750 diag.emit();
1751 self.abort.set(true);
1752 }
1753
1754 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1755 if !errors.is_empty() {
1756 infcx.err_ctxt().report_fulfillment_errors(errors);
1757 self.abort.set(true);
1758 }
1759 }
1760
1761 fn check_rustc_pub_transparent(&self, attr_span: Span, span: Span, attrs: &[Attribute]) {
1762 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))
1763 .unwrap_or(false)
1764 {
1765 self.dcx().emit_err(errors::RustcPubTransparent { span, attr_span });
1766 }
1767 }
1768
1769 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1770 if let (Target::Closure, None) = (
1771 target,
1772 {
'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),
1773 ) {
1774 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!(
1775 self.tcx.hir_expect_expr(hir_id).kind,
1776 hir::ExprKind::Closure(hir::Closure {
1777 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1778 ..
1779 })
1780 );
1781 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1782 let parent_span = self.tcx.def_span(parent_did);
1783
1784 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!(
1785 self.tcx.get_all_attrs(parent_did),
1786 AttributeKind::Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1787 ) && is_coro
1788 {
1789 self.dcx().emit_err(errors::RustcForceInlineCoro { attr_span, span: parent_span });
1790 }
1791 }
1792 }
1793
1794 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1795 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)
1796 && let Some(no_mangle_span) =
1797 {
'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)
1798 {
1799 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1800 "#[unsafe(no_mangle)]"
1801 } else {
1802 "#[no_mangle]"
1803 };
1804 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1805 "#[unsafe(export_name)]"
1806 } else {
1807 "#[export_name]"
1808 };
1809
1810 self.tcx.emit_node_span_lint(
1811 lint::builtin::UNUSED_ATTRIBUTES,
1812 hir_id,
1813 no_mangle_span,
1814 errors::MixedExportNameAndNoMangle {
1815 no_mangle_span,
1816 export_name_span,
1817 no_mangle_attr,
1818 export_name_attr,
1819 },
1820 );
1821 }
1822 }
1823
1824 fn check_autodiff(&self, _hir_id: HirId, _attr: &Attribute, span: Span, target: Target) {
1826 {
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:1826",
"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(1826u32),
::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");
1827 match target {
1828 Target::Fn => {}
1829 _ => {
1830 self.dcx().emit_err(errors::AutoDiffAttr { attr_span: span });
1831 self.abort.set(true);
1832 }
1833 }
1834 }
1835
1836 fn check_loop_match(&self, hir_id: HirId, attr_span: Span, target: Target) {
1837 let node_span = self.tcx.hir_span(hir_id);
1838
1839 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1840 return; }
1842
1843 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(..)) {
1844 self.dcx().emit_err(errors::LoopMatchAttr { attr_span, node_span });
1845 };
1846 }
1847
1848 fn check_const_continue(&self, hir_id: HirId, attr_span: Span, target: Target) {
1849 let node_span = self.tcx.hir_span(hir_id);
1850
1851 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Expression => true,
_ => false,
}matches!(target, Target::Expression) {
1852 return; }
1854
1855 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(..)) {
1856 self.dcx().emit_err(errors::ConstContinueAttr { attr_span, node_span });
1857 };
1858 }
1859
1860 fn check_custom_mir(
1861 &self,
1862 dialect: Option<(MirDialect, Span)>,
1863 phase: Option<(MirPhase, Span)>,
1864 attr_span: Span,
1865 ) {
1866 let Some((dialect, dialect_span)) = dialect else {
1867 if let Some((_, phase_span)) = phase {
1868 self.dcx()
1869 .emit_err(errors::CustomMirPhaseRequiresDialect { attr_span, phase_span });
1870 }
1871 return;
1872 };
1873
1874 match dialect {
1875 MirDialect::Analysis => {
1876 if let Some((MirPhase::Optimized, phase_span)) = phase {
1877 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1878 dialect,
1879 phase: MirPhase::Optimized,
1880 attr_span,
1881 dialect_span,
1882 phase_span,
1883 });
1884 }
1885 }
1886
1887 MirDialect::Built => {
1888 if let Some((phase, phase_span)) = phase {
1889 self.dcx().emit_err(errors::CustomMirIncompatibleDialectAndPhase {
1890 dialect,
1891 phase,
1892 attr_span,
1893 dialect_span,
1894 phase_span,
1895 });
1896 }
1897 }
1898 MirDialect::Runtime => {}
1899 }
1900 }
1901}
1902
1903impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1904 type NestedFilter = nested_filter::OnlyBodies;
1905
1906 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1907 self.tcx
1908 }
1909
1910 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1911 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1915 let def_id = item.owner_id.to_def_id();
1916 if macro_def.macro_rules
1917 && !{
{
'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 { .. })
1918 {
1919 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1920 }
1921 }
1922
1923 let target = Target::from_item(item);
1924 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
1925 intravisit::walk_item(self, item)
1926 }
1927
1928 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1929 let spans = self
1934 .tcx
1935 .hir_attrs(where_predicate.hir_id)
1936 .iter()
1937 .filter(|attr| {
1939 #[allow(non_exhaustive_omitted_patterns)] match attr {
Attribute::Parsed(AttributeKind::DocComment { .. } |
AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
_ => false,
}matches!(
1940 attr,
1941 Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
1942 | Attribute::Unparsed(_)
1943 )
1944 })
1945 .map(|attr| attr.span())
1946 .collect::<Vec<_>>();
1947 if !spans.is_empty() {
1948 self.tcx.dcx().emit_err(errors::UnsupportedAttributesInWhere { span: spans.into() });
1949 }
1950 self.check_attributes(
1951 where_predicate.hir_id,
1952 where_predicate.span,
1953 Target::WherePredicate,
1954 None,
1955 );
1956 intravisit::walk_where_predicate(self, where_predicate)
1957 }
1958
1959 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1960 let target = Target::from_generic_param(generic_param);
1961 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1962 intravisit::walk_generic_param(self, generic_param)
1963 }
1964
1965 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1966 let target = Target::from_trait_item(trait_item);
1967 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1968 intravisit::walk_trait_item(self, trait_item)
1969 }
1970
1971 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1972 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1973 intravisit::walk_field_def(self, struct_field);
1974 }
1975
1976 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1977 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1978 intravisit::walk_arm(self, arm);
1979 }
1980
1981 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1982 let target = Target::from_foreign_item(f_item);
1983 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
1984 intravisit::walk_foreign_item(self, f_item)
1985 }
1986
1987 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1988 let target = target_from_impl_item(self.tcx, impl_item);
1989 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1990 intravisit::walk_impl_item(self, impl_item)
1991 }
1992
1993 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1994 if let hir::StmtKind::Let(l) = stmt.kind {
1996 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1997 }
1998 intravisit::walk_stmt(self, stmt)
1999 }
2000
2001 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2002 let target = match expr.kind {
2003 hir::ExprKind::Closure { .. } => Target::Closure,
2004 _ => Target::Expression,
2005 };
2006
2007 self.check_attributes(expr.hir_id, expr.span, target, None);
2008 intravisit::walk_expr(self, expr)
2009 }
2010
2011 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2012 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2013 intravisit::walk_expr_field(self, field)
2014 }
2015
2016 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2017 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
2018 intravisit::walk_variant(self, variant)
2019 }
2020
2021 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2022 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2023
2024 intravisit::walk_param(self, param);
2025 }
2026
2027 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2028 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2029 intravisit::walk_pat_field(self, field);
2030 }
2031}
2032
2033fn is_c_like_enum(item: &Item<'_>) -> bool {
2034 if let ItemKind::Enum(_, _, ref def) = item.kind {
2035 for variant in def.variants {
2036 match variant.data {
2037 hir::VariantData::Unit(..) => { }
2038 _ => return false,
2039 }
2040 }
2041 true
2042 } else {
2043 false
2044 }
2045}
2046
2047fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2050 const ATTRS_TO_CHECK: &[Symbol] =
2054 &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
2055
2056 for attr in attrs {
2057 let (span, name) = if let Some(a) =
2059 ATTRS_TO_CHECK.iter().find(|attr_to_check| attr.has_name(**attr_to_check))
2060 {
2061 (attr.span(), *a)
2062 } else if let Attribute::Parsed(AttributeKind::Repr {
2063 reprs: _,
2064 first_span: first_attr_span,
2065 }) = attr
2066 {
2067 (*first_attr_span, sym::repr)
2068 } else {
2069 continue;
2070 };
2071
2072 let item = tcx
2073 .hir_free_items()
2074 .map(|id| tcx.hir_item(id))
2075 .find(|item| !item.span.is_dummy()) .map(|item| errors::ItemFollowingInnerAttr {
2077 span: if let Some(ident) = item.kind.ident() { ident.span } else { item.span },
2078 kind: tcx.def_descr(item.owner_id.to_def_id()),
2079 });
2080 let err = tcx.dcx().create_err(errors::InvalidAttrAtCrateLevel {
2081 span,
2082 sugg_span: tcx
2083 .sess
2084 .source_map()
2085 .span_to_snippet(span)
2086 .ok()
2087 .filter(|src| src.starts_with("#!["))
2088 .map(|_| span.with_lo(span.lo() + BytePos(1)).with_hi(span.lo() + BytePos(2))),
2089 name,
2090 item,
2091 });
2092
2093 if let Attribute::Unparsed(p) = attr {
2094 tcx.dcx().try_steal_replace_and_emit_err(
2095 p.path.span,
2096 StashKey::UndeterminedMacroResolution,
2097 err,
2098 );
2099 } else {
2100 err.emit();
2101 }
2102 }
2103}
2104
2105fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2106 let attrs = tcx.hir_attrs(item.hir_id());
2107
2108 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)
2109 {
2110 tcx.dcx().emit_err(errors::NonExportedMacroInvalidAttrs { attr_span });
2111 }
2112}
2113
2114fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
2115 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
2116 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
2117 if module_def_id.to_local_def_id().is_top_level_module() {
2118 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2119 check_invalid_crate_level_attr(tcx, tcx.hir_krate_attrs());
2120 }
2121 if check_attr_visitor.abort.get() {
2122 tcx.dcx().abort_if_errors()
2123 }
2124}
2125
2126pub(crate) fn provide(providers: &mut Providers) {
2127 *providers = Providers { check_mod_attrs, ..*providers };
2128}
2129
2130fn check_duplicates(
2132 tcx: TyCtxt<'_>,
2133 attr_span: Span,
2134 attr: &Attribute,
2135 hir_id: HirId,
2136 duplicates: AttributeDuplicates,
2137 seen: &mut FxHashMap<Symbol, Span>,
2138) {
2139 use AttributeDuplicates::*;
2140 if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
WarnFollowingWordOnly => true,
_ => false,
}matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2141 return;
2142 }
2143 let attr_name = attr.name().unwrap();
2144 match duplicates {
2145 DuplicatesOk => {}
2146 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2147 match seen.entry(attr_name) {
2148 Entry::Occupied(mut entry) => {
2149 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnPreceding => true,
_ => false,
}matches!(duplicates, FutureWarnPreceding) {
2150 let to_remove = entry.insert(attr_span);
2151 (to_remove, attr_span)
2152 } else {
2153 (attr_span, *entry.get())
2154 };
2155 tcx.emit_node_span_lint(
2156 UNUSED_ATTRIBUTES,
2157 hir_id,
2158 this,
2159 errors::UnusedDuplicate {
2160 this,
2161 other,
2162 warning: #[allow(non_exhaustive_omitted_patterns)] match duplicates {
FutureWarnFollowing | FutureWarnPreceding => true,
_ => false,
}matches!(
2163 duplicates,
2164 FutureWarnFollowing | FutureWarnPreceding
2165 ),
2166 },
2167 );
2168 }
2169 Entry::Vacant(entry) => {
2170 entry.insert(attr_span);
2171 }
2172 }
2173 }
2174 ErrorFollowing | ErrorPreceding => match seen.entry(attr_name) {
2175 Entry::Occupied(mut entry) => {
2176 let (this, other) = if #[allow(non_exhaustive_omitted_patterns)] match duplicates {
ErrorPreceding => true,
_ => false,
}matches!(duplicates, ErrorPreceding) {
2177 let to_remove = entry.insert(attr_span);
2178 (to_remove, attr_span)
2179 } else {
2180 (attr_span, *entry.get())
2181 };
2182 tcx.dcx().emit_err(errors::UnusedMultiple { this, other, name: attr_name });
2183 }
2184 Entry::Vacant(entry) => {
2185 entry.insert(attr_span);
2186 }
2187 },
2188 }
2189}
2190
2191fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
2192 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
2193 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
2194 fn_ptr_ty.decl.inputs.len() == 1
2195 } else {
2196 false
2197 }
2198 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
2199 && let Some(&[hir::GenericArg::Type(ty)]) =
2200 path.segments.last().map(|last| last.args().args)
2201 {
2202 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
2203 } else {
2204 false
2205 })
2206}