blob: 6ba7c81333f404ebd809fcee640bbff7bf9eb0de [file]
// FIXME(jdonszelmann): should become rustc_attr_validation
//! This module implements some validity checks for attributes.
//! In particular it verifies that `#[inline]` and `#[repr]` attributes are
//! attached to items that actually support them and if there are
//! conflicts between multiple such attributes attached to the same
//! item.
use std::cell::Cell;
use std::slice;
use rustc_attr_ir::diagnostic::Directive;
use rustc_attr_ir::lang_items::LangItem;
use rustc_attr_ir::lint::LintCheck;
use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
use rustc_attr_ir::{
Attribute, AttributeKind, DocAttribute, EiiDecl, EiiImpl, EiiImplResolution, InlineAttr,
OptimizeAttr, ReprAttr, RustcAssertVarianceKind, find_attr,
};
use rustc_attr_parsing::AttributeParser;
use rustc_data_structures::thin_vec::ThinVec;
use rustc_errors::{DiagCtxtHandle, IntoDiagArg};
use rustc_feature::BUILTIN_ATTRIBUTE_SET;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::LocalModId;
use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{
self as hir, CRATE_HIR_ID, Constness, ForeignItem, GenericParam, GenericParamKind, HirId, Item,
ItemKind, Mod, Node, ParamName, TraitItem,
};
use rustc_lint_defs::builtin::{
CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES,
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, MISPLACED_DIAGNOSTIC_ATTRIBUTES, REPEATED_REPRS,
UNUSED_ATTRIBUTES,
};
use rustc_macros::Diagnostic;
use rustc_middle::hir::nested_filter;
use rustc_middle::query::Providers;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized, Variance};
use rustc_span::edition::Edition;
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, span_bug, sym};
use rustc_structures::CrateType;
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs};
use rustc_trait_selection::traits::{ObligationCtxt, TraitErrors};
use crate::diagnostics;
#[derive(Diagnostic)]
#[diag(
"the `diagnostic::on_const` attribute can only be applied to non-const trait implementations"
)]
struct DiagnosticOnConstOnlyForNonConstTraitImpls {
#[label("this is a const trait implementation")]
item_span: Span,
}
fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
match impl_item.kind {
hir::ImplItemKind::Const(..) => {
let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let containing_item = tcx.hir_expect_item(parent_def_id);
let of_trait = match &containing_item.kind {
hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
_ => bug!("parent of an ImplItem must be an Impl"),
};
Target::AssocConst(AssocCtxt::Impl { of_trait })
}
hir::ImplItemKind::Fn(..) => {
let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let containing_item = tcx.hir_expect_item(parent_def_id);
let containing_impl_is_for_trait = match &containing_item.kind {
hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
_ => bug!("parent of an ImplItem must be an Impl"),
};
if containing_impl_is_for_trait {
Target::Method(MethodKind::TraitImpl)
} else {
Target::Method(MethodKind::Inherent)
}
}
hir::ImplItemKind::Type(..) => {
let parent_def_id = tcx.hir_get_parent_item(impl_item.hir_id()).def_id;
let containing_item = tcx.hir_expect_item(parent_def_id);
let of_trait = match &containing_item.kind {
hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
_ => bug!("parent of an ImplItem must be an Impl"),
};
Target::AssocTy(AssocCtxt::Impl { of_trait })
}
}
}
#[derive(Copy, Clone)]
pub(crate) enum ProcMacroKind {
FunctionLike,
Derive,
Attribute,
}
impl IntoDiagArg for ProcMacroKind {
fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
match self {
ProcMacroKind::Attribute => "attribute proc macro",
ProcMacroKind::Derive => "derive proc macro",
ProcMacroKind::FunctionLike => "function-like proc macro",
}
.into_diag_arg(&mut None)
}
}
struct CheckAttrVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
// Whether or not this visitor should abort after finding errors
abort: Cell<bool>,
}
impl<'tcx> CheckAttrVisitor<'tcx> {
fn dcx(&self) -> DiagCtxtHandle<'tcx> {
self.tcx.dcx()
}
/// Checks any attribute.
fn check_attributes(
&self,
hir_id: HirId,
span: Span,
target: Target,
item: Option<&'tcx Item<'tcx>>,
) {
let attrs = self.tcx.hir_attrs(hir_id);
for attr in attrs {
match attr {
Attribute::Parsed(attr_kind) => {
self.check_one_parsed_attribute(hir_id, span, target, item, attr_kind);
}
Attribute::Tool(u) | Attribute::DeriveHelper(u) => {
match &*u.path.segments {
[name, rest @ ..] => {
if BUILTIN_ATTRIBUTE_SET.contains(name) {
if rest.len() > 0
&& AttributeParser::is_parsed_attribute(slice::from_ref(name))
{
// Check if we tried to use a builtin attribute as an attribute
// namespace, like `#[must_use::skip]`. This check is here to
// solve <https://github.com/rust-lang/rust/issues/137590>.
// An error is already produced for this case elsewhere.
return;
}
span_bug!(
u.span,
"builtin attribute {name:?} not handled by `CheckAttrVisitor`"
)
}
}
[] => unreachable!(),
}
}
}
}
self.check_repr(attrs, span, target, item, hir_id);
self.check_rustc_force_inline(hir_id, attrs, target);
self.check_mix_no_mangle_export(hir_id, attrs);
self.check_optimize_and_inline(attrs);
}
/// Called by [`Self::check_attributes()`] to check a single attribute which is
/// [`Attribute::Parsed`].
///
/// This is a separate function to help with comprehensibility and rustfmt-ability.
fn check_one_parsed_attribute(
&self,
hir_id: HirId,
span: Span,
target: Target,
item: Option<&'tcx Item<'tcx>>,
attr: &AttributeKind,
) {
match attr {
AttributeKind::ProcMacro => {
self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike)
}
AttributeKind::ProcMacroAttribute => {
self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute);
}
AttributeKind::ProcMacroDerive { .. } => {
self.check_proc_macro(hir_id, target, ProcMacroKind::Derive)
}
AttributeKind::MayDangle(attr_span) => self.check_may_dangle(hir_id, *attr_span),
AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target),
AttributeKind::EiiImpl(eii_impl) => self.check_eii_impl(eii_impl),
AttributeKind::RustcMustImplementOneOf { attr_span, fn_names } => {
self.check_rustc_must_implement_one_of(*attr_span, fn_names, hir_id, target)
}
AttributeKind::OnUnimplemented { directive } => {
self.check_diagnostic_on_unimplemented(hir_id, directive.as_deref())
}
AttributeKind::OnConst { span, directive } => {
self.check_diagnostic_on_const(*span, hir_id, target, item, directive.as_deref())
}
AttributeKind::OnMove { directive } => {
self.check_diagnostic_on_move(hir_id, directive.as_deref())
}
AttributeKind::OnTypeError { directive, .. } => {
self.check_diagnostic_on_type_error(hir_id, directive.as_deref())
}
AttributeKind::Linkage(_linkage, span) => {
self.check_linkage(*span, hir_id, target, item)
}
AttributeKind::RustcAssertVariance { span: attr_span, kind } => {
self.check_rustc_assert_variance(span, *attr_span, hir_id, target, *kind);
}
AttributeKind::LintCheck(lints) => self.check_lint_check(hir_id, lints),
// All of the following attributes have no specific checks.
// tidy-alphabetical-start
AttributeKind::AllowInternalUnsafe(..) => (),
AttributeKind::AllowInternalUnstable(..) => (),
AttributeKind::AlwaysGca => (),
AttributeKind::AutomaticallyDerived => (),
AttributeKind::CfgAttrTrace(..) => (),
AttributeKind::CfgTrace(..) => (),
AttributeKind::CfiEncoding { .. } => (),
AttributeKind::Cold => (),
AttributeKind::CollapseDebugInfo(..) => (),
AttributeKind::CompilerBuiltins => (),
AttributeKind::ConstContinue(..) => {}
AttributeKind::Coroutine => (),
AttributeKind::Coverage(..) => (),
AttributeKind::CrateName { .. } => (),
AttributeKind::CrateType(..) => (),
AttributeKind::CustomMir(..) => (),
AttributeKind::DebuggerVisualizer(..) => (),
AttributeKind::DefaultLibAllocator => (),
AttributeKind::Deprecated { .. } => (),
AttributeKind::DoNotRecommend => (),
AttributeKind::DocComment { .. } => (),
AttributeKind::EiiDeclaration { .. } => (),
AttributeKind::ExportName { .. } => (),
AttributeKind::ExportStable => (),
AttributeKind::Feature(..) => (),
AttributeKind::FfiConst => (),
AttributeKind::FfiPure(..) => (),
AttributeKind::Fundamental => (),
AttributeKind::Ignore { .. } => (),
AttributeKind::Inline(..) => (),
AttributeKind::InstructionSet(..) => (),
AttributeKind::InstrumentFn(..) => (),
AttributeKind::Lang(..) => (),
AttributeKind::Link(..) => (),
AttributeKind::LinkName { .. } => (),
AttributeKind::LinkOrdinal { .. } => (),
AttributeKind::LinkSection { .. } => (),
AttributeKind::LintAsPtr => (),
AttributeKind::LintNeverReturnsNullPtr => (),
AttributeKind::LintShouldNotBeCalledOnConstItems => (),
AttributeKind::LoopMatch(..) => (),
AttributeKind::MacroEscape => (),
AttributeKind::MacroExport { .. } => (),
AttributeKind::MacroUse { .. } => (),
AttributeKind::Marker => (),
AttributeKind::MoveSizeLimit { .. } => (),
AttributeKind::MustNotSuspend { .. } => (),
AttributeKind::MustUse { .. } => (),
AttributeKind::Naked(..) => (),
AttributeKind::NeedsAllocator => (),
AttributeKind::NeedsPanicRuntime => (),
AttributeKind::NoBuiltins => (),
AttributeKind::NoCore { .. } => (),
AttributeKind::NoImplicitPrelude => (),
AttributeKind::NoLink => (),
AttributeKind::NoMain => (),
AttributeKind::NoMangle(..) => (),
AttributeKind::NoStd { .. } => (),
AttributeKind::NonExhaustive(_) => (),
AttributeKind::OnUnknown { .. } => (),
AttributeKind::OnUnmatchedArgs { .. } => (),
AttributeKind::Opaque => (),
AttributeKind::Optimize(..) => (),
AttributeKind::PanicRuntime => (),
AttributeKind::PatchableFunctionEntry { .. } => (),
AttributeKind::Path(_, span) => self.check_path(*span, hir_id),
AttributeKind::PatternComplexityLimit { .. } => (),
AttributeKind::PinV2(..) => (),
AttributeKind::PreludeImport => (),
AttributeKind::ProfilerRuntime => (),
AttributeKind::RecursionLimit { .. } => (),
AttributeKind::ReexportTestHarnessMain(..) => (),
AttributeKind::RegisterTool { .. } => (),
// handled below this loop and elsewhere
AttributeKind::Repr { .. } => (),
AttributeKind::RustcAbi { .. } => (),
AttributeKind::RustcAlign { .. } => {}
AttributeKind::RustcAllocator => (),
AttributeKind::RustcAllocatorZeroed => (),
AttributeKind::RustcAllocatorZeroedVariant { .. } => (),
AttributeKind::RustcAllowConstFnUnstable(..) => (),
AttributeKind::RustcAllowIncoherentImpl(..) => (),
AttributeKind::RustcAllowLifetimeDependentSpecialization => (),
AttributeKind::RustcAutodiff(..) => (),
AttributeKind::RustcBodyStability { .. } => (),
AttributeKind::RustcBuiltinMacro { .. } => (),
AttributeKind::RustcCanonicalSymbol => (),
AttributeKind::RustcCaptureAnalysis => (),
AttributeKind::RustcCguTestAttr(..) => (),
AttributeKind::RustcClean(..) => (),
AttributeKind::RustcCoherenceIsCore => (),
AttributeKind::RustcCoinductive => (),
AttributeKind::RustcComptime(_) => (),
AttributeKind::RustcConfusables { .. } => (),
AttributeKind::RustcConstStability { .. } => (),
AttributeKind::RustcConstStableIndirect => (),
AttributeKind::RustcConversionSuggestion => (),
AttributeKind::RustcDeallocator => (),
AttributeKind::RustcDelayedBugFromInsideQuery => (),
AttributeKind::RustcDenyExplicitImpl => (),
AttributeKind::RustcDeprecatedSafe2024 { .. } => (),
AttributeKind::RustcDiagnosticItem(..) => (),
AttributeKind::RustcDoNotConstCheck => (),
AttributeKind::RustcDocPrimitive(..) => (),
AttributeKind::RustcDummy => (),
AttributeKind::RustcDumpClauses => (),
AttributeKind::RustcDumpDefParents => (),
AttributeKind::RustcDumpDefPath(..) => (),
AttributeKind::RustcDumpGenerics => (),
AttributeKind::RustcDumpHiddenTypeOfOpaques => (),
AttributeKind::RustcDumpInferredOutlives => (),
AttributeKind::RustcDumpItemBounds => (),
AttributeKind::RustcDumpLayout(..) => (),
AttributeKind::RustcDumpObjectLifetimeDefaults => (),
AttributeKind::RustcDumpSymbolName(..) => (),
AttributeKind::RustcDumpUserArgs => (),
AttributeKind::RustcDumpVariances => (),
AttributeKind::RustcDumpVariancesOfOpaques => (),
AttributeKind::RustcDumpVtable(..) => (),
AttributeKind::RustcDynIncompatibleTrait(..) => (),
AttributeKind::RustcEffectiveVisibility => (),
AttributeKind::RustcEiiForeignItem => (),
AttributeKind::RustcEvaluateWhereClauses => (),
AttributeKind::RustcHasIncoherentInherentImpls => (),
AttributeKind::RustcIfThisChanged(..) => (),
AttributeKind::RustcInheritOverflowChecks => (),
AttributeKind::RustcInsignificantDtor => (),
AttributeKind::RustcIntrinsic => (),
AttributeKind::RustcIntrinsicConstStableIndirect => (),
AttributeKind::RustcLegacyConstGenerics { .. } => (),
AttributeKind::RustcLintOptDenyFieldAccess { .. } => (),
AttributeKind::RustcLintOptTy => (),
AttributeKind::RustcLintQueryInstability => (),
AttributeKind::RustcLintUntrackedQueryInformation => (),
AttributeKind::RustcMacroTransparency(_) => (),
AttributeKind::RustcMain => (),
AttributeKind::RustcMir(_) => (),
AttributeKind::RustcMustMatchExhaustively(..) => (),
AttributeKind::RustcNoImplicitAutorefs => (),
AttributeKind::RustcNoImplicitBounds => (),
AttributeKind::RustcNoMirInline => (),
AttributeKind::RustcNoWritable => (),
AttributeKind::RustcNonConstTraitMethod => (),
AttributeKind::RustcNonnullOptimizationGuaranteed => (),
AttributeKind::RustcNounwind => (),
AttributeKind::RustcObjcClass { .. } => (),
AttributeKind::RustcObjcSelector { .. } => (),
AttributeKind::RustcOffloadKernel => (),
AttributeKind::RustcPanicsWhenZero => (),
AttributeKind::RustcParenSugar => (),
AttributeKind::RustcPassByValue => (),
AttributeKind::RustcPassIndirectlyInNonRusticAbis(..) => (),
AttributeKind::RustcPreserveUbChecks => (),
AttributeKind::RustcProcMacroDecls => (),
AttributeKind::RustcPubTransparent(..) => (),
AttributeKind::RustcReallocator => (),
AttributeKind::RustcRegions => (),
AttributeKind::RustcScalableVector { .. } => (),
AttributeKind::RustcShowSpans(_) => (),
AttributeKind::RustcSimdMonomorphizeLaneLimit(..) => (),
AttributeKind::RustcSkipDuringMethodDispatch { .. } => (),
AttributeKind::RustcSpecializationTrait => (),
AttributeKind::RustcStdInternalSymbol => (),
AttributeKind::RustcStrictCoherence(..) => (),
AttributeKind::RustcTestEntrypointMarker => (),
AttributeKind::RustcTestMarker(..) => (),
AttributeKind::RustcThenThisWouldNeed(..) => (),
AttributeKind::RustcTrivialFieldReads(..) => (),
AttributeKind::Sanitize { .. } => {}
AttributeKind::ShouldPanic { .. } => (),
AttributeKind::Splat(..) => (),
AttributeKind::Stability { .. } => (),
AttributeKind::TargetFeature { .. } => {}
AttributeKind::TestRunner(..) => (),
AttributeKind::ThreadLocal => (),
AttributeKind::TrackCaller(_) => (),
AttributeKind::TypeLengthLimit { .. } => (),
AttributeKind::UncheckedTypeAlias => (),
AttributeKind::Unroll(..) => (),
AttributeKind::UnstableFeatureBound(..) => (),
AttributeKind::UnstableRemoved(..) => (),
AttributeKind::Used { .. } => (),
AttributeKind::WindowsSubsystem(..) => (),
// tidy-alphabetical-end
}
}
fn check_path(&self, span: Span, hir_id: HirId) {
let Node::Item(item) = self.tcx.hir_node(hir_id) else {
return;
};
let ItemKind::Mod(_, module) = &item.kind else {
return;
};
if item.span == module.spans.inner_span || !item.span.contains(module.spans.inner_span) {
return;
}
// Do not warn when a nested module uses `#[path]` or is out-of-line,
// because the attribute may affect nested module path resolution.
if self.has_nested_module_path_dependency(module) {
return;
}
self.tcx.emit_node_span_lint(
UNUSED_ATTRIBUTES,
hir_id,
span,
diagnostics::Unused {
attr_span: span,
note: diagnostics::UnusedNote::PathOnInlineModule,
},
);
}
fn has_nested_module_path_dependency(&self, module: &Mod<'tcx>) -> bool {
module.item_ids.iter().any(|item_id| {
let child = self.tcx.hir_item(*item_id);
let ItemKind::Mod(_, child_module) = &child.kind else {
return false;
};
let is_out_of_line = child.span == child_module.spans.inner_span
|| !child.span.contains(child_module.spans.inner_span);
let has_path_attr = find_attr!(self.tcx, child.hir_id(), Path(..));
is_out_of_line || has_path_attr || self.has_nested_module_path_dependency(child_module)
})
}
fn check_rustc_must_implement_one_of(
&self,
attr_span: Span,
list: &ThinVec<Ident>,
hir_id: HirId,
target: Target,
) {
// Ignoring invalid targets because TyCtxt::associated_items emits bug if the target isn't valid
// the parser has already produced an error for the target being invalid
if !matches!(target, Target::Trait) {
return;
}
let def_id = hir_id.owner.def_id;
let items = self.tcx.associated_items(def_id);
// Check that all arguments of `#[rustc_must_implement_one_of]` reference
// functions in the trait with default implementations
for ident in list {
let item = items
.filter_by_name_unhygienic(ident.name)
.find(|item| item.ident(self.tcx) == *ident);
match item {
Some(item) if matches!(item.kind, ty::AssocKind::Fn { .. }) => {
if !item.defaultness(self.tcx).has_value() {
self.tcx.dcx().emit_err(
diagnostics::FunctionNotHaveDefaultImplementation {
span: self.tcx.def_span(item.def_id),
note_span: attr_span,
},
);
}
}
Some(item) => {
self.dcx().emit_err(diagnostics::MustImplementNotFunction {
span: self.tcx.def_span(item.def_id),
span_note: diagnostics::MustImplementNotFunctionSpanNote {
span: attr_span,
},
note: diagnostics::MustImplementNotFunctionNote {},
});
}
None => {
self.dcx().emit_err(diagnostics::FunctionNotFoundInTrait { span: ident.span });
}
}
}
}
/// Checks that each externally implementable item (EII) implementation uses `unsafe`
/// exactly when its declaration requires it.
fn check_eii_impl(&self, eii_impl: &EiiImpl) {
let EiiImpl { span, inner_span, resolution, impl_unsafe_span, is_default: _ } = eii_impl;
let impl_unsafe = match resolution {
EiiImplResolution::Macro(eii_macro) => find_attr!(
self.tcx,
*eii_macro,
EiiDeclaration(EiiDecl { impl_unsafe, .. }) => *impl_unsafe
),
EiiImplResolution::Known(foreign_item_did) => self
.tcx
.externally_implementable_items(foreign_item_did.krate)
.get(foreign_item_did)
.map(|(decl, _)| decl.impl_unsafe),
EiiImplResolution::Error(_) => None,
};
let Some(needs_unsafe) = impl_unsafe else {
return;
};
let name = match resolution {
EiiImplResolution::Macro(eii_macro) => self.tcx.item_name(*eii_macro),
EiiImplResolution::Known(def_id) => self.tcx.item_name(*def_id),
EiiImplResolution::Error(_) => unreachable!(),
};
match (needs_unsafe, *impl_unsafe_span) {
(true, None) => {
self.dcx().emit_err(diagnostics::EiiImplRequiresUnsafe {
span: *span,
name,
suggestion: diagnostics::EiiImplRequiresUnsafeSuggestion {
left: inner_span.shrink_to_lo(),
right: inner_span.shrink_to_hi(),
},
});
}
(false, Some(unsafe_span)) => {
self.dcx().emit_err(diagnostics::EiiImplCannotBeUnsafe {
impl_span: *span,
unsafe_span,
name,
});
}
_ => {}
}
}
/// Checks use of generic formatting parameters in `#[diagnostic::on_unimplemented]`
fn check_diagnostic_on_unimplemented(&self, hir_id: HirId, directive: Option<&Directive>) {
if let Some(directive) = directive {
if let Node::Item(Item {
kind: ItemKind::Trait { ident: trait_name, generics, .. },
..
}) = self.tcx.hir_node(hir_id)
{
directive.visit_params(&mut |argument_name, span| {
let has_generic = generics.params.iter().any(|p| {
if !matches!(p.kind, GenericParamKind::Lifetime { .. })
&& let ParamName::Plain(name) = p.name
&& name.name == argument_name
{
true
} else {
false
}
});
if !has_generic {
self.tcx.emit_node_span_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
hir_id,
span,
diagnostics::UnknownFormatParameterForOnUnimplementedAttr {
argument_name,
trait_name: *trait_name,
help: !directive.is_rustc_attr,
},
)
}
})
}
}
}
/// Checks if `#[diagnostic::on_const]` is applied to a on-const trait impl
fn check_diagnostic_on_const(
&self,
attr_path_span: Span,
hir_id: HirId,
target: Target,
item: Option<&'tcx Item<'tcx>>,
directive: Option<&Directive>,
) {
// We only check the non-constness here. A diagnostic for use
// on not-trait impl items is issued during attribute parsing.
if target == (Target::Impl { of_trait: true }) {
if let Some(directive) = directive
&& let Node::Item(Item { kind: ItemKind::Impl(hir::Impl { generics, .. }), .. }) =
self.tcx.hir_node(hir_id)
{
directive.visit_params(&mut |argument_name, span| {
let has_generic = generics.params.iter().any(|p| {
if !matches!(p.kind, GenericParamKind::Lifetime { .. })
&& let ParamName::Plain(name) = p.name
&& name.name == argument_name
{
true
} else {
false
}
});
if !has_generic {
self.tcx.emit_node_span_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
hir_id,
span,
diagnostics::OnConstMalformedFormatLiterals { name: argument_name },
)
}
});
}
match item.unwrap().expect_impl().constness {
Constness::Const { .. } => {
let item_span = self.tcx.hir_span(hir_id);
self.tcx.emit_node_span_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
hir_id,
attr_path_span,
DiagnosticOnConstOnlyForNonConstTraitImpls { item_span },
);
return;
}
Constness::NotConst => return,
}
}
}
/// Checks use of generic formatting parameters in `#[diagnostic::on_move]`
fn check_diagnostic_on_move(&self, hir_id: HirId, directive: Option<&Directive>) {
if let Some(directive) = directive {
if let Node::Item(Item {
kind:
ItemKind::Struct(_, generics, _)
| ItemKind::Enum(_, generics, _)
| ItemKind::Union(_, generics, _),
..
}) = self.tcx.hir_node(hir_id)
{
directive.visit_params(&mut |argument_name, span| {
let has_generic = generics.params.iter().any(|p| {
if !matches!(p.kind, GenericParamKind::Lifetime { .. })
&& let ParamName::Plain(name) = p.name
&& name.name == argument_name
{
true
} else {
false
}
});
if !has_generic {
self.tcx.emit_node_span_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
hir_id,
span,
diagnostics::OnMoveMalformedFormatLiterals { name: argument_name },
)
}
});
}
}
}
fn check_diagnostic_on_type_error(&self, hir_id: HirId, directive: Option<&Directive>) {
if let Some(directive) = directive {
if let Node::Item(Item {
kind:
ItemKind::Struct(_, generics, _)
| ItemKind::Enum(_, generics, _)
| ItemKind::Union(_, generics, _),
..
}) = self.tcx.hir_node(hir_id)
{
let generic_count = generics
.params
.iter()
.filter(|p| !matches!(p.kind, GenericParamKind::Lifetime { .. }))
.count();
// Enforce: at most one generic
if generic_count != 1 {
self.tcx.emit_node_span_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
hir_id,
generics.span,
diagnostics::OnTypeErrorNotExactlyOneGeneric { count: generic_count },
);
}
directive.visit_params(&mut |argument_name, span| {
let has_generic = generics.params.iter().any(|p| {
if !matches!(p.kind, GenericParamKind::Lifetime { .. })
&& let ParamName::Plain(name) = p.name
&& name.name == argument_name
{
true
} else {
false
}
});
let is_allowed = argument_name == sym::expected || argument_name == sym::found;
if !(has_generic | is_allowed) {
self.tcx.emit_node_span_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
hir_id,
span,
diagnostics::OnTypeErrorMalformedFormatLiterals { name: argument_name },
)
}
});
}
}
}
fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) {
if let Some(location) = match target {
Target::AssocTy(_) => {
if let DefKind::Impl { .. } =
self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id))
{
Some("type alias in implementation block")
} else {
None
}
}
Target::AssocConst(_) => {
let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id;
let containing_item = self.tcx.hir_expect_item(parent_def_id);
// We can't link to trait impl's consts.
let err = "associated constant in trait implementation block";
match containing_item.kind {
ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
_ => None,
}
}
// we check the validity of params elsewhere
Target::Param => return,
Target::Expression
| Target::Statement
| Target::Arm
| Target::ForeignMod
| Target::Closure
| Target::Impl { .. }
| Target::WherePredicate => Some(target.name()),
Target::ExternCrate
| Target::Use
| Target::Static
| Target::Const
| Target::Fn
| Target::Mod
| Target::GlobalAsm
| Target::TyAlias
| Target::Enum
| Target::Variant
| Target::Struct
| Target::Field
| Target::Union
| Target::Trait
| Target::TraitAlias
| Target::Method(..)
| Target::ForeignFn
| Target::ForeignStatic
| Target::ForeignTy
| Target::TypeParam
| Target::LifetimeParam
| Target::ConstParam
| Target::MacroDef
| Target::PatField
| Target::ExprField
| Target::Crate
| Target::MacroCall
| Target::Delegation { .. }
| Target::Loop
| Target::ForLoop
| Target::While
| Target::Break => None,
} {
self.tcx.dcx().emit_err(diagnostics::DocAliasBadLocation { span, location });
return;
}
if self.tcx.hir_opt_name(hir_id) == Some(alias) {
self.tcx.dcx().emit_err(diagnostics::DocAliasNotAnAlias { span, attr_str: alias });
return;
}
}
fn check_doc_fake_variadic(&self, span: Span, hir_id: HirId) {
let item_kind = match self.tcx.hir_node(hir_id) {
hir::Node::Item(item) => Some(&item.kind),
_ => None,
};
match item_kind {
Some(ItemKind::Impl(i)) => {
let is_valid = doc_fake_variadic_is_allowed_self_ty(i.self_ty)
|| if let Some(&[hir::GenericArg::Type(ty)]) = i
.of_trait
.and_then(|of_trait| of_trait.trait_ref.path.segments.last())
.map(|last_segment| last_segment.args().args)
{
matches!(&ty.kind, hir::TyKind::Tup([_]))
} else {
false
};
if !is_valid {
self.dcx().emit_err(diagnostics::DocFakeVariadicNotValid { span });
}
}
_ => {
self.dcx().emit_err(diagnostics::DocKeywordOnlyImpl { span });
}
}
}
fn check_doc_search_unbox(&self, span: Span, hir_id: HirId) {
let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else {
self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
return;
};
match item.kind {
ItemKind::Enum(_, generics, _) | ItemKind::Struct(_, generics, _)
if generics.params.len() != 0 => {}
ItemKind::Trait { generics, items, .. }
if generics.params.len() != 0
|| items.iter().any(|item| {
matches!(self.tcx.def_kind(item.owner_id), DefKind::AssocTy)
}) => {}
ItemKind::TyAlias(_, generics, _) if generics.params.len() != 0 => {}
_ => {
self.dcx().emit_err(diagnostics::DocSearchUnboxInvalid { span });
}
}
}
fn check_doc_masked(&self, span: Span, hir_id: HirId, target: Target) {
if target != Target::ExternCrate {
self.tcx.emit_node_span_lint(
INVALID_DOC_ATTRIBUTES,
hir_id,
span,
diagnostics::DocMaskedOnlyExternCrate {
attr_span: span,
item_span: self.tcx.hir_span(hir_id),
},
);
return;
}
if self.tcx.extern_mod_stmt_cnum(hir_id.owner.def_id).is_none() {
self.tcx.emit_node_span_lint(
INVALID_DOC_ATTRIBUTES,
hir_id,
span,
diagnostics::DocMaskedNotExternCrateSelf {
attr_span: span,
item_span: self.tcx.hir_span(hir_id),
},
);
}
}
/// Runs various checks on `#[doc]` attributes.
fn check_doc_attrs(&self, attr: &DocAttribute, hir_id: HirId, target: Target) {
let DocAttribute {
first_span: _,
aliases,
// valid pretty much anywhere, not checked here?
// FIXME: should we?
hidden: _,
// already checked in attr_parsing
inline: _,
// FIXME: currently unchecked
cfg: _,
// already checked in attr_parsing
auto_cfg: _,
// already checked in attr_parsing
auto_cfg_change: _,
fake_variadic,
// already checked in attr_parsing
keyword: _,
masked,
// FIXME: currently unchecked
notable_trait: _,
search_unbox,
// already checked in attr_parsing
html_favicon_url: _,
// already checked in attr_parsing
html_logo_url: _,
// already checked in attr_parsing
html_playground_url: _,
// already checked in attr_parsing
html_root_url: _,
// already checked in attr_parsing
html_no_source: _,
// already checked in attr_parsing
issue_tracker_base_url: _,
// already checked in attr_parsing
rust_logo: _,
// allowed anywhere
test_attrs: _,
// already checked in attr_parsing
no_crate_inject: _,
// already checked in attr_parsing
attribute: _,
} = attr;
for (alias, span) in aliases {
self.check_doc_alias_value(*span, hir_id, target, *alias);
}
if let Some(span) = fake_variadic {
self.check_doc_fake_variadic(*span, hir_id);
}
if let Some(span) = search_unbox {
self.check_doc_search_unbox(*span, hir_id);
}
if let Some(span) = masked {
self.check_doc_masked(*span, hir_id, target);
}
}
/// Checks if `#[may_dangle]` is applied to a lifetime or type generic parameter in `Drop` impl.
fn check_may_dangle(&self, hir_id: HirId, attr_span: Span) {
let hir::Node::GenericParam(
param @ GenericParam {
kind: hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. },
..
},
) = self.tcx.hir_node(hir_id)
else {
self.dcx().delayed_bug("Checked in attr parser");
return;
};
if matches!(param.source, hir::GenericParamSource::Generics)
&& let parent_hir_id = self.tcx.parent_hir_id(hir_id)
&& let hir::Node::Item(item) = self.tcx.hir_node(parent_hir_id)
&& let hir::ItemKind::Impl(impl_) = item.kind
&& let Some(of_trait) = impl_.of_trait
&& let Some(def_id) = of_trait.trait_ref.trait_def_id()
&& self.tcx.is_lang_item(def_id, LangItem::Drop)
{
return;
}
self.dcx().emit_err(diagnostics::InvalidMayDangle { attr_span });
}
/// Checks if the `#[repr]` attributes on `item` are valid.
fn check_repr(
&self,
attrs: &[Attribute],
span: Span,
target: Target,
item: Option<&'tcx Item<'tcx>>,
hir_id: HirId,
) {
// Extract the names of all repr hints, e.g., [foo, bar, align] for:
// ```
// #[repr(foo)]
// #[repr(bar, align(8))]
// ```
let (reprs, _first_attr_span) =
find_attr!(attrs, Repr { reprs, first_span } => (reprs.as_slice(), Some(*first_span)))
.unwrap_or((&[], None));
let mut int_reprs = 0;
let mut is_explicit_rust = false;
let mut is_c = false;
let mut is_simd = false;
let mut is_transparent = false;
for (repr, _repr_span) in reprs {
match repr {
ReprAttr::ReprRust => {
is_explicit_rust = true;
}
ReprAttr::ReprC => {
is_c = true;
}
ReprAttr::ReprAlign(..) => (),
ReprAttr::ReprPacked(..) => (),
ReprAttr::ReprSimd => {
is_simd = true;
}
ReprAttr::ReprTransparent => {
is_transparent = true;
}
ReprAttr::ReprInt(..) => {
int_reprs += 1;
}
};
}
if !reprs.is_empty() {
let sorted_reprs = {
let mut to_sort = reprs.to_owned();
to_sort.sort_unstable_by_key(|(attr, span)| (*attr, span.lo_hi()));
to_sort
};
// To collect all duplicates, get subslices where all of the elements of the subslice
// are equal, then filter out all those whose length is not 1. We could return warnings
// for each of them, but that's annoyingly excessive. So we instead collect all spans in
// one big Vec.
let spans: Vec<Span> = sorted_reprs
.chunk_by(|(a, _), (b, _)| a == b)
.map(ToOwned::to_owned)
.filter(|slice| slice.len() != 1)
.flatten()
.map(|(_, span)| span)
.collect();
if !spans.is_empty() {
self.tcx.emit_node_span_lint(
REPEATED_REPRS,
hir_id,
spans,
diagnostics::RepeatedRepr,
);
}
}
// Just point at all repr hints if there are any incompatibilities.
// This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
let hint_spans = reprs.iter().map(|(_, span)| *span);
// Error on repr(transparent, <anything else>).
if is_transparent && reprs.len() > 1 {
let hint_spans = hint_spans.clone().collect();
self.dcx().emit_err(diagnostics::TransparentIncompatible {
hint_spans,
target: target.to_string(),
});
}
// Error on `#[repr(transparent)]` in combination with
// `#[rustc_pass_indirectly_in_non_rustic_abis]`
if is_transparent
&& let Some(&pass_indirectly_span) =
find_attr!(attrs, RustcPassIndirectlyInNonRusticAbis(span) => span)
{
self.dcx().emit_err(diagnostics::TransparentIncompatible {
hint_spans: vec![span, pass_indirectly_span],
target: target.to_string(),
});
}
if is_explicit_rust && (int_reprs > 0 || is_c || is_simd) {
let hint_spans = hint_spans.clone().collect();
self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans });
}
// Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
if (int_reprs > 1)
|| (is_simd && is_c)
|| (int_reprs == 1 && is_c && item.is_some_and(is_c_like_enum))
{
self.tcx.emit_node_span_lint(
CONFLICTING_REPR_HINTS,
hir_id,
hint_spans.collect::<Vec<Span>>(),
diagnostics::ReprConflictingLint,
);
}
}
/// A best effort attempt to create an error for a mismatching proc macro signature.
///
/// If this best effort goes wrong, it will just emit a worse error later (see #102923)
fn check_proc_macro(&self, hir_id: HirId, target: Target, kind: ProcMacroKind) {
if target != Target::Fn {
return;
}
let tcx = self.tcx;
let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else {
return;
};
let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else {
return;
};
let def_id = hir_id.expect_owner().def_id;
let param_env = ty::ParamEnv::empty();
let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let span = tcx.def_span(def_id);
let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id());
let sig = tcx.liberate_late_bound_regions(
def_id.to_def_id(),
tcx.fn_sig(def_id).instantiate(tcx, fresh_args).skip_norm_wip(),
);
let mut cause = ObligationCause::misc(span, def_id);
let sig = ocx.normalize(&cause, param_env, Unnormalized::new_wip(sig));
// proc macro is not WF.
let errors = ocx.try_evaluate_obligations();
if !errors.no_errors() {
return;
}
let expected_sig = tcx.mk_fn_sig_safe_rust_abi(
std::iter::repeat_n(
token_stream,
match kind {
ProcMacroKind::Attribute => 2,
ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1,
},
),
token_stream,
);
if let Err(terr) = ocx.eq(&cause, param_env, expected_sig, sig) {
let mut diag = tcx.dcx().create_err(diagnostics::ProcMacroBadSig { span, kind });
let hir_sig = tcx.hir_fn_sig_by_hir_id(hir_id);
if let Some(hir_sig) = hir_sig {
match terr {
TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
if let Some(ty) = hir_sig.decl.inputs.get(idx) {
diag.span(ty.span);
cause.span = ty.span;
} else if idx == hir_sig.decl.inputs.len() {
let span = hir_sig.decl.output.span();
diag.span(span);
cause.span = span;
}
}
TypeError::ArgCount => {
if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
diag.span(ty.span);
cause.span = ty.span;
}
}
TypeError::SafetyMismatch(_) => {
// FIXME: Would be nice if we had a span here..
}
TypeError::AbiMismatch(_) => {
// FIXME: Would be nice if we had a span here..
}
TypeError::VariadicMismatch(_) => {
// FIXME: Would be nice if we had a span here..
}
_ => {}
}
}
infcx.err_ctxt().note_type_err(
&mut diag,
&cause,
None,
Some(param_env.and(ValuePairs::PolySigs(ExpectedFound {
expected: ty::Binder::dummy(expected_sig),
found: ty::Binder::dummy(sig),
}))),
terr,
false,
None,
);
diag.emit();
self.abort.set(true);
}
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if let TraitErrors::HasErrors(errors) = errors {
infcx.err_ctxt().report_fulfillment_errors(errors);
self.abort.set(true);
}
}
fn check_rustc_force_inline(&self, hir_id: HirId, attrs: &[Attribute], target: Target) {
if let (Target::Closure, None) = (
target,
find_attr!(attrs, Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span),
) {
let is_coro = matches!(
self.tcx.hir_expect_expr(hir_id).kind,
hir::ExprKind::Closure(hir::Closure {
kind: hir::ClosureKind::Coroutine(..) | hir::ClosureKind::CoroutineClosure(..),
..
})
);
let parent_did = self.tcx.hir_get_parent_item(hir_id).to_def_id();
let parent_span = self.tcx.def_span(parent_did);
if let Some(attr_span) = find_attr!(
self.tcx, parent_did,
Inline(InlineAttr::Force { attr_span, .. }, _) => *attr_span
) && is_coro
{
self.dcx()
.emit_err(diagnostics::RustcForceInlineCoro { attr_span, span: parent_span });
}
}
}
fn check_mix_no_mangle_export(&self, hir_id: HirId, attrs: &[Attribute]) {
if let Some(export_name_span) =
find_attr!(attrs, ExportName { span: export_name_span, .. } => *export_name_span)
&& let Some(no_mangle_span) =
find_attr!(attrs, NoMangle(no_mangle_span) => *no_mangle_span)
{
let no_mangle_attr = if no_mangle_span.edition() >= Edition::Edition2024 {
"#[unsafe(no_mangle)]"
} else {
"#[no_mangle]"
};
let export_name_attr = if export_name_span.edition() >= Edition::Edition2024 {
"#[unsafe(export_name)]"
} else {
"#[export_name]"
};
self.tcx.emit_node_span_lint(
UNUSED_ATTRIBUTES,
hir_id,
no_mangle_span,
diagnostics::MixedExportNameAndNoMangle {
no_mangle_span,
export_name_span,
no_mangle_attr,
export_name_attr,
},
);
}
}
fn check_optimize_and_inline(&self, attrs: &[Attribute]) {
if let Some(optimize_span) =
find_attr!(attrs, Optimize(OptimizeAttr::DoNotOptimize, span) => *span)
&& let Some((inline_attr, inline_span)) =
find_attr!(attrs, Inline(inline_attr, span) => (inline_attr, *span))
&& inline_attr != &InlineAttr::Never
{
self.dcx()
.emit_err(diagnostics::BothOptimizeNoneAndInline { optimize_span, inline_span });
}
}
fn check_linkage(
&self,
span: Span,
hir_id: HirId,
target: Target,
item: Option<&'tcx Item<'tcx>>,
) {
// FIXME(eii) Once eii is no longer so experimental, suggest doing
// linkage stuff with externally implementable items instead
match target {
Target::ForeignStatic
if self.tcx.is_mutable_static(hir_id.expect_owner().def_id.into()) =>
{
self.tcx.dcx().emit_err(diagnostics::StaticMutLinkage { span });
}
Target::Fn
if let Item { kind: ItemKind::Fn { sig, .. }, .. } = item.unwrap()
&& matches!(sig.header.constness, Constness::Const { .. }) =>
{
self.tcx.dcx().emit_err(diagnostics::ConstFnLinkage { span });
}
_ => {}
}
}
fn check_rustc_assert_variance(
&self,
span: Span,
attr_span: Span,
hir_id: HirId,
target: Target,
kind: RustcAssertVarianceKind,
) {
// If the target is invalid the parser has already emitted an error
if !matches!(target, Target::TypeParam | Target::LifetimeParam | Target::ConstParam) {
return;
}
let Node::GenericParam(param) = self.tcx.hir_node(hir_id) else { return };
let owner = hir_id.owner.to_def_id();
let variances = self.tcx.variances_of(owner);
let generics = self.tcx.generics_of(owner);
let variance = generics
.own_params
.iter()
.zip(variances.iter())
.filter(|(other_param, _)| other_param.def_id == param.def_id.to_def_id())
.map(|(_, variance)| variance)
.nth(0)
.expect("generic parameter should have variance");
match (kind, variance) {
(RustcAssertVarianceKind::Covariant, Variance::Covariant) => {}
(RustcAssertVarianceKind::Invariant, Variance::Invariant) => {}
(RustcAssertVarianceKind::Contravariant, Variance::Contravariant) => {}
(RustcAssertVarianceKind::Bivariant, Variance::Bivariant) => {}
(asserted, actual) => {
let expected_variance = match asserted {
RustcAssertVarianceKind::Covariant => sym::covariant,
RustcAssertVarianceKind::Invariant => sym::invariant,
RustcAssertVarianceKind::Contravariant => sym::contravariant,
RustcAssertVarianceKind::Bivariant => sym::bivariant,
};
let actual_variance = match actual {
Variance::Covariant => sym::covariant,
Variance::Invariant => sym::invariant,
Variance::Contravariant => sym::contravariant,
Variance::Bivariant => sym::bivariant,
};
let item_ident = self.tcx.item_ident(owner);
let note = diagnostics::RustcAssertVarianceFailedNote { span: attr_span };
self.tcx.dcx().emit_err(diagnostics::RustcAssertVarianceFailed {
item_span: self.tcx.def_span(owner),
note,
param_ident: param.name.ident(),
param_span: span,
item_ident,
expected_variance,
actual_variance,
});
}
}
}
fn check_lint_check(&self, hir_id: HirId, lints: &[LintCheck]) {
for LintCheck { lint_name, lint_span, .. } in lints {
if lint_name.is(sym::dead_code_pub_in_binary) {
if !self.tcx.crate_types().contains(&CrateType::Executable) {
self.tcx.emit_node_span_lint(
UNUSED_ATTRIBUTES,
hir_id,
*lint_span,
diagnostics::Unused {
attr_span: *lint_span,
note: diagnostics::UnusedNote::NoEffectDeadCodePubInBinary,
},
);
}
}
if lint_name.is(sym::linker_messages) | lint_name.is(sym::linker_info) {
if hir_id == CRATE_HIR_ID
&& self
.tcx
.crate_types()
.iter()
.all(|kind| matches!(kind, CrateType::Rlib | CrateType::StaticLib))
{
self.tcx.emit_node_span_lint(
UNUSED_ATTRIBUTES,
hir_id,
*lint_span,
diagnostics::Unused {
attr_span: *lint_span,
note: diagnostics::UnusedNote::LinkerMessagesBinaryCrateOnly,
},
);
}
}
}
}
}
impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
// Historically we've run more checks on non-exported than exported macros,
// so this lets us continue to run them while maintaining backwards compatibility.
// In the long run, the checks should be harmonized.
if let ItemKind::Macro(_, macro_def, _) = item.kind {
let def_id = item.owner_id.to_def_id();
if macro_def.macro_rules && !find_attr!(self.tcx, def_id, MacroExport { .. }) {
check_non_exported_macro_for_invalid_attrs(self.tcx, item);
}
}
let target = Target::from(item);
self.check_attributes(item.hir_id(), item.span, target, Some(item));
intravisit::walk_item(self, item)
}
fn visit_where_predicate(&mut self, where_predicate: &'tcx hir::WherePredicate<'tcx>) {
self.check_attributes(
where_predicate.hir_id,
where_predicate.span,
Target::WherePredicate,
None,
);
intravisit::walk_where_predicate(self, where_predicate)
}
fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
let target = Target::from(generic_param);
self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
intravisit::walk_generic_param(self, generic_param)
}
fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
let target = Target::from(trait_item);
self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
intravisit::walk_trait_item(self, trait_item)
}
fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
intravisit::walk_field_def(self, struct_field);
}
fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
intravisit::walk_arm(self, arm);
}
fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
let target = Target::from(f_item);
self.check_attributes(f_item.hir_id(), f_item.span, target, None);
intravisit::walk_foreign_item(self, f_item)
}
fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
let target = target_from_impl_item(self.tcx, impl_item);
self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
intravisit::walk_impl_item(self, impl_item)
}
fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
// When checking statements ignore expressions, they will be checked later.
if let hir::StmtKind::Let(l) = stmt.kind {
self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
}
intravisit::walk_stmt(self, stmt)
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
let target = match expr.kind {
hir::ExprKind::Closure { .. } => Target::Closure,
_ => Target::Expression,
};
self.check_attributes(expr.hir_id, expr.span, target, None);
intravisit::walk_expr(self, expr)
}
fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
intravisit::walk_expr_field(self, field)
}
fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
self.check_attributes(variant.hir_id, variant.span, Target::Variant, None);
intravisit::walk_variant(self, variant)
}
fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
self.check_attributes(param.hir_id, param.span, Target::Param, None);
intravisit::walk_param(self, param);
}
fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
self.check_attributes(field.hir_id, field.span, Target::PatField, None);
intravisit::walk_pat_field(self, field);
}
}
fn is_c_like_enum(item: &Item<'_>) -> bool {
if let ItemKind::Enum(_, _, ref def) = item.kind {
for variant in def.variants {
match variant.data {
hir::VariantData::Unit(..) => { /* continue */ }
_ => return false,
}
}
true
} else {
false
}
}
fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
let attrs = tcx.hir_attrs(item.hir_id());
if let Some(attr_span) =
find_attr!(attrs, Inline(i, span) if !matches!(i, InlineAttr::Force{..}) => *span)
{
tcx.dcx().emit_err(diagnostics::NonExportedMacroInvalidAttrs { attr_span });
}
}
fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalModId) {
let check_attr_visitor = &mut CheckAttrVisitor { tcx, abort: Cell::new(false) };
tcx.hir_visit_item_likes_in_module(module_def_id, check_attr_visitor);
if module_def_id.to_local_def_id().is_top_level_module() {
check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
}
if check_attr_visitor.abort.get() {
tcx.dcx().abort_if_errors()
}
}
pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers { check_mod_attrs, ..*providers };
}
fn doc_fake_variadic_is_allowed_self_ty(self_ty: &hir::Ty<'_>) -> bool {
matches!(&self_ty.kind, hir::TyKind::Tup([_]))
|| if let hir::TyKind::FnPtr(fn_ptr_ty) = &self_ty.kind {
fn_ptr_ty.decl.inputs.len() == 1
} else {
false
}
|| (if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &self_ty.kind
&& let Some(&[hir::GenericArg::Type(ty)]) =
path.segments.last().map(|last| last.args().args)
{
doc_fake_variadic_is_allowed_self_ty(ty.as_unambig_ty())
} else {
false
})
}