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