1use std::cell::Cell;
9use std::slice;
10
11use rustc_attr_ir::diagnostic::Directive;
12use rustc_attr_ir::lang_items::LangItem;
13use rustc_attr_ir::lint::LintCheck;
14use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
15use rustc_attr_ir::{
16 Attribute, AttributeKind, DocAttribute, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
17 OptimizeAttr, ReprAttr, RustcAssertVarianceKind, find_attr,
18};
19use rustc_attr_parsing::AttributeParser;
20use rustc_data_structures::thin_vec::ThinVec;
21use rustc_errors::{DiagCtxtHandle, IntoDiagArg};
22use rustc_feature::BUILTIN_ATTRIBUTE_SET;
23use rustc_hir::def::DefKind;
24use rustc_hir::def_id::LocalModId;
25use rustc_hir::intravisit::{self, Visitor};
26use rustc_hir::{
27 self as hir, CRATE_HIR_ID, Constness, ForeignItem, GenericParam, GenericParamKind, HirId, Item,
28 ItemKind, Mod, Node, ParamName, TraitItem,
29};
30use rustc_lint_defs::builtin::{
31 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES,
32 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, MISPLACED_DIAGNOSTIC_ATTRIBUTES, REPEATED_REPRS,
33 UNUSED_ATTRIBUTES,
34};
35use rustc_macros::Diagnostic;
36use rustc_middle::hir::nested_filter;
37use rustc_middle::query::Providers;
38use rustc_middle::traits::ObligationCause;
39use rustc_middle::ty::error::{ExpectedFound, TypeError};
40use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized, Variance};
41use rustc_span::edition::Edition;
42use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, span_bug, sym};
43use rustc_structures::CrateType;
44use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
45use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
46use rustc_trait_selection::traits::{ObligationCtxt, TraitErrors};
47
48use crate::diagnostics;
49
50#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for
DiagnosticOnConstOnlyForNonConstTraitImpls {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
match self {
DiagnosticOnConstOnlyForNonConstTraitImpls {
item_span: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `diagnostic::on_const` attribute can only be applied to non-const trait implementations")));
;
diag.span_label(__binding_0,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this is a const trait implementation")));
diag
}
}
}
}
};Diagnostic)]
51#[diag(
52 "the `diagnostic::on_const` attribute can only be applied to non-const trait implementations"
53)]
54struct DiagnosticOnConstOnlyForNonConstTraitImpls {
55 #[label("this is a const trait implementation")]
56 item_span: Span,
57}
58
59fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
60 match impl_item.kind {
61 hir::ImplItemKind::Const(..) => {
62 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
63 let containing_item = tcx.hir_expect_item(parent_def_id);
64 let of_trait = match &containing_item.kind {
65 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
66 _ => ::rustc_span::macros::bug_impl(None,
format_args!("parent of an ImplItem must be an Impl"), Location::caller())bug!("parent of an ImplItem must be an Impl"),
67 };
68 Target::AssocConst(AssocCtxt::Impl { of_trait })
69 }
70 hir::ImplItemKind::Fn(..) => {
71 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
72 let containing_item = tcx.hir_expect_item(parent_def_id);
73 let containing_impl_is_for_trait = match &containing_item.kind {
74 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
75 _ => ::rustc_span::macros::bug_impl(None,
format_args!("parent of an ImplItem must be an Impl"), Location::caller())bug!("parent of an ImplItem must be an Impl"),
76 };
77 if containing_impl_is_for_trait {
78 Target::Method(MethodKind::TraitImpl)
79 } else {
80 Target::Method(MethodKind::Inherent)
81 }
82 }
83 hir::ImplItemKind::Type(..) => {
84 let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
85 let containing_item = tcx.hir_expect_item(parent_def_id);
86 let of_trait = match &containing_item.kind {
87 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
88 _ => ::rustc_span::macros::bug_impl(None,
format_args!("parent of an ImplItem must be an Impl"), Location::caller())bug!("parent of an ImplItem must be an Impl"),
89 };
90 Target::AssocTy(AssocCtxt::Impl { of_trait })
91 }
92 }
93}
94
95#[derive(#[automatically_derived]impl ::core::marker::Copy for ProcMacroKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ProcMacroKind {
}
#[automatically_derived]impl ::core::clone::Clone for ProcMacroKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone)]
96pub(crate) enum ProcMacroKind {
97 FunctionLike,
98 Derive,
99 Attribute,
100}
101
102impl IntoDiagArg for ProcMacroKind {
103 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
104 match self {
105 ProcMacroKind::Attribute => "attribute proc macro",
106 ProcMacroKind::Derive => "derive proc macro",
107 ProcMacroKind::FunctionLike => "function-like proc macro",
108 }
109 .into_diag_arg(&mut None)
110 }
111}
112
113struct CheckAttrVisitor<'tcx> {
114 tcx: TyCtxt<'tcx>,
115
116 abort: Cell<bool>,
118}
119
120impl<'tcx> CheckAttrVisitor<'tcx> {
121 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
122 self.tcx.dcx()
123 }
124
125 fn check_attributes(
127 &self,
128 hir_id: HirId,
129 span: Span,
130 target: Target,
131 item: Option<&'tcx Item<'tcx>>,
132 ) {
133 let attrs = self.tcx.hir_attrs(hir_id);
134 for attr in attrs {
135 match attr {
136 Attribute::Parsed(attr_kind) => {
137 self.check_one_parsed_attribute(hir_id, span, target, item, attr_kind);
138 }
139 Attribute::Tool(u) | Attribute::DeriveHelper(u) => {
140 match &*u.path.segments {
141 [name, rest @ ..] => {
142 if BUILTIN_ATTRIBUTE_SET.contains(name) {
143 if rest.len() > 0
144 && AttributeParser::is_parsed_attribute(slice::from_ref(name))
145 {
146 return;
151 }
152
153 ::rustc_span::macros::bug_impl(Some(u.span),
format_args!("builtin attribute {0:?} not handled by `CheckAttrVisitor`",
name), Location::caller())span_bug!(
154 u.span,
155 "builtin attribute {name:?} not handled by `CheckAttrVisitor`"
156 )
157 }
158 }
159
160 [] => ::core::panicking::unreachable_default_msg()unreachable!(),
161 }
162 }
163 }
164 }
165
166 self.check_repr(attrs, span, target, item, hir_id);
167 self.check_rustc_force_inline(hir_id, attrs, target);
168 self.check_mix_no_mangle_export(hir_id, attrs);
169 self.check_optimize_and_inline(attrs);
170 }
171
172 fn check_one_parsed_attribute(
177 &self,
178 hir_id: HirId,
179 span: Span,
180 target: Target,
181 item: Option<&'tcx Item<'tcx>>,
182 attr: &AttributeKind,
183 ) {
184 match attr {
185 AttributeKind::ProcMacro => {
186 self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
187 }
188 AttributeKind::ProcMacroAttribute => {
189 self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
190 }
191 AttributeKind::ProcMacroDerive { .. } => {
192 self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
193 }
194 AttributeKind::MayDangle(attr_span) => self.check_may_dangle(hir_id, *attr_span),
195 AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target),
196 AttributeKind::EiiImpl(eii_impl) => self.check_eii_impl(eii_impl),
197 AttributeKind::RustcMustImplementOneOf { attr_span, fn_names } => {
198 self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id, target)
199 }
200 AttributeKind::OnUnimplemented { directive } => {
201 self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())
202 }
203 AttributeKind::OnConst { span, directive } => {
204 self.check_diagnostic_on_const(*span, hir_id, target, item, directive.as_deref())
205 }
206 AttributeKind::OnMove { directive } => {
207 self.check_diagnostic_on_move(hir_id, directive.as_deref())
208 }
209 AttributeKind::OnTypeError { directive, .. } => {
210 self.check_diagnostic_on_type_error(hir_id, directive.as_deref())
211 }
212 AttributeKind::Linkage(_linkage, span) => {
213 self.check_linkage(*span, hir_id, target, item)
214 }
215 AttributeKind::RustcAssertVariance { span: attr_span, kind } => {
216 self.check_rustc_assert_variance(span, *attr_span, hir_id, target, *kind);
217 }
218 AttributeKind::LintCheck(lints) => self.check_lint_check(hir_id, lints),
219
220 AttributeKind::AllowInternalUnsafe(..) => (),
223 AttributeKind::AllowInternalUnstable(..) => (),
224 AttributeKind::AlwaysGca => (),
225 AttributeKind::AutomaticallyDerived => (),
226 AttributeKind::CfgAttrTrace(..) => (),
227 AttributeKind::CfgTrace(..) => (),
228 AttributeKind::CfiEncoding { .. } => (),
229 AttributeKind::Cold => (),
230 AttributeKind::CollapseDebugInfo(..) => (),
231 AttributeKind::CompilerBuiltins => (),
232 AttributeKind::ConstContinue(..) => {}
233 AttributeKind::Coroutine => (),
234 AttributeKind::Coverage(..) => (),
235 AttributeKind::CrateName { .. } => (),
236 AttributeKind::CrateType(..) => (),
237 AttributeKind::CustomMir(..) => (),
238 AttributeKind::DebuggerVisualizer(..) => (),
239 AttributeKind::DefaultLibAllocator => (),
240 AttributeKind::Deprecated { .. } => (),
241 AttributeKind::DoNotRecommend => (),
242 AttributeKind::DocComment { .. } => (),
244 AttributeKind::EiiDeclaration { .. } => (),
245 AttributeKind::ExportName { .. } => (),
246 AttributeKind::ExportStable => (),
247 AttributeKind::Feature(..) => (),
248 AttributeKind::FfiConst => (),
249 AttributeKind::FfiPure(..) => (),
250 AttributeKind::Fundamental => (),
251 AttributeKind::Ignore { .. } => (),
252 AttributeKind::Inline(..) => (),
253 AttributeKind::InstructionSet(..) => (),
254 AttributeKind::InstrumentFn(..) => (),
255 AttributeKind::Lang(..) => (),
256 AttributeKind::Link(..) => (),
257 AttributeKind::LinkName { .. } => (),
258 AttributeKind::LinkOrdinal { .. } => (),
259 AttributeKind::LinkSection { .. } => (),
260 AttributeKind::LintAsPtr => (),
261 AttributeKind::LintNeverReturnsNullPtr => (),
262 AttributeKind::LintShouldNotBeCalledOnConstItems => (),
263 AttributeKind::LoopMatch(..) => (),
264 AttributeKind::MacroEscape => (),
265 AttributeKind::MacroExport { .. } => (),
266 AttributeKind::MacroUse { .. } => (),
267 AttributeKind::Marker => (),
268 AttributeKind::MoveSizeLimit { .. } => (),
269 AttributeKind::MustNotSupend { .. } => (),
270 AttributeKind::MustUse { .. } => (),
271 AttributeKind::Naked(..) => (),
272 AttributeKind::NeedsAllocator => (),
273 AttributeKind::NeedsPanicRuntime => (),
274 AttributeKind::NoBuiltins => (),
275 AttributeKind::NoCore { .. } => (),
276 AttributeKind::NoImplicitPrelude => (),
277 AttributeKind::NoLink => (),
278 AttributeKind::NoMain => (),
279 AttributeKind::NoMangle(..) => (),
280 AttributeKind::NoStd { .. } => (),
281 AttributeKind::NonExhaustive(_) => (),
282 AttributeKind::OnUnknown { .. } => (),
283 AttributeKind::OnUnmatchedArgs { .. } => (),
284 AttributeKind::Opaque => (),
285 AttributeKind::Optimize(..) => (),
286 AttributeKind::PanicRuntime => (),
287 AttributeKind::PatchableFunctionEntry { .. } => (),
288 AttributeKind::Path(_, span) => self.check_path(*span, hir_id),
289 AttributeKind::PatternComplexityLimit { .. } => (),
290 AttributeKind::PinV2(..) => (),
291 AttributeKind::PreludeImport => (),
292 AttributeKind::ProfilerRuntime => (),
293 AttributeKind::RecursionLimit { .. } => (),
294 AttributeKind::ReexportTestHarnessMain(..) => (),
295 AttributeKind::RegisterTool { .. } => (),
296 AttributeKind::Repr { .. } => (),
298 AttributeKind::RustcAbi { .. } => (),
299 AttributeKind::RustcAlign { .. } => {}
300 AttributeKind::RustcAllocator => (),
301 AttributeKind::RustcAllocatorZeroed => (),
302 AttributeKind::RustcAllocatorZeroedVariant { .. } => (),
303 AttributeKind::RustcAllowConstFnUnstable(..) => (),
304 AttributeKind::RustcAllowIncoherentImpl(..) => (),
305 AttributeKind::RustcAllowLifetimeDependentSpecialization => (),
306 AttributeKind::RustcAutodiff(..) => (),
307 AttributeKind::RustcBodyStability { .. } => (),
308 AttributeKind::RustcBuiltinMacro { .. } => (),
309 AttributeKind::RustcCanonicalSymbol => (),
310 AttributeKind::RustcCaptureAnalysis => (),
311 AttributeKind::RustcCguTestAttr(..) => (),
312 AttributeKind::RustcClean(..) => (),
313 AttributeKind::RustcCoherenceIsCore => (),
314 AttributeKind::RustcCoinductive => (),
315 AttributeKind::RustcComptime(_) => (),
316 AttributeKind::RustcConfusables { .. } => (),
317 AttributeKind::RustcConstStability { .. } => (),
318 AttributeKind::RustcConstStableIndirect => (),
319 AttributeKind::RustcConversionSuggestion => (),
320 AttributeKind::RustcDeallocator => (),
321 AttributeKind::RustcDelayedBugFromInsideQuery => (),
322 AttributeKind::RustcDenyExplicitImpl => (),
323 AttributeKind::RustcDeprecatedSafe2024 { .. } => (),
324 AttributeKind::RustcDiagnosticItem(..) => (),
325 AttributeKind::RustcDoNotConstCheck => (),
326 AttributeKind::RustcDocPrimitive(..) => (),
327 AttributeKind::RustcDummy => (),
328 AttributeKind::RustcDumpClauses => (),
329 AttributeKind::RustcDumpDefParents => (),
330 AttributeKind::RustcDumpDefPath(..) => (),
331 AttributeKind::RustcDumpGenerics => (),
332 AttributeKind::RustcDumpHiddenTypeOfOpaques => (),
333 AttributeKind::RustcDumpInferredOutlives => (),
334 AttributeKind::RustcDumpItemBounds => (),
335 AttributeKind::RustcDumpLayout(..) => (),
336 AttributeKind::RustcDumpObjectLifetimeDefaults => (),
337 AttributeKind::RustcDumpSymbolName(..) => (),
338 AttributeKind::RustcDumpUserArgs => (),
339 AttributeKind::RustcDumpVariances => (),
340 AttributeKind::RustcDumpVariancesOfOpaques => (),
341 AttributeKind::RustcDumpVtable(..) => (),
342 AttributeKind::RustcDynIncompatibleTrait(..) => (),
343 AttributeKind::RustcEffectiveVisibility => (),
344 AttributeKind::RustcEiiForeignItem => (),
345 AttributeKind::RustcEvaluateWhereClauses => (),
346 AttributeKind::RustcHasIncoherentInherentImpls => (),
347 AttributeKind::RustcIfThisChanged(..) => (),
348 AttributeKind::RustcInheritOverflowChecks => (),
349 AttributeKind::RustcInsignificantDtor => (),
350 AttributeKind::RustcIntrinsic => (),
351 AttributeKind::RustcIntrinsicConstStableIndirect => (),
352 AttributeKind::RustcLegacyConstGenerics { .. } => (),
353 AttributeKind::RustcLintOptDenyFieldAccess { .. } => (),
354 AttributeKind::RustcLintOptTy => (),
355 AttributeKind::RustcLintQueryInstability => (),
356 AttributeKind::RustcLintUntrackedQueryInformation => (),
357 AttributeKind::RustcMacroTransparency(_) => (),
358 AttributeKind::RustcMain => (),
359 AttributeKind::RustcMir(_) => (),
360 AttributeKind::RustcMustMatchExhaustively(..) => (),
361 AttributeKind::RustcNoImplicitAutorefs => (),
362 AttributeKind::RustcNoImplicitBounds => (),
363 AttributeKind::RustcNoMirInline => (),
364 AttributeKind::RustcNoWritable => (),
365 AttributeKind::RustcNonConstTraitMethod => (),
366 AttributeKind::RustcNonnullOptimizationGuaranteed => (),
367 AttributeKind::RustcNounwind => (),
368 AttributeKind::RustcObjcClass { .. } => (),
369 AttributeKind::RustcObjcSelector { .. } => (),
370 AttributeKind::RustcOffloadKernel => (),
371 AttributeKind::RustcPanicsWhenZero => (),
372 AttributeKind::RustcParenSugar => (),
373 AttributeKind::RustcPassByValue => (),
374 AttributeKind::RustcPassIndirectlyInNonRusticAbis(..) => (),
375 AttributeKind::RustcPreserveUbChecks => (),
376 AttributeKind::RustcProcMacroDecls => (),
377 AttributeKind::RustcPubTransparent(..) => (),
378 AttributeKind::RustcReallocator => (),
379 AttributeKind::RustcRegions => (),
380 AttributeKind::RustcScalableVector { .. } => (),
381 AttributeKind::RustcShouldNotBeCalledOnConstItems => (),
382 AttributeKind::RustcShowSpans(_) => (),
383 AttributeKind::RustcSimdMonomorphizeLaneLimit(..) => (),
384 AttributeKind::RustcSkipDuringMethodDispatch { .. } => (),
385 AttributeKind::RustcSpecializationTrait => (),
386 AttributeKind::RustcStdInternalSymbol => (),
387 AttributeKind::RustcStrictCoherence(..) => (),
388 AttributeKind::RustcTestMarker(..) => (),
389 AttributeKind::RustcThenThisWouldNeed(..) => (),
390 AttributeKind::RustcTrivialFieldReads => (),
391 AttributeKind::Sanitize { .. } => {}
392 AttributeKind::ShouldPanic { .. } => (),
393 AttributeKind::Splat(..) => (),
394 AttributeKind::Stability { .. } => (),
395 AttributeKind::TargetFeature { .. } => {}
396 AttributeKind::TestRunner(..) => (),
397 AttributeKind::ThreadLocal => (),
398 AttributeKind::TrackCaller(_) => (),
399 AttributeKind::TypeLengthLimit { .. } => (),
400 AttributeKind::UncheckedTypeAlias => (),
401 AttributeKind::Unroll(..) => (),
402 AttributeKind::UnstableFeatureBound(..) => (),
403 AttributeKind::UnstableRemoved(..) => (),
404 AttributeKind::Used { .. } => (),
405 AttributeKind::WindowsSubsystem(..) => (),
406 }
408 }
409
410 fn check_path(&self, span: Span, hir_id: HirId) {
411 let Node::Item(item) = self.tcx.hir_node(hir_id) else {
412 return;
413 };
414
415 let ItemKind::Mod(_, module) = &item.kind else {
416 return;
417 };
418
419 if item.span == module.spans.inner_span || !item.span.contains(module.spans.inner_span) {
420 return;
421 }
422
423 if self.has_nested_module_path_dependency(module) {
426 return;
427 }
428
429 self.tcx.emit_node_span_lint(
430 UNUSED_ATTRIBUTES,
431 hir_id,
432 span,
433 diagnostics::Unused {
434 attr_span: span,
435 note: diagnostics::UnusedNote::PathOnInlineModule,
436 },
437 );
438 }
439
440 fn has_nested_module_path_dependency(&self, module: &Mod<'tcx>) -> bool {
441 module.item_ids.iter().any(|item_id| {
442 let child = self.tcx.hir_item(*item_id);
443
444 let ItemKind::Mod(_, child_module) = &child.kind else {
445 return false;
446 };
447
448 let is_out_of_line = child.span == child_module.spans.inner_span
449 || !child.span.contains(child_module.spans.inner_span);
450
451 let has_path_attr = {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(child.hir_id(),
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Path(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, child.hir_id(), Path(..));
452
453 is_out_of_line || has_path_attr || self.has_nested_module_path_dependency(child_module)
454 })
455 }
456
457 fn check_rustc_must_implement_one_of(
458 &self,
459 attr_span: Span,
460 list: &ThinVec<Ident>,
461 hir_id: HirId,
462 target: Target,
463 ) {
464 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::Trait => true,
_ => false,
}matches!(target, Target::Trait) {
467 return;
468 }
469
470 let def_id = hir_id.owner.def_id;
471
472 let items = self.tcx.associated_items(def_id);
473 for ident in list {
476 let item = items
477 .filter_by_name_unhygienic(ident.name)
478 .find(|item| item.ident(self.tcx) == *ident);
479
480 match item {
481 Some(item) if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { .. }) => {
482 if !item.defaultness(self.tcx).has_value() {
483 self.tcx.dcx().emit_err(
484 diagnostics::FunctionNotHaveDefaultImplementation {
485 span: self.tcx.def_span(item.def_id),
486 note_span: attr_span,
487 },
488 );
489 }
490 }
491 Some(item) => {
492 self.dcx().emit_err(diagnostics::MustImplementNotFunction {
493 span: self.tcx.def_span(item.def_id),
494 span_note: diagnostics::MustImplementNotFunctionSpanNote {
495 span: attr_span,
496 },
497 note: diagnostics::MustImplementNotFunctionNote {},
498 });
499 }
500 None => {
501 self.dcx().emit_err(diagnostics::FunctionNotFoundInTrait { span: ident.span });
502 }
503 }
504 }
505 }
506
507 fn check_eii_impl(&self, eii_impl: &EiiImpl) {
510 let EiiImpl { span, inner_span, resolution, impl_unsafe_span, is_default: _ } = eii_impl;
511 let impl_unsafe = match resolution {
512 EiiImplResolution::Macro(eii_macro) => {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(*eii_macro, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
impl_unsafe, .. })) => {
break 'done Some(*impl_unsafe);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
513 self.tcx,
514 *eii_macro,
515 EiiDeclaration(EiiDecl { impl_unsafe, .. }) => *impl_unsafe
516 ),
517 EiiImplResolution::Known(foreign_item_did) => self
518 .tcx
519 .externally_implementable_items(foreign_item_did.krate)
520 .get(foreign_item_did)
521 .map(|(decl, _)| decl.impl_unsafe),
522 EiiImplResolution::Error(_) => None,
523 };
524 let Some(needs_unsafe) = impl_unsafe else {
525 return;
526 };
527
528 let name = match resolution {
529 EiiImplResolution::Macro(eii_macro) => self.tcx.item_name(*eii_macro),
530 EiiImplResolution::Known(def_id) => self.tcx.item_name(*def_id),
531 EiiImplResolution::Error(_) => ::core::panicking::unreachable_default_msg()unreachable!(),
532 };
533
534 match (needs_unsafe, *impl_unsafe_span) {
535 (true, None) => {
536 self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe {
537 span: *span,
538 name,
539 suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion {
540 left: inner_span.shrink_to_lo(),
541 right: inner_span.shrink_to_hi(),
542 },
543 });
544 }
545 (false, Some(unsafe_span)) => {
546 self.dcx().emit_err(diagnostics::EiiImplCannotBeUnsafe {
547 impl_span: *span,
548 unsafe_span,
549 name,
550 });
551 }
552 _ => {}
553 }
554 }
555
556 fn check_diagnostic_on_unimplemented(&self, hir_id: HirId, directive: Option<&Directive>) {
558 if let Some(directive) = directive {
559 if let Node::Item(Item {
560 kind: ItemKind::Trait { ident: trait_name, generics, .. },
561 ..
562 }) = self.tcx.hir_node(hir_id)
563 {
564 directive.visit_params(&mut |argument_name, span| {
565 let has_generic = generics.params.iter().any(|p| {
566 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
567 && let ParamName::Plain(name) = p.name
568 && name.name == argument_name
569 {
570 true
571 } else {
572 false
573 }
574 });
575 if !has_generic {
576 self.tcx.emit_node_span_lint(
577 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
578 hir_id,
579 span,
580 diagnostics::UnknownFormatParameterForOnUnimplementedAttr {
581 argument_name,
582 trait_name: *trait_name,
583 help: !directive.is_rustc_attr,
584 },
585 )
586 }
587 })
588 }
589 }
590 }
591
592 fn check_diagnostic_on_const(
594 &self,
595 attr_path_span: Span,
596 hir_id: HirId,
597 target: Target,
598 item: Option<&'tcx Item<'tcx>>,
599 directive: Option<&Directive>,
600 ) {
601 if target == (Target::Impl { of_trait: true }) {
604 if let Some(directive) = directive
605 && let Node::Item(Item { kind: ItemKind::Impl(hir::Impl { generics, .. }), .. }) =
606 self.tcx.hir_node(hir_id)
607 {
608 directive.visit_params(&mut |argument_name, span| {
609 let has_generic = generics.params.iter().any(|p| {
610 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
611 && let ParamName::Plain(name) = p.name
612 && name.name == argument_name
613 {
614 true
615 } else {
616 false
617 }
618 });
619 if !has_generic {
620 self.tcx.emit_node_span_lint(
621 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
622 hir_id,
623 span,
624 diagnostics::OnConstMalformedFormatLiterals { name: argument_name },
625 )
626 }
627 });
628 }
629 match item.unwrap().expect_impl().constness {
630 Constness::Const { .. } => {
631 let item_span = self.tcx.hir_span(hir_id);
632 self.tcx.emit_node_span_lint(
633 MISPLACED_DIAGNOSTIC_ATTRIBUTES,
634 hir_id,
635 attr_path_span,
636 DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
637 );
638 return;
639 }
640 Constness::NotConst => return,
641 }
642 }
643 }
644
645 fn check_diagnostic_on_move(&self, hir_id: HirId, directive: Option<&Directive>) {
647 if let Some(directive) = directive {
648 if let Node::Item(Item {
649 kind:
650 ItemKind::Struct(_, generics, _)
651 | ItemKind::Enum(_, generics, _)
652 | ItemKind::Union(_, generics, _),
653 ..
654 }) = self.tcx.hir_node(hir_id)
655 {
656 directive.visit_params(&mut |argument_name, span| {
657 let has_generic = generics.params.iter().any(|p| {
658 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
659 && let ParamName::Plain(name) = p.name
660 && name.name == argument_name
661 {
662 true
663 } else {
664 false
665 }
666 });
667 if !has_generic {
668 self.tcx.emit_node_span_lint(
669 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
670 hir_id,
671 span,
672 diagnostics::OnMoveMalformedFormatLiterals { name: argument_name },
673 )
674 }
675 });
676 }
677 }
678 }
679
680 fn check_diagnostic_on_type_error(&self, hir_id: HirId, directive: Option<&Directive>) {
681 if let Some(directive) = directive {
682 if let Node::Item(Item {
683 kind:
684 ItemKind::Struct(_, generics, _)
685 | ItemKind::Enum(_, generics, _)
686 | ItemKind::Union(_, generics, _),
687 ..
688 }) = self.tcx.hir_node(hir_id)
689 {
690 let generic_count = generics
691 .params
692 .iter()
693 .filter(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. }))
694 .count();
695
696 if generic_count != 1 {
698 self.tcx.emit_node_span_lint(
699 MALFORMED_DIAGNOSTIC_ATTRIBUTES,
700 hir_id,
701 generics.span,
702 diagnostics::OnTypeErrorNotExactlyOneGeneric { count: generic_count },
703 );
704 }
705
706 directive.visit_params(&mut |argument_name, span| {
707 let has_generic = generics.params.iter().any(|p| {
708 if !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(p.kind, GenericParamKind::Lifetime { .. })
709 && let ParamName::Plain(name) = p.name
710 && name.name == argument_name
711 {
712 true
713 } else {
714 false
715 }
716 });
717
718 let is_allowed = argument_name == sym::expected || argument_name == sym::found;
719 if !(has_generic | is_allowed) {
720 self.tcx.emit_node_span_lint(
721 MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
722 hir_id,
723 span,
724 diagnostics::OnTypeErrorMalformedFormatLiterals { name: argument_name },
725 )
726 }
727 });
728 }
729 }
730 }
731
732 fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
733 if let Some(location) = match target {
734 Target::AssocTy(_) => {
735 if let DefKind::Impl { .. } =
736 self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
737 {
738 Some("type alias in implementation block")
739 } else {
740 None
741 }
742 }
743 Target::AssocConst(_) => {
744 let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
745 let containing_item = self.tcx.hir_expect_item(parent_def_id);
746 let err = "associated constant in trait implementation block";
748 match containing_item.kind {
749 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
750 _ => None,
751 }
752 }
753 Target::Param => return,
755 Target::Expression
756 | Target::Statement
757 | Target::Arm
758 | Target::ForeignMod
759 | Target::Closure
760 | Target::Impl { .. }
761 | Target::WherePredicate => Some(target.name()),
762 Target::ExternCrate
763 | Target::Use
764 | Target::Static
765 | Target::Const
766 | Target::Fn
767 | Target::Mod
768 | Target::GlobalAsm
769 | Target::TyAlias
770 | Target::Enum
771 | Target::Variant
772 | Target::Struct
773 | Target::Field
774 | Target::Union
775 | Target::Trait
776 | Target::TraitAlias
777 | Target::Method(..)
778 | Target::ForeignFn
779 | Target::ForeignStatic
780 | Target::ForeignTy
781 | Target::TypeParam
782 | Target::LifetimeParam
783 | Target::ConstParam
784 | Target::MacroDef
785 | Target::PatField
786 | Target::ExprField
787 | Target::Crate
788 | Target::MacroCall
789 | Target::Delegation { .. }
790 | Target::Loop
791 | Target::ForLoop
792 | Target::While
793 | Target::Break => None,
794 } {
795 self.tcx.dcx().emit_err(diagnostics::DocAliasBadLocation { span, location });
796 return;
797 }
798 if self.tcx.hir_opt_name(hir_id) == Some(alias) {
799 self.tcx.dcx().emit_err(diagnostics::DocAliasNotAnAlias { span, attr_str: alias });
800 return;
801 }
802 }
803
804 fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
805 let item_kind = match self.tcx.hir_node(hir_id) {
806 hir::Node::Item(item) => Some(&item.kind),
807 _ => None,
808 };
809 match item_kind {
810 Some(ItemKind::Impl(i)) => {
811 let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
812 || if let Some(&[hir::GenericArg::Type(ty)]) = i
813 .of_trait
814 .and_then(|of_trait| of_trait.trait_ref.path.segments.last())
815 .map(|last_segment| last_segment.args().args)
816 {
817 #[allow(non_exhaustive_omitted_patterns)] match &ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&ty.kind, hir::TyKind::Tup([_]))
818 } else {
819 false
820 };
821 if !is_valid {
822 self.dcx().emit_err(diagnostics::DocFakeVariadicNotValid { span });
823 }
824 }
825 _ => {
826 self.dcx().emit_err(diagnostics::DocKeywordOnlyImpl { span });
827 }
828 }
829 }
830
831 fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
832 let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
833 self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
834 return;
835 };
836 match item.kind {
837 ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
838 if generics.params.len() != 0 => {}
839 ItemKind::Trait { generics, items, .. }
840 if generics.params.len() != 0
841 || items.iter().any(|item| {
842 #[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)
843 }) => {}
844 ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
845 _ => {
846 self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
847 }
848 }
849 }
850
851 fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
852 if target != Target::ExternCrate {
853 self.tcx.emit_node_span_lint(
854 INVALID_DOC_ATTRIBUTES,
855 hir_id,
856 span,
857 diagnostics::DocMaskedOnlyExternCrate {
858 attr_span: span,
859 item_span: self.tcx.hir_span(hir_id),
860 },
861 );
862 return;
863 }
864
865 if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
866 self.tcx.emit_node_span_lint(
867 INVALID_DOC_ATTRIBUTES,
868 hir_id,
869 span,
870 diagnostics::DocMaskedNotExternCrateSelf {
871 attr_span: span,
872 item_span: self.tcx.hir_span(hir_id),
873 },
874 );
875 }
876 }
877
878 fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
880 let DocAttribute {
881 first_span: _,
882 aliases,
883 hidden: _,
886 inline: _,
888 cfg: _,
890 auto_cfg: _,
892 auto_cfg_change: _,
894 fake_variadic,
895 keyword: _,
897 masked,
898 notable_trait: _,
900 search_unbox,
901 html_favicon_url: _,
903 html_logo_url: _,
905 html_playground_url: _,
907 html_root_url: _,
909 html_no_source: _,
911 issue_tracker_base_url: _,
913 rust_logo: _,
915 test_attrs: _,
917 no_crate_inject: _,
919 attribute: _,
921 } = attr;
922
923 for (alias, span) in aliases {
924 self.check_doc_alias_value(*span, hir_id, target, *alias);
925 }
926
927 if let Some(span) = fake_variadic {
928 self.check_doc_fake_variadic(*span, hir_id);
929 }
930
931 if let Some(span) = search_unbox {
932 self.check_doc_search_unbox(*span, hir_id);
933 }
934
935 if let Some(span) = masked {
936 self.check_doc_masked(*span, hir_id, target);
937 }
938 }
939
940 fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
942 let hir::Node::GenericParam(
943 param @ GenericParam {
944 kind: hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. },
945 ..
946 },
947 ) = self.tcx.hir_node(hir_id)
948 else {
949 self.dcx().delayed_bug("Checked in attr parser");
950 return;
951 };
952
953 if #[allow(non_exhaustive_omitted_patterns)] match param.source {
hir::GenericParamSource::Generics => true,
_ => false,
}matches!(param.source, hir::GenericParamSource::Generics)
954 && let parent_hir_id = self.tcx.parent_hir_id(hir_id)
955 && let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
956 && let hir::ItemKind::Impl(impl_) = item.kind
957 && let Some(of_trait) = impl_.of_trait
958 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
959 && self.tcx.is_lang_item(def_id, LangItem::Drop)
960 {
961 return;
962 }
963
964 self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
965 }
966
967 fn check_repr(
969 &self,
970 attrs: &[Attribute],
971 span: Span,
972 target: Target,
973 item: Option<&'tcx Item<'tcx>>,
974 hir_id: HirId,
975 ) {
976 let (reprs, _first_attr_span) =
982 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Repr { reprs, first_span })
=> {
break 'done Some((reprs.as_slice(), Some(*first_span)));
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span)))
983 .unwrap_or((&[], None));
984
985 let mut int_reprs = 0;
986 let mut is_explicit_rust = false;
987 let mut is_c = false;
988 let mut is_simd = false;
989 let mut is_transparent = false;
990
991 for (repr, _repr_span) in reprs {
992 match repr {
993 ReprAttr::ReprRust => {
994 is_explicit_rust = true;
995 }
996 ReprAttr::ReprC => {
997 is_c = true;
998 }
999 ReprAttr::ReprAlign(..) => (),
1000 ReprAttr::ReprPacked(..) => (),
1001 ReprAttr::ReprSimd => {
1002 is_simd = true;
1003 }
1004 ReprAttr::ReprTransparent => {
1005 is_transparent = true;
1006 }
1007 ReprAttr::ReprInt(..) => {
1008 int_reprs += 1;
1009 }
1010 };
1011 }
1012
1013 if !reprs.is_empty() {
1014 let sorted_reprs = {
1015 let mut to_sort = reprs.to_owned();
1016 to_sort.sort_unstable_by_key(|(attr, span)| (*attr, span.lo_hi()));
1017 to_sort
1018 };
1019
1020 let spans: Vec<Span> = sorted_reprs
1025 .chunk_by(|(a, _), (b, _)| a == b)
1026 .map(ToOwned::to_owned)
1027 .filter(|slice| slice.len() != 1)
1028 .flatten()
1029 .map(|(_, span)| span)
1030 .collect();
1031
1032 if !spans.is_empty() {
1033 self.tcx.emit_node_span_lint(
1034 REPEATED_REPRS,
1035 hir_id,
1036 spans,
1037 diagnostics::RepeatedRepr,
1038 );
1039 }
1040 }
1041
1042 let hint_spans = reprs.iter().map(|(_, span)| *span);
1045
1046 if is_transparent && reprs.len() > 1 {
1048 let hint_spans = hint_spans.clone().collect();
1049 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1050 hint_spans,
1051 target: target.to_string(),
1052 });
1053 }
1054 if is_transparent
1057 && let Some(&pass_indirectly_span) =
1058 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcPassIndirectlyInNonRusticAbis(span))
=> {
break 'done Some(span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcPassIndirectlyInNonRusticAbis(span) => span)
1059 {
1060 self.dcx().emit_err(diagnostics::TransparentIncompatible {
1061 hint_spans: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span, pass_indirectly_span]))vec![span, pass_indirectly_span],
1062 target: target.to_string(),
1063 });
1064 }
1065 if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
1066 let hint_spans = hint_spans.clone().collect();
1067 self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
1068 }
1069 if (int_reprs > 1)
1071 || (is_simd && is_c)
1072 || (int_reprs == 1 && is_c && item.is_some_and(is_c_like_enum))
1073 {
1074 self.tcx.emit_node_span_lint(
1075 CONFLICTING_REPR_HINTS,
1076 hir_id,
1077 hint_spans.collect::<Vec<Span>>(),
1078 diagnostics::ReprConflictingLint,
1079 );
1080 }
1081 }
1082
1083 fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
1087 if target != Target::Fn {
1088 return;
1089 }
1090
1091 let tcx = self.tcx;
1092 let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
1093 return;
1094 };
1095 let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
1096 return;
1097 };
1098
1099 let def_id = hir_id.expect_owner().def_id;
1100 let param_env = ty::ParamEnv::empty();
1101
1102 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1103 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1104
1105 let span = tcx.def_span(def_id);
1106 let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
1107 let sig = tcx.liberate_late_bound_regions(
1108 def_id.to_def_id(),
1109 tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
1110 );
1111
1112 let mut cause = ObligationCause::misc(span, def_id);
1113 let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
1114
1115 let errors = ocx.try_evaluate_obligations();
1117 if !errors.no_errors() {
1118 return;
1119 }
1120
1121 let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
1122 std::iter::repeat_n(
1123 token_stream,
1124 match kind {
1125 ProcMacroKind::Attribute => 2,
1126 ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
1127 },
1128 ),
1129 token_stream,
1130 );
1131
1132 if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
1133 let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
1134
1135 let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
1136 if let Some(hir_sig) = hir_sig {
1137 match terr {
1138 TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
1139 if let Some(ty) = hir_sig.decl.inputs.get(idx) {
1140 diag.span(ty.span);
1141 cause.span = ty.span;
1142 } else if idx == hir_sig.decl.inputs.len() {
1143 let span = hir_sig.decl.output.span();
1144 diag.span(span);
1145 cause.span = span;
1146 }
1147 }
1148 TypeError::ArgCount => {
1149 if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
1150 diag.span(ty.span);
1151 cause.span = ty.span;
1152 }
1153 }
1154 TypeError::SafetyMismatch(_) => {
1155 }
1157 TypeError::AbiMismatch(_) => {
1158 }
1160 TypeError::VariadicMismatch(_) => {
1161 }
1163 _ => {}
1164 }
1165 }
1166
1167 infcx.err_ctxt().note_type_err(
1168 &mut diag,
1169 &cause,
1170 None,
1171 Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
1172 expected: ty::Binder::dummy(expected_sig),
1173 found: ty::Binder::dummy(sig),
1174 }))),
1175 terr,
1176 false,
1177 None,
1178 );
1179 diag.emit();
1180 self.abort.set(true);
1181 }
1182
1183 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1184 if let TraitErrors::HasErrors(errors) = errors {
1185 infcx.err_ctxt().report_fulfillment_errors(errors);
1186 self.abort.set(true);
1187 }
1188 }
1189
1190 fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
1191 if let (Target::Closure, None) = (
1192 target,
1193 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
1194 ) {
1195 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!(
1196 self.tcx.hir_expect_expr(hir_id).kind,
1197 hir::ExprKind::Closure(hir::Closure {
1198 kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
1199 ..
1200 })
1201 );
1202 let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
1203 let parent_span = self.tcx.def_span(parent_did);
1204
1205 if let Some(attr_span) = {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(parent_did, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(InlineAttr::Force {
attr_span, .. }, _)) => {
break 'done Some(*attr_span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
1206 self.tcx, parent_did,
1207 Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
1208 ) && is_coro
1209 {
1210 self.dcx()
1211 .emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
1212 }
1213 }
1214 }
1215
1216 fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
1217 if let Some(export_name_span) =
1218 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ExportName {
span: export_name_span, .. }) => {
break 'done Some(*export_name_span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, ExportName { span: export_name_span, .. } => *export_name_span)
1219 && let Some(no_mangle_span) =
1220 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoMangle(no_mangle_span))
=> {
break 'done Some(*no_mangle_span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, NoMangle(no_mangle_span) => *no_mangle_span)
1221 {
1222 let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
1223 "#[unsafe(no_mangle)]"
1224 } else {
1225 "#[no_mangle]"
1226 };
1227 let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
1228 "#[unsafe(export_name)]"
1229 } else {
1230 "#[export_name]"
1231 };
1232
1233 self.tcx.emit_node_span_lint(
1234 UNUSED_ATTRIBUTES,
1235 hir_id,
1236 no_mangle_span,
1237 diagnostics::MixedExportNameAndNoMangle {
1238 no_mangle_span,
1239 export_name_span,
1240 no_mangle_attr,
1241 export_name_attr,
1242 },
1243 );
1244 }
1245 }
1246
1247 fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
1248 if let Some(optimize_span) =
1249 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Optimize(OptimizeAttr::DoNotOptimize,
span)) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Optimize(OptimizeAttr::DoNotOptimize, span) => *span)
1250 && let Some((inline_attr, inline_span)) =
1251 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(inline_attr, span))
=> {
break 'done Some((inline_attr, *span));
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Inline(inline_attr, span) => (inline_attr, *span))
1252 && inline_attr != &InlineAttr::Never
1253 {
1254 self.dcx()
1255 .emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
1256 }
1257 }
1258
1259 fn check_linkage(
1260 &self,
1261 span: Span,
1262 hir_id: HirId,
1263 target: Target,
1264 item: Option<&'tcx Item<'tcx>>,
1265 ) {
1266 match target {
1269 Target::ForeignStatic
1270 if self.tcx.is_mutable_static(hir_id.expect_owner().def_id.into()) =>
1271 {
1272 self.tcx.dcx().emit_err(diagnostics::StaticMutLinkage { span });
1273 }
1274 Target::Fn
1275 if let Item { kind: ItemKind::Fn { sig, .. }, .. } = item.unwrap()
1276 && #[allow(non_exhaustive_omitted_patterns)] match sig.header.constness {
Constness::Const { .. } => true,
_ => false,
}matches!(sig.header.constness, Constness::Const { .. }) =>
1277 {
1278 self.tcx.dcx().emit_err(diagnostics::ConstFnLinkage { span });
1279 }
1280 _ => {}
1281 }
1282 }
1283
1284 fn check_rustc_assert_variance(
1285 &self,
1286 span: Span,
1287 attr_span: Span,
1288 hir_id: HirId,
1289 target: Target,
1290 kind: RustcAssertVarianceKind,
1291 ) {
1292 if !#[allow(non_exhaustive_omitted_patterns)] match target {
Target::TypeParam | Target::LifetimeParam | Target::ConstParam => true,
_ => false,
}matches!(target, Target::TypeParam | Target::LifetimeParam | Target::ConstParam) {
1294 return;
1295 }
1296
1297 let Node::GenericParam(param) = self.tcx.hir_node(hir_id) else { return };
1298 let owner = hir_id.owner.to_def_id();
1299 let variances = self.tcx.variances_of(owner);
1300 let generics = self.tcx.generics_of(owner);
1301
1302 let variance = generics
1303 .own_params
1304 .iter()
1305 .zip(variances.iter())
1306 .filter(|(other_param, _)| other_param.def_id == param.def_id.to_def_id())
1307 .map(|(_, variance)| variance)
1308 .nth(0)
1309 .expect("generic parameter should have variance");
1310
1311 match (kind, variance) {
1312 (RustcAssertVarianceKind::Covariant, Variance::Covariant) => {}
1313 (RustcAssertVarianceKind::Invariant, Variance::Invariant) => {}
1314 (RustcAssertVarianceKind::Contravariant, Variance::Contravariant) => {}
1315 (RustcAssertVarianceKind::Bivariant, Variance::Bivariant) => {}
1316 (asserted, actual) => {
1317 let expected_variance = match asserted {
1318 RustcAssertVarianceKind::Covariant => sym::covariant,
1319 RustcAssertVarianceKind::Invariant => sym::invariant,
1320 RustcAssertVarianceKind::Contravariant => sym::contravariant,
1321 RustcAssertVarianceKind::Bivariant => sym::bivariant,
1322 };
1323
1324 let actual_variance = match actual {
1325 Variance::Covariant => sym::covariant,
1326 Variance::Invariant => sym::invariant,
1327 Variance::Contravariant => sym::contravariant,
1328 Variance::Bivariant => sym::bivariant,
1329 };
1330
1331 let item_ident = self.tcx.item_ident(owner);
1332
1333 let note = diagnostics::RustcAssertVarianceFailedNote { span: attr_span };
1334 self.tcx.dcx().emit_err(diagnostics::RustcAssertVarianceFailed {
1335 item_span: self.tcx.def_span(owner),
1336 note,
1337 param_ident: param.name.ident(),
1338 param_span: span,
1339 item_ident,
1340 expected_variance,
1341 actual_variance,
1342 });
1343 }
1344 }
1345 }
1346
1347 fn check_lint_check(&self, hir_id: HirId, lints: &[LintCheck]) {
1348 for LintCheck { lint_name, lint_span, .. } in lints {
1349 if lint_name.is(sym::dead_code_pub_in_binary) {
1350 if !self.tcx.crate_types().contains(&CrateType::Executable) {
1351 self.tcx.emit_node_span_lint(
1352 UNUSED_ATTRIBUTES,
1353 hir_id,
1354 *lint_span,
1355 diagnostics::Unused {
1356 attr_span: *lint_span,
1357 note: diagnostics::UnusedNote::NoEffectDeadCodePubInBinary,
1358 },
1359 );
1360 }
1361 }
1362
1363 if lint_name.is(sym::linker_messages) | lint_name.is(sym::linker_info) {
1364 if hir_id == CRATE_HIR_ID
1365 && self
1366 .tcx
1367 .crate_types()
1368 .iter()
1369 .all(|kind| #[allow(non_exhaustive_omitted_patterns)] match kind {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(kind, CrateType::Rlib | CrateType::StaticLib))
1370 {
1371 self.tcx.emit_node_span_lint(
1372 UNUSED_ATTRIBUTES,
1373 hir_id,
1374 *lint_span,
1375 diagnostics::Unused {
1376 attr_span: *lint_span,
1377 note: diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly,
1378 },
1379 );
1380 }
1381 }
1382 }
1383 }
1384}
1385
1386impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1387 type NestedFilter = nested_filter::OnlyBodies;
1388
1389 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1390 self.tcx
1391 }
1392
1393 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1394 if let ItemKind::Macro(_, macro_def, _) = item.kind {
1398 let def_id = item.owner_id.to_def_id();
1399 if macro_def.macro_rules && !{
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(MacroExport { .. }) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def_id, MacroExport { .. }) {
1400 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
1401 }
1402 }
1403
1404 let target = Target::from(item);
1405 self.check_attributes(item.hir_id(), item.span, target, Some(item));
1406 intravisit::walk_item(self, item)
1407 }
1408
1409 fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
1410 self.check_attributes(
1411 where_predicate.hir_id,
1412 where_predicate.span,
1413 Target::WherePredicate,
1414 None,
1415 );
1416 intravisit::walk_where_predicate(self, where_predicate)
1417 }
1418
1419 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1420 let target = Target::from(generic_param);
1421 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
1422 intravisit::walk_generic_param(self, generic_param)
1423 }
1424
1425 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1426 let target = Target::from(trait_item);
1427 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
1428 intravisit::walk_trait_item(self, trait_item)
1429 }
1430
1431 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1432 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
1433 intravisit::walk_field_def(self, struct_field);
1434 }
1435
1436 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1437 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
1438 intravisit::walk_arm(self, arm);
1439 }
1440
1441 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1442 let target = Target::from(f_item);
1443 self.check_attributes(f_item.hir_id(), f_item.span, target, None);
1444 intravisit::walk_foreign_item(self, f_item)
1445 }
1446
1447 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1448 let target = target_from_impl_item(self.tcx, impl_item);
1449 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
1450 intravisit::walk_impl_item(self, impl_item)
1451 }
1452
1453 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1454 if let hir::StmtKind::Let(l) = stmt.kind {
1456 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
1457 }
1458 intravisit::walk_stmt(self, stmt)
1459 }
1460
1461 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1462 let target = match expr.kind {
1463 hir::ExprKind::Closure { .. } => Target::Closure,
1464 _ => Target::Expression,
1465 };
1466
1467 self.check_attributes(expr.hir_id, expr.span, target, None);
1468 intravisit::walk_expr(self, expr)
1469 }
1470
1471 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
1472 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
1473 intravisit::walk_expr_field(self, field)
1474 }
1475
1476 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
1477 self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
1478 intravisit::walk_variant(self, variant)
1479 }
1480
1481 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1482 self.check_attributes(param.hir_id, param.span, Target::Param, None);
1483
1484 intravisit::walk_param(self, param);
1485 }
1486
1487 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
1488 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
1489 intravisit::walk_pat_field(self, field);
1490 }
1491}
1492
1493fn is_c_like_enum(item: &Item<'_>) -> bool {
1494 if let ItemKind::Enum(_, _, ref def) = item.kind {
1495 for variant in def.variants {
1496 match variant.data {
1497 hir::VariantData::Unit(..) => { }
1498 _ => return false,
1499 }
1500 }
1501 true
1502 } else {
1503 false
1504 }
1505}
1506
1507fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
1508 let attrs = tcx.hir_attrs(item.hir_id());
1509
1510 if let Some(attr_span) =
1511 {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(i, span)) if
!#[allow(non_exhaustive_omitted_patterns)] match i {
InlineAttr::Force { .. } => true,
_ => false,
} => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
1512 {
1513 tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
1514 }
1515}
1516
1517fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModId) {
1518 let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
1519 tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
1520 if module_def_id.to_local_def_id().is_top_level_module() {
1521 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
1522 }
1523 if check_attr_visitor.abort.get() {
1524 tcx.dcx().abort_if_errors()
1525 }
1526}
1527
1528pub(crate) fn provide(providers: &mut Providers) {
1529 *providers = Providers { check_mod_attrs, ..*providers };
1530}
1531
1532fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
1533 #[allow(non_exhaustive_omitted_patterns)] match &self_ty.kind {
hir::TyKind::Tup([_]) => true,
_ => false,
}matches!(&self_ty.kind, hir::TyKind::Tup([_]))
1534 || if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
1535 fn_ptr_ty.decl.inputs.len() == 1
1536 } else {
1537 false
1538 }
1539 || (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
1540 && let Some(&[hir::GenericArg::Type(ty)]) =
1541 path.segments.last().map(|last| last.args().args)
1542 {
1543 doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
1544 } else {
1545 false
1546 })
1547}